text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import * as React from 'react'
import * as Kb from '../common-adapters'
import * as Styles from '../styles'
import * as Container from '../util/container'
import * as RPCTypes from '../constants/types/rpc-gen'
import * as FsTypes from '../constants/types/fs'
import * as FsConstants from '../constants/fs'
import * as FsCommon from '../fs/common'
import * as FsGen from '../actions/fs-gen'
import * as ConfigGen from '../actions/config-gen'
import * as RouteTreeGen from '../actions/route-tree-gen'
import * as Platform from '../constants/platform'
import * as SettingsConstants from '../constants/settings'
import {MobileSendToChat} from '../chat/send-to-chat'
import useRPC from '../util/use-rpc'
export const OriginalOrCompressedButton = ({incomingShareItems}: IncomingShareProps) => {
const originalTotalSize = incomingShareItems.reduce((bytes, item) => bytes + (item.originalSize ?? 0), 0)
const scaledTotalSize = incomingShareItems.reduce(
(bytes, item) => bytes + (item.scaledSize ?? item.originalSize ?? 0),
0
)
const originalOnly = originalTotalSize <= scaledTotalSize
const dispatch = Container.useDispatch()
const setUseOriginalInStore = React.useCallback(
(useOriginal: boolean) => dispatch(ConfigGen.createSetIncomingShareUseOriginal({useOriginal})),
[dispatch]
)
const setUseOriginalInService = React.useCallback((useOriginal: boolean) => {
RPCTypes.incomingShareSetPreferenceRpcPromise({
preference: useOriginal
? {compressPreference: RPCTypes.IncomingShareCompressPreference.original}
: {compressPreference: RPCTypes.IncomingShareCompressPreference.compressed},
})
}, [])
// If it's original only, set original in store.
React.useEffect(() => {
originalOnly && setUseOriginalInStore(true)
}, [originalOnly, setUseOriginalInStore])
// From service to store, but only if this is not original only.
const getRPC = useRPC(RPCTypes.incomingShareGetPreferenceRpcPromise)
const syncCompressPreferenceFromServiceToStore = React.useCallback(() => {
getRPC(
[undefined],
pref =>
setUseOriginalInStore(pref.compressPreference === RPCTypes.IncomingShareCompressPreference.original),
err => {
throw err
}
)
}, [getRPC, setUseOriginalInStore])
React.useEffect(() => {
!originalOnly && syncCompressPreferenceFromServiceToStore()
}, [originalOnly, syncCompressPreferenceFromServiceToStore])
const setUseOriginalFromUI = (useOriginal: boolean) => {
!originalOnly && setUseOriginalInStore(useOriginal)
setUseOriginalInService(useOriginal)
}
const useOriginalValue = Container.useSelector(state => state.config.incomingShareUseOriginal)
const {popup, showingPopup, setShowingPopup} = Kb.usePopup(() => (
<Kb.FloatingMenu
closeOnSelect={true}
visible={showingPopup}
onHidden={() => setShowingPopup(false)}
items={[
{
icon: useOriginalValue ? 'iconfont-check' : undefined,
onClick: () => setUseOriginalFromUI(true),
title: `Keep full size (${FsConstants.humanizeBytes(originalTotalSize, 1)})`,
},
{
icon: useOriginalValue ? undefined : 'iconfont-check',
onClick: () => setUseOriginalFromUI(false),
title: `Compress (${FsConstants.humanizeBytes(scaledTotalSize, 1)})`,
},
]}
/>
))
if (originalOnly) {
return null
}
if (useOriginalValue === undefined) {
return <Kb.ProgressIndicator />
}
return (
<>
<Kb.Icon type="iconfont-gear" padding="tiny" onClick={() => setShowingPopup(true)} />
{showingPopup && popup}
</>
)
}
const getContentDescription = (items: Array<RPCTypes.IncomingShareItem>) => {
if (items.length === 0) {
return undefined
}
if (items.length > 1) {
return items.some(({type}) => type !== items[0].type) ? (
<Kb.Text type="BodyTiny">{items.length} items</Kb.Text>
) : (
<Kb.Text type="BodyTiny">
{items.length} {incomingShareTypeToString(items[0].type, false, true)}
</Kb.Text>
)
}
if (items[0].content) {
// If it's a text snippet, just say "1 text snippet" and don't show text
// file name. We can get a file name here if the payload is from a text
// selection (rather than URL).
return <Kb.Text type="BodyTiny">1 {incomingShareTypeToString(items[0].type, false, false)}</Kb.Text>
}
// If it's a URL, originalPath is not populated.
const name = items[0].originalPath && FsTypes.getLocalPathName(items[0].originalPath)
return name ? (
<FsCommon.Filename type="BodyTiny" filename={name} />
) : (
<Kb.Text type="BodyTiny">1 {incomingShareTypeToString(items[0].type, false, false)}</Kb.Text>
)
}
const useHeader = (incomingShareItems: Array<RPCTypes.IncomingShareItem>) => {
const dispatch = Container.useDispatch()
const onCancel = () => dispatch(RouteTreeGen.createClearModals())
return {
leftButton: (
<Kb.Text type="BodyBigLink" onClick={onCancel}>
Cancel
</Kb.Text>
),
rightButton: <OriginalOrCompressedButton incomingShareItems={incomingShareItems} />,
title: (
<Kb.Box2 direction="vertical" fullWidth={true} centerChildren={true}>
{getContentDescription(incomingShareItems)}
<Kb.Text type="BodyBig">Share to...</Kb.Text>
</Kb.Box2>
),
}
}
const useFooter = (incomingShareItems: Array<RPCTypes.IncomingShareItem>) => {
const dispatch = Container.useDispatch()
const saveInFiles = () => {
dispatch(FsGen.createSetIncomingShareSource({source: incomingShareItems}))
dispatch(
RouteTreeGen.createNavigateAppend({
path: [
{
props: {
headerRightButton: <OriginalOrCompressedButton incomingShareItems={incomingShareItems} />,
index: 0,
},
selected: 'destinationPicker',
},
],
})
)
}
return isChatOnly(incomingShareItems)
? undefined
: {
content: (
<Kb.ClickableBox style={styles.footer} onClick={saveInFiles}>
<Kb.Icon type="iconfont-file" color={Styles.globalColors.blue} style={styles.footerIcon} />
<Kb.Text type="BodyBigLink">Save in Files</Kb.Text>
</Kb.ClickableBox>
),
}
}
type IncomingShareProps = {
incomingShareItems: Array<RPCTypes.IncomingShareItem>
}
const IncomingShare = (props: IncomingShareProps) => {
const useOriginalValue = Container.useSelector(state => state.config.incomingShareUseOriginal)
const {sendPaths, text} = props.incomingShareItems.reduce(
({sendPaths, text}, item) => {
if (item.content) {
return {sendPaths, text: item.content}
}
if (!useOriginalValue && item.scaledPath) {
return {sendPaths: [...sendPaths, item.scaledPath], text}
}
if (item.originalPath) {
return {sendPaths: [...sendPaths, item.originalPath], text}
}
return {sendPaths, text}
},
{sendPaths: [] as Array<string>, text: undefined as string | undefined}
)
return (
<Kb.Modal header={useHeader(props.incomingShareItems)} footer={useFooter(props.incomingShareItems)}>
<Kb.Box2 direction="vertical" fullWidth={true} fullHeight={true}>
<Kb.Box2 direction="vertical" fullWidth={true} style={Styles.globalStyles.flexOne}>
<MobileSendToChat isFromShareExtension={true} sendPaths={sendPaths} text={text} />
</Kb.Box2>
</Kb.Box2>
</Kb.Modal>
)
}
const IncomingShareError = () => {
const dispatch = Container.useDispatch()
const erroredSendFeedback = () => {
dispatch(RouteTreeGen.createClearModals())
dispatch(
RouteTreeGen.createNavigateAppend({
path: [
{
props: {feedback: `iOS share failure`},
selected: SettingsConstants.feedbackTab,
},
],
})
)
}
const onCancel = () => dispatch(RouteTreeGen.createClearModals())
return (
<Kb.Modal
header={{
leftButton: (
<Kb.Text type="BodyBigLink" onClick={onCancel}>
Cancel
</Kb.Text>
),
}}
>
<Kb.Box2 direction="vertical" fullWidth={true} fullHeight={true} gap="small" centerChildren={true}>
<Kb.Text type="BodySmall">Whoops! Something went wrong.</Kb.Text>
<Kb.Button label="Please let us know" onClick={erroredSendFeedback} />
</Kb.Box2>
</Kb.Modal>
)
}
const useIncomingShareItems = () => {
const [incomingShareItems, setIncomingShareItems] = React.useState<Array<RPCTypes.IncomingShareItem>>([])
const [incomingShareError, setIncomingShareError] = React.useState<any>(undefined)
// iOS
const rpc = useRPC(RPCTypes.incomingShareGetIncomingShareItemsRpcPromise)
const getIncomingShareItemsIOS = React.useCallback(() => {
if (!Platform.isIOS) {
return
}
rpc(
[undefined],
items => setIncomingShareItems(items || []),
err => setIncomingShareError(err)
)
}, [rpc, setIncomingShareError, setIncomingShareItems])
React.useEffect(getIncomingShareItemsIOS, [getIncomingShareItemsIOS])
// Android
const androidShare = Container.useSelector(state => state.config.androidShare)
const getIncomingShareItemsAndroid = React.useCallback(() => {
if (!Platform.isAndroid || !androidShare) {
return
}
const item =
androidShare.type === RPCTypes.IncomingShareType.file
? {
originalPath: androidShare.url,
type: RPCTypes.IncomingShareType.file,
}
: {
content: androidShare.text,
type: RPCTypes.IncomingShareType.text,
}
setIncomingShareItems([item])
}, [androidShare, setIncomingShareItems])
React.useEffect(getIncomingShareItemsAndroid, [getIncomingShareItemsAndroid])
return {
incomingShareError,
incomingShareItems,
}
}
const IncomingShareMain = () => {
const {incomingShareError, incomingShareItems} = useIncomingShareItems()
return incomingShareError ? (
<IncomingShareError />
) : incomingShareItems?.length ? (
<IncomingShare incomingShareItems={incomingShareItems} />
) : (
<Kb.Box2 direction="vertical" centerChildren={true} fullHeight={true}>
<Kb.ProgressIndicator type="Large" />
</Kb.Box2>
)
}
export default IncomingShareMain
const styles = Styles.styleSheetCreate(() => ({
footer: {
...Styles.globalStyles.flexBoxRow,
alignItems: 'center',
justifyContent: 'center',
width: '100%',
},
footerIcon: {
marginRight: Styles.globalMargins.tiny,
},
}))
const incomingShareTypeToString = (
type: RPCTypes.IncomingShareType,
capitalize: boolean,
plural: boolean
): string => {
switch (type) {
case RPCTypes.IncomingShareType.file:
return (capitalize ? 'File' : 'file') + (plural ? 's' : '')
case RPCTypes.IncomingShareType.text:
return (capitalize ? 'Text snippet' : 'text snippet') + (plural ? 's' : '')
case RPCTypes.IncomingShareType.image:
return (capitalize ? 'Image' : 'image') + (plural ? 's' : '')
case RPCTypes.IncomingShareType.video:
return (capitalize ? 'Video' : 'video') + (plural ? 's' : '')
}
}
const isChatOnly = (items?: Array<RPCTypes.IncomingShareItem>): boolean =>
items?.length === 1 &&
items[0].type === RPCTypes.IncomingShareType.text &&
!!items[0].content &&
!items[0].originalPath | the_stack |
import 'mocha'
import * as C from '../constants'
import ListenerTestUtils from './listener-test-utils'
import 'mocha'
let tu
describe('listener-registry', () => {
/*
const ListenerRegistry = require('../../src/listen/listener-registry')
const testHelper = require('../test-helper/test-helper')
import SocketMock from '../test-mocks/socket-mock'
const options = testHelper.getDeepstreamOptions()
const msg = testHelper.msg
let listenerRegistry
const recordSubscriptionRegistryMock = {
getNames () {
return ['car/Mercedes', 'car/Abarth']
}
}
describe.skip('listener-registry errors', () => {
beforeEach(() => {
listenerRegistry = new ListenerRegistry('R', options, recordSubscriptionRegistryMock)
expect(typeof listenerRegistry.handle).to.equal('function')
})
it('adds a listener without message data', () => {
const socketWrapper = SocketWrapperFactory.create(new SocketMock(), options)
listenerRegistry.handle(socketWrapper, {
topic: 'R',
action: 'L',
data: []
})
expect(options.logger.lastLogArguments).to.deep.equal([3, 'INVALID_MESSAGE_DATA', undefined])
expect(socketWrapper.socket.lastSendMessage).to.equal(msg('R|E|INVALID_MESSAGE_DATA|undefined+'))
})
it('adds a listener with invalid message data message data', () => {
const socketWrapper = new SocketWrapper(new SocketMock(), options)
listenerRegistry.handle(socketWrapper, {
topic: 'R',
action: 'L',
data: [44]
})
expect(options.logger.lastLogArguments).to.deep.equal([3, 'INVALID_MESSAGE_DATA', 44])
expect(socketWrapper.socket.lastSendMessage).to.equal(msg('R|E|INVALID_MESSAGE_DATA|44+'))
})
it('adds a listener with an invalid regexp', () => {
const socketWrapper = new SocketWrapper(new SocketMock(), options)
listenerRegistry.handle(socketWrapper, {
topic: 'R',
action: 'L',
data: ['us(']
})
expect(options.logger.lastLogArguments).to.deep.equal([3, 'INVALID_MESSAGE_DATA', 'SyntaxError: Invalid regular expression: /us(/: Unterminated group'])
expect(socketWrapper.socket.lastSendMessage).to.equal(msg('R|E|INVALID_MESSAGE_DATA|SyntaxError: Invalid regular expression: /us(/: Unterminated group+'))
})
})
*/
describe('listener-registry-local-load-balancing', () => {
beforeEach(() => {
tu = new ListenerTestUtils()
})
afterEach(() => {
tu.complete()
})
describe('with a single provider', () => {
it('accepts a subscription', () => {
// 1. provider does listen a/.*
tu.providerListensTo(1, 'a/.*')
// 3. provider will get a SP
tu.providerWillGetSubscriptionFound(1, 'a/.*', 'a/1')
// 2. clients 1 request a/1
tu.clientSubscribesTo(1, 'a/1', true)
// 4. provider responds with ACCEPT
tu.publishUpdateWillBeSentToSubscribers('a/1', true)
tu.providerAccepts(1, 'a/.*', 'a/1')
// // 6. clients 2 request a/1
tu.clientWillRecievePublishedUpdate(2, 'a/1', true)
tu.clientSubscribesTo(2, 'a/1')
// // 6. clients 3 request a/1
tu.clientWillRecievePublishedUpdate(3, 'a/1', true)
tu.clientSubscribesTo(3, 'a/1')
// // 9. client 1 discards a/1
tu.clientUnsubscribesTo(3, 'a/1')
// // 9. client 2 discards a/1
tu.clientUnsubscribesTo(2, 'a/1')
// // 10. clients discards a/1
tu.providerWillGetSubscriptionRemoved(1, 'a/.*', 'a/1')
tu.publishUpdateWillBeSentToSubscribers('a/1', false)
tu.clientUnsubscribesTo(1, 'a/1', true)
// // 13. a/1 should have no active provider
tu.subscriptionHasActiveProvider('a/1', false)
// // 14. recieving unknown accept/reject throws an error
tu.acceptMessageThrowsError(1, 'a/.*', 'a/1')
tu.rejectMessageThrowsError(1, 'a/.*', 'a/1')
})
it('rejects a subscription', () => {
// 1. provider does listen a/.*
tu.providerListensTo(1, 'a/.*')
// 2. clients request a/1
tu.providerWillGetSubscriptionFound(1, 'a/.*', 'a/1')
tu.clientSubscribesTo(1, 'a/1', true)
// 4. provider responds with ACCEPT
tu.providerRejects(1, 'a/.*', 'a/1')
// 5. clients discards a/1
tu.clientUnsubscribesTo(1, 'a/1', true)
// mocks do expecations to ensure nothing else was called
})
it('rejects a subscription with a pattern for which subscriptions already exists', () => {
// 0. subscription already made for b/1
tu.subscriptionAlreadyMadeFor('b/1')
// 1. provider does listen a/.*
tu.providerWillGetSubscriptionFound(1, 'b/.*', 'b/1')
tu.providerListensTo(1, 'b/.*')
// 3. provider responds with REJECT
tu.providerRejects(1, 'b/.*', 'b/1')
// 4. clients discards b/1
tu.clientUnsubscribesTo(1, 'b/1', true)
// mocks do expecations to ensure nothing else was called
})
it('accepts a subscription with a pattern for which subscriptions already exists', () => {
// 0. subscription already made for b/1
tu.subscriptionAlreadyMadeFor('b/1')
// 1. provider does listen a/.*
tu.providerWillGetSubscriptionFound(1, 'b/.*', 'b/1')
tu.providerListensTo(1, 'b/.*')
// 3. provider responds with ACCEPT
tu.publishUpdateWillBeSentToSubscribers('b/1', true)
tu.providerAccepts(1, 'b/.*', 'b/1')
// 5. clients discards b/1
tu.providerWillGetSubscriptionRemoved(1, 'b/.*', 'b/1')
tu.publishUpdateWillBeSentToSubscribers('b/1', false)
tu.clientUnsubscribesTo(1, 'b/1', true)
// 7. send publishing=false to the clients
})
it('accepts a subscription for 2 clients', () => {
// 1. provider does listen a/.*
tu.providerListensTo(1, 'a/.*')
// 2. client 1 requests a/1
tu.providerWillGetSubscriptionFound(1, 'a/.*', 'a/1')
tu.clientSubscribesTo(1, 'a/1', true)
// 4. provider responds with ACCEPT
tu.publishUpdateWillBeSentToSubscribers('a/1', true)
tu.providerAccepts(1, 'a/.*', 'a/1')
// 5. send publishing=true to the clients
tu.clientWillRecievePublishedUpdate(2, 'a/1', true)
tu.clientSubscribesTo(2, 'a/1')
// 9. client 1 discards a/1
tu.clientUnsubscribesTo(1, 'a/1')
// 11. client 2 discards a/1
tu.providerWillGetSubscriptionRemoved(1, 'a/.*', 'a/1')
tu.publishUpdateWillBeSentToSubscribers('a/1', false)
tu.clientUnsubscribesTo(2, 'a/1', true)
// 13. a/1 should have no active provider
tu.subscriptionHasActiveProvider('a/1', false)
})
})
describe('with multiple providers', () => {
it('first rejects, seconds accepts, third does nothing', () => {
// 1. provider 1 does listen a/.*
tu.providerListensTo(1, 'a/.*')
// 2. provider 2 does listen a/[0-9]
tu.providerListensTo(2, 'a/[0-9]')
// 3. client 1 requests a/1
tu.providerWillGetSubscriptionFound(1, 'a/.*', 'a/1')
tu.clientSubscribesTo(1, 'a/1', true)
// 5. provider 1 responds with REJECTS
tu.providerWillGetSubscriptionFound(2, 'a/[0-9]', 'a/1')
tu.providerRejects(1, 'a/.*', 'a/1')
// 7. provider 2 responds with ACCEPTS
tu.publishUpdateWillBeSentToSubscribers('a/1', true)
tu.providerAccepts(2, 'a/[0-9]', 'a/1')
// 8. send publishing=true to the clients
// 9. provider 3 does listen a/[0-9]
tu.providerListensTo(3, 'a/[0-9]')
// 11. client 1 unsubscribed to a/1
tu.providerWillGetSubscriptionRemoved(2, 'a/[0-9]', 'a/1')
tu.publishUpdateWillBeSentToSubscribers('a/1', false)
tu.clientUnsubscribesTo(1, 'a/1', true)
})
it('first accepts, seconds does nothing', () => {
// 1. provider 1 does listen a/.*
tu.providerListensTo(1, 'a/.*')
// 2. provider 2 does listen a/[0-9]
tu.providerListensTo(2, 'a/[0-9]')
// 3. client 1 requests a/1
tu.providerWillGetSubscriptionFound(1, 'a/.*', 'a/1')
tu.clientSubscribesTo(1, 'a/1', true)
// 6. provider 1 accepts
tu.publishUpdateWillBeSentToSubscribers('a/1', true)
tu.providerAccepts(1, 'a/.*', 'a/1')
// 12. send publishing=true to the clients
// 6. client 1 unsubscribed to a/1
tu.providerWillGetSubscriptionRemoved(1, 'a/.*', 'a/1')
tu.publishUpdateWillBeSentToSubscribers('a/1', false)
tu.clientUnsubscribesTo(1, 'a/1', true)
})
it('first rejects, seconds - which start listening after first gets SP - accepts', () => {
// 1. provider 1 does listen a/.*
tu.providerListensTo(1, 'a/.*')
// 3. client 1 requests a/1
tu.providerWillGetSubscriptionFound(1, 'a/.*', 'a/1')
tu.clientSubscribesTo(1, 'a/1', true)
// 2. provider 2 does listen a/[0-9]
tu.providerListensTo(2, 'a/[0-9]')
// 6. provider 1 rejects
tu.providerWillGetSubscriptionFound(2, 'a/[0-9]', 'a/1')
tu.providerRejects(1, 'a/.*', 'a/1')
// 6. provider 1 accepts
tu.publishUpdateWillBeSentToSubscribers('a/1', true)
tu.providerAccepts(2, 'a/[0-9]', 'a/1')
// 12. send publishing=false to the clients
})
it('no messages after unlisten', () => {
// 1. provider 1 does listen a/.*
tu.providerListensTo(1, 'a/.*')
// 2. provider 2 does listen a/[0-9]
tu.providerListensTo(2, 'a/[0-9]')
// 3. client 1 requests a/1
tu.providerWillGetSubscriptionFound(1, 'a/.*', 'a/1')
tu.clientSubscribesTo(1, 'a/1', true)
// 2. provider 2 does unlisten a/[0-9]
tu.providerUnlistensTo(2, 'a/[0-9]')
// 6. provider 1 responds with REJECTS
tu.providerRejects(1, 'a/.*', 'a/1')
// mock does remaining expecations
})
it.skip('provider 1 accepts a subscription and disconnects then provider 2 gets a SP', () => {
// 1. provider 1 does listen a/.*
tu.providerListensTo(1, 'a/.*')
// 2. provider 2 does listen a/[0-9]
tu.providerListensTo(2, 'a/[0-9]')
// 3. client 1 requests a/1
tu.providerWillGetSubscriptionFound(1, 'a/.*', 'a/1')
tu.clientSubscribesTo(1, 'a/1', true)
// 5. provider 1 responds with ACCEPT
tu.providerAccepts(1, 'a/.*', 'a/1')
// 13. subscription has active provider
tu.subscriptionHasActiveProvider('a/1', true)
// 7. client 1 requests a/1
tu.providerWillGetSubscriptionFound(2, 'a/[0-9]', 'a/1')
tu.publishUpdateWillBeSentToSubscribers('a/1', false)
tu.providerLosesItsConnection(1)
// 8. send publishing=true to the clients
// 9. subscription doesnt have active provider
tu.subscriptionHasActiveProvider('a/1', false)
tu.publishUpdateWillBeSentToSubscribers('a/1', true)
tu.providerAccepts(2, 'a/[0-9]', 'a/1')
// 12. send publishing=true to the clients
// 13. subscription has active provider
tu.subscriptionHasActiveProvider('a/1', true)
})
})
})
describe('listener-registry-local-load-balancing does not send publishing updates for events', () => {
beforeEach(() => {
tu = new ListenerTestUtils(C.TOPIC.EVENT)
})
afterEach(() => {
tu.complete()
})
it('client with provider already registered', () => {
// 1. provider does listen a/.*
tu.providerListensTo(1, 'a/.*')
// 2. client 1 requests a/1
tu.providerWillGetSubscriptionFound(1, 'a/.*', 'a/1')
tu.clientSubscribesTo(1, 'a/1', true)
// 4. provider responds with ACCEPT
tu.providerAccepts(1, 'a/.*', 'a/1')
// 6. client 2 requests a/1
tu.clientSubscribesTo(2, 'a/1')
// 9. client 1 discards a/1
tu.clientUnsubscribesTo(1, 'a/1')
// 11. client 2 discards a/1
tu.providerWillGetSubscriptionRemoved(1, 'a/.*', 'a/1')
tu.clientUnsubscribesTo(2, 'a/1', true)
// 12. provider should get a SR
// 13. a/1 should have no active provider
tu.subscriptionHasActiveProvider('a/1', false)
})
})
describe('listener-registry-local-timeouts', () => {
beforeEach(() => {
tu = new ListenerTestUtils()
})
afterEach(() => {
tu.complete()
})
beforeEach(() => {
// 1. provider 1 does listen a/.*
tu.providerListensTo(1, 'a/.*')
// 2. provider 2 does listen a/[0-9]
tu.providerListensTo(2, 'a/[0-9]')
// 3. client 1 requests a/1
tu.providerWillGetSubscriptionFound(1, 'a/.*', 'a/1')
tu.clientSubscribesTo(1, 'a/1', true)
})
it('provider 1 times out, provider 2 accepts', (done) => {
tu.providerWillGetSubscriptionFound(2, 'a/[0-9]', 'a/1')
tu.publishUpdateWillBeSentToSubscribers('a/1', true)
tu.providerWillGetListenTimeout(1, 'a/1')
setTimeout(() => {
tu.providerAccepts(1, 'a/[0-9]', 'a/1')
tu.subscriptionHasActiveProvider('a/1', true)
done()
}, 40)
})
it.skip('provider 1 times out and gets a RESPONSE_TIMEOUT, but will be ignored because provider 2 accepts as well', (done) => {
tu.providerWillGetSubscriptionRemoved(1, 'a/.*', 'a/1')
tu.providerWillGetSubscriptionFound(2, 'a/[0-9]', 'a/1')
tu.providerWillGetListenTimeout(1, 'a/1')
setTimeout(() => {
tu.providerAcceptsButIsntAcknowledged(1, 'a/.*', 'a/1')
tu.publishUpdateWillBeSentToSubscribers('a/1', true)
tu.providerAccepts(2, 'a/[0-9]', 'a/1')
tu.subscriptionHasActiveProvider('a/1', true)
done()
}, 40)
})
it.skip('provider 1 times out, but then it accept and will be used because provider 2 rejects', (done) => {
tu.providerWillGetSubscriptionFound(2, 'a/[0-9]', 'a/1')
tu.providerWillGetListenTimeout(1, 'a/1')
setTimeout(() => {
tu.providerAcceptsButIsntAcknowledged(1, 'a/.*', 'a/1')
tu.subscriptionHasActiveProvider('a/1', false)
tu.publishUpdateWillBeSentToSubscribers('a/1', true)
tu.providerRejectsAndPreviousTimeoutProviderThatAcceptedIsUsed(2, 'a/[0-9]', 'a/1')
tu.subscriptionHasActiveProvider('a/1', true)
done()
}, 40)
})
it.skip('provider 1 and 2 times out and 3 rejects, 1 rejects and 2 accepts later and 2 wins', (done) => {
tu.providerWillGetListenTimeout(1, 'a/1')
tu.providerWillGetListenTimeout(2, 'a/1')
tu.providerWillGetSubscriptionFound(2, 'a/[0-9]', 'a/1')
tu.providerListensTo(3, 'a/[1]')
setTimeout(() => {
tu.providerWillGetSubscriptionFound(3, 'a/[1]', 'a/1')
// first provider timeout
setTimeout(() => {
tu.providerRejects(1, 'a/.*', 'a/1')
tu.providerAcceptsButIsntAcknowledged(2, 'a/[0-9]', 'a/1')
tu.publishUpdateWillBeSentToSubscribers('a/1', true)
tu.providerRejectsAndPreviousTimeoutProviderThatAcceptedIsUsed(3, 'a/[1]', 'a/1')
done()
}, 40)
}, 40)
})
it.skip('1 rejects and 2 accepts later and dies and 3 wins', (done) => {
tu.providerWillGetSubscriptionFound(2, 'a/[0-9]', 'a/1')
tu.providerListensTo(3, 'a/[1]')
setTimeout(() => {
tu.providerWillGetSubscriptionFound(3, 'a/[1]', 'a/1')
// first provider timeout
setTimeout(() => {
tu.providerRejects(1, 'a/.*', 'a/1')
tu.providerAcceptsButIsntAcknowledged(2, 'a/[0-9]', 'a/1')
tu.providerLosesItsConnection(2, 'a/[0-9]')
tu.providerRejects(3, 'a/[1]', 'a/1')
done()
}, 40)
}, 40)
})
it.skip('provider 1 and 2 times out and 3 rejects, 1 and 2 accepts later and 1 wins', (done) => {
tu.providerWillGetListenTimeout(1, 'a/1')
tu.providerWillGetListenTimeout(2, 'a/1')
tu.providerWillGetSubscriptionFound(2, 'a/[0-9]', 'a/1')
tu.providerListensTo(3, 'a/[1]')
setTimeout(() => {
tu.providerWillGetSubscriptionFound(3, 'a/[1]', 'a/1')
// first provider
setTimeout(() => {
// 10. provider 1 responds with ACCEPT
tu.providerAcceptsButIsntAcknowledged(1, 'a/.*', 'a/1')
// 11. provider 2 responds with ACCEPT
tu.providerAcceptsAndIsSentSubscriptionRemoved(2, 'a/[0-9]', 'a/1')
// 12. provider 3 responds with reject
tu.publishUpdateWillBeSentToSubscribers('a/1', true)
tu.providerRejectsAndPreviousTimeoutProviderThatAcceptedIsUsed(3, 'a/[1]', 'a/1')
done()
}, 40)
}, 40)
})
})
}) | the_stack |
import Serverless from "serverless";
import Service from "serverless/classes/Service";
import { CliCommand, CliCommandFactory } from "../config/cliCommandFactory";
import { BuildMode, FunctionAppOS, isNodeRuntime, isPythonRuntime, Runtime, supportedRuntimes, supportedRuntimeSet, isCompiledRuntime } from "../config/runtime";
import { DeploymentConfig, ServerlessAzureConfig, ServerlessAzureFunctionConfig } from "../models/serverless";
import { constants } from "../shared/constants";
import { Utils } from "../shared/utils";
import { AzureNamingService, AzureNamingServiceOptions } from "./namingService";
/**
* Handles all Service Configuration
*/
export class ConfigService {
/** Configuration for service */
private config: ServerlessAzureConfig;
/** CLI Command Factory */
private cliCommandFactory: CliCommandFactory;
public constructor(private serverless: Serverless, private options: Serverless.Options) {
this.config = this.initializeConfig(serverless.service);
this.cliCommandFactory = new CliCommandFactory();
this.registerCliCommands();
}
/**
* Get Azure Provider Configuration
*/
public getConfig(): ServerlessAzureConfig {
return this.config;
}
/**
* Name of Azure Region for deployment
*/
public getRegion(): string {
return this.config.provider.region;
}
/**
* Name of current deployment stage
*/
public getStage(): string {
return this.config.provider.stage;
}
/**
* Prefix for service
*/
public getPrefix(): string {
return this.config.provider.prefix;
}
/**
* Name of current resource group
*/
public getResourceGroupName(): string {
return this.config.provider.resourceGroup;
}
/**
* Azure Subscription ID
*/
public getSubscriptionId(): string {
return this.getOption(constants.variableKeys.subscriptionId)
|| process.env.AZURE_SUBSCRIPTION_ID
|| this.config.provider.subscriptionId
|| this.serverless.variables[constants.variableKeys.subscriptionId]
}
/**
* Name of current deployment
*/
public getDeploymentName(): string {
return AzureNamingService.getDeploymentName(
this.config,
(this.config.provider.deployment.rollback) ? `t${this.getTimestamp()}` : null
)
}
public getDeploymentConfig(): DeploymentConfig {
return this.config.provider.deployment;
}
/**
* Get rollback-configured artifact name. Contains `-t{timestamp}`
* Takes name of deployment and replaces `rg-deployment` or `deployment` with `artifact`
*/
public getArtifactName(deploymentName?: string): string {
deploymentName = deploymentName || this.getDeploymentName();
const { deployment, artifact } = constants.naming.suffix;
return `${deploymentName
.replace(`rg-${deployment}`, artifact)
.replace(deployment, artifact)}.zip`
}
/**
* Function configuration from serverless.yml
*/
public getFunctionConfig(): { [functionName: string]: ServerlessAzureFunctionConfig } {
return this.config.functions;
}
/**
* Name of file containing serverless config
*/
public getConfigFile(): string {
return this.getOption("config", "serverless.yml");
}
/**
* Name of Function App Service
*/
public getServiceName(): string {
return this.config.service;
}
/**
* Operating system for function app
*/
public getOs(): FunctionAppOS {
return this.config.provider.os;
}
/**
* Function app configured to run on Python
*/
public isPythonTarget(): boolean {
return isPythonRuntime(this.config.provider.runtime);
}
/**
* Function app configured to run on Node
*/
public isNodeTarget(): boolean {
return isNodeRuntime(this.config.provider.runtime);
}
/**
* Function app configured to run on Linux
*/
public isLinuxTarget(): boolean {
return this.getOs() === FunctionAppOS.LINUX
}
public getCommand(key: string): CliCommand {
return this.cliCommandFactory.getCommand(key);
}
public getCompilerCommand(runtime: Runtime, mode: BuildMode): CliCommand {
return this.cliCommandFactory.getCommand(`${runtime}-${mode}`);
}
public shouldCompileBeforePublish(): boolean {
return isCompiledRuntime(this.config.provider.runtime) && this.config.provider.os === FunctionAppOS.WINDOWS;
}
/**
* Set any default values required for service
* @param config Current Serverless configuration
*/
private setDefaultValues(config: ServerlessAzureConfig) {
const { awsRegion, region, stage, prefix, os } = constants.defaults;
const providerRegion = config.provider.region;
if (!providerRegion || providerRegion === awsRegion) {
config.provider.region = this.serverless.service.provider["location"] || region;
}
if (!config.provider.stage) {
config.provider.stage = stage;
}
if (!config.provider.prefix) {
config.provider.prefix = prefix;
}
if (!config.provider.os) {
config.provider.os = os;
}
if (!config.provider.type) {
config.provider.type = "consumption"
}
}
/**
* Overwrite values for resourceGroup, prefix, region and stage
* in config if passed through CLI
*/
private initializeConfig(service: Service): ServerlessAzureConfig {
const config: ServerlessAzureConfig = service as any;
const providerConfig = Utils.get(this.serverless.variables, constants.variableKeys.providerConfig);
if (providerConfig) {
config.provider = providerConfig;
return config;
}
this.serverless.cli.log("Initializing provider configuration...");
this.setDefaultValues(config);
const {
prefix,
region,
stage,
subscriptionId,
tenantId,
appId,
deployment,
runtime,
os
} = config.provider;
const options: AzureNamingServiceOptions = {
config: config,
suffix: `${config.service}-rg`,
includeHash: false,
}
config.provider = {
...config.provider,
prefix: this.getOption("prefix") || prefix,
stage: this.getOption("stage") || stage,
region: this.getOption("region") || region,
subscriptionId: this.getOption(constants.variableKeys.subscriptionId)
|| process.env.AZURE_SUBSCRIPTION_ID
|| subscriptionId
|| this.serverless.variables[constants.variableKeys.subscriptionId],
tenantId: this.getOption(constants.variableKeys.tenantId)
|| process.env.AZURE_TENANT_ID
|| tenantId,
appId: this.getOption(constants.variableKeys.appId)
|| process.env.AZURE_CLIENT_ID
|| appId,
}
config.provider.resourceGroup = (
this.getOption("resourceGroup", config.provider.resourceGroup)
) || AzureNamingService.getResourceName(options);
if (!runtime) {
throw new Error(`Runtime undefined. Runtimes supported: ${supportedRuntimes.join(",")}`);
}
if (!supportedRuntimeSet.has(runtime)) {
throw new Error(`Runtime ${runtime} is not supported. Runtimes supported: ${supportedRuntimes.join(",")}`)
}
if (isPythonRuntime(runtime) && os !== FunctionAppOS.LINUX) {
this.serverless.cli.log("Python functions can ONLY run on Linux Function Apps.");
config.provider.os = FunctionAppOS.LINUX;
}
config.provider.deployment = {
...constants.deploymentConfig,
...deployment,
}
this.serverless.variables[constants.variableKeys.providerConfig] = config.provider;
return config;
}
/**
* Get timestamp from `packageTimestamp` serverless variable
* If not set, create timestamp, set variable and return timestamp
*/
private getTimestamp(): number {
const key = constants.variableKeys.packageTimestamp
let timestamp = +this.getVariable(key);
if (!timestamp) {
timestamp = Date.now();
this.serverless.variables[key] = timestamp;
}
return timestamp;
}
/**
* Get value of option from Serverless CLI
* @param key Key of option
* @param defaultValue Default value if key not found in options object
*/
protected getOption(key: string, defaultValue?: any) {
return Utils.get(this.options, key, defaultValue);
}
/**
* Get variable value from Serverless variables
* @param key Key for variable
* @param defaultValue Default value if key not found in variable object
*/
protected getVariable(key: string, defaultValue?: any) {
return Utils.get(this.serverless.variables, key, defaultValue);
}
private registerCliCommands() {
// for (const key of Object.keys(cliCommands)) {
// this.cliCommandFactory.registerCommand(key, this.cliCommandFactory.registerCommand(key]);
// }
this.cliCommandFactory.registerCommand(constants.cliCommandKeys.start, {
command: "func",
args: [ "host", "start" ],
});
this.cliCommandFactory.registerCommand(`${Runtime.DOTNET22}-${BuildMode.RELEASE}`, {
command: "dotnet",
args: [
"build",
"--configuration",
"release",
"--framework",
"netcoreapp2.2",
"--output",
constants.tmpBuildDir
],
});
this.cliCommandFactory.registerCommand(`${Runtime.DOTNET22}-${BuildMode.DEBUG}`, {
command: "dotnet",
args: [
"build",
"--configuration",
"debug",
"--framework",
"netcoreapp2.2",
"--output",
constants.tmpBuildDir
],
});
this.cliCommandFactory.registerCommand(`${Runtime.DOTNET31}-${BuildMode.RELEASE}`, {
command: "dotnet",
args: [
"build",
"--configuration",
"release",
"--framework",
"netcoreapp3.1",
"--output",
constants.tmpBuildDir
],
});
this.cliCommandFactory.registerCommand(`${Runtime.DOTNET31}-${BuildMode.DEBUG}`, {
command: "dotnet",
args: [
"build",
"--configuration",
"debug",
"--framework",
"netcoreapp3.1",
"--output",
constants.tmpBuildDir
],
});
}
} | the_stack |
import { AzureAuthType } from 'ads-adal-library';
import * as vscode from 'vscode';
import { AccountStore } from '../azure/accountStore';
import * as Constants from '../constants/constants';
import * as vscodeMssql from 'vscode-mssql';
// interfaces
export enum ContentType {
Root = 0,
Messages = 1,
ResultsetsMeta = 2,
Columns = 3,
Rows = 4,
SaveResults = 5,
Copy = 6,
EditorSelection = 7,
OpenLink = 8,
ShowError = 9,
ShowWarning = 10,
Config = 11,
LocalizedTexts = 12
}
export interface ISlickRange {
fromCell: number;
fromRow: number;
toCell: number;
toRow: number;
}
export enum AuthenticationTypes {
Integrated = 1,
SqlLogin = 2,
AzureMFA = 3
}
export const contentTypes = [
Constants.outputContentTypeRoot,
Constants.outputContentTypeMessages,
Constants.outputContentTypeResultsetMeta,
Constants.outputContentTypeColumns,
Constants.outputContentTypeRows,
Constants.outputContentTypeSaveResults,
Constants.outputContentTypeCopy,
Constants.outputContentTypeEditorSelection,
Constants.outputContentTypeOpenLink,
Constants.outputContentTypeShowError,
Constants.outputContentTypeShowWarning,
Constants.outputContentTypeConfig,
Constants.localizedTexts
];
// A Connection Profile contains all the properties of connection credentials, with additional
// optional name and details on whether password should be saved
export interface IConnectionProfile extends vscodeMssql.IConnectionInfo {
profileName: string;
savePassword: boolean;
emptyPasswordInput: boolean;
azureAuthType: AzureAuthType;
accountStore: AccountStore;
isValidProfile(): boolean;
isAzureActiveDirectory(): boolean;
}
export enum CredentialsQuickPickItemType {
Profile,
Mru,
NewConnection
}
export interface IConnectionCredentialsQuickPickItem extends vscode.QuickPickItem {
connectionCreds: vscodeMssql.IConnectionInfo;
quickPickItemType: CredentialsQuickPickItemType;
}
// Obtained from an active connection to show in the status bar
export interface IConnectionProperties {
serverVersion: string;
currentUser: string;
currentDatabase: string;
}
export interface IDbColumn {
allowDBNull?: boolean;
baseCatalogName: string;
baseColumnName: string;
baseSchemaName: string;
baseServerName: string;
baseTableName: string;
columnName: string;
columnOrdinal?: number;
columnSize?: number;
isAliased?: boolean;
isAutoIncrement?: boolean;
isExpression?: boolean;
isHidden?: boolean;
isIdentity?: boolean;
isKey?: boolean;
isBytes?: boolean;
isChars?: boolean;
isSqlVariant?: boolean;
isUdt?: boolean;
dataType: string;
isXml?: boolean;
isJson?: boolean;
isLong?: boolean;
isReadOnly?: boolean;
isUnique?: boolean;
numericPrecision?: number;
numericScale?: number;
udtAssemblyQualifiedName: string;
dataTypeName: string;
}
export interface IGridResultSet {
columns: IDbColumn[];
rowsUri: string;
numberOfRows: number;
}
export interface ISelectionData {
startLine: number;
startColumn: number;
endLine: number;
endColumn: number;
}
export interface IResultMessage {
batchId?: number;
isError: boolean;
time: string;
message: string;
}
export interface IGridBatchMetaData {
resultSets: IGridResultSet[];
hasError: boolean;
selection: ISelectionData;
startTime: string;
endTime: string;
totalTime: string;
}
export interface IResultsConfig {
shortcuts: { [key: string]: string };
messagesDefaultOpen: boolean;
resultsFontSize: number;
}
export interface ILogger {
logDebug(message: string): void;
increaseIndent(): void;
decreaseIndent(): void;
append(message?: string): void;
appendLine(message?: string): void;
}
export interface IAzureSignInQuickPickItem extends vscode.QuickPickItem {
command: string;
}
export class DbCellValue {
displayValue: string;
isNull: boolean;
}
export class ResultSetSubset {
rowCount: number;
rows: DbCellValue[][];
}
export interface IDbColumn {
allowDBNull?: boolean;
baseCatalogName: string;
baseColumnName: string;
baseSchemaName: string;
baseServerName: string;
baseTableName: string;
columnName: string;
columnOrdinal?: number;
columnSize?: number;
isAliased?: boolean;
isAutoIncrement?: boolean;
isExpression?: boolean;
isHidden?: boolean;
isIdentity?: boolean;
isKey?: boolean;
isBytes?: boolean;
isChars?: boolean;
isSqlVariant?: boolean;
isUdt?: boolean;
dataType: string;
isXml?: boolean;
isJson?: boolean;
isLong?: boolean;
isReadOnly?: boolean;
isUnique?: boolean;
numericPrecision?: number;
numericScale?: number;
udtAssemblyQualifiedName: string;
dataTypeName: string;
}
export class ResultSetSummary {
id: number;
rowCount: number;
columnInfo: IDbColumn[];
}
export class BatchSummary {
id: number;
selection: ISelectionData;
resultSetSummaries: ResultSetSummary[];
executionElapsed: string;
executionEnd: string;
executionStart: string;
}
export interface IGridResultSet {
columns: IDbColumn[];
rowsUri: string;
numberOfRows: number;
}
export interface ISelectionData {
startLine: number;
startColumn: number;
endLine: number;
endColumn: number;
}
export interface IMessageLink {
uri: string;
text: string;
}
export interface IMessage {
batchId?: number;
time: string;
message: string;
isError: boolean;
link?: IMessageLink;
}
export interface IGridIcon {
showCondition: () => boolean;
icon: () => string;
hoverText: () => string;
functionality: (batchId: number, resultId: number, index: number) => void;
}
export interface IResultsConfig {
shortcuts: { [key: string]: string };
messagesDefaultOpen: boolean;
}
export class QueryEvent {
type: string;
data: any;
}
export interface ISlickRange {
fromCell: number;
fromRow: number;
toCell: number;
toRow: number;
}
export interface IResultsConfig {
shortcuts: { [key: string]: string };
messagesDefaultOpen: boolean;
}
export interface ISelectionData {
startLine: number;
startColumn: number;
endLine: number;
endColumn: number;
}
export interface ISlickRange {
fromCell: number;
fromRow: number;
toCell: number;
toRow: number;
}
export enum FieldType {
String = 0,
Boolean = 1,
Integer = 2,
Decimal = 3,
Date = 4,
Unknown = 5
}
export interface IColumnDefinition {
id?: string;
name: string;
type: FieldType;
asyncPostRender?: (cellRef: string, row: number, dataContext: JSON, colDef: any) => void;
formatter?: (row: number, cell: any, value: any, columnDef: any, dataContext: any) => string;
}
export interface IGridDataRow {
row?: number;
values: any[];
}
/**
* Simplified interface for a Range object returned by the Rangy javascript plugin
*
* @export
* @interface IRange
*/
export interface IRange {
selectNodeContents(el): void;
/**
* Returns any user-visible text covered under the range, using standard HTML Range API calls
*
* @returns {string}
*
* @memberOf IRange
*/
toString(): string;
/**
* Replaces the current selection with this range. Equivalent to rangy.getSelection().setSingleRange(range).
*
*
* @memberOf IRange
*/
select(): void;
/**
* Returns the `Document` element containing the range
*
* @returns {Document}
*
* @memberOf IRange
*/
getDocument(): Document;
/**
* Detaches the range so it's no longer tracked by Rangy using DOM manipulation
*
*
* @memberOf IRange
*/
detach(): void;
/**
* Gets formatted text under a range. This is an improvement over toString() which contains unnecessary whitespac
*
* @returns {string}
*
* @memberOf IRange
*/
text(): string;
}
/** Azure Account Interfaces */
export enum AzureLoginStatus {
Initializing = 'Initializing',
LoggingIn = 'LoggingIn',
LoggedIn = 'LoggedIn',
LoggedOut = 'LoggedOut'
}
export interface IAzureSession {
readonly environment: any;
readonly userId: string;
readonly tenantId: string;
readonly credentials: any;
}
export interface IAzureResourceFilter {
readonly sessions: IAzureSession[];
readonly subscription: ISubscription;
}
export interface ISubscription {
/**
* The fully qualified ID for the subscription. For example,
* /subscriptions/00000000-0000-0000-0000-000000000000.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* The subscription ID.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly subscriptionId?: string;
/**
* The subscription display name.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly displayName?: string;
/**
* The subscription state. Possible values are Enabled, Warned, PastDue, Disabled, and Deleted.
* Possible values include: 'Enabled', 'Warned', 'PastDue', 'Disabled', 'Deleted'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly state?: SubscriptionState;
/**
* The subscription policies.
*/
subscriptionPolicies?: ISubscriptionPolicies;
/**
* The authorization source of the request. Valid values are one or more combinations of Legacy,
* RoleBased, Bypassed, Direct and Management. For example, 'Legacy, RoleBased'.
*/
authorizationSource?: string;
}
/**
* Defines values for SubscriptionState.
* Possible values include: 'Enabled', 'Warned', 'PastDue', 'Disabled', 'Deleted'
* @readonly
* @enum {string}
*/
export type SubscriptionState = 'Enabled' | 'Warned' | 'PastDue' | 'Disabled' | 'Deleted';
/**
* Subscription policies.
*/
export interface ISubscriptionPolicies {
/**
* The subscription location placement ID. The ID indicates which regions are visible for a
* subscription. For example, a subscription with a location placement Id of Public_2014-09-01
* has access to Azure public regions.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly locationPlacementId?: string;
/**
* The subscription quota ID.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly quotaId?: string;
/**
* The subscription spending limit. Possible values include: 'On', 'Off', 'CurrentPeriodOff'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly spendingLimit?: SpendingLimit;
}
/**
* Defines values for SpendingLimit.
* Possible values include: 'On', 'Off', 'CurrentPeriodOff'
* @readonly
* @enum {string}
*/
export type SpendingLimit = 'On' | 'Off' | 'CurrentPeriodOff'; | the_stack |
const Ajv = require('ajv');
import { ValidationContext } from '../types';
import { validate,
getType } from '../validator';
import { pick,
patch } from '../picker';
import { compile } from '../compiler';
import { generateJsonSchemaObject } from '../codegen';
import { serialize, deserialize } from '../serializer';
import * as op from '../operators';
describe("json-schema-1", function() {
it("json-schema-1-1", function() {
const z = compile(`
type Foo = string;
interface A {
a: Foo;
@range(3, 5)
b: number;
@maxLength(3)
c: Foo;
[propNames: /^[e-f]$/]: number;
i?: string;
}
`);
const schema = generateJsonSchemaObject(z);
const ajv = new Ajv({allErrors: true});
// tslint:disable-next-line: no-implicit-dependencies
ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'));
const ajvValidate = ajv.addSchema(schema).getSchema('#/definitions/A');
expect(ajvValidate({a: 'z', b: 5, c: '123'})).toEqual(true);
expect(ajvValidate({b: 5, c: '123'})).toEqual(false);
expect(ajvValidate.errors).toEqual([{
keyword: 'required',
dataPath: '',
schemaPath: '#/required',
params: { missingProperty: 'a' },
message: 'should have required property \'a\'',
}]);
expect(ajvValidate({a: 1, b: 5, c: '123'})).toEqual(false);
expect(ajvValidate.errors).toEqual([{
keyword: 'type',
dataPath: '.a',
schemaPath: '#/definitions/Foo/type',
params: { type: 'string' },
message: 'should be string',
}]);
expect(ajvValidate({a: 'z', b: 6, c: '123'})).toEqual(false);
expect(ajvValidate.errors).toEqual([{
keyword: 'maximum',
dataPath: '.b',
schemaPath: '#/properties/b/maximum',
params: { comparison: '<=', limit: 5, exclusive: false },
message: 'should be <= 5',
}]);
expect(ajvValidate({a: 'z', b: 5, c: '1234'})).toEqual(false);
expect(ajvValidate.errors).toEqual([{
keyword: 'maxLength',
dataPath: '.c',
schemaPath: '#/properties/c/maxLength',
params: { limit: 3 },
message: 'should NOT be longer than 3 characters',
}]);
expect(ajvValidate({b: 6, c: '1234'})).toEqual(false);
expect(ajvValidate.errors).toEqual([{
keyword: 'required',
dataPath: '',
schemaPath: '#/required',
params: { missingProperty: 'a' },
message: 'should have required property \'a\'',
}, {
keyword: 'maximum',
dataPath: '.b',
schemaPath: '#/properties/b/maximum',
params: { comparison: '<=', limit: 5, exclusive: false },
message: 'should be <= 5',
}, {
keyword: 'maxLength',
dataPath: '.c',
schemaPath: '#/properties/c/maxLength',
params: { limit: 3 },
message: 'should NOT be longer than 3 characters',
}]);
expect(ajvValidate({a: 'z', b: 5, c: '123', d: 11})).toEqual(false);
expect(ajvValidate.errors).toEqual([{
keyword: 'additionalProperties',
dataPath: '',
schemaPath: '#/additionalProperties',
params: { additionalProperty: 'd' },
message: 'should NOT have additional properties',
}]);
expect(ajvValidate({a: 'z', b: 5, c: '123', d: '11'})).toEqual(false);
expect(ajvValidate.errors).toEqual([{
keyword: 'additionalProperties',
dataPath: '',
schemaPath: '#/additionalProperties',
params: { additionalProperty: 'd' },
message: 'should NOT have additional properties',
}]);
expect(ajvValidate({a: 'z', b: 5, c: '123', e: 11})).toEqual(true);
expect(ajvValidate({a: 'z', b: 5, c: '123', e: '11'})).toEqual(false);
expect(ajvValidate.errors).toEqual([{
keyword: 'type',
dataPath: '[\'e\']',
schemaPath: '#/patternProperties/%5E%5Be-f%5D%24/type',
params: { type: 'number' },
message: 'should be number',
}]);
expect(ajvValidate({a: 'z', b: 5, c: '123', i: '11'})).toEqual(true);
expect(ajvValidate({a: 'z', b: 5, c: '123', i: 11})).toEqual(false);
expect(ajvValidate.errors).toEqual([{
keyword: 'type',
dataPath: '.i',
schemaPath: '#/properties/i/type',
params: { type: 'string' },
message: 'should be string',
}]);
});
it("json-schema-1-2", function() {
const z = compile(`
type Foo = string;
interface A {
a: Foo;
@range(3, 5)
b: number;
@maxLength(3)
c: Foo;
[propNames: /^[e-f]$/]: number;
i?: string;
}
interface B {
x: A;
}
`);
const schema = generateJsonSchemaObject(z);
const ajv = new Ajv({allErrors: true});
// tslint:disable-next-line: no-implicit-dependencies
ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'));
const ajvValidate = ajv.addSchema(schema).getSchema('#/definitions/B');
expect(ajvValidate({x: {a: 'z', b: 5, c: '123'}})).toEqual(true);
expect(ajvValidate({x: {b: 5, c: '123'}})).toEqual(false);
expect(ajvValidate.errors).toEqual([{
keyword: 'required',
dataPath: '.x',
schemaPath: '#/required',
params: { missingProperty: 'a' },
message: 'should have required property \'a\'',
}]);
expect(ajvValidate({x: {a: 1, b: 5, c: '123'}})).toEqual(false);
expect(ajvValidate.errors).toEqual([{
keyword: 'type',
dataPath: '.x.a',
schemaPath: '#/definitions/Foo/type',
params: { type: 'string' },
message: 'should be string',
}]);
});
it("json-schema-1-3", function() {
const z = compile(`
type Foo = string;
type A = {
a: Foo,
@range(3, 5)
b: number,
@maxLength(3)
c: Foo,
[propNames: /^[e-f]$/]: number,
i?: string,
};
type B = {
x: A,
};
`);
const schema = generateJsonSchemaObject(z);
const ajv = new Ajv({allErrors: true});
// tslint:disable-next-line: no-implicit-dependencies
ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'));
const ajvValidate = ajv.addSchema(schema).getSchema('#/definitions/B');
expect(ajvValidate({x: {a: 'z', b: 5, c: '123'}})).toEqual(true);
expect(ajvValidate({x: {b: 5, c: '123'}})).toEqual(false);
expect(ajvValidate.errors).toEqual([{
keyword: 'required',
dataPath: '.x',
schemaPath: '#/required',
params: { missingProperty: 'a' },
message: 'should have required property \'a\'',
}]);
expect(ajvValidate({x: {a: 1, b: 5, c: '123'}})).toEqual(false);
expect(ajvValidate.errors).toEqual([{
keyword: 'type',
dataPath: '.x.a',
schemaPath: '#/definitions/Foo/type',
params: { type: 'string' },
message: 'should be string',
}]);
});
it("json-schema-1-4", function() {
const z = compile(`
type Foo = string|number;
`);
const schema = generateJsonSchemaObject(z);
const ajv = new Ajv({allErrors: true});
// tslint:disable-next-line: no-implicit-dependencies
ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'));
const ajvValidate = ajv.addSchema(schema).getSchema('#/definitions/Foo');
expect(ajvValidate(11)).toEqual(true);
expect(ajvValidate('11')).toEqual(true);
expect(ajvValidate(true)).toEqual(false);
expect(ajvValidate.errors).toEqual([{
keyword: 'type',
dataPath: '',
schemaPath: '#/anyOf/0/type',
params: { type: 'string' },
message: 'should be string',
}, {
keyword: 'type',
dataPath: '',
schemaPath: '#/anyOf/1/type',
params: { type: 'number' },
message: 'should be number',
}, {
keyword: 'anyOf',
dataPath: '',
schemaPath: '#/anyOf',
params: {},
message: 'should match some schema in anyOf',
}]);
});
it("json-schema-1-5", function() {
const z = compile(`
type Foo = number[];
`);
const schema = generateJsonSchemaObject(z);
const ajv = new Ajv({allErrors: true});
// tslint:disable-next-line: no-implicit-dependencies
ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'));
const ajvValidate = ajv.addSchema(schema).getSchema('#/definitions/Foo');
expect(ajvValidate([11, 13])).toEqual(true);
expect(ajvValidate([11, 13, '17'])).toEqual(false);
expect(ajvValidate.errors).toEqual([{
keyword: 'type',
dataPath: '[2]',
schemaPath: '#/items/type',
params: { type: 'number' },
message: 'should be number',
}]);
});
it("json-schema-1-6", function() {
const z = compile(`
type Foo = (number|boolean)[];
`);
const schema = generateJsonSchemaObject(z);
const ajv = new Ajv({allErrors: true});
// tslint:disable-next-line: no-implicit-dependencies
ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'));
const ajvValidate = ajv.addSchema(schema).getSchema('#/definitions/Foo');
expect(ajvValidate([11, 13, false])).toEqual(true);
expect(ajvValidate([11, 13, '17'])).toEqual(false);
expect(ajvValidate.errors).toEqual([{
keyword: 'type',
dataPath: '[2]',
schemaPath: '#/items/anyOf/0/type',
params: { type: 'number' },
message: 'should be number',
}, {
keyword: 'type',
dataPath: '[2]',
schemaPath: '#/items/anyOf/1/type',
params: { type: 'boolean' },
message: 'should be boolean',
}, {
keyword: 'anyOf',
dataPath: '[2]',
schemaPath: '#/items/anyOf',
params: {},
message: 'should match some schema in anyOf',
}]);
});
it("json-schema-1-6", function() {
const z = compile(`
type Foo = [number, boolean];
`);
const schema = generateJsonSchemaObject(z);
const ajv = new Ajv({allErrors: true});
// tslint:disable-next-line: no-implicit-dependencies
ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'));
const ajvValidate = ajv.addSchema(schema).getSchema('#/definitions/Foo');
expect(ajvValidate([11, false])).toEqual(true); // NOTE: In JSON Schema, compile to `(number | boolean)[]`
expect(ajvValidate([false, 11, 13])).toEqual(true);
expect(ajvValidate([11, 13, '17'])).toEqual(false);
expect(ajvValidate.errors).toEqual([{
keyword: 'type',
dataPath: '[2]',
schemaPath: '#/items/anyOf/0/type',
params: { type: 'number' },
message: 'should be number',
}, {
keyword: 'type',
dataPath: '[2]',
schemaPath: '#/items/anyOf/1/type',
params: { type: 'boolean' },
message: 'should be boolean',
}, {
keyword: 'anyOf',
dataPath: '[2]',
schemaPath: '#/items/anyOf',
params: {},
message: 'should match some schema in anyOf',
}]);
});
it("json-schema-1-7", function() {
const z = compile(`
enum Foo {
A = 'a',
B = 10,
C = 'b',
}
`);
const schema = generateJsonSchemaObject(z);
const ajv = new Ajv({allErrors: true});
// tslint:disable-next-line: no-implicit-dependencies
ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'));
const ajvValidate = ajv.addSchema(schema).getSchema('#/definitions/Foo');
expect(ajvValidate('a')).toEqual(true);
expect(ajvValidate(10)).toEqual(true);
expect(ajvValidate('b')).toEqual(true);
expect(ajvValidate(11)).toEqual(false);
expect(ajvValidate.errors).toEqual([{
keyword: 'enum',
dataPath: '',
schemaPath: '#/enum',
params: { allowedValues: ['a', 10, 'b'] },
message: 'should be equal to one of the allowed values',
}]);
expect(ajvValidate('c')).toEqual(false);
expect(ajvValidate.errors).toEqual([{
keyword: 'enum',
dataPath: '',
schemaPath: '#/enum',
params: { allowedValues: ['a', 10, 'b'] },
message: 'should be equal to one of the allowed values',
}]);
});
}); | the_stack |
import { xiexports } from "../xiexports"
xiexports.monaco = {
loaded: false,
}
var onloadCallbacks: Array<() => void> = []
// Pass in a callback to be notified once monaco is loaded
xiexports.monaco.onload = (f: () => void) => {
if (xiexports.monaco.loaded)
f()
else
onloadCallbacks.push(f)
}
// Called by monaco to announce that it is done loading
xiexports.monaco.init = () => {
xiexports.monaco.loaded = true
while (onloadCallbacks.length > 0) {
var callback = onloadCallbacks.shift()
if (callback != null)
callback()
}
}
xiexports.monaco.WorkbookCodeEditor = (options: WorkbookCodeEditorOptions) => new WorkbookCodeEditor(options)
xiexports.monaco.RegisterWorkbookCompletionItemProvider = (lang: string, onCompletionListRequested: IProvide<monaco.languages.CompletionItem[]>) =>
monaco.languages.registerCompletionItemProvider(
lang,
new WorkbookCompletionItemProvider(onCompletionListRequested))
xiexports.monaco.RegisterWorkbookSignatureHelpProvider = (lang: string, onSignatureHelpRequested: IProvide<monaco.languages.SignatureHelp>) =>
monaco.languages.registerSignatureHelpProvider(
lang,
new WorkbookSignatureHelpProvider(onSignatureHelpRequested))
xiexports.monaco.RegisterWorkbookHoverProvider = (lang: string, onHoverRequested: IProvide<monaco.languages.Hover>) =>
monaco.languages.registerHoverProvider(
lang,
new WorkbookHoverProvider(onHoverRequested))
xiexports.monaco.Promise = (init: (complete: monaco.TValueCallback<any>, error: (err: any) => void) => void) =>
new monaco.Promise(init)
interface IProvide<T> {
(model: monaco.editor.IReadOnlyModel, position: monaco.Position, token: monaco.CancellationToken): monaco.Thenable<T>;
}
enum AbstractCursorPosition {
DocumentStart = 0,
DocumentEnd = 1,
FirstLineEnd = 2,
Up,
Down,
}
enum ViewEventType {
ViewLinesDeleted = 8,
ViewLinesInserted = 9
}
class WorkbookCompletionItemProvider implements monaco.languages.CompletionItemProvider {
private provideImpl: IProvide<monaco.languages.CompletionItem[]>
triggerCharacters = ['.']
constructor(onCompletionListRequested: IProvide<monaco.languages.CompletionItem[]>) {
this.provideImpl = onCompletionListRequested
}
provideCompletionItems(
model: monaco.editor.IReadOnlyModel,
position: monaco.Position,
token: monaco.CancellationToken) {
return this.provideImpl(model, position, token)
}
}
class WorkbookSignatureHelpProvider implements monaco.languages.SignatureHelpProvider {
private provideImpl: IProvide<monaco.languages.SignatureHelp>
signatureHelpTriggerCharacters = ['(', ',']
constructor(onSignatureHelpRequested: IProvide<monaco.languages.SignatureHelp>) {
this.provideImpl = onSignatureHelpRequested
}
provideSignatureHelp(
model: monaco.editor.IReadOnlyModel,
position: monaco.Position,
token: monaco.CancellationToken) {
return this.provideImpl(model, position, token)
}
}
class WorkbookHoverProvider implements monaco.languages.HoverProvider {
private provideImpl: IProvide<monaco.languages.Hover>
constructor(onHoverRequested: IProvide<monaco.languages.Hover>) {
this.provideImpl = onHoverRequested
}
provideHover(
model: monaco.editor.IReadOnlyModel,
position: monaco.Position,
token: monaco.CancellationToken) {
return this.provideImpl(model, position, token)
}
}
interface WorkbookCodeEditorChangeEvent {
text: string
triggerChar: string|null
newCursorPosition: monaco.IPosition
isDelete: boolean
isUndoing: boolean
isRedoing: boolean
}
interface WorkbookCodeEditorOptions {
placeElem: HTMLElement
readOnly: boolean
fontSize: number
showLineNumbers: boolean
onCursorUpDown?: (isUp: boolean) => boolean
onEnter?: (isShift: boolean, isMeta: boolean, isCtrl: boolean) => boolean
onFocus?: () => void
onChange?: (event: WorkbookCodeEditorChangeEvent) => void
theme?: string,
wrapLongLines: boolean,
}
class WorkbookCodeEditor {
private options: WorkbookCodeEditorOptions
private monacoEditorOptions: monaco.editor.IEditorConstructionOptions
private markedTextIds: string[] = []
private windowResizeHandler: EventListener
private internalViewEventsHandler: any
private debouncedUpdateLayout: () => void
mEditor: monaco.editor.IStandaloneCodeEditor
constructor(options: WorkbookCodeEditorOptions) {
this.options = options
this.monacoEditorOptions = {
language: "csharp",
readOnly: options.readOnly,
scrollBeyondLastLine: false,
roundedSelection: false,
fontSize: options.fontSize,
overviewRulerLanes: 0, // 0 = hide overview ruler
formatOnType: true,
wordWrap: options.wrapLongLines ? "on" : "off",
renderIndentGuides: false,
contextmenu: false,
cursorBlinking: 'phase',
minimap: {
enabled: false,
},
scrollbar: {
// must explicitly hide scrollbars so they don't interfere with mouse events
horizontal: options.wrapLongLines ? "hidden" : "auto",
vertical: 'hidden',
handleMouseWheel: false,
useShadows: false,
},
}
this.updateLineNumbers()
this.mEditor = monaco.editor.create(
options.placeElem, this.monacoEditorOptions)
monaco.editor.setTheme(options.theme || "vs")
this.mEditor.onKeyDown(e => this.onKeyDown(e))
if (this.options.onChange)
this.mEditor.onDidChangeModelContent(e => this.onChange(e))
if (this.options.onFocus)
this.mEditor.onDidFocusEditor(() => {
if (this.options.onFocus != null)
this.options.onFocus()
})
this.debouncedUpdateLayout = this.debounce(() => this.updateLayout(), 250)
this.updateLayout()
this.windowResizeHandler = _ => this.updateLayout()
window.addEventListener("resize", this.windowResizeHandler)
let untypedEditor: any = this.mEditor
this.internalViewEventsHandler = {
handleEvents: (e: any[]) => this.handleInternalViewEvents(e),
}
untypedEditor._view.eventDispatcher.addEventHandler(this.internalViewEventsHandler)
}
// See ViewEventHandler
private handleInternalViewEvents(events: any[]) {
for (let i = 0, len = events.length; i < len; i++) {
let type: number = events[i].type;
// This is the best way for us to find out about lines being added and
// removed, if you take wrapping into account.
if (type == ViewEventType.ViewLinesInserted || type == ViewEventType.ViewLinesDeleted)
this.updateLayout()
}
}
private onKeyDown(e: monaco.IKeyboardEvent) {
if (this.isCompletionWindowVisible())
return
let cancel = false
if (e.keyCode == monaco.KeyCode.Enter && this.options.onEnter)
cancel = this.options.onEnter(e.shiftKey, e.metaKey, e.ctrlKey)
else if (e.keyCode == monaco.KeyCode.UpArrow && !e.shiftKey && !e.metaKey && this.options.onCursorUpDown && !this.isParameterHintsWindowVisible())
cancel = this.options.onCursorUpDown(true)
else if (e.keyCode == monaco.KeyCode.DownArrow && !e.shiftKey && !e.metaKey && this.options.onCursorUpDown && !this.isParameterHintsWindowVisible())
cancel = this.options.onCursorUpDown(false)
else if (e.metaKey && (
((e.keyCode == monaco.KeyCode.US_CLOSE_SQUARE_BRACKET || e.keyCode == monaco.KeyCode.US_OPEN_SQUARE_BRACKET) && e.shiftKey) ||
e.keyCode == monaco.KeyCode.KEY_G))
e.stopPropagation()
if (cancel) {
e.preventDefault()
e.stopPropagation()
}
}
private updateLayout() {
let clientWidth = this.options.placeElem.parentElement && this.options.placeElem.parentElement.clientWidth || 0
let fontSize = this.monacoEditorOptions.fontSize || 0
this.mEditor.layout({
// NOTE: Something weird happens in layout, and padding+border are added
// on top of the total width by monaco. So we subtract those here.
// Keep in sync with editor.css. Currently 0.5em left/right padding
// and 1px border means (1em + 2px) to subtract.
width: clientWidth - (fontSize + 2),
height: (<any>this.mEditor)._view._context.viewLayout._linesLayout.getLinesTotalHeight()
})
}
private onChange(e: monaco.editor.IModelContentChangedEvent) {
for (const change of e.changes) {
let changedText = change.text == null ? "" : change.text
let isDelete = changedText.length == 0
let newCursorPosition = {
lineNumber: change.range.startLineNumber,
column: change.range.startColumn,
}
for (let ch of changedText) {
if (ch == e.eol) {
newCursorPosition.lineNumber++
newCursorPosition.column = 1
} else
newCursorPosition.column++
}
if (this.options.onChange != null)
this.options.onChange({
isUndoing: e.isUndoing,
isRedoing: e.isRedoing,
isDelete: isDelete,
newCursorPosition: newCursorPosition,
triggerChar: isDelete ? null : change.text[change.text.length - 1],
text: changedText,
})
}
}
isSomethingSelected() {
let sel = this.mEditor.getSelection()
return !sel.getStartPosition().equals(sel.getEndPosition())
}
getLastLineIndex() {
return this.mEditor.getModel().getLineCount() - 1
}
isCursorAtEnd() {
let pos = this.mEditor.getPosition()
let model = this.mEditor.getModel()
return pos.lineNumber == model.getLineCount() &&
pos.column == model.getLineMaxColumn(pos.lineNumber)
}
isReadOnly() {
return this.monacoEditorOptions.readOnly
}
setReadOnly(readOnly: boolean) {
this.monacoEditorOptions.readOnly = readOnly
this.mEditor.updateOptions(this.monacoEditorOptions)
}
setFontSize(fontSize: number) {
this.monacoEditorOptions.fontSize = fontSize
this.updateOptions()
}
setTheme(themeName: string) {
monaco.editor.setTheme(themeName)
}
setWordWrap(wrapLongLines: boolean) {
this.monacoEditorOptions.wordWrap = wrapLongLines ? "on" : "off"
if (this.monacoEditorOptions.scrollbar)
this.monacoEditorOptions.scrollbar.horizontal = wrapLongLines ? "hidden" : "auto"
this.updateOptions()
}
setShowLineNumbers(showLineNumbers: boolean) {
this.options.showLineNumbers = showLineNumbers
this.updateLineNumbers()
this.updateOptions()
}
private updateLineNumbers() {
this.monacoEditorOptions.lineNumbersMinChars = 1
if (this.options.showLineNumbers) {
this.monacoEditorOptions.lineNumbers = 'on'
this.monacoEditorOptions.lineDecorationsWidth = 8
} else {
this.monacoEditorOptions.lineNumbers = 'off'
this.monacoEditorOptions.lineDecorationsWidth = 0
}
}
private updateOptions() {
this.mEditor.updateOptions(this.monacoEditorOptions)
this.debouncedUpdateLayout()
}
private debounce (action: () => void, delay: number) {
var debounceTimeout: number
return () => {
clearTimeout(debounceTimeout)
debounceTimeout = setTimeout(action, delay)
}
}
focus() {
this.updateLayout()
this.mEditor.focus()
}
getModelId() {
return this.mEditor.getModel().id
}
getText() {
return this.mEditor.getValue({
preserveBOM: true,
lineEnding: "\n"
})
}
setText(value: string) {
this.mEditor.setValue(value)
this.debouncedUpdateLayout()
}
// TODO: It would be better if we had API access to SuggestController, and if
// SuggestController had API to check widget visibility. In the future
// we could add this functionality to monaco.
// (or if our keybindings had access to 'suggestWidgetVisible' context key)
isCompletionWindowVisible() {
return this.isMonacoWidgetVisible("suggest-widget")
}
isParameterHintsWindowVisible() {
return this.isMonacoWidgetVisible("parameter-hints-widget")
}
dismissParameterHintsWindow() {
if (this.isParameterHintsWindowVisible())
this.mEditor.setPosition({lineNumber:1, column:1})
}
isMonacoWidgetVisible(widgetClassName: string) {
let node = this.mEditor.getDomNode()
if (node == null)
return false
let widgets = node.getElementsByClassName(widgetClassName)
for (var i = 0; i < widgets.length; i++)
if (widgets[i].classList.contains("visible"))
return true
return false
}
showCompletionWindow() {
this.mEditor.trigger("", "editor.action.triggerSuggest", null)
}
setCursorPosition(position: AbstractCursorPosition) {
switch (position) {
case AbstractCursorPosition.DocumentStart:
this.mEditor.trigger("", 'cursorTop', null)
break
case AbstractCursorPosition.DocumentEnd:
this.mEditor.trigger("", 'cursorBottom', null)
break
case AbstractCursorPosition.FirstLineEnd:
this.mEditor.setPosition(new monaco.Position(
1, this.mEditor.getModel().getLineContent(1).length + 1))
break
case AbstractCursorPosition.Up:
this.mEditor.trigger("", 'cursorUp', null)
break
case AbstractCursorPosition.Down:
this.mEditor.trigger("", 'cursorDown', null)
break
}
}
markText(range: monaco.IRange, className?: string, title?: string) {
let newIds = this.mEditor.getModel().deltaDecorations([], [{
range: range,
options: {
inlineClassName: className,
hoverMessage: title,
},
}])
this.markedTextIds.push(...newIds)
}
clearMarkedText() {
this.mEditor.getModel().deltaDecorations(this.markedTextIds, [])
this.markedTextIds = []
}
dispose() {
window.removeEventListener("resize", this.windowResizeHandler)
let untypedEditor: any = this.mEditor
untypedEditor._view.eventDispatcher.removeEventHandler(this.internalViewEventsHandler)
this.mEditor.dispose()
}
} | the_stack |
import { Code } from '@blueprintjs/core';
import React from 'react';
import { AutoForm, Field } from '../components';
import { deepGet, deepSet, oneOf, pluralIfNeeded, typeIs } from '../utils';
export interface ExtractionNamespaceSpec {
readonly type: string;
readonly uri?: string;
readonly uriPrefix?: string;
readonly fileRegex?: string;
readonly namespaceParseSpec?: NamespaceParseSpec;
readonly connectorConfig?: {
readonly createTables: boolean;
readonly connectURI: string;
readonly user: string;
readonly password: string;
};
readonly table?: string;
readonly keyColumn?: string;
readonly valueColumn?: string;
readonly filter?: any;
readonly tsColumn?: string;
readonly pollPeriod?: number | string;
}
export interface NamespaceParseSpec {
readonly format: string;
readonly columns?: string[];
readonly keyColumn?: string;
readonly valueColumn?: string;
readonly hasHeaderRow?: boolean;
readonly skipHeaderRows?: number;
readonly keyFieldName?: string;
readonly valueFieldName?: string;
readonly delimiter?: string;
readonly listDelimiter?: string;
}
export interface LookupSpec {
readonly type: string;
readonly map?: Record<string, string | number>;
readonly extractionNamespace?: ExtractionNamespaceSpec;
readonly firstCacheTimeout?: number;
readonly injective?: boolean;
}
function issueWithUri(uri: string): string | undefined {
if (!uri) return;
const m = /^(\w+):/.exec(uri);
if (!m) return `URI is invalid, must start with 'file:', 'hdfs:', 's3:', or 'gs:`;
if (!oneOf(m[1], 'file', 'hdfs', 's3', 'gs')) {
return `Unsupported location '${m[1]}:'. Only 'file:', 'hdfs:', 's3:', and 'gs:' locations are supported`;
}
return;
}
function issueWithConnectUri(uri: string): string | undefined {
if (!uri) return;
if (!uri.startsWith('jdbc:')) return `connectURI is invalid, must start with 'jdbc:'`;
return;
}
export const LOOKUP_FIELDS: Field<LookupSpec>[] = [
{
name: 'type',
type: 'string',
suggestions: ['map', 'cachedNamespace'],
required: true,
adjustment: l => {
if (l.type === 'map' && !l.map) {
return deepSet(l, 'map', {});
}
if (l.type === 'cachedNamespace' && !deepGet(l, 'extractionNamespace.type')) {
return deepSet(l, 'extractionNamespace', { type: 'uri', pollPeriod: 'PT1H' });
}
return l;
},
},
// map lookups are simple
{
name: 'map',
type: 'json',
height: '60vh',
defined: typeIs('map'),
required: true,
issueWithValue: value => {
if (!value) return 'map must be defined';
if (typeof value !== 'object') return `map must be an object`;
for (const k in value) {
const typeValue = typeof value[k];
if (typeValue !== 'string' && typeValue !== 'number') {
return `map key '${k}' is of the wrong type '${typeValue}'`;
}
}
return;
},
},
// cachedNamespace lookups have more options
{
name: 'extractionNamespace.type',
label: 'Extraction type',
type: 'string',
placeholder: 'uri',
suggestions: ['uri', 'jdbc'],
defined: typeIs('cachedNamespace'),
required: true,
},
{
name: 'extractionNamespace.uriPrefix',
label: 'URI prefix',
type: 'string',
placeholder: 's3://bucket/some/key/prefix/',
defined: l =>
deepGet(l, 'extractionNamespace.type') === 'uri' && !deepGet(l, 'extractionNamespace.uri'),
required: l =>
!deepGet(l, 'extractionNamespace.uriPrefix') && !deepGet(l, 'extractionNamespace.uri'),
issueWithValue: issueWithUri,
info: (
<p>
A URI which specifies a directory (or other searchable resource) in which to search for
files specified as a <Code>file</Code>, <Code>hdfs</Code>, <Code>s3</Code>, or{' '}
<Code>gs</Code> path prefix.
</p>
),
},
{
name: 'extractionNamespace.uri',
type: 'string',
label: 'URI (deprecated)',
placeholder: 's3://bucket/some/key/prefix/lookups-01.gz',
defined: l =>
deepGet(l, 'extractionNamespace.type') === 'uri' &&
!deepGet(l, 'extractionNamespace.uriPrefix'),
required: l =>
!deepGet(l, 'extractionNamespace.uriPrefix') && !deepGet(l, 'extractionNamespace.uri'),
issueWithValue: issueWithUri,
info: (
<>
<p>
URI for the file of interest, specified as a <Code>file</Code>, <Code>hdfs</Code>,{' '}
<Code>s3</Code>, or <Code>gs</Code> path
</p>
<p>The URI prefix option is strictly better than URI and should be used instead</p>
</>
),
},
{
name: 'extractionNamespace.fileRegex',
label: 'File regex',
type: 'string',
defaultValue: '.*',
defined: l =>
deepGet(l, 'extractionNamespace.type') === 'uri' &&
Boolean(deepGet(l, 'extractionNamespace.uriPrefix')),
info: 'Optional regex for matching the file name under uriPrefix.',
},
// namespaceParseSpec
{
name: 'extractionNamespace.namespaceParseSpec.format',
label: 'Parse format',
type: 'string',
suggestions: ['csv', 'tsv', 'simpleJson', 'customJson'],
defined: l => deepGet(l, 'extractionNamespace.type') === 'uri',
required: true,
info: (
<>
<p>The format of the data in the lookup files.</p>
<p>
The <Code>simpleJson</Code> lookupParseSpec does not take any parameters. It is simply a
line delimited JSON file where the field is the key, and the field's value is the
value.
</p>
</>
),
},
// TSV only
{
name: 'extractionNamespace.namespaceParseSpec.delimiter',
type: 'string',
defaultValue: '\t',
suggestions: ['\t', ';', '|', '#'],
defined: l => deepGet(l, 'extractionNamespace.namespaceParseSpec.format') === 'tsv',
},
// CSV + TSV
{
name: 'extractionNamespace.namespaceParseSpec.skipHeaderRows',
type: 'number',
defaultValue: 0,
defined: l => oneOf(deepGet(l, 'extractionNamespace.namespaceParseSpec.format'), 'csv', 'tsv'),
info: `Number of header rows to be skipped.`,
},
{
name: 'extractionNamespace.namespaceParseSpec.hasHeaderRow',
type: 'boolean',
defaultValue: false,
defined: l => oneOf(deepGet(l, 'extractionNamespace.namespaceParseSpec.format'), 'csv', 'tsv'),
info: `A flag to indicate that column information can be extracted from the input files' header row`,
},
{
name: 'extractionNamespace.namespaceParseSpec.columns',
type: 'string-array',
placeholder: 'key, value',
defined: l => oneOf(deepGet(l, 'extractionNamespace.namespaceParseSpec.format'), 'csv', 'tsv'),
required: l => !deepGet(l, 'extractionNamespace.namespaceParseSpec.hasHeaderRow'),
info: 'The list of columns in the csv file',
},
{
name: 'extractionNamespace.namespaceParseSpec.keyColumn',
type: 'string',
placeholder: '(optional - defaults to the first column)',
defined: l => oneOf(deepGet(l, 'extractionNamespace.namespaceParseSpec.format'), 'csv', 'tsv'),
info: 'The name of the column containing the key',
},
{
name: 'extractionNamespace.namespaceParseSpec.valueColumn',
type: 'string',
placeholder: '(optional - defaults to the second column)',
defined: l => oneOf(deepGet(l, 'extractionNamespace.namespaceParseSpec.format'), 'csv', 'tsv'),
info: 'The name of the column containing the value',
},
// Custom JSON
{
name: 'extractionNamespace.namespaceParseSpec.keyFieldName',
type: 'string',
placeholder: `key`,
defined: l => deepGet(l, 'extractionNamespace.namespaceParseSpec.format') === 'customJson',
required: true,
},
{
name: 'extractionNamespace.namespaceParseSpec.valueFieldName',
type: 'string',
placeholder: `value`,
defined: l => deepGet(l, 'extractionNamespace.namespaceParseSpec.format') === 'customJson',
required: true,
},
// JDBC stuff
{
name: 'extractionNamespace.connectorConfig.connectURI',
label: 'Connect URI',
type: 'string',
defined: l => deepGet(l, 'extractionNamespace.type') === 'jdbc',
required: true,
issueWithValue: issueWithConnectUri,
info: 'Defines the connectURI for connecting to the database',
},
{
name: 'extractionNamespace.connectorConfig.user',
type: 'string',
defined: l => deepGet(l, 'extractionNamespace.type') === 'jdbc',
info: 'Defines the user to be used by the connector config',
},
{
name: 'extractionNamespace.connectorConfig.password',
type: 'string',
defined: l => deepGet(l, 'extractionNamespace.type') === 'jdbc',
info: 'Defines the password to be used by the connector config',
},
{
name: 'extractionNamespace.table',
type: 'string',
placeholder: 'lookup_table',
defined: l => deepGet(l, 'extractionNamespace.type') === 'jdbc',
required: true,
info: (
<>
<p>
The table which contains the key value pairs. This will become the table value in the SQL
query:
</p>
<p>
SELECT keyColumn, valueColumn, tsColumn? FROM <strong>table</strong> WHERE filter
</p>
</>
),
},
{
name: 'extractionNamespace.keyColumn',
type: 'string',
placeholder: 'key_column',
defined: l => deepGet(l, 'extractionNamespace.type') === 'jdbc',
required: true,
info: (
<>
<p>
The column in the table which contains the keys. This will become the keyColumn value in
the SQL query:
</p>
<p>
SELECT <strong>keyColumn</strong>, valueColumn, tsColumn? FROM table WHERE filter
</p>
</>
),
},
{
name: 'extractionNamespace.valueColumn',
type: 'string',
placeholder: 'value_column',
defined: l => deepGet(l, 'extractionNamespace.type') === 'jdbc',
required: true,
info: (
<>
<p>
The column in table which contains the values. This will become the valueColumn value in
the SQL query:
</p>
<p>
SELECT keyColumn, <strong>valueColumn</strong>, tsColumn? FROM table WHERE filter
</p>
</>
),
},
{
name: 'extractionNamespace.tsColumn',
type: 'string',
label: 'Timestamp column',
placeholder: 'timestamp_column (optional)',
defined: l => deepGet(l, 'extractionNamespace.type') === 'jdbc',
info: (
<>
<p>
The column in table which contains when the key was updated. This will become the Value in
the SQL query:
</p>
<p>
SELECT keyColumn, valueColumn, <strong>tsColumn</strong>? FROM table WHERE filter
</p>
</>
),
},
{
name: 'extractionNamespace.filter',
type: 'string',
placeholder: 'for_lookup = 1 (optional)',
defined: l => deepGet(l, 'extractionNamespace.type') === 'jdbc',
info: (
<>
<p>
The filter to be used when selecting lookups, this is used to create a where clause on
lookup population. This will become the expression filter in the SQL query:
</p>
<p>
SELECT keyColumn, valueColumn, tsColumn? FROM table WHERE <strong>filter</strong>
</p>
</>
),
},
{
name: 'extractionNamespace.pollPeriod',
type: 'duration',
defined: l => oneOf(deepGet(l, 'extractionNamespace.type'), 'uri', 'jdbc'),
info: `Period between polling for updates`,
required: true,
suggestions: ['PT1M', 'PT10M', 'PT30M', 'PT1H', 'PT6H', 'P1D'],
},
// Extra cachedNamespace things
{
name: 'firstCacheTimeout',
type: 'number',
defaultValue: 0,
defined: typeIs('cachedNamespace'),
info: `How long to wait (in ms) for the first run of the cache to populate. 0 indicates to not wait`,
},
{
name: 'injective',
type: 'boolean',
defaultValue: false,
defined: typeIs('cachedNamespace'),
info: `If the underlying map is injective (keys and values are unique) then optimizations can occur internally by setting this to true`,
},
];
export function isLookupInvalid(
lookupId: string | undefined,
lookupVersion: string | undefined,
lookupTier: string | undefined,
lookupSpec: Partial<LookupSpec>,
) {
return (
!lookupId || !lookupVersion || !lookupTier || !AutoForm.isValidModel(lookupSpec, LOOKUP_FIELDS)
);
}
export function lookupSpecSummary(spec: LookupSpec): string {
const { map, extractionNamespace } = spec;
if (map) {
return pluralIfNeeded(Object.keys(map).length, 'key');
}
if (extractionNamespace) {
switch (extractionNamespace.type) {
case 'uri':
if (extractionNamespace.uriPrefix) {
return `URI prefix: ${extractionNamespace.uriPrefix}, Match: ${
extractionNamespace.fileRegex || '.*'
}`;
}
if (extractionNamespace.uri) {
return `URI: ${extractionNamespace.uri}`;
}
return 'Unknown extractionNamespace lookup';
case 'jdbc': {
const columns = [
`${extractionNamespace.keyColumn} AS key`,
`${extractionNamespace.valueColumn} AS value`,
];
if (extractionNamespace.tsColumn) {
columns.push(`${extractionNamespace.tsColumn} AS ts`);
}
const queryParts = ['SELECT', columns.join(', '), `FROM ${extractionNamespace.table}`];
if (extractionNamespace.filter) {
queryParts.push(`WHERE ${extractionNamespace.filter}`);
}
return `${
extractionNamespace.connectorConfig?.connectURI || 'No connectURI'
} [${queryParts.join(' ')}]`;
}
}
}
return 'Unknown lookup';
} | the_stack |
import {
Directive,
EmbeddedViewRef,
Input,
Optional,
TemplateRef,
ViewContainerRef,
OnInit,
OnDestroy,
Renderer2,
} from '@angular/core';
import { makeStateKey, StateKey, TransferState } from '@angular/platform-browser';
import { BuilderContentService } from '../services/builder-content.service';
import { BuilderService } from '../services/builder.service';
import { Builder, Subscription as BuilderSubscription } from '@builder.io/sdk';
import { BuilderComponentService } from '../components/builder-component/builder-component.service';
import { Router, NavigationEnd, NavigationStart } from '@angular/router';
import { Subscription } from 'rxjs';
@Directive({
selector: '[builderModel]',
providers: [BuilderContentService],
})
export class BuilderContentDirective implements OnInit, OnDestroy {
private get component() {
// return BuilderService.componentInstances[this._context.model as string];
return this.builderComponentService.contentComponentInstance;
}
lastContentId: string | null = null;
lastUrl: string | null = null;
private subscriptions = new Subscription();
private _context: BuilderContentContext = new BuilderContentContext();
private _templateRef: TemplateRef<BuilderContentContext> | null = null;
private _viewRef: EmbeddedViewRef<BuilderContentContext> | null = null;
// private _repeat = false;
private match: any;
private matchId = '';
private clickTracked = false;
hydrated = false;
constructor(
private _viewContainer: ViewContainerRef,
private renderer: Renderer2,
private builder: BuilderService,
private builderComponentService: BuilderComponentService,
@Optional() private transferState: TransferState,
templateRef: TemplateRef<BuilderContentContext>,
@Optional() private router?: Router
) {
builderComponentService.contentDirectiveInstance = this;
this._templateRef = templateRef;
}
// TODO: pass this option down from builder-component
@Input() reloadOnRoute = true;
contentSubscription: BuilderSubscription | null = null;
stateKey: StateKey<any> | undefined;
requesting = true;
reset() {
// TODO: listen to any target change? This just updates target?
// TODO: track last fetched ID and don't replace dom if on new url the content is the same...
this.clickTracked = false;
this.hydrated = false;
// Verify the route didn't result in this component being destroyed
this.request();
}
ngOnInit() {
Builder.nextTick(() => {
this.request();
});
if (this.router) {
this.subscriptions.add(
this.router.events.subscribe((event) => {
// TODO: this doesn't trigger
if (event instanceof NavigationEnd) {
if (this.reloadOnRoute) {
const viewRef = this._viewRef;
if (viewRef && viewRef.destroyed) {
return;
}
if (this.url !== this.lastUrl) {
this.reset();
}
}
}
})
);
}
}
ngOnDestroy() {
this.subscriptions.unsubscribe();
if (this.contentSubscription) {
this.contentSubscription.unsubscribe();
}
}
// TODO: have another option for this or get from metadata
// @Input()
// set modelMultiple(repeat: boolean) {
// this._repeat = repeat;
// }
// @HostListener('click')
onClick(event: MouseEvent) {
if (this.matchId && !this.hydrated) {
const match = this.match;
if (this.builder.autoTrack) {
this.builder.trackInteraction(
this.matchId,
match && match.variationId,
this.clickTracked,
event,
{ content: match }
);
}
this.clickTracked = true;
}
// TODO: only in editor mode
// TODO: put messaging on builder class
if (document.body.classList.contains('builder-editing')) {
if (this.matchId) {
// TODO: get event object and pass mouse coordinages
window.parent.postMessage(
{
type: 'builder.clickContent',
data: {
id: this.matchId,
model: this._context.model,
},
},
'*'
);
} else {
window.parent.postMessage(
{
type: 'builder.clickModel',
data: {
model: this._context.model,
},
},
'*'
);
}
}
}
get stateKeyString() {
return 'builder:' + this._context.model + ':' + (this.reloadOnRoute ? this.url : '');
}
// TODO: limit?
// TODO: context with index, etc
@Input()
set builderModel(model: string) {
if (!model) {
return;
}
this._context.model = model;
this._updateView();
this.stateKey = makeStateKey(this.stateKeyString);
// this.request();
const rootNode = this._viewRef!.rootNodes[0];
this.renderer.setAttribute(rootNode, 'builder-model', model);
this.renderer.setAttribute(rootNode, 'builder-model-name', model.replace(/-/g, ' '));
this.renderer.listen(rootNode, 'click', (event: MouseEvent) => this.onClick(event));
}
private get url() {
const location = this.builder.getLocation();
return location.pathname || ''; // + (location.search || '');
}
// TODO: service for this
request() {
this.lastUrl = this.url;
this.requesting = true;
if (this.component && !this.component.prerender) {
return;
}
const viewRef = this._viewRef;
if (viewRef && viewRef.destroyed) {
return;
}
let receivedFirstResponse = false;
const model = this._context.model as string;
const options = this.component && this.component.options;
const initialContent =
(this.component && this.component.content) ||
(Builder.isBrowser &&
// firstEverLoad &&
this.transferState &&
this.transferState.get(this.stateKeyString as any, null as any));
// firstEverLoad = false;
// TODO: if not multipe
if (this.contentSubscription) {
// TODO: cancel a request if one is pending... or set some kind of flag
this.contentSubscription.unsubscribe();
}
const hydrate = Builder.isBrowser && this.component && this.component.hydrate;
const key = Builder.isEditing || !this.reloadOnRoute ? model : `${model}:${this.url}`;
const subscription = (this.contentSubscription = this.builder
.queueGetContent(model, {
initialContent,
key,
...options,
prerender: true,
static: !hydrate,
})
.subscribe(
(result: any[]) => {
let match = result[0];
// Cancel handling request if new one created or they have been canceled, to avoid race conditions
// if multiple routes or other events happen
if (this.contentSubscription !== subscription) {
if (!receivedFirstResponse) {
}
return;
}
if (match && match.id === this.lastContentId) {
return;
}
this.lastContentId = match && match.id;
if (this.transferState && !Builder.isBrowser) {
this.transferState.set(this.stateKeyString as any, result);
}
// tslint:disable-next-line:no-non-null-assertion
const viewRef = this._viewRef!;
if (viewRef.destroyed) {
this.subscriptions.unsubscribe();
if (this.contentSubscription) {
this.contentSubscription.unsubscribe();
}
return;
}
const rootNode = Builder.isBrowser && viewRef.rootNodes[0];
if (Builder.isBrowser) {
if (rootNode) {
if (rootNode && rootNode.classList.contains('builder-editor-injected')) {
viewRef.detach();
return;
}
}
}
// FIXME: nasty hack to detect secondary updates vs original. Build proper support into JS SDK
// if (this._context.loading || result.length > viewRef.context.results.length) {
this._context.loading = false;
const search = this.builder.getLocation().search || '';
// TODO: how handle singleton vs multiple
if (!match && search.includes('builder.preview=' + this._context.model)) {
match = {
id: 'preview',
name: 'Preview',
data: {},
};
}
if (this.component) {
this.component.contentLoad.next(match);
} else {
console.warn('No component!');
}
if (match) {
const rootNode = this._viewRef!.rootNodes[0];
this.matchId = match.id;
this.renderer.setAttribute(rootNode, 'builder-content-entry-id', match.id);
this.match = match;
viewRef.context.$implicit = match.data;
// viewRef.context.results = result.map(item => ({ ...item.data, $id: item.id }));
if (!hydrate && this.builder.autoTrack) {
this.builder.trackImpression(match.id, match.variationId, undefined, {
content: match,
});
}
}
if (!viewRef.destroyed) {
viewRef.detectChanges();
if (
this.builderComponentService.contentComponentInstance &&
this.builderComponentService.contentComponentInstance.prerender &&
Builder.isBrowser &&
Builder.isStatic
) {
Builder.nextTick(() => {
if (this.builderComponentService.contentComponentInstance) {
this.builderComponentService.contentComponentInstance.findAndRunScripts();
}
});
}
// TODO: it's possible we don't want anything below to run if this has been destroyed
if (match && match.data && match.data.animations && Builder.isBrowser && !hydrate) {
Builder.nextTick(() => {
Builder.animator.bindAnimations(match.data.animations);
});
}
}
if (!receivedFirstResponse) {
receivedFirstResponse = true;
}
},
(error) => {
if (this.component) {
this.component.contentError.next(error);
} else {
console.warn('No component!');
}
if (!receivedFirstResponse) {
// TODO: how to zone error
receivedFirstResponse = true;
}
}
));
}
private _updateView() {
if (this._context.model) {
this._viewContainer.clear();
if (this._templateRef) {
this._viewRef = this._viewContainer.createEmbeddedView(this._templateRef, this._context);
}
}
}
}
export class BuilderContentContext {
$implicit?: any;
match?: any;
model?: string;
loading = true;
results: any[] = [];
} | the_stack |
import { FsUtils } from '../io/fs.utils';
import { ConsoleColors } from '../logs/log.colors';
import { Asserter } from './test.asserter';
import {
ITestService, ITestServiceArgs, ITestMethod, ITestMethodArgs, ITestStats,
TestTypeDetector, TTestServiceItFunc, TTestMethodItFunc
} from './test.shared';
import { isAbsolute, join } from 'path';
import { Configuration } from '../configuration/configuration.interfaces';
import { ConfigurationLoader } from '../configuration/configuration.loader';
import { Container } from '../dependecy-injection/di.container';
import { defaultProjectConfiguration } from '../configuration/configuration.default';
import { ProjectConfigurationService } from '../configuration/configuration.service';
import { ObjectValidator } from '../object-validator/object-validator.service';
import { ClassParameter } from '../utils/typescript.utils';
export class TestManager {
// Contains all the registered test classes anotated with @TestService
private static testClasses: ITestService[] = [];
// Contains a temporal version for the methods until the antation from class executes
private static tmpMethods: { [key: string /* Class name */]: ITestMethod[] } = {};
private static tmpBeforeMethods: { [key: string /* Class name */]: ITestMethod[] } = {};
private static tmpAfterMethods: { [key: string /* Class name */]: ITestMethod[] } = {};
// Keeps a register of the result of all the executed tests
private static executionStats: ITestStats[] = [];
private static initialExecutionTime = 0;
//
// Public CLI methods
//
public static async executeTests(testFolder: string, argConfigFolder?: string) {
// 1: Force an execution on all decorators from the test folder
this.initialExecutionTime = Date.now();
// 2: Load project configuration
process.env.NODE_ENV = 'test';
let configuration: Configuration;
let configurationFolder: string;
if (argConfigFolder) {
configurationFolder = isAbsolute(argConfigFolder) ? argConfigFolder : join(process.cwd(), argConfigFolder);
configuration = await ConfigurationLoader.loadProject(configurationFolder);
} else {
configurationFolder = __dirname;
configuration = <any>defaultProjectConfiguration;
}
const objectValidator = await Container.get(ObjectValidator);
const configurationService = new ProjectConfigurationService(configuration, objectValidator, configurationFolder);
Container.set(ProjectConfigurationService, configurationService);
// 3: Load all the classes inside the test folder
await this.loadTests(testFolder);
// 4: Print test classes and methods
await this.printTestsStart(false);
this.printTestsExec();
// 5: Check if there are some tests we are focusing on in this executions
const testOnlyClasses = this.testClasses
.filter(tc => tc.testThisOnly || tc.testMethods.findIndex(m => m.testThisOnly === true) >= 0)
.map(tc => tc.name);
// 6: Execute all tests at the same time
await Promise.all(
this.testClasses.map(tc => this.executeTestService(tc, testOnlyClasses))
);
// 7: Print stats
this.printTestsEnd();
}
public static async showTestsInfo(testFolder: string) {
// 1: Force an execution on all decorators from the test folder
await this.loadTests(testFolder);
// 2: Iterate secuentally over all classes and methods
await this.printTestsStart(true);
}
//
// Public Decorator methods
//
public static registerTestService(clazz: ClassParameter<any>, decoratorArgs: ITestServiceArgs) {
this.testClasses.push({
clazz,
name: clazz.name,
testMethods: this.tmpMethods[clazz.name] || [],
beforeTestMethods: this.tmpBeforeMethods[clazz.name],
afterTestMethods: this.tmpAfterMethods[clazz.name],
testThisOnly: decoratorArgs.testThisOnly
});
}
public static registerTestMethod(testClass: string, methodName: string, methodFunc: (...args: any) => any, decoratorArgs: ITestMethodArgs) {
this.tmpMethods[testClass] = (this.tmpMethods[testClass] || []).concat(<ITestMethod>{
methodName,
methodFunc,
testThisOnly: decoratorArgs.testThisOnly
});
}
public static registerBeforeTestMethod(testClass: string, methodName: string, methodFunc: (...args: any) => any) {
this.tmpBeforeMethods[testClass] = (this.tmpBeforeMethods[testClass] || []).concat(<ITestMethod>{
methodName, methodFunc
});
}
public static registerAfterTestMethod(testClass: string, methodName: string, methodFunc: (...args: any) => any) {
this.tmpAfterMethods[testClass] = (this.tmpAfterMethods[testClass] || []).concat(<ITestMethod>{
methodName, methodFunc
});
}
//
// Public Assert error methods
//
public static assertErrorOnTest(testClass: string, testMethod: string) {
const testClassStat = this.getTestServiceStat(testClass);
const testClassMethod = this.getTestMethodStat(testClassStat, testMethod);
testClassMethod.errorAsserts++;
}
public static assertSuccessOnTest(testClass: string, testMethod: string) {
const testClassStat = this.getTestServiceStat(testClass);
const testClassMethod = this.getTestMethodStat(testClassStat, testMethod);
testClassMethod.successAsserts++;
}
public static unexpectedAssertErrorOnTestMethod(testClass: string, testMethod: string) {
const testClassStat = this.getTestServiceStat(testClass);
const testClassMethod = this.getTestMethodStat(testClassStat, testMethod);
testClassMethod.unexpectedError = true;
}
public static unexpectedAssertErrorOnTestService(testClass: string) {
const testClassStat = this.getTestServiceStat(testClass);
testClassStat.unexpectedError = true;
}
public static finishedTestMethod(testClass: string, testMethod: string) {
const testClassStat = this.getTestServiceStat(testClass);
const testClassMethod = this.getTestMethodStat(testClassStat, testMethod);
testClassMethod.success = testClassMethod.errorAsserts === 0 && !testClassStat.unexpectedError;
}
public static finishedTestService(testClass: string) {
const testClassStat = this.getTestServiceStat(testClass);
const testMethodsWithErrors = testClassStat.methods.filter(tm => tm.errorAsserts > 0);
testClassStat.success = testMethodsWithErrors.length === 0 && !testClassStat.unexpectedError;
console.log((testClassStat.success ? ConsoleColors.fgGreen : ConsoleColors.fgRed) +
`* ${testClass} * ` + (testClassStat.success ? '(ok)' : '(Error)'), ConsoleColors.reset);
}
//
// Private methods
//
private static async loadTests(testFolder: string) {
return FsUtils.loadJsFolder(testFolder, true);
}
private static async iterateOverTests(classFunc: TTestServiceItFunc, methodFunc: TTestMethodItFunc, showAll: boolean) {
const anyHasFocus = this.testClasses.find(testClass => testClass.testThisOnly ||
testClass.testMethods.find(tm => tm.testThisOnly)) !== undefined;
for (const testClass of this.testClasses) {
const anyChildHasTestOnly = testClass.testMethods.find(tm => tm.testThisOnly) !== undefined;
const noChildHasNotTestOnly = testClass.testMethods.every(tm => !tm.testThisOnly);
if (showAll || !anyHasFocus || (testClass.testThisOnly || anyChildHasTestOnly)) {
await classFunc(testClass);
for (const testMethod of testClass.testMethods) {
if (showAll || !anyHasFocus || (testMethod.testThisOnly || noChildHasNotTestOnly)) {
await methodFunc(testMethod, testClass);
}
}
}
}
}
//
// Private print methods
//
private static async logTestService(clazz: ITestService) {
console.log(`${ConsoleColors.fgYellow}${clazz.name}${clazz.testThisOnly ? ' (Focused test)' : ''}`, ConsoleColors.reset);
}
private static async logTestMethod(method: ITestMethod) {
console.log(`${ConsoleColors.fgCyan}- ${method.methodName}${method.testThisOnly ? ' (Focused test)' : ''}`, ConsoleColors.reset);
}
private static async printTestsStart(showAll: boolean) {
console.log('-------------------------------------------------');
console.log('-- Registered tests');
console.log('-------------------------------------------------\n');
await this.iterateOverTests(this.logTestService, this.logTestMethod, showAll);
console.log('');
}
private static printTestsExec() {
console.log('-------------------------------------------------');
console.log('-- Tests execution');
console.log('-------------------------------------------------\n');
}
private static printTestsEnd() {
console.log('\n-------------------------------------------------');
console.log('-- Tests results');
console.log('-------------------------------------------------\n');
// Stats for executed classes
let successTests = 0;
let errorTests = 0;
for (const classStat of this.executionStats) {
// Class stat log
const numOfTests = classStat.methods.length;
const numOfTestsWithErrors = classStat.methods.filter(m => !m.success).length;
const classPrefix = (numOfTestsWithErrors === 0) ? ConsoleColors.fgGreen :
numOfTestsWithErrors < numOfTests ? ConsoleColors.fgYellow :
ConsoleColors.fgRed;
const successMethods = numOfTests - numOfTestsWithErrors;
console.log(
`${classPrefix}${classStat.className}: ` +
`( ${successMethods} successful tests ) and ( ${numOfTestsWithErrors} test with errors )`,
ConsoleColors.reset
);
successTests = successTests + successMethods;
errorTests = errorTests + numOfTestsWithErrors;
for (const methodStat of classStat.methods) {
// Method stat log
const methodPrefix = (methodStat.errorAsserts === 0) ? ConsoleColors.fgGreen :
(methodStat.errorAsserts > 0 && methodStat.successAsserts > 0) ? ConsoleColors.fgYellow :
ConsoleColors.fgRed;
console.log(
`${methodPrefix}- ${methodStat.methodName}: ` +
`( ${methodStat.successAsserts} successful assertions ) and ( ${methodStat.errorAsserts} assertions with errors )`,
ConsoleColors.reset
);
}
}
// Final stats
console.log('\n--- Final results ---');
console.log(`Execution time: ${Date.now() - this.initialExecutionTime} ms`);
console.log(
`Tests with errors: ${errorTests === 0 ? ConsoleColors.fgGreen : ConsoleColors.fgRed}${errorTests}`,
ConsoleColors.reset
);
console.log(
`Successful tests: ${errorTests === 0 ? ConsoleColors.fgGreen : ConsoleColors.fgYellow}${successTests}`,
ConsoleColors.reset
);
console.log(
`Tests result: ${errorTests === 0 ? ConsoleColors.fgGreen : ConsoleColors.fgRed}` +
(errorTests === 0 ? 'Success' : 'Error'),
ConsoleColors.reset
);
console.log('---------------------');
return errorTests === 0;
}
//
// Private test execution methods
//
private static async executeTestService(testClass: ITestService, testOnlyClasses: string[]) {
// Test this class only if there is no focus in any other test o this class is being focused
if (testOnlyClasses.length === 0 || testOnlyClasses.includes(testClass.name)) {
const promises: Promise<boolean>[] = [];
// TODO check how to remove this any
const asserter = new Asserter(testClass);
const testObj = await Container.get(testClass.clazz);
testObj.assert = asserter;
// Check if there is a before tests func
if (testClass.beforeTestMethods) {
try {
await Promise.all(testClass.beforeTestMethods.map(btm => testObj[btm.methodName]()));
} catch (error: any) {
console.log(`${ConsoleColors.fgRed}Unexpected error while executing beforeTest functions`, ConsoleColors.reset);
console.log(`${ConsoleColors.fgRed}${error.stack || (new Error()).stack}`, ConsoleColors.reset);
}
}
// Test only focused methods or all of them if there is no focus
const testOnlyMethods = testClass.testMethods.filter(m => m.testThisOnly);
if (testOnlyMethods.length === 0) {
promises.push(
...testClass.testMethods.map(m => this.executeTestMethod(m, testObj, testClass))
);
} else {
promises.push(
...testOnlyMethods.map(m => this.executeTestMethod(m, testObj, testClass))
);
}
// Wait for all methods to execute
await Promise.all(promises);
// Calc stadistics
this.finishedTestService(testClass.name);
// Check if there is a after tests func
if (testClass.afterTestMethods) {
try {
await Promise.all(testClass.afterTestMethods.map(btm => testObj[btm.methodName]()));
} catch (error: any) {
console.log(`${ConsoleColors.fgRed}Unexpected error while executing afterTest functions`, ConsoleColors.reset);
console.log(`${ConsoleColors.fgRed}${error.stack || (new Error()).stack}`, ConsoleColors.reset);
}
}
}
}
private static async executeTestMethod(method: ITestMethod, testObj: any, clazz: ITestService): Promise<boolean> {
try {
await testObj[method.methodName]();
this.finishedTestMethod(clazz.name, method.methodName);
return true;
} catch (error: any) {
if (!TestTypeDetector.isTestMethodErrorToIgnore(error)) {
this.unexpectedAssertErrorOnTestMethod(clazz.name, method.methodName);
console.log(`${ConsoleColors.fgMagenta}An error ocureed while executing the test: ${clazz.name} - ${method.methodName}`);
console.log(`${ConsoleColors.fgRed}${error.stack || (new Error()).stack}`, ConsoleColors.reset);
}
return false;
}
}
//
// Private assert methods
//
private static getTestServiceStat(testClass: string) {
let testClassStats = this.executionStats.find(tc => tc.className === testClass);
if (testClassStats) {
return testClassStats;
} else {
testClassStats = {
className: testClass,
success: false,
unexpectedError: false,
methods: []
};
this.executionStats.push(testClassStats);
return testClassStats;
}
}
private static getTestMethodStat(testClassStat: ITestStats, testMethod: string) {
let testMethodStats = testClassStat.methods.find(tm => tm.methodName === testMethod);
if (testMethodStats) {
return testMethodStats;
} else {
testMethodStats = {
methodName: testMethod,
success: false,
unexpectedError: false,
errorAsserts: 0,
successAsserts: 0
};
testClassStat.methods.push(testMethodStats);
return testMethodStats;
}
}
} | the_stack |
import { Body, Bodies, Composite, Constraint, Vector, Vertices, World, IBodyDefinition } from 'matter-js';
import { Part } from './part';
import { PartType, PartFactory } from './factory';
import { getVertexSets } from './partvertices';
import { SPACING, PART_SIZE, UNRELEASED_BALL_MASK, UNRELEASED_BALL_CATEGORY, PART_CATEGORY,
PART_MASK, DAMPER_RADIUS, BALL_DENSITY,
COUNTERWEIGHT_STIFFNESS, COUNTERWEIGHT_DAMPING, BIAS_STIFFNESS,
BIAS_DAMPING, PART_DENSITY, BALL_FRICTION, PART_FRICTION,
BALL_FRICTION_STATIC, PART_FRICTION_STATIC, IDEAL_VX, NUDGE_ACCEL,
MAX_V, DROP_FRICTION, DROP_FRICTION_STATIC, BALL_MASK, GATE_CATEGORY,
GATE_MASK, BALL_CATEGORY, BIT_BIAS_STIFFNESS, BALL_RADIUS } from 'board/constants';
import { PartBallContact } from 'board/physics';
import { Ball } from './ball';
import { Slope } from './fence';
import { Drop } from './drop';
import { Turnstile } from './turnstile';
// this composes a part with a matter.js body which simulates it
export class PartBody {
constructor(part:Part) {
this.type = part.type;
this.part = part;
}
public readonly type:PartType;
public get part():Part { return(this._part); }
public set part(part:Part) {
if (part === this._part) return;
if (part) {
if (part.type !== this.type) throw('Part type must match PartBody type');
this._partChangeCounter = NaN;
this._part = part;
this.initBodyFromPart();
}
}
private _part:Part;
// a body representing the physical form of the part
public get body():Body {
// if there are no stored vertices, the body will be set to null,
// and we shouldn't keep trying to construct it
if (this._body === undefined) this._makeBody();
return(this._body);
};
private _makeBody():void {
this._body = null;
// construct the ball as a circle
if (this.type == PartType.BALL) {
this._body = Bodies.circle(0, 0, BALL_RADIUS,
{ density: BALL_DENSITY, friction: BALL_FRICTION,
frictionStatic: BALL_FRICTION_STATIC,
collisionFilter: { category: UNRELEASED_BALL_CATEGORY, mask: UNRELEASED_BALL_MASK, group: 0 } });
}
// construct fences based on their configuration params
else if (this._part instanceof Slope) {
this._body = this._bodyForSlope(this._part);
this._slopeSignature = this._part.signature;
}
// construct other parts from stored vertices
else {
const constructor = PartFactory.constructorForType(this.type);
this._body = this._bodyFromVertexSets(getVertexSets(constructor.name));
}
if (this._body) {
Body.setPosition(this._body, { x: 0.0, y: 0.0 });
Composite.add(this._composite, this._body);
}
this.initBodyFromPart();
}
private _refreshBody():void {
this._clearBody();
this._makeBody();
}
protected _body:Body = undefined;
// the fence parameters last time we constructed a fence
private _slopeSignature:number = NaN;
// a composite representing the body and related constraints, etc.
public get composite():Composite { return(this._composite); }
private _composite:Composite = Composite.create();
// initialize the body after creation
protected initBodyFromPart():void {
if ((! this._body) || (! this._part)) return;
// parts that can't rotate can be static
if ((! this._part.bodyCanRotate) && (! this._part.bodyCanMove)) {
Body.setStatic(this._body, true);
}
else {
Body.setStatic(this._body, false);
}
// add bodies and constraints to control rotation
if (this._part.bodyCanRotate) {
this._makeRotationConstraints();
}
// set restitution
this._body.restitution = this._part.bodyRestitution;
// do special configuration for ball drops
if (this._part.type == PartType.DROP) {
this._makeDropGate();
}
// perform a first update of properties from the part
this.updateBodyFromPart();
}
protected _makeRotationConstraints():void {
// make constraints that bias parts and keep them from bouncing at the
// ends of their range
if (this._part.isCounterWeighted) {
this._counterweightDamper = this._makeDamper(this._part.isFlipped, true,
COUNTERWEIGHT_STIFFNESS, COUNTERWEIGHT_DAMPING);
}
else if (this._part.biasRotation) {
this._biasDamper = this._makeDamper(false, false,
this._part.type == PartType.BIT ? BIT_BIAS_STIFFNESS : BIAS_STIFFNESS,
BIAS_DAMPING);
}
}
private _makeDamper(flipped:boolean, counterweighted:boolean,
stiffness:number, damping:number):Constraint {
const constraint = Constraint.create({
bodyA: this._body,
pointA: this._damperAttachmentVector(flipped),
pointB: this._damperAnchorVector(flipped, counterweighted),
stiffness: stiffness,
damping: damping
});
Composite.add(this._composite, constraint);
return(constraint);
}
private _damperAttachmentVector(flipped:boolean):Vector {
return({ x: flipped ? DAMPER_RADIUS : - DAMPER_RADIUS,
y: - DAMPER_RADIUS });
}
private _damperAnchorVector(flipped:boolean, counterweighted:boolean):Vector {
return(counterweighted ?
{ x: (flipped ? DAMPER_RADIUS : - DAMPER_RADIUS), y: 0 } :
{ x: 0, y: DAMPER_RADIUS });
}
private _makeDropGate():void {
this._body.friction = DROP_FRICTION;
this._body.friction = DROP_FRICTION_STATIC;
const sign = this._part.isFlipped ? -1 : 1;
this._dropGate = Bodies.rectangle(
(SPACING / 2) * sign, 0, PART_SIZE / 16, SPACING,
{ friction: DROP_FRICTION, frictionStatic: DROP_FRICTION_STATIC,
collisionFilter: { category: GATE_CATEGORY, mask: GATE_MASK, group: 0 },
isStatic: true });
Composite.add(this._composite, this._dropGate);
}
// remove all constraints and bodies we've added to the composite
private _clearBody():void {
const clear = (item:Body|Constraint):undefined => {
if (item) Composite.remove(this._composite, item);
return(undefined);
};
this._counterweightDamper = clear(this._counterweightDamper);
this._biasDamper = clear(this._biasDamper);
this._dropGate = clear(this._dropGate);
this._body = clear(this._body);
this._compositePosition.x = this._compositePosition.y = 0;
}
private _counterweightDamper:Constraint;
private _biasDamper:Constraint;
private _dropGate:Body;
// transfer relevant properties to the body
public updateBodyFromPart():void {
// skip the update if we have no part
if ((! this._body) || (! this._part)) return;
// update collision masks for balls
if (this._part instanceof Ball) {
this._body.collisionFilter.category = this._part.released ?
BALL_CATEGORY : UNRELEASED_BALL_CATEGORY;
this._body.collisionFilter.mask = this._part.released ?
BALL_MASK : UNRELEASED_BALL_MASK;
}
// skip the rest of the update if the part hasn't changed
if (this._part.changeCounter === this._partChangeCounter) return;
// rebuild the body if the slope signature changes
if ((this._part instanceof Slope) &&
(this._part.signature != this._slopeSignature)) {
this._refreshBody();
return;
}
// update mirroring
if (this._bodyFlipped !== this._part.isFlipped) {
this._refreshBody();
return;
}
// update position
const position = { x: (this._part.column * SPACING) + this._bodyOffset.x,
y: (this._part.row * SPACING) + this._bodyOffset.y };
const positionDelta = Vector.sub(position, this._compositePosition);
Composite.translate(this._composite, positionDelta, true);
this._compositePosition = position;
Body.setVelocity(this._body, { x: 0, y: 0 });
// move damper anchor points
if (this._counterweightDamper) {
Vector.add(this._body.position,
this._damperAnchorVector(this._part.isFlipped, true),
this._counterweightDamper.pointB);
}
if (this._biasDamper) {
Vector.add(this._body.position,
this._damperAnchorVector(this._part.isFlipped, false),
this._biasDamper.pointB);
}
Body.setAngle(this._body, this._part.angleForRotation(this._part.rotation));
// record that we've synced with the part
this._partChangeCounter = this._part.changeCounter;
}
protected _compositePosition:Vector = { x: 0.0, y: 0.0 };
protected _bodyOffset:Vector = { x: 0.0, y: 0.0 };
private _bodyFlipped:boolean = false;
private _partChangeCounter:number = NaN;
// tranfer relevant properties from the body
public updatePartFromBody():void {
if ((! this._body) || (! this._part) || (this._body.isStatic)) return;
if (this._part.bodyCanMove) {
this._part.column = this._body.position.x / SPACING;
this._part.row = this._body.position.y / SPACING;
}
if (this._part.bodyCanRotate) {
const r:number = this._part.rotationForAngle(this._body.angle);
this._part.rotation = r;
}
// record that we've synced with the part
this._partChangeCounter = this._part.changeCounter;
}
// add the body to the given world, creating the body if needed
public addToWorld(world:World):void {
const body = this.body;
if (body) {
World.add(world, this._composite);
// try to release any stored energy in the part
Body.setVelocity(this._body, { x: 0, y: 0 });
Body.setAngularVelocity(this._body, 0);
}
}
// remove the body from the given world
public removeFromWorld(world:World):void {
World.remove(world, this._composite);
}
// construct a body for the current fence configuration
protected _bodyForSlope(slope:Slope):Body {
const name:string = 'Slope-'+slope.modulus;
const y:number = - ((slope.sequence % slope.modulus) / slope.modulus) * SPACING;
return(this._bodyFromVertexSets(getVertexSets(name), 0, y));
}
// construct a body from a set of vertex lists
protected _bodyFromVertexSets(vertexSets:Vector[][],
x:number=0, y:number=0):Body {
if (! vertexSets) return(null);
const parts:Body[] = [ ];
this._bodyFlipped = this._part.isFlipped;
for (const vertices of vertexSets) {
// flip the vertices if the part is flipped
if (this._part.isFlipped) {
Vertices.scale(vertices, -1, 1, { x: 0, y: 0 });
}
// make sure they're in clockwise order, because flipping reverses
// their direction and we can't be sure how the source SVG is drawn
Vertices.clockwiseSort(vertices);
const center = Vertices.centre(vertices);
parts.push(Body.create({ position: center, vertices: vertices }));
}
const body = Body.create({ parts: parts,
friction: PART_FRICTION, frictionStatic: PART_FRICTION_STATIC,
density: PART_DENSITY,
collisionFilter: { category: PART_CATEGORY, mask: PART_MASK, group: 0 } });
// this is a hack to prevent matter.js from placing the body's center
// of mass over the origin, which complicates our ability to precisely
// position parts of an arbitrary shape
body.position.x = x;
body.position.y = y;
(body as any).positionPrev.x = x;
(body as any).positionPrev.y = y;
return(body);
}
// PHYSICS ENGINE CHEATS ****************************************************
// apply corrections to the body and any balls contacting it
public cheat(contacts:Set<PartBallContact>, nearby:Set<PartBody>):void {
if ((! this._body) || (! this._part)) return;
this._controlRotation(contacts, nearby);
this._controlVelocity();
this._nudge(contacts, nearby);
if (nearby) {
for (const ballPartBody of nearby) {
this._influenceBall(ballPartBody);
}
}
}
private _nudge(contacts:Set<PartBallContact>, nearby:Set<PartBody>):void {
if (! contacts) return;
// don't nudge multiple balls on slopes,
// it tends to cause pileups in the output
if ((this._part.type === PartType.SLOPE) && (contacts.size > 1)) return;
for (const contact of contacts) {
const nudged = this._nudgeBall(contact);
// if we've nudged a ball, don't do other stuff to it
if ((nudged) && (nearby)) nearby.delete(contact.ballPartBody);
}
}
// constrain the position and angle of the part to simulate
// an angle-constrained revolute joint
private _controlRotation(contacts:Set<PartBallContact>, nearby:Set<PartBody>):void {
const positionDelta:Vector = { x: 0, y: 0 };
let angleDelta:number = 0;
let moved:boolean = false;
if (! this._part.bodyCanMove) {
Vector.sub(this._compositePosition, this._body.position, positionDelta);
Body.translate(this._body, positionDelta);
Body.setVelocity(this._body, { x: 0, y: 0 });
moved = true;
}
if (this._part.bodyCanRotate) {
const r:number = this._part.rotationForAngle(this._body.angle);
let target:number =
this._part.angleForRotation(Math.min(Math.max(0.0, r), 1.0));
let lock:boolean = false;
if (this._part instanceof Turnstile) {
// turnstiles can only rotate in one direction
if (((! this._part.isFlipped) && (this._body.angularVelocity < 0)) ||
((this._part.isFlipped) && (this._body.angularVelocity > 0))) {
Body.setAngularVelocity(this._body, 0);
}
// engage and disengage based on ball contact
const engaged = ((nearby instanceof Set) && (nearby.size > 0));
if (! engaged) {
target = this._part.angleForRotation(0);
lock = true;
}
else if (r >= 1.0) lock = true;
}
else if ((r < 0) || (r > 1)) lock = true;
if (lock) {
angleDelta = target - this._body.angle;
Body.rotate(this._body, angleDelta);
Body.setAngularVelocity(this._body, 0);
}
moved = true;
}
// apply the same movements to balls if there are any, otherwise they
// will squash into the part
if ((moved) && (contacts)) {
const combined = Vector.rotate(positionDelta, angleDelta);
for (const contact of contacts) {
Body.translate(contact.ballPartBody.body, combined);
}
}
}
// apply a limit to how fast a part can move, mainly to prevent fall-through
// and conditions resulting from too much kinetic energy
private _controlVelocity():void {
if ((! this._body) || (! this._part) || (! this._part.bodyCanMove)) return;
if (Vector.magnitude(this._body.velocity) > MAX_V) {
const v = Vector.mult(Vector.normalise(this._body.velocity), MAX_V);
Body.setVelocity(this._body, v);
}
}
// apply a speed limit to the given ball
private _nudgeBall(contact:PartBallContact):boolean {
if ((! this._body) || (! contact.ballPartBody.body)) return(false);
const ball = contact.ballPartBody.part as Ball;
const body = contact.ballPartBody.body;
let tangent = Vector.clone(contact.tangent);
// only nudge the ball if it's touching a horizontal-ish surface
let maxSlope:number = 0.3;
// get the horizontal direction and relative magnitude we want the ball
// to be going in
let mag:number = 1;
let sign:number = 0;
// ramps direct in a single direction
if (this._part.type == PartType.RAMP) {
if ((this._part.rotation < 0.25) && (ball.row < this._part.row)) {
sign = this._part.isFlipped ? -1 : 1;
}
if (body.velocity.y < 0) {
Body.setVelocity(body, { x: body.velocity.x, y: 0 });
}
}
// gearbits are basically like switchable ramps
else if (this._part.type == PartType.GEARBIT) {
if (this._part.rotation < 0.25) sign = 1;
else if (this._part.rotation > 0.75) sign = -1;
}
// bits direct the ball according to their state, but the direction is
// opposite for the top and bottom halves
else if (this._part.type == PartType.BIT) {
const bottomHalf:boolean = ball.row > this._part.row;
if (this._part.rotation >= 0.9) sign = bottomHalf ? 1 : -1;
else if (this._part.rotation <= 0.1) sign = bottomHalf ? -1 : 1;
if (! bottomHalf) mag = 0.5;
}
// crossovers direct the ball in the same direction it has been going
else if (this._part.type == PartType.CROSSOVER) {
if (ball.lastDistinctColumn < ball.lastColumn) sign = 1;
else if (ball.lastDistinctColumn > ball.lastColumn) sign = -1;
else if (ball.row < this._part.row) { // top half
sign = ball.column < this._part.column ? 1 : -1;
// remember this for when we get to the bottom
ball.lastDistinctColumn -= sign;
}
else { // bottom half
sign = ball.column < this._part.column ? -1 : 1;
}
if (ball.row < this._part.row) mag *= 16;
}
// slopes always nudge, and the ball can move fast because
// interactions are simple
else if (this._part instanceof Slope) {
mag = 2;
sign = this._part.isFlipped ? -1 : 1;
// the tangent is always the same for slopes, and setting it explicitly
// prevents strange effect at corners
tangent = Vector.normalise({ x: this._part.modulus * sign, y: 1 });
maxSlope = 1;
}
// the ball drop only nudges balls it's dropping
else if ((this._part instanceof Drop) && (ball.released)) {
sign = this._part.isFlipped ? -1 : 1;
}
// exit if we're not nudging
if (sign == 0) return(false);
// limit slope
const slope = Math.abs(tangent.y) / Math.abs(tangent.x);
if (slope > maxSlope) return(false);
// flip the tangent if the direction doesn't match the target direction
if (((sign < 0) && (tangent.x > 0)) ||
((sign > 0) && (tangent.x < 0))) tangent = Vector.mult(tangent, -1);
// see how much and in which direction we need to correct the horizontal velocity
const target = IDEAL_VX * sign * mag;
const current = body.velocity.x;
let accel:number = 0;
if (sign > 0) {
if (current < target) accel = NUDGE_ACCEL; // too slow => right
else if (current > target) accel = - NUDGE_ACCEL; // too fast => right
}
else {
if (target < current) accel = NUDGE_ACCEL; // too slow <= left
else if (target > current) accel = - NUDGE_ACCEL; // too fast <= left
}
if (accel == 0) return(false);
// scale the acceleration by the difference
// if it gets close to prevent flip-flopping
accel *= Math.min(Math.abs(current - target) * 4, 1.0);
// accelerate the ball in the desired direction
Body.applyForce(body, body.position,
Vector.mult(tangent, accel * body.mass));
// return that we've nudged the ball
return(true);
}
// apply trajectory influences to balls in the vicinity
private _influenceBall(ballPartBody:PartBody):boolean {
const ball = ballPartBody.part as Ball;
const body = ballPartBody.body;
// crossovers are complicated!
if (this._part.type == PartType.CROSSOVER) {
const currentSign:number = body.velocity.x > 0 ? 1 : -1;
// make trajectories in the upper half of the crossover more diagonal,
// which ensures they have enough horizontal energy to make it through
// the bottom half without the "conveyer belt" nudge being obvious
if ((ball.row < this._part.row) && (body.velocity.x > 0.001)) {
if (Math.abs(body.velocity.x) < Math.abs(body.velocity.y)) {
Body.applyForce(body, body.position,
{ x: currentSign * NUDGE_ACCEL * body.mass, y: 0});
return(true);
}
}
// if the ball somehow happens to be going the wrong way in the
// bottom half, as it sometimes does, we need to intervene and fix it
// even if that looks unnatural
else if (ball.row > this._part.row) {
let desiredSign:number = 0;
if (ball.lastDistinctColumn < ball.lastColumn) desiredSign = 1;
else if (ball.lastDistinctColumn > ball.lastColumn) desiredSign = -1;
if ((desiredSign != 0) && (desiredSign != currentSign)) {
Body.applyForce(body, body.position,
{ x: desiredSign * NUDGE_ACCEL * body.mass, y: 0});
return(true);
}
}
}
return(false);
}
}
// FACTORY / CACHE ************************************************************
// maintain a cache of PartBody instances
export class PartBodyFactory {
// make or reuse a part body from the cache
public make(part:Part):PartBody {
if (! this._instances.has(part)) {
this._instances.set(part, new PartBody(part));
}
return(this._instances.get(part));
}
// cached instances
private _instances:WeakMap<Part,PartBody> = new WeakMap();
// mark that a part body is not currently being used
public release(instance:PartBody):void {
}
} | the_stack |
import { Property, Term } from "./ast";
import { newScopeWithBuiltins } from "./builtins";
import { forceUnwrapFailed } from "./builtins/common";
import { functionize, insertFunction, noinline, returnType, statementsInValue, wrapped, FunctionBuilder } from "./functions";
import { parseAST, parseDeclaration, parseType } from "./parse";
import { defaultInstantiateType, expressionSkipsCopy, newClass, primitive, reifyType, store, withPossibleRepresentations, EnumCase, FunctionMap, PossibleRepresentation, ProtocolConformanceMap, ReifiedType, TypeMap } from "./reified";
import { addVariable, emitScope, lookup, mangleName, newScope, uniqueName, DeclarationFlags, MappedNameValue, Scope } from "./scope";
import { Function, Type } from "./types";
import { camelCase, concat, expectLength, lookupForMap } from "./utils";
import { annotate, annotateValue, array, binary, boxed, call, callable, conditional, conformance, copy, expr, expressionLiteralValue, functionValue, ignore, isPure, literal, locationForTerm, logical, member, read, representationsForTypeValue, reuse, set, statements, stringifyType, stringifyValue, subscript, transform, tuple, typeFromValue, typeType, typeTypeValue, typeValue, unary, undefinedValue, variable, ArgGetter, Value } from "./values";
import { emptyOptional, optionalIsSome, unwrapOptional, wrapInOptional } from "./builtins/Optional";
import generate from "@babel/generator";
import { assignmentExpression, blockStatement, catchClause, classBody, classDeclaration, classMethod, doWhileStatement, exportNamedDeclaration, forOfStatement, forStatement, identifier, ifStatement, isIdentifier, logicalExpression, newExpression, objectExpression, objectProperty, program, returnStatement, templateElement, templateLiteral, thisExpression, throwStatement, tryStatement, variableDeclaration, variableDeclarator, whileStatement, ClassMethod, ClassProperty, Expression, ObjectProperty, Program, ReturnStatement, Statement } from "@babel/types";
import { spawn } from "child_process";
import { readdirSync, readFile as readFile_ } from "fs";
import { argv } from "process";
import { promisify } from "util";
const readFile = promisify(readFile_);
const emptyStatements: Statement[] = [];
function termsWithName(terms: Term[], name: string): Term[] {
return terms.filter((term) => term.name === name);
}
function findTermWithName(terms: Term[], name: string | RegExp): Term | undefined {
if (typeof name === "string") {
for (const term of terms) {
if (term.name === name) {
return term;
}
}
} else {
for (const term of terms) {
if (name.test(term.name)) {
return term;
}
}
}
return undefined;
}
function termWithName(terms: Term[], name: string | RegExp): Term {
const result = findTermWithName(terms, name);
if (typeof result === "undefined") {
throw new Error(`Could not find ${name} term: ${terms.map((term) => term.name).join(", ")}`);
}
return result;
}
function checkTermName(term: Term, expectedName: string, errorPrefix?: string) {
if (term.name !== expectedName) {
throw new TypeError(`Expected a ${expectedName}${typeof errorPrefix !== "undefined" ? " " + errorPrefix : ""}, got a ${term.name}`);
}
}
function isString(value: unknown): value is string {
return typeof value === "string";
}
function getProperty<T extends Property>(term: Term, key: string, checker: (prop: Property) => prop is T): T {
const props = term.properties;
if (Object.hasOwnProperty.call(props, key)) {
const value = props[key];
if (checker(value)) {
return value;
}
throw new Error(`Value for ${key} on ${term.name} is of the wrong type: ${JSON.stringify(term.properties)}`);
}
throw new Error(`Could not find ${key} in ${term.name}. Keys are ${Object.keys(props).join(", ")}`);
}
function constructTypeFromNames(baseType: string, typeParameters?: ReadonlyArray<string>): Type {
if (typeof typeParameters === "undefined") {
return parseType(baseType);
}
switch (baseType) {
case "Optional":
if (typeParameters.length < 1) {
throw new TypeError(`Expected at least one type parameter for Optional`);
}
return { kind: "optional", type: parseType(typeParameters[0]) };
case "Tuple":
return { kind: "tuple", types: typeParameters.map((type) => parseType(type)) };
case "Array":
if (typeParameters.length < 1) {
throw new TypeError(`Expected at least one type parameter for Array`);
}
return { kind: "array", type: parseType(typeParameters[0]) };
case "Dictionary":
if (typeParameters.length < 2) {
throw new TypeError(`Expected at least two type parameters for Dictionary`);
}
return { kind: "dictionary", keyType: parseType(typeParameters[0]), valueType: parseType(typeParameters[1]) };
default:
return { kind: "generic", base: parseType(baseType), arguments: typeParameters.map((type) => parseType(type)) };
}
}
function extractReference(term: Term, scope: Scope, type?: Function, suffix: string = ""): Value {
const decl = getProperty(term, "decl", isString);
const declaration = parseDeclaration(decl);
if (typeof declaration.local === "string") {
if (declaration.local === "$match") {
return variable(identifier("$match"), term);
}
return annotateValue(lookup(declaration.local, scope), term);
}
if (typeof declaration.member === "string") {
let parentType: Value | undefined;
if (typeof declaration.type === "string") {
parentType = typeValue(constructTypeFromNames(declaration.type, typeof declaration.substitutions !== "undefined" ? declaration.substitutions.map((sub) => sub.to) : undefined));
} else if (!Object.hasOwnProperty.call(scope.functions, declaration.member)) {
return annotateValue(lookup(declaration.member, scope), term);
}
const functionType = type || getFunctionType(term);
const substitutionValues: Value[] = [];
if (typeof declaration.substitutions !== "undefined") {
const functionArgs = functionType.arguments.types;
let argIndex: number = 0;
for (const substitution of declaration.substitutions) {
const arg: Type | undefined = functionArgs[argIndex];
if (typeof arg !== "undefined") {
if (arg.kind === "metatype") {
argIndex++;
continue;
} else {
argIndex = functionArgs.length;
}
}
substitutionValues.push(typeValue(parseType(substitution.to)));
}
}
return functionValue(`${declaration.member}${suffix}`, parentType, functionType, substitutionValues, term);
}
throw new TypeError(`Unable to parse and locate declaration: ${decl} (got ${JSON.stringify(declaration)})`);
}
function getType(term: Term) {
try {
return parseType(getProperty(term, "type", isString));
} catch (e) {
console.error(term);
throw e;
}
}
function getTypeValue(term: Term) {
return typeValue(getType(term), term);
}
function findFunctionType(type: Type): Function {
switch (type.kind) {
case "generic":
const baseType = findFunctionType(type.base);
return {
kind: "function",
arguments: {
kind: "tuple",
types: concat(type.arguments.map((argument) => typeType), baseType.arguments.types),
location: baseType.arguments.location,
},
return: baseType.return,
throws: baseType.throws,
rethrows: baseType.rethrows,
attributes: baseType.attributes,
location: baseType.location,
};
case "function":
return type;
default:
throw new TypeError(`Expected a function, got ${stringifyType(type)}`);
}
}
function getFunctionType(term: Term) {
return findFunctionType(getType(term));
}
function noSemanticExpressions(term: Term) {
return term.name !== "semantic_expr";
}
function isReadImpl(value: unknown): value is "stored" | "getter" | "inherited" {
return value === "stored" || value === "getter" || value === "inherited";
}
function readTypeOfProperty(term: Term) {
return getProperty(term, "readImpl", isReadImpl);
}
function isWriteImpl(value: unknown): value is "stored" | "setter" | "inherited" {
return value === "stored" || value === "setter" || value === "inherited";
}
function writeTypeOfProperty(term: Term) {
if (Object.hasOwnProperty.call(term.properties, "writeImpl")) {
return getProperty(term, "writeImpl", isWriteImpl);
} else {
return undefined;
}
}
function returnUndef(): undefined {
return undefined;
}
interface PatternOutput {
prefix: Statement[];
test: Value;
next?: PatternOutput;
}
const trueValue = literal(true);
function isTrueExpression(expression: Expression) {
return expression.type === "BooleanLiteral" && expression.value;
}
const emptyPattern: PatternOutput = {
prefix: emptyStatements,
test: trueValue,
};
function mergeDeclarationStatements(body: Statement[]) {
let result = body;
let i = body.length - 1;
if (i >= 0) {
while (i--) {
const current = body[i];
const previous = body[i + 1];
if (current.type === "VariableDeclaration" && previous.type === "VariableDeclaration" && current.kind === previous.kind) {
if (result === body) {
result = body.slice();
}
result.splice(i, 2, variableDeclaration(current.kind, concat(current.declarations, previous.declarations)));
}
}
}
return result;
}
function mergePatterns(first: PatternOutput, second: PatternOutput, scope: Scope, term: Term): PatternOutput {
const prefix = mergeDeclarationStatements(concat(first.prefix, second.prefix));
const next = first.next ? (second.next ? mergePatterns(first.next, second.next, scope, term) : first.next) : second.next;
const firstExpression = read(first.test, scope);
if (isTrueExpression(firstExpression)) {
return {
prefix,
test: second.test,
next,
};
}
const secondExpression = read(second.test, scope);
if (isTrueExpression(secondExpression)) {
return {
prefix,
test: expr(firstExpression, first.test.location),
next,
};
}
return {
prefix,
test: logical("&&", expr(firstExpression), expr(secondExpression), scope, term),
next,
};
}
export function convertToPattern(value: Value): PatternOutput {
if (value.kind === "copied") {
const inner = convertToPattern(value.value);
return {
prefix: inner.prefix,
test: copy(inner.test, value.type),
};
}
let prefix: Statement[] = emptyStatements;
if (value.kind === "statements" && value.statements.length > 0) {
const returningIndex = value.statements.findIndex((statement) => statement.type === "ReturnStatement");
if (returningIndex === value.statements.length - 1) {
prefix = value.statements.slice(0, value.statements.length - 1);
const argument = (value.statements[value.statements.length - 1] as ReturnStatement).argument;
value = expr(argument === null ? identifier("undefined") : argument, value.location);
} else if (returningIndex === -1) {
prefix = value.statements;
value = expr(identifier("undefined"), value.location);
}
}
return {
prefix,
test: value,
};
}
function discriminantForPatternTerm(term: Term): string {
for (const key of Object.keys(term.properties)) {
if (term.properties[key] === true) {
const match = key.match(/\.(.+?)$/);
if (match) {
return match[1];
}
}
}
throw new Error(`Expected to have a discriminant property!`);
}
function unwrapCopies(value: Value): Value {
while (value.kind === "copied") {
value = value.value;
}
return value;
}
function translatePattern(term: Term, value: Value, scope: Scope, functions: FunctionMap, declarationFlags: DeclarationFlags = DeclarationFlags.None): PatternOutput {
switch (term.name) {
case "pattern_optional_some": {
expectLength(term.children, 1);
if (value.kind === "conditional" && value.consequent.kind === "optional" && value.alternate.kind === "optional") {
// Avoid creating and unwrapping an optional when value is a conditional expression that creates an optional in only one path
if (value.consequent.value !== undefined && value.alternate.value === undefined) {
return {
prefix: emptyStatements,
test: value.predicate,
next: translatePattern(term.children[0], value.consequent, scope, functions, declarationFlags),
};
}
if (value.consequent.value === undefined && value.alternate.value !== undefined) {
return {
prefix: emptyStatements,
test: unary("!", value.predicate, scope),
next: translatePattern(term.children[0], value.alternate, scope, functions, declarationFlags),
};
}
}
const type = getTypeValue(term.children[0]);
let next: PatternOutput | undefined;
const test = annotateValue(reuse(annotateValue(value, term), scope, "optional", (reusableValue) => {
next = translatePattern(term.children[0], unwrapOptional(reusableValue, type, scope), scope, functions, declarationFlags);
return annotateValue(optionalIsSome(reusableValue, type, scope), term);
}), term);
return {
prefix: emptyStatements,
test,
next,
};
}
case "case_label_item": {
expectLength(term.children, 1);
return translatePattern(term.children[0], annotateValue(value, term), scope, functions, declarationFlags);
}
case "pattern_let": {
expectLength(term.children, 1);
// TODO: Figure out how to avoid the copy here since it should only be necessary on var patterns
return translatePattern(term.children[0], copy(annotateValue(value, term), getTypeValue(term)), scope, functions, declarationFlags | DeclarationFlags.Const);
}
case "pattern_var": {
expectLength(term.children, 1);
return translatePattern(term.children[0], copy(annotateValue(value, term), getTypeValue(term)), scope, functions, declarationFlags & ~DeclarationFlags.Const);
}
case "pattern_expr": {
expectLength(term.children, 1);
return {
prefix: emptyStatements,
test: annotateValue(translateTermToValue(term.children[0], scope, functions), term),
};
}
case "pattern_typed": {
expectLength(term.children, 2);
return translatePattern(term.children[0], annotateValue(value, term), scope, functions, declarationFlags);
}
case "pattern_named": {
expectLength(term.children, 0);
expectLength(term.args, 1);
const name = term.args[0];
const type = getTypeValue(term);
if (Object.hasOwnProperty.call(scope.declarations, name)) {
return {
prefix: ignore(store(lookup(name, scope), annotateValue(value, term), type, scope), scope),
test: trueValue,
};
} else {
const pattern = convertToPattern(copy(annotateValue(value, term), type));
const hasMapping = Object.hasOwnProperty.call(scope.mapping, name);
let result: Statement[];
if (hasMapping) {
result = ignore(set(lookup(name, scope), pattern.test, scope, "=", term), scope);
} else {
const namedDeclaration = annotate(addVariable(scope, name, type, pattern.test, declarationFlags), term);
if (declarationFlags & DeclarationFlags.Export) {
result = [annotate(exportNamedDeclaration(namedDeclaration, []), term)];
} else {
result = [namedDeclaration];
}
}
return {
prefix: concat(pattern.prefix, result),
test: trueValue,
};
}
}
case "pattern_tuple": {
const type = getType(term);
if (type.kind !== "tuple") {
throw new TypeError(`Expected a tuple, got a ${stringifyType(type)}`);
}
const innerValue = unwrapCopies(value);
if (innerValue.kind === "tuple") {
return term.children.reduce((existing, child, i) => {
if (innerValue.values.length <= i) {
expectLength(innerValue.values, i);
}
const childPattern = translatePattern(child, annotateValue(innerValue.values[i], term), scope, functions, declarationFlags);
return mergePatterns(existing, childPattern, scope, term);
}, emptyPattern);
}
let prefix: Statement[] = emptyPattern.prefix;
let next: PatternOutput | undefined;
const test = reuse(annotateValue(value, term), scope, "tuple", (reusableValue) => {
return term.children.reduce((partialTest, child, i) => {
const childPattern = translatePattern(child, member(reusableValue, i, scope, term), scope, functions, declarationFlags);
const merged = mergePatterns({ prefix, test: partialTest, next }, childPattern, scope, term);
prefix = merged.prefix;
next = merged.next;
return merged.test;
}, emptyPattern.test);
});
return {
prefix,
test,
next,
};
}
case "pattern_enum_element": {
const type = getTypeValue(term);
const reified = typeFromValue(type, scope);
const cases = reified.cases;
if (typeof cases === "undefined") {
throw new TypeError(`Expected ${stringifyValue(type)} to be an enum, but it didn't have any cases.`);
}
const discriminant = discriminantForPatternTerm(term);
const index = cases.findIndex((possibleCase) => possibleCase.name === discriminant);
if (index === -1) {
throw new TypeError(`Could not find the ${discriminant} case in ${stringifyValue(type)}, only found ${cases.map((enumCase) => enumCase.name).join(", ")}`);
}
const isDirectRepresentation = binary("!==", representationsForTypeValue(type, scope), literal(PossibleRepresentation.Array), scope);
let next: PatternOutput | undefined;
const test = reuse(annotateValue(value, term), scope, "enum", (reusableValue) => {
const discriminantValue = conditional(isDirectRepresentation, reusableValue, member(reusableValue, 0, scope, term), scope);
const result = binary("===", discriminantValue, literal(index), scope, term);
expectLength(term.children, 0, 1);
if (term.children.length === 0) {
return result;
}
const child = term.children[0];
let patternValue: Value;
switch (cases[index].fieldTypes.length) {
case 0:
throw new Error(`Tried to use a pattern on an enum case that has no fields`);
case 1:
// Index 1 to account for the discriminant
patternValue = member(reusableValue, 1, scope, term);
// Special-case pattern matching using pattern_paren on a enum case with one field
if (child.name === "pattern_paren") {
next = translatePattern(child.children[0], patternValue, scope, functions, declarationFlags);
return result;
}
break;
default:
// Special-case pattern matching using pattern_tuple on a enum case with more than one field
if (child.name === "pattern_tuple") {
next = child.children.reduce((existing, tupleChild, i) => {
// Offset by 1 to account for the discriminant
const childPattern = translatePattern(tupleChild, member(reusableValue, i + 1, scope, term), scope, functions, declarationFlags);
return mergePatterns(existing, childPattern, scope, term);
}, emptyPattern);
return result;
}
// Remove the discriminant
patternValue = call(member(reusableValue, "slice", scope, term), [literal(1)], ["Int"], scope, term);
break;
}
// General case pattern matching on an enum
next = translatePattern(child, patternValue, scope, functions, declarationFlags);
return result;
});
return {
prefix: emptyStatements,
test,
next,
};
}
case "pattern_any": {
return emptyPattern;
}
default: {
console.error(term);
return {
prefix: emptyStatements,
test: expr(identifier("unknown_pattern_type$" + term.name), term),
};
}
}
}
function valueForPattern(pattern: PatternOutput, scope: Scope, term: Term): Value {
let test: Value;
if (typeof pattern.next !== "undefined") {
test = logical("&&", pattern.test, valueForPattern(pattern.next, scope, term), scope, term);
} else {
test = pattern.test;
}
if (pattern.prefix.length) {
return statements(pattern.prefix.concat([annotate(returnStatement(read(test, scope)), term)]));
}
return test;
}
function flattenPattern(pattern: PatternOutput, scope: Scope, term: Term): { prefix: Statement[]; test: Expression; suffix: Statement[] } {
let prefix: Statement[] = emptyStatements;
let test: Value = literal(true, term);
let currentPattern: PatternOutput | undefined = pattern;
while (currentPattern) {
prefix = concat(prefix, currentPattern.prefix);
const currentTest = read(currentPattern.test, scope);
currentPattern = currentPattern.next;
if (!isTrueExpression(currentTest)) {
test = expr(currentTest);
break;
}
}
let suffix: Statement[] = emptyStatements;
while (currentPattern) {
suffix = concat(suffix, currentPattern.prefix);
const currentTest = read(currentPattern.test, scope);
currentPattern = currentPattern.next;
if (!isTrueExpression(currentTest)) {
test = logical("&&", test, statements(concat(suffix, [annotate(returnStatement(currentTest), term)])), scope, term);
suffix = emptyStatements;
}
}
return {
prefix,
test: read(test, scope),
suffix,
};
}
function translateTermToValue(term: Term, scope: Scope, functions: FunctionMap, bindingContext?: (value: Value, optionalType: Value) => Value): Value {
switch (term.name) {
case "member_ref_expr": {
expectLength(term.children, 1);
const child = term.children[0];
const type = getTypeValue(child);
const decl = getProperty(term, "decl", isString);
const { member: memberName } = parseDeclaration(decl);
if (typeof memberName !== "string") {
throw new TypeError(`Expected a member expression when parsing declaration: ${decl}`);
}
const reified = typeFromValue(type, scope);
const getter = reified.functions(memberName);
if (typeof getter === "undefined") {
throw new TypeError(`Could not find ${memberName} in ${stringifyValue(type)}`);
}
const setter = reified.functions(memberName + "_set");
const childValue = translateTermToValue(term.children[0], scope, functions, bindingContext);
return subscript(
getter(scope, () => type, decl, [type]),
typeof setter !== "undefined" ? setter(scope, () => type, decl, [type]) : callable(() => {
throw new TypeError(`Could not find ${memberName} setter in ${stringifyValue(type)}`);
}, "() -> Void"),
[childValue],
[type],
);
}
case "tuple_element_expr": {
expectLength(term.children, 1);
const child = term.children[0];
const tupleType = getType(child);
if (tupleType.kind !== "tuple") {
throw new TypeError(`Expected a tuple, got a ${stringifyType(tupleType)}`);
}
if (tupleType.types.length === 1) {
return annotateValue(translateTermToValue(child, scope, functions, bindingContext), term);
}
return member(
translateTermToValue(child, scope, functions, bindingContext),
literal(+getProperty(term, "field", isString)),
scope,
term,
);
}
case "pattern_typed": {
expectLength(term.children, 2);
return translateTermToValue(term.children[0], scope, functions, bindingContext);
}
case "declref_expr": {
expectLength(term.children, 0);
return annotateValue(extractReference(term, scope), term);
}
case "subscript_expr": {
expectLength(term.children, 2);
const type = getType(term);
const getterType: Function = {
kind: "function",
arguments: {
kind: "tuple",
types: term.children.map(getType),
location: type.location,
},
return: type,
throws: false,
rethrows: false,
attributes: [],
location: type.location,
};
const getter = extractReference(term, scope, getterType);
const setterArgTypes = concat(term.children.map(getType), [type]);
const setterType: Function = {
kind: "function",
arguments: {
kind: "tuple",
types: setterArgTypes,
location: type.location,
},
return: parseType("Void"),
throws: false,
rethrows: false,
attributes: [],
location: type.location,
};
const setter = extractReference(term, scope, setterType, "_set");
return subscript(
call(getter, [typeValue(type)], ["Type"], scope, term),
callable((innerScope, arg, length) => {
// Defer resolving setter until invocation, in case there is no setter
const forwarded = call(setter, [typeValue(type)], ["Type"], innerScope, term);
if (forwarded.kind === "callable") {
return annotateValue(forwarded.call(innerScope, arg, length), term);
}
return call(
forwarded,
setterArgTypes.map((_, i) => arg(i)),
setterArgTypes.map((argumentType) => typeValue(argumentType)),
innerScope,
term,
);
}, setterType, term),
term.children.map((child) => translateTermToValue(child, scope, functions, bindingContext)),
term.children.map(getTypeValue),
term,
);
}
case "prefix_unary_expr":
case "call_expr":
case "constructor_ref_call_expr":
case "dot_syntax_call_expr":
case "binary_expr": {
expectLength(term.children, 2);
const target = term.children[0];
const args = term.children[1];
const targetValue = translateTermToValue(target, scope, functions, bindingContext);
const type = getType(args);
const argsValue = type.kind === "tuple" && type.types.length !== 1 ? translateTermToValue(args, scope, functions, bindingContext) : tuple([translateTermToValue(args, scope, functions, bindingContext)]);
const argTypes = type.kind === "tuple" ? type.types.map((innerType) => typeValue(innerType)) : [typeValue(type)];
if (argsValue.kind === "tuple") {
return call(targetValue, argsValue.values, argTypes, scope, term);
} else {
let updatedArgs: Value = argsValue;
if (targetValue.kind === "function" && targetValue.substitutions.length !== 0) {
// Insert substitutions as a [Foo$Type].concat(realArgs) expression
updatedArgs = call(
member(array(targetValue.substitutions, scope, term), "concat", scope, term),
[argsValue],
argTypes,
scope,
argsValue.location,
);
}
return call(
member(targetValue, "apply", scope, term),
[undefinedValue, updatedArgs],
["Any", "[Any]"],
scope,
term,
);
}
}
case "tuple_expr": {
if (term.children.length === 1) {
return annotateValue(translateTermToValue(term.children[0], scope, functions, bindingContext), term);
}
return tuple(term.children.map((child) => translateTermToValue(child, scope, functions, bindingContext)), term);
}
case "type_expr": {
expectLength(term.children, 0);
return annotateValue(getTypeValue(term), term);
}
case "boolean_literal_expr": {
expectLength(term.children, 0);
return literal(getProperty(term, "value", isString) === "true", term);
}
case "float_literal_expr":
case "integer_literal_expr": {
expectLength(term.children, 0);
return literal(+getProperty(term, "value", isString), term);
}
case "string_literal_expr": {
expectLength(term.children, 0);
return literal(getProperty(term, "value", isString), term);
}
case "magic_identifier_literal_expr": {
const location = locationForTerm(term);
if (typeof location === "undefined") {
throw new TypeError(`Expected location information for a magic identifier`);
}
const kind = getProperty(term, "kind", isString);
let value: string | number = "unknown";
switch (kind) {
case "#file":
const range = term.properties.range;
value = "unknown";
if (typeof range === "object" && !Array.isArray(range) && Object.hasOwnProperty.call(range, "from") && Object.hasOwnProperty.call(range, "to")) {
const match = range.from.match(/^(.*):\d+:\d+$/);
if (match !== null) {
value = match[1];
}
}
break;
case "#function":
value = scope.name;
break;
case "#line":
value = location.start.line;
break;
case "#column":
value = location.start.column;
break;
default:
throw new TypeError(`Expected a valid kind of magic, got ${kind}`);
}
return literal(value, term);
}
case "object_literal": {
throw new TypeError(`Playground literals are not supported`);
}
case "interpolated_string_literal_expr": {
expectLength(term.children, 2);
return annotateValue(translateTermToValue(term.children[0], scope, functions, bindingContext), term);
}
case "array_expr": {
const type = getType(term);
if (type.kind !== "array") {
throw new TypeError(`Expected an array type, got a ${stringifyType(type)}`);
}
return array(term.children.filter(noSemanticExpressions).map((child) => translateTermToValue(child, scope, functions, bindingContext)), scope, term);
}
case "dictionary_expr": {
const type = getType(term);
if (type.kind !== "dictionary") {
console.error(term);
throw new TypeError(`Expected a dictionary type, got a ${stringifyType(type)}`);
}
// Reify type so that if the dictionary type isn't supported we throw
reifyType(type, scope);
const properties: ObjectProperty[] = [];
for (const child of term.children.filter(noSemanticExpressions)) {
checkTermName(child, "tuple_expr", "as child of a dictionary expression");
expectLength(child.children, 2);
const keyChild = child.children[0];
const valueChild = child.children[1];
properties.push(objectProperty(read(translateTermToValue(keyChild, scope, functions, bindingContext), scope), read(translateTermToValue(valueChild, scope, functions, bindingContext), scope), true));
}
return expr(objectExpression(properties), term);
}
case "paren_expr": {
expectLength(term.children, 1);
return annotateValue(translateTermToValue(term.children[0], scope, functions, bindingContext), term);
}
case "if_expr": {
expectLength(term.children, 3);
return conditional(
translateTermToValue(term.children[0], scope, functions, bindingContext),
translateTermToValue(term.children[1], scope, functions, bindingContext),
translateTermToValue(term.children[2], scope, functions, bindingContext),
scope,
term,
);
}
case "inject_into_optional": {
expectLength(term.children, 1);
return annotateValue(wrapInOptional(translateTermToValue(term.children[0], scope, functions, bindingContext), getTypeValue(term.children[0]), scope), term);
}
case "function_conversion_expr": {
expectLength(term.children, 1);
return annotateValue(translateTermToValue(term.children[0], scope, functions, bindingContext), term);
}
case "load_expr": {
expectLength(term.children, 1);
return annotateValue(translateTermToValue(term.children[0], scope, functions, bindingContext), term);
}
case "assign_expr": {
expectLength(term.children, 2);
const destTerm = term.children[0];
if (destTerm.name === "discard_assignment_expr") {
return translateTermToValue(term.children[1], scope, functions, bindingContext);
}
const dest = translateTermToValue(destTerm, scope, functions, bindingContext);
const source = translateTermToValue(term.children[1], scope, functions, bindingContext);
return set(dest, source, scope, "=", term);
}
case "discard_assignment_expr": {
return annotateValue(undefinedValue, term);
}
case "inout_expr": {
expectLength(term.children, 1);
// return boxed(translateTermToValue(term.children[0], scope, functions, bindingContext));
return annotateValue(translateTermToValue(term.children[0], scope, functions, bindingContext), term);
}
case "pattern": {
expectLength(term.children, 2);
return annotateValue(valueForPattern(translatePattern(term.children[0], translateTermToValue(term.children[1], scope, functions, bindingContext), scope, functions), scope, term), term);
}
case "closure_expr":
case "autoclosure_expr": {
expectLength(term.children, 2);
const parameterList = termWithName(term.children, "parameter_list");
return callable((innerScope, arg) => {
return newScope("anonymous", innerScope, (childScope) => {
const paramStatements = applyParameterMappings(0, termsWithName(parameterList.children, "parameter"), arg, innerScope, childScope);
const result = translateTermToValue(term.children[1], childScope, functions, bindingContext);
if (paramStatements.length) {
return statements(concat(paramStatements, [returnStatement(read(result, childScope))]));
} else {
return result;
}
});
}, getFunctionType(term), term);
}
case "tuple_shuffle_expr": {
const elements = getProperty(term, "elements", Array.isArray);
const variadicSources = getProperty(term, "variadic_sources", Array.isArray).slice();
const type = getType(term);
if (type.kind !== "tuple") {
throw new Error(`Expected a tuple type, got ${stringifyType(type)}`);
}
const values = term.children.map((childTerm) => translateTermToValue(childTerm, scope, functions, bindingContext));
const valueTypes = type.types;
return tuple(elements.map((source, i) => {
const numeric = parseInt(source, 10);
switch (numeric) {
case -1: { // DefaultInitialize
return defaultInstantiateType(typeValue(valueTypes[i]), scope, returnUndef);
}
case -2: { // Variadic
if (variadicSources.length === 0) {
throw new Error(`Used more variadic sources than we have`);
}
const index = parseInt(variadicSources.shift(), 10);
if (Number.isNaN(index) || index < 0 || index >= term.children.length) {
throw new Error(`Invalid variadic index`);
}
return values[index];
}
case -3: { // CallerDefaultInitialize
return defaultInstantiateType(typeValue(valueTypes[i]), scope, returnUndef);
}
default: {
if (numeric < 0) {
throw new Error(`Unknown variadic element type ${source}`);
}
if (values.length < 1) {
expectLength(values, 1);
}
const firstValue = values[0];
if (firstValue.kind === "tuple") {
if (firstValue.values.length <= numeric) {
expectLength(firstValue.values, 1);
}
return firstValue.values[numeric];
} else {
return member(firstValue, numeric, scope, term);
}
}
}
}), term);
}
case "force_value_expr": {
expectLength(term.children, 1);
const type = getTypeValue(term);
const value = translateTermToValue(term.children[0], scope, functions, bindingContext);
return reuse(value, scope, "optional", (reusableValue) => {
// TODO: Optimize some cases where we can prove it to be a .some
return conditional(
optionalIsSome(reusableValue, type, scope),
unwrapOptional(reusableValue, type, scope),
call(forceUnwrapFailed, [], [], scope),
scope,
term,
);
});
}
case "super_ref_expr": {
return expr(identifier("super"));
}
case "derived_to_base_expr":
case "try_expr":
case "force_try_expr": {
expectLength(term.children, 1);
// Errors are dispatched via the native throw mechanism in JavaScript, so try expressions don't need special handling
return annotateValue(translateTermToValue(term.children[0], scope, functions, bindingContext), term);
}
case "optional_try_expr": {
expectLength(term.children, 1);
const type = getType(term.children[0]);
if (type.kind !== "optional") {
throw new Error(`Expected an optional type for optional_type_expr, got a ${type.kind}: ${stringifyType(type)}`);
}
const temp = uniqueName(scope, ":try");
return statements([
addVariable(scope, temp, typeValue(type)),
tryStatement(
blockStatement(
ignore(set(lookup(temp, scope), translateTermToValue(term.children[0], scope, functions, bindingContext), scope), scope),
),
catchClause(identifier("e"), blockStatement(
ignore(set(lookup(temp, scope), emptyOptional(typeValue(type.type), scope), scope), scope),
)),
),
annotate(returnStatement(read(lookup(temp, scope), scope)), term),
], term);
}
case "erasure_expr": {
// TODO: Support runtime Any type that can be inspected
expectLength(term.children, 1, 2);
return annotateValue(translateTermToValue(term.children[term.children.length - 1], scope, functions, bindingContext), term);
}
case "normal_conformance": {
// TODO: Wrap with runtime type information
expectLength(term.children, 1);
return annotateValue(translateTermToValue(term.children[0], scope, functions, bindingContext), term);
}
case "optional_evaluation_expr": {
expectLength(term.children, 1);
const type = getType(term);
if (type.kind !== "optional") {
throw new TypeError(`Expected an optional type, got a ${type.kind}`);
}
const innerType = typeValue(type.type);
let testValue: Value | undefined;
const someCase = translateTermToValue(term.children[0], scope, functions, (value: Value) => {
if (typeof testValue !== "undefined") {
throw new Error(`Expected only one binding expression to bind to this optional evaluation`);
}
return reuse(value, scope, "optional", (reusableValue) => {
testValue = optionalIsSome(reusableValue, innerType, scope);
return unwrapOptional(reusableValue, innerType, scope);
});
});
if (typeof testValue === "undefined") {
throw new Error(`Expected a binding expression to bind to this optional evaluation`);
}
return conditional(
testValue,
wrapInOptional(someCase, innerType, scope),
emptyOptional(innerType, scope),
scope,
term,
);
}
case "bind_optional_expr": {
if (typeof bindingContext !== "function") {
throw new Error(`Expected a binding context in order to bind an optional expression`);
}
expectLength(term.children, 1);
const expressionTerm = term.children[0];
const wrappedValue = translateTermToValue(expressionTerm, scope, functions);
return annotateValue(bindingContext(wrappedValue, getTypeValue(expressionTerm)), term);
}
case "make_temporarily_escapable_expr": {
expectLength(term.children, 3);
const closure = translateTermToValue(term.children[1], scope, functions, bindingContext);
const callTerm = term.children[2];
if (callTerm.name !== "call_expr") {
throw new TypeError(`Expected a call expression as the child of a temporarily escapable expression, got a ${callTerm.name}`);
}
const receiver = translateTermToValue(callTerm.children[0], scope, functions, bindingContext);
return call(receiver, [closure], ["Any"], scope, term);
}
case "tap_expr":
expectLength(term.children, 2);
const varValue = getProperty(term, "var", isString);
const declaration = parseDeclaration(varValue);
if (typeof declaration.local !== "string") {
throw new TypeError(`Expected a declaration local on ${varValue}`);
}
const secondChild = term.children[1];
checkTermName(secondChild, "brace_stmt", "as second child of a tap");
const init = translateTermToValue(term.children[0], scope, functions, bindingContext);
const head = annotate(addVariable(scope, declaration.local, typeValue(getType(term)), init, DeclarationFlags.Boxed), term);
const body = translateAllStatements(secondChild.children, scope, functions);
const expressions: Expression[] = [];
for (const statement of body) {
if (statement.type !== "ExpressionStatement" || statement.expression.type !== "AssignmentExpression" || statement.expression.operator !== "+=") {
const tail = returnStatement(read(lookup(declaration.local, scope), scope));
return statements(concat([head], body, [tail]));
}
expressions.push(statement.expression.right);
}
if (init.kind === "expression") {
const initValue = expressionLiteralValue(init.expression);
if (typeof initValue === "string") {
const templateElements = [];
const templateExpressions = [];
let pendingString = initValue;
for (const expression of expressions) {
const value = expressionLiteralValue(expression);
if (value === undefined) {
templateElements.push(templateElement({ cooked: pendingString, raw: pendingString }, false));
templateExpressions.push(expression);
pendingString = "";
} else {
pendingString += value;
}
}
templateElements.push(templateElement({ cooked: pendingString, raw: pendingString }, true));
return expr(templateLiteral(templateElements, templateExpressions), term);
}
}
return annotateValue(expressions.reduce((left, right) => binary("+", left, expr(right), scope), init), term);
case "is_subtype_expr": {
expectLength(term.children, 1);
const writtenType = mangleName(getProperty(term, "writtenType", isString));
const value = translateTermToValue(term.children[0], scope, functions, bindingContext);
return binary("instanceof", value, expr(writtenType), scope, term);
}
case "conditional_checked_cast_expr": {
expectLength(term.children, 1);
const writtenType = getProperty(term, "writtenType", isString);
const type = typeValue(parseType(writtenType));
const value = translateTermToValue(term.children[0], scope, functions, bindingContext);
return reuse(value, scope, writtenType, (reusableValue) => {
return conditional(
binary("instanceof", reusableValue, expr(mangleName(writtenType)), scope, term),
wrapInOptional(reusableValue, type, scope),
emptyOptional(type, scope),
scope,
);
});
}
default: {
console.error(term);
throw new TypeError(`Unknown term type ${JSON.stringify(term.name)}`);
}
}
}
function translateAllStatements(terms: Term[], scope: Scope, functions: FunctionMap, nextTerm?: Term): Statement[] {
let tailStatements = emptyStatements;
let headStatements = emptyStatements;
for (let i = 0; i < terms.length; i++) {
const term = terms[i];
if (term.name === "defer_stmt") {
tailStatements = concat(translateStatement(term, scope, functions, terms[i + 1] || nextTerm), tailStatements);
} else {
headStatements = concat(headStatements, translateStatement(term, scope, functions, terms[i + 1] || nextTerm));
}
}
if (tailStatements.length) {
return headStatements.length ? [tryStatement(blockStatement(headStatements), undefined, blockStatement(tailStatements))] : tailStatements;
} else {
return headStatements;
}
}
function applyParameterMappings(typeParameterCount: number, parameterTerms: Term[], arg: ArgGetter, scope: Scope, childScope: Scope, ignoreSelf: boolean = false): Statement[] {
return parameterTerms.reduce((body, param, index) => {
expectLength(param.args, 1);
const parameterName = param.args[0];
const value = arg(index + typeParameterCount, parameterName);
const type = getTypeValue(param);
if (Object.hasOwnProperty.call(param.properties, "inout") && (index !== 0 || !ignoreSelf)) {
// if (value.kind !== "boxed") {
// throw new TypeError(`Expected a boxed value, got a ${value.kind}`);
// }
// childScope.mapping[parameterName] = value.kind === "boxed" ? value : boxed(value, { kind: "modified", type, modifier: "inout" });
childScope.mapping[parameterName] = value.kind === "boxed" ? value : boxed(value, type);
return body;
} else if (value.kind === "type" || value.kind === "conformance") {
childScope.mapping[parameterName] = value;
return body;
} else {
const expression = read(value, scope);
if (isIdentifier(expression) || expression.type === "ThisExpression") {
childScope.mapping[parameterName] = expr(expression);
return body;
}
const literalValue = expressionLiteralValue(expression);
if (typeof literalValue === "boolean" || typeof literalValue === "number" || typeof literalValue === "string" || literalValue === null) {
childScope.mapping[parameterName] = literal(literalValue);
return body;
}
const temporary = uniqueName(scope, parameterName);
childScope.mapping[parameterName] = expr(identifier(temporary), expression.loc);
return concat(body, [addVariable(scope, temporary, type, expr(expression), DeclarationFlags.Const)]);
}
}, emptyStatements);
}
function flagsForDeclarationTerm(term: Term): DeclarationFlags {
let flags: DeclarationFlags = DeclarationFlags.None;
if (term.properties.let || term.properties.immutable) {
flags |= DeclarationFlags.Const;
} else {
flags |= DeclarationFlags.Boxed;
}
if (term.properties.access === "public") {
flags |= DeclarationFlags.Export;
}
return flags;
}
function typeMappingForGenericArguments(typeArguments: Type, arg: ArgGetter): TypeMap {
const result: TypeMap = Object.create(null);
if (typeArguments.kind === "generic") {
for (let i = 0; i < typeArguments.arguments.length; i++) {
const typeParameter = typeArguments.arguments[i];
let name: string | undefined;
if (typeParameter.kind === "name") {
name = typeParameter.name;
} else if (typeParameter.kind === "constrained") {
if (typeParameter.type.kind === "name") {
name = typeParameter.type.name;
} else {
throw new Error(`Expected a type name or a constrained type name, got a ${typeParameter.type.kind}`);
}
} else {
throw new Error(`Expected a type name or a constrained type name, got a ${typeParameter.kind}`);
}
result[name] = (scope: Scope) => typeFromValue(arg(i, name), scope);
}
}
return result;
}
function translateFunctionTerm(name: string, term: Term, parameterLists: Term[][], constructedTypeName: string | undefined, scope: Scope, functions: FunctionMap, selfValue?: MappedNameValue): (scope: Scope, arg: ArgGetter) => Value {
function constructCallable(head: Statement[], parameterListIndex: number, functionType: Function, isInitial: boolean): (scope: Scope, arg: ArgGetter) => Value {
return (targetScope: Scope, arg: ArgGetter) => {
// Apply generic function mapping for outermost function
let typeMap: TypeMap | undefined;
if (isInitial && term.args.length >= 2) {
typeMap = typeMappingForGenericArguments(parseType("Base" + term.args[1]), arg);
}
return newScope(isInitial ? name : "inner", targetScope, (childScope) => {
if (typeof selfValue !== "undefined") {
childScope.mapping.self = selfValue;
}
let typeArgumentCount: number = 0;
if (typeof typeMap !== "undefined") {
const typeArgumentKeys = Object.keys(typeMap);
typeArgumentCount = typeArgumentKeys.length;
for (let i = 0; i < typeArgumentCount; i++) {
const argValue = arg(i, typeArgumentKeys[i]);
if (argValue.kind !== "direct") {
throw new TypeError(`Expected a direct value, got a ${argValue.kind}`);
}
childScope.mapping[typeArgumentKeys[i]] = argValue;
}
}
// Apply parameters
const parameterList = parameterLists[parameterListIndex];
const parameterStatements = concat(head, applyParameterMappings(typeArgumentCount, termsWithName(parameterList, "parameter"), arg, targetScope, childScope, isInitial && !!constructedTypeName));
if (parameterListIndex !== parameterLists.length - 1) {
// Not the innermost function, emit a wrapper. If we were clever we could curry some of the body
const type = returnType(functionType);
if (type.kind !== "function") {
throw new TypeError(`Expected a function as return type of wrapper function, instead got ${type.kind}`);
}
return callable(constructCallable(parameterStatements, parameterListIndex + 1, type, false), type);
}
// Emit the innermost function
const brace = findTermWithName(term.children, "brace_stmt");
if (brace) {
const body = termWithName(term.children, "brace_stmt").children.slice();
if (typeof constructedTypeName === "string") {
const typeOfResult = returnType(returnType(getType(term)));
const nonOptionalResult = typeOfResult.kind === "optional" ? typeOfResult.type : typeOfResult;
const selfMapping = uniqueName(childScope, camelCase(constructedTypeName));
childScope.mapping.self = expr(identifier(selfMapping));
const defaultInstantiation = defaultInstantiateType(typeValue(nonOptionalResult), scope, (fieldName) => {
if (body.length && body[0].name === "assign_expr") {
const children = body[0].children;
expectLength(children, 2);
if (children[0].name === "member_ref_expr") {
if (parseDeclaration(getProperty(children[0], "decl", isString)).member === fieldName) {
body.shift();
return read(translateTermToValue(children[1], childScope, functions), childScope);
}
}
}
return undefined;
});
if (body.length === 1 && body[0].name === "return_stmt" && body[0].properties.implicit) {
const defaultStatements = defaultInstantiation.kind === "statements" ? defaultInstantiation.statements : [annotate(returnStatement(read(defaultInstantiation, scope)), brace)];
return statements(concat(parameterStatements, defaultStatements), brace);
}
if (defaultInstantiation.kind === "statements" && defaultInstantiation.statements.length !== 0) {
const finalStatement = defaultInstantiation.statements[defaultInstantiation.statements.length - 1];
if (finalStatement.type === "ReturnStatement" && finalStatement.argument !== null && typeof finalStatement.argument !== "undefined" && finalStatement.argument.type === "Identifier") {
childScope.mapping.self = expr(finalStatement.argument);
const optimizedConstructorBody: Statement[] = translateAllStatements(body, childScope, functions);
return statements(concat(concat(parameterStatements, defaultInstantiation.statements.slice(0, defaultInstantiation.statements.length - 1)), optimizedConstructorBody), brace);
}
}
const declarations: Statement[] = [addVariable(childScope, selfMapping, typeValue(typeOfResult), defaultInstantiation)];
const constructorBody: Statement[] = translateAllStatements(body, childScope, functions);
return statements(concat(concat(parameterStatements, declarations), constructorBody), brace);
}
return statements(concat(parameterStatements, translateAllStatements(body, childScope, functions)), brace);
} else {
if (typeof constructedTypeName === "string") {
const typeOfResult = returnType(returnType(getType(term)));
const selfMapping = uniqueName(childScope, camelCase(constructedTypeName));
childScope.mapping.self = expr(identifier(selfMapping));
const defaultInstantiation = defaultInstantiateType(typeValue(typeOfResult), scope, () => undefined);
return statements(concat(parameterStatements, [annotate(returnStatement(read(defaultInstantiation, scope)), term)]), term);
} else {
return statements(parameterStatements, term);
}
}
}, typeMap);
};
}
return constructCallable(emptyStatements, 0, getFunctionType(term), true);
}
function nameForFunctionTerm(term: Term): string {
expectLength(term.args, 1, 2);
return term.args[0].replace(/\((_:)+\)$/, "");
}
function addFunctionToType(functions: FunctionMap, conformances: ProtocolConformanceMap | undefined, name: string, builder: FunctionBuilder) {
functions[name] = builder;
if (typeof conformances !== "undefined") {
for (const key of Object.keys(conformances)) {
const protocolConformance = conformances[key].functions;
if (Object.hasOwnProperty.call(protocolConformance, name)) {
protocolConformance[name] = builder;
}
}
}
}
function translateStatement(term: Term, scope: Scope, functions: FunctionMap, nextTerm?: Term): Statement[] {
switch (term.name) {
case "source_file": {
return translateAllStatements(term.children, scope, functions);
}
case "accessor_decl":
if (Object.hasOwnProperty.call(term.properties, "materializeForSet_for")) {
return emptyStatements;
}
case "constructor_decl":
case "func_decl": {
const isConstructor = term.name === "constructor_decl";
expectLength(term.args, 1, 2);
const name = nameForFunctionTerm(term);
const parameters = termsWithName(term.children, "parameter");
const parameterLists = concat(parameters.length ? [parameters] : [], termsWithName(term.children, "parameter_list").map((paramList) => paramList.children));
if (parameterLists.length === 0) {
throw new Error(`Expected a parameter list for a function declaration`);
}
const fn = translateFunctionTerm(name, term, parameterLists, isConstructor ? "self" : undefined, scope, functions);
const type = getFunctionType(term);
if (/^anonname=/.test(name)) {
scope.functions[name] = fn;
} else if (!isConstructor && (flagsForDeclarationTerm(term) & DeclarationFlags.Export) && functions === scope.functions) {
addFunctionToType(functions, undefined, name, noinline(fn, type));
insertFunction(name, scope, fn, type, undefined, true);
} else {
addFunctionToType(functions, undefined, name, isConstructor ? fn : noinline(fn, type));
}
return emptyStatements;
}
case "return_stmt": {
expectLength(term.children, 0, 1);
if (term.children.length) {
const value = transform(translateTermToValue(term.children[0], scope, functions), scope, (expression) => {
if (isIdentifier(expression) && Object.hasOwnProperty.call(scope.declarations, expression.name)) {
return expr(expression);
}
return copy(expr(expression), getTypeValue(term.children[0]));
});
if (value.kind === "statements") {
return value.statements;
}
return [annotate(returnStatement(read(value, scope)), term)];
} else if (term.properties.implicit) {
return [annotate(returnStatement(read(lookup("self", scope), scope)), term)];
} else {
return [annotate(returnStatement(), term)];
}
}
case "fail_stmt": {
return [annotate(returnStatement(read(literal(null), scope)), term)];
}
case "top_level_code_decl": {
return translateAllStatements(term.children, scope, functions, nextTerm);
}
case "var_decl": {
expectLength(term.children, 0);
const name = term.args[0];
if (Object.hasOwnProperty.call(scope.declarations, name)) {
const decl = scope.declarations[name];
if (term.properties.access === "public") {
decl.flags |= DeclarationFlags.Export;
}
if (typeof decl.declaration !== "undefined") {
decl.declaration = annotate(decl.declaration, term);
}
return emptyStatements;
} else {
const type = getTypeValue(term);
const defaultInstantiation = defaultInstantiateType(type, scope, returnUndef);
return [annotate(addVariable(scope, name, type, defaultInstantiation, flagsForDeclarationTerm(term)), term)];
}
break;
}
case "brace_stmt": {
return translateAllStatements(term.children, scope, functions, nextTerm);
}
case "if_stmt": {
const children = term.children;
expectLength(children, 2, 3);
let pattern: PatternOutput;
const testTerm = children[0];
if (testTerm.name === "pattern") {
pattern = translatePattern(testTerm.children[0], translateTermToValue(testTerm.children[1], scope, functions), scope, functions);
} else {
pattern = convertToPattern(translateTermToValue(testTerm, scope, functions));
}
const { prefix, test, suffix } = flattenPattern(pattern, scope, term);
const consequent = concat(suffix, translateInNewScope(children[1], scope, functions, "consequent"));
if (isTrueExpression(test)) {
return concat(prefix, consequent);
}
const alternate = children.length === 3 ? blockStatement(translateInNewScope(children[2], scope, functions, "alternate")) : undefined;
return concat(prefix, [annotate(ifStatement(test, blockStatement(consequent), alternate), term)]);
}
case "while_stmt": {
expectLength(term.children, 2);
const testTerm = term.children[0];
const bodyTerm = term.children[1];
return [annotate(whileStatement(read(translateTermToValue(testTerm, scope, functions), scope), blockStatement(translateInNewScope(bodyTerm, scope, functions, "body"))), term)];
}
case "repeat_while_stmt": {
expectLength(term.children, 2);
const bodyTerm = term.children[0];
const testTerm = term.children[1];
return [annotate(doWhileStatement(read(translateTermToValue(testTerm, scope, functions), scope), blockStatement(translateInNewScope(bodyTerm, scope, functions, "body"))), term)];
}
case "for_each_stmt": {
expectLength(term.children, 6);
const patternTerm = term.children[0];
if (patternTerm.name !== "pattern_named") {
throw new TypeError(`Only named patterns are supported in for each iteration, got a ${patternTerm.name}`);
}
expectLength(patternTerm.args, 1);
const targetTerm = term.children[2];
const targetType = getType(targetTerm);
const elementName = patternTerm.args[0];
const valueType = typeValue(getType(patternTerm));
return ignore(transform(translateTermToValue(targetTerm, scope, functions), scope, (target) => {
const bodyTerm = term.children[5];
if (targetType.kind === "array") {
const targetTypeValue = typeValue(targetType);
const sequenceConformance = conformance(targetTypeValue, "Sequence", scope);
const makeIterator = call(functionValue("makeIterator()", sequenceConformance, "(T.Type) -> (T) -> T.Iterator"), [targetTypeValue], [typeTypeValue], scope);
const iteratorType = call(functionValue("Iterator", sequenceConformance, "(T.Type) -> T.Type"), [targetTypeValue], [typeTypeValue], scope);
const iteratorConformance = conformance(iteratorType, "IteratorProtocol", scope);
const next = call(functionValue("next()", iteratorConformance, "(T.Type) -> (T) -> T.Element?"), [iteratorType], [typeTypeValue], scope);
const iterator = call(makeIterator, [expr(target)], [typeValue(getType(targetTerm))], scope);
return transform(iterator, scope, (iteratorValue) => {
const iteratorName = uniqueName(scope, "iterator");
return statements([
addVariable(scope, iteratorName, typeValue(targetType), expr(iteratorValue), DeclarationFlags.Const),
annotate(forStatement(
addVariable(scope, elementName, typeValue(getType(patternTerm))),
// TODO: Call the IteratorProtocol's next() method
read(optionalIsSome(expr(
assignmentExpression("=", identifier(elementName), read(call(next, [lookup(iteratorName, scope)], [iteratorType], scope), scope)),
), valueType, scope), scope),
null,
blockStatement(concat(
ignore(set(lookup(elementName, scope), unwrapOptional(lookup(elementName, scope), valueType, scope), scope), scope),
translateInNewScope(bodyTerm, scope, functions, "body"),
)),
), term),
], term);
});
} else {
return statements([annotate(forOfStatement(
addVariable(scope, elementName, typeValue(getType(patternTerm)), undefined, DeclarationFlags.Const),
target,
blockStatement(translateInNewScope(bodyTerm, scope, functions, "body")),
), term)], term);
}
}), scope);
}
case "switch_stmt": {
if (term.children.length < 1) {
throw new Error(`Expected at least one term, got ${term.children.length}`);
}
const discriminantTerm = term.children[0];
const declaration = annotate(variableDeclaration("var", [variableDeclarator(identifier("$match"), read(translateTermToValue(discriminantTerm, scope, functions), scope))]), term);
const cases = term.children.slice(1).reduceRight((previous: Statement | undefined, childTerm: Term): Statement => {
checkTermName(childTerm, "case_stmt", "as child of a switch statement");
if (childTerm.children.length < 1) {
throw new Error(`Expected at least one term, got ${childTerm.children.length}`);
}
let mergedPrefix: Statement[] = emptyStatements;
let mergedTest: Expression = literal(false).expression;
let mergedSuffix: Statement[] = emptyStatements;
const body = newScope("case", scope, (childScope) => {
const remainingChildren = childTerm.children.slice(0, childTerm.children.length - 1);
for (const child of remainingChildren) {
const { prefix, test, suffix } = flattenPattern(translatePattern(child, expr(identifier("$match")), childScope, functions), scope, term);
mergedPrefix = concat(mergedPrefix, prefix);
if (expressionLiteralValue(mergedTest) === false) {
mergedTest = test;
} else if (!isTrueExpression(mergedTest)) {
mergedTest = logicalExpression("||", mergedTest, test);
}
mergedSuffix = concat(mergedSuffix, suffix);
}
return statements(concat(mergedSuffix, translateStatement(childTerm.children[childTerm.children.length - 1], childScope, functions)), term);
});
// Basic optimization for else case in switch statement
if (typeof previous === "undefined" && isTrueExpression(mergedTest)) {
return annotate(blockStatement(concat(mergedPrefix, statementsInValue(body, scope))), term);
}
// Push the if statement into a block if the test required prefix statements
const pendingStatement = annotate(ifStatement(mergedTest, blockStatement(statementsInValue(body, scope)), previous), term);
if (mergedPrefix.length) {
return annotate(blockStatement(concat(mergedPrefix, [pendingStatement])), term);
}
return pendingStatement;
}, undefined);
return typeof cases !== "undefined" ? [declaration, cases] : [declaration];
}
case "throw_stmt": {
expectLength(term.children, 1);
const expressionTerm = term.children[0];
return [annotate(throwStatement(read(translateTermToValue(expressionTerm, scope, functions), scope)), term)];
}
case "guard_stmt": {
expectLength(term.children, 2);
const testTerm = term.children[0];
const bodyTerm = term.children[1];
return [annotate(ifStatement(
read(unary("!", translateTermToValue(testTerm, scope, functions), scope), scope),
blockStatement(translateInNewScope(bodyTerm, scope, functions, "alternate")),
), term)];
}
case "do_catch_stmt": {
if (term.children.length < 2) {
expectLength(term.children, 2);
}
const bodyTerm = term.children[0];
checkTermName(bodyTerm, "brace_stmt", "as first child of a do catch statement");
return term.children.slice(1).reduce((body, catchTerm) => {
checkTermName(catchTerm, "catch", "as non-first child of a do catch");
expectLength(catchTerm.children, 2);
const patternTerm = catchTerm.children[0];
checkTermName(patternTerm, "pattern_let", "as child of a catch pattern");
expectLength(patternTerm.children, 1);
const letPatternChild = patternTerm.children[0];
checkTermName(letPatternChild, "pattern_named", "as child of a catch pattern let expression");
expectLength(letPatternChild.args, 1);
const catchClauseExpression = identifier(letPatternChild.args[0]);
const catchBodyTerm = catchTerm.children[1];
checkTermName(catchBodyTerm, "brace_stmt", "as only child of a catch clause");
const catchBodyStatements = translateInNewScope(catchBodyTerm, scope, functions, "catch");
return [annotate(tryStatement(blockStatement(body), catchClause(catchClauseExpression, blockStatement(catchBodyStatements))), term)];
}, translateInNewScope(bodyTerm, scope, functions, "body"));
}
case "do_stmt": {
return translateAllStatements(term.children, scope, functions, nextTerm);
}
case "defer_stmt": {
expectLength(term.children, 2);
const firstChild = term.children[0];
checkTermName(firstChild, "func_decl", "as second child of a defer statement");
expectLength(firstChild.children, 2);
checkTermName(firstChild.children[0], "parameter_list", "as first child of defer statement function");
expectLength(firstChild.children[0].children, 0);
checkTermName(firstChild.children[1], "brace_stmt", "as second child of defer statement function");
checkTermName(term.children[1], "call_expr", "as second child of a defer statement");
return translateInNewScope(firstChild.children[1], scope, functions, "deferred");
}
case "enum_decl": {
expectLength(term.args, 1);
const inherits = term.properties.inherits;
const baseType = typeof inherits === "string" ? parseType(inherits) : undefined;
const baseReifiedType = typeof baseType !== "undefined" ? reifyType(baseType, scope) : undefined;
let body = emptyStatements;
const enumName = term.args[0];
const copyFunctionName = `${enumName}.copy`;
const methods: FunctionMap = {
[copyFunctionName]: noinline((innerScope, arg) => copyHelper(arg(0, "source"), innerScope), "(Self) -> Self"),
};
function copyHelper(value: Value, innerScope: Scope): Value {
// Passthrough to the underlying type, which should generally be simple
if (baseReifiedType) {
return baseReifiedType.copy ? baseReifiedType.copy(value, innerScope) : value;
}
const expression = read(value, innerScope);
if (expressionSkipsCopy(expression)) {
return expr(expression);
}
if (requiresCopyHelper) {
// Emit checks for cases that have field that require copying
return reuse(expr(expression), scope, "copySource", (reusableValue) => {
return cases.reduce(
(previous, enumCase, i) => {
if (enumCase.fieldTypes.some((fieldType) => !!fieldType.copy)) {
const test = binary("===",
member(reusableValue, 0, scope),
literal(i),
scope,
);
const copyCase = array(concat([literal(i)], enumCase.fieldTypes.map((fieldType, fieldIndex) => {
// if (fieldType === baseReifiedType) {
// TODO: Avoid resetting this each time
// methods["$copy"] = noinline((innermostScope, arg) => copyHelper(arg(0), innermostScope));
// }
const fieldValue = member(reusableValue, fieldIndex + 1, scope);
return fieldType.copy ? fieldType.copy(fieldValue, scope) : fieldValue;
})), scope);
return conditional(test, copyCase, previous, scope);
} else {
return previous;
}
},
// Fallback to slicing the array for remaining simple cases
call(member(reusableValue, "slice", scope), [], [], scope),
);
});
} else {
return call(member(expr(expression), "slice", scope), [], [], innerScope);
}
}
let requiresCopyHelper: boolean = false;
const cases: EnumCase[] = [];
const selfType: Type = {
kind: "name",
name: enumName,
};
const innerTypes: TypeMap = Object.create(null);
innerTypes.Type = () => primitive(PossibleRepresentation.Undefined, undefinedValue);
// Reify self
const reifiedSelfType: ReifiedType = {
functions: lookupForMap(methods),
conformances: baseReifiedType ? baseReifiedType.conformances : withPossibleRepresentations(Object.create(null), PossibleRepresentation.Array),
innerTypes,
copy: baseReifiedType ? baseReifiedType.copy : (value, innerScope) => {
// Skip the copy if we can—must be done on this side of the inlining boundary
const expression = read(value, scope);
if (expressionSkipsCopy(expression)) {
return expr(expression);
}
if (!requiresCopyHelper) {
return copyHelper(expr(expression), innerScope);
}
// Dispatch through the function so that recursion doesn't kill us
const copyFunctionType: Function = { kind: "function", arguments: { kind: "tuple", types: [selfType] }, return: selfType, throws: false, rethrows: false, attributes: [] };
return call(functionValue(copyFunctionName, typeValue(selfType), copyFunctionType), [expr(expression)], [typeValue(selfType)], scope);
},
cases,
};
scope.types[enumName] = () => reifiedSelfType;
// Populate each case
termsWithName(term.children, "enum_case_decl").forEach((caseDecl, index) => {
const elementDecl = termWithName(caseDecl.children, "enum_element_decl");
expectLength(elementDecl.args, 1);
// TODO: Extract the actual rawValue and use this as the discriminator
const name = elementDecl.args[0].match(/^[^\(]*/)![0];
const type = returnType(getType(elementDecl));
if (type.kind === "function") {
methods[name] = wrapped((innerScope, arg) => {
const args = type.arguments.types.map((argType, argIndex) => copy(arg(argIndex), typeValue(argType)));
return array(concat([literal(index) as Value], args), scope);
}, type);
cases.push({
name,
fieldTypes: type.arguments.types.map((argType) => {
const reified = reifyType(argType, scope);
if (reified.copy) {
requiresCopyHelper = true;
}
return reified;
}),
});
return;
}
if (baseType) {
// TODO: Extract the underlying value, which may actually not be numeric!
methods[name] = () => literal(index);
} else {
methods[name] = () => literal([index]);
}
cases.push({
name,
fieldTypes: [],
});
});
// Populate fields and members
for (const child of term.children) {
if (child.name === "var_decl") {
expectLength(child.args, 1);
if (readTypeOfProperty(child) === "getter") {
expectLength(child.children, 1);
const fieldName = child.args[0];
if (fieldName === "rawValue") {
// The built-in rawValue accessors don't have proper pattern matching :(
if (typeof baseType !== "undefined" && typeof baseReifiedType !== "undefined") {
methods.rawValue = wrapped((innerScope, arg) => copy(arg(0, "value"), typeValue(baseType)), "(Self) -> Int");
if (!Object.hasOwnProperty.call(methods, "hashValue")) {
methods.hashValue = methods.rawValue;
}
} else {
throw new TypeError(`Unable to synthesize rawValue for ${enumName}`);
}
} else if (fieldName === "hashValue") {
// The built-in hashValue accessors don't have proper pattern matching :(
if (typeof baseType !== "undefined" && typeof baseReifiedType !== "undefined") {
methods.hashValue = wrapped((innerScope, arg) => copy(arg(0, "value"), typeValue(baseType)), "(Self) -> Int");
} else {
throw new TypeError(`Unable to synthesize hashValue for ${enumName}`);
}
} else {
methods[fieldName] = wrapped((innerScope, arg) => {
const childTypeValue = getTypeValue(child);
const declaration = findTermWithName(child.children, "func_decl") || termWithName(child.children, "accessor_decl");
return call(call(functionValue(declaration.args[0], undefined, getFunctionType(declaration)), [arg(0, "self")], [childTypeValue], innerScope), [], [], innerScope);
}, "() -> Void");
}
body = concat(body, translateStatement(child.children[0], scope, methods));
} else {
throw new TypeError(`Enums should not have any stored fields`);
}
} else if (child.name !== "enum_case_decl" && child.name !== "enum_element_decl" && child.name !== "typealias") {
body = concat(body, translateStatement(child, scope, methods));
}
}
return body;
}
case "struct_decl": {
expectLength(term.args, 1);
let body: Statement[] = [];
const methods: FunctionMap = {};
const structName = term.args[0];
const conformances: ProtocolConformanceMap = Object.create(null);
if (Object.hasOwnProperty.call(term.properties, "inherits")) {
const inherits = term.properties.inherits;
if (typeof inherits === "string") {
const inheritsReified = reifyType(inherits, scope);
conformances[inherits] = { ...inheritsReified.conformances[inherits] };
}
}
const innerTypes: TypeMap = Object.create(null);
const storedFields: Array<{ name: string, type: Value }> = [];
conformances.Object = {
functions: {
":rep": wrapped((innerScope) => {
switch (storedFields.length) {
case 0:
return literal(PossibleRepresentation.Undefined);
case 1:
return representationsForTypeValue(storedFields[0].type, innerScope);
default:
return literal(PossibleRepresentation.Object);
}
}, "(Self.Type) -> Int"),
},
requirements: [],
};
innerTypes.Type = () => primitive(PossibleRepresentation.Undefined, undefinedValue);
scope.types[structName] = (globalScope) => {
return {
functions: lookupForMap(methods),
conformances,
defaultValue(innerScope, consume) {
if (storedFields.length === 0) {
return undefinedValue;
}
if (storedFields.length === 1) {
// TODO: Handle case where defaultValue isn't available
const defaultValue = typeFromValue(storedFields[0].type, globalScope).defaultValue;
if (typeof defaultValue === "undefined") {
throw new TypeError(`Cannot default instantiate ${storedFields[0].name} in ${structName}`);
}
return defaultValue(innerScope, consume);
}
return expr(objectExpression(storedFields.map((fieldDeclaration) => {
const consumed = consume(fieldDeclaration.name);
let fieldExpression: Expression;
if (typeof consumed !== "undefined") {
fieldExpression = consumed;
} else {
const defaultValue = typeFromValue(fieldDeclaration.type, innerScope).defaultValue;
if (typeof defaultValue === "undefined") {
throw new TypeError(`Cannot default instantiate ${fieldDeclaration.name} in ${structName}`);
}
fieldExpression = read(defaultValue(innerScope, () => undefined), innerScope);
}
return objectProperty(mangleName(fieldDeclaration.name), fieldExpression);
})));
},
copy(value, innerScope) {
if (storedFields.length === 0) {
return value;
}
if (storedFields.length === 1) {
const onlyFieldType = typeFromValue(storedFields[0].type, innerScope);
return onlyFieldType.copy ? onlyFieldType.copy(value, scope) : value;
}
const expression = read(value, scope);
if (expressionSkipsCopy(expression)) {
return expr(expression);
}
return reuse(expr(expression), scope, "copySource", (source) => {
return expr(objectExpression(storedFields.map((fieldDeclaration, index) => {
const propertyExpr = member(source, mangleName(fieldDeclaration.name).name, scope);
const reified = typeFromValue(fieldDeclaration.type, innerScope);
const copiedValue = reified.copy ? reified.copy(propertyExpr, scope) : propertyExpr;
return objectProperty(mangleName(fieldDeclaration.name), read(copiedValue, scope));
})));
});
},
innerTypes,
};
};
for (const child of term.children) {
switch (child.name) {
case "var_decl": {
expectLength(child.args, 1);
const fieldName = child.args[0];
const childTypeValue = getTypeValue(child);
if (readTypeOfProperty(child) === "getter") {
expectLength(child.children, 1);
methods[fieldName] = wrapped((innerScope, arg) => {
const declaration = findTermWithName(child.children, "func_decl") || termWithName(child.children, "accessor_decl");
return call(call(functionValue(declaration.args[0], undefined, getFunctionType(declaration)), [arg(0, "self")], [childTypeValue], innerScope), [], [], innerScope);
}, "() -> Void");
body = concat(body, translateStatement(child.children[0], scope, methods));
} else {
storedFields.push({
name: fieldName,
type: childTypeValue,
});
methods[fieldName] = wrapped((innerScope, arg) => {
return member(arg(0, "self"), fieldName, innerScope);
}, "(Self) -> Any");
methods[fieldName + "_set"] = wrapped((innerScope, arg) => {
return set(member(arg(0, "lhs"), fieldName, innerScope), arg(1, "rhs"), innerScope);
}, "(inout Self, Any) -> Void");
}
break;
}
case "constructor_decl":
case "func_decl": {
const isConstructor = child.name === "constructor_decl";
expectLength(child.args, 1, 2);
const name = nameForFunctionTerm(child);
const parameters = termsWithName(child.children, "parameter");
const parameterLists = concat(parameters.length ? [parameters] : [], termsWithName(child.children, "parameter_list").map((paramList) => paramList.children));
if (parameterLists.length === 0) {
throw new Error(`Expected a parameter list for a function declaration`);
}
const fn = translateFunctionTerm(name, child, parameterLists, isConstructor ? structName : undefined, scope, functions);
addFunctionToType(methods, conformances, name, fn);
break;
}
default: {
body = concat(body, translateStatement(child, scope, methods));
}
}
}
return body;
}
case "pattern_binding_decl": {
if (term.children.length === 2) {
const valueChild = term.children[1];
const value = translateTermToValue(valueChild, scope, functions);
const flags: DeclarationFlags = typeof nextTerm !== "undefined" && nextTerm.name === "var_decl" ? flagsForDeclarationTerm(nextTerm) : DeclarationFlags.None;
const pattern = translatePattern(term.children[0], value, scope, functions, flags);
if (typeof pattern.next !== "undefined") {
throw new Error(`Chained patterns are not supported on binding declarations`);
}
const prefix = pattern.prefix.map((statement) => annotate(statement, term));
return concat(prefix, ignore(pattern.test, scope));
}
if (term.children.length === 1) {
return emptyStatements;
}
throw new Error(`Expected 1 or 2 terms, got ${term.children.length}`);
}
case "class_decl": {
expectLength(term.args, 1);
// const layout: Field[] = [];
const methods: FunctionMap = Object.create(null);
const classIdentifier = mangleName(term.args[0]);
const className = term.args[0];
const selfType = typeValue({ kind: "name", name: className });
const conformances: ProtocolConformanceMap = Object.create(null);
const innerTypes: TypeMap = Object.create(null);
const storedFields: Array<{ name: string, type: Value }> = [];
innerTypes.Type = () => primitive(PossibleRepresentation.Undefined, undefinedValue);
scope.types[className] = () => newClass(methods, conformances, innerTypes, (innerScope: Scope, consume: (fieldName: string) => Expression | undefined) => {
const self = uniqueName(innerScope, camelCase(className));
const newExpr = newExpression(classIdentifier, []);
let bodyStatements: Statement[] = [addVariable(innerScope, self, selfType, expr(newExpr), DeclarationFlags.Const)];
const selfValue = lookup(self, scope);
for (const storedField of storedFields) {
const fieldExpression = consume(storedField.name);
let fieldValue;
if (typeof fieldExpression === "undefined") {
const defaultValue = typeFromValue(storedField.type, innerScope).defaultValue;
if (typeof defaultValue === "undefined") {
// Swift always ensures all mandatory fields are filled, so we can be certain that later in the body it will be assigned
continue;
}
fieldValue = defaultValue(innerScope, () => undefined);
} else {
fieldValue = expr(fieldExpression);
}
bodyStatements = concat(bodyStatements, ignore(set(member(selfValue, storedField.name, scope), fieldValue, scope), scope));
}
if (bodyStatements.length === 1) {
return expr(newExpr);
} else {
bodyStatements.push(returnStatement(read(selfValue, scope)));
return statements(bodyStatements);
}
});
const bodyContents: Array<ClassProperty | ClassMethod> = [];
for (const child of term.children) {
switch (child.name) {
case "var_decl": {
if (child.args.length < 1) {
expectLength(child.args, 1);
}
const fieldName = child.args[0];
if (readTypeOfProperty(child) === "getter") {
// TODO: Implement getters/setters
if (child.children.length < 1) {
expectLength(child.children, 1);
}
const childDeclaration = findTermWithName(child.children, "func_decl") || termWithName(child.children, "accessor_decl");
if (flagsForDeclarationTerm(child) & DeclarationFlags.Export) {
const fn = translateFunctionTerm(fieldName + ".get", childDeclaration, [[]], undefined, scope, functions, expr(thisExpression()));
const [args, body] = functionize(scope, fieldName, (innerScope) => fn(innerScope, () => expr(thisExpression())), getFunctionType(childDeclaration));
bodyContents.push(classMethod("get", identifier(fieldName), args, blockStatement(body)));
// Default implementation will call getter/setter
methods[fieldName] = wrapped((innerScope, arg) => {
return member(arg(0, "self"), fieldName, innerScope);
}, "(Self) -> Any");
} else {
methods[fieldName] = wrapped((innerScope, arg) => {
return reuse(arg(0, "self"), innerScope, "self", (self) => {
const fn = translateFunctionTerm(fieldName + ".get", childDeclaration, [[]], undefined, scope, functions, self);
return fn(scope, arg);
});
}, "(Self) -> Any");
}
} else {
const childTypeValue = getTypeValue(child);
storedFields.push({
name: fieldName,
type: childTypeValue,
});
methods[fieldName] = wrapped((innerScope, arg) => {
return member(arg(0, "self"), fieldName, innerScope);
}, "(Self) -> Any");
if (writeTypeOfProperty(child) === "stored") {
methods[fieldName + "_set"] = wrapped((innerScope, arg) => {
return set(member(arg(0, "lhs"), fieldName, innerScope), arg(1, "rhs"), innerScope);
}, "(inout Self, Any) -> Void");
}
}
break;
}
case "destructor_decl": {
const brace = findTermWithName(child.children, "brace_stmt");
if (typeof brace !== "undefined" && brace.children.length > 0) {
console.warn(`Non-trivial deinit method found on ${className}, will never be called at runtime`);
}
break;
}
case "constructor_decl":
case "func_decl": {
const isConstructor = child.name === "constructor_decl";
expectLength(child.args, 1, 2);
const name = nameForFunctionTerm(child);
const parameters = termsWithName(child.children, "parameter");
const parameterLists = concat(parameters.length ? [parameters] : [], termsWithName(child.children, "parameter_list").map((paramList) => paramList.children));
if (parameterLists.length === 0) {
throw new Error(`Expected a parameter list for a function declaration`);
}
const fn = translateFunctionTerm(name, child, parameterLists, isConstructor ? className : undefined, scope, functions);
if (child.properties.final || isConstructor) {
addFunctionToType(methods, conformances, name, fn);
} else {
const type = getFunctionType(child);
const innerReturnType = returnType(type);
if (innerReturnType.kind !== "function") {
throw new TypeError(`Expected a function, got a ${innerReturnType.kind}: ${stringifyType(innerReturnType)}`);
}
const methodIdentifier = mangleName(name);
const [args, body] = functionize(scope, name, (innerScope, arg) => {
const innerFunction = fn(innerScope, () => expr(thisExpression()));
if (innerFunction.kind === "callable") {
return innerFunction.call(innerScope, arg, innerReturnType.arguments.types.map((argType) => typeValue(argType)));
}
return call(
innerFunction,
innerReturnType.arguments.types.map((_, i) => arg(i)),
innerReturnType.arguments.types.map((argumentType) => typeValue(argumentType)),
innerScope,
);
}, type);
bodyContents.push(classMethod("method", methodIdentifier, args, blockStatement(body)));
addFunctionToType(methods, conformances, name, (innerScope, arg) => {
const self = arg(0, "self");
return callable((innerMostScope, innerArg) => {
return call(
member(self, methodIdentifier.name, innerMostScope),
innerReturnType.arguments.types.map((_, i) => innerArg(i)),
innerReturnType.arguments.types.map((argumentType) => typeValue(argumentType)),
innerMostScope,
);
}, innerReturnType);
});
}
break;
}
default:
break;
}
}
const inherits = term.properties.inherits;
const flags = flagsForDeclarationTerm(term);
const declaration = classDeclaration(classIdentifier, typeof inherits === "string" ? identifier(inherits) : undefined, classBody(bodyContents), []);
return [flags & DeclarationFlags.Export ? exportNamedDeclaration(declaration, []) : declaration];
}
default: {
const value = translateTermToValue(term, scope, functions);
const pattern = convertToPattern(value);
const { prefix, test, suffix } = flattenPattern(pattern, scope, term);
let result = prefix;
if (!isPure(test)) {
if (test.type === "ConditionalExpression") {
result = concat(result, [ifStatement(
test.test,
blockStatement(isPure(test.consequent) ? [] : ignore(expr(test.consequent), scope)),
isPure(test.alternate) ? undefined : blockStatement(ignore(expr(test.alternate), scope)),
)]);
} else {
result = concat(result, ignore(expr(test), scope));
}
}
return concat(result, suffix);
}
}
}
function translateInNewScope(term: Term, scope: Scope, functions: FunctionMap, scopeName: string): Statement[] {
return statementsInValue(newScope(scopeName, scope, (childScope) => statements(translateStatement(term, childScope, functions))), scope);
}
export function compileTermToProgram(root: Term): Program {
const programScope = newScopeWithBuiltins();
const programValue = emitScope(programScope, statements(translateStatement(root, programScope, programScope.functions)));
if (programValue.kind !== "statements") {
throw new TypeError(`Expected program to emit statements, not a ${programValue.kind}`);
}
return program(programValue.statements);
}
function readAsString(stream: NodeJS.ReadableStream): Promise<string> {
return new Promise<string>((resolve, reject) => {
stream.setEncoding("utf8");
stream.resume();
const input: Array<unknown> = [];
stream.on("data", (chunk) => input.push(chunk));
stream.on("end", () => {
resolve(input.join(""));
});
stream.on("error", reject);
});
}
const swiftPath: string = (() => {
try {
// Search toolchains
let hasLatest: boolean = false;
const developmentToolchains: { [date: string]: string } = Object.create(null);
for (const subpath of readdirSync("/Library/Developer/Toolchains/")) {
const match = subpath.match(/^swift-(5\.0-)?DEVELOPMENT-SNAPSHOT-(.*)\.xctoolchain$/);
if (match !== null) {
developmentToolchains[match[2]] = `/Library/Developer/Toolchains/${subpath}/usr/bin/swiftc`;
} else if (subpath === "swift-latest.xctoolchain") {
hasLatest = true;
}
}
// Attempt to use the latest development toolchain
const toolchainKeys = Object.keys(developmentToolchains);
if (toolchainKeys.length) {
toolchainKeys.sort();
return developmentToolchains[toolchainKeys[toolchainKeys.length - 1]];
}
// Or the latest symlink
if (hasLatest) {
return "/Library/Developer/Toolchains/swift-latest.xctoolchain/usr/bin/swiftc";
}
// Or whatever the installed Xcode version has
return "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc";
} catch (e) {
// Or the swiftc in the user's path
return "swiftc";
}
})();
export interface CompilerOutput {
code: string;
map: object;
ast: string;
}
export async function compile(path: string): Promise<CompilerOutput> {
const process = spawn(swiftPath, ["-dump-ast", "--", path]);
const processPromise = new Promise((resolve, reject) => {
process.on("error", reject);
process.on("exit", async (code, signal) => {
try {
if (code !== 0) {
const lines = (await stderr).split(/\r\n|\r|\n/g);
const bracketIndex = lines.findIndex((line) => /^\(/.test(line));
const filteredLines = bracketIndex !== -1 ? lines.slice(0, bracketIndex) : lines;
reject(new Error(filteredLines.join("\n")));
} else {
resolve();
}
} catch (e) {
reject(e);
}
});
});
const stdout = readAsString(process.stdout);
const stderr = readAsString(process.stderr);
try {
const file = readFile(path);
await processPromise;
let ast = (await stderr).trim() + (await stdout).trim();
if (ast[0] !== "(") {
const lines = ast.split(/\r\n|\r|\n/g);
const bracketIndex = lines.findIndex((line) => /^\(/.test(line));
console.error(lines.slice(0, bracketIndex).join("\n"));
ast = lines.slice(bracketIndex).join("\n");
}
// console.log(ast);
try {
const rootTerm = parseAST(ast);
const convertedProgram = compileTermToProgram(rootTerm);
const result = generate(convertedProgram, {
filename: path,
sourceFileName: path,
compact: false,
sourceMaps: true,
}, (await file).toString());
// console.log(rootTerm.children);
// console.log(JSON.stringify(result.ast, null, 2));
// console.log(result.map);
return {
code: result.code,
map: result.map!,
ast,
};
} catch (e) {
if (typeof e === "object" && e !== null) {
e.ast = ast;
}
throw e;
}
} finally {
await processPromise;
process.unref();
}
}
if (require.main === module) {
compile(argv[argv.length - 1]).then((result) => {
console.log(result.code);
}).catch((e) => {
// console.error(e instanceof Error ? e.message : e);
console.error(e);
process.exit(1);
});
} | the_stack |
import * as ts from 'typescript';
import { IdentifierResolver } from './resolvers';
import { Helpers } from './helpers';
import { Preprocessor } from './preprocessor';
import { CodeWriter } from './codewriter';
export class Emitter {
public writer: CodeWriter;
private resolver: IdentifierResolver;
private preprocessor: Preprocessor;
private sourceFileName: string;
private scope: Array<ts.Node> = new Array<ts.Node>();
private opsMap: Map<number, string> = new Map<number, string>();
private embeddedCPPTypes: Array<string>;
private isWritingMain = false;
public constructor(
typeChecker: ts.TypeChecker, private options: ts.CompilerOptions,
private cmdLineOptions: any, private singleModule: boolean, private rootFolder?: string) {
this.writer = new CodeWriter();
this.resolver = new IdentifierResolver(typeChecker);
this.preprocessor = new Preprocessor(this.resolver, this);
this.opsMap[ts.SyntaxKind.EqualsToken] = '=';
this.opsMap[ts.SyntaxKind.PlusToken] = '+';
this.opsMap[ts.SyntaxKind.MinusToken] = '-';
this.opsMap[ts.SyntaxKind.AsteriskToken] = '*';
this.opsMap[ts.SyntaxKind.PercentToken] = '%';
this.opsMap[ts.SyntaxKind.AsteriskAsteriskToken] = '__Math.pow';
this.opsMap[ts.SyntaxKind.SlashToken] = '/';
this.opsMap[ts.SyntaxKind.AmpersandToken] = '__std::bit_and()';
this.opsMap[ts.SyntaxKind.BarToken] = '__std::bit_or()';
this.opsMap[ts.SyntaxKind.CaretToken] = '__std::bit_xor()';
this.opsMap[ts.SyntaxKind.LessThanLessThanToken] = '__bitwise::lshift';
this.opsMap[ts.SyntaxKind.GreaterThanGreaterThanToken] = '__bitwise::rshift';
this.opsMap[ts.SyntaxKind.GreaterThanGreaterThanGreaterThanToken] = '__bitwise::rshift_nosign';
this.opsMap[ts.SyntaxKind.EqualsEqualsToken] = '__equals';
this.opsMap[ts.SyntaxKind.EqualsEqualsEqualsToken] = '==';
this.opsMap[ts.SyntaxKind.LessThanToken] = '<';
this.opsMap[ts.SyntaxKind.LessThanEqualsToken] = '<=';
this.opsMap[ts.SyntaxKind.ExclamationEqualsToken] = '__not_equals';
this.opsMap[ts.SyntaxKind.ExclamationEqualsEqualsToken] = '!=';
this.opsMap[ts.SyntaxKind.GreaterThanToken] = '>';
this.opsMap[ts.SyntaxKind.GreaterThanEqualsToken] = '>=';
this.opsMap[ts.SyntaxKind.PlusEqualsToken] = '+=';
this.opsMap[ts.SyntaxKind.MinusEqualsToken] = '-=';
this.opsMap[ts.SyntaxKind.AsteriskEqualsToken] = '*=';
this.opsMap[ts.SyntaxKind.PercentEqualsToken] = '%=';
this.opsMap[ts.SyntaxKind.AsteriskAsteriskEqualsToken] = '**=';
this.opsMap[ts.SyntaxKind.SlashEqualsToken] = '/=';
this.opsMap[ts.SyntaxKind.AmpersandEqualsToken] = '&=';
this.opsMap[ts.SyntaxKind.BarEqualsToken] = '|=';
this.opsMap[ts.SyntaxKind.CaretEqualsToken] = '^=';
this.opsMap[ts.SyntaxKind.LessThanLessThanEqualsToken] = '<<=';
this.opsMap[ts.SyntaxKind.GreaterThanGreaterThanEqualsToken] = '>>=';
this.opsMap[ts.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken] = '__StrictNotEqualsAssign';
this.opsMap[ts.SyntaxKind.TildeToken] = '__std::bit_not()';
this.opsMap[ts.SyntaxKind.ExclamationToken] = '!';
this.opsMap[ts.SyntaxKind.PlusPlusToken] = '++';
this.opsMap[ts.SyntaxKind.MinusMinusToken] = '--';
this.opsMap[ts.SyntaxKind.InKeyword] = '__in';
this.opsMap[ts.SyntaxKind.AmpersandAmpersandToken] = '__AND';
this.opsMap[ts.SyntaxKind.BarBarToken] = '__OR';
this.opsMap[ts.SyntaxKind.CommaToken] = ',';
// embedded types
this.embeddedCPPTypes = [
'bool',
'char',
'signed char',
'unsigned char',
'short',
'short int',
'signed short',
'signed short int',
'unsigned short',
'unsigned short int',
'int',
'signed',
'signed int',
'unsigned',
'unsigned int',
'long',
'long int',
'signed long',
'signed long int',
'unsigned long',
'unsigned long int',
'long long',
'long long int',
'signed long long',
'signed long long int',
'unsigned long long',
'unsigned long long int',
'float',
'double',
'long double',
'int8_t',
'int16_t',
'int32_t',
'int64_t',
'int_fast8_t',
'int_fast16_t',
'int_fast32_t',
'int_fast64_t',
'int_least8_t',
'int_least16_t',
'int_least32_t',
'int_least64_t',
'intmax_t',
'intptr_t',
'uint8_t',
'uint16_t',
'uint32_t',
'uint64_t',
'uint_fast8_t',
'uint_fast16_t',
'uint_fast32_t',
'uint_fast64_t',
'uint_least8_t',
'uint_least16_t',
'uint_least32_t',
'uint_least64_t',
'uintmax_t',
'uintptr_t',
'wchar_t',
'char16_t',
'char32_t',
'char8_t'
];
}
public HeaderMode: boolean;
public SourceMode: boolean;
public isHeader() {
return this.HeaderMode;
}
public isSource() {
return this.SourceMode;
}
public isHeaderWithSource() {
return (this.HeaderMode && this.SourceMode) || (!this.HeaderMode && !this.SourceMode);
}
public get isGlobalScope() {
return this.scope.length > 0 && this.scope[this.scope.length - 1].kind === ts.SyntaxKind.SourceFile;
}
public printNode(node: ts.Statement): string {
const sourceFile = ts.createSourceFile(
'noname', '', ts.ScriptTarget.ES2018, /*setParentNodes */ true, ts.ScriptKind.TS);
(<any>sourceFile.statements) = [node];
// debug output
const emitter = ts.createPrinter({
newLine: ts.NewLineKind.LineFeed,
});
const result = emitter.printNode(ts.EmitHint.SourceFile, sourceFile, sourceFile);
return result;
}
public processNode(node: ts.Node): void {
switch (node.kind) {
case ts.SyntaxKind.SourceFile:
this.processFile(<ts.SourceFile>node);
break;
case ts.SyntaxKind.Bundle:
this.processBundle(<ts.Bundle>node);
break;
case ts.SyntaxKind.UnparsedSource:
this.processUnparsedSource(<ts.UnparsedSource>node);
break;
default:
// TODO: finish it
throw new Error('Method not implemented.');
}
}
private isImportStatement(f: ts.Statement | ts.Declaration): boolean {
if (f.kind === ts.SyntaxKind.ImportDeclaration
|| f.kind === ts.SyntaxKind.ImportEqualsDeclaration) {
return true;
}
return false;
}
private isDeclarationStatement(f: ts.Statement | ts.Declaration): boolean {
if (f.kind === ts.SyntaxKind.FunctionDeclaration
|| f.kind === ts.SyntaxKind.EnumDeclaration
|| f.kind === ts.SyntaxKind.ClassDeclaration
|| f.kind === ts.SyntaxKind.InterfaceDeclaration
|| f.kind === ts.SyntaxKind.ModuleDeclaration
|| f.kind === ts.SyntaxKind.NamespaceExportDeclaration
|| f.kind === ts.SyntaxKind.TypeAliasDeclaration) {
return true;
}
return false;
}
private isVariableStatement(f: ts.Node): boolean {
if (f.kind === ts.SyntaxKind.VariableStatement) {
return true;
}
return false;
}
private isNamespaceStatement(f: ts.Node): boolean {
if (f.kind === ts.SyntaxKind.ModuleDeclaration
|| f.kind === ts.SyntaxKind.NamespaceExportDeclaration) {
return true;
}
return false;
}
private childrenVisitorNoScope(location: ts.Node, visit: (node: ts.Node) => boolean) {
function checkChild(node: ts.Node): any {
if (!visit(node)) {
ts.forEachChild(node, checkChild);
}
}
ts.forEachChild(location, checkChild);
}
private childrenVisitor(location: ts.Node, visit: (node: ts.Node) => boolean) {
let root = true;
function checkChild(node: ts.Node): any {
if (root) {
root = false;
} else {
if (node.kind === ts.SyntaxKind.FunctionDeclaration
|| node.kind === ts.SyntaxKind.ArrowFunction
|| node.kind === ts.SyntaxKind.MethodDeclaration
|| node.kind === ts.SyntaxKind.FunctionExpression
|| node.kind === ts.SyntaxKind.FunctionType
|| node.kind === ts.SyntaxKind.ClassDeclaration
|| node.kind === ts.SyntaxKind.ClassExpression) {
return;
}
}
if (!visit(node)) {
ts.forEachChild(node, checkChild);
}
}
ts.forEachChild(location, checkChild);
}
private hasReturn(location: ts.Node): boolean {
let hasReturnResult = false;
this.childrenVisitor(location, (node: ts.Node) => {
if (node.kind === ts.SyntaxKind.ReturnStatement) {
hasReturnResult = true;
return true;
}
return false;
});
return hasReturnResult;
}
private hasReturnWithValue(location: ts.Node): boolean {
let hasReturnResult = false;
this.childrenVisitor(location, (node: ts.Node) => {
if (node.kind === ts.SyntaxKind.ReturnStatement) {
const returnStatement = <ts.ReturnStatement>node;
if (returnStatement.expression) {
hasReturnResult = true;
return true;
}
}
return false;
});
return hasReturnResult;
}
private hasPropertyAccess(location: ts.Node, property: string): boolean {
let hasPropertyAccessResult = false;
this.childrenVisitor(location, (node: ts.Node) => {
if (node.kind === ts.SyntaxKind.Identifier && node.parent.kind === ts.SyntaxKind.PropertyAccessExpression) {
const identifier = <ts.Identifier>node;
if (identifier.text === property) {
hasPropertyAccessResult = true;
return true;
}
}
return false;
});
return hasPropertyAccessResult;
}
private hasArguments(location: ts.Node): boolean {
let hasArgumentsResult = false;
this.childrenVisitor(location, (node: ts.Node) => {
if (node.kind === ts.SyntaxKind.Identifier && node.parent.kind !== ts.SyntaxKind.PropertyAccessExpression) {
const identifier = <ts.Identifier>node;
if (identifier.text === 'arguments') {
hasArgumentsResult = true;
return true;
}
}
return false;
});
return hasArgumentsResult;
}
private requireCapture(location: ts.Node): boolean {
let requireCaptureResult = false;
this.childrenVisitor(location, (node: ts.Node) => {
if (node.kind === ts.SyntaxKind.Identifier
&& node.parent.kind !== ts.SyntaxKind.FunctionDeclaration
&& node.parent.kind !== ts.SyntaxKind.ClassDeclaration
&& node.parent.kind !== ts.SyntaxKind.MethodDeclaration
&& node.parent.kind !== ts.SyntaxKind.EnumDeclaration) {
const data = this.resolver.isLocal(node);
if (data) {
const isLocal = data[0];
if (isLocal !== undefined && !isLocal) {
requireCaptureResult = true;
return true;
}
}
}
return false;
});
return requireCaptureResult;
}
private markRequiredCapture(location: ts.Node): void {
this.childrenVisitorNoScope(location, (node: ts.Node) => {
if (node.kind === ts.SyntaxKind.Identifier
&& node.parent.kind !== ts.SyntaxKind.FunctionDeclaration
&& node.parent.kind !== ts.SyntaxKind.ClassDeclaration
&& node.parent.kind !== ts.SyntaxKind.MethodDeclaration
&& node.parent.kind !== ts.SyntaxKind.EnumDeclaration) {
const data = this.resolver.isLocal(node);
if (data) {
const isLocal = data[0];
const resolvedSymbol = data[1];
if (isLocal !== undefined && !isLocal) {
(<any>resolvedSymbol).valueDeclaration.__requireCapture = true;
}
}
}
return false;
});
}
private hasThis(location: ts.Node): boolean {
let createThis = false;
this.childrenVisitor(location, (node: ts.Node) => {
if (node.kind === ts.SyntaxKind.ThisKeyword) {
createThis = true;
return true;
}
return false;
});
return createThis;
}
private hasThisAsShared(location: ts.Node): boolean {
let createThis = false;
this.childrenVisitor(location, (node: ts.Node) => {
if (node.kind === ts.SyntaxKind.ThisKeyword && node.parent.kind !== ts.SyntaxKind.PropertyAccessExpression) {
createThis = true;
return true;
}
return false;
});
return createThis;
}
private processFile(sourceFile: ts.SourceFile): void {
this.scope.push(sourceFile);
this.processFileInternal(sourceFile);
this.scope.pop();
}
private processFileInternal(sourceFile: ts.SourceFile): void {
this.fixupParentReferences(sourceFile);
this.sourceFileName = sourceFile.fileName;
if (this.isHeader()) {
// added header
this.WriteHeader();
sourceFile.referencedFiles.forEach(f => {
this.writer.writeString('#include \"');
this.writer.writeString(f.fileName.replace('.d.ts', ''));
this.writer.writeStringNewLine('.h\"');
});
sourceFile.statements.filter(s => this.isImportStatement(s)).forEach(s => {
this.processInclude(s);
});
this.writer.writeStringNewLine('');
this.writer.writeStringNewLine('using namespace js;');
this.writer.writeStringNewLine('');
const position = this.writer.newSection();
sourceFile.statements.filter(s => this.isDeclarationStatement(s)).forEach(s => {
this.processInclude(s);
});
sourceFile.statements.filter(s => this.isDeclarationStatement(s)).forEach(s => {
this.processForwardDeclaration(s);
});
if (this.writer.hasAnyContent(position)) {
this.writer.writeStringNewLine();
}
sourceFile.statements
.map(v => this.preprocessor.preprocessStatement(v))
.filter(s => this.isDeclarationStatement(s) || this.isVariableStatement(s))
.forEach(s => {
if (this.isVariableStatement(s)) {
this.processForwardDeclaration(s);
} else {
this.processStatement(s);
}
});
sourceFile.statements.filter(s => this.isDeclarationStatement(s) || this.isVariableStatement(s)).forEach(s => {
this.processImplementation(s, true);
});
}
if (this.isSource()) {
// added header
this.WriteHeader();
sourceFile.statements.filter(s => this.isImportStatement(s)).forEach(s => {
this.processImplementation(s);
});
this.writer.writeStringNewLine('');
this.writer.writeStringNewLine('using namespace js;');
this.writer.writeStringNewLine('');
sourceFile.statements.filter(s => this.isDeclarationStatement(s)).forEach(s => {
this.processImplementation(s);
});
const positionBeforeVars = this.writer.newSection();
sourceFile.statements
.map(v => this.preprocessor.preprocessStatement(v))
.filter(s => this.isVariableStatement(s)
|| this.isNamespaceStatement(s))
.forEach(s => {
if (this.isNamespaceStatement(s)) {
this.isWritingMain = true;
this.processModuleVariableStatements(<ts.ModuleDeclaration>s);
this.isWritingMain = false;
} else {
this.processStatement(<ts.Statement>s);
}
});
const hasVarsContent = this.writer.hasAnyContent(positionBeforeVars);
const rollbackPosition = this.writer.newSection();
this.writer.writeStringNewLine('');
this.writer.writeStringNewLine('void Main(void)');
this.writer.BeginBlock();
this.isWritingMain = true;
const position = this.writer.newSection();
sourceFile.statements.filter(s => !this.isDeclarationStatement(s) && !this.isVariableStatement(s)
|| this.isNamespaceStatement(s)).forEach(s => {
if (this.isNamespaceStatement(s)) {
this.processModuleImplementationInMain(<ts.ModuleDeclaration>s);
} else {
this.processStatement(s);
}
});
this.isWritingMain = false;
if (hasVarsContent || this.writer.hasAnyContent(position, rollbackPosition)) {
this.writer.EndBlock();
this.writer.writeStringNewLine('');
this.writer.writeStringNewLine('MAIN');
}
}
if (this.isHeader()) {
// end of header
this.writer.writeStringNewLine(`#endif`);
}
}
private WriteHeader() {
const filePath = Helpers.getSubPath(Helpers.cleanUpPath(this.sourceFileName), Helpers.cleanUpPath(this.rootFolder));
if (this.isSource()) {
this.writer.writeStringNewLine(`#include "${filePath.replace(/\.ts$/, '.h')}"`);
} else {
const headerName = filePath.replace(/\.ts$/, '_h').replace(/[\\\/\.]/g, '_').toUpperCase();
this.writer.writeStringNewLine(`#ifndef ${headerName}`);
this.writer.writeStringNewLine(`#define ${headerName}`);
this.writer.writeStringNewLine(`#include "core.h"`);
}
}
private processBundle(bundle: ts.Bundle): void {
throw new Error('Method not implemented.');
}
private processUnparsedSource(unparsedSource: ts.UnparsedSource): void {
throw new Error('Method not implemented.');
}
private processStatement(node: ts.Statement | ts.Declaration): void {
this.processStatementInternal(node);
}
private processStatementInternal(nodeIn: ts.Statement | ts.Declaration, enableTypeAliases = false): void {
const node = this.preprocessor.preprocessStatement(nodeIn);
switch (node.kind) {
case ts.SyntaxKind.EmptyStatement: return;
case ts.SyntaxKind.VariableStatement: this.processVariableStatement(<ts.VariableStatement>node); return;
case ts.SyntaxKind.FunctionDeclaration: this.processFunctionDeclaration(<ts.FunctionDeclaration>node); return;
case ts.SyntaxKind.Block: this.processBlock(<ts.Block>node); return;
case ts.SyntaxKind.ModuleBlock: this.processModuleBlock(<ts.ModuleBlock>node); return;
case ts.SyntaxKind.ReturnStatement: this.processReturnStatement(<ts.ReturnStatement>node); return;
case ts.SyntaxKind.IfStatement: this.processIfStatement(<ts.IfStatement>node); return;
case ts.SyntaxKind.DoStatement: this.processDoStatement(<ts.DoStatement>node); return;
case ts.SyntaxKind.WhileStatement: this.processWhileStatement(<ts.WhileStatement>node); return;
case ts.SyntaxKind.ForStatement: this.processForStatement(<ts.ForStatement>node); return;
case ts.SyntaxKind.ForInStatement: this.processForInStatement(<ts.ForInStatement>node); return;
case ts.SyntaxKind.ForOfStatement: this.processForOfStatement(<ts.ForOfStatement>node); return;
case ts.SyntaxKind.BreakStatement: this.processBreakStatement(<ts.BreakStatement>node); return;
case ts.SyntaxKind.ContinueStatement: this.processContinueStatement(<ts.ContinueStatement>node); return;
case ts.SyntaxKind.SwitchStatement: this.processSwitchStatement(<ts.SwitchStatement>node); return;
case ts.SyntaxKind.ExpressionStatement: this.processExpressionStatement(<ts.ExpressionStatement>node); return;
case ts.SyntaxKind.TryStatement: this.processTryStatement(<ts.TryStatement>node); return;
case ts.SyntaxKind.ThrowStatement: this.processThrowStatement(<ts.ThrowStatement>node); return;
case ts.SyntaxKind.DebuggerStatement: this.processDebuggerStatement(<ts.DebuggerStatement>node); return;
case ts.SyntaxKind.EnumDeclaration: this.processEnumDeclaration(<ts.EnumDeclaration>node); return;
case ts.SyntaxKind.ClassDeclaration: this.processClassDeclaration(<ts.ClassDeclaration>node); return;
case ts.SyntaxKind.InterfaceDeclaration: this.processClassDeclaration(<ts.InterfaceDeclaration>node); return;
case ts.SyntaxKind.ExportDeclaration: this.processExportDeclaration(<ts.ExportDeclaration>node); return;
case ts.SyntaxKind.ModuleDeclaration: this.processModuleDeclaration(<ts.ModuleDeclaration>node); return;
case ts.SyntaxKind.NamespaceExportDeclaration: this.processNamespaceDeclaration(<ts.NamespaceDeclaration>node); return;
case ts.SyntaxKind.LabeledStatement: this.processLabeledStatement(<ts.LabeledStatement>node); return;
case ts.SyntaxKind.ImportEqualsDeclaration: /*this.processImportEqualsDeclaration(<ts.ImportEqualsDeclaration>node);*/ return;
case ts.SyntaxKind.ImportDeclaration:
/*done in forward declaration*/ /*this.processImportDeclaration(<ts.ImportDeclaration>node);*/ return;
case ts.SyntaxKind.TypeAliasDeclaration:
/*done in forward Declaration*/
if (enableTypeAliases) {
this.processTypeAliasDeclaration(<ts.TypeAliasDeclaration>node);
}
return;
case ts.SyntaxKind.ExportAssignment: /*nothing to do*/ return;
}
// TODO: finish it
throw new Error('Method not implemented.');
}
private processExpression(nodeIn: ts.Expression): void {
const node = this.preprocessor.preprocessExpression(nodeIn);
if (!node) {
return;
}
// we need to process it for statements only
//// this.functionContext.code.setNodeToTrackDebugInfo(node, this.sourceMapGenerator);
switch (node.kind) {
case ts.SyntaxKind.NewExpression: this.processNewExpression(<ts.NewExpression>node); return;
case ts.SyntaxKind.CallExpression: this.processCallExpression(<ts.CallExpression>node); return;
case ts.SyntaxKind.PropertyAccessExpression: this.processPropertyAccessExpression(<ts.PropertyAccessExpression>node); return;
case ts.SyntaxKind.PrefixUnaryExpression: this.processPrefixUnaryExpression(<ts.PrefixUnaryExpression>node); return;
case ts.SyntaxKind.PostfixUnaryExpression: this.processPostfixUnaryExpression(<ts.PostfixUnaryExpression>node); return;
case ts.SyntaxKind.BinaryExpression: this.processBinaryExpression(<ts.BinaryExpression>node); return;
case ts.SyntaxKind.ConditionalExpression: this.processConditionalExpression(<ts.ConditionalExpression>node); return;
case ts.SyntaxKind.DeleteExpression: this.processDeleteExpression(<ts.DeleteExpression>node); return;
case ts.SyntaxKind.TypeOfExpression: this.processTypeOfExpression(<ts.TypeOfExpression>node); return;
case ts.SyntaxKind.FunctionExpression: this.processFunctionExpression(<ts.FunctionExpression>node); return;
case ts.SyntaxKind.ArrowFunction: this.processArrowFunction(<ts.ArrowFunction>node); return;
case ts.SyntaxKind.ElementAccessExpression: this.processElementAccessExpression(<ts.ElementAccessExpression>node); return;
case ts.SyntaxKind.ParenthesizedExpression: this.processParenthesizedExpression(<ts.ParenthesizedExpression>node); return;
case ts.SyntaxKind.TypeAssertionExpression: this.processTypeAssertionExpression(<ts.TypeAssertion>node); return;
case ts.SyntaxKind.VariableDeclarationList: this.processVariableDeclarationList(<ts.VariableDeclarationList><any>node); return;
case ts.SyntaxKind.TrueKeyword:
case ts.SyntaxKind.FalseKeyword: this.processBooleanLiteral(<ts.BooleanLiteral>node); return;
case ts.SyntaxKind.NullKeyword: this.processNullLiteral(<ts.NullLiteral>node); return;
case ts.SyntaxKind.NumericLiteral: this.processNumericLiteral(<ts.NumericLiteral>node); return;
case ts.SyntaxKind.StringLiteral: this.processStringLiteral(<ts.StringLiteral>node); return;
case ts.SyntaxKind.NoSubstitutionTemplateLiteral:
this.processNoSubstitutionTemplateLiteral(<ts.NoSubstitutionTemplateLiteral>node); return;
case ts.SyntaxKind.ObjectLiteralExpression: this.processObjectLiteralExpression(<ts.ObjectLiteralExpression>node); return;
case ts.SyntaxKind.TemplateExpression: this.processTemplateExpression(<ts.TemplateExpression>node); return;
case ts.SyntaxKind.ArrayLiteralExpression: this.processArrayLiteralExpression(<ts.ArrayLiteralExpression>node); return;
case ts.SyntaxKind.RegularExpressionLiteral: this.processRegularExpressionLiteral(<ts.RegularExpressionLiteral>node); return;
case ts.SyntaxKind.ThisKeyword: this.processThisExpression(<ts.ThisExpression>node); return;
case ts.SyntaxKind.SuperKeyword: this.processSuperExpression(<ts.SuperExpression>node); return;
case ts.SyntaxKind.VoidExpression: this.processVoidExpression(<ts.VoidExpression>node); return;
case ts.SyntaxKind.NonNullExpression: this.processNonNullExpression(<ts.NonNullExpression>node); return;
case ts.SyntaxKind.AsExpression: this.processAsExpression(<ts.AsExpression>node); return;
case ts.SyntaxKind.SpreadElement: this.processSpreadElement(<ts.SpreadElement>node); return;
case ts.SyntaxKind.AwaitExpression: this.processAwaitExpression(<ts.AwaitExpression>node); return;
case ts.SyntaxKind.Identifier: this.processIdentifier(<ts.Identifier>node); return;
case ts.SyntaxKind.ComputedPropertyName: this.processComputedPropertyName(<ts.ComputedPropertyName><any>node); return;
}
// TODO: finish it
throw new Error('Method not implemented.');
}
private processDeclaration(node: ts.Declaration): void {
switch (node.kind) {
case ts.SyntaxKind.PropertySignature: this.processPropertyDeclaration(<ts.PropertySignature>node); return;
case ts.SyntaxKind.PropertyDeclaration: this.processPropertyDeclaration(<ts.PropertyDeclaration>node); return;
case ts.SyntaxKind.Parameter: this.processPropertyDeclaration(<ts.ParameterDeclaration>node); return;
case ts.SyntaxKind.MethodSignature: this.processMethodDeclaration(<ts.MethodSignature>node); return;
case ts.SyntaxKind.MethodDeclaration: this.processMethodDeclaration(<ts.MethodDeclaration>node); return;
case ts.SyntaxKind.ConstructSignature: this.processMethodDeclaration(<ts.ConstructorDeclaration>node); return;
case ts.SyntaxKind.Constructor: this.processMethodDeclaration(<ts.ConstructorDeclaration>node); return;
case ts.SyntaxKind.SetAccessor: this.processMethodDeclaration(<ts.MethodDeclaration>node); return;
case ts.SyntaxKind.GetAccessor: this.processMethodDeclaration(<ts.MethodDeclaration>node); return;
case ts.SyntaxKind.FunctionDeclaration: this.processFunctionDeclaration(<ts.FunctionDeclaration>node); return;
case ts.SyntaxKind.IndexSignature: /*TODO: index*/ return;
case ts.SyntaxKind.SemicolonClassElement: /*TODO: index*/ return;
}
// TODO: finish it
throw new Error('Method not implemented.');
}
private processInclude(nodeIn: ts.Declaration | ts.Statement): void {
const node = this.preprocessor.preprocessStatement(<ts.Statement>nodeIn);
switch (node.kind) {
case ts.SyntaxKind.TypeAliasDeclaration: this.processTypeAliasDeclaration(<ts.TypeAliasDeclaration>node); return;
case ts.SyntaxKind.ImportDeclaration: this.processImportDeclaration(<ts.ImportDeclaration>node); return;
default:
return;
}
}
private processForwardDeclaration(nodeIn: ts.Declaration | ts.Statement): void {
const node = this.preprocessor.preprocessStatement(<ts.Statement>nodeIn);
switch (node.kind) {
case ts.SyntaxKind.VariableStatement: this.processVariablesForwardDeclaration(<ts.VariableStatement>node); return;
case ts.SyntaxKind.InterfaceDeclaration:
case ts.SyntaxKind.ClassDeclaration: this.processClassForwardDeclaration(<ts.ClassDeclaration>node); return;
case ts.SyntaxKind.ModuleDeclaration: this.processModuleForwardDeclaration(<ts.ModuleDeclaration>node); return;
case ts.SyntaxKind.EnumDeclaration: this.processEnumForwardDeclaration(<ts.EnumDeclaration>node); return;
default:
return;
}
}
public isTemplate(declaration:
ts.MethodDeclaration | ts.ConstructorDeclaration | ts.ClassDeclaration
| ts.FunctionDeclaration | ts.FunctionExpression) {
if (!declaration) {
return false;
}
if (declaration.typeParameters && declaration.typeParameters.length > 0) {
return true;
}
if (this.isMethodParamsTemplate(declaration)) {
return true;
}
if (this.isClassMemberDeclaration(declaration)) {
if (declaration.parent && declaration.parent.kind === ts.SyntaxKind.ClassDeclaration) {
return this.isTemplate(<any>declaration.parent);
}
}
return false;
}
private isTemplateType(effectiveType: any): boolean {
if (!effectiveType) {
return false;
}
if (effectiveType.kind === ts.SyntaxKind.UnionType) {
return this.resolver.checkUnionType(effectiveType);
}
if (effectiveType.typeName && effectiveType.typeName.text === 'ArrayLike') {
return true;
}
if (effectiveType.typeArguments && effectiveType.typeArguments.length > 0) {
if (effectiveType.typeArguments.some(t => this.isTemplateType(t))) {
return true;
}
}
if (effectiveType.kind === ts.SyntaxKind.FunctionType
&& this.resolver.isTypeParameter(effectiveType.type)) {
return true;
}
if (this.resolver.isTypeAliasUnionType(effectiveType.typeName)) {
return true;
}
}
private isMethodParamsTemplate(declaration: ts.MethodDeclaration | any): boolean {
if (!declaration) {
return false;
}
// if method has union type, it should be treated as generic method
if (!this.isClassMemberDeclaration(declaration)
&& declaration.kind !== ts.SyntaxKind.FunctionDeclaration) {
return false;
}
if (this.isTemplateType(declaration.type)) {
return true;
}
for (const element of declaration.parameters) {
if (element.dotDotDotToken || this.isTemplateType(element.type)) {
return true;
}
}
}
private processImplementation(nodeIn: ts.Declaration | ts.Statement, template?: boolean): void {
const node = this.preprocessor.preprocessStatement(nodeIn);
switch (node.kind) {
case ts.SyntaxKind.ClassDeclaration: this.processClassImplementation(<ts.ClassDeclaration>node, template); return;
case ts.SyntaxKind.ModuleDeclaration: this.processModuleImplementation(<ts.ModuleDeclaration>node, template); return;
case ts.SyntaxKind.PropertyDeclaration:
if (!template && this.isStatic(node)) {
this.processPropertyDeclaration(<ts.PropertyDeclaration>node, true);
}
return;
case ts.SyntaxKind.Constructor:
case ts.SyntaxKind.MethodDeclaration:
case ts.SyntaxKind.GetAccessor:
case ts.SyntaxKind.SetAccessor:
case ts.SyntaxKind.FunctionDeclaration:
if ((template && this.isTemplate(<ts.MethodDeclaration>node))
|| (!template && !this.isTemplate(<ts.MethodDeclaration>node))) {
this.processMethodDeclaration(<ts.MethodDeclaration>node, true);
}
return;
case ts.SyntaxKind.ImportEqualsDeclaration:
if (!template) {
this.processImportEqualsDeclaration(<ts.ImportEqualsDeclaration>node);
}
return;
default:
return;
}
}
private processModuleImplementation(node: ts.ModuleDeclaration, template?: boolean) {
this.scope.push(node);
this.processModuleImplementationInternal(node, template);
this.scope.pop();
}
private processModuleImplementationInternal(node: ts.ModuleDeclaration, template?: boolean) {
this.writer.writeString('namespace ');
this.writer.writeString(node.name.text);
this.writer.writeString(' ');
this.writer.BeginBlock();
if (node.body.kind === ts.SyntaxKind.ModuleBlock) {
const block = <ts.ModuleBlock>node.body;
block.statements.forEach(element => {
this.processImplementation(element, template);
});
} else if (node.body.kind === ts.SyntaxKind.ModuleDeclaration) {
this.processModuleImplementation(node.body, template);
} else {
throw new Error('Not Implemented');
}
this.writer.EndBlock();
}
private processClassImplementation(node: ts.ClassDeclaration, template?: boolean) {
this.scope.push(node);
this.processClassImplementationInternal(node, template);
this.scope.pop();
}
private processClassImplementationInternal(node: ts.ClassDeclaration, template?: boolean) {
if (this.isDeclare(node)) {
return;
}
for (const member of node.members) {
this.processImplementation(member, template);
}
}
private processExpressionStatement(node: ts.ExpressionStatement): void {
this.processExpression(node.expression);
this.writer.EndOfStatement();
}
private fixupParentReferences<T extends ts.Node>(rootNode: T, setParent?: ts.Node): T {
let parent: ts.Node = rootNode;
if (setParent) {
rootNode.parent = setParent;
}
ts.forEachChild(rootNode, visitNode);
return rootNode;
function visitNode(n: ts.Node): void {
// walk down setting parents that differ from the parent we think it should be. This
// allows us to quickly bail out of setting parents for sub-trees during incremental
// parsing
if (n.parent !== parent) {
n.parent = parent;
const saveParent = parent;
parent = n;
ts.forEachChild(n, visitNode);
parent = saveParent;
}
}
}
private transpileTSNode(node: ts.Node, transformText?: (string) => string) {
return this.transpileTSCode(node.getFullText(), transformText);
}
private transpileTSCode(code: string, transformText?: (string) => string) {
const opts = {
module: ts.ModuleKind.CommonJS,
alwaysStrict: false,
noImplicitUseStrict: true,
moduleResolution: ts.ModuleResolutionKind.NodeJs,
target: ts.ScriptTarget.ES5
};
const result = ts.transpileModule(code, { compilerOptions: opts });
let jsText = result.outputText;
if (transformText) {
jsText = transformText(jsText);
}
return this.parseJSCode(jsText);
}
private parseTSCode(jsText: string) {
const opts = {
module: ts.ModuleKind.CommonJS,
alwaysStrict: false,
noImplicitUseStrict: true,
moduleResolution: ts.ModuleResolutionKind.NodeJs,
target: ts.ScriptTarget.ES5
};
const sourceFile = ts.createSourceFile(
this.sourceFileName, jsText, ts.ScriptTarget.ES5, /*setParentNodes */ true, ts.ScriptKind.TS);
// needed to make typeChecker to work properly
(<any>ts).bindSourceFile(sourceFile, opts);
return sourceFile.statements;
}
private bind(node: ts.Statement) {
const opts = {
module: ts.ModuleKind.CommonJS,
alwaysStrict: false,
noImplicitUseStrict: true,
moduleResolution: ts.ModuleResolutionKind.NodeJs,
target: ts.ScriptTarget.ES5
};
const sourceFile = ts.createSourceFile(
this.sourceFileName, '', ts.ScriptTarget.ES5, /*setParentNodes */ true, ts.ScriptKind.TS);
(<any>sourceFile.statements) = [node];
(<any>ts).bindSourceFile(sourceFile, opts);
return sourceFile.statements[0];
}
private parseJSCode(jsText: string) {
const opts = {
module: ts.ModuleKind.CommonJS,
alwaysStrict: false,
noImplicitUseStrict: true,
moduleResolution: ts.ModuleResolutionKind.NodeJs,
target: ts.ScriptTarget.ES5
};
const sourceFile = ts.createSourceFile('partial', jsText, ts.ScriptTarget.ES5, /*setParentNodes */ true);
this.fixupParentReferences(sourceFile);
// needed to make typeChecker to work properly
(<any>ts).bindSourceFile(sourceFile, opts);
return sourceFile.statements;
}
private processTSNode(node: ts.Node, transformText?: (string) => string) {
const statements = this.transpileTSNode(node, transformText);
if (statements && statements.length === 1 && (<any>statements[0]).expression) {
this.processExpression((<any>statements[0]).expression);
return;
}
statements.forEach(s => {
this.processStatementInternal(s);
});
}
private processTSCode(code: string, parse?: any) {
const statements = (!parse) ? this.transpileTSCode(code) : this.parseTSCode(code);
statements.forEach(s => {
this.processStatementInternal(s);
});
}
private processJSCode(code: string) {
const statements = this.parseJSCode(code);
statements.forEach(s => {
this.processStatementInternal(s);
});
}
private processLabeledStatement(node: ts.LabeledStatement): void {
this.processExpression(node.label);
this.writer.writeStringNewLine(':');
this.processStatement(node.statement);
}
private processTryStatement(node: ts.TryStatement): void {
let anyCase = false;
if (node.finallyBlock) {
this.writer.BeginBlock();
const finallyName = `__finally${node.finallyBlock.getFullStart()}_${node.finallyBlock.getEnd()}`;
this.writer.writeString(`utils::finally ${finallyName}(`);
const newArrowFunctions =
ts.createArrowFunction(
undefined,
undefined,
undefined,
undefined,
undefined,
node.finallyBlock);
(<any>newArrowFunctions).__lambda_by_reference = true;
this.processFunctionExpression(newArrowFunctions);
this.writer.cancelNewLine();
this.writer.writeString(')');
this.writer.EndOfStatement();
}
this.writer.writeStringNewLine('try');
this.writer.BeginBlock();
node.tryBlock.statements.forEach(element => this.processStatement(element));
this.writer.EndBlock();
if (node.catchClause) {
this.writer.writeString('catch (const ');
if (node.catchClause.variableDeclaration.type) {
this.processType(node.catchClause.variableDeclaration.type);
} else {
this.writer.writeString('any');
}
this.writer.writeString('& ');
if (node.catchClause.variableDeclaration.name.kind === ts.SyntaxKind.Identifier) {
this.processVariableDeclarationOne(
<ts.Identifier>(node.catchClause.variableDeclaration.name),
node.catchClause.variableDeclaration.initializer,
node.catchClause.variableDeclaration.type);
} else {
throw new Error('Method not implemented.');
}
this.writer.writeStringNewLine(')');
this.processStatement(node.catchClause.block);
anyCase = true;
}
if (!anyCase) {
this.writer.writeStringNewLine('catch (...)');
this.writer.BeginBlock();
this.writer.writeString('throw');
this.writer.EndOfStatement();
this.writer.EndBlock();
}
if (node.finallyBlock) {
this.writer.EndBlock();
}
}
private processThrowStatement(node: ts.ThrowStatement): void {
this.writer.writeString('throw');
if (node.expression) {
this.writer.writeString(' any(');
this.processExpression(node.expression);
this.writer.writeString(')');
}
this.writer.EndOfStatement();
}
private processTypeOfExpression(node: ts.TypeOfExpression): void {
this.writer.writeString('type_of(');
this.processExpression(node.expression);
this.writer.writeString(')');
}
private processDebuggerStatement(node: ts.DebuggerStatement): void {
this.writer.writeString('__asm { int 3 }');
}
private processEnumForwardDeclaration(node: ts.EnumDeclaration): void {
this.scope.push(node);
this.processEnumForwardDeclarationInternal(node);
this.scope.pop();
}
private processEnumForwardDeclarationInternal(node: ts.EnumDeclaration): void {
if (!this.isHeader()) {
return;
}
this.writer.writeString('enum struct ');
this.processIdentifier(node.name);
this.writer.EndOfStatement();
}
private processEnumDeclaration(node: ts.EnumDeclaration): void {
this.scope.push(node);
this.processEnumDeclarationInternal(node);
this.scope.pop();
}
private processEnumDeclarationInternal(node: ts.EnumDeclaration): void {
if (!this.isHeader()) {
return;
}
if (this.isDeclare(node)) {
return;
}
/*
const properties = [];
let value = 0;
for (const member of node.members) {
if (member.initializer) {
switch (member.initializer.kind) {
case ts.SyntaxKind.NumericLiteral:
value = parseInt((<ts.NumericLiteral>member.initializer).text, 10);
break;
default:
throw new Error('Not Implemented');
}
} else {
value++;
}
const namedProperty = ts.createPropertyAssignment(
member.name,
ts.createNumericLiteral(value.toString()));
const valueProperty = ts.createPropertyAssignment(
ts.createNumericLiteral(value.toString()),
ts.createStringLiteral((<ts.Identifier>member.name).text));
properties.push(namedProperty);
properties.push(valueProperty);
}
const enumLiteralObject = ts.createObjectLiteral(properties);
const varDecl = ts.createVariableDeclaration(node.name, undefined, enumLiteralObject);
const enumDeclare = ts.createVariableStatement([], [varDecl]);
this.processStatement(this.fixupParentReferences(enumDeclare, node));
*/
this.writer.writeString('enum struct ');
this.processIdentifier(node.name);
this.writer.writeString(' ');
this.writer.BeginBlock();
let next = false;
for (const member of node.members) {
if (next) {
this.writer.writeString(', ');
}
if (member.name.kind === ts.SyntaxKind.Identifier) {
this.processExpression(member.name);
} else {
throw new Error('Not Implemented');
}
if (member.initializer) {
this.writer.writeString(' = ');
this.processExpression(member.initializer);
}
next = true;
}
this.writer.EndBlock();
this.writer.EndOfStatement();
}
private hasAccessModifier(modifiers: ts.ModifiersArray) {
if (!modifiers) {
return false;
}
return modifiers
.some(m => m.kind === ts.SyntaxKind.PrivateKeyword
|| m.kind === ts.SyntaxKind.ProtectedKeyword
|| m.kind === ts.SyntaxKind.PublicKeyword);
}
private processVariablesForwardDeclaration(node: ts.VariableStatement) {
if (this.processVariableDeclarationList(node.declarationList, true)) {
this.writer.EndOfStatement();
}
}
private processClassForwardDeclaration(node: ts.ClassDeclaration) {
this.scope.push(node);
this.processClassForwardDeclarationInternal(node);
this.scope.pop();
this.writer.EndOfStatement();
}
private processClassForwardDeclarationInternal(node: ts.ClassDeclaration | ts.InterfaceDeclaration) {
let next = false;
if (node.typeParameters) {
this.writer.writeString('template <');
node.typeParameters.forEach(type => {
if (next) {
this.writer.writeString(', ');
}
this.processType(type);
next = true;
});
this.writer.writeStringNewLine('>');
}
this.writer.writeString('class ');
this.processIdentifier(node.name);
}
private processModuleForwardDeclaration(node: ts.ModuleDeclaration, template?: boolean) {
this.scope.push(node);
this.processModuleForwardDeclarationInternal(node, template);
this.scope.pop();
}
private processModuleForwardDeclarationInternal(node: ts.ModuleDeclaration, template?: boolean) {
this.writer.writeString('namespace ');
this.writer.writeString(node.name.text);
this.writer.writeString(' ');
this.writer.BeginBlock();
if (node.body.kind === ts.SyntaxKind.ModuleBlock) {
const block = <ts.ModuleBlock>node.body;
block.statements.forEach(element => {
this.processForwardDeclaration(element);
});
} else if (node.body.kind === ts.SyntaxKind.ModuleDeclaration) {
this.processModuleForwardDeclaration(node.body, template);
} else {
throw new Error('Not Implemented');
}
this.writer.EndBlock();
}
private isInBaseClass(baseClass: ts.TypeNode, identifier: ts.Identifier): boolean {
const effectiveSymbol = (<any>baseClass).symbol || ((<any>baseClass).exprName).symbol;
if (!effectiveSymbol
|| !effectiveSymbol.valueDeclaration
|| !effectiveSymbol.valueDeclaration.heritageClauses) {
return false;
}
const hasInBase = effectiveSymbol.valueDeclaration
.heritageClauses.some(hc => hc.types.some(t => t.expression.text === identifier.text));
return hasInBase;
}
private processClassDeclaration(node: ts.ClassDeclaration | ts.InterfaceDeclaration) {
this.scope.push(node);
this.processClassDeclarationInternal(node);
this.scope.pop();
}
private processClassDeclarationInternal(node: ts.ClassDeclaration | ts.InterfaceDeclaration): void {
if (!this.isHeader()) {
return;
}
this.processClassForwardDeclarationInternal(node);
let next = false;
if (node.heritageClauses) {
let baseClass;
node.heritageClauses.forEach(heritageClause => {
heritageClause.types.forEach(type => {
if (type.expression.kind === ts.SyntaxKind.Identifier) {
const identifier = <ts.Identifier>type.expression;
if (baseClass && this.isInBaseClass(baseClass, identifier)) {
return;
}
if (!baseClass) {
baseClass = this.resolver.getOrResolveTypeOfAsTypeNode(identifier);
}
if (next) {
this.writer.writeString(', ');
} else {
this.writer.writeString(' : ');
}
this.writer.writeString('public ');
this.writer.writeString(identifier.text);
this.processTemplateArguments(type, true);
next = true;
} else {
/* TODO: finish xxx.yyy<zzz> */
}
});
});
} else {
this.writer.writeString(' : public object');
}
this.writer.writeString(', public std::enable_shared_from_this<');
this.processIdentifier(node.name);
this.processTemplateParameters(<ts.ClassDeclaration>node);
this.writer.writeString('>');
this.writer.writeString(' ');
this.writer.BeginBlock();
this.writer.DecreaseIntent();
this.writer.writeString('public:');
this.writer.IncreaseIntent();
this.writer.writeStringNewLine();
this.writer.writeString('using std::enable_shared_from_this<');
this.processIdentifier(node.name);
this.processTemplateParameters(<ts.ClassDeclaration>node);
this.writer.writeStringNewLine('>::shared_from_this;');
/*
if (!node.heritageClauses) {
// to make base class polymorphic
this.writer.writeStringNewLine('virtual void dummy() {};');
}
*/
// declare all private parameters of constructors
for (const constructor of <ts.ConstructorDeclaration[]>(<ts.ClassDeclaration>node)
.members.filter(m => m.kind === ts.SyntaxKind.Constructor)) {
for (const fieldAsParam of constructor.parameters.filter(p => this.hasAccessModifier(p.modifiers))) {
this.processDeclaration(fieldAsParam);
}
}
const propertyWithThis = (m: ts.Node) => {
return m.kind === ts.SyntaxKind.PropertyDeclaration && this.hasThis(m);
};
for (const member of (<any[]><any>node.members).filter(m => !propertyWithThis(m))) {
this.processDeclaration(member);
}
for (const member of (<any[]><any>node.members).filter(m => propertyWithThis(m))) {
this.processDeclaration(member);
}
this.writer.cancelNewLine();
this.writer.cancelNewLine();
this.writer.EndBlock();
this.writer.EndOfStatement();
this.writer.writeStringNewLine();
if (node.modifiers && node.modifiers.some(m => m.kind === ts.SyntaxKind.DefaultKeyword)) {
this.writer.writeString('using _default = ');
this.processIdentifier(node.name);
this.processTemplateParameters(<ts.ClassDeclaration>node);
this.writer.writeStringNewLine(';');
}
}
private processPropertyDeclaration(node: ts.PropertyDeclaration | ts.PropertySignature | ts.ParameterDeclaration,
implementationMode?: boolean): void {
if (!implementationMode) {
this.processModifiers(node.modifiers);
}
const effectiveType = node.type
|| this.resolver.getOrResolveTypeOfAsTypeNode(node.initializer);
this.processPredefineType(effectiveType);
this.processType(effectiveType);
this.writer.writeString(' ');
if (node.name.kind === ts.SyntaxKind.Identifier) {
if (implementationMode) {
// write class name
const classNode = this.scope[this.scope.length - 1];
if (classNode.kind === ts.SyntaxKind.ClassDeclaration) {
this.writer.writeString((<ts.ClassDeclaration>classNode).name.text);
this.writer.writeString('::');
} else {
throw new Error('Not Implemented');
}
}
this.processExpression(node.name);
} else {
throw new Error('Not Implemented');
}
const isStatic = this.isStatic(node);
if (node.initializer && (implementationMode && isStatic || !isStatic)) {
this.writer.writeString(' = ');
this.processExpression(node.initializer);
}
this.writer.EndOfStatement();
this.writer.writeStringNewLine();
}
private processMethodDeclaration(node: ts.MethodDeclaration | ts.MethodSignature | ts.ConstructorDeclaration,
implementationMode?: boolean): void {
const skip = this.processFunctionDeclaration(<ts.FunctionDeclaration><any>node, implementationMode);
if (implementationMode) {
if (!skip) {
this.writer.writeStringNewLine();
}
} else {
this.writer.EndOfStatement();
}
}
private processModifiers(modifiers: ts.NodeArray<ts.Modifier>) {
if (!modifiers) {
return;
}
modifiers.forEach(modifier => {
switch (modifier.kind) {
case ts.SyntaxKind.StaticKeyword:
this.writer.writeString('static ');
break;
}
});
}
private processTypeAliasDeclaration(node: ts.TypeAliasDeclaration): void {
if (this.isDeclare(node)) {
return;
}
if (node.type.kind === ts.SyntaxKind.ImportType) {
const typeLiteral = <ts.ImportTypeNode>node.type;
const argument = typeLiteral.argument;
if (argument.kind === ts.SyntaxKind.LiteralType) {
const literal = <ts.LiteralTypeNode>argument;
this.writer.writeString('#include \"');
this.writer.writeString((<any>literal.literal).text);
this.writer.writeStringNewLine('.h\"');
} else {
throw new Error('Not Implemented');
}
return;
}
const name = node.name.text;
// remove NULL from union types, do we need to remove "undefined" as well?
let type = node.type;
if (type.kind === ts.SyntaxKind.AnyKeyword
|| type.kind === ts.SyntaxKind.NumberKeyword && this.embeddedCPPTypes.some((e) => e === name)) {
return;
}
this.processPredefineType(type);
if (node.type.kind === ts.SyntaxKind.UnionType) {
const unionType = <ts.UnionTypeNode>type;
const filtered = unionType.types.filter(t => t.kind !== ts.SyntaxKind.NullKeyword && t.kind !== ts.SyntaxKind.UndefinedKeyword);
if (filtered.length === 1) {
type = filtered[0];
}
} else if (node.type.kind === ts.SyntaxKind.ConditionalType) {
const conditionType = <ts.ConditionalTypeNode>type;
type = conditionType.checkType;
} else if (node.type.kind === ts.SyntaxKind.MappedType) {
if (node.typeParameters && node.typeParameters[0]) {
type = <any>{ kind: ts.SyntaxKind.TypeParameter, name: ts.createIdentifier((<any>(node.typeParameters[0])).symbol.name) };
}
}
if (node.typeParameters) {
this.processTemplateParams(node);
this.writer.writeString('using ');
this.processExpression(node.name);
this.writer.writeString(' = ');
this.processType(type, false, true, true);
} else {
// default typedef
this.writer.writeString('typedef ');
this.processType(type, false, true, true);
this.writer.writeString(' ');
this.processExpression(node.name);
}
this.writer.EndOfStatement();
this.writer.writeStringNewLine();
}
private processModuleDeclaration(node: ts.ModuleDeclaration): void {
this.writer.writeString('namespace ');
this.processExpression(node.name);
this.writer.writeString(' ');
this.writer.BeginBlock();
if (node.body.kind === ts.SyntaxKind.ModuleBlock) {
const block = <ts.ModuleBlock>node.body;
block.statements.forEach(s => {
if (this.isDeclarationStatement(s) || this.isVariableStatement(s)) {
this.processStatement(s);
} else if (this.isNamespaceStatement(s)) {
this.processModuleDeclaration(<ts.ModuleDeclaration>s);
}
});
} else if (node.body.kind === ts.SyntaxKind.ModuleDeclaration) {
this.processModuleDeclaration(node.body);
} else {
throw new Error('Not Implemented');
}
this.writer.EndBlock();
}
private processNamespaceDeclaration(node: ts.NamespaceDeclaration): void {
this.processModuleDeclaration(node);
}
private processModuleImplementationInMain(node: ts.ModuleDeclaration | ts.NamespaceDeclaration): void {
if (node.body.kind === ts.SyntaxKind.ModuleBlock) {
const block = <ts.ModuleBlock>node.body;
block.statements.forEach(s => {
if (!this.isDeclarationStatement(s) && !this.isVariableStatement(s)) {
this.processStatement(s);
} else if (this.isNamespaceStatement(s)) {
this.processModuleImplementationInMain(<ts.ModuleDeclaration>s);
}
});
} else if (node.body.kind === ts.SyntaxKind.ModuleDeclaration) {
this.processModuleImplementationInMain(node.body);
} else {
throw new Error('Not Implemented');
}
}
private processModuleVariableStatements(node: ts.ModuleDeclaration | ts.NamespaceDeclaration): void {
if (node.body.kind === ts.SyntaxKind.ModuleBlock) {
const block = <ts.ModuleBlock>node.body;
block.statements.forEach(s => {
if (this.isVariableStatement(s)) {
this.processStatement(s);
} else if (this.isNamespaceStatement(s)) {
this.processModuleVariableStatements(<ts.ModuleDeclaration>s);
}
});
} else if (node.body.kind === ts.SyntaxKind.ModuleDeclaration) {
this.processModuleVariableStatements(node.body);
} else {
throw new Error('Not Implemented');
}
}
private processImportEqualsDeclaration(node: ts.ImportEqualsDeclaration): void {
const typeOfExpr = this.resolver.getOrResolveTypeOf(node.moduleReference);
if (typeOfExpr && typeOfExpr.symbol &&
(typeOfExpr.symbol.valueDeclaration.kind === ts.SyntaxKind.ModuleDeclaration
|| typeOfExpr.symbol.valueDeclaration.kind === ts.SyntaxKind.NamespaceExportDeclaration)) {
this.writer.writeString('namespace ');
} else {
this.writer.writeString('using ');
}
this.processExpression(node.name);
this.writer.writeString(' = ');
this.processModuleReferenceOrEntityName(node.moduleReference);
this.writer.EndOfStatement();
}
private processModuleReferenceOrEntityName(node: ts.ModuleReference | ts.EntityName) {
switch (node.kind) {
case ts.SyntaxKind.Identifier: this.processIdentifier(node); break;
case ts.SyntaxKind.QualifiedName: this.processQualifiedName(node); break;
case ts.SyntaxKind.ExternalModuleReference: this.processExpression(node.expression); break;
}
}
private processQualifiedName(node: ts.QualifiedName) {
this.processModuleReferenceOrEntityName(node.left);
this.writer.writeString('::');
this.processExpression(node.right);
}
private processExportDeclaration(node: ts.ExportDeclaration): void {
/* TODO: */
}
private processImportDeclaration(node: ts.ImportDeclaration): void {
if (node.moduleSpecifier.kind !== ts.SyntaxKind.StringLiteral) {
return;
}
this.writer.writeString('#include \"');
if (node.moduleSpecifier.kind === ts.SyntaxKind.StringLiteral) {
const ident = <ts.StringLiteral>node.moduleSpecifier;
this.writer.writeString(ident.text);
this.writer.writeString('.h');
}
this.writer.writeStringNewLine('\"');
if (node.importClause) {
if (node.importClause.name && node.importClause.name.kind === ts.SyntaxKind.Identifier) {
this.writer.writeString('using ');
this.processExpression(node.importClause.name);
this.writer.writeStringNewLine(' = _default;');
}
if (node.importClause.namedBindings
&& node.importClause.namedBindings.kind === ts.SyntaxKind.NamedImports) {
for (const binding of (<ts.NamedImports>node.importClause.namedBindings).elements.filter(e => e.propertyName)) {
this.writer.writeString('using ');
this.processExpression(binding.name);
this.writer.writeString(' = ');
this.processExpression(binding.propertyName);
this.writer.writeStringNewLine(';');
}
}
}
}
private processVariableDeclarationList(declarationList: ts.VariableDeclarationList, forwardDeclaration?: boolean): boolean {
if (this.isDeclare(declarationList.parent) && !forwardDeclaration) {
return false;
}
const scopeItem = this.scope[this.scope.length - 1];
const autoAllowed =
scopeItem.kind !== ts.SyntaxKind.SourceFile
&& scopeItem.kind !== ts.SyntaxKind.ClassDeclaration
&& scopeItem.kind !== ts.SyntaxKind.ModuleDeclaration
&& scopeItem.kind !== ts.SyntaxKind.NamespaceExportDeclaration;
const forceCaptureRequired = autoAllowed && declarationList.declarations.some(d => d && (<any>d).__requireCapture);
if (!((<any>declarationList).__ignore_type)) {
if (forwardDeclaration) {
this.writer.writeString('extern ');
}
const firstType = declarationList.declarations.filter(d => d.type)[0]?.type;
const firstInitializer = declarationList.declarations.filter(d => d.initializer)[0]?.initializer;
const effectiveType = firstType || this.resolver.getOrResolveTypeOfAsTypeNode(firstInitializer);
const useAuto = autoAllowed && !!(firstInitializer);
this.processPredefineType(effectiveType);
if (!forceCaptureRequired) {
this.processType(effectiveType, useAuto);
} else {
if (useAuto) {
this.writer.writeString('shared');
} else {
this.writer.writeString('shared<');
this.processType(effectiveType, useAuto);
this.writer.writeString('>');
}
}
this.writer.writeString(' ');
}
const next = { next: false };
let result = false;
declarationList.declarations.forEach(d => {
result =
this.processVariableDeclarationOne(
d.name, d.initializer, d.type, next, forwardDeclaration, forceCaptureRequired)
|| result;
} );
return result;
}
private processVariableDeclarationOne(
name: ts.BindingName,
initializer: ts.Expression,
type: ts.TypeNode,
next?: { next: boolean },
forwardDeclaration?: boolean,
forceCaptureRequired?: boolean): boolean {
if (next && next.next) {
this.writer.writeString(', ');
}
if (name.kind === ts.SyntaxKind.ArrayBindingPattern) {
this.writer.writeString('[');
let hasNext = false;
name.elements.forEach(element => {
if (hasNext) {
this.writer.writeString(', ');
}
hasNext = true;
this.writer.writeString((<ts.Identifier>(<ts.BindingElement>element).name).text);
});
this.writer.writeString(']');
} else if (name.kind === ts.SyntaxKind.Identifier) {
this.writer.writeString(name.text);
} else {
throw new Error('Not implemented!');
}
if (!forwardDeclaration) {
if (initializer) {
this.writer.writeString(' = ');
this.processExpression(initializer);
} else {
if (type && type.kind === ts.SyntaxKind.TupleType) {
this.processDefaultValue(type);
}
}
}
if (next) {
next.next = true;
}
return true;
}
private processVariableStatement(node: ts.VariableStatement): void {
const anyVal = this.processVariableDeclarationList(node.declarationList);
if (anyVal) {
this.writer.EndOfStatement();
}
}
private processPredefineType(typeIn: ts.TypeNode | ts.ParameterDeclaration | ts.TypeParameterDeclaration | ts.Expression,
auto: boolean = false): void {
if (auto) {
return;
}
let type = typeIn;
if (typeIn && typeIn.kind === ts.SyntaxKind.LiteralType) {
type = (<ts.LiteralTypeNode>typeIn).literal;
}
switch (type && type.kind) {
case ts.SyntaxKind.ArrayType:
const arrayType = <ts.ArrayTypeNode>type;
this.processPredefineType(arrayType.elementType, false);
break;
case ts.SyntaxKind.TupleType:
const tupleType = <ts.TupleTypeNode>type;
tupleType.elementTypes.forEach(element => {
this.processPredefineType(element, false);
});
break;
case ts.SyntaxKind.TypeReference:
const typeReference = <ts.TypeReferenceNode>type;
if (typeReference.typeArguments) {
typeReference.typeArguments.forEach(element => {
this.processPredefineType(element, false);
});
}
break;
case ts.SyntaxKind.Parameter:
const parameter = <ts.ParameterDeclaration>type;
if (parameter.name.kind === ts.SyntaxKind.Identifier) {
this.processPredefineType(parameter.type);
} else {
throw new Error('Not Implemented');
}
break;
case ts.SyntaxKind.FunctionType:
const functionType = <ts.FunctionTypeNode>type;
this.processPredefineType(functionType.type);
if (functionType.parameters) {
functionType.parameters.forEach(element => {
this.processPredefineType(element);
});
}
break;
case ts.SyntaxKind.UnionType:
/*
const unionType = <ts.UnionTypeNode>type;
const unionTypes = unionType.types
.filter(f => f.kind !== ts.SyntaxKind.NullKeyword && f.kind !== ts.SyntaxKind.UndefinedKeyword);
if (this.typesAreNotSame(unionTypes)) {
unionTypes.forEach((element, i) => {
this.processPredefineType(element);
});
this.processType(type, undefined, undefined, undefined, true);
this.writer.EndOfStatement();
} else {
this.processPredefineType(unionTypes[0]);
}
*/
break;
}
}
private compareTypes(t1: ts.TypeNode, t2: ts.TypeNode): boolean {
const kind1 = t1.kind === ts.SyntaxKind.LiteralType ? (<ts.LiteralTypeNode>t1).literal.kind : t1.kind;
const kind2 = t2.kind === ts.SyntaxKind.LiteralType ? (<ts.LiteralTypeNode>t2).literal.kind : t2.kind;
return kind1 === kind2;
}
private typesAreNotSame(unionTypes: ts.TypeNode[]): boolean {
if (unionTypes.length <= 1) {
return false;
}
const firstType = unionTypes[0];
const same = unionTypes.slice(1).every(t => this.compareTypes(t, firstType));
return !same;
}
private processType(typeIn: ts.TypeNode | ts.ParameterDeclaration | ts.TypeParameterDeclaration | ts.Expression,
auto: boolean = false, skipPointerInType: boolean = false, noTypeName: boolean = false,
implementingUnionType: boolean = false): void {
if (auto) {
this.writer.writeString('auto');
return;
}
let type = typeIn;
if (typeIn && typeIn.kind === ts.SyntaxKind.LiteralType) {
type = (<ts.LiteralTypeNode>typeIn).literal;
}
let next;
switch (type && type.kind) {
case ts.SyntaxKind.TrueKeyword:
case ts.SyntaxKind.FalseKeyword:
case ts.SyntaxKind.BooleanKeyword:
this.writer.writeString('boolean');
break;
case ts.SyntaxKind.NumericLiteral:
case ts.SyntaxKind.NumberKeyword:
this.writer.writeString('js::number');
break;
case ts.SyntaxKind.StringLiteral:
case ts.SyntaxKind.StringKeyword:
this.writer.writeString('string');
break;
case ts.SyntaxKind.TypeLiteral:
case ts.SyntaxKind.ObjectLiteralExpression:
this.writer.writeString('object');
break;
case ts.SyntaxKind.ArrayType:
const arrayType = <ts.ArrayTypeNode>type;
this.writer.writeString('array<');
if (arrayType.elementType && arrayType.elementType.kind !== ts.SyntaxKind.UndefinedKeyword) {
this.processType(arrayType.elementType, false);
} else {
this.writer.writeString('any');
}
this.writer.writeString('>');
break;
case ts.SyntaxKind.TupleType:
const tupleType = <ts.TupleTypeNode>type;
this.writer.writeString('std::tuple<');
next = false;
tupleType.elementTypes.forEach(element => {
if (next) {
this.writer.writeString(', ');
}
this.processType(element, false);
next = true;
});
this.writer.writeString('>');
break;
case ts.SyntaxKind.TypeReference:
const typeReference = <ts.TypeReferenceNode>type;
const typeInfo = this.resolver.getOrResolveTypeOf(type);
const isTypeAlias = ((typeInfo && this.resolver.checkTypeAlias(typeInfo.aliasSymbol))
|| this.resolver.isTypeAlias((<any>type).typeName)) && !this.resolver.isThisType(typeInfo);
// detect if pointer
const isEnum = this.isEnum(typeReference);
const isArray = this.resolver.isArrayType(typeInfo);
const skipPointerIf =
(typeInfo && (<any>typeInfo).symbol && (<any>typeInfo).symbol.name === '__type')
|| (typeInfo && (<any>typeInfo).primitiveTypesOnly)
|| (typeInfo && (<any>typeInfo).intrinsicName === 'number')
|| this.resolver.isTypeFromSymbol(typeInfo, ts.SyntaxKind.TypeParameter)
|| this.resolver.isTypeFromSymbol(typeInfo, ts.SyntaxKind.EnumMember)
|| this.resolver.isTypeFromSymbol(typeInfo, ts.SyntaxKind.EnumDeclaration)
|| this.resolver.isTypeFromSymbol((<any>type).typeName, ts.SyntaxKind.EnumDeclaration)
|| isEnum
|| skipPointerInType
|| isTypeAlias
|| isArray;
if (!skipPointerIf) {
this.writer.writeString('std::shared_ptr<');
}
// writing namespace
if (this.isWritingMain) {
const symbol = (<any>typeReference.typeName).symbol || typeInfo && typeInfo.symbol;
if (symbol) {
const symbolDecl = symbol.valueDeclaration || symbol.declarations[0];
if (symbolDecl) {
let parent = symbolDecl.parent;
if (parent) {
parent = parent.parent;
}
if (parent) {
const symbolNamespace = parent.symbol;
if (symbolNamespace) {
const valDeclNamespace = symbolNamespace.valueDeclaration;
if (valDeclNamespace && valDeclNamespace.kind !== ts.SyntaxKind.SourceFile) {
this.processType(valDeclNamespace);
this.writer.writeString('::');
}
}
}
}
}
}
if ((<any>typeReference.typeName).symbol
&& (<any>typeReference.typeName).symbol.parent
&& (<any>typeReference.typeName).symbol.parent.valueDeclaration.kind !== ts.SyntaxKind.SourceFile) {
this.processType((<any>typeReference.typeName).symbol.parent.valueDeclaration);
this.writer.writeString('::');
}
if (isArray) {
this.writer.writeString('array');
} else {
this.writeTypeName(typeReference);
}
if (typeReference.typeArguments) {
this.writer.writeString('<');
let next1 = false;
typeReference.typeArguments.forEach(element => {
if (next1) {
this.writer.writeString(', ');
}
this.processType(element, false);
next1 = true;
});
this.writer.writeString('>');
}
if (!skipPointerIf) {
this.writer.writeString('>');
}
break;
case ts.SyntaxKind.TypeParameter:
const typeParameter = <ts.TypeParameterDeclaration>type;
if (typeParameter.name.kind === ts.SyntaxKind.Identifier) {
if (!noTypeName) {
this.writer.writeString('typename ');
}
this.writer.writeString(typeParameter.name.text);
} else {
throw new Error('Not Implemented');
}
break;
case ts.SyntaxKind.Parameter:
const parameter = <ts.ParameterDeclaration>type;
if (parameter.name.kind === ts.SyntaxKind.Identifier) {
this.processType(parameter.type);
} else {
throw new Error('Not Implemented');
}
break;
case ts.SyntaxKind.FunctionType:
const functionType = <ts.FunctionTypeNode>type;
this.writer.writeString('std::function<');
this.processType(functionType.type);
this.writer.writeString('(');
if (functionType.parameters) {
next = false;
functionType.parameters.forEach(element => {
if (next) {
this.writer.writeString(', ');
}
this.processType(element);
next = true;
});
} else {
this.writer.writeString('void');
}
this.writer.writeString(')>');
break;
case ts.SyntaxKind.VoidKeyword:
this.writer.writeString('void');
break;
case ts.SyntaxKind.AnyKeyword:
this.writer.writeString('any');
break;
case ts.SyntaxKind.NullKeyword:
this.writer.writeString('std::nullptr_t');
break;
case ts.SyntaxKind.UndefinedKeyword:
this.writer.writeString('undefined_t');
break;
case ts.SyntaxKind.UnionType:
/*
const unionType = <ts.UnionTypeNode>type;
const unionTypes = unionType.types
.filter(f => f.kind !== ts.SyntaxKind.NullKeyword && f.kind !== ts.SyntaxKind.UndefinedKeyword);
if (this.typesAreNotSame(unionTypes)) {
const pos = type.pos >= 0 ? type.pos : 0;
const end = type.end >= 0 ? type.end : 0;
const unionName = `__union${pos}_${end}`;
if (implementingUnionType) {
this.writer.writeString('union ');
this.writer.writeString(unionName);
this.writer.writeString(' ');
this.writer.BeginBlock();
this.writer.writeStringNewLine(`${unionName}(std::nullptr_t v_) {}`);
unionTypes.forEach((element, i) => {
this.processType(element);
this.writer.writeString(` v${i}`);
this.writer.EndOfStatement();
this.writer.cancelNewLine();
this.writer.writeString(` ${unionName}(`);
this.processType(element);
this.writer.writeStringNewLine(` v_) : v${i}(v_) {}`);
});
this.writer.EndBlock();
this.writer.cancelNewLine();
} else {
this.writer.writeString(unionName);
}
} else {
this.processType(unionTypes[0]);
}
*/
this.writer.writeString(auto ? 'auto' : 'any');
break;
case ts.SyntaxKind.ModuleDeclaration:
if ((<any>type).symbol
&& (<any>type).symbol.parent
&& (<any>type).symbol.parent.valueDeclaration.kind !== ts.SyntaxKind.SourceFile) {
this.processType((<any>type).symbol.parent.valueDeclaration);
this.writer.writeString('::');
}
const moduleDeclaration = <ts.ModuleDeclaration><any>type;
this.writer.writeString(moduleDeclaration.name.text);
break;
case ts.SyntaxKind.TypeQuery:
const exprName = (<any>type).exprName;
if ((<any>exprName).symbol
&& (<any>exprName).symbol.parent
&& (<any>exprName).symbol.parent.valueDeclaration.kind !== ts.SyntaxKind.SourceFile) {
this.processType((<any>exprName).symbol.parent.valueDeclaration);
this.writer.writeString('::');
}
this.writer.writeString(exprName.text);
break;
default:
this.writer.writeString(auto ? 'auto' : 'any');
break;
}
}
private writeTypeName(typeReference: ts.TypeReferenceNode) {
const entityProcess = (entity: ts.EntityName) => {
if (entity.kind === ts.SyntaxKind.Identifier) {
this.writer.writeString(entity.text);
} else if (entity.kind === ts.SyntaxKind.QualifiedName) {
entityProcess(entity.left);
if (!this.resolver.isTypeFromSymbol(entity.left, ts.SyntaxKind.EnumDeclaration)) {
this.writer.writeString('::');
this.writer.writeString(entity.right.text);
}
} else {
throw new Error('Not Implemented');
}
};
entityProcess(typeReference.typeName);
}
private isEnum(typeReference: ts.TypeReferenceNode) {
let isEnum = false;
const entityProcessCheck = (entity: ts.EntityName) => {
if (entity.kind === ts.SyntaxKind.QualifiedName) {
entityProcessCheck(entity.left);
isEnum = this.resolver.isTypeFromSymbol(entity.left, ts.SyntaxKind.EnumDeclaration);
}
};
entityProcessCheck(typeReference.typeName);
return isEnum;
}
private processDefaultValue(type: ts.TypeNode): void {
switch (type.kind) {
case ts.SyntaxKind.BooleanKeyword:
this.writer.writeString('false');
break;
case ts.SyntaxKind.NumberKeyword:
this.writer.writeString('0');
break;
case ts.SyntaxKind.StringKeyword:
this.writer.writeString('STR("")');
break;
case ts.SyntaxKind.ArrayType:
this.writer.writeString('{}');
break;
case ts.SyntaxKind.TupleType:
const tupleType = <ts.TupleTypeNode>type;
this.writer.writeString('{');
let next = false;
tupleType.elementTypes.forEach(element => {
if (next) {
this.writer.writeString(', ');
}
this.processDefaultValue(element);
next = true;
});
this.writer.writeString('}');
break;
case ts.SyntaxKind.TypeReference:
this.writer.writeString('{}');
break;
default:
this.writer.writeString('any');
break;
}
}
private processFunctionExpression(
node: ts.FunctionExpression | ts.ArrowFunction | ts.FunctionDeclaration | ts.MethodDeclaration
| ts.ConstructorDeclaration | ts.GetAccessorDeclaration | ts.SetAccessorDeclaration,
implementationMode?: boolean): boolean {
this.scope.push(node);
const result = this.processFunctionExpressionInternal(node, implementationMode);
this.scope.pop();
return result;
}
private processFunctionExpressionInternal(
node: ts.FunctionExpression | ts.ArrowFunction | ts.FunctionDeclaration | ts.MethodDeclaration
| ts.ConstructorDeclaration | ts.GetAccessorDeclaration | ts.SetAccessorDeclaration,
implementationMode?: boolean): boolean {
if (implementationMode && this.isDeclare(node)) {
return true;
}
// skip function declaration as union
let noBody = false;
if (!node.body
|| ((<any>node).body.statements
&& (<any>node).body.statements.length === 0
&& ((<any>node).body.statements).isMissingList)) {
// function without body;
if ((<any>node).nextContainer
&& node.kind === (<any>node).nextContainer.kind
&& (<any>node).name.text === (<any>node).nextContainer.name.text) {
return true;
}
noBody = true;
}
const isAbstract = this.isAbstract(node)
|| (<any>node).kind === ts.SyntaxKind.MethodSignature && node.parent.kind === ts.SyntaxKind.InterfaceDeclaration;
if (implementationMode && isAbstract) {
// ignore declarations
return true;
}
const noReturnStatement = !this.hasReturn(node);
const noReturn = !this.hasReturnWithValue(node);
// const noParams = node.parameters.length === 0 && !this.hasArguments(node);
// const noCapture = !this.requireCapture(node);
// in case of nested function
const isNestedFunction = node.parent && node.parent.kind === ts.SyntaxKind.Block;
if (isNestedFunction) {
implementationMode = true;
}
const isClassMemberDeclaration = this.isClassMemberDeclaration(node);
const isClassMember = isClassMemberDeclaration || this.isClassMemberSignature(node);
const isFunctionOrMethodDeclaration =
(node.kind === ts.SyntaxKind.FunctionDeclaration || isClassMember)
&& !isNestedFunction;
const isFunctionExpression = node.kind === ts.SyntaxKind.FunctionExpression;
const isFunction = isFunctionOrMethodDeclaration || isFunctionExpression;
const isArrowFunction = node.kind === ts.SyntaxKind.ArrowFunction || isNestedFunction;
const writeAsLambdaCFunction = isArrowFunction || isFunction;
if (implementationMode && node.parent && node.parent.kind === ts.SyntaxKind.ClassDeclaration && this.isTemplate(<any>node.parent)) {
this.processTemplateParams(<any>node.parent);
}
this.processTemplateParams(node);
if (implementationMode !== true) {
this.processModifiers(node.modifiers);
}
const writeReturnType = () => {
if (node.type) {
if (this.isTemplateType(node.type)) {
this.writer.writeString('RET');
} else {
this.processType(node.type);
}
} else {
if (noReturn) {
this.writer.writeString('void');
} else {
if (isClassMember && (<ts.Identifier>node.name).text === 'toString') {
this.writer.writeString('string');
} else {
this.writer.writeString('any');
}
}
}
};
if (writeAsLambdaCFunction) {
if (isFunctionOrMethodDeclaration) {
// type declaration
if (node.kind !== ts.SyntaxKind.Constructor) {
const isVirtual = isClassMember
&& !this.isStatic(node)
&& !this.isTemplate(<ts.MethodDeclaration>node)
&& implementationMode !== true;
if (isVirtual) {
this.writer.writeString('virtual ');
}
writeReturnType();
this.writer.writeString(' ');
}
if (isClassMemberDeclaration && implementationMode) {
// in case of constructor
this.writeClassName();
if (implementationMode
&& node.parent
&& node.parent.kind === ts.SyntaxKind.ClassDeclaration
&& this.isTemplate(<any>node.parent)) {
this.processTemplateParameters(<any>node.parent);
}
this.writer.writeString('::');
}
// name
if (node.name && node.name.kind === ts.SyntaxKind.Identifier) {
if (node.kind === ts.SyntaxKind.GetAccessor) {
this.writer.writeString('get_');
} else if (node.kind === ts.SyntaxKind.SetAccessor) {
this.writer.writeString('set_');
}
if (node.name.kind === ts.SyntaxKind.Identifier) {
this.processExpression(node.name);
} else {
throw new Error('Not implemented');
}
} else {
// in case of constructor
this.writeClassName();
}
} else if (isArrowFunction || isFunctionExpression) {
if (isNestedFunction) {
this.writer.writeString('auto ');
if (node.name.kind === ts.SyntaxKind.Identifier) {
this.processExpression(node.name);
} else {
throw new Error('Not implemented');
}
this.writer.writeString(' = ');
}
// lambda or noname function
const byReference = (<any>node).__lambda_by_reference ? '&' : '=';
this.writer.writeString(`[${byReference}]`);
}
}
this.writer.writeString('(');
let defaultParams = false;
let next = false;
node.parameters.forEach((element, index) => {
if (element.name.kind !== ts.SyntaxKind.Identifier) {
throw new Error('Not implemented');
}
if (next) {
this.writer.writeString(', ');
}
const effectiveType = element.type
|| this.resolver.getOrResolveTypeOfAsTypeNode(element.initializer);
if (element.dotDotDotToken) {
this.writer.writeString('Args...');
} else if (this.isTemplateType(effectiveType)) {
this.writer.writeString('P' + index);
} else {
this.processType(effectiveType, isArrowFunction);
}
this.writer.writeString(' ');
this.processExpression(element.name);
// extra symbol to change parameter name
if (node.kind === ts.SyntaxKind.Constructor
&& this.hasAccessModifier(element.modifiers)
|| element.dotDotDotToken) {
this.writer.writeString('_');
}
if (!implementationMode) {
if (element.initializer) {
this.writer.writeString(' = ');
this.processExpression(element.initializer);
defaultParams = true;
} else if (element.questionToken || defaultParams) {
switch (element.type && element.type.kind) {
case ts.SyntaxKind.FunctionType:
this.writer.writeString(' = nullptr');
break;
default:
this.writer.writeString(' = undefined');
break;
}
}
}
next = true;
});
if (isArrowFunction || isFunctionExpression) {
this.writer.writeStringNewLine(') mutable');
} else {
this.writer.writeStringNewLine(')');
}
// constructor init
let skipped = 0;
if (node.kind === ts.SyntaxKind.Constructor && implementationMode) {
this.writer.cancelNewLine();
next = false;
node.parameters
.filter(e => this.hasAccessModifier(e.modifiers))
.forEach(element => {
if (next) {
this.writer.writeString(', ');
} else {
this.writer.writeString(' : ');
}
if (element.name.kind === ts.SyntaxKind.Identifier) {
this.processExpression(element.name);
this.writer.writeString('(');
this.processExpression(element.name);
this.writer.writeString('_)');
} else {
throw new Error('Not implemented');
}
next = true;
});
// process base constructor call
let superCall = (<any>node.body).statements[0];
if (superCall && superCall.kind === ts.SyntaxKind.ExpressionStatement) {
superCall = (<ts.ExpressionStatement>superCall).expression;
}
if (superCall && superCall.kind === ts.SyntaxKind.CallExpression
&& (<ts.CallExpression>superCall).expression.kind === ts.SyntaxKind.SuperKeyword) {
if (!next) {
this.writer.writeString(' : ');
} else {
this.writer.writeString(', ');
}
this.processExpression(superCall);
skipped = 1;
}
if (next) {
this.writer.writeString(' ');
}
this.writer.writeString(' ');
}
if (!implementationMode && isAbstract) {
// abstract
this.writer.cancelNewLine();
this.writer.writeString(' = 0');
}
if (!noBody && (isArrowFunction || isFunctionExpression || implementationMode)) {
this.writer.BeginBlock();
node.parameters
.filter(e => e.dotDotDotToken)
.forEach(element => {
this.processType(element.type, false);
this.writer.writeString(' ');
this.processExpression(<ts.Identifier>element.name);
this.writer.writeString(' = ');
this.processType(element.type, false);
this.writer.writeString('{');
this.processExpression(<ts.Identifier>element.name);
this.writer.writeStringNewLine('_...};');
});
if (node.kind === ts.SyntaxKind.Constructor && this.hasThisAsShared(node)) {
// adding header to constructor
this.processType(this.resolver.getOrResolveTypeOfAsTypeNode(node.parent));
this.writer.writeStringNewLine(' _this(this, [] (auto&) {/*to be finished*/});');
}
this.markRequiredCapture(node);
(<any>node.body).statements.filter((item, index) => index >= skipped).forEach(element => {
this.processStatementInternal(element, true);
});
// add default return if no body
if (noReturnStatement && node && node.type && node.type.kind !== ts.SyntaxKind.VoidKeyword) {
this.writer.writeString('return ');
writeReturnType();
this.writer.writeString('()');
this.writer.EndOfStatement();
}
this.writer.EndBlock();
}
}
private writeClassName() {
const classNode = this.scope[this.scope.length - 2];
if (classNode && classNode.kind === ts.SyntaxKind.ClassDeclaration) {
this.processExpression((<ts.ClassDeclaration>classNode).name);
} else {
throw new Error('Not Implemented');
}
}
private processTemplateParams(node: ts.FunctionExpression | ts.ArrowFunction | ts.FunctionDeclaration | ts.MethodDeclaration
| ts.MethodSignature | ts.ConstructorDeclaration | ts.TypeAliasDeclaration | ts.GetAccessorDeclaration
| ts.SetAccessorDeclaration) {
let types = <ts.TypeParameterDeclaration[]><any>node.typeParameters;
if (types && node.parent && (<any>node.parent).typeParameters) {
types = types.filter(t => (<any>node.parent).typeParameters.every(t2 => t.name.text !== t2.name.text));
}
const templateTypes = types && types.length > 0;
const isParamTemplate = this.isMethodParamsTemplate(node);
const isReturnTemplate = this.isTemplateType(node.type);
let next = false;
if (templateTypes || isParamTemplate || isReturnTemplate) {
this.writer.writeString('template <');
if (templateTypes) {
types.forEach(type => {
if (next) {
this.writer.writeString(', ');
}
this.processType(type);
next = true;
});
}
if (isReturnTemplate) {
if (next) {
this.writer.writeString(', ');
}
this.writer.writeString('typename RET');
next = true;
}
// add params
if (isParamTemplate) {
(<ts.MethodDeclaration>node).parameters.forEach((element, index) => {
if (this.isTemplateType(element.type)) {
if (next) {
this.writer.writeString(', ');
}
this.writer.writeString('typename P' + index);
next = true;
}
if (element.dotDotDotToken) {
this.writer.writeString('typename ...Args');
next = true;
}
});
}
this.writer.writeStringNewLine('>');
}
return next;
}
private processTemplateParameters(node: ts.ClassDeclaration) {
let next = false;
if (node.typeParameters) {
this.writer.writeString('<');
node.typeParameters.forEach(type => {
if (next) {
this.writer.writeString(', ');
}
this.processType(type, undefined, undefined, true);
next = true;
});
this.writer.writeString('>');
}
return next;
}
private processTemplateArguments(node: ts.ExpressionWithTypeArguments | ts.CallExpression | ts.NewExpression,
skipPointerInType?: boolean) {
let next = false;
if (node.typeArguments) {
this.writer.writeString('<');
node.typeArguments.forEach(element => {
if (next) {
this.writer.writeString(', ');
}
this.processType(element, undefined, skipPointerInType);
next = true;
});
this.writer.writeString('>');
} else {
/*
const typeInfo = this.resolver.getOrResolveTypeOf(node.expression);
const templateParametersInfoFromType: ts.TypeParameter[] = typeInfo
&& typeInfo.symbol
&& typeInfo.symbol.valueDeclaration
&& (<any>typeInfo.symbol.valueDeclaration).typeParameters;
if (templateParametersInfoFromType) {
this.writer.writeString('<void>');
}
*/
}
}
private processArrowFunction(node: ts.ArrowFunction): void {
if (node.body.kind !== ts.SyntaxKind.Block) {
// create body
node.body = ts.createBlock([ts.createReturn(<ts.Expression>node.body)]);
}
this.processFunctionExpression(<any>node);
}
private isClassMemberDeclaration(node: ts.Node) {
if (!node) {
return false;
}
return node.kind === ts.SyntaxKind.Constructor
|| node.kind === ts.SyntaxKind.MethodDeclaration
|| node.kind === ts.SyntaxKind.PropertyDeclaration
|| node.kind === ts.SyntaxKind.GetAccessor
|| node.kind === ts.SyntaxKind.SetAccessor;
}
private isClassMemberSignature(node: ts.Node) {
if (!node) {
return false;
}
return node.kind === ts.SyntaxKind.MethodSignature
|| node.kind === ts.SyntaxKind.PropertySignature;
}
private isStatic(node: ts.Node) {
return node.modifiers && node.modifiers.some(m => m.kind === ts.SyntaxKind.StaticKeyword);
}
private isAbstract(node: ts.Node) {
return node.modifiers && node.modifiers.some(m => m.kind === ts.SyntaxKind.AbstractKeyword);
}
private isDeclare(node: ts.Node) {
return node.modifiers && node.modifiers.some(m => m.kind === ts.SyntaxKind.DeclareKeyword);
}
private processFunctionDeclaration(node: ts.FunctionDeclaration | ts.MethodDeclaration, implementationMode?: boolean): boolean {
if (!implementationMode) {
this.processPredefineType(node.type);
node.parameters.forEach((element) => {
this.processPredefineType(element.type);
});
}
const skip = this.processFunctionExpression(<ts.FunctionExpression><any>node, implementationMode);
if (!skip && !this.isClassMemberDeclaration(node)) {
this.writer.EndOfStatement();
if (!this.isClassMemberSignature(node)) {
this.writer.writeStringNewLine();
}
}
return skip;
}
private processReturnStatement(node: ts.ReturnStatement): void {
const typeReturn = this.resolver.getOrResolveTypeOfAsTypeNode(node.expression);
const functionDeclaration = (<ts.FunctionDeclaration>(this.scope[this.scope.length - 1]));
let functionReturn = functionDeclaration.type || this.resolver.getOrResolveTypeOfAsTypeNode(functionDeclaration);
if (functionReturn.kind === ts.SyntaxKind.FunctionType) {
functionReturn = (<ts.FunctionTypeNode>functionReturn).type;
} else if (!functionDeclaration.type) {
// if it is not function then use "any"
functionReturn = null;
}
this.writer.writeString('return');
if (node.expression) {
this.writer.writeString(' ');
/*
let theSame = (typeReturn && typeReturn.kind === ts.SyntaxKind.ThisKeyword)
|| this.resolver.typesAreTheSame(typeReturn, functionReturn);
// TODO: hack
if (typeReturn && typeReturn.kind === ts.SyntaxKind.ArrayType) {
theSame = false;
}
// cast only if we have provided type
if (!theSame && functionReturn) {
this.writer.writeString('cast<');
if (this.isTemplateType(functionReturn)) {
this.writer.writeString('RET');
} else {
this.processType(functionReturn);
}
this.writer.writeString('>(');
}
*/
this.processExpression(node.expression);
/*
if (!theSame && functionReturn) {
this.writer.writeString(')');
}
*/
} else {
if (functionReturn && functionReturn.kind !== ts.SyntaxKind.VoidKeyword) {
this.writer.writeString(' ');
this.processType(functionReturn);
this.writer.writeString('()');
}
}
this.writer.EndOfStatement();
}
private processIfStatement(node: ts.IfStatement): void {
this.writer.writeString('if (');
this.processExpression(node.expression);
this.writer.writeString(') ');
this.processStatement(node.thenStatement);
if (node.elseStatement) {
this.writer.cancelNewLine();
this.writer.writeString(' else ');
this.processStatement(node.elseStatement);
}
}
private processDoStatement(node: ts.DoStatement): void {
this.writer.writeStringNewLine('do');
this.processStatement(node.statement);
this.writer.writeString('while (');
this.processExpression(node.expression);
this.writer.writeStringNewLine(');');
}
private processWhileStatement(node: ts.WhileStatement): void {
this.writer.writeString('while (');
this.processExpression(node.expression);
this.writer.writeStringNewLine(')');
this.processStatement(node.statement);
}
private processForStatement(node: ts.ForStatement): void {
this.writer.writeString('for (');
const initVar = <any>node.initializer;
this.processExpression(initVar);
this.writer.writeString('; ');
this.processExpression(node.condition);
this.writer.writeString('; ');
this.processExpression(node.incrementor);
this.writer.writeStringNewLine(')');
this.processStatement(node.statement);
}
private processForInStatement(node: ts.ForInStatement): void {
this.processForInStatementNoScope(node);
}
private processForInStatementNoScope(node: ts.ForInStatement): void {
this.writer.writeString('for (auto& ');
const initVar = <any>node.initializer;
initVar.__ignore_type = true;
this.processExpression(initVar);
this.writer.writeString(' : keys_(');
this.processExpression(node.expression);
this.writer.writeStringNewLine('))');
this.processStatement(node.statement);
}
private processForOfStatement(node: ts.ForOfStatement): void {
// if has Length access use iteration
const hasLengthAccess = this.hasPropertyAccess(node.statement, 'length');
if (!hasLengthAccess) {
this.writer.writeString('for (auto& ');
const initVar = <any>node.initializer;
initVar.__ignore_type = true;
this.processExpression(initVar);
this.writer.writeString(' : ');
this.processExpression(node.expression);
this.writer.writeStringNewLine(')');
this.processStatement(node.statement);
} else {
const arrayName = `__array${node.getFullStart()}_${node.getEnd()}`;
const indexName = `__indx${node.getFullStart()}_${node.getEnd()}`;
this.writer.writeString(`auto& ${arrayName} = `);
this.processExpression(node.expression);
this.writer.EndOfStatement();
this.writer.writeStringNewLine(`for (auto ${indexName} = 0_N; ${indexName} < ${arrayName}->get_length(); ${indexName}++)`);
this.writer.BeginBlock();
this.writer.writeString(`auto& `);
const initVar = <any>node.initializer;
initVar.__ignore_type = true;
this.processExpression(initVar);
this.writer.writeStringNewLine(` = const_(${arrayName})[${indexName}]`);
this.writer.EndOfStatement();
this.processStatement(node.statement);
this.writer.EndBlock();
}
}
private processBreakStatement(node: ts.BreakStatement) {
this.writer.writeStringNewLine('break;');
}
private processContinueStatement(node: ts.ContinueStatement) {
this.writer.writeStringNewLine('continue;');
}
private processSwitchStatement(node: ts.SwitchStatement) {
const caseExpressions = node.caseBlock.clauses
.filter(c => c.kind === ts.SyntaxKind.CaseClause)
.map(element => (<ts.CaseClause>element).expression);
if (!caseExpressions || caseExpressions.length === 0) {
this.processSwitchStatementForBasicTypesInternal(node);
return;
}
const isAllStatic = caseExpressions
.every(expression => expression.kind === ts.SyntaxKind.NumericLiteral
|| expression.kind === ts.SyntaxKind.StringLiteral
|| expression.kind === ts.SyntaxKind.TrueKeyword
|| expression.kind === ts.SyntaxKind.FalseKeyword
|| this.resolver.isTypeFromSymbol(this.resolver.getOrResolveTypeOf(expression), ts.SyntaxKind.EnumMember));
const firstExpression = caseExpressions[0];
const firstType = this.resolver.getOrResolveTypeOf(firstExpression);
const firstTypeNode = this.resolver.typeToTypeNode(firstType);
const isTheSameTypes = caseExpressions.every(
ce => this.resolver.typesAreTheSame(this.resolver.getOrResolveTypeOfAsTypeNode(ce), firstTypeNode));
if (isTheSameTypes && isAllStatic && !this.resolver.isStringType(firstType)) {
this.processSwitchStatementForBasicTypesInternal(node);
return;
}
this.processSwitchStatementForAnyInternal(node);
}
private processSwitchStatementForBasicTypesInternal(node: ts.SwitchStatement) {
const caseExpressions = node.caseBlock.clauses
.filter(c => c.kind === ts.SyntaxKind.CaseClause)
.map(element => (<ts.CaseClause>element).expression);
const isNumeric = this.resolver.isNumberType(this.resolver.getOrResolveTypeOf(node.expression));
const isInteger = caseExpressions.every(expression => expression.kind === ts.SyntaxKind.NumericLiteral
&& this.isInt((<ts.NumericLiteral>expression).text));
this.writer.writeString(`switch (`);
if (isInteger && isNumeric) {
this.writer.writeString(`static_cast<size_t>(`);
}
this.processExpression(node.expression);
if (isInteger && isNumeric) {
this.writer.writeString(`)`);
}
this.writer.writeStringNewLine(')');
this.writer.BeginBlock();
node.caseBlock.clauses.forEach(element => {
this.writer.DecreaseIntent();
if (element.kind === ts.SyntaxKind.CaseClause) {
this.writer.writeString(`case `);
(<any>element.expression).__skip_boxing = true;
this.processExpression(element.expression);
} else {
this.writer.writeString('default');
}
this.writer.IncreaseIntent();
this.writer.writeStringNewLine(':');
element.statements.forEach(elementCase => {
this.processStatement(elementCase);
});
});
this.writer.EndBlock();
}
private processSwitchStatementForAnyInternal(node: ts.SwitchStatement) {
const switchName = `__switch${node.getFullStart()}_${node.getEnd()}`;
const isAllStatic = node.caseBlock.clauses
.filter(c => c.kind === ts.SyntaxKind.CaseClause)
.map(element => (<ts.CaseClause>element).expression)
.every(expression => expression.kind === ts.SyntaxKind.NumericLiteral
|| expression.kind === ts.SyntaxKind.StringLiteral
|| expression.kind === ts.SyntaxKind.TrueKeyword
|| expression.kind === ts.SyntaxKind.FalseKeyword);
if (isAllStatic) {
this.writer.writeString('static ');
}
this.writer.writeString(`switch_type ${switchName} = `);
this.writer.BeginBlock();
let caseNumber = 0;
node.caseBlock.clauses.filter(c => c.kind === ts.SyntaxKind.CaseClause).forEach(element => {
if (caseNumber > 0) {
this.writer.writeStringNewLine(',');
}
this.writer.BeginBlockNoIntent();
this.writer.writeString('any(');
this.processExpression((<ts.CaseClause>element).expression);
this.writer.writeString('), ');
this.writer.writeString((++caseNumber).toString());
this.writer.EndBlockNoIntent();
});
this.writer.EndBlock();
this.writer.EndOfStatement();
this.writer.writeString(`switch (${switchName}[`);
this.processExpression(node.expression);
this.writer.writeStringNewLine('])');
this.writer.BeginBlock();
caseNumber = 0;
node.caseBlock.clauses.forEach(element => {
this.writer.DecreaseIntent();
if (element.kind === ts.SyntaxKind.CaseClause) {
this.writer.writeString(`case ${++caseNumber}`);
} else {
this.writer.writeString('default');
}
this.writer.IncreaseIntent();
this.writer.writeStringNewLine(':');
element.statements.forEach(elementCase => {
this.processStatement(elementCase);
});
});
this.writer.EndBlock();
}
private processBlock(node: ts.Block): void {
this.writer.BeginBlock();
node.statements.forEach(element => {
this.processStatement(element);
});
this.writer.EndBlock();
}
private processModuleBlock(node: ts.ModuleBlock): void {
node.statements.forEach(s => {
this.processStatement(s);
});
}
private processBooleanLiteral(node: ts.BooleanLiteral): void {
// find if you need to box value
const boxing = (<any>node).__boxing;
this.writer.writeString(`${node.kind === ts.SyntaxKind.TrueKeyword ? ('true' + (boxing ? '_t' : '')) : ('false' + (boxing ? '_t' : ''))}`);
}
private processNullLiteral(node: ts.NullLiteral): void {
this.writer.writeString(node && node.parent.kind === ts.SyntaxKind.TypeAssertionExpression ? 'nullptr' : 'null');
}
private isInt(valAsString: string) {
const val = parseInt(valAsString, 10);
return val.toString() === valAsString;
}
private processNumericLiteral(node: ts.NumericLiteral): void {
const boxing = (<any>node).__boxing;
const val = parseInt(node.text, 10);
const isInt = val.toString() === node.text;
const isNegative = node.parent
&& node.parent.kind === ts.SyntaxKind.PrefixUnaryExpression
&& (<ts.PrefixUnaryExpression>node.parent).operator === ts.SyntaxKind.MinusToken;
let suffix = '';
if (isInt && val >= 2147483648) {
suffix = 'll';
}
// find if you need to box value
let currentNode: ts.Expression = node;
if (isNegative) {
currentNode = <ts.Expression>currentNode.parent;
}
while (currentNode && currentNode.parent && currentNode.parent.kind === ts.SyntaxKind.ParenthesizedExpression) {
currentNode = <ts.Expression>currentNode.parent;
}
this.writer.writeString(`${node.text}`);
if (boxing) {
this.writer.writeString(`_N`);
} else {
this.writer.writeString(`${suffix}`);
}
}
private processStringLiteral(node: ts.StringLiteral | ts.LiteralLikeNode
| ts.TemplateHead | ts.TemplateMiddle | ts.TemplateTail): void {
const text = node.text.replace(/\n/g, '\\\n');
if (text === '') {
this.writer.writeString(`string_empty`);
} else {
this.writer.writeString(`STR("${text}")`);
}
}
private processNoSubstitutionTemplateLiteral(node: ts.NoSubstitutionTemplateLiteral): void {
this.processStringLiteral(<ts.StringLiteral><any>node);
}
private processTemplateExpression(node: ts.TemplateExpression): void {
this.processStringLiteral(node.head);
node.templateSpans.forEach(element => {
this.writer.writeString(' + ');
if (element.expression.kind === ts.SyntaxKind.BinaryExpression) {
this.writer.writeString('(');
}
this.processExpression(element.expression);
if (element.expression.kind === ts.SyntaxKind.BinaryExpression) {
this.writer.writeString(')');
}
this.writer.writeString(' + ');
this.processStringLiteral(element.literal);
});
}
private processRegularExpressionLiteral(node: ts.RegularExpressionLiteral): void {
this.writer.writeString('(new RegExp(');
this.processStringLiteral(<ts.LiteralLikeNode>{ text: node.text.substring(1, node.text.length - 2) });
this.writer.writeString('))');
}
private processObjectLiteralExpression(node: ts.ObjectLiteralExpression): void {
let next = false;
const hasSpreadAssignment = node.properties.some(e => e.kind === ts.SyntaxKind.SpreadAssignment);
if (hasSpreadAssignment) {
this.writer.writeString('utils::assign(');
}
this.writer.writeString('object');
if (node.properties.length !== 0) {
this.writer.BeginBlock();
node.properties.forEach(element => {
if (next && element.kind !== ts.SyntaxKind.SpreadAssignment) {
this.writer.writeStringNewLine(', ');
}
if (element.kind === ts.SyntaxKind.PropertyAssignment) {
const property = <ts.PropertyAssignment>element;
this.writer.writeString('object::pair{');
if (property.name
&& (property.name.kind === ts.SyntaxKind.Identifier
|| property.name.kind === ts.SyntaxKind.NumericLiteral)) {
this.processExpression(ts.createStringLiteral(property.name.text));
} else {
this.processExpression(<ts.Expression>property.name);
}
this.writer.writeString(', ');
this.processExpression(property.initializer);
this.writer.writeString('}');
} else if (element.kind === ts.SyntaxKind.ShorthandPropertyAssignment) {
const property = <ts.ShorthandPropertyAssignment>element;
this.writer.writeString('object::pair{');
if (property.name
&& (property.name.kind === ts.SyntaxKind.Identifier
|| property.name.kind === ts.SyntaxKind.NumericLiteral)) {
this.processExpression(ts.createStringLiteral(property.name.text));
} else {
this.processExpression(<ts.Expression>property.name);
}
this.writer.writeString(', ');
if (property.name
&& (property.name.kind === ts.SyntaxKind.Identifier
|| property.name.kind === ts.SyntaxKind.NumericLiteral)) {
this.processExpression(ts.createStringLiteral(property.name.text));
} else {
this.processExpression(<ts.Expression>property.name);
}
this.writer.writeString('}');
}
next = true;
});
this.writer.EndBlock(true);
} else {
this.writer.writeString('{}');
}
if (hasSpreadAssignment) {
node.properties.forEach(element => {
if (element.kind === ts.SyntaxKind.SpreadAssignment) {
this.writer.writeString(', ');
const spreadAssignment = <ts.SpreadAssignment>element;
this.processExpression(spreadAssignment.expression);
}
});
this.writer.writeString(')');
}
}
private processComputedPropertyName(node: ts.ComputedPropertyName): void {
this.processExpression(node.expression);
}
private processArrayLiteralExpression(node: ts.ArrayLiteralExpression): void {
let next = false;
const isDeconstruct = node.parent && node.parent.kind === ts.SyntaxKind.BinaryExpression
&& (<ts.BinaryExpression>node.parent).left === node;
let isTuple = false;
const type = this.resolver.typeToTypeNode(this.resolver.getOrResolveTypeOf(node));
if (type.kind === ts.SyntaxKind.TupleType) {
isTuple = true;
}
let elementsType = (<any>node).parent.type;
if (!elementsType) {
if (node.elements.length !== 0) {
elementsType = this.resolver.typeToTypeNode(this.resolver.getTypeAtLocation(node.elements[0]));
}
} else {
if (elementsType.elementType) {
elementsType = elementsType.elementType;
} else if (elementsType.typeArguments && elementsType.typeArguments[0]) {
elementsType = elementsType.typeArguments[0];
}
}
if (isDeconstruct) {
this.writer.writeString('std::tie(');
node.elements.forEach(element => {
if (next) {
this.writer.writeString(', ');
}
this.processExpression(element);
next = true;
});
this.writer.writeString(')');
return;
}
if (!isTuple) {
this.writer.writeString('array<');
if (elementsType) {
this.processType(elementsType, false);
} else {
this.writer.writeString('any');
}
this.writer.writeString('>');
} else {
this.processType(type);
}
if (node.elements.length !== 0) {
this.writer.BeginBlockNoIntent();
node.elements.forEach(element => {
if (next) {
this.writer.writeString(', ');
}
this.processExpression(element);
next = true;
});
this.writer.EndBlockNoIntent();
} else {
this.writer.writeString('()');
}
}
private processElementAccessExpression(node: ts.ElementAccessExpression): void {
const symbolInfo = this.resolver.getSymbolAtLocation(node.expression);
const type = this.resolver.typeToTypeNode(this.resolver.getOrResolveTypeOf(node.expression));
if (type && type.kind === ts.SyntaxKind.TupleType) {
// tuple
if (node.argumentExpression.kind !== ts.SyntaxKind.NumericLiteral) {
throw new Error('Not implemented');
}
this.writer.writeString('std::get<');
(<any>node.argumentExpression).__skip_boxing = true;
this.processExpression(node.argumentExpression);
this.writer.writeString('>(');
this.processExpression(node.expression);
this.writer.writeString(')');
} else {
let isWriting = false;
let dereference = true;
if (node.parent.kind === ts.SyntaxKind.BinaryExpression) {
const binaryExpression = <ts.BinaryExpression>node.parent;
isWriting = binaryExpression.operatorToken.kind === ts.SyntaxKind.EqualsToken
&& binaryExpression.left === node;
}
dereference = type
&& type.kind !== ts.SyntaxKind.TypeLiteral
&& type.kind !== ts.SyntaxKind.StringKeyword
&& type.kind !== ts.SyntaxKind.ArrayType
&& type.kind !== ts.SyntaxKind.ObjectKeyword
&& type.kind !== ts.SyntaxKind.AnyKeyword
&& symbolInfo
&& symbolInfo.valueDeclaration
&& (!(<ts.ParameterDeclaration>symbolInfo.valueDeclaration).dotDotDotToken)
&& (<any>symbolInfo.valueDeclaration).initializer
&& (<any>symbolInfo.valueDeclaration).initializer.kind !== ts.SyntaxKind.ObjectLiteralExpression;
if (dereference) {
this.writer.writeString('(*');
}
if (!isWriting) {
this.writer.writeString('const_(');
}
this.processExpression(node.expression);
if (!isWriting) {
this.writer.writeString(')');
}
if (dereference) {
this.writer.writeString(')');
}
this.writer.writeString('[');
this.processExpression(node.argumentExpression);
this.writer.writeString(']');
}
}
private processParenthesizedExpression(node: ts.ParenthesizedExpression) {
this.writer.writeString('(');
this.processExpression(node.expression);
this.writer.writeString(')');
}
private processTypeAssertionExpression(node: ts.TypeAssertion) {
this.writer.writeString('static_cast<');
this.processType(node.type);
this.writer.writeString('>(');
this.processExpression(node.expression);
this.writer.writeString(')');
}
private processPrefixUnaryExpression(node: ts.PrefixUnaryExpression): void {
const typeInfo = this.resolver.getOrResolveTypeOf(node.operand);
const isEnum = this.resolver.isTypeFromSymbol(typeInfo, ts.SyntaxKind.EnumDeclaration);
const op = this.opsMap[node.operator];
const isFunction = op.substr(0, 2) === '__';
if (isFunction) {
this.writer.writeString(op.substr(2) + '(');
} else {
this.writer.writeString(op);
}
if (isEnum) {
this.writer.writeString('js::number(');
}
this.processExpression(node.operand);
if (isEnum) {
this.writer.writeString(')');
}
if (isFunction) {
this.writer.writeString(')');
}
}
private processPostfixUnaryExpression(node: ts.PostfixUnaryExpression): void {
this.processExpression(node.operand);
this.writer.writeString(this.opsMap[node.operator]);
}
private processConditionalExpression(node: ts.ConditionalExpression): void {
const whenTrueType = this.resolver.getOrResolveTypeOfAsTypeNode(node.whenTrue);
const whenFalseType = this.resolver.getOrResolveTypeOfAsTypeNode(node.whenFalse);
const equals = this.compareTypes(whenTrueType, whenFalseType);
this.writer.writeString('(');
this.processExpression(node.condition);
this.writer.writeString(') ? ');
if (!equals) {
this.writer.writeString('any(');
}
this.processExpression(node.whenTrue);
if (!equals) {
this.writer.writeString(')');
}
this.writer.writeString(' : ');
if (!equals) {
this.writer.writeString('any(');
}
this.processExpression(node.whenFalse);
if (!equals) {
this.writer.writeString(')');
}
}
private processBinaryExpression(node: ts.BinaryExpression): void {
const opCode = node.operatorToken.kind;
if (opCode === ts.SyntaxKind.InstanceOfKeyword) {
this.writer.writeString('is<');
if (node.right.kind === ts.SyntaxKind.Identifier) {
const identifier = <ts.Identifier>node.right;
switch (identifier.text) {
case 'Number':
case 'String':
case 'Boolean':
this.writer.writeString('js::');
this.writer.writeString(identifier.text.toLocaleLowerCase());
break;
default:
this.processExpression(node.right);
break;
}
} else {
this.processExpression(node.right);
}
this.writer.writeString('>(');
this.processExpression(node.left);
this.writer.writeString(')');
return;
}
const wrapIntoRoundBrackets =
opCode === ts.SyntaxKind.AmpersandAmpersandToken
|| opCode === ts.SyntaxKind.BarBarToken;
const op = this.opsMap[node.operatorToken.kind];
const isFunction = op.substr(0, 2) === '__';
if (isFunction) {
this.writer.writeString(op.substr(2) + '(');
}
const leftType = this.resolver.getOrResolveTypeOf(node.left);
const rightType = this.resolver.getOrResolveTypeOf(node.right);
const isLeftEnum = this.resolver.isTypeFromSymbol(leftType, ts.SyntaxKind.EnumDeclaration)
const isRightEnum = this.resolver.isTypeFromSymbol(rightType, ts.SyntaxKind.EnumDeclaration)
const leftSouldBePointer = isLeftEnum &&
(opCode === ts.SyntaxKind.EqualsToken
|| opCode === ts.SyntaxKind.AmpersandToken
|| opCode === ts.SyntaxKind.BarEqualsToken
|| opCode === ts.SyntaxKind.CaretEqualsToken
|| opCode === ts.SyntaxKind.PercentEqualsToken)
if (wrapIntoRoundBrackets) {
this.writer.writeString('(');
}
if (isLeftEnum) {
if (leftSouldBePointer) {
this.writer.writeString('*reinterpret_cast<long*>(&');
} else {
this.writer.writeString('static_cast<long>(');
}
}
this.processExpression(node.left);
if (isLeftEnum) {
this.writer.writeString(')');
}
if (wrapIntoRoundBrackets) {
this.writer.writeString(')');
}
if (isFunction) {
this.writer.writeString(', ');
} else {
this.writer.writeString(' ' + op + ' ');
}
if (wrapIntoRoundBrackets) {
this.writer.writeString('(');
}
if (isRightEnum) {
this.writer.writeString('static_cast<long>(');
}
this.processExpression(node.right);
if (isRightEnum) {
this.writer.writeString(')');
}
if (wrapIntoRoundBrackets) {
this.writer.writeString(')');
}
if (isFunction) {
this.writer.writeString(')');
}
}
private processDeleteExpression(node: ts.DeleteExpression): void {
if (node.expression.kind === ts.SyntaxKind.PropertyAccessExpression) {
const propertyAccess = <ts.PropertyAccessExpression>node.expression;
this.processExpression(propertyAccess.expression);
this.writer.writeString('.Delete("');
this.processExpression(<ts.Identifier>propertyAccess.name);
this.writer.writeString('")');
} else if (node.expression.kind === ts.SyntaxKind.ElementAccessExpression) {
const elementAccessExpression = <ts.ElementAccessExpression>node.expression;
this.processExpression(elementAccessExpression.expression);
this.writer.writeString('.Delete(');
this.processExpression(elementAccessExpression.argumentExpression);
this.writer.writeString(')');
} else {
throw new Error('Method not implemented.');
}
}
private processNewExpression(node: ts.NewExpression): void {
if (node.parent.kind === ts.SyntaxKind.PropertyAccessExpression) {
this.writer.writeString('(');
}
this.processCallExpression(node);
if (node.parent.kind === ts.SyntaxKind.PropertyAccessExpression) {
this.writer.writeString(')');
}
}
private processCallExpression(node: ts.CallExpression | ts.NewExpression): void {
const isNew = node.kind === ts.SyntaxKind.NewExpression;
const typeOfExpression = isNew && this.resolver.getOrResolveTypeOf(node.expression);
const isArray = isNew && typeOfExpression && typeOfExpression.symbol && typeOfExpression.symbol.name === 'ArrayConstructor';
if (node.kind === ts.SyntaxKind.NewExpression && !isArray) {
this.writer.writeString('std::make_shared<');
}
if (isArray) {
this.writer.writeString('array');
} else {
this.processExpression(node.expression);
this.processTemplateArguments(node);
}
if (node.kind === ts.SyntaxKind.NewExpression && !isArray) {
// closing template
this.writer.writeString('>');
}
this.writer.writeString('(');
let next = false;
if (node.arguments.length) {
node.arguments.forEach(element => {
if (next) {
this.writer.writeString(', ');
}
this.processExpression(element);
next = true;
});
}
this.writer.writeString(')');
}
private processThisExpression(node: ts.ThisExpression): void {
const method = this.scope[this.scope.length - 1];
if (method
&& (this.isClassMemberDeclaration(method) || this.isClassMemberSignature(method))
&& this.isStatic(method)) {
const classNode = <ts.ClassDeclaration>this.scope[this.scope.length - 2];
if (classNode) {
const identifier = classNode.name;
this.writer.writeString(identifier.text);
return;
}
}
if (node.parent.kind === ts.SyntaxKind.PropertyAccessExpression) {
this.writer.writeString('this');
} else if (method.kind === ts.SyntaxKind.Constructor) {
this.writer.writeString('_this');
} else {
this.writer.writeString('shared_from_this()');
}
}
private processSuperExpression(node: ts.SuperExpression): void {
if (node.parent.kind === ts.SyntaxKind.CallExpression) {
const classNode = <ts.ClassDeclaration>this.scope[this.scope.length - 2];
if (classNode) {
const heritageClause = classNode.heritageClauses[0];
if (heritageClause) {
const firstType = heritageClause.types[0];
if (firstType.expression.kind === ts.SyntaxKind.Identifier) {
const identifier = <ts.Identifier>firstType.expression;
this.writer.writeString(identifier.text);
return;
}
}
}
}
this.writer.writeString('__super');
}
private processVoidExpression(node: ts.VoidExpression): void {
this.writer.writeString('Void(');
this.processExpression(node.expression);
this.writer.writeString(')');
}
private processNonNullExpression(node: ts.NonNullExpression): void {
this.processExpression(node.expression);
}
private processAsExpression(node: ts.AsExpression): void {
this.writer.writeString('as<');
this.processType(node.type);
this.writer.writeString('>(');
this.processExpression(node.expression);
this.writer.writeString(')');
}
private processSpreadElement(node: ts.SpreadElement): void {
if (node.parent && node.parent.kind === ts.SyntaxKind.CallExpression) {
const info = this.resolver.getSymbolAtLocation((<ts.CallExpression>node.parent).expression);
const parameters = (<ts.FunctionDeclaration>info.valueDeclaration).parameters;
if (parameters) {
let next = false;
parameters.forEach((item, index) => {
if (next) {
this.writer.writeString(', ');
}
const elementAccess = ts.createElementAccess(node.expression, index);
this.processExpression(this.fixupParentReferences(elementAccess, node.parent));
next = true;
});
}
} else {
this.processExpression(node.expression);
}
}
private processAwaitExpression(node: ts.AwaitExpression): void {
this.writer.writeString('std::async([=]() { ');
this.processExpression(node.expression);
this.writer.writeString('; })');
}
private processIdentifier(node: ts.Identifier): void {
if (this.isWritingMain) {
const isRightPartOfPropertyAccess = node.parent.kind === ts.SyntaxKind.QualifiedName
|| node.parent.kind === ts.SyntaxKind.PropertyAccessExpression
&& (<ts.PropertyAccessExpression>(node.parent)).name === node;
if (!isRightPartOfPropertyAccess) {
const identifierSymbol = this.resolver.getSymbolAtLocation(node);
const valDecl = identifierSymbol && identifierSymbol.valueDeclaration;
if (valDecl) {
const containerParent = valDecl.parent.parent;
if (containerParent && this.isNamespaceStatement(containerParent)) {
const type = this.resolver.getOrResolveTypeOfAsTypeNode(containerParent);
if (type) {
this.processType(type);
this.writer.writeString('::');
}
}
}
}
}
// fix issue with 'continue'
if (node.text === 'continue'
|| node.text === 'catch') {
this.writer.writeString('_');
}
this.writer.writeString(node.text);
}
private processPropertyAccessExpression(node: ts.PropertyAccessExpression): void {
const typeInfo = this.resolver.getOrResolveTypeOf(node.expression);
const symbolInfo = this.resolver.getSymbolAtLocation(node.name);
const methodAccess = symbolInfo
&& symbolInfo.valueDeclaration.kind === ts.SyntaxKind.MethodDeclaration
&& !(node.parent.kind === ts.SyntaxKind.CallExpression && (<ts.CallExpression>node.parent).expression === node);
const isStaticMethodAccess = symbolInfo && symbolInfo.valueDeclaration && this.isStatic(symbolInfo.valueDeclaration);
const getAccess = symbolInfo
&& symbolInfo.declarations
&& symbolInfo.declarations.length > 0
&& (symbolInfo.declarations[0].kind === ts.SyntaxKind.GetAccessor
|| symbolInfo.declarations[0].kind === ts.SyntaxKind.SetAccessor)
|| node.name.text === 'length' && this.resolver.isArrayOrStringType(typeInfo);
if (methodAccess) {
if (isStaticMethodAccess) {
this.writer.writeString('&');
this.processExpression(<ts.Identifier>node.name);
} else {
this.writer.writeString('std::bind(&');
const valueDeclaration = <ts.ClassDeclaration>symbolInfo.valueDeclaration.parent;
this.processExpression(<ts.Identifier>valueDeclaration.name);
this.writer.writeString('::');
this.processExpression(<ts.Identifier>node.name);
this.writer.writeString(', ');
this.processExpression(node.expression);
const methodDeclaration = <ts.MethodDeclaration>(symbolInfo.valueDeclaration);
methodDeclaration.parameters.forEach((p, i) => {
this.writer.writeString(', std::placeholders::_' + (i + 1));
});
this.writer.writeString(')');
}
} else {
if (node.expression.kind === ts.SyntaxKind.NewExpression
|| node.expression.kind === ts.SyntaxKind.ArrayLiteralExpression) {
this.writer.writeString('(');
}
// field access
this.processExpression(node.expression);
if (node.expression.kind === ts.SyntaxKind.NewExpression
|| node.expression.kind === ts.SyntaxKind.ArrayLiteralExpression) {
this.writer.writeString(')');
}
if (this.resolver.isAnyLikeType(typeInfo)) {
this.writer.writeString('["');
this.processExpression(<ts.Identifier>node.name);
this.writer.writeString('"]');
return;
} else if (this.resolver.isStaticAccess(typeInfo)
|| node.expression.kind === ts.SyntaxKind.SuperKeyword
|| typeInfo && typeInfo.symbol && typeInfo.symbol.valueDeclaration
&& typeInfo.symbol.valueDeclaration.kind === ts.SyntaxKind.ModuleDeclaration) {
this.writer.writeString('::');
} else {
this.writer.writeString('->');
}
if (getAccess) {
if ((<any>node).__set === true) {
this.writer.writeString('set_');
} else {
this.writer.writeString('get_');
}
}
this.processExpression(<ts.Identifier>node.name);
if (getAccess && (<any>node).__set !== true) {
this.writer.writeString('()');
}
}
}
} | the_stack |
import {
animate,
keyframes,
style,
transition,
trigger
} from '@angular/animations';
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
DoCheck,
ElementRef,
forwardRef,
HostListener,
Input,
OnDestroy,
OnInit,
Optional,
Renderer2,
Self,
TemplateRef,
ViewChild,
NgZone,
OnChanges,
QueryList,
ContentChildren,
AfterContentInit,
Directive,
ContentChild,
Output,
EventEmitter,
isDevMode,
} from '@angular/core';
import {
ControlValueAccessor,
FormGroupDirective,
NgControl,
NgForm
} from '@angular/forms';
import { LyField, LyFieldControlBase, STYLES as FIELD_STYLES } from '@alyle/ui/field';
import {
LyOverlay,
LyTheme2,
OverlayFactory,
shadowBuilder,
ThemeVariables,
toBoolean,
Positioning,
CanDisableCtor,
mixinDisableRipple,
mixinTabIndex,
LyRippleService,
XPosition,
YPosition,
Dir,
lyl,
StyleCollection,
LyClasses,
StyleTemplate,
ThemeRef,
StyleRenderer,
Style,
WithStyles
} from '@alyle/ui';
import { Subject, Observable, defer, merge } from 'rxjs';
import { take, takeUntil, startWith, switchMap, distinctUntilChanged, filter, mapTo } from 'rxjs/operators';
import { Platform } from '@angular/cdk/platform';
import { FocusableOption, FocusOrigin, ActiveDescendantKeyManager } from '@angular/cdk/a11y';
import { ENTER, SPACE, hasModifierKey, DOWN_ARROW, UP_ARROW, LEFT_ARROW, RIGHT_ARROW, A } from '@angular/cdk/keycodes';
import { coerceNumberProperty, coerceBooleanProperty } from '@angular/cdk/coercion';
import { SelectionModel } from '@angular/cdk/collections';
import { getLySelectNonFunctionValueError, getLySelectNonArrayValueError } from './select-errors';
export interface LySelectTheme {
/** Styles for Select Component */
root?: StyleCollection<((classes: LyClasses<typeof STYLES>) => StyleTemplate)>
| ((classes: LyClasses<typeof STYLES>) => StyleTemplate);
}
export interface LySelectVariables {
select?: LySelectTheme;
}
const DEFAULT_DISABLE_RIPPLE = false;
const STYLE_PRIORITY = -2;
export const STYLES = (theme: ThemeVariables & LySelectVariables, ref: ThemeRef) => {
const select = ref.selectorsOf(STYLES);
const { after } = theme;
return {
$priority: STYLE_PRIORITY,
root: () => lyl `{
display: block
position: relative
padding-${after}: 1em
min-height: 1em
-webkit-tap-highlight-color: transparent
{
...${
(theme.select
&& theme.select.root
&& (theme.select.root instanceof StyleCollection
? theme.select.root.setTransformer(fn => fn(select))
: theme.select.root(select))
)
}
}
}`,
container: {
background: theme.background.primary.default,
borderRadius: '2px',
boxShadow: shadowBuilder(4),
display: 'block',
transformOrigin: 'inherit',
pointerEvents: 'all',
overflow: 'auto',
maxHeight: '256px'
},
valueText: {
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap'
},
option: {
display: 'flex',
fontFamily: theme.typography.fontFamily,
color: theme.text.default,
'-webkit-tap-highlight-color': 'transparent',
backgroundColor: `rgba(0, 0, 0, 0)`,
border: 0,
padding: '0 1em',
margin: 0,
outline: 'none',
boxSizing: 'border-box',
position: 'relative',
justifyContent: 'flex-start',
alignItems: 'center',
alignContent: 'center',
'-webkit-user-select': 'none',
'-moz-user-select': 'none',
'-ms-user-select': 'none',
userSelect: 'none',
lineHeight: 1.125,
height: '3em',
cursor: 'pointer',
},
optionActive: lyl `{
background: ${theme.hover}
}`,
optionText: {
'ly-checkbox ~ &': {
display: 'flex',
alignItems: 'inherit',
alignContent: 'inherit'
}
},
content: {
padding: 0,
display: 'flex',
justifyContent: 'inherit',
alignItems: 'inherit',
alignContent: 'inherit',
width: '100%',
height: '100%',
boxSizing: 'border-box'
}
};
};
/** Change event object that is emitted when the select value has changed. */
export class LySelectChange {
constructor(
/** Reference to the select that emitted the change event. */
public source: LySelect,
/** Current value of the select that emitted the event. */
public value: any) { }
}
/** @docs-private */
const ANIMATIONS = [
trigger('selectEnter', [
transition('void => in', [
animate('125ms cubic-bezier(0, 0, 0.2, 1)', keyframes([
style({
opacity: 0,
transform: 'scaleY(0.9)'
}),
style({
opacity: 1,
transform: 'scaleY(1)'
})
]))
]),
transition('* => void', animate('100ms 25ms linear', style({ opacity: 0 })))
]),
];
/** @docs-private */
export class LySelectBase { }
/** @docs-private */
export const LySelectMixinBase = mixinTabIndex(LySelectBase as CanDisableCtor);
/**
* Allows the user to customize the trigger that is displayed when the select has a value.
*/
@Directive({
selector: 'ly-select-trigger'
})
export class LySelectTrigger { }
@Component({
selector: 'ly-select',
templateUrl: 'select.html',
changeDetection: ChangeDetectionStrategy.OnPush,
exportAs: 'lySelect',
host: {
'[attr.tabindex]': 'tabIndex',
'(keydown)': '_handleKeydown($event)',
'(focus)': '_onFocus()',
'(blur)': '_onBlur()',
},
animations: [...ANIMATIONS],
inputs: ['tabIndex'],
providers: [
StyleRenderer,
{ provide: LyFieldControlBase, useExisting: LySelect }
]
})
export class LySelect
extends LySelectMixinBase
implements ControlValueAccessor, LyFieldControlBase, OnInit, DoCheck, AfterContentInit, OnDestroy {
/** @docs-private */
readonly classes = this._theme.addStyleSheet(STYLES);
/** @internal */
_selectionModel: SelectionModel<LyOption>;
/** @internal */
_value: any;
/** The cached font-size of the trigger element. */
_triggerFontSize = 0;
private _overlayRef: OverlayFactory | null;
protected _disabled = false;
protected _required = false;
protected _placeholder: string;
readonly stateChanges: Subject<void> = new Subject<void>();
private _hasDisabledClass?: boolean;
private _errorClass?: string;
private _form: NgForm | FormGroupDirective | null = this._parentForm || this._parentFormGroup;
private _multiple: boolean;
private _opened: boolean;
private _valueKey: (opt: unknown) => unknown = same;
_focused: boolean = false;
errorState: boolean = false;
private _cursorClass: string;
/** Manages keyboard events for options in the panel. */
_keyManager: ActiveDescendantKeyManager<LyOption>;
/** Emits when the panel element is finished transforming in. */
_panelDoneAnimatingStream = new Subject<string>();
/** Comparison function to specify which option is displayed. Defaults to object equality. */
private _compareWith = (o1: any, o2: any) => o1 === o2;
/** Emits whenever the component is destroyed. */
private readonly _destroy = new Subject<void>();
/** Combined stream of all of the child options' change events. */
readonly optionSelectionChanges: Observable<LyOptionSelectionChange> = defer(() => {
const options = this.options;
if (options) {
return options.changes.pipe(
startWith(options),
switchMap(() => merge(...options.map(option => option.onSelectionChange)))
);
}
return this._ngZone.onStable
.pipe(take(1), switchMap(() => this.optionSelectionChanges));
}) as Observable<LyOptionSelectionChange>;
@ViewChild('templateRef') templateRef: TemplateRef<any>;
@ViewChild('valueText') valueTextDivRef: ElementRef<HTMLDivElement>;
/** @internal */
@ViewChild(forwardRef(() => LyOption)) _options: QueryList<LyOption>;
@ContentChildren(forwardRef(() => LyOption), { descendants: true }) options: QueryList<LyOption>;
@ContentChild(LySelectTrigger) customTrigger: LySelectTrigger;
/** Event emitted when the select panel has been toggled. */
@Output() readonly openedChange: EventEmitter<boolean> = new EventEmitter<boolean>();
/** Event emitted when the select has been opened. */
@Output('opened') readonly _openedStream: Observable<void> =
this.openedChange.pipe(filter(o => o), mapTo(null!));
/** Event emitted when the select has been closed. */
@Output('closed') readonly _closedStream: Observable<void> =
this.openedChange.pipe(filter(o => !o), mapTo(null!));
/** Event emitted when the selected value has been changed by the user. */
@Output() readonly selectionChange: EventEmitter<LySelectChange> = new EventEmitter<LySelectChange>();
/**
* Event that emits whenever the raw value of the select changes. This is here primarily
* to facilitate the two-way binding for the `value` input.
* @docs-private
*/
@Output() readonly valueChange: EventEmitter<any> = new EventEmitter<any>();
/**
* The registered callback function called when a change event occurs on the input element.
*/
onChange = (_: any) => {};
/**
* The registered callback function called when a blur event occurs on the input element.
*/
onTouched = () => {};
_onFocus() {
if (!this.disabled) {
this._focused = true;
this.stateChanges.next();
}
}
_onBlur() {
this._focused = false;
if (!this.disabled && !this._opened) {
this.onTouched();
this._cd.markForCheck();
this.stateChanges.next();
}
}
/** Time to wait in milliseconds after the last keystroke before moving focus to an item. */
@Input()
get typeaheadDebounceInterval(): number { return this._typeaheadDebounceInterval; }
set typeaheadDebounceInterval(value: number) {
const newVal = coerceNumberProperty(value);
if (this._typeaheadDebounceInterval !== newVal && this._keyManager) {
this._typeaheadDebounceInterval = newVal;
this._keyManager.withTypeAhead(newVal);
}
}
private _typeaheadDebounceInterval: number;
/** Value of the select control. */
@Input()
get value(): any { return this._value; }
set value(newValue: any) {
if (newValue !== this._value) {
if (this.options) {
this._setSelectionByValue(newValue);
}
this._value = newValue;
}
}
/** Whether the input is disabled. */
@Input()
set disabled(val: boolean) {
if (val !== this._disabled) {
this._disabled = toBoolean(val);
if (this._field) {
if (!val && this._hasDisabledClass) {
this._renderer.removeClass(this._field._getHostElement(), this._field.classes.disabled);
if (this._cursorClass) {
this._renderer.addClass(this._field._getHostElement(), this._cursorClass);
}
this._hasDisabledClass = undefined;
} else if (val) {
this._renderer.addClass(this._field._getHostElement(), this._field.classes.disabled);
if (this._cursorClass) {
this._renderer.removeClass(this._field._getHostElement(), this._cursorClass);
}
this._hasDisabledClass = true;
}
}
this.stateChanges.next();
}
}
get disabled(): boolean {
if (this.ngControl && this.ngControl.disabled !== null) {
return this.ngControl.disabled;
}
return this._disabled;
}
@Input()
set required(value: boolean) {
this._required = toBoolean(value);
}
get required(): boolean { return this._required; }
@Input()
set multiple(value: boolean) {
this._multiple = toBoolean(value);
}
get multiple(): boolean { return this._multiple; }
/**
* @deprecated has been deprecated in favor of `compareWith`
*/
@Input()
set valueKey(fn: (opt: unknown) => unknown) {
this._valueKey = fn;
console.warn('LySelect: `[valueKey]` has been deprecated in favor of `[compareWith]`');
}
get valueKey(): (opt: unknown) => unknown { return this._valueKey; }
@Input()
set placeholder(val: string) {
this._placeholder = val;
}
get placeholder(): string { return this._placeholder; }
/**
* Function to compare the option values with the selected values. The first argument
* is a value from an option. The second is a value from the selection. A boolean
* should be returned.
*/
@Input()
get compareWith() { return this._compareWith; }
set compareWith(fn: (o1: any, o2: any) => boolean) {
if (typeof fn !== 'function' && isDevMode) {
throw getLySelectNonFunctionValueError();
}
this._compareWith = fn;
if (this._selectionModel) {
// A different comparator means the selection could change.
this._initializeSelection();
}
}
/**
* Function used to sort the values in a select in multiple mode.
* Follows the same logic as `Array.prototype.sort`.
*/
@Input() sortComparator: (a: LyOption, b: LyOption, options: LyOption[]) => number;
get focused() {
return this._focused;
}
get empty() {
return !this._selectionModel || this._selectionModel.isEmpty();
}
get floatingLabel() {
return this._opened ? true : !this.empty;
}
/** The value displayed in the trigger. */
get triggerValue(): string {
if (this._multiple) {
const selectedOptions = this._selectionModel.selected.map(option => option.viewValue);
if (this._theme.variables.direction === Dir.rtl) {
selectedOptions.reverse();
}
return selectedOptions.join(', ');
}
return this._selectionModel.selected[0].viewValue;
}
/** Current selecteds */
get selected(): LyOption | LyOption[] {
const selected = this._selectionModel.selected;
return this.multiple ? selected : selected[0];
}
constructor(private _theme: LyTheme2,
readonly sRenderer: StyleRenderer,
private _renderer: Renderer2,
private _el: ElementRef,
private _overlay: LyOverlay,
/** @internal */
@Optional() public _field: LyField,
/** @internal */
public _cd: ChangeDetectorRef,
private _ngZone: NgZone,
/** @docs-private */
@Optional() @Self() public ngControl: NgControl,
@Optional() private _parentForm: NgForm,
@Optional() private _parentFormGroup: FormGroupDirective) {
super();
if (this.ngControl) {
// Note: we provide the value accessor through here, instead of
// the `providers` to avoid running into a circular import.
this.ngControl.valueAccessor = this;
}
this._cursorClass = this._theme.addStyle('lyField.select', {
'& {container}': {
cursor: 'pointer'
}
}, this._field._getHostElement(), null, STYLE_PRIORITY, FIELD_STYLES);
}
ngOnInit() {
this._selectionModel = new SelectionModel<LyOption>(this.multiple);
this.stateChanges.next();
// We need `distinctUntilChanged` here, because some browsers will
// fire the animation end event twice for the same animation. See:
// https://github.com/angular/angular/issues/24084
this._panelDoneAnimatingStream
.pipe(distinctUntilChanged(), takeUntil(this._destroy))
.subscribe(() => {
if (this._opened) {
this.openedChange.emit(true);
} else {
if (this._overlayRef) {
this._overlayRef.remove();
this._overlayRef = null;
}
this.openedChange.emit(false);
this.stateChanges.next();
this._cd.markForCheck();
}
});
const ngControl = this.ngControl;
// update styles on disabled
if (ngControl && ngControl.statusChanges) {
ngControl.statusChanges.pipe(takeUntil(this._destroy)).subscribe(() => {
this.disabled = !!ngControl.disabled;
});
}
// apply class {selectArrow} to `<select>`
this._renderer.addClass(this._field._getHostElement(), this._field.classes.selectArrow);
// apply default styles
this._renderer.addClass(this._el.nativeElement, this._field.classes.inputNative);
this._renderer.addClass(this._el.nativeElement, this.classes.root);
}
ngDoCheck() {
const oldVal = this.errorState;
const newVal = !!(this.ngControl && this.ngControl.invalid && (this.ngControl.touched || (this._form && this._form.submitted)));
if (newVal !== oldVal) {
this.errorState = newVal;
if (this._field) {
const errorClass = this._field.classes.errorState;
if (newVal) {
this._renderer.addClass(this._field._getHostElement(), errorClass);
this._errorClass = errorClass;
} else if (this._errorClass) {
this._renderer.removeClass(this._field._getHostElement(), errorClass);
this._errorClass = undefined;
}
this.stateChanges.next();
}
}
}
ngAfterContentInit() {
this._initKeyManager();
this.options.changes.pipe(startWith(null), takeUntil(this._destroy)).subscribe(() => {
this._resetOptions();
this._initializeSelection();
});
this._selectionModel.changed.pipe(takeUntil(this._destroy)).subscribe(event => {
event.added.forEach(option => option.select());
event.removed.forEach(option => option.deselect());
});
Promise.resolve().then(() => {
this.value = this.ngControl ? this.ngControl.value : this._value;
this.stateChanges.next();
this._cd.markForCheck();
});
this._keyManager.change.pipe(takeUntil(this._destroy)).subscribe(() => {
if (!this._opened && !this.multiple && this._keyManager.activeItem) {
this._keyManager.activeItem._selectViaInteraction();
}
});
}
ngOnDestroy() {
this._destroy.next();
this._destroy.complete();
this.stateChanges.complete();
if (this._overlayRef) {
this._overlayRef.destroy();
}
}
open() {
if (this.disabled || !this.options || !this.options.length || this._opened) {
return;
}
this._opened = true;
if (this._overlayRef) {
this._overlayRef.destroy();
}
this._overlayRef = this._overlay.create(this.templateRef, null, {
styles: {
top: 0,
left: 0,
pointerEvents: null
},
fnDestroy: this.close.bind(this),
onResizeScroll: this._updatePlacement.bind(this)
});
this._keyManager.withHorizontalOrientation(null);
this._triggerFontSize = parseInt(getComputedStyle(this._getHostElement()).fontSize || '0');
this._highlightCorrectOption();
this._cd.markForCheck();
this.stateChanges.next();
this._ngZone.onStable.pipe(
take(1)
).subscribe(() => this._updatePlacement(true));
}
close() {
if (this._opened) {
this._opened = false;
this._overlayRef?.detach();
this._keyManager.withHorizontalOrientation(this._theme.variables.direction);
this._cd.markForCheck();
this.onTouched();
}
}
/** @docs-private */
onContainerClick() {
this.focus();
this.open();
}
/** Focuses the select element. */
focus(options?: FocusOptions): void {
this._getHostElement().focus(options);
}
_getHostElement() {
return this._el.nativeElement;
}
/**
* Sets the "value" property on the input element.
*
* @param value The checked value
*/
writeValue(value: any): void {
this.value = value;
}
/**
* Registers a function called when the control value changes.
*
* @param fn The callback function
*/
registerOnChange(fn: (value: any) => any): void {
this.onChange = (_valueString: string) => {
fn(this.value);
};
}
/**
* Registers a function called when the control is touched.
*
* @param fn The callback function
*/
registerOnTouched(fn: () => any): void { this.onTouched = fn; }
/**
* Disables the select. Part of the ControlValueAccessor interface required
* to integrate with Angular's core forms API.
*
* @param isDisabled Sets whether the component is disabled.
*/
setDisabledState(isDisabled: boolean) {
this.disabled = isDisabled;
this._cd.markForCheck();
this.stateChanges.next();
}
/** Handles all keydown events on the select. */
_handleKeydown(event: KeyboardEvent): void {
if (!this.disabled) {
this._opened ? this._handleOpenKeydown(event) : this._handleClosedKeydown(event);
}
}
/** Handles keyboard events while the select is closed. */
private _handleClosedKeydown(event: KeyboardEvent): void {
const keyCode = event.keyCode;
const isArrowKey = keyCode === DOWN_ARROW || keyCode === UP_ARROW ||
keyCode === LEFT_ARROW || keyCode === RIGHT_ARROW;
const isOpenKey = keyCode === ENTER || keyCode === SPACE;
const manager = this._keyManager;
// Open the select on ALT + arrow key to match the native <select>
if (!manager.isTyping() && (isOpenKey && !hasModifierKey(event)) ||
((this.multiple || event.altKey) && isArrowKey)) {
event.preventDefault(); // prevents the page from scrolling down when pressing space
this.open();
} else if (!this.multiple) {
manager.onKeydown(event);
}
}
/** Handles keyboard events when the selected is open. */
private _handleOpenKeydown(event: KeyboardEvent): void {
const manager = this._keyManager;
const keyCode = event.keyCode;
const isArrowKey = keyCode === DOWN_ARROW || keyCode === UP_ARROW;
const isTyping = manager.isTyping();
if (isArrowKey && event.altKey) {
// Close the select on ALT + arrow key to match the native <select>
event.preventDefault();
this.close();
// Don't do anything in this case if the user is typing,
// because the typing sequence can include the space key.
} else if (!isTyping && (keyCode === ENTER || keyCode === SPACE) && manager.activeItem &&
!hasModifierKey(event)) {
event.preventDefault();
manager.activeItem._selectViaInteraction();
} else if (!isTyping && this._multiple && keyCode === A && event.ctrlKey) {
event.preventDefault();
const hasDeselectedOptions = this.options.some(opt => !opt.disabled && !opt.selected);
this.options.forEach(option => {
if (!option.disabled) {
hasDeselectedOptions ? option.select() : option.deselect();
}
});
} else {
const previouslyFocusedIndex = manager.activeItemIndex;
manager.onKeydown(event);
if (this._multiple && isArrowKey && event.shiftKey && manager.activeItem &&
manager.activeItemIndex !== previouslyFocusedIndex) {
manager.activeItem._selectViaInteraction();
}
}
}
private _initializeSelection(): void {
// Defer setting the value in order to avoid the "Expression
// has changed after it was checked" errors from Angular.
Promise.resolve().then(() => {
this._setSelectionByValue(this.ngControl ? this.ngControl.value : this._value);
this.stateChanges.next();
});
}
/**
* Sets the selected option based on a value. If no option can be
* found with the designated value, the select trigger is cleared.
*/
private _setSelectionByValue(value: any | any[]): void {
if (this.multiple && value) {
if (!Array.isArray(value) && isDevMode()) {
throw getLySelectNonArrayValueError();
}
this._selectionModel.clear();
value.forEach((currentValue: any) => this._selectValue(currentValue));
this._sortValues();
} else {
this._selectionModel.clear();
const correspondingOption = this._selectValue(value);
// Shift focus to the active item. Note that we shouldn't do this in multiple
// mode, because we don't know what option the user interacted with last.
if (correspondingOption) {
this._keyManager.updateActiveItem(correspondingOption);
} else if (!this._opened) {
// Otherwise reset the highlighted option. Note that we only want to do this while
// closed, because doing it while open can shift the user's focus unnecessarily.
this._keyManager.updateActiveItem(-1);
}
}
this._cd.markForCheck();
}
/**
* Finds and selects and option based on its value.
* @returns Option that has the corresponding value.
*/
private _selectValue(value: any): LyOption | undefined {
const correspondingOption = this.options.find((option: LyOption) => {
if (this._valueKey !== same) {
return this.valueKey(option.value) === this.valueKey(value);
}
try {
// Treat null as a special reset value.
return option.value != null && this._compareWith(option.value, value);
} catch (error) {
if (isDevMode()) {
// Notify developers of errors in their comparator.
console.warn(error);
}
return false;
}
});
if (correspondingOption) {
this._selectionModel.select(correspondingOption);
}
return correspondingOption;
}
private _updatePlacement(updateScroll: boolean) {
const el = this._overlayRef!.containerElement as HTMLElement;
const container = el.querySelector('div')!;
const triggerFontSize = this._triggerFontSize;
const { nativeElement } = this.valueTextDivRef;
let panelWidth: number;
if (this.multiple) {
panelWidth = nativeElement.offsetWidth + triggerFontSize * 4;
} else {
panelWidth = nativeElement.offsetWidth + triggerFontSize * 2;
}
// reset height & width
this._renderer.setStyle(container, 'height', 'initial');
this._renderer.setStyle(container, 'width', `${panelWidth}px`);
let selectedElement: HTMLElement | null = this._selectionModel.isEmpty()
? el.querySelector('ly-option')
: this._selectionModel.selected[0]._getHostElement() as HTMLElement;
if (!selectedElement) {
selectedElement = (el.firstElementChild!.firstElementChild! || el.firstElementChild!) as HTMLElement;
}
const offset = {
y: -(nativeElement.offsetHeight / 2 + selectedElement.offsetTop + selectedElement.offsetHeight / 2),
x: -triggerFontSize
};
// scroll to selected option
if (container.scrollHeight !== container.offsetHeight) {
if (updateScroll) {
if (container.scrollTop === selectedElement.offsetTop) {
container.scrollTop = container.scrollTop - (container.offsetHeight / 2) + selectedElement.offsetHeight / 2;
} else {
container.scrollTop = container.scrollTop
- (container.offsetHeight / 2 - (selectedElement.offsetTop - container.scrollTop)) + selectedElement.offsetHeight / 2;
}
}
offset.y = container.scrollTop + offset.y;
}
if (this.multiple) {
offset.x -= 24;
}
const position = new Positioning(
YPosition.below,
XPosition.after,
null as any,
nativeElement,
el,
this._theme.variables,
offset,
false
);
// set position
this._renderer.setStyle(el, 'transform', `translate3d(${position.x}px, ${position.y}px, 0)`);
this._renderer.setStyle(el, 'transform-origin', `${position.ox} ${position.oy} 0`);
// set height & width
this._renderer.setStyle(container, 'height', position.height);
const width = position.width === 'initial'
? `${panelWidth}px`
: position.width;
this._renderer.setStyle(container, 'width', width);
}
/** Sets up a key manager to listen to keyboard events on the overlay panel. */
private _initKeyManager() {
this._keyManager = new ActiveDescendantKeyManager<LyOption>(this.options)
.withTypeAhead(this._typeaheadDebounceInterval)
.withVerticalOrientation()
.withHorizontalOrientation(this._theme.variables.direction)
.withHomeAndEnd()
.withAllowedModifierKeys(['shiftKey']);
this._keyManager.tabOut.pipe(takeUntil(this._destroy)).subscribe(() => {
if (this._opened) {
// Select the active item when tabbing away. This is consistent with how the native
// select behaves. Note that we only want to do this in single selection mode.
if (!this.multiple && this._keyManager.activeItem) {
this._keyManager.activeItem._selectViaInteraction();
}
// Restore focus to the trigger before closing. Ensures that the focus
// position won't be lost if the user got focus into the overlay.
this.focus();
this.close();
}
});
this._keyManager.change.pipe(takeUntil(this._destroy)).subscribe(() => {
if (this._opened) {
this._scrollActiveOptionIntoView();
} else if (!this._opened && !this.multiple && this._keyManager.activeItem) {
this._keyManager.activeItem._selectViaInteraction();
}
});
}
/** Sorts the selected values in the selected based on their order in the panel. */
private _sortValues() {
if (this.multiple) {
const options = this.options.toArray();
this._selectionModel.sort((a, b) => {
return this.sortComparator ? this.sortComparator(a, b, options) :
options.indexOf(a) - options.indexOf(b);
});
this.stateChanges.next();
}
}
private _resetOptions(): void {
const changedOrDestroyed = merge(this.options.changes, this._destroy);
this.optionSelectionChanges.pipe(takeUntil(changedOrDestroyed)).subscribe(event => {
this._onSelect(event.source, event.isUserInput);
if (event.isUserInput && !this.multiple && this._opened) {
this.close();
this.focus();
}
});
}
/** Invoked when an option is clicked. */
private _onSelect(option: LyOption, isUserInput: boolean): void {
const wasSelected = this._selectionModel.isSelected(option);
if (option.value == null && !this._multiple) {
option.deselect();
this._selectionModel.clear();
if (this.value != null) {
this._propagateChanges(option.value);
}
} else {
if (wasSelected !== option.selected) {
option.selected ? this._selectionModel.select(option) :
this._selectionModel.deselect(option);
}
if (isUserInput) {
this._keyManager.setActiveItem(option);
}
if (this.multiple) {
this._sortValues();
if (isUserInput) {
// In case the user selected the option with their mouse, we
// want to restore focus back to the trigger, in order to
// prevent the select keyboard controls from clashing with
// the ones from `ly-option`.
this.focus();
}
}
}
if (wasSelected !== this._selectionModel.isSelected(option)) {
this._propagateChanges();
}
this.stateChanges.next();
}
/** Emits change event to set the model value. */
private _propagateChanges(fallbackValue?: any): void {
let valueToEmit: any = null;
if (this.multiple) {
valueToEmit = (this.selected as LyOption[]).map(option => option.value);
} else {
valueToEmit = this.selected ? (this.selected as LyOption).value : fallbackValue;
}
this._value = valueToEmit;
this.valueChange.emit(valueToEmit);
this.onChange(valueToEmit);
this.selectionChange.emit(new LySelectChange(this, valueToEmit));
this._cd.markForCheck();
}
/**
* Highlights the selected item. If no option is selected, it will highlight
* the first item instead.
*/
private _highlightCorrectOption(): void {
if (this._keyManager) {
if (this.empty) {
this._keyManager.setFirstItemActive();
} else {
this._keyManager.setActiveItem(this._selectionModel.selected[0]);
}
}
}
/** Scrolls the active option into view. */
private _scrollActiveOptionIntoView(): void {
const el = this._overlayRef!.containerElement as HTMLElement;
const container = el.querySelector('div')!;
const activeOption = this._keyManager.activeItem!._getHostElement();
// const containerRect = container.getBoundingClientRect();
// const activeOptionRect = ;
if (typeof activeOption.scrollIntoView === 'function') {
if (container.scrollTop > activeOption.offsetTop) {
container.scrollTop = activeOption.offsetTop;
} else if (
container.scrollTop + container.offsetHeight < activeOption.offsetTop + activeOption.offsetHeight
) {
container.scrollTop = activeOption.offsetTop - container.offsetHeight + activeOption.offsetHeight;
}
}
}
}
/** Event object emitted by LyOption when selected or deselected. */
export class LyOptionSelectionChange {
constructor(
/** Reference to the option that emitted the event. */
public source: LyOption,
/** Whether the change in the option's value was a result of a user action. */
public isUserInput = false) { }
}
/** @docs-private */
export class LyOptionBase {
constructor(
public _theme: LyTheme2,
public _ngZone: NgZone,
public _platform: Platform
) { }
}
/** @docs-private */
export const LyOptionMixinBase = mixinDisableRipple(LyOptionBase);
/**
* @dynamic
*/
@Component({
selector: 'ly-option',
templateUrl: './option.html',
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'role': 'option',
'(keydown)': '_handleKeydown($event)',
'[attr.tabindex]': '_getTabIndex()',
},
inputs: [
'disableRipple'
],
providers: [
StyleRenderer
]
})
export class LyOption extends LyOptionMixinBase implements WithStyles, FocusableOption, OnInit, OnChanges {
/** @docs-private */
readonly classes = this._theme.addStyleSheet(STYLES, STYLE_PRIORITY);
private _value: any;
private _selected = false;
private _disabled = false;
@ViewChild('rippleContainer') _rippleContainer: ElementRef;
/** Event emitted when the option is selected or deselected. */
// tslint:disable-next-line: no-output-on-prefix
@Output() readonly onSelectionChange = new EventEmitter<LyOptionSelectionChange>();
@HostListener('click') _onClick() {
this._selectViaInteraction();
}
/** Whether or not the option is currently selected. */
get selected(): boolean { return this._selected; }
/** Whether the wrapping component is in multiple selection mode. */
get multiple() { return this._select && this._select.multiple; }
/**
* Tracks simple string values bound to the option element.
*/
@Input('value')
set value(value: any) {
this._value = value;
}
get value() {
return this._value;
}
/** Whether the option is disabled. */
@Input()
set disabled(value: any) {
this._disabled = coerceBooleanProperty(value);
}
get disabled() {
return this._disabled;
}
@Style<string | null>(
value => (theme: ThemeVariables) => lyl `{
color: ${theme.colorOf(value)}
}`
)
_selectedColor: string | null;
/** The displayed value of the option. */
get viewValue(): string {
return ((this._getHostElement() as Element).textContent || '').trim();
}
/** The color of Select option */
get _color() {
return this._selected ? this._select._field.color : null;
}
/**
* @deprecated use instead `selected`
*/
get isSelected(): boolean {
return this._selected;
}
constructor(readonly sRenderer: StyleRenderer,
/** @internal */
readonly _select: LySelect,
private _el: ElementRef,
/** @internal */
public _rippleService: LyRippleService,
_renderer: Renderer2,
_theme: LyTheme2,
/** @internal */
public _cd: ChangeDetectorRef,
_ngZone: NgZone,
platform: Platform
) {
super(_theme, _ngZone, platform);
_renderer.addClass(_el.nativeElement, this.classes.option);
this._triggerElement = _el;
}
ngOnInit() {
if (this.disableRipple == null) {
this.disableRipple = DEFAULT_DISABLE_RIPPLE;
}
}
ngOnChanges() { }
/** Applies the styles for an active item to this item. */
setActiveStyles(): void {
this.sRenderer.addClass(this.classes.optionActive);
}
/** Applies the styles for an inactive item to this item. */
setInactiveStyles(): void {
this.sRenderer.removeClass(this.classes.optionActive);
}
/** Gets the label to be used when determining whether the option should be focused. */
getLabel(): string {
return this.viewValue;
}
/** Selects the option. */
select(): void {
if (!this._selected) {
this._selected = true;
this._selectedColor = this._color;
this._cd.markForCheck();
this._emitSelectionChangeEvent();
}
}
/** Deselects the option. */
deselect(): void {
if (this._selected) {
this._selected = false;
this._selectedColor = null;
this._cd.markForCheck();
this._emitSelectionChangeEvent();
}
}
/** Sets focus onto this option. */
focus(_origin?: FocusOrigin, options?: FocusOptions) {
const element = this._getHostElement();
if (typeof element.focus === 'function') {
element.focus(options);
}
}
/** Ensures the option is selected when activated from the keyboard. */
_handleKeydown(event: KeyboardEvent): void {
// tslint:disable-next-line: deprecation
if ((event.keyCode === ENTER || event.keyCode === SPACE) && !hasModifierKey(event)) {
this._selectViaInteraction();
// Prevent the page from scrolling down and form submits.
event.preventDefault();
}
}
/**
* `Selects the option while indicating the selection came from the user. Used to
* determine if the select's view -> model callback should be invoked.`
*/
_selectViaInteraction(): void {
if (!this.disabled) {
this._selected = this.multiple ? !this._selected : true;
this._selectedColor = this._color;
this._cd.markForCheck();
this._emitSelectionChangeEvent(true);
}
}
/** @internal */
_getHostElement(): HTMLElement {
return this._el.nativeElement;
}
/** Returns the correct tabindex for the option depending on disabled state. */
_getTabIndex(): string {
return this.disabled ? '-1' : '0';
}
/** Emits the selection change event. */
private _emitSelectionChangeEvent(isUserInput = false): void {
this.onSelectionChange.emit(new LyOptionSelectionChange(this, isUserInput));
}
}
function same(o: unknown): unknown {
return o;
} | the_stack |
import SceneItem, { getEntries } from "../../src/SceneItem";
import { THRESHOLD } from "../../src/consts";
import { EASE_IN_OUT } from "../../src/easing";
import removeProperty from "./injections/ClassListInjection";
import { orderByASC, group, waitEvent } from "./TestHelper";
import { setRole, toFixed } from "../../src/utils";
import Animator from "../../src/Animator";
import * as sinon from "sinon";
import { isTemplateSpan } from "typescript";
import Scene from "../../src/Scene";
import { DirectionType } from "../../src/types";
import { Frame } from "../../src";
describe("SceneItem Test", () => {
describe("test item initialize", () => {
it("should check default item", () => {
const item = new SceneItem({
0: {
a: 1,
},
1: {
display: "block",
a: 2,
},
});
item.mergeFrame(2, item.getFrame(0));
expect(item.get(0, "a")).to.be.equals(1);
expect(item.get(1, "display")).to.be.equals("block");
expect(item.get(1, "a")).to.be.equals(2);
expect(item.get(2, "a")).to.be.equals(1);
expect(item.size()).to.be.equals(3);
});
it("should check array item", () => {
const item = new SceneItem([{
a: 1,
}]);
const item2 = new SceneItem([
{
a: 1,
},
{
a: 2,
},
{
a: 3,
},
]);
const item3 = new SceneItem([
{
a: 1,
},
{
a: 2,
},
{
a: 3,
},
], {
duration: 2,
});
expect(item.get(0, "a")).to.be.equals(1);
expect(item.getDuration()).to.be.equals(0);
expect(item2.get(0, "a")).to.be.equals(1);
expect(item2.get(100, "a")).to.be.equals(3);
expect(item2.get("0%", "a")).to.be.equals(1);
expect(item2.get("50%", "a")).to.be.equals(2);
expect(item2.get("100%", "a")).to.be.equals(3);
expect(item2.get("from", "a")).to.be.equals(1);
expect(item2.get("to", "a")).to.be.equals(3);
expect(item2.getDuration()).to.be.equals(100);
expect(item3.get(0, "a")).to.be.equals(1);
expect(item3.get(1, "a")).to.be.equals(2);
expect(item3.get(2, "a")).to.be.equals(3);
expect(item2.get("from", "a")).to.be.equals(1);
expect(item2.get("to", "a")).to.be.equals(3);
expect(item3.getDuration()).to.be.equals(2);
});
it("should check array item", () => {
const item = new SceneItem({ keyframes: { 0: { opacity: 0 }, 1: { opacity: 1 } } });
expect(item.getDuration()).to.be.equals(1);
expect(item.get(0, "opacity")).to.be.equals(0);
expect(item.get(1, "opacity")).to.be.equals(1);
});
it("should check floating-point", () => {
// Given, When
const item = new SceneItem({
[1 / 3]: "opacity: 0.5",
[1 + 2]: "opacity: 1",
});
// Then
expect(item.get(1 / 3, "opacity")).to.be.equals("0.5");
expect(item.get(1 + 2, "opacity")).to.be.equals("1");
});
it("should check array property", () => {
// Given, When
const item = new SceneItem({
opacity: [0, 1],
});
const item2 = new SceneItem({
transform: {
translate: ["0px", "20px"],
},
});
const item3 = new SceneItem({
transform: [
"translate(0px)",
"translate(20px)",
],
});
// Then
expect(item.getDuration()).to.be.equals(100);
expect(item.get(0, "opacity")).to.be.equals(0);
expect(item.get("100%", "opacity")).to.be.equals(1);
expect(item2.get(0, "transform", "translate")).to.be.equals("0px");
expect(item2.get("100%", "transform", "translate")).to.be.equals("20px");
expect(item3.get(0, "transform", "translate")).to.be.equals("0px");
expect(item3.get("100%", "transform", "translate")).to.be.equals("20px");
});
it("should check multiple time", () => {
// Given, When
const item = new SceneItem({
"0, 1": {
opacity: 1,
},
});
const item2 = new SceneItem();
const item3 = new SceneItem();
const item4 = new SceneItem();
// When
item2.set("0%, 100%", "opacity", 0.5);
item3.set({
"0, 1": new Frame().set({
opacity: 1,
transform: {
rotate: `100deg`,
scale: 1,
},
}),
});
item4.set({
"0, 0": new Frame().set({
opacity: 1,
transform: {
rotate: `100deg`,
scale: 1,
},
}),
});
// Then
expect(item.getDuration()).to.be.equals(1);
expect(item.get(0, "opacity")).to.be.equals(1);
expect(item.get(1, "opacity")).to.be.equals(1);
expect(item2.getDuration()).to.be.equals(100);
expect(item2.get("0%", "opacity")).to.be.equals(0.5);
expect(item2.get("100%", "opacity")).to.be.equals(0.5);
expect(item3.getDuration()).to.be.equals(1);
expect(item3.get(0, "opacity")).to.be.equals(1);
expect(item3.get(1, "opacity")).to.be.equals(1);
expect(item4.get(0, "transform", "rotate")).to.be.equals("100deg");
});
});
describe("test item method", () => {
let item: SceneItem;
beforeEach(() => {
item = new SceneItem({
0: {
a: 1,
display: "block",
},
0.5: {
a: 1.5,
},
1: {
display: "none",
a: 2,
},
});
});
afterEach(() => {
item = null;
});
it("should check 'setId' method", () => {
// When
item.setId(".a .b");
// Then
expect(item.getId()).to.be.equals(".a .b");
});
it("should check 'get' method with transform", () => {
// Given // When
item.set(0, "transform", {});
// Then
expect(item.getFrame(0).has("transform")).to.be.equals(true);
expect(item.get(0, "transform")).to.be.deep.equals({});
});
it("should check 'getComputedFrame' method", () => {
// Then
expect(item.getComputedFrame(0).get("display")).to.be.equals("block");
expect(item.getComputedFrame(0.5).get("display")).to.be.equals("block");
expect(item.getComputedFrame(0.5).get("a")).to.be.equals(1.5);
expect(item.getComputedFrame(1).get("display")).to.be.equals("none");
});
it("should check 'getComputedFrame' method with wrong easing", () => {
["easdasd", "easde(aa)"].forEach(easing => {
// When
item.setEasing(easing);
// Then
expect(item.getComputedFrame(0).get("display")).to.be.equals("block");
expect(item.getComputedFrame(0.5).get("display")).to.be.equals("block");
expect(item.getComputedFrame(0.5).get("a")).to.be.equals(1.5);
expect(item.getComputedFrame(1).get("display")).to.be.equals("none");
});
});
it("should check 'getComputedFrame' method with easing", () => {
// When
item.setEasing("ease-out");
// Then
expect(item.getComputedFrame(0.25).get("a")).to.be.not.equals(1.25);
expect(item.getComputedFrame(0).get("display")).to.be.equals("block");
expect(item.getComputedFrame(0.5).get("display")).to.be.equals("block");
expect(item.getComputedFrame(0.5).get("a")).to.be.equals(1.5);
expect(item.getComputedFrame(1).get("display")).to.be.equals("none");
});
it("should check 'getComputedFrame' method with steps(start) easing", () => {
// When
item.setEasing("steps(2, start)");
// Then
expect(item.getComputedFrame(0).get("a")).to.be.equals(1);
expect(item.getComputedFrame(0.1).get("a")).to.be.equals(1.25);
expect(item.getComputedFrame(0.2).get("a")).to.be.equals(1.25);
expect(item.getComputedFrame(0.25).get("a")).to.be.equals(1.5);
expect(item.getComputedFrame(0.4).get("a")).to.be.equals(1.5);
expect(item.getComputedFrame(0.5).get("a")).to.be.equals(1.5);
});
it("should check 'getComputedFrame' method with steps(end) easing", () => {
// When
item.setEasing("steps(2, end)");
// Then
expect(item.getComputedFrame(0).get("a")).to.be.equals(1);
expect(item.getComputedFrame(0.2).get("a")).to.be.equals(1);
expect(item.getComputedFrame(0.25).get("a")).to.be.equals(1.25);
expect(item.getComputedFrame(0.4).get("a")).to.be.equals(1.25);
expect(item.getComputedFrame(0.5).get("a")).to.be.equals(1.5);
});
it("should check 'getComputedFrame(true)' method", () => {
// When
item.set(0, "transform", "translate(20px)");
item.set(1, "transform", "scale(0)");
item.set(2, "transform", "translate(40px)");
// Then
expect(item.getComputedFrame(0, 0, true).get("display")).to.be.equals("block");
expect(item.getComputedFrame(0.5, 0, true).get("display")).to.be.not.ok;
expect(item.getComputedFrame(1, 0, true).get("display")).to.be.equals("none");
expect(item.getComputedFrame(0, 0, true).get("transform", "translate")).to.be.equals("20px");
expect(item.getComputedFrame(0.5, 0, true).get("transform", "translate")).to.be.not.ok;
expect(item.getComputedFrame(1, 0, true).get("transform", "translate")).to.be.equals("30px");
expect(item.getComputedFrame(2, 0, true).get("transform", "translate")).to.be.equals("40px");
expect(item.getComputedFrame(0, 0, true).get("transform", "scale")).to.be.equals("0");
expect(item.getComputedFrame(0.5, 0, true).get("transform", "scale")).to.be.not.ok;
expect(item.getComputedFrame(1, 0, true).get("transform", "scale")).to.be.equal("0");
expect(item.getComputedFrame(2, 0, true).get("transform", "scale")).to.be.equal("0");
});
it("should check 'getComputedFrame' method (no 0%)", () => {
item = new SceneItem({
0.5: {
display: "none",
a: 1.5,
filter: { "hue-rotate": "0deg" },
},
1: {
display: "block",
a: 2,
filter: { "hue-rotate": "100deg" },
},
1.2: {
},
});
expect(item.getComputedFrame(0).get("display")).to.be.equals("none");
expect(item.getComputedFrame(0).get("a")).to.be.equals(1.5);
expect(item.getComputedFrame(0.4).get("display")).to.be.equals("none");
expect(item.getComputedFrame(0.4).get("a")).to.be.equals(1.5);
expect(item.getComputedFrame(0.6).get("display")).to.be.equals("none");
expect(item.getComputedFrame(0.75).get("filter", "hue-rotate")).to.be.equals("50deg");
expect(item.getComputedFrame(0.6).get("a")).to.be.equals(1.6);
expect(item.getComputedFrame(1).get("display")).to.be.equals("block");
expect(item.getComputedFrame(1).get("a")).to.be.equals(2);
});
it("should check 'getCurrentFrame' with no needUpdate", () => {
// Given
item = new SceneItem({
0.5: {
display: "none",
a: 1.5,
filter: { "hue-rotate": "0deg" },
},
1: {
display: "block",
a: 2,
filter: { "hue-rotate": "100deg" },
},
1.2: {
},
});
item.setTime(0);
// When
const frame = item.getCurrentFrame();
// Then
expect(frame.get("display")).to.be.equals("none");
})
it("should check 'getFrame' method", () => {
expect(item.getFrame(0).get("display")).to.be.equals("block");
expect(item.getFrame(0.7)).to.be.not.ok;
expect(item.getFrame(1).get("display")).to.be.equals("none");
});
it("should check 'setOrders', 'getFrame' method", () => {
// Given
item.set(0, {
transform: "translate(10px) scale(2)",
});
const css1 = item.getFrame(0).toCSS();
const css2 = item.getComputedFrame(0).toCSS();
const css3 = item.getComputedFrame(0, undefined, true).toCSS();
// When
item.setOrders(["transform"], ["scale", "translate"]);
const css4 = item.getFrame(0).toCSS();
const css5 = item.getComputedFrame(0).toCSS();
const css6 = item.getComputedFrame(0, undefined, true).toCSS();
// Then
expect(css1).to.have.string("translate(10px) scale(2)");
expect(css2).to.have.string("translate(10px) scale(2)");
expect(css3).to.have.string("translate(10px) scale(2)");
expect(css4).to.have.string("scale(2) translate(10px)");
expect(css5).to.have.string("scale(2) translate(10px)");
expect(css6).to.have.string("scale(2) translate(10px)");
});
it("should check 'hasFrame' method", () => {
expect(item.hasFrame("0")).to.be.true;
expect(item.hasFrame("0.5")).to.be.true;
expect(item.hasFrame("1")).to.be.true;
expect(item.hasFrame("1.2")).to.be.false;
});
it("should check 'removeFrame' method", () => {
expect(item.hasFrame("0")).to.be.true;
expect(item.hasFrame("1")).to.be.true;
item.removeFrame(0);
expect(item.hasFrame("0")).to.be.false;
expect(item.getDuration()).to.be.equals(1);
item.removeFrame(1);
expect(item.hasFrame("1")).to.be.false;
expect(item.getDuration()).to.be.equals(0.5);
});
it("should check dot function", () => {
let vari = 0;
item = new SceneItem({
0: {
a: "rgb(0, 0, 0)",
b: 0,
c: () => {
return vari;
},
},
1: {
a: () => {
return "rgb(200, 200, 200)";
},
b: () => {
return vari;
},
c: () => {
return vari + 2;
},
},
});
[0, 0.2, 0.5, 0.7, 1].forEach((t, i) => {
const frame = item.getComputedFrame(t);
if (t !== 1) {
expect(frame.get("a")).to.be.equals(`rgba(${200 * t},${200 * t},${200 * t},1)`);
expect(frame.get("b")).to.be.equals(i * t);
} else {
expect(frame.get("a")).to.be.equals(`rgb(200, 200, 200)`);
}
expect(frame.get("c")).to.be.closeTo(i + 2 * t, 0.001);
expect(frame.get("b")).to.be.equals(i * t);
++vari;
});
});
it("should check 'set' method", () => {
item.set(0.5, "a", 1);
item.set(0.6, "transform", "a", 1);
item.set(0.7, "b", "b");
item.set(1, "display", "block");
item.set(1, "c", 1);
item.set(1, "d:1;e:2;f:a;transform:translate(10px, 20px);");
[0.8, 1, 1.2, 1.4].forEach(time => item.set(time, "c", 1));
[0.8, 1, 1.2, 1.4].forEach(time => item.set(time, "g:1;h:5;transform:scale(5);"));
item.set({
5: {
a: 1,
b: 2,
},
10: {
a: 4,
b: 5,
},
});
item.set(12, [
{
a: 1,
b: 2,
},
{
c: 1,
d: 2,
},
]);
expect(item.getFrame(0.5).get("a")).to.be.equals(1);
expect(item.getFrame(0.6).get("transform", "a")).to.be.equals(1);
expect(item.getFrame(0.7).get("b")).to.be.equals("b");
expect(item.getFrame(1).get("display")).to.be.equals("block");
expect(item.getFrame(1).get("a")).to.be.equals(2);
expect(item.getFrame(5).get("a")).to.be.equals(1);
expect(item.getFrame(5).get("b")).to.be.equals(2);
expect(item.getFrame(10).get("a")).to.be.equals(4);
expect(item.getFrame(10).get("b")).to.be.equals(5);
expect(parseFloat(item.getFrame(1).get("d"))).to.be.equals(1);
[0.8, 1, 1.2, 1.4].forEach(time => {
expect(item.getFrame(time).get("c")).to.be.equals(1);
expect(item.getFrame(time).get("g")).to.be.equals("1");
expect(item.getFrame(time).get("h")).to.be.equals("5");
});
expect(item.getFrame(12).get("a")).to.be.equals(1);
expect(item.getFrame(12).get("b")).to.be.equals(2);
expect(item.getFrame(12).get("c")).to.be.equals(1);
expect(item.getFrame(12).get("d")).to.be.equals(2);
});
it("should check 'remove' method", () => {
// When
item.remove(0, "a");
// Then
expect(item.get(0, "a")).to.be.not.equals(1);
});
it("should check 'getDuration' method", () => {
// Given
// When
item.setDuration(10);
// Then
expect(item.getDuration()).to.be.equals(10);
expect(item.getActiveDuration()).to.be.equals(10);
expect(item.getTotalDuration()).to.be.equals(10);
// When
item.setDelay(5);
// Then
expect(item.getDuration()).to.be.equals(10);
expect(item.getActiveDuration()).to.be.equals(10);
expect(item.getTotalDuration()).to.be.equals(15);
});
it("should check 'setDuration' with no frame", () => {
item = new SceneItem({});
item.setDuration(0);
expect(item.getDuration()).to.be.equals(0);
});
it("should check 'setDuration' option", () => {
item = new SceneItem({
"0%": {
transform: "translate(0px, 0px) rotate(0deg)",
},
"25%": {
transform: "translate(200px, 0px) rotate(90deg)",
},
"50%": {
transform: "translate(200px, 200px) rotate(180deg)",
},
"75%": {
transform: "translate(0px, 200px) rotate(270deg)",
},
"100%": {
transform: "translate(0px, 0px) rotate(360deg)",
},
}, {
duration: 3,
});
const item2 = new SceneItem({
0: {
transform: "translate(0px, 0px) rotate(0deg)",
},
1: {
transform: "translate(200px, 0px) rotate(90deg)",
},
2: {
transform: "translate(200px, 200px) rotate(180deg)",
},
3: {
transform: "translate(0px, 200px) rotate(270deg)",
},
4: {
transform: "translate(0px, 0px) rotate(360deg)",
},
}, {
duration: 3,
});
expect(item.getDuration()).to.be.equals(3);
expect(item2.getDuration()).to.be.equals(3);
});
it("should check 'getDuration' method with iterationCount", () => {
// Given
// When
item.setDuration(10);
item.setIterationCount(2);
// Then
expect(item.getDuration()).to.be.equals(10);
expect(item.getActiveDuration()).to.be.equals(20);
expect(item.getTotalDuration()).to.be.equals(20);
// When
item.setDelay(5);
// Then
expect(item.getDuration()).to.be.equals(10);
expect(item.getActiveDuration()).to.be.equals(20);
expect(item.getTotalDuration()).to.be.equals(25);
// When
item.setIterationCount("infinite");
// Then
expect(item.getDuration()).to.be.equals(10);
expect(item.getActiveDuration()).to.be.equals(Infinity);
expect(item.getTotalDuration()).to.be.equals(Infinity);
});
it("should check 'from, to' method", () => {
// Given
// When
item.setDuration(10);
item.load({
from: {
a: 1,
},
to: {
a: 2,
},
});
// Then
expect(item.getDuration()).to.be.equals(10);
expect(item.get("from", "a")).to.be.equal(1);
expect(item.get("to", "a")).to.be.equal(2);
expect(item.get("50%", "a")).to.be.equal(1.5);
});
it("should check 'clone' method", () => {
// Given
/*
item = new SceneItem({
0: {
a: 1,
display: "block",
},
0.5: {
a: 1.5,
},
1: {
display: "none",
a: 2,
},
});
*/
const item1 = item.clone();
// Then
expect(item.getDuration()).to.be.equals(1);
expect(item1.getDuration()).to.be.equals(1);
expect(item.get("from", "a")).to.be.equal(1);
expect(item.get("to", "a")).to.be.equal(2);
expect(item.get("50%", "a")).to.be.equal(1.5);
expect(item1.get("from", "a")).to.be.equal(1);
expect(item1.get("to", "a")).to.be.equal(2);
expect(item1.get("50%", "a")).to.be.equal(1.5);
expect(item1.getComputedFrame(0).get("a")).to.be.equal(1);
expect(item1.getComputedFrame(1).get("a")).to.be.equal(2);
expect(item1.getComputedFrame(0.5).get("a")).to.be.equal(1.5);
expect(item1.getDelay()).to.be.equal(0);
expect(item.constructor).to.be.equals(item1.constructor);
});
it(`should check 'mergeFrame' method`, () => {
/*
0: {
a: 1,
display: "block",
},
"0.5": {
a: 1.5,
},
1: {
display: "none",
a: 2,
},
*/
// Given
item.set(0.5, "b", 2);
item.set(0.7, "c", 3);
// When
item.mergeFrame(1.5, item.getFrame(0.5));
item.mergeFrame(1.5, item.getFrame(1));
item.mergeFrame(1.5, item.getFrame(0.7));
item.mergeFrame(1.5, item.getFrame(0.8));
expect(item.getFrame(1.5).get("a")).to.be.deep.equals(2);
expect(item.getFrame(1.5).get("b")).to.be.deep.equals(2);
expect(item.getFrame(1.5).get("c")).to.be.deep.equals(3);
expect(item.getFrame(1.5).get("display")).to.be.deep.equals("none");
});
it("should check no frame", () => {
item = new SceneItem({});
item.setTime(0);
expect(item.getDuration()).to.be.equals(0);
expect(item.getTime()).to.be.equals(0);
});
});
describe("test item events", () => {
let item: SceneItem;
beforeEach(() => {
item = new SceneItem({
0: {
a: 1,
display: "block",
},
1: {
display: "none",
a: 2,
},
}, {
iterationCount: 4,
});
});
afterEach(() => {
item = null;
});
it("should check 'animate' event", done => {
item.on("animate", ({ time, frame, currentTime }) => {
expect(time).to.be.equals(0.5);
expect(currentTime).to.be.equals(1.5);
expect(frame.get("a")).to.be.equals(1.5);
expect(frame.get("display")).to.be.equals("block");
done();
});
item.setTime(1.5);
});
});
describe("test frame for CSS", () => {
let element: HTMLElement;
let item: SceneItem;
beforeEach(() => {
element = document.createElement("div");
item = new SceneItem({
0: {
a: 1,
},
0.5: {
a: 3,
},
1: {
display: "block",
a: 2,
},
});
});
afterEach(() => {
element = null;
document.body.innerHTML = "";
});
it("should check 'setId' method (Element)", () => {
// Given
item.elements = [element];
// When
item.setId(".a .b");
// Then
expect(item.state.id).to.be.equals(".a .b");
expect(item.state.selector).to.be.equals(`[data-scene-id="ab"]`);
expect(item.elements[0].getAttribute("data-scene-id")).to.be.equal("ab");
});
it("should check 'setSelector' method", () => {
// Given
document.body.appendChild(element);
// When
item.setSelector("div");
// Then
expect(item.state.selector).to.be.equals("div");
expect(item.elements[0].getAttribute("data-scene-id")).to.be.not.ok;
});
it("should check 'setSelector' method(peusdo)", () => {
// Given
document.body.appendChild(element);
// When
item.setSelector("div:before");
// Then
expect(item.state.selector).to.be.equals("div:before");
expect(item.elements[0].tagName).to.be.equals("DIV");
});
it("should check 'setElement' method", () => {
// Given
// When
item.setElement(element);
const id = item.elements[0].getAttribute("data-scene-id");
// Then
expect(item.state.id).to.be.equals(id);
expect(item.state.selector).to.be.equals(`[data-scene-id="${id}"]`);
expect(item.elements[0]).to.be.equals(element);
});
it("should check 'setElement' method with 'attribute'", () => {
// Given
item.setElement(element);
item.set(1, "attribute", "a", 1);
// When
item.setTime(1);
// Then
expect(item.elements[0].getAttribute("a")).to.be.equals("1");
});
it("should check 'setElement' method (already has id)", () => {
// Given
item.state.id = "id123";
// When
item.setElement(element);
const id = item.elements[0].getAttribute("data-scene-id");
// Then
expect(item.state.id).to.be.equals(id);
expect(item.state.id).to.be.equals("id123");
expect(item.elements[0]).to.be.equals(element);
});
it("should check 'setElement' method (already has selector)", () => {
// Given
item.state.selector = "div";
// When
item.setElement(element);
const id = item.elements[0].getAttribute("data-scene-id");
// Then
expect(id).to.be.not.ok;
expect(item.state.selector).to.be.equals(`div`);
expect(item.elements[0]).to.be.equals(element);
});
it("should check 'toKeyframes' method", () => {
// Given
// When
// Then
// console.log(item.toKeyframes());
});
it("should check 'toCSS' method", () => {
// Given
// When
// Then
// console.log(item.toCSS());
});
it(`should check toCSS method with no element`, () => {
const scene = new SceneItem({
0: {
width: "100px",
height: "100px",
},
0.1: {
width: "200px",
height: "200px",
},
}, {
selector: ".noelement",
});
// when
const css = scene.toCSS();
// then
expect(css).to.be.have.string(".noelement.startAnimation");
expect(css).to.be.have.string(".noelement.pauseAnimation");
expect(css).to.be.have.string("width:200px;");
});
it("should check 'setCSS' method", () => {
// Given
element.style.width = "200px";
element.style.border = "5px solid black";
// When
item.setCSS(0, ["width"]);
const width = item.get(0, "width");
item.setCSS(0, ["border"]);
const border = item.get(0, "border");
item.setCSS(0);
document.body.appendChild(element);
item.setElement(element);
item.setCSS(0, ["width"]);
const width2 = item.get(0, "width");
item.setCSS(0, ["border"]);
const border2 = item.get(0, "border");
// Then
expect(width).to.be.undefined;
expect(border).to.be.undefined;
expect(width2).to.be.equals("200px");
expect(border2).to.be.equals("5px solid rgba(0,0,0,1)");
});
it("should check 'exportCSS' method", () => {
// Given
// When
item.setElement(element);
item.exportCSS();
// Then
expect(document.querySelector(`[data-styled-id="${item.styled.className}"]`)).to.be.ok;
});
it(`should check role test`, () => {
// Given
setRole(["html"], true, true);
setRole(["html2"], true, false);
setRole(["html3"], false);
// When
item.set(0, "html", "a(1) b(2) c(3)");
item.set(2, "html", "a(3) b(4) c(5)");
item.set(0, "html2", "a(1) b(2) c(3)");
item.set(2, "html2", "a(3) b(4) c(5)");
item.set(0, "html3", "a(1) b(2) c(3)");
item.set(2, "html3", "a(3) b(4) c(5)");
// Then
const frame = item.getComputedFrame(1);
expect(frame.get("html")).to.be.equals("a(1) b(2) c(3)");
expect(frame.get("html2")).to.be.equals("a(2) b(3) c(4)");
expect(frame.get("html3")).to.be.deep.equals({ a: 2, b: 3, c: 4 });
expect(frame.get("html3", "a")).to.be.deep.equals(2);
expect(frame.get("html3", "b")).to.be.deep.equals(3);
expect(frame.get("html3", "c")).to.be.deep.equals(4);
});
it(`should check 'append' method`, () => {
// 1 3 2
item.append(new SceneItem({
0: {
a: 3,
},
1: {
a: 5,
},
}, {
iterationCount: 1,
}));
item.append(new SceneItem({
0: {
a: 4,
},
1: {
a: 6,
},
}, {
iterationCount: 2,
easing: EASE_IN_OUT,
}));
// Then
expect(item.getDuration()).to.be.equals(3);
expect(item.get(1, "a")).to.be.equals(2);
expect(item.get(1 + THRESHOLD, "a")).to.be.equals(3);
expect(item.get("1>", "a")).to.be.equals(3);
expect(item.get(2, "a")).to.be.equals(5);
expect(item.get(2 + THRESHOLD, "a")).to.be.equals(4);
expect(item.get("2>", "a")).to.be.equals(4);
expect(item.get(3, "a")).to.be.equals(6);
});
it(`should check 'prepend' method`, () => {
item.prepend(new SceneItem({
0: {
a: 3,
},
1: {
a: 5,
},
}, {
iterationCount: 1,
}));
item.prepend({
0: {
a: 4,
},
1: {
a: 6,
},
});
/*
0: {
a: 1,
display: "block",
},
1: {
display: "none",
a: 2,
},
*/
// Then
expect(item.getDuration()).to.be.equals(3);
expect(item.get(0, "a")).to.be.equals(4);
expect(item.get(1, "a")).to.be.equals(6);
expect(item.get("1>", "a")).to.be.equals(3);
expect(item.get(2, "a")).to.be.equals(5);
expect(item.get(2 + THRESHOLD, "a")).to.be.equals(1);
expect(item.get(3, "a")).to.be.equals(2);
});
function testEntries(...animators: Animator[]) {
const states = animators.map(({ state }) => state);
it(`should check 'getEntries' => ${
states.map(({ direction, delay, iterationCount }) =>
`{delay:${delay}, direction:${direction}, iterationCount:${iterationCount}}`).join(",")
}`, () => {
// Given
const entries = getEntries([0, 0.5, 1], states);
const animatorItem = animators[0];
const scene = animators[animators.length - 1];
const delay = scene.getDelay();
entries.forEach(([time, iterationTime], i) => {
const [prevTime] = entries[i - 1] || [-1, -1];
const [nextTime] = entries[i + 1] || [-1, -1];
const currentTime = time - delay;
// When
if (time === scene.getTotalDuration()) {
scene.setTime(currentTime - THRESHOLD);
} else if (time === prevTime) {
// 0
scene.setTime(currentTime + THRESHOLD);
} else if (time === nextTime) {
// duration
scene.setTime(currentTime - THRESHOLD);
} else {
scene.setTime(currentTime, true);
}
const animatorTime = animatorItem.getIterationTime();
// Then
expect(animatorTime).to.be.closeTo(iterationTime, 0.0001);
});
});
}
describe(`should check 'getEntries' function`, () => {
const directions = ["normal", "reverse", "alternate", "alternate-reverse"] as const;
directions.forEach((direction: DirectionType) => {
[0.3, 1, 1.3, 2, 2.3].forEach(iterationCount => {
const item1 = new SceneItem({
0: { a: 1 },
0.5: { a: 3 },
1: { a: 2 },
}, {
iterationCount, direction,
fillMode: "both",
});
const item2 = new SceneItem({
0: { a: 1 },
0.5: { a: 3 },
1: { a: 2 },
}, {
delay: 1, iterationCount, direction,
fillMode: "both",
});
// Then
testEntries(item1);
testEntries(item2);
directions.forEach((direction2: DirectionType) => {
[0.5, 1, 1.5, 2].forEach(iterationCount2 => {
// Given
const scene1 = new Scene({
item1,
}, {
iterationCount: iterationCount2,
direction: direction2,
fillMode: "both",
});
const scene2 = new Scene({
item2,
}, {
iterationCount: iterationCount2,
direction: direction2,
fillMode: "both",
});
// Then
testEntries(item1, scene1);
testEntries(item2, scene2);
});
});
});
});
});
});
[true, false].forEach(hasClassList => {
describe(`test SceneItem events(hasClassList = ${hasClassList})`, () => {
let item: SceneItem;
let element: HTMLElement;
beforeEach(() => {
element = document.createElement("div");
!hasClassList && removeProperty(element, "classList");
document.body.appendChild(element);
item = new SceneItem({
0: {
a: 1,
},
0.1: {
a: 3,
},
0.2: {
display: "block",
a: 2,
},
});
});
afterEach(() => {
document.body.innerHTML = "";
element = null;
item.off();
item = null;
});
it(`should check "playCSS" and event order `, async () => {
// Given
item.setElement(element);
const play = sinon.spy();
const ended = sinon.spy();
const iteration = sinon.spy();
const paused = sinon.spy();
item.on("play", play);
item.on("ended", ended);
item.on("iteration", iteration);
item.on("paused", paused);
// When
item.playCSS();
item.playCSS();
// Then
expect(item.getPlayState()).to.be.equals("running");
expect(item.state.playCSS).to.be.true;
await waitEvent(item, "ended");
expect(play.calledOnce).to.be.true;
expect(iteration.calledOnce).to.be.false;
expect(ended.calledOnce).to.be.true;
expect(paused.calledOnce).to.be.true;
});
it(`should check "playCSS" and replay`, async () => {
// Given
item.setElement(element);
const play = sinon.spy();
const ended = sinon.spy();
item.on("play", play);
item.on("ended", ended);
// When
item.playCSS();
await waitEvent(item, "ended");
// replay
item.playCSS();
await waitEvent(item, "ended");
// Then
expect(play.callCount).to.be.equals(2);
expect(ended.callCount).to.be.equals(2);
});
it(`should check "iteration" event `, done => {
// Given
item.setElement(element);
const play = sinon.spy();
const ended = sinon.spy();
const iteration = sinon.spy();
const paused = sinon.spy();
item.on("play", play);
item.on("ended", ended);
item.on("iteration", iteration);
item.on("paused", paused);
// When
item.setIterationCount(2);
item.playCSS();
item.on("ended", e => {
// Then
expect(play.calledOnce).to.be.true;
expect(iteration.calledOnce).to.be.true;
expect(ended.calledOnce).to.be.true;
expect(paused.calledOnce).to.be.true;
done();
});
});
it(`should check "playCSS" and no elements `, () => {
// Given
// When
item.playCSS();
// Then
expect(item.getPlayState()).to.be.equals("paused");
});
});
});
describe("test property", () => {
let item!: SceneItem;
let element!: HTMLElement;
beforeEach(() => {
element = document.createElement("div");
document.body.appendChild(element);
item = new SceneItem();
item.setElement(element);
});
afterEach(() => {
document.body.innerHTML = "";
element = null;
item.off();
item = null;
});
it("test 'html' property", () => {
// Given
item.set(0, "html", "1");
item.set(1, "html", "2");
item.set(2, "html", "3");
// When
item.setTime(0);
const html1 = element.innerHTML;
item.setTime(0.5);
const html2 = element.innerHTML;
item.setTime(1);
const html3 = element.innerHTML;
item.setTime(2);
const html4 = element.innerHTML;
// then
expect(html1).to.be.equals("1");
expect(html2).to.be.equals("1");
expect(html3).to.be.equals("2");
expect(html4).to.be.equals("3");
});
});
}); | the_stack |
import { existsSync, readFileSync } from "fs";
import * as ts from "typescript";
import { IClassDiagramOptions } from "./classDiagramOptions";
import { Delinter } from "./delint";
import * as formatter from "./formatter/index";
import { IParseOptions } from "./parseOptions";
import * as uml from "./uml/index";
export class TypeScriptUml {
/**
* Parse the source files in a TypeScript project
*
* @static
* @param {string} rootPath Project root path, if tsConfigPath is not defined, the tsconfig.json file
* will be searched in this directory
* @param {string} [tsConfigPath] (Optional) Path to tsconfig.json file
* @returns {uml.CodeModel} The parse results
*
* @memberOf TypeScriptUml
*/
public static parseProject(rootPath: string, options?: IParseOptions): uml.CodeModel {
const _options = this._setDefaultParseOptions(options);
const tsConfig = this._readTsconfig(rootPath, _options);
const delinter = new Delinter();
for (const f of tsConfig.fileNames) {
this.parseFile(f, tsConfig.options.target, undefined, delinter);
}
return delinter.umlCodeModel;
}
/**
* Parse a single TypeScript source file
*
* @static
* @param {string} fileName Source file to parse
* @param {ts.ScriptTarget} target TypeScript compiler script target
* @param {Delinter} [delinter] (Optional) Delinter instance to use for delinting
* @returns {uml.CodeModel} The parse results
*
* @memberOf TypeScriptUml
*/
public static parseFile(
fileName: string,
target: ts.ScriptTarget,
sourceText?: string,
delinter?: Delinter,
): uml.CodeModel {
if (!delinter) {
delinter = new Delinter();
}
if (!sourceText) {
sourceText = readFileSync(fileName).toString();
}
const sourceFile = ts.createSourceFile(fileName, sourceText,
target, /*setParentNodes */ true);
delinter.parse(sourceFile);
return delinter.umlCodeModel;
}
/**
* Generate a uml class diagram from a uml CodeModel description.
*
* @static
* @param {uml.CodeModel} codeModel Uml CodeModel description
* @param {ITypeScriptUmlOptions} [options] Options
* @returns {string} Class diagram formatted according to the specified options
*
* @memberOf TypeScriptUml
*/
public static generateClassDiagram(codeModel: uml.CodeModel, options?: IClassDiagramOptions): string {
let _formatter: formatter.AbstractFormatter = null;
const defaultOptions: IClassDiagramOptions = {
formatter: "yuml",
nodes: {
exclude: null,
include: null,
},
plantuml: {
diagramTags: true,
},
};
if (!options) {
options = {};
}
if (!options.hasOwnProperty("formatter")) {
options.formatter = defaultOptions.formatter;
}
if (!options.hasOwnProperty("nodes")) {
options.nodes = defaultOptions.nodes;
} else {
if (!options.nodes.hasOwnProperty("include")) {
options.nodes.include = defaultOptions.nodes.include;
}
if (!options.nodes.hasOwnProperty("exclude")) {
options.nodes.exclude = defaultOptions.nodes.exclude;
}
}
if (!options.hasOwnProperty("plantuml")) {
options.plantuml = defaultOptions.plantuml;
} else {
if (!options.plantuml.hasOwnProperty("diagramTags")) {
options.plantuml.diagramTags = defaultOptions.plantuml.diagramTags;
}
}
let diagramCodeModel = codeModel;
if (options.nodes.include) {
// Include nodes
diagramCodeModel = this._createIncludeCodeModel(codeModel, options.nodes.include, options.nodes.exclude);
} else if (options.nodes.exclude) {
// Exclude nodes
diagramCodeModel = this._createExcludeCodeModel(codeModel, options.nodes.exclude);
}
switch (options.formatter) {
case "yuml":
_formatter = new formatter.YumlFormatter(options);
break;
case "plantuml":
_formatter = new formatter.PlantUMLFormatter(options);
break;
default:
throw new Error(`Unknown formatter ${options.formatter}`);
}
return _formatter.generateClassDiagram(diagramCodeModel);
}
/* istanbul ignore next: code only used by TypeScript API, which is mocked during tests */
private static _defaultFormatDiagnosticsHost: ts.FormatDiagnosticsHost = {
getCanonicalFileName: (fileName: string) => {
return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
},
getCurrentDirectory: () => ts.sys.getCurrentDirectory(),
getNewLine: () => ts.sys.newLine,
};
/**
* Fill options object with default values for unspecified properties.
*
* @private
* @static
* @param {IParseOptions} [options] Options object
* @returns {IParseOptions} Options object with default values for unspecified properties
*
* @memberOf TypeScriptUml
*/
private static _setDefaultParseOptions(options?: IParseOptions): IParseOptions {
const defaultOptions: IParseOptions = {
exclude: [],
include: null,
tsconfig: null,
};
if (!options) {
options = defaultOptions;
}
Object.keys(defaultOptions).forEach((key) => {
if (!options.hasOwnProperty(key)) {
(options as any)[key] = (defaultOptions as any)[key];
}
});
return options;
}
/**
* Find and parse the tsconfig.json file for the project in the searchPath.
*
* @private
* @static
* @param {string} searchPath Base search path to look for the tsconfig
* @param {string} options Path of the tsconfig.json file to parse (optional)
* @returns {ts.ParsedCommandLine} The parse results
*
* @memberOf TypeScriptUml
*/
private static _readTsconfig(searchPath: string, options: IParseOptions): ts.ParsedCommandLine {
const configPath = options.tsconfig ? options.tsconfig : ts.findConfigFile(searchPath, existsSync);
const config = ts.readConfigFile(configPath, (path) => {
return readFileSync(path).toString();
});
if (config.error) {
const formattedDiagnostic = ts.formatDiagnostics([config.error], this._defaultFormatDiagnosticsHost);
throw new Error(`Failed to read tsconfig file ${configPath}: ${formattedDiagnostic}`);
}
if (options.include) {
config.config.include = options.include;
}
if (options.exclude) {
config.config.exclude = !config.config.exclude ?
options.exclude : (config.config.exclude as string[]).concat(options.exclude);
}
const parsed = ts.parseJsonConfigFileContent(config.config, ts.sys, searchPath);
if (parsed.errors.length > 0) {
const formattedDiagnostic = ts.formatDiagnostics(parsed.errors, this._defaultFormatDiagnosticsHost);
throw new Error(`Failed to parse tsconfig file ${configPath}: ${formattedDiagnostic}`);
}
return parsed;
}
private static _createIncludeCodeModel(
codeModel: uml.CodeModel, include: string[], exclude: string[]): uml.CodeModel {
const newCodeModel = new uml.CodeModel();
if (exclude === null || exclude === undefined) {
exclude = [];
}
codeModel.nodes.forEach((key, node) => {
if (this._isIncluded(node, include) && !this._isExcluded(node, exclude)) {
newCodeModel.nodes.setValue(key, codeModel.nodes.getValue(key));
}
});
codeModel.associations.forEach((association) => {
if (this._isIncluded(association, include) && !this._isExcluded(association, exclude)) {
newCodeModel.associations.add(association);
}
});
codeModel.generalizations.forEach((generalization) => {
if (this._isIncluded(generalization, include) && !this._isExcluded(generalization, exclude)) {
newCodeModel.generalizations.add(generalization);
}
});
return newCodeModel;
}
private static _createExcludeCodeModel(
codeModel: uml.CodeModel, exclude: string[]): uml.CodeModel {
const newCodeModel = new uml.CodeModel();
codeModel.nodes.forEach((key, node) => {
if (!this._isExcluded(node, exclude)) {
newCodeModel.nodes.setValue(key, codeModel.nodes.getValue(key));
}
});
codeModel.associations.forEach((association) => {
if (!this._isExcluded(association, exclude)) {
newCodeModel.associations.add(association);
}
});
codeModel.generalizations.forEach((generalization) => {
if (!this._isExcluded(generalization, exclude)) {
newCodeModel.generalizations.add(generalization);
}
});
return newCodeModel;
}
private static _isIncluded(object: uml.Node | uml.Link, include: string[]): boolean {
const node: uml.Node = object instanceof uml.Node ? object as uml.Node : null;
const link: uml.Link = object instanceof uml.Link ? object as uml.Link : null;
if (node) {
return include.find((value) => {
return node.identifier === value;
}) !== undefined;
} else if (link) {
return include.find((value) => value === link.fromName) !== undefined &&
include.find((value) => value === link.toName) !== undefined;
}
}
private static _isExcluded(object: uml.Node | uml.Link, exclude: string[]): boolean {
const node: uml.Node = object instanceof uml.Node ? object as uml.Node : null;
const link: uml.Link = object instanceof uml.Link ? object as uml.Link : null;
return exclude.find((value) => {
if (node) {
return node.identifier === value;
} else if (link) {
return link.fromName === value || link.toName === value;
}
}) !== undefined;
}
private constructor() {
// Static class, don't allow instantiation
}
} | the_stack |
declare module Check.ServiceModel
{
interface IReturnVoid
{
}
interface IReturn<T>
{
}
interface QueryBase_1<T> extends QueryBase
{
}
interface Rockstar
{
id?:number;
firstName?:string;
lastName?:string;
age?:number;
}
// @DataContract
interface ResponseStatus
{
// @DataMember(Order=1)
errorCode?:string;
// @DataMember(Order=2)
message?:string;
// @DataMember(Order=3)
stackTrace?:string;
// @DataMember(Order=4)
errors?:ResponseError[];
}
interface MetadataTestChild
{
name?:string;
results?:MetadataTestNestedChild[];
}
interface NestedClass
{
value?:string;
}
enum EnumType
{
value1,
value2,
}
// @Flags()
enum EnumFlags
{
value1 = 1,
value2 = 2,
value3 = 4,
}
interface AllTypes
{
id?:number;
nullableId?:number;
byte?:number;
short?:number;
int?:number;
long?:number;
uShort?:number;
uInt?:number;
uLong?:number;
float?:number;
double?:number;
decimal?:number;
string?:string;
dateTime?:string;
timeSpan?:string;
nullableDateTime?:string;
nullableTimeSpan?:string;
stringList?:string[];
stringArray?:string[];
stringMap?:{ [index:string]: string; };
intStringMap?:{ [index:number]: string; };
subType?:SubType;
}
interface AllCollectionTypes
{
intArray?:number[];
intList?:number[];
stringArray?:string[];
stringList?:string[];
pocoArray?:Poco[];
pocoList?:Poco[];
}
interface HelloBase
{
id?:number;
}
interface HelloResponseBase
{
refId?:number;
}
interface Poco
{
name?:string;
}
interface HelloBase_1<T>
{
items?:T[];
counts?:number[];
}
interface Item
{
value?:string;
}
interface InheritedItem
{
name?:string;
}
interface HelloWithReturnResponse
{
result?:string;
}
interface HelloType
{
result?:string;
}
// @DataContract
interface AuthUserSession
{
// @DataMember(Order=1)
referrerUrl?:string;
// @DataMember(Order=2)
id?:string;
// @DataMember(Order=3)
userAuthId?:string;
// @DataMember(Order=4)
userAuthName?:string;
// @DataMember(Order=5)
userName?:string;
// @DataMember(Order=6)
twitterUserId?:string;
// @DataMember(Order=7)
twitterScreenName?:string;
// @DataMember(Order=8)
facebookUserId?:string;
// @DataMember(Order=9)
facebookUserName?:string;
// @DataMember(Order=10)
firstName?:string;
// @DataMember(Order=11)
lastName?:string;
// @DataMember(Order=12)
displayName?:string;
// @DataMember(Order=13)
company?:string;
// @DataMember(Order=14)
email?:string;
// @DataMember(Order=15)
primaryEmail?:string;
// @DataMember(Order=16)
phoneNumber?:string;
// @DataMember(Order=17)
birthDate?:string;
// @DataMember(Order=18)
birthDateRaw?:string;
// @DataMember(Order=19)
address?:string;
// @DataMember(Order=20)
address2?:string;
// @DataMember(Order=21)
city?:string;
// @DataMember(Order=22)
state?:string;
// @DataMember(Order=23)
country?:string;
// @DataMember(Order=24)
culture?:string;
// @DataMember(Order=25)
fullName?:string;
// @DataMember(Order=26)
gender?:string;
// @DataMember(Order=27)
language?:string;
// @DataMember(Order=28)
mailAddress?:string;
// @DataMember(Order=29)
nickname?:string;
// @DataMember(Order=30)
postalCode?:string;
// @DataMember(Order=31)
timeZone?:string;
// @DataMember(Order=32)
requestTokenSecret?:string;
// @DataMember(Order=33)
createdAt?:string;
// @DataMember(Order=34)
lastModified?:string;
// @DataMember(Order=35)
providerOAuthAccess?:IAuthTokens[];
// @DataMember(Order=36)
roles?:string[];
// @DataMember(Order=37)
permissions?:string[];
// @DataMember(Order=38)
isAuthenticated?:boolean;
// @DataMember(Order=39)
sequence?:string;
// @DataMember(Order=40)
tag?:number;
}
interface IPoco
{
name?:string;
}
interface IEmptyInterface
{
}
interface EmptyClass
{
}
// @DataContract
interface RestService
{
// @DataMember(Name="path")
path?:string;
// @DataMember(Name="description")
description?:string;
}
interface QueryBase_2<From, Into> extends QueryBase
{
}
interface CustomRockstar
{
firstName?:string;
lastName?:string;
age?:number;
rockstarAlbumName?:string;
}
interface Movie
{
id?:number;
imdbId?:string;
title?:string;
rating?:string;
score?:number;
director?:string;
releaseDate?:string;
tagLine?:string;
genres?:string[];
}
interface RockstarReference
{
id?:number;
firstName?:string;
lastName?:string;
age?:number;
albums?:RockstarAlbum[];
}
interface QueryBase
{
// @DataMember(Order=1)
skip?:number;
// @DataMember(Order=2)
take?:number;
// @DataMember(Order=3)
orderBy?:string;
// @DataMember(Order=4)
orderByDesc?:string;
}
// @DataContract
interface ResponseError
{
// @DataMember(Order=1, EmitDefaultValue=false)
errorCode?:string;
// @DataMember(Order=2, EmitDefaultValue=false)
fieldName?:string;
// @DataMember(Order=3, EmitDefaultValue=false)
message?:string;
}
interface MetadataTestNestedChild
{
name?:string;
}
interface SubType
{
id?:number;
name?:string;
}
interface IAuthTokens
{
provider?:string;
userId?:string;
accessToken?:string;
accessTokenSecret?:string;
refreshToken?:string;
refreshTokenExpiry?:string;
requestToken?:string;
requestTokenSecret?:string;
items?:{ [index:string]: string; };
}
interface RockstarAlbum
{
id?:number;
rockstarId?:number;
name?:string;
}
// @DataContract
interface QueryResponse<Rockstar>
{
// @DataMember(Order=1)
offset?:number;
// @DataMember(Order=2)
total?:number;
// @DataMember(Order=3)
results?:Rockstar[];
// @DataMember(Order=4)
meta?:{ [index:string]: string; };
// @DataMember(Order=5)
responseStatus?:ResponseStatus;
}
interface ChangeRequestResponse
{
contentType?:string;
header?:string;
queryString?:string;
form?:string;
responseStatus?:ResponseStatus;
}
interface CustomHttpErrorResponse
{
custom?:string;
responseStatus?:ResponseStatus;
}
interface CustomFieldHttpErrorResponse
{
custom?:string;
responseStatus?:ResponseStatus;
}
interface MetadataTestResponse
{
id?:number;
results?:MetadataTestChild[];
}
interface HelloResponse
{
result?:string;
}
/**
* Description on HelloAllResponse type
*/
// @DataContract
interface HelloAnnotatedResponse
{
// @DataMember
result?:string;
}
interface HelloAllTypesResponse
{
result?:string;
allTypes?:AllTypes;
allCollectionTypes?:AllCollectionTypes;
}
// @DataContract
interface HelloWithDataContractResponse
{
// @DataMember(Name="result", Order=1, IsRequired=true, EmitDefaultValue=false)
result?:string;
}
/**
* Description on HelloWithDescriptionResponse type
*/
interface HelloWithDescriptionResponse
{
result?:string;
}
interface HelloWithInheritanceResponse extends HelloResponseBase
{
result?:string;
}
interface HelloWithAlternateReturnResponse extends HelloWithReturnResponse
{
altResult?:string;
}
interface HelloWithRouteResponse
{
result?:string;
}
interface HelloWithTypeResponse
{
result?:HelloType;
}
interface HelloSessionResponse
{
result?:AuthUserSession;
}
interface Echo
{
sentence?:string;
}
interface acsprofileResponse
{
profileId?:string;
}
// @DataContract
interface ResourcesResponse
{
// @DataMember(Name="swaggerVersion")
swaggerVersion?:string;
// @DataMember(Name="apiVersion")
apiVersion?:string;
// @DataMember(Name="basePath")
basePath?:string;
// @DataMember(Name="apis")
apis?:RestService[];
}
// @Route("/anontype")
interface AnonType
{
}
// @Route("/query/rockstars")
interface QueryRockstars extends QueryBase_1<Rockstar>, IReturn<QueryResponse<Rockstar>>
{
age?:number;
}
// @Route("/changerequest/{Id}")
interface ChangeRequest extends IReturn<ChangeRequest>
{
id?:string;
}
// @Route("/Routing/LeadPost.aspx")
interface LegacyLeadPost
{
leadType?:string;
myId?:number;
}
interface CustomHttpError extends IReturn<CustomHttpError>
{
statusCode?:number;
statusDescription?:string;
}
interface CustomFieldHttpError extends IReturn<CustomFieldHttpError>
{
}
interface MetadataTest extends IReturn<MetadataTestResponse>
{
id?:number;
}
// @Route("/hello/{Name}")
interface Hello extends IReturn<Hello>
{
name?:string;
}
/**
* Description on HelloAll type
*/
// @DataContract
interface HelloAnnotated extends IReturn<HelloAnnotatedResponse>
{
// @DataMember
name?:string;
}
interface HelloWithNestedClass extends IReturn<HelloResponse>
{
name?:string;
nestedClassProp?:NestedClass;
}
interface HelloWithEnum
{
enumProp?:EnumType;
nullableEnumProp?:EnumType;
enumFlags?:EnumFlags;
}
interface RestrictedAttributes
{
id?:number;
name?:string;
hello?:Hello;
}
/**
* AllowedAttributes Description
*/
// @Route("/allowed-attributes", "GET")
// @Api("AllowedAttributes Description")
// @ApiResponse(400, "Your request was not understood")
// @DataContract
interface AllowedAttributes
{
// @Default(5)
// @Required()
id:number;
// @DataMember(Name="Aliased")
// @ApiMember(Description="Range Description", ParameterType="path", DataType="double", IsRequired=true)
range?:number;
// @Meta("Foo", "Bar")
// @StringLength(20)
// @References(typeof(Hello))
name?:string;
}
interface HelloAllTypes extends IReturn<HelloAllTypes>
{
name?:string;
allTypes?:AllTypes;
allCollectionTypes?:AllCollectionTypes;
}
interface HelloString
{
name?:string;
}
interface HelloVoid
{
name?:string;
}
// @DataContract
interface HelloWithDataContract extends IReturn<HelloWithDataContract>
{
// @DataMember(Name="name", Order=1, IsRequired=true, EmitDefaultValue=false)
name?:string;
// @DataMember(Name="id", Order=2, EmitDefaultValue=false)
id?:number;
}
/**
* Description on HelloWithDescription type
*/
interface HelloWithDescription extends IReturn<HelloWithDescription>
{
name?:string;
}
interface HelloWithInheritance extends HelloBase, IReturn<HelloWithInheritance>
{
name?:string;
}
interface HelloWithGenericInheritance extends HelloBase_1<Poco>
{
result?:string;
}
interface HelloWithGenericInheritance2 extends HelloBase_1<Hello>
{
result?:string;
}
interface HelloWithNestedInheritance extends HelloBase_1<Item>
{
}
interface HelloWithListInheritance extends Array<InheritedItem>
{
}
interface HelloWithReturn extends IReturn<HelloWithAlternateReturnResponse>
{
name?:string;
}
// @Route("/helloroute")
interface HelloWithRoute extends IReturn<HelloWithRoute>
{
name?:string;
}
interface HelloWithType extends IReturn<HelloWithType>
{
name?:string;
}
interface HelloSession extends IReturn<HelloSessionResponse>
{
}
interface HelloInterface
{
poco?:IPoco;
emptyInterface?:IEmptyInterface;
emptyClass?:EmptyClass;
}
/**
* Echoes a sentence
*/
// @Route("/echoes", "POST")
// @Api("Echoes a sentence")
interface Echoes extends IReturn<Echo>
{
// @ApiMember(Description="The sentence to echo.", ParameterType="form", DataType="string", IsRequired=true, Name="Sentence")
sentence?:string;
}
interface AsyncTest extends IReturn<Echo>
{
}
// @Route("/throwhttperror/{Status}")
interface ThrowHttpError
{
status?:number;
message?:string;
}
// @Route("/api/acsprofiles/{profileId}")
// @Route("/api/acsprofiles", "POST,PUT,PATCH,DELETE")
interface ACSProfile extends IReturn<acsprofileResponse>
{
profileId?:string;
// @StringLength(20)
// @Required()
shortName:string;
// @StringLength(60)
longName?:string;
// @StringLength(20)
regionId?:string;
// @StringLength(20)
groupId?:string;
// @StringLength(12)
deviceID?:string;
lastUpdated?:string;
enabled?:boolean;
}
// @Route("/resources")
// @DataContract
interface Resources extends IReturn<Resources>
{
// @DataMember(Name="apiKey")
apiKey?:string;
}
// @Route("/resource/{Name*}")
// @DataContract
interface ResourceRequest
{
// @DataMember(Name="apiKey")
apiKey?:string;
// @DataMember(Name="name")
name?:string;
}
// @Route("/postman")
interface Postman
{
label?:string[];
exportSession?:boolean;
ssid?:string;
sspid?:string;
ssopt?:string;
}
interface QueryRockstarsConventions extends QueryBase_1<Rockstar>, IReturn<QueryResponse<Rockstar>>
{
ids?:number[];
ageOlderThan?:number;
ageGreaterThanOrEqualTo?:number;
ageGreaterThan?:number;
greaterThanAge?:number;
firstNameStartsWith?:string;
lastNameEndsWith?:string;
lastNameContains?:string;
rockstarAlbumNameContains?:string;
rockstarIdAfter?:number;
rockstarIdOnOrAfter?:number;
}
interface QueryCustomRockstars extends QueryBase_2<Rockstar, CustomRockstar>, IReturn<QueryResponse<CustomRockstar>>
{
age?:number;
}
// @Route("/customrockstars")
interface QueryRockstarAlbums extends QueryBase_2<Rockstar, CustomRockstar>, IReturn<QueryResponse<CustomRockstar>>
{
age?:number;
rockstarAlbumName?:string;
}
interface QueryRockstarAlbumsImplicit extends QueryBase_2<Rockstar, CustomRockstar>, IReturn<QueryResponse<CustomRockstar>>
{
}
interface QueryRockstarAlbumsLeftJoin extends QueryBase_2<Rockstar, CustomRockstar>, IReturn<QueryResponse<CustomRockstar>>
{
age?:number;
albumName?:string;
}
interface QueryOverridedRockstars extends QueryBase_1<Rockstar>, IReturn<QueryResponse<Rockstar>>
{
age?:number;
}
interface QueryOverridedCustomRockstars extends QueryBase_2<Rockstar, CustomRockstar>, IReturn<QueryResponse<CustomRockstar>>
{
age?:number;
}
interface QueryFieldRockstars extends QueryBase_1<Rockstar>, IReturn<QueryResponse<Rockstar>>
{
firstName?:string;
firstNames?:string[];
age?:number;
firstNameCaseInsensitive?:string;
firstNameStartsWith?:string;
lastNameEndsWith?:string;
firstNameBetween?:string[];
orLastName?:string;
}
interface QueryFieldRockstarsDynamic extends QueryBase_1<Rockstar>, IReturn<QueryResponse<Rockstar>>
{
age?:number;
}
interface QueryRockstarsFilter extends QueryBase_1<Rockstar>, IReturn<QueryResponse<Rockstar>>
{
age?:number;
}
interface QueryCustomRockstarsFilter extends QueryBase_2<Rockstar, CustomRockstar>, IReturn<QueryResponse<CustomRockstar>>
{
age?:number;
}
interface QueryRockstarsIFilter extends QueryBase_1<Rockstar>, IReturn<QueryResponse<Rockstar>>
{
age?:number;
}
// @Route("/OrRockstars")
interface QueryOrRockstars extends QueryBase_1<Rockstar>, IReturn<QueryResponse<Rockstar>>
{
age?:number;
firstName?:string;
}
interface QueryGetRockstars extends QueryBase_1<Rockstar>, IReturn<QueryResponse<Rockstar>>
{
ids?:number[];
ages?:number[];
firstNames?:string[];
idsBetween?:number[];
}
interface QueryGetRockstarsDynamic extends QueryBase_1<Rockstar>, IReturn<QueryResponse<Rockstar>>
{
}
// @Route("/movies/search")
interface SearchMovies extends QueryBase_1<Movie>, IReturn<QueryResponse<Movie>>
{
}
// @Route("/movies")
interface QueryMovies extends QueryBase_1<Movie>, IReturn<QueryResponse<Movie>>
{
ids?:number[];
imdbIds?:string[];
ratings?:string[];
}
interface StreamMovies extends QueryBase_1<Movie>, IReturn<QueryResponse<Movie>>
{
ratings?:string[];
}
interface QueryUnknownRockstars extends QueryBase_1<Rockstar>, IReturn<QueryResponse<Rockstar>>
{
unknownInt?:number;
unknownProperty?:string;
}
// @Route("/query/rockstar-references")
interface QueryRockstarsWithReferences extends QueryBase_1<RockstarReference>, IReturn<QueryResponse<RockstarReference>>
{
age?:number;
}
} | the_stack |
import { assert, expect } from 'chai';
import 'mocha';
import { Index } from '../lib/index';
import { Series } from '../lib/series';
import { DataFrame } from '../lib/dataframe';
//
// These tests based on these examples:
//
// http://chrisalbon.com/python/pandas_join_merge_dataframe.html
//
describe('pandas-examples', () => {
var df_a: any;
var df_b: any;
var df_n: any;
const concat = DataFrame.concat;
beforeEach(() => {
df_a = new DataFrame({
columnNames: [
'subject_id',
'first_name',
'last_name',
],
rows: [
[1, 'Alex', 'Anderson'],
[2, 'Amy', 'Ackerman'],
[3, 'Allen', 'Ali'],
[4, 'Alice', 'Aoni'],
[5, 'Ayoung', 'Aitches'],
],
});
df_b = new DataFrame({
columnNames: [
'subject_id',
'first_name',
'last_name',
],
rows: [
[4, 'Billy', 'Bonder'],
[5, 'Brian', 'Black'],
[6, 'Bran', 'Balwner'],
[7, 'Bryce', 'Brice'],
[8, 'Betty', 'Btisan'],
],
});
df_n = new DataFrame({
columnNames: [
"subject_id",
"test_id",
],
rows: [
[1, 51],
[2, 15],
[3, 15],
[4, 61],
[5, 16],
[7, 14],
[8, 15],
[9, 1],
[10, 61],
[11, 16],
],
});
});
it('Join the two dataframes along rows', () => {
var df_new = concat([df_a, df_b]);
expect(df_new.getIndex().take(10).toArray()).to.eql([
0, 1, 2, 3, 4,
0, 1, 2, 3, 4,
]);
expect(df_new.toRows()).to.eql([
[1, 'Alex', 'Anderson'],
[2, 'Amy', 'Ackerman'],
[3, 'Allen', 'Ali'],
[4, 'Alice', 'Aoni'],
[5, 'Ayoung', 'Aitches'],
[4, 'Billy', 'Bonder'],
[5, 'Brian', 'Black'],
[6, 'Bran', 'Balwner'],
[7, 'Bryce', 'Brice'],
[8, 'Betty', 'Btisan'],
]);
});
it('Join the two dataframes along columns', () => {
var df_new = df_a.zip(df_b, (a: any, b: any) => ({
"subject_id.1": a.subject_id,
"first_name.1": a.first_name,
"last_name.1": a.last_name,
"subject_id.2": b.subject_id,
"first_name.2": b.first_name,
"last_name.2": b.last_name,
}));
expect(df_new.getIndex().take(5).toArray()).to.eql([
0, 1, 2, 3, 4,
]);
expect(df_new.getColumnNames()).to.eql([
'subject_id.1',
'first_name.1',
'last_name.1',
'subject_id.2',
'first_name.2',
'last_name.2',
]);
expect(df_new.toRows()).to.eql([
[1, 'Alex', 'Anderson', 4, 'Billy', 'Bonder'],
[2, 'Amy', 'Ackerman', 5, 'Brian', 'Black'],
[3, 'Allen', 'Ali', 6, 'Bran', 'Balwner'],
[4, 'Alice', 'Aoni', 7, 'Bryce', 'Brice'],
[5, 'Ayoung', 'Aitches', 8, 'Betty', 'Btisan'],
]);
});
it('Merge two dataframes along the subject_id value', () => {
var df_new = concat([df_a, df_b]);
var df_merged = df_new
.join(
df_n,
(rowA: any) => {
return rowA.subject_id;
},
(rowB: any) => {
return rowB.subject_id;
},
(rowA: any, rowB: any) => {
return {
subject_id: rowA.subject_id,
first_name: rowA.first_name,
last_name: rowA.last_name,
test_id: rowB.test_id,
};
}
)
;
expect(df_merged.getIndex().take(9).toArray()).to.eql([
0, 1, 2, 3, 4, 5, 6, 7, 8,
]);
expect(df_merged.getColumnNames()).to.eql([
'subject_id',
'first_name',
'last_name',
"test_id",
]);
expect(df_merged.toRows()).to.eql([
[1, 'Alex', 'Anderson', 51],
[2, 'Amy', 'Ackerman', 15],
[3, 'Allen', 'Ali', 15],
[4, 'Alice', 'Aoni', 61],
[5, 'Ayoung', 'Aitches', 16],
[4, 'Billy', 'Bonder', 61], // Note this is slighly different to the ordering from Pandas.
[5, 'Brian', 'Black', 16],
[7, 'Bryce', 'Brice', 14],
[8, 'Betty', 'Btisan', 15],
]);
});
it('Merge two dataframes along the subject_id value', () => {
var df_new = concat([df_a, df_b]);
var df_merged = df_new.join(
df_n,
(left: any) => left.subject_id,
(right: any) => right.subject_id,
(left: any, right: any) => {
return {
subject_id: left.subject_id,
first_name: left.first_name,
last_name: left.last_name,
test_id: right.test_id,
};
}
)
;
expect(df_merged.getIndex().take(9).toArray()).to.eql([
0, 1, 2, 3, 4, 5, 6, 7, 8,
]);
expect(df_merged.getColumnNames()).to.eql([
'subject_id',
'first_name',
'last_name',
"test_id",
]);
expect(df_merged.toRows()).to.eql([
[1, 'Alex', 'Anderson', 51],
[2, 'Amy', 'Ackerman', 15],
[3, 'Allen', 'Ali', 15],
[4, 'Alice', 'Aoni', 61],
[5, 'Ayoung', 'Aitches', 16],
[4, 'Billy', 'Bonder', 61], // Note this is slighly different to the ordering from Pandas.
[5, 'Brian', 'Black', 16],
[7, 'Bryce', 'Brice', 14],
[8, 'Betty', 'Btisan', 15],
]);
});
// Exactly the same as the previous example.
it('Merge two dataframes with both the left and right dataframes using the subject_id key', () => {
var df_new = concat([df_a, df_b]);
var df_merged = df_new.join(
df_n,
(left: any) => left.subject_id,
(right: any) => right.subject_id,
(left, right) => {
return {
subject_id: left.subject_id,
first_name: left.first_name,
last_name: left.last_name,
test_id: right.test_id,
};
}
)
;
expect(df_merged.getIndex().take(9).toArray()).to.eql([
0, 1, 2, 3, 4, 5, 6, 7, 8,
]);
expect(df_merged.getColumnNames()).to.eql([
'subject_id',
'first_name',
'last_name',
"test_id",
]);
expect(df_merged.toRows()).to.eql([
[1, 'Alex', 'Anderson', 51],
[2, 'Amy', 'Ackerman', 15],
[3, 'Allen', 'Ali', 15],
[4, 'Alice', 'Aoni', 61],
[5, 'Ayoung', 'Aitches', 16],
[4, 'Billy', 'Bonder', 61], // Note this is slighly different to the ordering from Pandas.
[5, 'Brian', 'Black', 16],
[7, 'Bryce', 'Brice', 14],
[8, 'Betty', 'Btisan', 15],
]);
});
it('Merge with outer join', () => {
var df_merged = df_a.joinOuter(
df_b,
(left: any) => left.subject_id,
(right: any) => right.subject_id,
(left: any, right: any) => {
var output: any = {};
if (left) {
output.subject_id = left.subject_id;
output.first_name_x = left.first_name;
output.last_name_x = left.last_name;
}
if (right) {
output.subject_id = right.subject_id;
output.first_name_y = right.first_name;
output.last_name_y = right.last_name;
}
return output;
}
)
;
expect(df_merged.getIndex().take(8).toArray()).to.eql([
0, 1, 2, 3, 4, 5, 6, 7
]);
expect(df_merged.getColumnNames()).to.eql([
'subject_id',
'first_name_x',
'last_name_x',
'first_name_y',
'last_name_y',
]);
expect(df_merged.toRows()).to.eql([
[1, 'Alex', 'Anderson', undefined, undefined],
[2, 'Amy', 'Ackerman', undefined, undefined],
[3, 'Allen', 'Ali', undefined, undefined],
[4, 'Alice', 'Aoni', 'Billy', 'Bonder'],
[5, 'Ayoung', 'Aitches', 'Brian', 'Black'],
[6, undefined, undefined, 'Bran', 'Balwner'],
[7, undefined, undefined, 'Bryce', 'Brice'],
[8, undefined, undefined, 'Betty', 'Btisan'],
]);
});
it('Merge with inner join', () => {
var df_merged = df_a.join(
df_b,
(left: any) => left.subject_id,
(right: any) => right.subject_id,
(left: any, right: any) => {
return {
subject_id: left.subject_id,
first_name_x: left.first_name,
last_name_x: left.last_name,
first_name_y: right.first_name,
last_name_y: right.last_name,
};
}
)
;
expect(df_merged.getIndex().take(2).toArray()).to.eql([
0, 1,
]);
expect(df_merged.getColumnNames()).to.eql([
'subject_id',
'first_name_x',
'last_name_x',
'first_name_y',
'last_name_y',
]);
expect(df_merged.toRows()).to.eql([
[4, 'Alice', 'Aoni', 'Billy', 'Bonder'],
[5, 'Ayoung', 'Aitches', 'Brian', 'Black'],
]);
});
it('Merge with right join', () => {
var df_merged = df_a.joinOuterRight(
df_b,
(left: any) => left.subject_id,
(right: any) => right.subject_id,
(left: any, right: any) => {
var output: any = {};
if (left) {
output.subject_id = left.subject_id;
output.first_name_x = left.first_name;
output.last_name_x = left.last_name;
}
if (right) {
output.subject_id = right.subject_id;
output.first_name_y = right.first_name;
output.last_name_y = right.last_name;
}
return output;
}
)
;
expect(df_merged.getIndex().take(5).toArray()).to.eql([
0, 1, 2, 3, 4,
]);
expect(df_merged.getColumnNames()).to.eql([
'subject_id',
'first_name_x',
'last_name_x',
'first_name_y',
'last_name_y',
]);
expect(df_merged.toRows()).to.eql([
[4, 'Alice', 'Aoni', 'Billy', 'Bonder'],
[5, 'Ayoung', 'Aitches', 'Brian', 'Black'],
[6, undefined, undefined, 'Bran', 'Balwner'],
[7, undefined, undefined, 'Bryce', 'Brice'],
[8, undefined, undefined, 'Betty', 'Btisan'],
]);
});
it('Merge with left join', () => {
var df_merged = df_a.joinOuterLeft(
df_b,
(left: any) => left.subject_id,
(right: any) => right.subject_id,
(left: any, right: any) => {
var output: any = {};
if (left) {
output.subject_id = left.subject_id;
output.first_name_x = left.first_name;
output.last_name_x = left.last_name;
}
if (right) {
output.subject_id = right.subject_id;
output.first_name_y = right.first_name;
output.last_name_y = right.last_name;
}
return output;
}
)
;
expect(df_merged.getIndex().take(5).toArray()).to.eql([
0, 1, 2, 3, 4,
]);
expect(df_merged.getColumnNames()).to.eql([
'subject_id',
'first_name_x',
'last_name_x',
'first_name_y',
'last_name_y',
]);
expect(df_merged.toRows()).to.eql([
[1, 'Alex', 'Anderson', undefined, undefined],
[2, 'Amy', 'Ackerman', undefined, undefined],
[3, 'Allen', 'Ali', undefined, undefined],
[4, 'Alice', 'Aoni', 'Billy', 'Bonder'],
[5, 'Ayoung', 'Aitches', 'Brian', 'Black'],
]);
});
it('Merge while adding a suffix to duplicate column names', () => {
var df_merged = df_a.joinOuterLeft(
df_b,
(left: any) => left.subject_id,
(right: any) => right.subject_id,
(left: any, right: any) => {
var output: any = {};
if (left) {
output.subject_id = left.subject_id;
output.first_name_left = left.first_name;
output.last_name_left = left.last_name;
}
if (right) {
output.subject_id = right.subject_id;
output.first_name_right = right.first_name;
output.last_name_right = right.last_name;
}
return output;
}
)
;
expect(df_merged.getIndex().take(5).toArray()).to.eql([
0, 1, 2, 3, 4,
]);
expect(df_merged.getColumnNames()).to.eql([
'subject_id',
'first_name_left',
'last_name_left',
'first_name_right',
'last_name_right',
]);
expect(df_merged.toRows()).to.eql([
[1, 'Alex', 'Anderson', undefined, undefined],
[2, 'Amy', 'Ackerman', undefined, undefined],
[3, 'Allen', 'Ali', undefined, undefined],
[4, 'Alice', 'Aoni', 'Billy', 'Bonder'],
[5, 'Ayoung', 'Aitches', 'Brian', 'Black'],
]);
});
}); | the_stack |
import { Component, Ref, Watch } from 'vue-property-decorator';
import {
operationRecords,
getOperators,
getOperationDiff,
getFieldContraintConfigs,
getModelVersionDiff,
getReleaseList,
} from '../Api/index';
import { DataModelManageBase } from '../Controller/DataModelManageBase';
import moment from 'moment';
import { BizDiffContents } from './Common/index';
import { VNode } from 'vue/types/umd';
import { generateId } from '@/common/js/util';
import { bkOverflowTips } from 'bk-magic-vue';
interface IConditions {
key: string;
value: string[];
}
@Component({
components: { BizDiffContents },
directives: { bkOverflowTips },
})
export default class ModelOperation extends DataModelManageBase {
@Ref('searchSelect') public readonly searchSelectNode!: VNode;
@Ref() public readonly operationsTable!: VNode;
/**
* 获取操作记录接口参数
*/
get apiParams() {
const params = {
modelId: this.modelId,
page: this.operationData.pagination.current,
pageSize: this.operationData.pagination.limit,
};
if (this.startTime && this.endTime) {
params.startTime = this.startTime;
params.endTime = this.endTime;
}
const conditions = this.getConditions();
if (conditions.length) {
params.conditions = conditions;
}
if (this.order) {
params.orderByCreatedAt = this.order;
}
return params;
}
/**
* 获取旧版本信息
*/
get versionInfo() {
const { createdAt, createdBy } = this.origContents;
return createdAt && createdBy ? `${createdBy} (${createdAt})` : '';
}
/**
* 获取新版本信息
*/
get newVersionInfo() {
const { createdAt, createdBy } = this.newContents;
return createdAt && createdBy ? `${createdBy} (${createdAt})` : '';
}
/**
* 获取旧版本日志
*/
get versionLog() {
const item = this.releaseList.find(item => item.versionId === this.diffSlider.origVersionId);
return item ? item.versionLog : '--';
}
/**
* 获取新版本日志
*/
get newVersionLog() {
const item = this.releaseList.find(item => item.versionId === this.diffSlider.newVersionId);
return item ? item.versionLog : '--';
}
get renderCoditionsData() {
const renderCoditionsData = [...this.conditionsData];
for (const item of this.searchSelectData) {
const id = item.id;
const conditionIndex = renderCoditionsData.findIndex(condition => condition.id === id);
if (conditionIndex >= 0) {
renderCoditionsData.splice(conditionIndex, 1);
}
}
return renderCoditionsData;
}
/**
* 获取操作对象类别已选过滤 values
*/
get operationFiltered() {
const item = this.searchSelectData.find(item => item.id === 'object_operation');
return item ? item.values.map(value => value.id) : [];
}
/**
* 获取类型已选过滤 values
*/
get typeFiltered() {
const item = this.searchSelectData.find(item => item.id === 'object_type');
return item ? item.values.map(value => value.id) : [];
}
public generateId = generateId;
public initDateTimeRange: Array<string> = [];
public diffData = {};
public newContents: object = {};
public origContents: object = {};
public fieldContraintConfigList: object[] = [];
public diffSlider: object = {
isShow: false,
isLoading: false,
onlyShowDiff: true,
showResult: true,
origVersionId: null,
newVersionId: null,
contentLoading: false,
};
public releaseList: any[] = [];
cancelKey: string = generateId('operation_diff_api');
appHeight: number = window.innerHeight;
isLoading = false;
startTime = '';
endTime = '';
order = '';
searchSelectData: any[] = [];
// 操作 map
operationMap = {
create: this.$t('新增'),
update: this.$t('更新'),
delete: this.$t('删除'),
release: this.$t('发布'),
model: this.$t('数据模型'),
master_table: this.$t('主表'),
calculation_atom: this.$t('统计口径'),
indicator: this.$t('指标'),
};
// search-select conditions data
public conditionsData = [
{
name: '操作类型',
id: 'object_operation',
multiable: true,
children: [
{
name: '更新',
id: 'update',
},
{
name: '新增',
id: 'create',
},
{
name: '删除',
id: 'delete',
},
{
name: '发布',
id: 'release',
},
],
},
{
name: '操作对象类型',
id: 'object_type',
multiable: true,
children: [
{
name: '数据模型',
id: 'model',
},
{
name: '主表',
id: 'master_table',
},
{
name: '统计口径',
id: 'calculation_atom',
},
{
name: '指标',
id: 'indicator',
},
],
},
{
name: '操作对象',
id: 'object',
},
{
name: '操作者',
id: 'created_by',
remote: true,
},
];
public objectOperationFilters: any[] = [
{ text: '新增', value: 'create' },
{ text: '删除', value: 'delete' },
{ text: '更新', value: 'update' },
{ text: '发布', value: 'release' },
];
public objectTypeFilters: any[] = [
{ text: '数据模型', value: 'model' },
{ text: '主表', value: 'master_table' },
{ text: '统计口径', value: 'calculation_atom' },
{ text: '指标', value: 'indicator' },
];
public operationData = {
data: [],
pagination: {
current: 1,
count: 0,
limit: 10,
},
};
@Watch('initDateTimeRange')
onChangeValue(newVal: any[], oldVal: any[]) {
if (newVal === oldVal) return;
if (this.initDateTimeRange[0] && this.initDateTimeRange[1]) {
this.startTime = moment(newVal[0]).format('YYYY-MM-DD HH:mm:ss');
this.endTime = moment(newVal[1]).format('YYYY-MM-DD HH:mm:ss');
} else {
this.startTime = '';
this.endTime = '';
}
this.handlePageChange(1);
}
@Watch('searchSelectData', { deep: true })
handleChangeSearchSelectData() {
this.handlePageChange(1);
}
/**
* 处理过滤条件
*/
public getConditions() {
if (!this.searchSelectData.length) return [];
const conditions = {
object_operation: [],
object_type: [],
created_by: [],
object: [],
query: [],
};
for (const item of this.searchSelectData) {
const key = item.id;
if (conditions[key]) {
const values = item.values.map(value => value.id);
conditions[key].push(...values);
} else {
conditions.query.push(item.name);
}
}
const res: IConditions[] = [];
// 去重,获取结果
Object.keys(conditions).forEach(key => {
const value = Array.from(new Set(conditions[key]));
value.length && res.push({ key, value });
});
return res;
}
/**
* 远程加载操作者过滤条件
*/
public handleRemoteMethod() {
return getOperators(this.modelId).then(res => {
if (res.result) {
const list = res.data.results || [];
return list.map((operator: string) => ({ id: operator, name: operator }));
}
return [];
});
}
/**
* 处理 table filters 事件
* @param filters
*/
public handleFilterChange(filters) {
const nameMap = {
object_operation: '操作类型',
object_type: '操作对象类别',
};
const columnKeys = Object.keys(filters);
for (const columnKey of columnKeys) {
const keys = filters[columnKey];
const values = keys.reduce((res, key) => res.concat([{ id: key, name: this.operationMap[key] }]), []);
const index = this.searchSelectData.findIndex(item => item.id === columnKey);
if (index >= 0) {
if (!keys.length) {
this.searchSelectData.splice(index, 1);
} else {
const item = this.searchSelectData[index];
item.values = values;
this.searchSelectData.splice(index, 1, item);
}
} else {
this.searchSelectData.push({
id: columnKey,
name: nameMap[columnKey],
multiable: true,
values,
});
}
}
}
/**
* 处理翻页
* @param page
*/
public handlePageChange(page: number) {
this.operationData.pagination.current = page;
this.operationRecords();
}
/**
* 处理每页显示数量
* @param limit
*/
public handleLimitChange(limit: number) {
this.operationData.pagination.limit = limit;
this.handlePageChange(1);
}
/**
* 处理 table 排序
*/
public handleSortChange({ order }) {
const map = {
ascending: 'asc',
descending: 'desc',
};
this.order = map[order];
this.handlePageChange(1);
}
/**
* 处理详情源版本选择
* @param id
*/
public handleOrigVersionChange(id: string) {
this.diffSlider.origVersionId = id;
this.diffSlider.contentLoading = true;
this.getModelVersionDiff(id, this.diffSlider.newVersionId);
}
/**
* 处理详情新版本选择
* @param id
*/
public handleNewVersionChange(id: string) {
this.diffSlider.newVersionId = id;
this.diffSlider.contentLoading = true;
this.getModelVersionDiff(this.diffSlider.origVersionId, id);
}
/**
* 展示操作记录 diff
* @param row
*/
public handleShowDiffSlider(row: object) {
/** 设置Cancel请求 */
this.handleCancelRequest(this.cancelKey);
this.diffSlider.showResult = row.objectOperation === 'release';
this.diffSlider.onlyShowDiff = true;
this.diffSlider.origVersionId = row.origVersionId;
this.diffSlider.newVersionId = row.newVersionId;
this.diffSlider.isShow = true;
this.diffSlider.isLoading = true;
row.objectOperation === 'release'
? this.getModelVersionDiff(row.origVersionId, row.newVersionId)
: this.getOperationDiff(row.id);
}
/**
* 获取操作记录列表
*/
public operationRecords() {
this.isLoading = true;
const { modelId, page, pageSize, conditions, startTime, endTime, orderByCreatedAt } = this.apiParams;
operationRecords(modelId, page, pageSize, conditions, startTime, endTime, orderByCreatedAt)
.then(res => {
res.setDataFn(data => {
const { results, count } = data;
this.operationData.data = results;
this.operationData.pagination.count = count;
});
})
['finally'](() => {
this.isLoading = false;
});
}
/**
* 获取值约束条件
*/
public getFieldContraintConfigs() {
getFieldContraintConfigs().then(res => {
res.setData(this, 'fieldContraintConfigList');
});
}
/**
* 模型发布 diff
* @param origVersionId
* @param newVersionId
*/
public getModelVersionDiff(origVersionId: string | null, newVersionId: string) {
getModelVersionDiff(this.modelId, origVersionId, newVersionId, this.getCancelToken(this.cancelKey))
.then(res => {
res.setDataFn(data => {
const { diff = {}, newContents = {}, origContents = {} } = data || {};
this.diffData = diff;
this.newContents = newContents;
this.origContents = origContents;
});
})
['finally'](() => {
this.diffSlider.isLoading = false;
this.diffSlider.contentLoading = false;
});
}
/**
* 除发布外的操作 diff
* @param operationId
*/
public getOperationDiff(operationId: number) {
getOperationDiff(this.modelId, operationId, this.getCancelToken(this.cancelKey))
.then(res => {
res.setDataFn(data => {
const { diff = {}, newContents = {}, origContents = {} } = data || {};
this.diffData = diff;
this.newContents = newContents;
this.origContents = origContents;
});
})
['finally'](() => {
this.diffSlider.isLoading = false;
});
}
/**
* 获取版本列表
*/
public getReleaseList() {
getReleaseList(this.modelId).then(res => {
res.setDataFn(data => {
this.releaseList = data.results || [];
});
});
}
/**
* 过滤条件改变
* @param list
*/
public handleSearchSelectChange(list: any[]) {
// search-select 没有 conditions 后取消显示 menu popper
this.$nextTick(() => {
!this.renderCoditionsData.length && this.searchSelectNode && this.searchSelectNode.hidePopper();
});
}
/**
* 重置高度
*/
public handleResetHeight() {
this.appHeight = window.innerHeight;
}
public async created() {
window.addEventListener('resize', this.handleResetHeight);
this.operationRecords();
this.getFieldContraintConfigs();
await this.getReleaseList();
}
public beforeDestroy() {
window.removeEventListener('resize', this.handleResetHeight);
}
} | the_stack |
import { TestBed, fakeAsync, ComponentFixture, tick, flush } from '@angular/core/testing';
import { Component, Type } from '@angular/core';
import { MdcFloatingLabelDirective } from '../floating-label/mdc.floating-label.directive';
import { SELECT_DIRECTIVES, MdcSelectDirective } from './mdc.select.directive';
import { MENU_DIRECTIVES } from '../menu/mdc.menu.directive';
import { LIST_DIRECTIVES } from '../list/mdc.list.directive';
import { MENU_SURFACE_DIRECTIVES } from '../menu-surface/mdc.menu-surface.directive';
import { NOTCHED_OUTLINE_DIRECTIVES } from '../notched-outline/mdc.notched-outline.directive';
import { hasRipple, simulateKey } from '../../testutils/page.test';
import { By } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
// TODO: test disabled options
// TODO: test structure when surface open
// TODO: test structure when required
// TODO: test mdcSelect with FormsModule
describe('MdcSelectDirective', () => {
it('filled: test DOM, aria properties, and ripple', fakeAsync(() => {
const { fixture, testComponent } = setup(TestStaticComponent);
const root = fixture.nativeElement.querySelector('.mdc-select');
const { anchor } = validateDom(root);
expect(hasRipple(anchor)).toBe(true, 'the ripple element should be attached to the anchor');
testComponent.disabled = true;
fixture.detectChanges(); tick(5);
validateDom(root, {disabled: true});
testComponent.labeled = false; testComponent.disabled = false;
fixture.detectChanges(); tick(5);
validateDom(root, {labeled: false});
}));
it('outlined: test DOM, aria properties, and ripple', fakeAsync(() => {
const { fixture, testComponent } = setup(TestStaticOutlinedComponent);
const root = fixture.nativeElement.querySelector('.mdc-select');
const { anchor } = validateDom(root, {outlined: true});
expect(hasRipple(anchor)).toBe(false, 'no ripple allowed for outlined variant');
testComponent.disabled = true;
fixture.detectChanges(); tick(5);
validateDom(root, {outlined: true, disabled: true});
testComponent.labeled = false; testComponent.disabled = false;
fixture.detectChanges(); tick(5);
validateDom(root, {outlined: true, labeled: false});
}));
it('filled: floating label must float when input has focus', fakeAsync(() => {
const { fixture } = setup(TestStaticComponent);
validateFloatOnFocus(fixture);
}));
it('outlined: floating label must float when input has focus', fakeAsync(() => {
const { fixture } = setup(TestStaticOutlinedComponent);
validateFloatOnFocus(fixture);
}));
it('value can be changed programmatically', fakeAsync(() => {
const { fixture, testComponent } = setup(TestStaticComponent);
expect(testComponent.value).toBe(null);
setAndCheck(fixture, 'vegetables', TestStaticComponent);
setAndCheck(fixture, '', TestStaticComponent);
setAndCheck(fixture, 'fruit', TestStaticComponent);
setAndCheck(fixture, null, TestStaticComponent);
setAndCheck(fixture, 'invalid', TestStaticComponent);
}));
it('value can be changed by user', fakeAsync(() => {
const { fixture, testComponent } = setup();
expect(testComponent.value).toBe(null);
selectAndCheck(fixture, 0, 2, 'vegetables');
selectAndCheck(fixture, 2, 3, 'fruit');
selectAndCheck(fixture, 3, 0, '');
}));
it('label remains floating when switching between outlined and without outline', fakeAsync(() => {
const { fixture, testComponent } = setup(TestSwitchOutlinedComponent);
const root = fixture.nativeElement.querySelector('.mdc-select');
checkFloating(fixture, false);
setAndCheck(fixture, 'vegetables', TestSwitchOutlinedComponent);
checkFloating(fixture, true);
validateDom(root, {outlined: true, selected: 2});
testComponent.outlined = false;
fixture.detectChanges(); tick(20);
validateDom(root, {outlined: false, selected: 2});
checkFloating(fixture, true);
testComponent.outlined = true;
fixture.detectChanges(); tick(20);
validateDom(root, {outlined: true, selected: 2});
checkFloating(fixture, true);
}));
function setAndCheck(fixture: ComponentFixture<any>, value: any, type = TestComponent) {
const testComponent = fixture.debugElement.injector.get(type);
const mdcSelect = fixture.debugElement.query(By.directive(MdcSelectDirective))?.injector.get(MdcSelectDirective);
testComponent.value = value;
fixture.detectChanges(); flush(); fixture.detectChanges(); flush(); fixture.detectChanges(); flush();
if (value === 'invalid')
value = '';
expect(mdcSelect.value).toBe(value || '');
expect(testComponent.value).toBe(value || '');
checkFloating(fixture, value != null && value.length > 0);
}
function selectAndCheck(fixture: ComponentFixture<any>, focusIndex: number, selectIndex: number, value: string, type: Type<any> = TestComponent) {
const testComponent = fixture.debugElement.injector.get(type);
const text = fixture.nativeElement.querySelector('.mdc-select__selected-text');
const items = [...fixture.nativeElement.querySelectorAll('.mdc-list-item')];
const mdcSelect = fixture.debugElement.query(By.directive(MdcSelectDirective))?.injector.get(MdcSelectDirective);
text.dispatchEvent(new Event('focus'));
simulateKey(text, 'ArrowDown');
animationCycle(fixture);
expect(document.activeElement).toBe(items[focusIndex]);
let selected = focusIndex;
while (selected < selectIndex) {
simulateKey(items[selected], 'ArrowDown');
fixture.detectChanges(); flush();
expect(document.activeElement).toBe(items[++selected]);
}
while (selected > selectIndex) {
simulateKey(items[selected], 'ArrowUp');
fixture.detectChanges(); flush();
expect(document.activeElement).toBe(items[--selected]);
}
simulateKey(items[selected], 'Enter');
animationCycle(fixture);
expect(mdcSelect.value).toBe(value);
expect(testComponent.value).toBe(value);
checkFloating(fixture, value != null && value.length > 0);
}
@Component({
template: `
<div mdcSelect [(value)]="value">
<div mdcSelectAnchor>
<div mdcSelectText>{{value}}</div>
<span mdcFloatingLabel>Pick a Food Group</span>
</div>
<div mdcSelectMenu>
<ul mdcList>
<li mdcListItem value="" aria-selected="true"></li>
<li mdcListItem value="grains">Bread, Cereal, Rice, and Pasta</li>
<li mdcListItem value="vegetables">Vegetables</li>
<li mdcListItem value="fruit">Fruit</li>
</ul>
</div>
</div>
<div>selected: {{value}}</div>
`
})
class TestComponent {
value: any = null;
}
@Component({
template: `
<div mdcSelect [(value)]="value" [disabled]="disabled">
<div mdcSelectAnchor>
<div mdcSelectText>{{value}}</div>
<span *ngIf="labeled" mdcFloatingLabel>Pick a Food Group</span>
</div>
<div mdcSelectMenu>
<ul mdcList>
<li mdcListItem value="" aria-selected="true"></li>
<li mdcListItem value="grains">Bread, Cereal, Rice, and Pasta</li>
<li mdcListItem value="vegetables">Vegetables</li>
<li mdcListItem value="fruit">Fruit</li>
</ul>
</div>
</div>
<div>selected: {{value}}</div>
`
})
class TestStaticComponent {
value: any = null;
labeled = true;
disabled = false;
}
@Component({
template: `
<div mdcSelect [(value)]="value" [disabled]="disabled">
<div mdcSelectAnchor>
<div mdcSelectText>{{value}}</div>
<span mdcNotchedOutline>
<span *ngIf="labeled" mdcNotchedOutlineNotch>
<span mdcFloatingLabel>Floating Label</span>
</span>
</span>
</div>
<div mdcSelectMenu>
<ul mdcList>
<li mdcListItem value="" aria-selected="true"></li>
<li mdcListItem value="grains">Bread, Cereal, Rice, and Pasta</li>
<li mdcListItem value="vegetables">Vegetables</li>
<li mdcListItem value="fruit">Fruit</li>
</ul>
</div>
</div>
<div>selected: {{value}}</div>
`
})
class TestStaticOutlinedComponent {
value: any = null;
labeled = true;
disabled = false;
}
@Component({
template: `
<div mdcSelect [(value)]="value" [disabled]="disabled">
<div mdcSelectAnchor>
<div mdcSelectText>{{value}}</div>
<span *ngIf="outlined; else notOutlined" mdcNotchedOutline>
<span mdcNotchedOutlineNotch>
<span mdcFloatingLabel>Pick a Food Group</span>
</span>
</span>
<ng-template #notOutlined>
<span mdcFloatingLabel>Pick a Food Group</span>
</ng-template>
</div>
<div mdcSelectMenu>
<ul mdcList>
<li mdcListItem value="" aria-selected="true"></li>
<li mdcListItem value="grains">Bread, Cereal, Rice, and Pasta</li>
<li mdcListItem value="vegetables">Vegetables</li>
<li mdcListItem value="fruit">Fruit</li>
</ul>
</div>
</div>
<div>selected: {{value}}</div>
`
})
class TestSwitchOutlinedComponent {
value: any = null;
outlined = true;
}
function setup(compType: Type<any> = TestComponent) {
const fixture = TestBed.configureTestingModule({
declarations: [
...SELECT_DIRECTIVES,
...MENU_DIRECTIVES,
...MENU_SURFACE_DIRECTIVES,
...LIST_DIRECTIVES,
MdcFloatingLabelDirective,
...NOTCHED_OUTLINE_DIRECTIVES,
compType]
}).createComponent(compType);
fixture.detectChanges(); flush();
const testComponent = fixture.debugElement.injector.get(compType);
const select = fixture.nativeElement.querySelector('.mdc-select');
return { fixture, testComponent, select };
}
});
function validateDom(select, options: Partial<{
outlined: boolean,
expanded: boolean,
disabled: boolean,
required: boolean,
labeled: boolean,
selected: number,
values: boolean
}> = {}) {
options = {...{
outlined: false,
expanded: false,
disabled: false,
required: false,
labeled: true,
selected: -1,
values: true
}, ...options};
expect(select.classList).toContain('mdc-select');
if (!options.labeled)
expect(select.classList).toContain('mdc-select--no-label');
else
expect(select.classList).not.toContain('mdc-select--no-label');
if (options.disabled)
expect(select.classList).toContain('mdc-select--disabled');
else
expect(select.classList).not.toContain('mdc-select--disabled');
if (options.required)
expect(select.classList).toContain('mdc-select--required');
else
expect(select.classList).not.toContain('mdc-select--required');
expect(select.children.length).toBe(2);
const anchor = select.children[0];
if (options.outlined)
expect(anchor.children.length).toBe(3);
else
expect(anchor.children.length).toBe(options.labeled ? 4 : 3);
const dropDownIcon = anchor.children[0];
const selectedText = anchor.children[1];
expect(selectedText.id).toMatch(/mdc-u-id-.*/);
const floatingLabel = anchor.querySelector('.mdc-floating-label');
expect(!!floatingLabel).toBe(options.labeled);
if (floatingLabel) {
expect(floatingLabel.id).toMatch(/mdc-u-id-.*/);
expect(floatingLabel.classList).toContain('mdc-floating-label');
}
if (options.outlined) {
const notchedOutline = anchor.children[2];
expect(notchedOutline.classList).toContain('mdc-notched-outline');
expect(notchedOutline.children.length).toBe(options.labeled ? 3 : 2);
expect(notchedOutline.children[0].classList).toContain('mdc-notched-outline__leading');
expect(notchedOutline.children[notchedOutline.children.length - 1].classList).toContain('mdc-notched-outline__trailing');
if (floatingLabel) {
expect(notchedOutline.children[1].classList).toContain('mdc-notched-outline__notch');
const notch = notchedOutline.children[1];
expect(notch.children.length).toBe(1);
expect(notch.children[0]).toBe(floatingLabel);
}
} else {
const lineRipple = anchor.children[anchor.children.length - 1];
expect(lineRipple.classList).toContain('mdc-line-ripple');
if (floatingLabel)
expect(anchor.children[2]).toBe(floatingLabel);
}
expect(dropDownIcon.classList).toContain('mdc-select__dropdown-icon');
expect(selectedText.classList).toContain('mdc-select__selected-text');
expect(selectedText.getAttribute('tabindex')).toBe(options.disabled ? '-1': '0');
expect(selectedText.getAttribute('aria-disabled')).toBe(`${options.disabled}`);
expect(selectedText.getAttribute('aria-required')).toBe(`${options.required}`);
expect(selectedText.getAttribute('role')).toBe('button');
expect(selectedText.getAttribute('aria-haspopup')).toBe('listbox');
expect(selectedText.getAttribute('aria-labelledBy')).toBe(`${floatingLabel ? floatingLabel.id + ' ' : ''}${selectedText.id}`);
expect(selectedText.getAttribute('aria-expanded')).toBe(options.expanded ? 'true' : 'false');
expect(anchor.classList).toContain('mdc-select__anchor');
const menu = select.children[1];
expect(menu.classList).toContain('mdc-select__menu');
expect(menu.classList).toContain('mdc-menu');
expect(menu.classList).toContain('mdc-menu-surface');
expect(menu.children.length).toBe(1);
const list = menu.children[0];
expect(list.classList).toContain('mdc-list');
expect(list.getAttribute('role')).toBe('listbox');
expect(list.getAttribute('aria-labelledBy')).toBe(floatingLabel ? floatingLabel.id : null);
expect(list.getAttribute('tabindex')).toBeNull();
const items = [...list.querySelectorAll('li')];
let index = 0;
items.forEach(item => {
expect(item.classList).toContain('mdc-list-item');
expect(item.getAttribute('role')).toBe('option');
expect(item.getAttribute('tabindex')).toMatch(/0|-1/);
const selected = options.selected === index
expect(item.getAttribute('aria-selected')).toBe(selected ? 'true' : 'false');
if (selected)
expect(item.classList).toContain('mdc-list-item--selected');
else
expect(item.classList).not.toContain('mdc-list-item--selected');
expect(item.hasAttribute('value')).toBe(options.values);
++index;
});
return { anchor, menu, list, items };
}
function validateFloatOnFocus(fixture) {
const floatingLabelElm = fixture.nativeElement.querySelector('.mdc-floating-label');
const text = fixture.nativeElement.querySelector('.mdc-select__selected-text');
expect(floatingLabelElm.classList).not.toContain('mdc-floating-label--float-above');
text.dispatchEvent(new Event('focus')); tick();
expect(floatingLabelElm.classList).toContain('mdc-floating-label--float-above');
text.dispatchEvent(new Event('blur')); tick();
expect(floatingLabelElm.classList).not.toContain('mdc-floating-label--float-above');
}
function checkFloating(fixture: ComponentFixture<any>, expected: boolean) {
// when not empty, the label must be floating:
const floatingLabelElm = fixture.nativeElement.querySelector('.mdc-floating-label');
if (floatingLabelElm) {
if (expected)
expect(floatingLabelElm.classList).toContain('mdc-floating-label--float-above');
else
expect(floatingLabelElm.classList).not.toContain('mdc-floating-label--float-above');
}
}
function animationCycle(fixture) {
fixture.detectChanges(); tick(300); flush();
} | the_stack |
// IMPORTANT
// This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually.
// In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator
// Generated from: https://oslogin.googleapis.com/$discovery/rest?version=v1alpha
/// <reference types="gapi.client" />
declare namespace gapi.client {
/** Load Google Cloud OS Login API v1alpha */
function load(name: "oslogin", version: "v1alpha"): PromiseLike<void>;
function load(name: "oslogin", version: "v1alpha", callback: () => any): void;
const users: oslogin.UsersResource;
namespace oslogin {
interface ImportSshPublicKeyResponse {
/** The login profile information for the user. */
loginProfile?: LoginProfile;
}
interface LoginProfile {
/** A unique user ID for identifying the user. */
name?: string;
/** The list of POSIX accounts associated with the Directory API user. */
posixAccounts?: PosixAccount[];
/** A map from SSH public key fingerprint to the associated key object. */
sshPublicKeys?: Record<string, SshPublicKey>;
/** Indicates if the user is suspended. */
suspended?: boolean;
}
interface PosixAccount {
/** The GECOS (user information) entry for this account. */
gecos?: string;
/** The default group ID. */
gid?: string;
/** The path to the home directory for this account. */
homeDirectory?: string;
/** Only one POSIX account can be marked as primary. */
primary?: boolean;
/** The path to the logic shell for this account. */
shell?: string;
/**
* System identifier for which account the username or uid applies to.
* By default, the empty value is used.
*/
systemId?: string;
/** The user ID. */
uid?: string;
/** The username of the POSIX account. */
username?: string;
}
interface SshPublicKey {
/** An expiration time in microseconds since epoch. */
expirationTimeUsec?: string;
/**
* The SHA-256 fingerprint of the SSH public key.
* Output only.
*/
fingerprint?: string;
/**
* Public key text in SSH format, defined by
* <a href="https://www.ietf.org/rfc/rfc4253.txt" target="_blank">RFC4253</a>
* section 6.6.
*/
key?: string;
}
interface SshPublicKeysResource {
/** Deletes an SSH public key. */
delete(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/**
* The fingerprint of the public key to update. Public keys are identified by
* their SHA-256 fingerprint. The fingerprint of the public key is in format
* `users/{user}/sshPublicKeys/{fingerprint}`.
*/
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
/** Retrieves an SSH public key. */
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/**
* The fingerprint of the public key to retrieve. Public keys are identified
* by their SHA-256 fingerprint. The fingerprint of the public key is in
* format `users/{user}/sshPublicKeys/{fingerprint}`.
*/
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<SshPublicKey>;
/**
* Updates an SSH public key and returns the profile information. This method
* supports patch semantics.
*/
patch(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/**
* The fingerprint of the public key to update. Public keys are identified by
* their SHA-256 fingerprint. The fingerprint of the public key is in format
* `users/{user}/sshPublicKeys/{fingerprint}`.
*/
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Mask to control which fields get updated. Updates all if not present. */
updateMask?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<SshPublicKey>;
}
interface UsersResource {
/**
* Retrieves the profile information used for logging in to a virtual machine
* on Google Compute Engine.
*/
getLoginProfile(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The unique ID for the user in format `users/{user}`. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<LoginProfile>;
/**
* Adds an SSH public key and returns the profile information. Default POSIX
* account information is set when no username and UID exist as part of the
* login profile.
*/
importSshPublicKey(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The unique ID for the user in format `users/{user}`. */
parent: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ImportSshPublicKeyResponse>;
sshPublicKeys: SshPublicKeysResource;
}
}
} | the_stack |
export function connect(host: string, username: string, password: string): Promise<QBittorrentApiEndpoint>;
export interface QBittorrentApiEndpoint {
appVersion(): Promise<string>;
apiVersion(): Promise<string>;
buildInfo(): Promise<BuildInfo>;
shutdown(): Promise<void>;
preferences(): Promise<Preferences>;
defaultSavePath(): Promise<string>;
log(normal?: boolean, info?: boolean, warning?: boolean, critical?: boolean, lastKnownId?: number): Promise<Log[]>;
peerLog(lastKnownId?: number): Promise<PeerLog[]>;
syncMainData(rid?: number): Promise<MainData>;
syncPeersData(hash: string, rid?: number): Promise<PeerData>;
transferInfo(): Promise<TransferInfo>;
speedLimitsMode(): Promise<number>;
toggleSpeedLimitsMode(): Promise<void>;
globalDownloadLimit(): Promise<number>;
setGlobalDownloadLimit(limit: number): Promise<void>;
globalUploadLimit(): Promise<number>;
setGlobalUploadLimit(limit: number): Promise<void>;
banPeers(peers: string): Promise<void>;
torrents(
filter?: filterString,
category?: string,
sort?: string,
reverse?: boolean,
limit?: number,
offset?: number,
hashes?: string,
): Promise<Torrent[]>;
properties(hash: string): Promise<TorrentInfo>;
trackers(hash: string): Promise<Tracker[]>;
webseeds(hash: string): Promise<Webseed[]>;
files(hash: string): Promise<Content[]>;
pieceStates(hash: string): Promise<Array<(0 | 1 | 2)>>;
pieceHashes(hash: string): Promise<string[]>;
pauseTorrents(hashes: string): Promise<void>;
resumeTorrents(hashes: string): Promise<void>;
deleteTorrents(hashes: string, deleteFile: boolean): Promise<void>;
recheckTorrents(hashes: string): Promise<void>;
reannounceTorrents(hashes: string): Promise<void>;
editTrackers(hash: string, origUrl: string, newUrl: string): Promise<void>;
removeTrackers(hash: string, urls: string): Promise<void>;
addPeers(hashes: string, peers: string): Promise<void>;
addTrackers(hash: string, urls: string): Promise<void>;
increasePriority(hashes: string): Promise<void>;
decreasePriority(hashes: string): Promise<void>;
maxPriority(hashes: string): Promise<void>;
minPriority(hashes: string): Promise<void>;
setFilePriority(hash: string, id: string, priority: 0 | 1 | 6 | 7): Promise<void>;
downloadLimit(hashes: string): Promise<void>;
setDownloadLimit(hashes: string, limit: string): Promise<void>;
setShareLimit(hashes: string, ratioLimit: string, seedingTimeLimit: string): Promise<void>;
uploadLimit(hashes: string): Promise<void>;
setUploadLimit(hashes: string, limit: string): Promise<void>;
setLocation(hashes: string, location: string): Promise<void>;
rename(hash: string, name: string): Promise<void>;
setCategory(hashes: string, category: string): Promise<void>;
categories(): Promise<Categories>;
createCategory(category: string, savePath: string): Promise<void>;
editCategory(category: string, savePath: string): Promise<void>;
removeCategories(categories: string): Promise<void>;
addTags(hashes: string, tags: string): Promise<void>;
removeTags(hashes: string, tags: string): Promise<void>;
tags(): Promise<string[]>;
createTags(tags: string): Promise<void>;
deleteTags(tags: string): Promise<void>;
setAutoManagement(hashes: string, enable: boolean): Promise<void>;
toggleSequentialDownload(hashes: string): Promise<void>;
toggleFirstLastPiecePrio(hashes: string): Promise<void>;
setForceStart(hashes: string, value: boolean): Promise<void>;
setSuperSeeding(hashes: string, value: boolean): Promise<void>;
renameFile(hash: string, id: number, name: string): Promise<void>;
startSearch(pattern: string, plugins: string, category: string): Promise<SearchJob>;
stopSearch(id: number): Promise<void>;
searchStatus(id?: number): Promise<SearchStatus[]>;
searchResults(id: number, limit?: number, offset?: number): Promise<SearchResults>;
deleteSearch(id: number): Promise<void>;
searchCategories(pluginName?: string | 'all' | 'enabled'): Promise<string[]>;
searchPlugins(): Promise<SearchPlugin[]>;
installPlugin(sources: string): Promise<void>;
uninstallPlugin(names: string): Promise<void>;
enablePlugin(names: string, enable: boolean): Promise<void>;
updatePlugins(): Promise<void>;
}
export interface BuildInfo {
qt: string;
libtorrent: string;
boost: string;
openssl: string;
bitness: string;
}
export interface Preferences {
locale: string;
create_subfolder_enabled: boolean;
start_paused_enabled: boolean;
auto_delete_mode: number;
preallocate_all: boolean;
incomplete_files_ext: boolean;
auto_tmm_enabled: boolean;
torrent_changed_tmm_enabled: boolean;
save_path_changed_tmm_enabled: boolean;
category_changed_tmm_enabled: boolean;
save_path: string;
temp_path_enabled: boolean;
temp_path: string;
scan_dirs: object;
export_dir: string;
export_dir_fin: string;
mail_notification_enabled: boolean;
mail_notification_sender: string;
mail_notification_email: string;
mail_notification_smtp: string;
mail_notification_ssl_enabled: boolean;
mail_notification_auth_enabled: boolean;
mail_notification_username: string;
mail_notification_password: string;
autorun_enabled: boolean;
autorun_program: string;
queueing_enabled: boolean;
max_active_downloads: number;
max_active_torrents: number;
max_active_uploads: number;
dont_count_slow_torrents: boolean;
slow_torrent_dl_rate_threshold: number;
slow_torrent_ul_rate_threshold: number;
slow_torrent_inactive_timer: number;
max_ratio_enabled: boolean;
max_ratio: number;
max_ratio_act: boolean;
listen_port: number;
upnp: boolean;
random_port: boolean;
dl_limit: number;
up_limit: number;
max_connec: number;
max_connec_per_torrent: number;
max_uploads: number;
max_uploads_per_torrent: number;
enable_utp: boolean;
limit_utp_rate: boolean;
limit_tcp_overhead: boolean;
limit_lan_peers: boolean;
alt_dl_limit: number;
alt_up_limit: number;
scheduler_enabled: boolean;
schedule_from_hour: number;
schedule_from_min: number;
schedule_to_hour: number;
schedule_to_min: number;
scheduler_days: number;
dht: boolean;
dhtSameAsBT: boolean;
dht_port: number;
pex: boolean;
lsd: boolean;
encryption: number;
anonymous_mode: boolean;
proxy_type: number;
proxy_ip: string;
proxy_port: number;
proxy_peer_connections: boolean;
force_proxy: boolean;
proxy_auth_enabled: boolean;
proxy_username: string;
proxy_password: string;
ip_filter_enabled: boolean;
ip_filter_path: string;
ip_filter_trackers: boolean;
web_ui_domain_list: string;
web_ui_address: string;
web_ui_port: number;
web_ui_upnp: boolean;
web_ui_username: string;
web_ui_password: string; // writeonly
web_ui_csrf_protection_enabled: boolean;
web_ui_clickjacking_protection_enabled: boolean;
bypass_local_auth: boolean;
bypass_auth_subnet_whitelist_enabled: boolean;
bypass_auth_subnet_whitelist: string;
alternative_webui_enabled: boolean;
alternative_webui_path: string;
use_https: boolean;
ssl_key: string;
ssl_cert: string;
dyndns_enabled: boolean;
dyndns_service: number;
dyndns_username: string;
dyndns_password: string;
dyndns_domain: string;
rss_refresh_interval: number;
rss_max_articles_per_feed: number;
rss_processing_enabled: boolean;
rss_auto_downloading_enabled: boolean;
}
export interface Log {
id: number;
message: string;
timestamp: number;
type: LogTypesInt;
}
export type LogTypesInt = 1 | 2 | 4 | 8;
export type LogTypesString = 'normal' | 'info' | 'warning' | 'critical';
export interface PeerLog {
id: number;
ip: string;
timestamp: number;
blocked: boolean;
reason: string;
}
export interface MainData {
rid: number;
full_update: boolean;
torrents: object;
torrents_removed: string[];
categories: object;
categories_removed: string[];
tags: string[];
tags_removed: string[];
server_state: object;
}
export interface TransferInfo {
dl_info_speed: number;
dl_info_data: number;
up_info_speed: number;
up_info_data: number;
dl_rate_limit: number;
up_rate_limit: number;
dht_nodes: number;
connection_status: string;
}
export interface Torrent {
added_on: number;
amount_left: number;
auto_tmm: boolean;
category: string;
completed: number;
completion_on: number;
dl_limit: number;
dlspeed: number;
downloaded: number;
downloaded_session: number;
eta: number;
f_l_piece_prio: boolean;
force_start: boolean;
hash: string;
last_activity: number;
magnet_uri: string;
max_ratio: number;
max_seeding_time: number;
name: string;
num_complete: number;
num_incomplete: number;
num_leechs: number;
num_seeds: number;
priority: number;
progress: number;
ratio: number;
ratio_limit: number;
save_path: string;
seeding_time_limit: number;
seen_complete: number;
seq_dl: boolean;
size: number;
state: string;
super_seeding: boolean;
tags: string;
time_active: number;
total_size: number;
tracker: string;
up_limit: number;
uploaded: number;
uploaded_session: number;
upspeed: number;
}
export interface TorrentInfo {
save_path: string;
creation_date: number;
piece_size: number;
comment: string;
total_wasted: number;
total_uploaded: number;
total_uploaded_session: number;
total_downloaded: number;
total_downloaded_session: number;
up_limit: number;
dl_limit: number;
time_elapsed: number;
seeding_time: number;
nb_connections: number;
nb_connections_limit: number;
share_ratio: number;
addition_date: number;
completion_date: number;
created_by: string;
dl_speed_avg: number;
dl_speed: number;
eta: number;
last_seen: number;
peers: number;
peers_total: number;
pieces_have: number;
pieces_num: number;
reannounce: number;
seeds: number;
seeds_total: number;
total_size: number;
up_speed_avg: number;
up_speed: number;
}
export interface Tracker {
url: string;
status: number;
tier: number;
num_peers: number;
num_seeds: number;
num_leeches: number;
num_downloaded: number;
msg: string;
}
export interface Webseed {
url: string;
}
export interface Content {
name: string;
size: number;
progress: number;
priority: 0 | 1 | 6 | 7;
is_seed: boolean;
piece_range: number;
availability: number;
}
export interface SearchJob {
id: number;
}
export interface SearchStatus {
id: number;
status: string;
total: number;
}
export interface SearchResult {
descrLink: string;
fileName: string;
fileSize: number;
fileUrl: string;
nbLeechers: number;
nbSeeders: number;
siteUrl: string;
}
export interface SearchResults {
results: SearchResult[];
status: string;
total: number;
}
export interface SearchPlugin {
enabled: boolean;
fullName: string;
name: string;
supportedCategories: string[];
url: string;
version: string;
}
export type filterString = 'all' | 'downloading' | 'completed' | 'paused' | 'active' | 'inactive' | 'resumed';
export type Categories = object;
export type PeerData = object; | the_stack |
import {Component, ElementRef, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {FormGroup, FormBuilder, Validators} from '@angular/forms';
import {
NgbModal,
NgbActiveModal,
NgbModalRef,
NgbPopover,
NgbAccordion
} from '@ng-bootstrap/ng-bootstrap';
import {find, map, findIndex, cloneDeep, extend} from 'lodash';
import {TranslateService} from '@ngx-translate/core';
import {Observable} from 'rxjs';
import {ContentField} from './models/content_field.model';
import {ContentType} from './models/content_type.model';
import {FieldType} from './models/field-type.model';
import {QueryOptions} from '../models/query-options';
import {PageTableAbstractComponent} from '../page-table.abstract';
import {SortData} from '../components/sorting-dnd.conponent';
import {AppModalContentAbstractComponent} from '../components/app-modal-content.abstract';
import {ContentTypesService} from './services/content_types.service';
import {SystemNameService} from '../services/system-name.service';
import {CollectionsService} from './services/collections.service';
import {FieldTypesService} from './services/field-types.service';
import {FormFieldsErrors, FormFieldsOptions} from '../models/form-fields-options.interface';
import {ModalEditTextareaComponent} from '../components/modal-edit-textarea.component';
@Component({
selector: 'app-content-type-modal-content',
templateUrl: 'templates/modal-content_type.html'
})
export class ContentTypeModalContentComponent extends AppModalContentAbstractComponent<ContentType> implements OnInit, OnDestroy {
@ViewChild('addCollectionBlock', { static: true }) elementAddCollectionBlock;
@ViewChild('addGroupBlock', { static: true }) elementAddGroupBlock;
@ViewChild('accordion', { static: true }) accordion;
@ViewChild('blockFieldList') blockFieldList;
modalRef: NgbModalRef;
private _secondFormFieldsErrors: FormFieldsErrors = {};
model = new ContentType(0, '', '', '', 'products', [], ['General', 'Service'], true, false);
fieldModel = new ContentField(0, '', '', '', '', {}, '', {}, '');
sortData: SortData[] = [];
sortingFieldName = '';
fld_submitted = false;
errorFieldMessage: string;
action = 'add_field';
currentFieldName = '';
collections: string[] = ['products'];
secondForm: FormGroup;
fieldTypes: FieldType[];
fieldTypeProperties = {
input: [],
output: []
};
formFields: FormFieldsOptions[] = [
{
name: 'title',
validators: [Validators.required]
},
{
name: 'name',
validators: [Validators.required, Validators.pattern('[A-Za-z0-9_-]+')]
},
{
name: 'description',
validators: []
},
{
name: 'collection',
validators: [Validators.required]
},
{
name: 'newCollection',
validators: [Validators.pattern('[A-Za-z0-9_-]+')]
},
{
name: 'isCreateByUsersAllowed',
validators: []
},
{
name: 'isActive',
validators: []
}
];
secondFormFields: FormFieldsOptions[] = [
{
name: 'title',
validators: [Validators.required]
},
{
name: 'name',
validators: [Validators.required, Validators.pattern('[A-Za-z0-9_-]+')]
},
{
name: 'description',
validators: []
},
{
name: 'inputType',
validators: [Validators.required]
},
{
name: 'outputType',
validators: [Validators.required]
},
{
name: 'group',
validators: [Validators.required]
},
{
name: 'newGroup',
validators: []
},
{
name: 'required',
validators: []
},
{
name: 'showInTable',
validators: []
},
{
name: 'showOnPage',
validators: []
},
{
name: 'showInList',
validators: []
},
{
name: 'isFilter',
validators: []
}
];
set secondFormErrors(formFieldsErrors: FormFieldsErrors) {
for (const key in formFieldsErrors) {
if (formFieldsErrors.hasOwnProperty(key)) {
const control = this.getControl(this.form, null, key);
if (control) {
control.setErrors({incorrect: true});
}
}
}
this._secondFormFieldsErrors = formFieldsErrors;
}
get secondFormErrors() {
return this._secondFormFieldsErrors;
}
constructor(
public fb: FormBuilder,
public activeModal: NgbActiveModal,
public translateService: TranslateService,
public systemNameService: SystemNameService,
public dataService: ContentTypesService,
public elRef: ElementRef,
private fieldTypesService: FieldTypesService,
private collectionsService: CollectionsService,
private modalService: NgbModal
) {
super(fb, activeModal, translateService, systemNameService, dataService, elRef);
}
onAfterInit(): void {
this.buildForm('secondForm', this.secondFormFields, this.secondFormErrors, 'fieldModel');
this.onValueChanged('secondForm', this.secondFormErrors);
this.getFieldTypes();
this.getCollectionsList();
}
/** Get field types */
getFieldTypes(): void {
const options = new QueryOptions('title', 'asc', 0, 0, 1);
this.fieldTypesService.getListPage(options)
.subscribe(
data => {
this.fieldTypes = data.items;
},
error => this.errorMessage = error
);
}
/** Get collections list */
getCollectionsList(): void {
this.collectionsService.getList()
.subscribe(data => {
if (data.length > 0) {
this.collections = data;
}
}
);
}
/**
* Select field type properties
* @param {string} type
* @param {string} fieldTypeName
*/
selectFieldTypeProperties(type: string, fieldTypeName?: string): void {
if (fieldTypeName) {
this.secondForm.get(`${type}Type`).setValue(fieldTypeName);
} else {
fieldTypeName = this.secondForm.get(`${type}Type`).value;
}
this.fieldModel[`${type}Type`] = fieldTypeName;
const fieldType = find(this.fieldTypes, {name: fieldTypeName});
if (!fieldType) {
this.fieldTypeProperties[type] = [];
return;
}
const modelPropertiesField = `${type}Properties`;
const propNames = map(fieldType[`${type}Properties`], 'name');
this.fieldTypeProperties[type].splice(0);
fieldType[type + 'Properties'].forEach((v, i) => {
this.fieldTypeProperties[type].push(v);
});
for (const prop in this.fieldModel[modelPropertiesField]) {
if (this.fieldModel[modelPropertiesField].hasOwnProperty(prop)) {
if (propNames.indexOf(prop) === -1) {
delete this.fieldModel[modelPropertiesField][prop];
}
}
}
for (const i in this.fieldTypeProperties[type]) {
if (this.fieldTypeProperties[type].hasOwnProperty(i)) {
const fldName = this.fieldTypeProperties[type][i].name;
if (typeof this.fieldModel[modelPropertiesField][fldName] === 'undefined') {
this.fieldModel[modelPropertiesField][fldName] = this.fieldTypeProperties[type][i].default_value;
}
}
}
if (type === 'input' && !this.fieldModel.outputType) {
this.selectFieldTypeProperties('output', fieldTypeName);
}
}
addCollectionToggle(addCollectionField: HTMLInputElement, event?: MouseEvent): void {
this.displayToggle(this.elementAddCollectionBlock.nativeElement);
addCollectionField.value = '';
this.onValueChanged();
addCollectionField.focus();
}
/** Add collection */
addCollection(event?: MouseEvent) {
if (event) {
event.preventDefault();
}
const fieldName = 'newCollection';
const control = this.form.get(fieldName);
if (!control.valid || !control.value) {
return false;
}
this.formErrors[fieldName] = '';
const value = control.value;
if (this.collections.indexOf(value) > -1) {
this.getControl(this.form, null, fieldName).setErrors({exists: 'COLLECTION_EXISTS'});
this.formErrors[fieldName] = this.getLangString('COLLECTION_EXISTS');
return false;
}
this.collections.push(value);
this.model.collection = value;
this.getControl(this.form, null, fieldName).setValue(value);
this.elementAddCollectionBlock.nativeElement.style.display = 'none';
return true;
}
/** Delete collection */
deleteCollection(popover: NgbPopover) {
if (!this.model.collection) {
return;
}
if (popover.isOpen()) {
popover.close();
return;
}
let popoverContent: any;
popover.placement = 'top';
popover.popoverTitle = this.getLangString('CONFIRM');
const confirm = () => {
this.loading = true;
this.collectionsService.deleteItemByName(this.model.collection)
.subscribe((data) => {
const index = this.collections.indexOf(this.model.collection);
if (index > -1) {
this.collections.splice(index, 1);
this.model.collection = this.collections[0] || '';
}
popover.close();
this.loading = false;
}, (err) => {
this.errorMessage = err.error || 'Error.';
this.loading = false;
});
};
popoverContent = {
p: popover,
confirm: confirm.bind(this),
message: ''
};
popover.open(popoverContent);
}
/** Add group */
addGroup(event?: MouseEvent) {
if (event) {
event.preventDefault();
}
const fieldName = 'newGroup';
const control = this.secondForm.get(fieldName);
if (!control || !control.valid || !control.value) {
return false;
}
this.errorFieldMessage = '';
this.secondFormErrors[fieldName] = '';
const value = control.value;
const index = this.model.groups.indexOf(value);
if (index > -1) {
this.getControl(this.secondForm, null, fieldName).setErrors({exists: 'GROUP_ALREADY_EXISTS'});
this.secondFormErrors[fieldName] = this.getLangString('GROUP_ALREADY_EXISTS');
return false;
}
this.model.groups.push(value);
this.fieldModel.group = value;
this.getControl(this.secondForm, null, 'group').setValue(this.fieldModel.group);
this.elementAddGroupBlock.nativeElement.style.display = 'none';
return true;
}
/** Delete group */
deleteGroup() {
const currentGroupName = this.secondForm.get('group').value;
let index = findIndex(this.model.fields, {group: currentGroupName});
this.errorFieldMessage = '';
if (index > -1) {
this.errorFieldMessage = this.getLangString('YOU_CANT_DELETE_NOTEMPTY_GROUP');
return;
}
index = this.model.groups.indexOf(currentGroupName);
if (index > -1) {
this.model.groups.splice(index, 1);
}
}
editField(field: ContentField, event?: MouseEvent) {
if (event) {
event.preventDefault();
}
this.toggleAccordion(this.accordion, 'accordion-content-type-fields');
this.action = 'edit_field';
this.fieldModel = cloneDeep(field);
const newFormValue = {};
this.secondFormFields.forEach((opt) => {
newFormValue[opt.name] = field[opt.name] || null;
});
this.secondForm.setValue(newFormValue);
this.selectFieldTypeProperties('input');
this.selectFieldTypeProperties('output');
this.currentFieldName = this.fieldModel.name;
this.fld_submitted = false;
}
copyField(field: ContentField, event?: MouseEvent) {
if (event) {
event.preventDefault();
}
this.toggleAccordion(this.accordion, 'accordion-content-type-fields');
this.action = 'add_field';
this.fieldModel = cloneDeep(field);
this.fieldModel.name = '';
this.secondForm.setValue(this.fieldModel);
this.currentFieldName = '';
this.fld_submitted = false;
}
deleteField(field: ContentField, event?: MouseEvent) {
if (event) {
event.preventDefault();
}
const index = findIndex( this.model.fields, {name: field.name} );
if (index === -1 ) {
this.errorMessage = 'Field not found.';
return;
}
this.model.fields.splice(index, 1);
}
/** Reset field form */
resetFieldForm() {
this.action = 'add_field';
this.errorMessage = '';
this.errorFieldMessage = '';
this.fld_submitted = false;
this.currentFieldName = '';
this.secondForm.reset();
this.fieldModel = new ContentField(0, '', '', '', '', {}, '', {}, '');
}
/** Cancel edit field */
editFieldCancel(event?: MouseEvent) {
if (event) {
event.preventDefault();
}
this.toggleAccordion(this.accordion, 'accordion-content-type-fields', true);
this.resetFieldForm();
this.onValueChanged('secondForm', this.secondFormErrors);
}
/** Change field order index */
fieldMove(index: number, direction: string): void {
if ((direction === 'up' && index === 0)
|| (direction === 'down' && index === this.model.fields.length - 1)) {
return;
}
const newIndex = direction === 'up' ? index - 1 : index + 1;
const field = this.model.fields[index];
this.model.fields.splice(index, 1);
this.model.fields.splice(newIndex, 0, field);
}
/** Submit field */
submitField(event?: MouseEvent) {
if (event) {
event.preventDefault();
}
this.errorFieldMessage = '';
this.fld_submitted = true;
if (!this.secondForm.valid) {
this.formGroupMarkTouched(this.secondForm);
this.onValueChanged('secondForm', this.secondFormErrors);
this.fld_submitted = false;
return;
}
const data = cloneDeep(Object.assign({}, this.secondForm.value, {
inputProperties: this.fieldModel.inputProperties,
outputProperties: this.fieldModel.outputProperties
}));
let index = findIndex(this.model.fields, {name: data.name});
if (index > -1 && this.currentFieldName !== data.name) {
this.errorFieldMessage = this.getLangString('FIELD_NAME_EXISTS');
return;
}
this.toggleAccordion(this.accordion, 'accordion-content-type-fields', true);
if (this.action === 'add_field') {
this.model.fields.push(data);
} else if (this.action === 'edit_field') {
index = findIndex(this.model.fields, {name: this.currentFieldName});
if (index > -1) {
this.model.fields[index] = data;
}
}
this.resetFieldForm();
}
getFieldTypeProperty(inputType: string|null, propertyName: string): string|null {
if (!inputType) {
return null;
}
let output = null;
const index = findIndex(this.fieldTypes, {name: inputType});
if (index > -1 && typeof this.fieldTypes[index][propertyName] !== 'undefined') {
output = this.fieldTypes[index][propertyName];
}
return output;
}
sortingInit(sortingFieldName: string, filterFieldName: string, event?: MouseEvent): void {
if (event) {
event.preventDefault();
}
this.sortingFieldName = sortingFieldName;
let filteredData;
if (filterFieldName) {
filteredData = this.model.fields.filter((field) => {
return field[filterFieldName];
});
} else {
filteredData = this.model.fields;
}
if (sortingFieldName) {
filteredData.sort(function(a, b) {
return a[sortingFieldName] - b[sortingFieldName]
});
}
this.sortData = [];
filteredData.forEach((data) => {
this.sortData.push({
name: data['name'],
title: data['title']
});
});
this.blockFieldList.nativeElement.style.display = 'none';
}
sortingStart(sortTypeValue: string, event?: MouseEvent): void {
if (event) {
event.preventDefault();
}
this.errorMessage = '';
const sortTypeValueArr = sortTypeValue.split('-');
this.sortingFieldName = sortTypeValueArr[0];
const filteredData = sortTypeValueArr[1]
? this.model.fields.filter((field) => {
return field[sortTypeValueArr[1]];
})
: this.model.fields;
filteredData.sort(function(a, b) {
return a[sortTypeValueArr[0]] - b[sortTypeValueArr[0]]
});
if (filteredData.length === 0) {
this.errorMessage = this.getLangString('SORT_FIELDS_EMPTY');
return;
}
this.sortData = filteredData.map((data) => {
return {name: data.name, title: data.title};
});
this.blockFieldList.nativeElement.style.display = 'none';
}
sortingApply(items?: any): void {
if (this.sortingFieldName) {
this.sortData.forEach((field, index) => {
const ind = this.model.fields.findIndex((fld) => {
return fld.name === field.name;
});
if (ind > -1) {
this.model.fields[ind][this.sortingFieldName] = index;
}
});
} else {
const sortedNames = this.sortData.map((item) => {
return item['name'];
});
this.model.fields.sort(function(a, b) {
return sortedNames.indexOf(a['name']) - sortedNames.indexOf(b['name']);
});
}
this.sortingReset();
}
sortingReset(): void {
const index = findIndex(this.model.fields, {name: this.currentFieldName});
if (index > -1) {
this.action = 'edit_field';
} else {
this.action = 'add_field';
}
this.sortData.splice(0, this.sortData.length);
this.sortingFieldName = '';
this.blockFieldList.nativeElement.style.display = 'block';
}
getSaveRequest(data: ContentType): Observable<ContentType> {
if (data.id) {
return this.dataService.update(data);
} else {
return this.dataService.create(data);
}
}
getFormData(): ContentType {
if (this.sortData.length > 0) {
this.sortingApply();
}
const data = this.form.value as ContentType;
data.id = this.model.id || 0;
data.groups = this.model.groups;
data.fields = this.model.fields;
return data;
}
toggleAccordion(accordion: NgbAccordion, panelId: string, display?: boolean): void {
const isOpened = accordion.activeIds.indexOf(panelId) > -1;
if (isOpened && display) {
return;
}
accordion.toggle(panelId);
}
fieldsExport(event?: MouseEvent): void {
if (event) {
event.preventDefault();
}
this.errorMessage = '';
if (!this.model.fields) {
this.model.fields = [];
}
this.errorMessage = '';
const dataStr = JSON.stringify(this.model.fields, null, '\t');
const modalRef = this.modalService.open(ModalEditTextareaComponent, {
backdrop: 'static',
keyboard: false,
container: '#modals-container'
});
modalRef.componentInstance.modalTitle = `${this.getLangString('EXPORT')} JSON`;
modalRef.componentInstance.textValue = dataStr;
modalRef.result.then((result) => {
if (result.data) {
try {
const outputData = JSON.parse(result.data);
this.model.fields.splice(0, this.model.fields.length);
this.model.fields.push(...outputData);
} catch (e) {
this.errorMessage = this.getLangString('JSON_SYNTAX_ERROR');
}
}
}, (reason) => {
// console.log(reason);
});
}
}
@Component({
selector: 'app-shk-content-types',
templateUrl: 'templates/catalog-content_types.html'
})
export class ContentTypesComponent extends PageTableAbstractComponent<ContentType> {
title = 'Типы контента';
queryOptions: QueryOptions = new QueryOptions('name', 'asc', 1, 10, 0, 0);
tableFields = [
{
name: 'id',
sortName: 'id',
title: 'ID',
outputType: 'text',
outputProperties: {}
},
{
name: 'title',
sortName: 'title',
title: 'TITLE',
outputType: 'text',
outputProperties: {}
},
{
name: 'name',
sortName: 'name',
title: 'SYSTEM_NAME',
outputType: 'text',
outputProperties: {}
},
{
name: 'collection',
sortName: 'collection',
title: 'COLLECTION',
outputType: 'text',
outputProperties: {}
},
{
name: 'isActive',
sortName: 'isActive',
title: 'STATUS',
outputType: 'boolean',
outputProperties: {}
}
];
constructor(
public dataService: ContentTypesService,
public activeModal: NgbActiveModal,
public modalService: NgbModal,
public translateService: TranslateService
) {
super(dataService, activeModal, modalService, translateService);
}
getModalContent() {
return ContentTypeModalContentComponent;
}
getModalElementId(itemId?: number): string {
// if (this.isEditMode) {
// this.modalTitle = ` ${this.getLangString('CONTENT_TYPE')} #${this.itemId}`;
// }
return ['modal', 'content_type', itemId || 0].join('-');
}
setModalInputs(itemId?: number, isItemCopy: boolean = false, modalId = ''): void {
super.setModalInputs(itemId, isItemCopy, modalId);
this.modalRef.componentInstance.modalTitle = itemId && !isItemCopy
? `${this.getLangString('CONTENT_TYPE')} #${itemId}`
: this.getLangString('ADD_CONTENT_TYPE');
}
} | the_stack |
window.browser = (function(){
return window.msBrowser ||
window.browser ||
window.chrome;
})();
module VORLON {
declare var $: any;
export class DashboardManager {
static ExtensionConfigUrl: string;
static TargetTabid: number;
static DisplayingTab: boolean;
static TabList: any;
static PluginsLoaded: boolean;
constructor(tabId) {
//Dashboard session id
DashboardManager.PluginsLoaded = false;
DashboardManager.DisplayingTab = false;
//Client ID
DashboardManager.TargetTabid = tabId;
DashboardManager.TabList = {};
DashboardManager.ExtensionConfigUrl = "/extensionconfig.json";
DashboardManager.GetTabs();
browser.tabs.onCreated.addListener((tab) => {
DashboardManager.addTab(DashboardManager.GetInternalTabObject(tab));
});
browser.tabs.onRemoved.addListener((tabId, removeInfo) => {
if(tabId === DashboardManager.TargetTabid){
DashboardManager.showWaitingLogo();
}
DashboardManager.removeTab({'id': tabId});
});
browser.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
var internalTab = DashboardManager.GetInternalTabObject(tab);
DashboardManager.renameTab(internalTab);
});
browser.tabs.onReplaced.addListener((addedTabId, removedTabId) => {
DashboardManager.removeTab({'id': removedTabId});
browser.tabs.get(addedTabId, (tab: browser.tabs.Tab) => {
DashboardManager.addTab(DashboardManager.GetInternalTabObject(tab));
});
});
}
public static GetInternalTabObject(tab:browser.tabs.Tab): any{
return {
'id': tab.id,
'name': tab.title,
'url': tab.url
};
}
public static GetTabs(): void {
//Init ClientTab Object
DashboardManager.TabList = {};
//Loading tab list
var tabs = [];
browser.tabs.getCurrent((currentTab) => {
browser.tabs.query({}, (tabresult) => {
for(var i = 0; i < tabresult.length; i++){
var tab = DashboardManager.GetInternalTabObject(tabresult[i]);
if (tab.id === currentTab.id) {
continue;
}
tabs.push(tab);
}
//Test if the client to display is in the list
var contains = false;
if (tabs && tabs.length) {
for (var j = 0; j < tabs.length; j++) {
if (tabs[j].id === DashboardManager.TargetTabid) {
contains = true;
break;
}
}
}
//Get the client list placeholder
var divClientsListPane = <HTMLDivElement> document.getElementById("clientsListPaneContent");
//Create the new empty list
var clientlist = document.createElement("ul");
clientlist.setAttribute("id", "clientsListPaneContentList")
divClientsListPane.appendChild(clientlist);
for (var i = 0; i < tabs.length; i++) {
var tab = tabs[i];
DashboardManager.AddTabToList(tab);
}
if (contains) {
DashboardManager.loadPlugins();
}
});
});
}
public static AddTabToList(tab: any){
var filteredURL = [
"https://www.msn.com/spartan/dhp", // Start page
"https://www.msn.com/spartan/ntp", // New Tab Page
"about:", // All other about pages
".pdf", // .PDF files
"read:", // Reading view
"ms-browser-extension://", // Extension pages
"moz-extension://",
"chrome-extension://"
];
var tabToFilter = false;
for (var f in filteredURL)
{
if (tab.url.indexOf(filteredURL[f]) !== -1)
{
tabToFilter = true;
break;
}
}
if (!tabToFilter) {
var tablist = <HTMLUListElement> document.getElementById("clientsListPaneContentList");
if (DashboardManager.TargetTabid == null) {
DashboardManager.TargetTabid = tab.id;
}
var pluginlistelement = document.createElement("li");
pluginlistelement.classList.add('client');
pluginlistelement.id = tab.id;
if (tab.id == DashboardManager.TargetTabid) {
pluginlistelement.classList.add('active');
}
var tabs = tablist.children;
if(tabs.length === 0 || DashboardManager.TabList[(<HTMLElement>tabs[tabs.length - 1]).id].name < tab.name){
tablist.appendChild(pluginlistelement);
}
else if(tabs.length === 1){
var firstClient = <HTMLElement>tabs[tabs.length - 1];
tablist.insertBefore(pluginlistelement, firstClient);
}
else{
for (var i = 0; i < tabs.length - 1; i++) {
var currentClient = <HTMLElement>(tabs[i]);
var nextClient = <HTMLElement>(tabs[i+1]);
if(DashboardManager.TabList[currentClient.id].name < tab.name
&& DashboardManager.TabList[nextClient.id].name >= tab.name){
tablist.insertBefore(pluginlistelement, nextClient);
break;
}
else if(i === 0){
tablist.insertBefore(pluginlistelement, currentClient);
}
}
}
var pluginlistelementa = document.createElement("a");
pluginlistelementa.textContent = " " + (tab.name);
pluginlistelementa.setAttribute("href", "?tabid=" + tab.id);
pluginlistelement.appendChild(pluginlistelementa);
DashboardManager.TabList[tab.id] = tab;
}
}
static TabCount(): number{
return Object.keys(DashboardManager.TabList).length;
}
public static loadPlugins(): void {
if(DashboardManager.TargetTabid == null && isNaN(DashboardManager.TargetTabid)){
return;
}
if(this.PluginsLoaded){
// Start Listening
return;
}
let xhr = new XMLHttpRequest();
let divPluginsTop = <HTMLDivElement> document.getElementById("pluginsPaneTop");
let coreLoaded = false;
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var extensionConfig;
try {
extensionConfig = JSON.parse(xhr.responseText);
} catch (ex) {
throw new Error("The catalog JSON is not well-formed");
}
var existingLocation = document.querySelector('[data-plugin=' + extensionConfig.name + ']');
if (!existingLocation) {
var pluginmaindiv = document.createElement('div');
pluginmaindiv.classList.add('plugin');
pluginmaindiv.classList.add('plugin-' + extensionConfig.name.toLowerCase());
pluginmaindiv.setAttribute('data-plugin', extensionConfig.name);
if (divPluginsTop.children.length === 1) {
pluginmaindiv.classList.add("active");
}
divPluginsTop.appendChild(pluginmaindiv);
}
var pluginscript = document.createElement("script");
pluginscript.setAttribute("src", "../plugin/vorlon." + extensionConfig.name + ".dashboard.js");
pluginscript.onload = (oError) => {
//Start listening server
VORLON.Core.StartDashboardSide(DashboardManager.TargetTabid, DashboardManager.divMapper);
coreLoaded = true;
this.PluginsLoaded = true;
DashboardManager.hideWaitingLogo();
};
document.body.appendChild(pluginscript);
}
}
}
xhr.open("GET", browser.extension.getURL(DashboardManager.ExtensionConfigUrl));
xhr.send();
}
public static hideWaitingLogo(): void{
var elt = <HTMLElement>document.querySelector('.dashboard-plugins-overlay');
VORLON.Tools.AddClass(elt, 'hidden');
}
public static showWaitingLogo(): void{
var elt = <HTMLElement>document.querySelector('.dashboard-plugins-overlay');
VORLON.Tools.RemoveClass(elt, 'hidden');
}
public static divMapper(pluginId: number): HTMLDivElement {
let divId = pluginId + "div";
var pluginIdS = pluginId.toString().toLowerCase();
return <HTMLDivElement> (document.getElementById(divId) || document.querySelector(`[data-plugin=${pluginIdS}]`));
}
public static addTab(tab: any): void {
DashboardManager.AddTabToList(tab);
if(!DashboardManager.DisplayingTab){
DashboardManager.loadPlugins();
}
}
public static removeTab(tab: any): void {
let tabInList = <HTMLLIElement> document.getElementById(tab.id);
if(tabInList){
if(tab.id === DashboardManager.TargetTabid){
DashboardManager.TargetTabid = null;
//Start listening server
}
tabInList.parentElement.removeChild(tabInList);
DashboardManager.removeInTabList(tab);
if (DashboardManager.TabCount() === 0) {
DashboardManager.DisplayingTab = false;
}
}
}
public static renameTab(tab): void {
let tabInList = <HTMLLIElement> document.getElementById(tab.id);
if(tabInList){
(<HTMLLIElement>tabInList.firstChild).innerText = " " + (tab.name);
}
else {
this.addTab(tab);
}
}
public static removeInTabList(tab: any): void{
if(DashboardManager.TabList[tab.id] != null){
delete DashboardManager.TabList[tab.id];
}
}
}
} | the_stack |
'use strict'
import * as path from 'path';
import * as fs from 'fs';
import { TreeDataProvider, TreeItem, TreeItemCollapsibleState, Uri, window, Event, EventEmitter,
Disposable, commands } from 'vscode';
import { GitService, GitCommittedFile } from './gitService';
import { Model, FilesViewContext } from './model'
import { Icons, getIconUri } from './icons';
const rootFolderIcon = {
dark: getIconUri('structure', 'dark'),
light: getIconUri('structure', 'light')
};
class InfoItem extends TreeItem {
constructor(content: string, label: string) {
super(label);
this.command = {
title: '',
command: 'githd.openCommitInfo',
arguments: [content]
};
this.iconPath = getIconUri('info', '');
};
readonly parent = null;
}
class CommittedFileItem extends TreeItem {
constructor(readonly parent: FolderItem, readonly file: GitCommittedFile, label: string) {
super(label);
this.command = {
title: '',
command: 'githd.openCommittedFile',
arguments: [this.file]
};
if (this.file.status) {
this.iconPath = { light: this._getIconPath('light'), dark: this._getIconPath('dark') };
}
};
private _getIconPath(theme: string): Uri | undefined {
switch (this.file.status[0].toUpperCase()) {
case 'M': return Icons[theme].Modified;
case 'A': return Icons[theme].Added;
case 'D': return Icons[theme].Deleted;
case 'R': return Icons[theme].Renamed;
case 'C': return Icons[theme].Copied;
default: return void 0;
}
}
}
class FolderItem extends TreeItem {
private _subFolders: FolderItem[] = [];
private _files: CommittedFileItem[] = [];
private _infoItem: InfoItem;
constructor(private _parent: FolderItem, private _gitRelativePath: string, label: string, iconPath?: { light: Uri; dark: Uri }) {
super(label);
this.contextValue = 'folder';
this.iconPath = iconPath;
this.collapsibleState = TreeItemCollapsibleState.Expanded;
}
readonly parent = this._parent;
readonly gitRelativePath: string = this._gitRelativePath;
get subFolders(): FolderItem[] { return this._subFolders; }
set subFolders(value: FolderItem[]) { this._subFolders = value; }
get files(): CommittedFileItem[] { return this._files; }
set files(value: CommittedFileItem[]) { this._files = value; }
get infoItem(): InfoItem { return this._infoItem; }
set infoItem(value: InfoItem) { this._infoItem = value; }
}
function getFormattedLabel(relativePath: string): string {
const name: string = path.basename(relativePath);
let dir: string = path.dirname(relativePath);
if (dir === '.') {
dir = '';
}
return name + ' \u00a0\u2022\u00a0 ' + dir;
}
function createCommittedFileItem(rootFolder: FolderItem, file: GitCommittedFile): CommittedFileItem {
return new CommittedFileItem(rootFolder, file, getFormattedLabel(file.gitRelativePath));
}
function buildOneFileWithFolder(rootFolder: FolderItem, file: GitCommittedFile, relativePath: string = ''): void {
const segments: string[] = relativePath ? path.relative(relativePath, file.gitRelativePath).split(/\\|\//) :
file.gitRelativePath.split('/');
let gitRelativePath: string = relativePath;
let parent: FolderItem = rootFolder;
let i = 0;
for (; i < segments.length - 1; ++i) {
gitRelativePath += segments[i] + '/';
let folder: FolderItem = parent.subFolders.find(item => { return item.label === segments[i]; });
if (!folder) {
folder = new FolderItem(parent, gitRelativePath, segments[i]);
parent.subFolders.push(folder);
}
parent = folder;
}
parent.files.push(new CommittedFileItem(parent, file, segments[i]));
}
function buildFileTree(rootFolder: FolderItem, files: GitCommittedFile[], withFolder: boolean): void {
if (withFolder) {
files.forEach(file => buildOneFileWithFolder(rootFolder, file));
} else {
rootFolder.files.push(...(files.map(file => { return createCommittedFileItem(rootFolder, file); })));
}
}
function buildFilesWithoutFolder(rootFolder: FolderItem, folder: FolderItem): void {
rootFolder.files.push(...(folder.files.map(item => {
item.label = getFormattedLabel(path.relative(rootFolder.gitRelativePath, item.file.gitRelativePath).replace(/\\/g, '/'));
return item;
})));
folder.subFolders.forEach(f => buildFilesWithoutFolder(rootFolder, f));
folder.files = [];
folder.subFolders = [];
}
function buildFilesWithFolder(rootFolder: FolderItem): void {
rootFolder.subFolders.forEach(folder => buildFilesWithFolder(folder));
const files: CommittedFileItem[] = rootFolder.files;
rootFolder.files = [];
files.forEach(fileItem => buildOneFileWithFolder(rootFolder, fileItem.file, rootFolder.gitRelativePath));
}
function setCollapsibleStateOnAll(rootFolder: FolderItem, state: TreeItemCollapsibleState): void {
if (rootFolder) {
rootFolder.collapsibleState = state;
rootFolder.subFolders.forEach(sub => setCollapsibleStateOnAll(sub, state));
}
}
type CommittedTreeItem = CommittedFileItem | FolderItem | InfoItem;
export class ExplorerViewProvider implements TreeDataProvider<CommittedTreeItem> {
private _disposables: Disposable[] = [];
private _onDidChange: EventEmitter<CommittedTreeItem> = new EventEmitter<CommittedTreeItem>();
private _withFolder: boolean;
private _context: FilesViewContext;
private _treeRoot: (FolderItem | InfoItem)[] = [];
constructor(model: Model, private _gitService: GitService) {
this._disposables.push(window.registerTreeDataProvider('committedFiles', this));
this._disposables.push(commands.registerCommand('githd.showFilesWithFolder',
(folder: FolderItem) => this._showFilesWithFolder(folder)));
this._disposables.push(commands.registerCommand('githd.showFilesWithoutFolder',
(folder: FolderItem) => this._showFilesWithoutFolder(folder)));
this._disposables.push(commands.registerCommand('githd.collapseFolder',
(folder: FolderItem) => this._setCollapsibleStateOnAll(folder, TreeItemCollapsibleState.Collapsed)));
this._disposables.push(commands.registerCommand('githd.expandFolder',
(folder: FolderItem) => this._setCollapsibleStateOnAll(folder, TreeItemCollapsibleState.Expanded)));
this._disposables.push(commands.registerCommand('githd.viewFileHistoryFromTree',
(fileItem: CommittedFileItem) => model.setHistoryViewContext({ repo: this._context.repo, specifiedPath: fileItem.file.fileUri })));
this._disposables.push(commands.registerCommand('githd.viewFolderHistoryFromTree',
(folder: FolderItem) => model.setHistoryViewContext({
repo: this._context.repo,
specifiedPath: Uri.file(path.join(this._context.repo.root, folder.gitRelativePath))
})));
this._disposables.push(this._onDidChange);
model.onDidChangeFilesViewContext(context => {
this._context = context;
this._update();
}, null, this._disposables);
this._context = model.filesViewContext;
this._withFolder = model.configuration.withFolder;
this._update();
}
readonly onDidChangeTreeData: Event<CommittedTreeItem> = this._onDidChange.event;
dispose(): void {
this._disposables.forEach(d => d.dispose());
}
getTreeItem(element: CommittedTreeItem): CommittedTreeItem {
return element;
}
getChildren(element?: CommittedTreeItem): CommittedTreeItem[] {
if (!element) {
return this._treeRoot;
}
let folder = element as FolderItem;
if (folder) {
return [].concat(folder.subFolders, folder.infoItem, folder.files);
}
return [];
}
getParent(element: CommittedTreeItem): CommittedTreeItem {
return element.parent;
}
private get commitOrStashString(): string {
return this._context.isStash ? 'Stash' : 'Commit';
}
private async _update(): Promise<void> {
this._treeRoot = [];
if (!this._context) {
return;
}
const leftRef: string = this._context.leftRef;
const rightRef: string = this._context.rightRef;
const specifiedPath: Uri = this._context.specifiedPath;
const lineInfo: string = this._context.focusedLineInfo;
if (!rightRef) {
this._onDidChange.fire();
return;
}
const committedFiles: GitCommittedFile[] = await this._gitService.getCommittedFiles(this._context.repo, leftRef, rightRef, this._context.isStash);
if (!leftRef) {
await this._buildCommitInfo(rightRef);
}
if (!leftRef && !specifiedPath) {
this._buildCommitTree(committedFiles, rightRef);
} else if (leftRef && !specifiedPath) {
this._buildDiffBranchTree(committedFiles, leftRef, rightRef);
} else if (!leftRef && specifiedPath) {
await this._buildPathSpecifiedCommitTree(committedFiles, specifiedPath, lineInfo, rightRef);
} else {
await this._buildPathSpecifiedDiffBranchTree(committedFiles, this._context);
}
this._onDidChange.fire();
}
private async _buildCommitInfo(ref: string): Promise<void> {
await this._treeRoot.push(new InfoItem(await this._gitService.getCommitDetails(this._context.repo, ref, this._context.isStash),
`${this.commitOrStashString} Info`));
}
private _buildCommitTree(files: GitCommittedFile[], ref: string): void {
this._buildCommitFolder(`${this.commitOrStashString} ${ref} \u00a0 (${files.length} files changed)`, files);
}
private _buildDiffBranchTree(files: GitCommittedFile[], leftRef: string, rightRef): void {
this._buildCommitFolder(`Diffs between ${leftRef} and ${rightRef} \u00a0 (${files.length} files)`, files);
}
private async _buildPathSpecifiedCommitTree(files: GitCommittedFile[], specifiedPath: Uri, lineInfo:string, ref: string): Promise<void> {
await this._buildFocusFolder('Focus', files, specifiedPath, lineInfo);
this._buildCommitTree(files, ref);
}
private async _buildPathSpecifiedDiffBranchTree(files: GitCommittedFile[], context: FilesViewContext): Promise<void> {
await this._buildFocusFolder(`${context.leftRef} .. ${context.rightRef}`, files, context.specifiedPath);
}
private _buildCommitFolder(label: string, committedFiles: GitCommittedFile[]): void {
let folder = new FolderItem(null, '', label, rootFolderIcon);
buildFileTree(folder, committedFiles, this._withFolder);
this._treeRoot.push(folder);
}
private async _buildFocusFolder(label: string, committedFiles: GitCommittedFile[], specifiedPath: Uri, lineInfo?: string): Promise<void> {
let folder = new FolderItem(null, '', label, rootFolderIcon);
const relativePath = await this._gitService.getGitRelativePath(specifiedPath);
if (fs.lstatSync(specifiedPath.fsPath).isFile()) {
if (lineInfo) {
folder.infoItem = new InfoItem(lineInfo, 'line diff');
}
let file = committedFiles.find(value => { return value.gitRelativePath === relativePath; });
if (file) {
folder.files.push(createCommittedFileItem(folder, file));
}
} else {
let focus: GitCommittedFile[] = [];
committedFiles.forEach(file => {
if (file.gitRelativePath.search(relativePath) === 0) {
focus.push(file);
}
});
buildFileTree(folder, focus, this._withFolder);
}
if (folder.files.length + folder.subFolders.length > 0 || folder.infoItem) {
this._treeRoot.push(folder);
}
}
private _showFilesWithFolder(parent: FolderItem): void {
if (!parent) {
this._withFolder = true;
this._update();
} else {
buildFilesWithFolder(parent);
this._onDidChange.fire(parent);
}
}
private _showFilesWithoutFolder(parent: FolderItem): void {
if (!parent) {
this._withFolder = false;
this._update();
} else {
parent.subFolders.forEach(folder => buildFilesWithoutFolder(parent, folder));
parent.subFolders = [];
this._onDidChange.fire(parent);
}
}
private _setCollapsibleStateOnAll(folder: FolderItem, state: TreeItemCollapsibleState): void {
let parent: FolderItem;
if (!folder) {
this._treeRoot.forEach(sub => {
if (sub instanceof FolderItem) {
setCollapsibleStateOnAll(sub, state);
}
});
} else {
parent = folder.parent;
folder.collapsibleState = state;
folder.subFolders.forEach(sub => setCollapsibleStateOnAll(sub, state));
}
// HACK: workaround of vscode regression.
// seems vscode people are planing to add new API https://github.com/Microsoft/vscode/issues/55879
if (parent) {
const temp = parent.subFolders;
parent.subFolders = [];
this._onDidChange.fire(parent);
setTimeout(() => {
parent.subFolders = temp;
this._onDidChange.fire(parent);
}, 250);
} else {
const root = this._treeRoot;
this._treeRoot = null;
this._onDidChange.fire();
setTimeout(() => {
this._treeRoot = root;
this._onDidChange.fire();
}, 250);
}
}
} | the_stack |
import * as path from "path";
import * as vscode from "vscode";
import { Constants } from "../common/constants";
import { Utility } from "../common/utility";
import { DigitalTwinConstants } from "./digitalTwinConstants";
import { IntelliSenseUtility } from "./intelliSenseUtility";
/**
* Class node of DigitalTwin graph
*/
export interface ClassNode {
id: string;
label?: string;
isAbstract?: boolean;
children?: ClassNode[];
properties?: PropertyNode[];
enums?: string[];
constraint?: ConstraintNode;
version?: VersionNode;
}
/**
* Property node of DigitalTwin graph
*/
export interface PropertyNode {
id: string;
label?: string;
isArray?: boolean;
comment?: string;
range?: ClassNode[];
constraint?: ConstraintNode;
version?: VersionNode;
}
/**
* Constraint node of DigitalTwin graph
*/
export interface ConstraintNode {
minItems?: number;
maxItems?: number;
minLength?: number;
maxLength?: number;
pattern?: string;
required?: string[];
}
/**
* Version node of DigitalTwin graph
*/
export interface VersionNode {
includeSince?: number;
excludeSince?: number;
}
/**
* Context node of DigitalTwin graph
*/
interface ContextNode {
name: string;
container: ContainerType;
}
/**
* Value schema definition for DigitalTwin graph
*/
export enum ValueSchema {
String = "http://www.w3.org/2001/XMLSchema#string",
Int = "http://www.w3.org/2001/XMLSchema#int",
Boolean = "http://www.w3.org/2001/XMLSchema#boolean"
}
/**
* Node type definition for DigitalTwin graph
*/
enum NodeType {
Class = "http://www.w3.org/2000/01/rdf-schema#Class",
Property = "http://www.w3.org/1999/02/22-rdf-syntax-ns#Property"
}
/**
* Edge type definition for DigitalTwin graph
*/
enum EdgeType {
Type = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
Range = "http://www.w3.org/2000/01/rdf-schema#range",
Label = "http://www.w3.org/2000/01/rdf-schema#label",
Domain = "http://www.w3.org/2000/01/rdf-schema#domain",
SubClassOf = "http://www.w3.org/2000/01/rdf-schema#subClassOf",
Comment = "http://www.w3.org/2000/01/rdf-schema#comment"
}
/**
* Container type of JSON-LD
*/
enum ContainerType {
None,
Array,
Language
}
/**
* DigitalTwin graph
*/
export class DigitalTwinGraph {
/**
* get singleton instance of DigitalTwin graph
* @param context extension context
*/
static async getInstance(context: vscode.ExtensionContext): Promise<DigitalTwinGraph> {
if (!DigitalTwinGraph.instance) {
DigitalTwinGraph.instance = new DigitalTwinGraph();
await DigitalTwinGraph.instance.init(context);
}
return DigitalTwinGraph.instance;
}
private static instance: DigitalTwinGraph;
/**
* check if json object is a valid constraint node
* @param object object data
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private static isConstraintNode(object: any): object is ConstraintNode {
return (
object.minItems || object.maxItems || object.minLength || object.maxLength || object.pattern || object.required
);
}
/**
* check if json object is a valid edge
* @param object object data
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private static isValidEdge(object: any): boolean {
return object.SourceNode && object.TargetNode && object.Label;
}
/**
* resolve container type
* @param object object data
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private static resolveContainerType(object: any): ContainerType {
const container = object[DigitalTwinConstants.CONTAINER];
if (!container || typeof container !== "string") {
return ContainerType.None;
}
switch (container) {
case DigitalTwinConstants.LIST:
case DigitalTwinConstants.SET:
return ContainerType.Array;
case DigitalTwinConstants.LANGUAGE:
return ContainerType.Language;
default:
return ContainerType.None;
}
}
/**
* resolve definition
* @param context extension context
* @param fileName file name
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private static async resolveDefinition(context: vscode.ExtensionContext, fileName: string): Promise<any> {
const filePath: string = context.asAbsolutePath(
path.join(Constants.RESOURCE_FOLDER, Constants.DEFINITION_FOLDER, fileName)
);
return await Utility.getJsonContent(filePath);
}
private classNodes: Map<string, ClassNode>;
private propertyNodes: Map<string, PropertyNode>;
private contextNodes: Map<string, ContextNode>;
private constraintNodes: Map<string, ConstraintNode>;
private reversedIndex: Map<string, string>;
private contextVersions: Map<string, number>;
private vocabulary: string;
private constructor() {
this.classNodes = new Map<string, ClassNode>();
this.propertyNodes = new Map<string, PropertyNode>();
this.contextNodes = new Map<string, ContextNode>();
this.constraintNodes = new Map<string, ConstraintNode>();
this.reversedIndex = new Map<string, string>();
this.contextVersions = new Map<string, number>();
this.vocabulary = Constants.EMPTY_STRING;
}
/**
* check if DigitalTwin graph has been initialized
*/
initialized(): boolean {
return this.vocabulary !== Constants.EMPTY_STRING;
}
/**
* get property node by name
* @param name name
*/
getPropertyNode(name: string): PropertyNode | undefined {
const id: string = this.reversedIndex.get(name) || name;
return this.propertyNodes.get(id);
}
/**
* get class node by name
* @param name name
*/
getClassNode(name: string): ClassNode | undefined {
const id: string = this.reversedIndex.get(name) || this.getId(name);
return this.classNodes.get(id);
}
/**
* get version from context value
* @param context DigitalTwin context
*/
getVersion(context: string): number {
return this.contextVersions.get(context) || 0;
}
/**
* inititalize DigitalTwin graph
* @param context extension context
*/
private async init(context: vscode.ExtensionContext): Promise<void> {
let contextJson;
let constraintJson;
let graphJson;
// load definition file
try {
contextJson = await DigitalTwinGraph.resolveDefinition(context, Constants.CONTEXT_FILE_NAME);
constraintJson = await DigitalTwinGraph.resolveDefinition(context, Constants.CONSTRAINT_FILE_NAME);
graphJson = await DigitalTwinGraph.resolveDefinition(context, Constants.GRAPH_FILE_NAME);
} catch (error) {
return;
}
// build graph by definitions
this.buildContext(contextJson);
this.buildConstraint(constraintJson);
this.buildGraph(graphJson);
}
/**
* get node id of DigitalTwin graph
* @param name name
*/
private getId(name: string): string {
return this.vocabulary + name;
}
/**
* build context nodes by id and reversed index
* @param contextJson json object of context definition
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private buildContext(contextJson: any): void {
let id: string;
const context = contextJson[DigitalTwinConstants.CONTEXT];
this.vocabulary = context[DigitalTwinConstants.VOCABULARY] as string;
for (const key in context) {
if (IntelliSenseUtility.isReservedName(key)) {
continue;
}
const value = context[key];
if (typeof value === "string") {
id = this.getId(value);
this.contextNodes.set(id, { name: key, container: ContainerType.None });
} else {
const containerType: ContainerType = DigitalTwinGraph.resolveContainerType(value);
id = this.getId(value[DigitalTwinConstants.ID] as string);
this.contextNodes.set(id, { name: key, container: containerType });
}
this.reversedIndex.set(key, id);
}
}
/**
* build constraint nodes by name
* @param constraintJson json object of constraint definition
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private buildConstraint(constraintJson: any): void {
for (const key in constraintJson) {
if (DigitalTwinGraph.isConstraintNode(constraintJson[key])) {
this.constraintNodes.set(key, constraintJson[key]);
} else if (key === DigitalTwinConstants.CONTEXT) {
const versions = constraintJson[key];
// vKey starts with "v", so use slice to get version number
for (const vKey in versions) {
this.contextVersions.set(versions[vKey] as string, parseInt(vKey.slice(1)));
}
}
}
}
/**
* build DigitalTwin graph by the definitions of context, constraint and graph
* @param graphJson json object of graph definition
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private buildGraph(graphJson: any): void {
for (const edge of graphJson.Edges) {
if (DigitalTwinGraph.isValidEdge(edge)) {
this.handleEdge(edge);
}
}
this.adjustNode();
this.expandProperties();
this.buildEntryNode();
}
/**
* handle data of edge
* @param edge edge data
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private handleEdge(edge: any): void {
switch (edge.Label) {
case EdgeType.Type:
this.handleEdgeOfType(edge);
break;
case EdgeType.Label:
this.handleEdgeOfLabel(edge);
break;
case EdgeType.Domain:
this.handleEdgeOfDomain(edge);
break;
case EdgeType.Range:
this.handleEdgeOfRange(edge);
break;
case EdgeType.SubClassOf:
this.handleEdgeOfSubClassOf(edge);
break;
case EdgeType.Comment:
this.handleEdgeOfComment(edge);
break;
default:
}
}
/**
* handle data of Type edge
* 1. create class/property node, set label and constraint
* 2. add enum value to enum node
* @param edge edge data
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private handleEdgeOfType(edge: any): void {
const id: string = edge.SourceNode.Id as string;
const type: string = edge.TargetNode.Id as string;
switch (type) {
case NodeType.Class:
this.ensureClassNode(id);
break;
case NodeType.Property:
this.ensurePropertyNode(id);
break;
default: {
// mark target class as enum node
const contextNode: ContextNode | undefined = this.contextNodes.get(id);
const enumValue: string = contextNode ? contextNode.name : id;
const enumNode: ClassNode = this.ensureClassNode(type);
if (!enumNode.enums) {
enumNode.enums = [];
}
enumNode.enums.push(enumValue);
}
}
}
/**
* handle data of Label edge
* 1. assume Type edge is handled before Label edge
* 2. set label and constraint if not defined
* @param edge edge data
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private handleEdgeOfLabel(edge: any): void {
const id: string = edge.SourceNode.Id as string;
const label: string = edge.TargetNode.Value as string;
const propertyNode: PropertyNode | undefined = this.propertyNodes.get(id);
// skip property node since value has been set in Type edge
if (propertyNode) {
return;
}
const classNode: ClassNode = this.ensureClassNode(id);
if (!classNode.label) {
classNode.label = label;
const constraintNode: ConstraintNode | undefined = this.constraintNodes.get(label);
if (constraintNode) {
classNode.constraint = constraintNode;
}
}
}
/**
* handle data of Domain edge
* 1. add property to class node
* @param edge edge data
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private handleEdgeOfDomain(edge: any): void {
const id: string = edge.SourceNode.Id as string;
const classId: string = edge.TargetNode.Id as string;
const propertyNode: PropertyNode = this.ensurePropertyNode(id);
const classNode: ClassNode = this.ensureClassNode(classId);
if (!classNode.properties) {
classNode.properties = [];
}
classNode.properties.push(propertyNode);
}
/**
* handle data of Range edge
* 1. add range to property node
* @param edge edge data
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private handleEdgeOfRange(edge: any): void {
const id: string = edge.SourceNode.Id as string;
const classId: string = edge.TargetNode.Id as string;
const propertyNode: PropertyNode = this.ensurePropertyNode(id);
const classNode: ClassNode = this.ensureClassNode(classId);
if (!propertyNode.range) {
propertyNode.range = [];
}
propertyNode.range.push(classNode);
}
/**
* handle data of SubClassOf edge
* 1. add children to base class node
* @param edge edge data
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private handleEdgeOfSubClassOf(edge: any): void {
const id: string = edge.SourceNode.Id as string;
const baseId: string = edge.TargetNode.Id as string;
const classNode: ClassNode = this.ensureClassNode(id);
const baseClassNode: ClassNode = this.ensureClassNode(baseId);
if (!baseClassNode.children) {
baseClassNode.children = [];
}
baseClassNode.children.push(classNode);
}
/**
* handle data of Comment edge
* 1. set comment of property node
* @param edge edge data
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private handleEdgeOfComment(edge: any): void {
const id: string = edge.SourceNode.Id as string;
const comment: string = edge.TargetNode.Value as string;
const propertyNode: PropertyNode | undefined = this.propertyNodes.get(id);
if (propertyNode) {
propertyNode.comment = comment;
}
}
/**
* ensure class node exist, create if not found
* @param id node id
*/
private ensureClassNode(id: string): ClassNode {
let classNode: ClassNode | undefined = this.classNodes.get(id);
if (!classNode) {
classNode = { id };
const contextNode: ContextNode | undefined = this.contextNodes.get(id);
if (contextNode) {
classNode.label = contextNode.name;
const constraintNode: ConstraintNode | undefined = this.constraintNodes.get(contextNode.name);
if (constraintNode) {
classNode.constraint = constraintNode;
}
}
this.classNodes.set(id, classNode);
}
return classNode;
}
/**
* ensure property node exist, create if not found
* @param id node id
*/
private ensurePropertyNode(id: string): PropertyNode {
let propertyNode: PropertyNode | undefined = this.propertyNodes.get(id);
if (!propertyNode) {
propertyNode = { id };
const contextNode: ContextNode | undefined = this.contextNodes.get(id);
if (contextNode) {
propertyNode.label = contextNode.name;
propertyNode.isArray = contextNode.container === ContainerType.Array;
// handle language node
if (contextNode.container === ContainerType.Language) {
const languageNode: ClassNode = this.ensureClassNode(DigitalTwinConstants.LANGUAGE);
languageNode.label = DigitalTwinConstants.LANGUAGE;
propertyNode.range = [languageNode];
}
const constraintNode: ConstraintNode | undefined = this.constraintNodes.get(contextNode.name);
if (constraintNode) {
propertyNode.constraint = constraintNode;
}
}
this.propertyNodes.set(id, propertyNode);
}
return propertyNode;
}
/**
* adjust node to achieve special definitions
*/
private adjustNode(): void {
// build reserved property
const stringNode: ClassNode = this.ensureClassNode(ValueSchema.String);
this.buildReservedProperty(DigitalTwinConstants.ID, stringNode);
// mark abstract class
this.markAbstractClass(DigitalTwinConstants.SCHEMA_NODE);
this.markAbstractClass(DigitalTwinConstants.UNIT_NODE);
// handle interfaceSchema
this.handleInterfaceSchema(stringNode);
}
/**
* build reserved property
* @param id node id
* @param classNode class node of property range
*/
private buildReservedProperty(id: string, classNode: ClassNode): void {
const propertyNode: PropertyNode = { id, range: [classNode] };
const constraintNode: ConstraintNode | undefined = this.constraintNodes.get(id);
if (constraintNode) {
propertyNode.constraint = constraintNode;
}
this.propertyNodes.set(id, propertyNode);
}
/**
* mark class node as abstract class
* @param name class node name
*/
private markAbstractClass(name: string): void {
const classNode: ClassNode | undefined = this.classNodes.get(this.getId(name));
if (classNode) {
classNode.isAbstract = true;
}
}
/**
* update label and range of interfaceSchema property
*/
private handleInterfaceSchema(classNode: ClassNode): void {
const propertyNode: PropertyNode | undefined = this.propertyNodes.get(
this.getId(DigitalTwinConstants.INTERFACE_SCHEMA_NODE)
);
if (propertyNode) {
propertyNode.label = DigitalTwinConstants.SCHEMA;
if (propertyNode.range) {
propertyNode.range.push(classNode);
propertyNode.constraint = this.constraintNodes.get(DigitalTwinConstants.ID);
}
}
}
/**
* expand properties from base class node
*/
private expandProperties(): void {
let classNode: ClassNode | undefined = this.classNodes.get(this.getId(DigitalTwinConstants.BASE_CLASS));
if (!classNode) {
return;
}
const queue: ClassNode[] = [];
while (classNode) {
if (classNode.children) {
for (const child of classNode.children) {
// skip enum node
if (child.enums) {
continue;
}
if (classNode.properties) {
if (!child.properties) {
child.properties = [];
}
child.properties.push(...classNode.properties);
}
queue.push(child);
}
}
classNode = queue.shift();
}
}
/**
* build entry node of DigitalTwin graph
*/
private buildEntryNode(): void {
const interfaceNode: ClassNode | undefined = this.classNodes.get(this.getId(DigitalTwinConstants.INTERFACE_NODE));
const capabilityModelNode: ClassNode | undefined = this.classNodes.get(
this.getId(DigitalTwinConstants.CAPABILITY_MODEL_NODE)
);
if (interfaceNode && capabilityModelNode) {
const entryNode: PropertyNode = {
id: DigitalTwinConstants.ENTRY_NODE,
range: [interfaceNode, capabilityModelNode]
};
this.propertyNodes.set(entryNode.id, entryNode);
}
}
} | the_stack |
import {Issue} from './issue';
import {Logger} from './loggers/logger';
import {LoggerService} from '../services/logger.service';
interface IGroupValue {
name: string;
count: number;
}
export class Statistics {
private readonly _logger: Logger = new Logger();
processedIssuesCount = 0;
processedPullRequestsCount = 0;
staleIssuesCount = 0;
stalePullRequestsCount = 0;
undoStaleIssuesCount = 0;
undoStalePullRequestsCount = 0;
operationsCount = 0;
closedIssuesCount = 0;
closedPullRequestsCount = 0;
deletedIssuesLabelsCount = 0;
deletedPullRequestsLabelsCount = 0;
deletedCloseIssuesLabelsCount = 0;
deletedClosePullRequestsLabelsCount = 0;
deletedBranchesCount = 0;
addedIssuesLabelsCount = 0;
addedPullRequestsLabelsCount = 0;
addedIssuesCommentsCount = 0;
addedPullRequestsCommentsCount = 0;
fetchedItemsCount = 0;
fetchedItemsEventsCount = 0;
fetchedItemsCommentsCount = 0;
fetchedPullRequestsCount = 0;
incrementProcessedItemsCount(
issue: Readonly<Issue>,
increment: Readonly<number> = 1
): Statistics {
if (issue.isPullRequest) {
return this._incrementProcessedPullRequestsCount(increment);
}
return this._incrementProcessedIssuesCount(increment);
}
incrementStaleItemsCount(
issue: Readonly<Issue>,
increment: Readonly<number> = 1
): Statistics {
if (issue.isPullRequest) {
return this._incrementStalePullRequestsCount(increment);
}
return this._incrementStaleIssuesCount(increment);
}
incrementUndoStaleItemsCount(
issue: Readonly<Issue>,
increment: Readonly<number> = 1
): Statistics {
if (issue.isPullRequest) {
return this._incrementUndoStalePullRequestsCount(increment);
}
return this._incrementUndoStaleIssuesCount(increment);
}
setOperationsCount(operationsCount: Readonly<number>): Statistics {
this.operationsCount = operationsCount;
return this;
}
incrementClosedItemsCount(
issue: Readonly<Issue>,
increment: Readonly<number> = 1
): Statistics {
if (issue.isPullRequest) {
return this._incrementClosedPullRequestsCount(increment);
}
return this._incrementClosedIssuesCount(increment);
}
incrementDeletedItemsLabelsCount(
issue: Readonly<Issue>,
increment: Readonly<number> = 1
): Statistics {
if (issue.isPullRequest) {
return this._incrementDeletedPullRequestsLabelsCount(increment);
}
return this._incrementDeletedIssuesLabelsCount(increment);
}
incrementDeletedCloseItemsLabelsCount(
issue: Readonly<Issue>,
increment: Readonly<number> = 1
): Statistics {
if (issue.isPullRequest) {
return this._incrementDeletedClosePullRequestsLabelsCount(increment);
}
return this._incrementDeletedCloseIssuesLabelsCount(increment);
}
incrementDeletedBranchesCount(increment: Readonly<number> = 1): Statistics {
this.deletedBranchesCount += increment;
return this;
}
incrementAddedItemsLabel(
issue: Readonly<Issue>,
increment: Readonly<number> = 1
): Statistics {
if (issue.isPullRequest) {
return this._incrementAddedPullRequestsLabel(increment);
}
return this._incrementAddedIssuesLabel(increment);
}
incrementAddedItemsComment(
issue: Readonly<Issue>,
increment: Readonly<number> = 1
): Statistics {
if (issue.isPullRequest) {
return this._incrementAddedPullRequestsComment(increment);
}
return this._incrementAddedIssuesComment(increment);
}
incrementFetchedItemsCount(increment: Readonly<number> = 1): Statistics {
this.fetchedItemsCount += increment;
return this;
}
incrementFetchedItemsEventsCount(
increment: Readonly<number> = 1
): Statistics {
this.fetchedItemsEventsCount += increment;
return this;
}
incrementFetchedItemsCommentsCount(
increment: Readonly<number> = 1
): Statistics {
this.fetchedItemsCommentsCount += increment;
return this;
}
incrementFetchedPullRequestsCount(
increment: Readonly<number> = 1
): Statistics {
this.fetchedPullRequestsCount += increment;
return this;
}
logStats(): Statistics {
this._logger.info(LoggerService.yellow(LoggerService.bold(`Statistics:`)));
this._logProcessedIssuesAndPullRequestsCount();
this._logStaleIssuesAndPullRequestsCount();
this._logUndoStaleIssuesAndPullRequestsCount();
this._logClosedIssuesAndPullRequestsCount();
this._logDeletedIssuesAndPullRequestsLabelsCount();
this._logDeletedCloseIssuesAndPullRequestsLabelsCount();
this._logDeletedBranchesCount();
this._logAddedIssuesAndPullRequestsLabelsCount();
this._logAddedIssuesAndPullRequestsCommentsCount();
this._logFetchedItemsCount();
this._logFetchedItemsEventsCount();
this._logFetchedItemsCommentsCount();
this._logFetchedPullRequestsCount();
this._logOperationsCount();
return this;
}
private _incrementProcessedIssuesCount(
increment: Readonly<number> = 1
): Statistics {
this.processedIssuesCount += increment;
return this;
}
private _incrementProcessedPullRequestsCount(
increment: Readonly<number> = 1
): Statistics {
this.processedPullRequestsCount += increment;
return this;
}
private _incrementStaleIssuesCount(
increment: Readonly<number> = 1
): Statistics {
this.staleIssuesCount += increment;
return this;
}
private _incrementStalePullRequestsCount(
increment: Readonly<number> = 1
): Statistics {
this.stalePullRequestsCount += increment;
return this;
}
private _incrementUndoStaleIssuesCount(
increment: Readonly<number> = 1
): Statistics {
this.undoStaleIssuesCount += increment;
return this;
}
private _incrementUndoStalePullRequestsCount(
increment: Readonly<number> = 1
): Statistics {
this.undoStalePullRequestsCount += increment;
return this;
}
private _incrementClosedIssuesCount(
increment: Readonly<number> = 1
): Statistics {
this.closedIssuesCount += increment;
return this;
}
private _incrementClosedPullRequestsCount(
increment: Readonly<number> = 1
): Statistics {
this.closedPullRequestsCount += increment;
return this;
}
private _incrementDeletedIssuesLabelsCount(
increment: Readonly<number> = 1
): Statistics {
this.deletedIssuesLabelsCount += increment;
return this;
}
private _incrementDeletedPullRequestsLabelsCount(
increment: Readonly<number> = 1
): Statistics {
this.deletedPullRequestsLabelsCount += increment;
return this;
}
private _incrementDeletedCloseIssuesLabelsCount(
increment: Readonly<number> = 1
): Statistics {
this.deletedCloseIssuesLabelsCount += increment;
return this;
}
private _incrementDeletedClosePullRequestsLabelsCount(
increment: Readonly<number> = 1
): Statistics {
this.deletedClosePullRequestsLabelsCount += increment;
return this;
}
private _incrementAddedIssuesLabel(
increment: Readonly<number> = 1
): Statistics {
this.addedIssuesLabelsCount += increment;
return this;
}
private _incrementAddedPullRequestsLabel(
increment: Readonly<number> = 1
): Statistics {
this.addedPullRequestsLabelsCount += increment;
return this;
}
private _incrementAddedIssuesComment(
increment: Readonly<number> = 1
): Statistics {
this.addedIssuesCommentsCount += increment;
return this;
}
private _incrementAddedPullRequestsComment(
increment: Readonly<number> = 1
): Statistics {
this.addedPullRequestsCommentsCount += increment;
return this;
}
private _logProcessedIssuesAndPullRequestsCount(): void {
this._logGroup('Processed items', [
{
name: 'Processed issues',
count: this.processedIssuesCount
},
{
name: 'Processed PRs',
count: this.processedPullRequestsCount
}
]);
}
private _logStaleIssuesAndPullRequestsCount(): void {
this._logGroup('New stale items', [
{
name: 'New stale issues',
count: this.staleIssuesCount
},
{
name: 'New stale PRs',
count: this.stalePullRequestsCount
}
]);
}
private _logUndoStaleIssuesAndPullRequestsCount(): void {
this._logGroup('No longer stale items', [
{
name: 'No longer stale issues',
count: this.undoStaleIssuesCount
},
{
name: 'No longer stale PRs',
count: this.undoStalePullRequestsCount
}
]);
}
private _logClosedIssuesAndPullRequestsCount(): void {
this._logGroup('Closed items', [
{
name: 'Closed issues',
count: this.closedIssuesCount
},
{
name: 'Closed PRs',
count: this.closedPullRequestsCount
}
]);
}
private _logDeletedIssuesAndPullRequestsLabelsCount(): void {
this._logGroup('Deleted items labels', [
{
name: 'Deleted issues labels',
count: this.deletedIssuesLabelsCount
},
{
name: 'Deleted PRs labels',
count: this.deletedPullRequestsLabelsCount
}
]);
}
private _logDeletedCloseIssuesAndPullRequestsLabelsCount(): void {
this._logGroup('Deleted close items labels', [
{
name: 'Deleted close issues labels',
count: this.deletedCloseIssuesLabelsCount
},
{
name: 'Deleted close PRs labels',
count: this.deletedClosePullRequestsLabelsCount
}
]);
}
private _logDeletedBranchesCount(): void {
this._logCount('Deleted branches', this.deletedBranchesCount);
}
private _logAddedIssuesAndPullRequestsLabelsCount(): void {
this._logGroup('Added items labels', [
{
name: 'Added issues labels',
count: this.addedIssuesLabelsCount
},
{
name: 'Added PRs labels',
count: this.addedPullRequestsLabelsCount
}
]);
}
private _logAddedIssuesAndPullRequestsCommentsCount(): void {
this._logGroup('Added items comments', [
{
name: 'Added issues comments',
count: this.addedIssuesCommentsCount
},
{
name: 'Added PRs comments',
count: this.addedPullRequestsCommentsCount
}
]);
}
private _logFetchedItemsCount(): void {
this._logCount('Fetched items', this.fetchedItemsCount);
}
private _logFetchedItemsEventsCount(): void {
this._logCount('Fetched items events', this.fetchedItemsEventsCount);
}
private _logFetchedItemsCommentsCount(): void {
this._logCount('Fetched items comments', this.fetchedItemsCommentsCount);
}
private _logFetchedPullRequestsCount(): void {
this._logCount('Fetched pull requests', this.fetchedPullRequestsCount);
}
private _logOperationsCount(): void {
this._logCount('Operations performed', this.operationsCount);
}
private _logCount(name: Readonly<string>, count: Readonly<number>): void {
if (count > 0) {
this._logger.info(`${name}:`, LoggerService.cyan(count));
}
}
private _logGroup(groupName: Readonly<string>, values: IGroupValue[]): void {
if (this._isGroupValuesPartiallySet(values)) {
this._logCount(groupName, this._getGroupValuesTotalCount(values));
this._logGroupValues(values);
} else {
// Only one value will be display
for (const value of values) {
this._logCount(value.name, value.count);
}
}
}
/**
* @private
* @description
* If there is a least two elements with a valid count then it's partially set
* Useful to defined if we should display the values as a group or not
*
* @param {IGroupValue[]} values The list of group values to check
*/
private _isGroupValuesPartiallySet(values: IGroupValue[]): boolean {
return (
values
.map((value: Readonly<IGroupValue>): boolean => {
return value.count > 0;
})
.filter((isSet: Readonly<boolean>): boolean => isSet).length >= 2
);
}
private _getGroupValuesTotalCount(values: IGroupValue[]): number {
return values.reduce(
(count: Readonly<number>, value: Readonly<IGroupValue>): number => {
return count + value.count;
},
0
);
}
private _getAllGroupValuesSet(values: IGroupValue[]): IGroupValue[] {
return values.filter((value: Readonly<IGroupValue>): boolean => {
return value.count > 0;
});
}
private _logGroupValues(values: IGroupValue[]): void {
const onlyValuesSet: IGroupValue[] = this._getAllGroupValuesSet(values);
const longestValue: number = this._getLongestGroupValue(onlyValuesSet);
for (const [index, value] of onlyValuesSet.entries()) {
const prefix = index === onlyValuesSet.length - 1 ? '└──' : '├──';
this._logCount(
`${LoggerService.white(prefix)} ${value.name.padEnd(
longestValue,
' '
)}`,
value.count
);
}
}
private _getLongestGroupValue(values: IGroupValue[]): number {
return values.reduce(
(
longestValue: Readonly<number>,
value: Readonly<IGroupValue>
): number => {
return value.name.length > longestValue
? value.name.length
: longestValue;
},
0
);
}
} | the_stack |
import * as React from "react";
import { sp } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/items";
import { Label } from "@fluentui/react/lib/Label";
import Media from "react-bootstrap/Media";
import Row from "react-bootstrap/Row";
import Col from "react-bootstrap/Col";
import "bootstrap/dist/css/bootstrap.min.css";
import styles from "../scss/TOTLandingPage.module.scss";
import siteconfig from "../config/siteconfig.json";
import commonServices from "../Common/CommonServices";
import * as stringsConstants from "../constants/strings";
import TOTLeaderBoard from "./TOTLeaderBoard";
import TOTMyDashboard from "./TOTMyDashboard";
import TOTCreateTournament from "./TOTCreateTournament";
import TOTEnableTournament from "./TOTEnableTournament";
import Navbar from "react-bootstrap/Navbar";
export interface ITOTLandingPageProps {
context?: any;
siteUrl: string;
isTOTEnabled: boolean;
}
interface ITOTLandingPageState {
showSuccess: Boolean;
showError: Boolean;
errorMessage: string;
dashboard: boolean;
siteUrl: string;
siteName: string;
inclusionpath: string;
leaderBoard: boolean;
createTournament: boolean;
manageTournament: boolean;
isAdmin: boolean;
isShowLoader: boolean;
activeTournamentExists: boolean;
}
let commonService: commonServices;
class TOTLandingPage extends React.Component<
ITOTLandingPageProps,
ITOTLandingPageState
> {
constructor(props: ITOTLandingPageProps, state: ITOTLandingPageState) {
super(props);
this.state = {
showSuccess: false,
showError: false,
errorMessage: "",
dashboard: false,
siteUrl: "",
siteName: siteconfig.sitename,
inclusionpath: siteconfig.inclusionPath,
createTournament: false,
manageTournament: false,
leaderBoard: false,
isAdmin: false,
isShowLoader: false,
activeTournamentExists: false
};
commonService = new commonServices(this.props.context, this.props.siteUrl);
this.redirectTotHome = this.redirectTotHome.bind(this);
}
public componentDidMount() {
this.initialChecks();
}
//verify isTOTEnabled props(from clb home), if already enabled then check admin role and active tournaments
//else run provisioning code
private async initialChecks() {
try {
this.setState({
isShowLoader: true,
});
//if isTOTEnabled is true then just check for role else run provisioning to add missing lists and fields
if (this.props.isTOTEnabled == true) {
this.checkUserRole();
this.checkActiveTournament();
}
else {
//verify tot lists/fields are present, create missing lists/fields
await this.provisionTOTListsAndFields().then((res) => {
//if provision of lists is completed then create lookup
if (res == "Success") {
this.createLookupField();
}
});
//get active tournament details, and dynamic text change for manage tournament link
this.checkActiveTournament();
}
}
catch (error) {
console.error("TOT_TOTLandingPage_componentDidMount_FailedToGetUserDetails \n", error);
this.setState({ showError: true, errorMessage: stringsConstants.TOTErrorMessage + "while getting user details. Below are the details: \n" + JSON.stringify(error), showSuccess: false });
}
}
//get active tournament details, and dynamic text change for manage tournament link
private async checkActiveTournament() {
let tournamentDetails = await commonService.getActiveTournamentDetails();
if (tournamentDetails.length == 0) {
//no active tournament
this.setState({ activeTournamentExists: false });
}
else {
//there is an active tournament
this.setState({ activeTournamentExists: true });
}
}
//Check current users's is admin from "ToT admin List" and set the UI components accordingly
private async checkUserRole() {
try {
let filterQuery: string =
"Title eq '" +
this.props.context.pageContext.user.email.toLowerCase() +
"'";
const listItem: any = await commonService.getItemsWithOnlyFilter(
stringsConstants.AdminList,
filterQuery
);
if (listItem.length != 0) {
this.setState({ isAdmin: true });
} else {
this.setState({ isAdmin: false });
}
this.setState({
isShowLoader: false,
});
} catch (error) {
console.error(
"TOT_TOTLandingPage_checkUserRole_FailedToValidateUserInAdminList \n",
error
);
this.setState({
showError: true,
errorMessage:
stringsConstants.TOTErrorMessage +
"while getting user from TOT Admin list. Below are the details: \n" +
JSON.stringify(error),
showSuccess: false,
});
}
}
//validate if the list column already exists
private async checkFieldExists(
spListTitle: string,
fieldsToCreate: string[]
) {
let totalFieldsToCreate = [];
try {
const filterFields = await sp.web.lists
.getByTitle(spListTitle)
.fields.filter("Hidden eq false and ReadOnlyField eq false")
.get();
for (let i = 0; i < fieldsToCreate.length; i++) {
// compare fields
const parser = new DOMParser();
const xml = parser.parseFromString(fieldsToCreate[i], "text/xml");
let fieldNameToCheck = xml
.querySelector("Field")
.getAttribute("DisplayName");
let fieldExists = filterFields.filter(
(e) => e.Title == fieldNameToCheck
);
if (fieldExists.length == 0) {
totalFieldsToCreate.push(fieldsToCreate[i]);
}
}
return totalFieldsToCreate;
} catch (error) {
console.error("TOT_TOTLandingPage_checkFieldExists \n", error);
this.setState({
showError: true,
errorMessage:
stringsConstants.TOTErrorMessage +
" while validating if field exists. Below are the details: \n" +
JSON.stringify(error),
showSuccess: false,
});
}
}
//add master data to list
private async createMasterData(
listname: string,
masterDataToAdd: any
): Promise<any> {
return new Promise<any>(async (resolve, reject) => {
try {
//get list context
const listContext = await sp.web.lists.getByTitle(listname);
const listItemCount = (await listContext.get()).ItemCount;
if (listItemCount == 0) {
let batchProcess = sp.web.createBatch();
const entityTypeFullName =
await listContext.getListItemEntityTypeFullName();
//update Title display name
switch (listname) {
case stringsConstants.AdminList:
//add master data
listContext.items
.inBatch(batchProcess)
.add(
{ Title: this.props.context.pageContext.user.email },
entityTypeFullName
);
await batchProcess.execute();
break;
case stringsConstants.ActionsMasterList:
//create master data
for (let j = 0; j < masterDataToAdd.length; j++) {
listContext.items.inBatch(batchProcess).add(
{
Title: masterDataToAdd[j]["Title"],
Category: masterDataToAdd[j]["Category"],
Description: masterDataToAdd[j]["Description"],
Points: masterDataToAdd[j]["Points"],
HelpURL: masterDataToAdd[j]["HelpURL"],
},
entityTypeFullName
);
}
await batchProcess.execute();
break;
case stringsConstants.TournamentsMasterList:
//add master data
for (let j = 0; j < masterDataToAdd.length; j++) {
listContext.items.inBatch(batchProcess).add(
{
Title: masterDataToAdd[j]["Title"],
Description: masterDataToAdd[j]["Description"],
Status: masterDataToAdd[j]["Status"],
},
entityTypeFullName
);
}
await batchProcess.execute();
break;
case stringsConstants.TournamentActionsMasterList:
//add master data
for (let j = 0; j < masterDataToAdd.length; j++) {
listContext.items.inBatch(batchProcess).add(
{
Title: masterDataToAdd[j]["Title"],
Category: masterDataToAdd[j]["Category"],
Action: masterDataToAdd[j]["Action"],
Description: masterDataToAdd[j]["Description"],
Points: masterDataToAdd[j]["Points"],
HelpURL: masterDataToAdd[j]["HelpURL"],
},
entityTypeFullName
);
}
await batchProcess.execute();
break;
default:
}
}
resolve("Success");
} catch (error) {
console.error("TOT_TOTLandingPage_createMasterData \n", error);
this.setState({
showError: true,
errorMessage:
stringsConstants.TOTErrorMessage +
" while adding master data to lists. Below are the details: \n" +
JSON.stringify(error),
showSuccess: false,
});
reject("Failed");
}
});
}
//Onclick of header Redirect to TOT landing page
public redirectTotHome() {
this.setState({
leaderBoard: false,
createTournament: false,
manageTournament: false,
dashboard: false,
});
this.checkActiveTournament();
}
//Create tournament name look up field in Digital badge assets lib
private async createLookupField() {
const listStructure: any = siteconfig.libraries;
//get lookup column
await sp.web.lists.getByTitle(stringsConstants.TournamentsMasterList).get()
.then(async (resp) => {
if (resp.Title != undefined) {
let digitalLib = sp.web.lists.getByTitle(
stringsConstants.DigitalBadgeLibrary
);
if (digitalLib != undefined) {
digitalLib.fields.getByInternalNameOrTitle("Tournament").get()
.then(() => {
let imageContext;
listStructure.forEach(async (element) => {
const masterDataDetails: string[] = element["masterData"];
for (let k = 0; k < masterDataDetails.length; k++) {
//check file exists before adding
let fileExists = await sp.web.getFileByServerRelativeUrl("/" + this.state.inclusionpath + "/"
+ this.state.siteName + "/" + stringsConstants.DigitalBadgeLibrary + "/" + masterDataDetails[k]['Name']).select('Exists').get()
.then((d) => d.Exists)
.catch(() => false);
if (!fileExists) {
//unable to resolve the dynamic path from siteconfig/dynamic var, hence the switch case
switch (masterDataDetails[k]['Title']) {
case "Shortcut Hero":
imageContext = fetch(require('../assets/images/Photo_Frame_Shortcuts.png'));
break;
case "Always on Mute":
imageContext = fetch(require('../assets/images/Photo_Frame_Mute.png'));
break;
case "Virtual Background":
imageContext = fetch(require('../assets/images/Photo_Frame_Mess.png'));
break;
case "Jokester":
imageContext = fetch(require('../assets/images/Photo_Frame_Jokes.png'));
break;
case "Double Booked":
imageContext = fetch(require('../assets/images/Photo_Frame_Booked.png'));
break;
}
//upload default badges
imageContext.then(res => res.blob()).then((blob) => {
sp.web.getFolderByServerRelativeUrl("/" + this.state.inclusionpath + "/"
+ this.state.siteName + "/" + stringsConstants.DigitalBadgeLibrary).files.add(masterDataDetails[k]['Name'], blob, true)
.then((res) => {
res.file.getItem().then(item => {
item.update({
Title: masterDataDetails[k]['Title'],
TournamentId: masterDataDetails[k]['TournamentName']
});
});
});
});
}
}//master data loop
});
}).catch(async () => {
//field doesn't exists, hence create it
await digitalLib.fields.addLookup("Tournament", resp.Id, "Title").then(() => {
let imageContext;
listStructure.forEach(async (element) => {
const masterDataDetails: string[] = element["masterData"];
for (let k = 0; k < masterDataDetails.length; k++) {
//unable to resolve the dynamic path from siteconfig, hence the switch case
switch (masterDataDetails[k]['Title']) {
case "Shortcut Hero":
imageContext = fetch(require('../assets/images/Photo_Frame_Shortcuts.png'));
break;
case "Always on Mute":
imageContext = fetch(require('../assets/images/Photo_Frame_Mute.png'));
break;
case "Virtual Background":
imageContext = fetch(require('../assets/images/Photo_Frame_Mess.png'));
break;
case "Jokester":
imageContext = fetch(require('../assets/images/Photo_Frame_Jokes.png'));
break;
case "Double Booked":
imageContext = fetch(require('../assets/images/Photo_Frame_Booked.png'));
break;
}
//upload default badges
imageContext.then(res => res.blob()).then((blob) => {
sp.web.getFolderByServerRelativeUrl("/" + this.state.inclusionpath + "/"
+ this.state.siteName + "/" + stringsConstants.DigitalBadgeLibrary).files.add(masterDataDetails[k]['Name'], blob, true)
.then((res) => {
res.file.getItem().then(item => {
item.update({
Title: masterDataDetails[k]['Title'],
TournamentId: masterDataDetails[k]['TournamentName']
});
});
});
});
}//master data loop
});
});
await digitalLib.defaultView.fields.add("Tournament");
});
}
}
})
.catch((err) => {
console.error(
"TOT_TOTLandingPage_createLookField \n",
JSON.stringify(err)
);
this.setState({
showError: true,
errorMessage:
stringsConstants.TOTErrorMessage +
" while adding lookup field. Below are the details: \n" +
JSON.stringify(err),
showSuccess: false,
});
});
}
//create lists and fileds and upload master data related to TOT
private async provisionTOTListsAndFields(): Promise<any> {
return new Promise<any>(async (resolve, reject) => {
try {
//get all lists schema from siteconfig
const listStructure: any = siteconfig.totLists;
listStructure.forEach(async (element) => {
const spListTitle: string = element["listName"];
const spListTemplate = element["listTemplate"];
const fieldsToCreate: string[] = element["fields"];
const masterDataToAdd: string[] = element["masterData"];
//Ensure list exists, creates if not found and add fields/data if already created
await sp.web.lists.getByTitle(spListTitle).get().then(async (list) => {
let totalFieldsToCreate = await this.checkFieldExists(spListTitle, fieldsToCreate);
if (totalFieldsToCreate.length > 0) {
await commonService.createListFields(list.Title, totalFieldsToCreate).then(async (res) => {
if (res = "Success") {
await this.checkUserRole();
resolve("Success");
}
});
}
else {
await this.checkUserRole();
resolve("Success");
}
}).catch(async () => {
await sp.web.lists.add(spListTitle, "", spListTemplate, false).then(async () => {
//verify field exists
let totalFieldsToCreate = await this.checkFieldExists(spListTitle, fieldsToCreate);
await commonService.createListFields(spListTitle, totalFieldsToCreate).
then(async (res) => {
if (res = "Success")
//rename title fields and upload master data
switch (spListTitle) {
case stringsConstants.AdminList:
//rename title display name to TOT Admins
await sp.web.lists.getByTitle(spListTitle).fields.getByTitle("Title").update({ Title: "TOT Admins" });
break;
case stringsConstants.ActionsMasterList:
//rename title display name to Action
await sp.web.lists.getByTitle(spListTitle).fields.getByTitle("Title").update({ Title: "Action" });
break;
case stringsConstants.TournamentsMasterList:
//rename title display name to Tournament Name
await sp.web.lists.getByTitle(spListTitle).fields.getByTitle("Title").update({ Title: "Tournament Name", Indexed: true, EnforceUniqueValues: true });
break;
case stringsConstants.TournamentActionsMasterList:
//rename title display name to Tournament Name and apply unique
await sp.web.lists.getByTitle(spListTitle).fields.getByTitle("Title").update({ Title: "Tournament Name" });
break;
case stringsConstants.UserActionsList:
//rename title display name to User Email
await sp.web.lists.getByTitle(spListTitle).fields.getByTitle("Title").update({ Title: "User Email", Indexed: true });
break;
default:
}
let statusOfCreation = await this.createMasterData(spListTitle, masterDataToAdd);
let promiseStatus = Promise.all(statusOfCreation);
promiseStatus.then(async () => {
await this.checkUserRole();
this.setState({ showSuccess: true });
resolve("Success");
}).catch((err) => {
console.error("TOT_TOTLandingPage_provisionTOTListsAndFields_FailedToAddMasterData \n", err);
this.setState({ showError: true, errorMessage: stringsConstants.TOTErrorMessage + " while adding master data. Below are the details: \n" + JSON.stringify(err), showSuccess: false });
});
}).catch((err) => {
console.error("TOT_TOTLandingPage_provisionTOTListsAndFields_FailedToCreatedField \n", err);
this.setState({ showError: true, errorMessage: stringsConstants.TOTErrorMessage + " while adding list fields. Below are the details: \n" + JSON.stringify(err), showSuccess: false });
});
}).catch((err) => {
console.error("TOT_TOTLandingPage_provisionTOTListsAndFields_FailedToAddList\n", err);
this.setState({ showError: true, errorMessage: stringsConstants.TOTErrorMessage + " while adding list. Below are the details: \n" + JSON.stringify(err), showSuccess: false });
});
});
});
}
catch (error) {
reject("Failed");
console.error("TOT_TOTLandingPage_provisionTOTListsAndFields \n", error);
this.setState({ showError: true, errorMessage: stringsConstants.TOTErrorMessage + " while adding list and/or fields. Below are the details: \n" + JSON.stringify(error), showSuccess: false });
}
});
}
public render(): React.ReactElement<ITOTLandingPageProps> {
return (
<div className={styles.totLandingPage}>
{this.state.isShowLoader && <div className={styles.load}></div>}
<div className={styles.container}>
{!this.state.leaderBoard &&
!this.state.createTournament &&
!this.state.dashboard &&
!this.state.manageTournament && (
<div>
<div className={styles.totHeader}>
<span className={styles.totPageHeading} onClick={this.redirectTotHome}>Tournament of Teams</span>
</div>
<div className={styles.grid}>
<div className={styles.messageContainer}>
{this.state.showSuccess && (
<Label className={styles.successMessage}>
<img src={require('../assets/TOTImages/tickIcon.png')} alt="tickIcon" className={styles.tickImage} />
Tournament of Teams enabled successfully. Please refresh the app
before using.
</Label>
)}
{this.state.showError && (
<Label className={styles.errorMessage}>
{this.state.errorMessage}
</Label>
)}
</div>
<h5 className={styles.pageSubHeader}>Quick Links</h5>
<Row className="mt-4">
<Col sm={3} className={styles.imageLayout}>
<Media
className={styles.cursor}
onClick={() =>
this.setState({
leaderBoard: !this.state.leaderBoard,
showSuccess: false,
})
}
>
<div className={styles.mb}>
<img
src={require("../assets/TOTImages/LeaderBoard.svg")}
alt="Leader Board"
title="Leader Board"
className={styles.dashboardimgs}
/>
<div className={styles.center} title="Leader Board">Leader Board</div>
</div>
</Media>
</Col>
<Col sm={3} className={styles.imageLayout}>
<Media
className={styles.cursor}
onClick={() =>
this.setState({
dashboard: !this.state.dashboard,
showSuccess: false,
})
}
>
<div className={styles.mb}>
<img
src={require("../assets/TOTImages/MyDashboard.svg")}
alt="My Dashboard"
title="My Dashboard"
className={styles.dashboardimgs}
/>
<div className={styles.center} title="My Dashboard">My Dashboard</div>
</div>
</Media>
</Col>
</Row>
{this.state.isAdmin && (
<div>
<h5 className={styles.pageSubHeader}>Admin Tools</h5>
</div>
)}
{this.state.isAdmin && (
<Row className="mt-4">
<Col sm={3} className={styles.imageLayout}>
<Media className={styles.cursor}>
<div className={styles.mb}>
<a
href={`/${this.state.inclusionpath}/${this.state.siteName}/Lists/Actions%20List/AllItems.aspx`}
target="_blank"
>
<img
src={require("../assets/TOTImages/ManageTournamentActions.svg")}
alt="Accessing Tournament Actions List"
title="Accessing Tournament Actions List"
className={`${styles.dashboardimgs}`}
/>
</a>
<div className={`${styles.center}`} title="Manage Tournament Actions">
Manage Tournament Actions
</div>
</div>
</Media>
</Col>
<Col sm={3} className={styles.imageLayout}>
<Media
className={styles.cursor}
onClick={() =>
this.setState({
createTournament: !this.state.createTournament,
showSuccess: false,
})
}
>
<div className={styles.mb}>
<img
src={require("../assets/TOTImages/CreateTournament.svg")}
alt="Create Tournament"
title="Create Tournament"
className={styles.dashboardimgs}
/>
<div className={styles.center} title="Create Tournament">
Create Tournament
</div>
</div>
</Media>
</Col>
<Col sm={3} className={styles.imageLayout}>
<Media
className={styles.cursor}
onClick={() =>
this.setState({
manageTournament: !this.state.manageTournament,
showSuccess: false,
})
}
>
{this.state.activeTournamentExists && (<div className={styles.mb}>
<img
src={require("../assets/TOTImages/ManageTournaments.svg")}
alt="End Current Tournament"
title="End Current Tournament"
className={styles.dashboardimgs}
/>
<div className={styles.center} title="End Current Tournament">End Current Tournament</div>
</div>)}
{!this.state.activeTournamentExists && (<div className={styles.mb}>
<img
src={require("../assets/TOTImages/ManageTournaments.svg")}
alt="Start New Tournament"
title="Start New Tournament"
className={styles.dashboardimgs}
/>
<div className={styles.center} title="Start New Tournament">Start New Tournament</div>
</div>)}
</Media>
</Col>
<Col sm={3} className={styles.imageLayout}>
<Media className={styles.cursor}>
<div className={styles.mb}>
<a
href={`/${this.state.inclusionpath}/${this.state.siteName}/Lists/ToT%20Admins/AllItems.aspx`}
target="_blank"
>
<img
src={require("../assets/TOTImages/ManageAdmins.svg")}
alt="Accessing Admin List"
title="Accessing Admin List"
className={styles.dashboardimgs}
/>
</a>
<div className={styles.center} title="Manage Admins">Manage Admins</div>
</div>
</Media>
</Col>
<Col sm={3} className={styles.imageLayout}>
<Media className={styles.cursor}>
<div className={styles.mb}>
<a
href={`/${this.state.inclusionpath}/${this.state.siteName}/Digital%20Badge%20Assets/Forms/AllItems.aspx`}
target="_blank"
>
<img
src={require("../assets/TOTImages/ManageDigitalBadges.svg")}
alt="Manage Digital Badges"
title="Manage Digital Badges"
className={`${styles.dashboardimgs}`}
/>
</a>
<div className={`${styles.center}`} title="Manage Digital Badges">
Manage Digital Badges
</div>
</div>
</Media>
</Col>
</Row>
)}
</div>
</div>
)
}
{
this.state.leaderBoard && (
<TOTLeaderBoard
siteUrl={this.props.siteUrl}
context={this.props.context}
onClickCancel={() => {
this.checkActiveTournament();
this.setState({ leaderBoard: false });
}}
onClickMyDashboardLink={() => {
this.checkActiveTournament();
this.setState({ dashboard: true, leaderBoard: false });
}}
/>
)
}
{
this.state.dashboard && (
<TOTMyDashboard
siteUrl={this.props.siteUrl}
context={this.props.context}
onClickCancel={() => {
this.checkActiveTournament();
this.setState({ dashboard: false });
}
}
/>
)
}
{
this.state.createTournament && (
<TOTCreateTournament
siteUrl={this.props.siteUrl}
context={this.props.context}
onClickCancel={() => {
this.checkActiveTournament();
this.setState({ createTournament: false });
}}
/>
)
}
{
this.state.manageTournament && (
<TOTEnableTournament
siteUrl={this.props.siteUrl}
context={this.props.context}
onClickCancel={() => {
this.setState({ manageTournament: false });
this.checkActiveTournament();
}}
/>
)}
</div>
</div>
);
}
}
export default TOTLandingPage; | the_stack |
import $ from './dom';
import * as _ from './utils';
import { EditorConfig, SanitizerConfig } from '../../types';
import { EditorModules } from '../types-internal/editor-modules';
import I18n from './i18n';
import { CriticalError } from './errors/critical';
import EventsDispatcher from './utils/events';
/**
* @typedef {Core} Core - editor core class
*/
/**
* Require Editor modules places in components/modules dir
*/
const contextRequire = require.context('./modules', true);
const modules = [];
contextRequire.keys().forEach((filename) => {
/**
* Include files if:
* - extension is .js or .ts
* - does not starts with _
*/
if (filename.match(/^\.\/[^_][\w/]*\.([tj])s$/)) {
modules.push(contextRequire(filename));
}
});
/**
* @class Core
*
* @classdesc Editor.js core class
*
* @property {EditorConfig} config - all settings
* @property {EditorModules} moduleInstances - constructed editor components
*
* @type {Core}
*/
export default class Core {
/**
* Editor configuration passed by user to the constructor
*/
public config: EditorConfig;
/**
* Object with core modules instances
*/
public moduleInstances: EditorModules = {} as EditorModules;
/**
* Promise that resolves when all core modules are prepared and UI is rendered on the page
*/
public isReady: Promise<void>;
/**
* Event Dispatcher util
*/
private eventsDispatcher: EventsDispatcher = new EventsDispatcher();
/**
* @param {EditorConfig} config - user configuration
*
*/
constructor(config?: EditorConfig|string) {
/**
* Ready promise. Resolved if Editor.js is ready to work, rejected otherwise
*/
let onReady, onFail;
this.isReady = new Promise((resolve, reject) => {
onReady = resolve;
onFail = reject;
});
Promise.resolve()
.then(async () => {
this.configuration = config;
await this.validate();
await this.init();
await this.start();
_.logLabeled('I\'m ready! (ノ◕ヮ◕)ノ*:・゚✧', 'log', '', 'color: #E24A75');
setTimeout(async () => {
await this.render();
if ((this.configuration as EditorConfig).autofocus) {
const { BlockManager, Caret } = this.moduleInstances;
Caret.setToBlock(BlockManager.blocks[0], Caret.positions.START);
BlockManager.highlightCurrentNode();
}
/**
* Remove loader, show content
*/
this.moduleInstances.UI.removeLoader();
/**
* Resolve this.isReady promise
*/
onReady();
}, 500);
})
.catch((error) => {
_.log(`Editor.js is not ready because of ${error}`, 'error');
/**
* Reject this.isReady promise
*/
onFail(error);
});
}
/**
* Setting for configuration
*
* @param {EditorConfig|string} config - Editor's config to set
*/
public set configuration(config: EditorConfig|string) {
/**
* Place config into the class property
*
* @type {EditorConfig}
*/
if (_.isObject(config)) {
this.config = {
...config,
};
} else {
/**
* Process zero-configuration or with only holderId
* Make config object
*/
this.config = {
holder: config,
};
}
/**
* If holderId is preset, assign him to holder property and work next only with holder
*/
_.deprecationAssert(!!this.config.holderId, 'config.holderId', 'config.holder');
if (this.config.holderId && !this.config.holder) {
this.config.holder = this.config.holderId;
this.config.holderId = null;
}
/**
* If holder is empty then set a default value
*/
if (this.config.holder == null) {
this.config.holder = 'editorjs';
}
if (!this.config.logLevel) {
this.config.logLevel = _.LogLevels.VERBOSE;
}
_.setLogLevel(this.config.logLevel);
/**
* If default Block's Tool was not passed, use the Paragraph Tool
*/
_.deprecationAssert(Boolean(this.config.initialBlock), 'config.initialBlock', 'config.defaultBlock');
this.config.defaultBlock = this.config.defaultBlock || this.config.initialBlock || 'paragraph';
/**
* Height of Editor's bottom area that allows to set focus on the last Block
*
* @type {number}
*/
this.config.minHeight = this.config.minHeight !== undefined ? this.config.minHeight : 300;
/**
* Default block type
* Uses in case when there is no blocks passed
*
* @type {{type: (*), data: {text: null}}}
*/
const defaultBlockData = {
type: this.config.defaultBlock,
data: {},
};
this.config.placeholder = this.config.placeholder || false;
this.config.sanitizer = this.config.sanitizer || {
p: true,
b: true,
a: true,
} as SanitizerConfig;
this.config.hideToolbar = this.config.hideToolbar ? this.config.hideToolbar : false;
this.config.tools = this.config.tools || {};
this.config.i18n = this.config.i18n || {};
this.config.data = this.config.data || { blocks: [] };
// eslint-disable-next-line @typescript-eslint/no-empty-function
this.config.onReady = this.config.onReady || ((): void => {});
// eslint-disable-next-line @typescript-eslint/no-empty-function
this.config.onChange = this.config.onChange || ((): void => {});
this.config.inlineToolbar = this.config.inlineToolbar !== undefined ? this.config.inlineToolbar : true;
/**
* Initialize default Block to pass data to the Renderer
*/
if (_.isEmpty(this.config.data) || !this.config.data.blocks || this.config.data.blocks.length === 0) {
this.config.data = { blocks: [ defaultBlockData ] };
}
this.config.readOnly = this.config.readOnly as boolean || false;
/**
* Adjust i18n
*/
if (this.config.i18n?.messages) {
I18n.setDictionary(this.config.i18n.messages);
}
/**
* Text direction. If not set, uses ltr
*/
this.config.i18n.direction = this.config.i18n?.direction || 'ltr';
}
/**
* Returns private property
*
* @returns {EditorConfig}
*/
public get configuration(): EditorConfig|string {
return this.config;
}
/**
* Checks for required fields in Editor's config
*
* @returns {Promise<void>}
*/
public async validate(): Promise<void> {
const { holderId, holder } = this.config;
if (holderId && holder) {
throw Error('«holderId» and «holder» param can\'t assign at the same time.');
}
/**
* Check for a holder element's existence
*/
if (_.isString(holder) && !$.get(holder)) {
throw Error(`element with ID «${holder}» is missing. Pass correct holder's ID.`);
}
if (holder && _.isObject(holder) && !$.isElement(holder)) {
throw Error('«holder» value must be an Element node');
}
}
/**
* Initializes modules:
* - make and save instances
* - configure
*/
public init(): void {
/**
* Make modules instances and save it to the @property this.moduleInstances
*/
this.constructModules();
/**
* Modules configuration
*/
this.configureModules();
}
/**
* Start Editor!
*
* Get list of modules that needs to be prepared and return a sequence (Promise)
*
* @returns {Promise<void>}
*/
public async start(): Promise<void> {
const modulesToPrepare = [
'Tools',
'UI',
'BlockManager',
'Paste',
'BlockSelection',
'RectangleSelection',
'CrossBlockSelection',
'ReadOnly',
];
await modulesToPrepare.reduce(
(promise, module) => promise.then(async () => {
// _.log(`Preparing ${module} module`, 'time');
try {
await this.moduleInstances[module].prepare();
} catch (e) {
/**
* CriticalError's will not be caught
* It is used when Editor is rendering in read-only mode with unsupported plugin
*/
if (e instanceof CriticalError) {
throw new Error(e.message);
}
_.log(`Module ${module} was skipped because of %o`, 'warn', e);
}
// _.log(`Preparing ${module} module`, 'timeEnd');
}),
Promise.resolve()
);
}
/**
* Render initial data
*/
private render(): Promise<void> {
return this.moduleInstances.Renderer.render(this.config.data.blocks);
}
/**
* Make modules instances and save it to the @property this.moduleInstances
*/
private constructModules(): void {
modules.forEach((module) => {
/**
* If module has non-default exports, passed object contains them all and default export as 'default' property
*/
const Module = _.isFunction(module) ? module : module.default;
try {
/**
* We use class name provided by displayName property
*
* On build, Babel will transform all Classes to the Functions so, name will always be 'Function'
* To prevent this, we use 'babel-plugin-class-display-name' plugin
*
* @see https://www.npmjs.com/package/babel-plugin-class-display-name
*/
this.moduleInstances[Module.displayName] = new Module({
config: this.configuration,
eventsDispatcher: this.eventsDispatcher,
});
} catch (e) {
_.log(`Module ${Module.displayName} skipped because`, 'error', e);
}
});
}
/**
* Modules instances configuration:
* - pass other modules to the 'state' property
* - ...
*/
private configureModules(): void {
for (const name in this.moduleInstances) {
if (Object.prototype.hasOwnProperty.call(this.moduleInstances, name)) {
/**
* Module does not need self-instance
*/
this.moduleInstances[name].state = this.getModulesDiff(name);
}
}
}
/**
* Return modules without passed name
*
* @param {string} name - module for witch modules difference should be calculated
*/
private getModulesDiff(name: string): EditorModules {
const diff = {} as EditorModules;
for (const moduleName in this.moduleInstances) {
/**
* Skip module with passed name
*/
if (moduleName === name) {
continue;
}
diff[moduleName] = this.moduleInstances[moduleName];
}
return diff;
}
} | the_stack |
'use strict';
import {ExtHostCommands} from 'vs/workbench/api/node/extHostCommands';
import Severity from 'vs/base/common/severity';
import {isFalsyOrEmpty} from 'vs/base/common/arrays';
import {IDisposable} from 'vs/base/common/lifecycle';
import {stringDiff} from 'vs/base/common/diff/diff';
import * as modes from 'vs/editor/common/modes';
import * as types from './extHostTypes';
import {Position as EditorPosition} from 'vs/platform/editor/common/editor';
import {IPosition, ISelection, IRange, IDecorationOptions, ISingleEditOperation} from 'vs/editor/common/editorCommon';
import {IWorkspaceSymbol} from 'vs/workbench/parts/search/common/search';
import * as vscode from 'vscode';
import URI from 'vs/base/common/uri';
export interface PositionLike {
line: number;
character: number;
}
export interface RangeLike {
start: PositionLike;
end: PositionLike;
}
export interface SelectionLike extends RangeLike {
anchor: PositionLike;
active: PositionLike;
}
export function toSelection(selection: ISelection): types.Selection {
let {selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn} = selection;
let start = new types.Position(selectionStartLineNumber - 1, selectionStartColumn - 1);
let end = new types.Position(positionLineNumber - 1, positionColumn - 1);
return new types.Selection(start, end);
}
export function fromSelection(selection: SelectionLike): ISelection {
let {anchor, active} = selection;
return {
selectionStartLineNumber: anchor.line + 1,
selectionStartColumn: anchor.character + 1,
positionLineNumber: active.line + 1,
positionColumn: active.character + 1
};
}
export function fromRange(range: RangeLike): IRange {
let {start, end} = range;
return {
startLineNumber: start.line + 1,
startColumn: start.character + 1,
endLineNumber: end.line + 1,
endColumn: end.character + 1
};
}
export function toRange(range: IRange): types.Range {
let {startLineNumber, startColumn, endLineNumber, endColumn} = range;
return new types.Range(startLineNumber - 1, startColumn - 1, endLineNumber - 1, endColumn - 1);
}
export function toPosition(position: IPosition): types.Position {
return new types.Position(position.lineNumber - 1, position.column - 1);
}
export function fromPosition(position: types.Position):IPosition {
return { lineNumber: position.line + 1, column: position.character + 1};
}
export function fromDiagnosticSeverity(value: number): Severity {
switch (value) {
case types.DiagnosticSeverity.Error:
return Severity.Error;
case types.DiagnosticSeverity.Warning:
return Severity.Warning;
case types.DiagnosticSeverity.Information:
return Severity.Info;
case types.DiagnosticSeverity.Hint:
return Severity.Ignore;
}
return Severity.Error;
}
export function toDiagnosticSeverty(value: Severity): types.DiagnosticSeverity {
switch (value) {
case Severity.Info:
return types.DiagnosticSeverity.Information;
case Severity.Warning:
return types.DiagnosticSeverity.Warning;
case Severity.Error:
return types.DiagnosticSeverity.Error;
case Severity.Ignore:
return types.DiagnosticSeverity.Hint;
}
return types.DiagnosticSeverity.Error;
}
export function fromViewColumn(column?: vscode.ViewColumn): EditorPosition {
let editorColumn = EditorPosition.LEFT;
if (typeof column !== 'number') {
// stick with LEFT
} else if (column === <number>types.ViewColumn.Two) {
editorColumn = EditorPosition.CENTER;
} else if (column === <number>types.ViewColumn.Three) {
editorColumn = EditorPosition.RIGHT;
}
return editorColumn;
}
export function toViewColumn(position?: EditorPosition): vscode.ViewColumn {
if (typeof position !== 'number') {
return;
}
if (position === EditorPosition.LEFT) {
return <number> types.ViewColumn.One;
} else if (position === EditorPosition.CENTER) {
return <number> types.ViewColumn.Two;
} else if (position === EditorPosition.RIGHT) {
return <number> types.ViewColumn.Three;
}
}
function isDecorationOptions(something: any): something is vscode.DecorationOptions {
return (typeof something.range !== 'undefined');
}
function isDecorationOptionsArr(something: vscode.Range[]|vscode.DecorationOptions[]): something is vscode.DecorationOptions[] {
if (something.length === 0) {
return true;
}
return isDecorationOptions(something[0]) ? true : false;
}
export function fromRangeOrRangeWithMessage(ranges:vscode.Range[]|vscode.DecorationOptions[]): IDecorationOptions[] {
if (isDecorationOptionsArr(ranges)) {
return ranges.map((r): IDecorationOptions => {
return {
range: fromRange(r.range),
hoverMessage: r.hoverMessage,
renderOptions: r.renderOptions
};
});
} else {
return ranges.map((r): IDecorationOptions => {
return {
range: fromRange(r)
};
});
}
}
export const TextEdit = {
minimalEditOperations(edits: vscode.TextEdit[], document: vscode.TextDocument, beforeDocumentVersion: number): ISingleEditOperation[] {
// document has changed in the meantime and we shouldn't do
// offset math as it's likely to be all wrong
if (document.version !== beforeDocumentVersion) {
return edits.map(TextEdit.from);
}
const result: ISingleEditOperation[] = [];
for (let edit of edits) {
const original = document.getText(edit.range);
const modified = edit.newText;
const changes = stringDiff(original, modified);
if (changes.length <= 1) {
result.push(TextEdit.from(edit));
continue;
}
const editOffset = document.offsetAt(edit.range.start);
for (let j = 0; j < changes.length; j++) {
const {originalStart, originalLength, modifiedStart, modifiedLength} = changes[j];
const start = fromPosition(<types.Position> document.positionAt(editOffset + originalStart));
const end = fromPosition(<types.Position> document.positionAt(editOffset + originalStart + originalLength));
result.push({
text: modified.substr(modifiedStart, modifiedLength),
range: { startLineNumber: start.lineNumber, startColumn: start.column, endLineNumber: end.lineNumber, endColumn: end.column }
});
}
}
return result;
},
from(edit: vscode.TextEdit): ISingleEditOperation{
return <ISingleEditOperation>{
text: edit.newText,
range: fromRange(edit.range)
};
},
to(edit: ISingleEditOperation): vscode.TextEdit {
return new types.TextEdit(toRange(edit.range), edit.text);
}
};
export namespace SymbolInformation {
export function fromOutlineEntry(entry: modes.SymbolInformation): types.SymbolInformation {
return new types.SymbolInformation(
entry.name,
entry.kind,
toRange(entry.location.range),
entry.location.uri,
entry.containerName
);
}
export function toOutlineEntry(symbol: vscode.SymbolInformation): modes.SymbolInformation {
return <modes.SymbolInformation>{
name: symbol.name,
kind: symbol.kind,
containerName: symbol.containerName,
location: {
uri: <URI>symbol.location.uri,
range: fromRange(symbol.location.range)
}
};
}
}
export function fromSymbolInformation(info: vscode.SymbolInformation): IWorkspaceSymbol {
return <IWorkspaceSymbol>{
name: info.name,
type: types.SymbolKind[info.kind || types.SymbolKind.Property].toLowerCase(),
containerName: info.containerName,
range: info.location && fromRange(info.location.range),
resource: info.location && info.location.uri,
};
}
export function toSymbolInformation(bearing: IWorkspaceSymbol): types.SymbolInformation {
return new types.SymbolInformation(bearing.name,
types.SymbolKind[bearing.type.charAt(0).toUpperCase() + bearing.type.substr(1)],
bearing.containerName,
new types.Location(bearing.resource, toRange(bearing.range))
);
}
export const location = {
from(value: types.Location): modes.Location {
return {
range: fromRange(value.range),
uri: value.uri
};
},
to(value: modes.Location): types.Location {
return new types.Location(value.uri, toRange(value.range));
}
};
export function fromHover(hover: vscode.Hover): modes.Hover {
return <modes.Hover>{
range: fromRange(hover.range),
contents: hover.contents
};
}
export function toHover(info: modes.Hover): types.Hover {
return new types.Hover(info.contents, toRange(info.range));
}
export function toDocumentHighlight(occurrence: modes.DocumentHighlight): types.DocumentHighlight {
return new types.DocumentHighlight(toRange(occurrence.range), occurrence.kind);
}
export const CompletionItemKind = {
from(kind: types.CompletionItemKind): modes.SuggestionType {
switch (kind) {
case types.CompletionItemKind.Method: return 'method';
case types.CompletionItemKind.Function: return 'function';
case types.CompletionItemKind.Constructor: return 'constructor';
case types.CompletionItemKind.Field: return 'field';
case types.CompletionItemKind.Variable: return 'variable';
case types.CompletionItemKind.Class: return 'class';
case types.CompletionItemKind.Interface: return 'interface';
case types.CompletionItemKind.Module: return 'module';
case types.CompletionItemKind.Property: return 'property';
case types.CompletionItemKind.Unit: return 'unit';
case types.CompletionItemKind.Value: return 'value';
case types.CompletionItemKind.Enum: return 'enum';
case types.CompletionItemKind.Keyword: return 'keyword';
case types.CompletionItemKind.Snippet: return 'snippet';
case types.CompletionItemKind.Text: return 'text';
case types.CompletionItemKind.Color: return 'color';
case types.CompletionItemKind.File: return 'file';
case types.CompletionItemKind.Reference: return 'reference';
}
return 'property';
},
to(type: modes.SuggestionType): types.CompletionItemKind {
if (!type) {
return types.CompletionItemKind.Property;
} else {
return types.CompletionItemKind[type.charAt(0).toUpperCase() + type.substr(1)];
}
}
};
export const Suggest = {
from(item: vscode.CompletionItem, disposables: IDisposable[]): modes.ISuggestion {
const suggestion: modes.ISuggestion = {
label: item.label,
insertText: item.insertText || item.label,
type: CompletionItemKind.from(item.kind),
detail: item.detail,
documentation: item.documentation,
sortText: item.sortText,
filterText: item.filterText,
command: Command.from(item.command, disposables),
additionalTextEdits: item.additionalTextEdits && item.additionalTextEdits.map(TextEdit.from)
};
return suggestion;
},
to(container: modes.ISuggestResult, position: types.Position, suggestion: modes.ISuggestion): types.CompletionItem {
const result = new types.CompletionItem(suggestion.label);
result.insertText = suggestion.insertText;
result.kind = CompletionItemKind.to(suggestion.type);
result.detail = suggestion.detail;
result.documentation = suggestion.documentation;
result.sortText = suggestion.sortText;
result.filterText = suggestion.filterText;
let overwriteBefore = (typeof suggestion.overwriteBefore === 'number') ? suggestion.overwriteBefore : container.currentWord.length;
let startPosition = new types.Position(position.line, Math.max(0, position.character - overwriteBefore));
let endPosition = position;
if (typeof suggestion.overwriteAfter === 'number') {
endPosition = new types.Position(position.line, position.character + suggestion.overwriteAfter);
}
result.textEdit = types.TextEdit.replace(new types.Range(startPosition, endPosition), suggestion.insertText);
return result;
}
};
export namespace SignatureHelp {
export function from(signatureHelp: types.SignatureHelp): modes.SignatureHelp {
return signatureHelp;
}
export function to(hints: modes.SignatureHelp): types.SignatureHelp {
return hints;
}
}
export namespace DocumentLink {
export function from(link: vscode.DocumentLink): modes.ILink {
return {
range: fromRange(link.range),
url: link.target && link.target.toString()
};
}
export function to(link: modes.ILink): vscode.DocumentLink {
return new types.DocumentLink(toRange(link.range), link.url && URI.parse(link.url));
}
}
export namespace Command {
const _delegateId = '_internal_delegate_command';
const _cache: { [id: string]: vscode.Command } = Object.create(null);
let _idPool = 1;
export function initialize(commands: ExtHostCommands) {
return commands.registerCommand(_delegateId, (id: string) => {
const command = _cache[id];
if (!command) {
// handle already disposed delegations graceful
return;
}
return commands.executeCommand(command.command, ...command.arguments);
});
}
export function from(command: vscode.Command, disposables: IDisposable[]): modes.Command {
if (!command) {
return;
}
const result = <modes.Command>{
id: command.command,
title: command.title
};
if (!isFalsyOrEmpty(command.arguments)) {
// redirect to delegate command and store actual command
const id = `delegate/${_idPool++}/for/${command.command}`;
result.id = _delegateId;
result.arguments = [id];
_cache[id] = command;
disposables.push({
dispose() {
delete _cache[id];
}
});
}
return result;
}
export function to(command: modes.Command): vscode.Command {
let result: vscode.Command;
if (command.id === _delegateId) {
let [key] = command.arguments;
result = _cache[key];
}
if (!result) {
result = {
command: command.id,
title: command.title
};
}
return result;
}
} | the_stack |
declare module '@microsoft/office-js-helpers/authentication/authenticator' {
import { EndpointStorage } from '@microsoft/office-js-helpers/authentication/endpoint/index';
import { TokenStorage, IToken, ICode, IError } from '@microsoft/office-js-helpers/authentication/token/index';
import { CustomError } from '@microsoft/office-js-helpers/errors/custom/index';
/**
* Custom error type to handle OAuth specific errors.
*/
export class AuthError extends CustomError {
innerError?: Error;
/**
* @constructor
*
* @param message Error message to be propagated.
* @param state OAuth state if available.
*/
constructor(message: string, innerError?: Error);
}
/**
* Helper for performing Implicit OAuth Authentication with registered endpoints.
*/
export class Authenticator {
endpoints?: EndpointStorage;
tokens?: TokenStorage;
/**
* @constructor
*
* @param endpoints Depends on an instance of EndpointStorage.
* @param tokens Depends on an instance of TokenStorage.
*/
constructor(endpoints?: EndpointStorage, tokens?: TokenStorage);
/**
* Authenticate based on the given provider.
* Either uses DialogAPI or Window Popups based on where it's being called from (either Add-in or Web).
* If the token was cached, then it retrieves the cached token.
* If the cached token has expired then the authentication dialog is displayed.
*
* NOTE: you have to manually check the expires_in or expires_at property to determine
* if the token has expired.
*
* @param {string} provider Link to the provider.
* @param {boolean} force Force re-authentication.
* @return {Promise<IToken|ICode>} Returns a promise of the token, code, or error.
*/
authenticate(provider: string, force?: boolean, useMicrosoftTeams?: boolean): Promise<IToken>;
/**
* Check if the current url is running inside of a Dialog that contains an access_token, code, or error.
* If true then it calls messageParent by extracting the token information, thereby closing the dialog.
* Otherwise, the caller should proceed with normal initialization of their application.
*
* This logic assumes that the redirect url is your application and hence when your code runs again in
* the dialog, this logic takes over and closes it for you.
*
* @return {boolean}
* Returns false if the code is running inside of a dialog without the required information
* or is not running inside of a dialog at all.
*/
static isAuthDialog(useMicrosoftTeams?: boolean): boolean;
/**
* Extract the token from the URL
*
* @param {string} url The url to extract the token from.
* @param {string} exclude Exclude a particular string from the url, such as a query param or specific substring.
* @param {string} delimiter[optional] Delimiter used by OAuth provider to mark the beginning of token response. Defaults to #.
* @return {object} Returns the extracted token.
*/
static getUrlParams(url?: string, exclude?: string, delimiter?: string): ICode | IToken | IError;
static extractParams(segment: string): any;
private _openAuthDialog;
/**
* Helper for exchanging the code with a registered Endpoint.
* The helper sends a POST request to the given Endpoint's tokenUrl.
*
* The Endpoint must accept the data JSON input and return an 'access_token'
* in the JSON output.
*
* @param {Endpoint} endpoint Endpoint configuration.
* @param {object} data Data to be sent to the tokenUrl.
* @param {object} headers Headers to be sent to the tokenUrl.
* @return {Promise<IToken>} Returns a promise of the token or error.
*/
private _exchangeCodeForToken;
private _handleTokenResult;
}
}
declare module '@microsoft/office-js-helpers/authentication/endpoint.manager' {
import { Storage, StorageType } from '@microsoft/office-js-helpers/helpers/storage';
export const DefaultEndpoints: {
Google: string;
Microsoft: string;
Facebook: string;
AzureAD: string;
Dropbox: string;
};
export interface IEndpointConfiguration {
provider?: string;
clientId?: string;
baseUrl?: string;
authorizeUrl?: string;
redirectUrl?: string;
tokenUrl?: string;
scope?: string;
resource?: string;
state?: boolean;
nonce?: boolean;
responseType?: string;
extraQueryParameters?: {
[index: string]: string;
};
}
/**
* Helper for creating and registering OAuth Endpoints.
*/
export class EndpointStorage extends Storage<IEndpointConfiguration> {
/**
* @constructor
*/
constructor(storageType?: StorageType);
/**
* Extends Storage's default add method.
* Registers a new OAuth Endpoint.
*
* @param {string} provider Unique name for the registered OAuth Endpoint.
* @param {object} config Valid Endpoint configuration.
* @see {@link IEndpointConfiguration}.
* @return {object} Returns the added endpoint.
*/
add(provider: string, config: IEndpointConfiguration): IEndpointConfiguration;
/**
* Register Google Implicit OAuth.
* If overrides is left empty, the default scope is limited to basic profile information.
*
* @param {string} clientId ClientID for the Google App.
* @param {object} config Valid Endpoint configuration to override the defaults.
* @return {object} Returns the added endpoint.
*/
registerGoogleAuth(clientId: string, overrides?: IEndpointConfiguration): IEndpointConfiguration;
/**
* Register Microsoft Implicit OAuth.
* If overrides is left empty, the default scope is limited to basic profile information.
*
* @param {string} clientId ClientID for the Microsoft App.
* @param {object} config Valid Endpoint configuration to override the defaults.
* @return {object} Returns the added endpoint.
*/
registerMicrosoftAuth(clientId: string, overrides?: IEndpointConfiguration): void;
/**
* Register Facebook Implicit OAuth.
* If overrides is left empty, the default scope is limited to basic profile information.
*
* @param {string} clientId ClientID for the Facebook App.
* @param {object} config Valid Endpoint configuration to override the defaults.
* @return {object} Returns the added endpoint.
*/
registerFacebookAuth(clientId: string, overrides?: IEndpointConfiguration): void;
/**
* Register AzureAD Implicit OAuth.
* If overrides is left empty, the default scope is limited to basic profile information.
*
* @param {string} clientId ClientID for the AzureAD App.
* @param {string} tenant Tenant for the AzureAD App.
* @param {object} config Valid Endpoint configuration to override the defaults.
* @return {object} Returns the added endpoint.
*/
registerAzureADAuth(clientId: string, tenant: string, overrides?: IEndpointConfiguration): void;
/**
* Register Dropbox Implicit OAuth.
* If overrides is left empty, the default scope is limited to basic profile information.
*
* @param {string} clientId ClientID for the Dropbox App.
* @param {object} config Valid Endpoint configuration to override the defaults.
* @return {object} Returns the added endpoint.
*/
registerDropboxAuth(clientId: string, overrides?: IEndpointConfiguration): void;
/**
* Helper to generate the OAuth login url.
*
* @param {object} config Valid Endpoint configuration.
* @return {object} Returns the added endpoint.
*/
static getLoginParams(endpointConfig: IEndpointConfiguration): {
url: string;
state: number;
};
}
}
declare module '@microsoft/office-js-helpers/authentication/token.manager' {
import { Storage, StorageType } from '@microsoft/office-js-helpers/helpers/storage';
export interface IToken {
provider: string;
id_token?: string;
access_token?: string;
token_type?: string;
scope?: string;
state?: string;
expires_in?: string;
expires_at?: Date;
}
export interface ICode {
provider: string;
code: string;
scope?: string;
state?: string;
}
export interface IError {
error: string;
state?: string;
}
/**
* Helper for caching and managing OAuth Tokens.
*/
export class TokenStorage extends Storage<IToken> {
/**
* @constructor
*/
constructor(storageType?: StorageType);
/**
* Compute the expiration date based on the expires_in field in a OAuth token.
*/
static setExpiry(token: IToken): void;
/**
* Check if an OAuth token has expired.
*/
static hasExpired(token: IToken): boolean;
/**
* Extends Storage's default get method
* Gets an OAuth Token after checking its expiry
*
* @param {string} provider Unique name of the corresponding OAuth Token.
* @return {object} Returns the token or null if its either expired or doesn't exist.
*/
get(provider: string): IToken;
/**
* Extends Storage's default add method
* Adds a new OAuth Token after settings its expiry
*
* @param {string} provider Unique name of the corresponding OAuth Token.
* @param {object} config valid Token
* @see {@link IToken}.
* @return {object} Returns the added token.
*/
add(provider: string, value: IToken): IToken;
}
}
declare module '@microsoft/office-js-helpers/errors/api.error' {
import { CustomError } from '@microsoft/office-js-helpers/errors/custom/index';
/**
* Custom error type to handle API specific errors.
*/
export class APIError extends CustomError {
innerError?: Error;
/**
* @constructor
*
* @param message: Error message to be propagated.
* @param innerError: Inner error if any
*/
constructor(message: string, innerError?: Error);
}
}
declare module '@microsoft/office-js-helpers/errors/custom.error' {
/**
* Custom error type
*/
export abstract class CustomError extends Error {
name: string;
message: string;
innerError?: Error;
constructor(name: string, message: string, innerError?: Error);
}
}
declare module '@microsoft/office-js-helpers/errors/exception' {
import { CustomError } from '@microsoft/office-js-helpers/errors/custom/index';
/**
* Error type to handle general errors.
*/
export class Exception extends CustomError {
innerError?: Error;
/**
* @constructor
*
* @param message: Error message to be propagated.
* @param innerError: Inner error if any
*/
constructor(message: string, innerError?: Error);
}
}
declare module '@microsoft/office-js-helpers/excel/utilities' {
/// <reference types="office-js" />
/**
* Helper exposing useful Utilities for Excel Add-ins.
*/
export class ExcelUtilities {
/**
* Utility to create (or re-create) a worksheet, even if it already exists.
* @param workbook
* @param sheetName
* @param clearOnly If the sheet already exists, keep it as is, and only clear its grid.
* This results in a faster operation, and avoid a screen-update flash
* (and the re-setting of the current selection).
* Note: Clearing the grid does not remove floating objects like charts.
* @returns the new worksheet
*/
static forceCreateSheet(workbook: Excel.Workbook, sheetName: string, clearOnly?: boolean): Promise<Excel.Worksheet>;
}
}
declare module '@microsoft/office-js-helpers/helpers/dialog' {
import { CustomError } from '@microsoft/office-js-helpers/errors/custom/index';
/**
* Custom error type to handle API specific errors.
*/
export class DialogError extends CustomError {
innerError?: Error;
/**
* @constructor
*
* @param message Error message to be propagated.
* @param state OAuth state if available.
*/
constructor(message: string, innerError?: Error);
}
/**
* An optimized size object computed based on Screen Height & Screen Width
*/
export interface IDialogSize {
width: number;
width$: number;
height: number;
height$: number;
}
export class Dialog<T> {
url: string;
useTeamsDialog: boolean;
/**
* @constructor
*
* @param url Url to be opened in the dialog.
* @param width Width of the dialog.
* @param height Height of the dialog.
*/
constructor(url?: string, width?: number, height?: number, useTeamsDialog?: boolean);
private readonly _windowFeatures;
private static readonly key;
private _result;
get result(): Promise<T>;
size: IDialogSize;
private _addinDialog;
private _teamsDialog;
private _webDialog;
private _pollLocalStorageForToken;
/**
* Close any open dialog by providing an optional message.
* If more than one dialogs are attempted to be opened
* an exception will be created.
*/
static close(message?: any, useTeamsDialog?: boolean): void;
private _optimizeSize;
private _maxSize;
private _percentage;
private _safeParse;
}
}
declare module '@microsoft/office-js-helpers/helpers/dictionary' {
/**
* Helper for creating and querying Dictionaries.
* A wrapper around ES6 Maps.
*/
export class Dictionary<T> {
protected _items: Map<string, T>;
/**
* @constructor
* @param {object} items Initial seed of items.
*/
constructor(items?: {
[index: string]: T;
} | Array<[string, T]> | Map<string, T>);
/**
* Gets an item from the dictionary.
*
* @param {string} key The key of the item.
* @return {object} Returns an item if found.
*/
get(key: string): T;
/**
* Inserts an item into the dictionary.
* If an item already exists with the same key, it will be overridden by the new value.
*
* @param {string} key The key of the item.
* @param {object} value The item to be added.
* @return {object} Returns the added item.
*/
set(key: string, value: T): T;
/**
* Removes an item from the dictionary.
* Will throw if the key doesn't exist.
*
* @param {string} key The key of the item.
* @return {object} Returns the deleted item.
*/
delete(key: string): T;
/**
* Clears the dictionary.
*/
clear(): void;
/**
* Check if the dictionary contains the given key.
*
* @param {string} key The key of the item.
* @return {boolean} Returns true if the key was found.
*/
has(key: string): boolean;
/**
* Lists all the keys in the dictionary.
*
* @return {array} Returns all the keys.
*/
keys(): Array<string>;
/**
* Lists all the values in the dictionary.
*
* @return {array} Returns all the values.
*/
values(): Array<T>;
/**
* Get a shallow copy of the underlying map.
*
* @return {object} Returns the shallow copy of the map.
*/
clone(): Map<string, T>;
/**
* Number of items in the dictionary.
*
* @return {number} Returns the number of items in the dictionary.
*/
get count(): number;
private _validateKey;
}
}
declare module '@microsoft/office-js-helpers/helpers/dictionary.spec' {
export {};
}
declare module '@microsoft/office-js-helpers/helpers/storage' {
export enum StorageType {
LocalStorage = 0,
SessionStorage = 1,
InMemoryStorage = 2
}
export interface Subscription {
closed: boolean;
unsubscribe(): void;
}
/**
* Helper for creating and querying Local Storage or Session Storage.
* Uses {@link Dictionary} so all the data is encapsulated in a single
* storage namespace. Writes update the actual storage.
*/
export class Storage<T> {
container: string;
private _type;
private _storage;
private _observable;
private _containerRegex;
/**
* @constructor
* @param {string} container Container name to be created in the LocalStorage.
* @param {StorageType} type[optional] Storage Type to be used, defaults to Local Storage.
*/
constructor(container: string, _type?: StorageType);
/**
* Switch the storage type.
* Switches the storage type and then reloads the in-memory collection.
*
* @type {StorageType} type The desired storage to be used.
*/
switchStorage(type: StorageType): void;
/**
* Gets an item from the storage.
*
* @param {string} key The key of the item.
* @return {object} Returns an item if found.
*/
get(key: string): T;
/**
* Inserts an item into the storage.
* If an item already exists with the same key,
* it will be overridden by the new value.
*
* @param {string} key The key of the item.
* @param {object} value The item to be added.
* @return {object} Returns the added item.
*/
set(key: string, value: T): T;
/**
* Removes an item from the storage.
* Will throw if the key doesn't exist.
*
* @param {string} key The key of the item.
* @return {object} Returns the deleted item.
*/
delete(key: string): T;
/**
* Clear the storage.
*/
clear(): void;
/**
* Check if the storage contains the given key.
*
* @param {string} key The key of the item.
* @return {boolean} Returns true if the key was found.
*/
has(key: string): boolean;
/**
* Lists all the keys in the storage.
*
* @return {array} Returns all the keys.
*/
keys(): Array<string>;
/**
* Lists all the values in the storage.
*
* @return {array} Returns all the values.
*/
values(): Array<T>;
/**
* Number of items in the store.
*
* @return {number} Returns the number of items in the dictionary.
*/
get count(): number;
/**
* Clear all storages.
* Completely clears both the localStorage and sessionStorage.
*/
static clearAll(): void;
/**
* Returns an observable that triggers every time there's a Storage Event
* or if the collection is modified in a different tab.
*/
notify(next: () => void, error?: (error: any) => void, complete?: () => void): Subscription;
private _validateKey;
/**
* Determine if the value was a Date type and if so return a Date object instead.
* https://blog.mariusschulz.com/2016/04/28/deserializing-json-strings-as-javascript-date-objects
*/
private _reviver;
/**
* Scope the key to the container as @<container>/<key> so as to easily identify
* the item in localStorage and reduce collisions
* @param key key to be scoped
*/
private _scope;
}
}
declare module '@microsoft/office-js-helpers/helpers/storage.spec' {
export {};
}
declare module '@microsoft/office-js-helpers/helpers/utilities' {
import { CustomError } from '@microsoft/office-js-helpers/errors/custom/index';
/**
* Constant strings for the host types
*/
export const HostType: {
WEB: string;
ACCESS: string;
EXCEL: string;
ONENOTE: string;
OUTLOOK: string;
POWERPOINT: string;
PROJECT: string;
WORD: string;
};
/**
* Constant strings for the host platforms
*/
export const PlatformType: {
IOS: string;
MAC: string;
OFFICE_ONLINE: string;
PC: string;
};
/**
* Helper exposing useful Utilities for Office-Add-ins.
*/
export class Utilities {
/**
* A promise based helper for Office initialize.
* If Office.js was found, the 'initialize' event is waited for and
* the promise is resolved with the right reason.
*
* Else the application starts as a web application.
*/
static initialize(): Promise<string>;
static get host(): string;
static get platform(): string;
/**
* Utility to check if the code is running inside of an add-in.
*/
static get isAddin(): boolean;
/**
* Utility to check if the browser is IE11 or Edge.
*/
static get isIEOrEdge(): boolean;
/**
* Utility to generate crypto safe random numbers
*/
static generateCryptoSafeRandom(): number;
/**
* Utility to print prettified errors.
* If multiple parameters are sent then it just logs them instead.
*/
static log(exception: Error | CustomError | string, extras?: any, ...args: any[]): void;
}
}
declare module '@microsoft/office-js-helpers/index' {
export * from '@microsoft/office-js-helpers/errors/custom/index';
export * from '@microsoft/office-js-helpers/helpers/dialog';
export * from '@microsoft/office-js-helpers/helpers/utilities';
export * from '@microsoft/office-js-helpers/helpers/dictionary';
export * from '@microsoft/office-js-helpers/helpers/storage';
export * from '@microsoft/office-js-helpers/helpers/dialog';
export * from '@microsoft/office-js-helpers/authentication/token/index';
export * from '@microsoft/office-js-helpers/authentication/endpoint/index';
export * from '@microsoft/office-js-helpers/authentication/authenticator';
export * from '@microsoft/office-js-helpers/excel/utilities';
export { UI } from '@microsoft/office-js-helpers/ui/ui';
}
declare module '@microsoft/office-js-helpers/ui/ui' {
export interface IMessageBannerParams {
title?: string;
message?: string;
type: 'default' | 'success' | 'error' | 'warning' | 'severe-warning';
details?: string;
}
export class UI {
/** Shows a basic notification at the top of the page
* @param message - body of the notification
*/
static notify(message: string): any;
/** Shows a basic notification with a custom title at the top of the page
* @param message - body of the notification
* @param title - title of the notification
*/
static notify(message: string, title: string): any;
/** Shows a basic notification at the top of the page, with a background color set based on the type parameter
* @param message - body of the notification
* @param title - title of the notification
* @param type - type of the notification - see https://dev.office.com/fabric-js/Components/MessageBar/MessageBar.html#Variants
*/
static notify(message: string, title: string, type: 'default' | 'success' | 'error' | 'warning' | 'severe-warning'): any;
/** Shows a basic error notification at the top of the page
* @param error - Error object
*/
static notify(error: Error): any;
/** Shows a basic error notification with a custom title at the top of the page
* @param title - Title, bolded
* @param error - Error object
*/
static notify(error: Error, title: string): any;
/** Shows a basic notification at the top of the page
* @param message - The body of the notification
*/
static notify(message: any): any;
/** Shows a basic notification with a custom title at the top of the page
* @param message - body of the notification
* @param title - title of the notification
*/
static notify(message: any, title: string): any;
/** Shows a basic notification at the top of the page, with a background color set based on the type parameter
* @param message - body of the notification
* @param title - title of the notification
* @param type - type of the notification - see https://dev.office.com/fabric-js/Components/MessageBar/MessageBar.html#Variants
*/
static notify(message: any, title: string, type: 'default' | 'success' | 'error' | 'warning' | 'severe-warning'): any;
}
export function _parseNotificationParams(params: any[]): IMessageBannerParams;
}
declare module '@microsoft/office-js-helpers/ui/ui.spec' {
export {};
}
declare module '@microsoft/office-js-helpers/util/stringify' {
export function stringify(value: any): string;
}
declare module '@microsoft/office-js-helpers' {
import main = require('@microsoft/office-js-helpers/index');
export = main;
} | the_stack |
import Utils from './utils';
/* CONSTS */
const Consts = {
key2id: { // Map of lowercased supported characters to their internal id number
/* MODIFIERS */
alt: 0b1_00000000,
option: 0b1_00000000,
cmd: 0b10_00000000,
command: 0b10_00000000,
meta: 0b10_00000000,
ctrl: 0b100_00000000,
control: 0b100_00000000,
shift: 0b1000_00000000,
cmdorctrl: Utils.isMac ? 0b10_00000000 : 0b100_00000000,
commandorcontrol: Utils.isMac ? 0b10_00000000 : 0b100_00000000,
/* SPECIAL CHARACTERS */
backspace: 1,
capslock: 2,
del: 3,
delete: 3,
down: 4,
end: 5,
enter: 6,
return: 6,
esc: 7,
escape: 7,
home: 8,
insert: 9,
left: 10,
pagedown: 11,
pageup: 12,
right: 13,
space: 14,
spacebar: 14,
tab: 15,
up: 16,
/* DIGITS */
0: 17,
1: 18,
2: 19,
3: 20,
4: 21,
5: 22,
6: 23,
7: 24,
8: 25,
9: 26,
/* ALPHABET */
a: 27,
b: 28,
c: 29,
d: 30,
e: 31,
f: 32,
g: 33,
h: 34,
i: 35,
j: 36,
k: 37,
l: 38,
m: 39,
n: 40,
o: 41,
p: 42,
q: 43,
r: 44,
s: 45,
t: 46,
u: 47,
v: 48,
w: 49,
x: 50,
y: 51,
z: 52,
/* PUNCTUATION */
'!': 53,
'"': 54,
'#': 55,
'$': 56,
'%': 57,
'&': 58,
'\'': 59,
'(': 60,
')': 61,
'*': 62,
'+': 63,
plus: 63,
',': 64,
'-': 65,
'.': 66,
'/': 67,
':': 68,
';': 69,
'<': 70,
'=': 71,
'>': 72,
'?': 73,
'@': 74,
'[': 75,
'\\': 76,
']': 77,
'^': 78,
'_': 79,
'`': 80,
'{': 81,
'|': 82,
'}': 83,
'~': 84,
/* FUNCTION KEYS */
f1: 85,
f2: 86,
f3: 87,
f4: 88,
f5: 89,
f6: 90,
f7: 91,
f8: 92,
f9: 93,
f10: 94,
f11: 95,
f12: 96,
f13: 97,
f14: 98,
f15: 99,
f16: 100,
f17: 101,
f18: 102,
f19: 103,
f20: 104,
f21: 105,
f22: 106,
f23: 107,
f24: 108,
/* NUMPAD DIGITS */
numpad0: 109,
numpad1: 110,
numpad2: 111,
numpad3: 112,
numpad4: 113,
numpad5: 114,
numpad6: 115,
numpad7: 116,
numpad8: 117,
numpad9: 118
},
code2id: { // Map of supported key code to their internal id number //URL: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
/* MODIFIERS */
18: 0b1_00000000, // alt
91: 0b10_00000000, // cmd (OSLeft)
92: 0b10_00000000, // cmd (OSRight)
93: 0b10_00000000, // cmd (OSRight)
224: 0b10_00000000, // cmd (OSLeft/OSRight)
17: 0b100_00000000, // ctrl
16: 0b1000_00000000, // shift
/* SPECIAL CHARACTERS */
8: 1, // backspace
20: 2, // capslock
46: 3, // delete
40: 4, // down
35: 5, // end
13: 6, // return
27: 7, // escape
36: 8, // home
45: 9, // insert
37: 10, // left
34: 11, // pagedown
33: 12, // pageup
39: 13, // right
32: 14, // space
9: 15, // tab
38: 16, // up
/* PUNCTUATION */ // Ensuring Shift+Punctuation works more reliably
222: 59, // '
188: 64, // ,
189: 65, // -
190: 66, // .
191: 67, // /
186: 69, // ;
187: 71, // =
219: 75, // [
220: 76, // \
221: 77, // ]
192: 80, // `
/* FUNCTION KEYS */
112: 85, // f1
113: 86, // f2
114: 87, // f3
115: 88, // f4
116: 89, // f5
117: 90, // f6
118: 91, // f7
119: 92, // f8
120: 93, // f9
121: 94, // f10
122: 95, // f11
123: 96, // f12
124: 97, // f13
125: 98, // f14
126: 99, // f15
127: 100, // f16
128: 101, // f17
129: 102, // f18
130: 103, // f19
131: 104, // f20
132: 105, // f21
133: 106, // f22
134: 107, // f23
135: 108, // f24
/* NUMPAD DIGITS */
96: 109, // numpad0
97: 110, // numpad1
98: 111, // numpad2
99: 112, // numpad3
100: 113, // numpad4
101: 114, // numpad5
102: 115, // numpad6
103: 116, // numpad7
104: 117, // numpad8
105: 118 // numpad9
},
id2shortcut: { // Map of id numbers to their shortcut string
/* MODIFIERS */
0b1_00000000: 'Alt',
0b10_00000000: 'Cmd',
0b100_00000000: 'Ctrl',
0b1000_00000000: 'Shift',
/* SPECIAL CHARACTERS */
1: 'Backspace',
2: 'Capslock',
3: 'Delete',
4: 'Down',
5: 'End',
6: 'Enter',
7: 'Escape',
8: 'Home',
9: 'Insert',
10: 'Left',
11: 'PageDown',
12: 'PageUp',
13: 'Right',
14: 'Space',
15: 'Tab',
16: 'Up',
/* DIGITS */
17: '0',
18: '1',
19: '2',
20: '3',
21: '4',
22: '5',
23: '6',
24: '7',
25: '8',
26: '9',
/* ALPHABET */
27: 'A',
28: 'B',
29: 'C',
30: 'D',
31: 'E',
32: 'F',
33: 'G',
34: 'H',
35: 'I',
36: 'J',
37: 'K',
38: 'L',
39: 'M',
40: 'N',
41: 'O',
42: 'P',
43: 'Q',
44: 'R',
45: 'S',
46: 'T',
47: 'U',
48: 'V',
49: 'W',
50: 'X',
51: 'Y',
52: 'Z',
/* PUNCTUATION */
53: '!',
54: '"',
55: '#',
56: '$',
57: '%',
58: '&',
59: '\'',
60: '(',
61: ')',
62: '*',
63: 'Plus',
64: ',',
65: '-',
66: '.',
67: '/',
68: ':',
69: ';',
70: '<',
71: '=',
72: '>',
73: '?',
74: '@',
75: '[',
76: '\\',
77: ']',
78: '^',
79: '_',
80: '`',
81: '{',
82: '|',
83: '}',
84: '~',
/* FUNCTION KEYS */
85: 'F1',
86: 'F2',
87: 'F3',
88: 'F4',
89: 'F5',
90: 'F6',
91: 'F7',
92: 'F8',
93: 'F9',
94: 'F10',
95: 'F11',
96: 'F12',
97: 'F13',
98: 'F14',
99: 'F15',
100: 'F16',
101: 'F17',
102: 'F18',
103: 'F19',
104: 'F20',
105: 'F21',
106: 'F22',
107: 'F23',
108: 'F24',
/* NUMPAD DIGITS */
109: 'Numpad0',
110: 'Numpad1',
111: 'Numpad2',
112: 'Numpad3',
113: 'Numpad4',
114: 'Numpad5',
115: 'Numpad6',
116: 'Numpad7',
117: 'Numpad8',
118: 'Numpad9'
},
id2accelerator: { // Map of id numbers to their Electron's accelerator representation
/* MODIFIERS */
0b1_00000000: 'Alt',
0b10_00000000: 'Cmd',
0b100_00000000: 'Ctrl',
0b1000_00000000: 'Shift',
/* SPECIAL CHARACTERS */
1: 'Backspace',
2: 'Capslock',
3: 'Delete',
4: 'Down',
5: 'End',
6: 'Enter',
7: 'Escape',
8: 'Home',
9: 'Insert',
10: 'Left',
11: 'PageDown',
12: 'PageUp',
13: 'Right',
14: 'Space',
15: 'Tab',
16: 'Up',
/* DIGITS */
17: '0',
18: '1',
19: '2',
20: '3',
21: '4',
22: '5',
23: '6',
24: '7',
25: '8',
26: '9',
/* ALPHABET */
27: 'A',
28: 'B',
29: 'C',
30: 'D',
31: 'E',
32: 'F',
33: 'G',
34: 'H',
35: 'I',
36: 'J',
37: 'K',
38: 'L',
39: 'M',
40: 'N',
41: 'O',
42: 'P',
43: 'Q',
44: 'R',
45: 'S',
46: 'T',
47: 'U',
48: 'V',
49: 'W',
50: 'X',
51: 'Y',
52: 'Z',
/* PUNCTUATION */
53: '!',
54: '"',
55: '#',
56: '$',
57: '%',
58: '&',
59: '\'',
60: '(',
61: ')',
62: '*',
63: 'Plus',
64: ',',
65: '-',
66: '.',
67: '/',
68: ':',
69: ';',
70: '<',
71: '=',
72: '>',
73: '?',
74: '@',
75: '[',
76: '\\',
77: ']',
78: '^',
79: '_',
80: '`',
81: '{',
82: '|',
83: '}',
84: '~',
/* FUNCTION KEYS */
85: 'F1',
86: 'F2',
87: 'F3',
88: 'F4',
89: 'F5',
90: 'F6',
91: 'F7',
92: 'F8',
93: 'F9',
94: 'F10',
95: 'F11',
96: 'F12',
97: 'F13',
98: 'F14',
99: 'F15',
100: 'F16',
101: 'F17',
102: 'F18',
103: 'F19',
104: 'F20',
105: 'F21',
106: 'F22',
107: 'F23',
108: 'F24',
/* NUMPAD DIGITS */
109: 'num0',
110: 'num1',
111: 'num2',
112: 'num3',
113: 'num4',
114: 'num5',
115: 'num6',
116: 'num7',
117: 'num8',
118: 'num9'
},
id2symbol: { // Map of id numbers to their symbol representation
/* MODIFIERS */
0b1_00000000: '⌥', // alt
0b10_00000000: '⌘', // cmd
0b100_00000000: '⌃', // ctrl
0b1000_00000000: '⇧', // shift
/* SPECIAL CHARACTERS */
1: '⌫', // backspace
2: '⇪', // capslock
3: '⌦', // delete
4: '↓', // down
5: '↘', // end
6: '⏎', // enter
7: '⎋', // escape
8: '↖', // home
9: '⎀', // insert
10: '←', // left
11: '⇟', // pagedown
12: '⇞', // pageup
13: '→', // right
14: '␣', // space
15: '⇥', // tab
16: '↑', // up
/* DIGITS */
17: '0', // 0
18: '1', // 1
19: '2', // 2
20: '3', // 3
21: '4', // 4
22: '5', // 5
23: '6', // 6
24: '7', // 7
25: '8', // 8
26: '9', // 9
/* ALPHABET */
27: 'A', // a
28: 'B', // b
29: 'C', // c
30: 'D', // d
31: 'E', // e
32: 'F', // f
33: 'G', // g
34: 'H', // h
35: 'I', // i
36: 'J', // j
37: 'K', // k
38: 'L', // l
39: 'M', // m
40: 'N', // n
41: 'O', // o
42: 'P', // p
43: 'Q', // q
44: 'R', // r
45: 'S', // s
46: 'T', // t
47: 'U', // u
48: 'V', // v
49: 'W', // w
50: 'X', // x
51: 'Y', // y
52: 'Z', // z
/* PUNCTUATION */
53: '!', // !
54: '"', // "
55: '#', // #
56: '$', // $
57: '%', // %
58: '&', // &
59: '\'', // '
60: '(', // (
61: ')', // )
62: '*', // *
63: '+', // plus
64: ',', // ,
65: '-', // -
66: '.', // .
67: '/', // /
68: ':', // :
69: ';', // ;
70: '<', // <
71: '=', // =
72: '>', // >
73: '?', // ?
74: '@', // @
75: '[', // [
76: '\\', // \
77: ']', // ]
78: '^', // ^
79: '_', // _
80: '`', // `
81: '{', // {
82: '|', // |
83: '}', // }
84: '~', // ~
/* FUNCTION KEYS */
85: 'F1', // f1
86: 'F2', // f2
87: 'F3', // f3
88: 'F4', // f4
89: 'F5', // f5
90: 'F6', // f6
91: 'F7', // f7
92: 'F8', // f8
93: 'F9', // f9
94: 'F10', // f10
95: 'F11', // f11
96: 'F12', // f12
97: 'F13', // f13
98: 'F14', // f14
99: 'F15', // f15
100: 'F16', // f16
101: 'F17', // f17
102: 'F18', // f18
103: 'F19', // f19
104: 'F20', // f20
105: 'F21', // f21
106: 'F22', // f22
107: 'F23', // f23
108: 'F24', // f24
/* NUMPAD DIGITS */
109: 'Numpad0', // numpad0
110: 'Numpad1', // numpad1
111: 'Numpad2', // numpad2
112: 'Numpad3', // numpad3
113: 'Numpad4', // numpad4
114: 'Numpad5', // numpad5
115: 'Numpad6', // numpad6
116: 'Numpad7', // numpad7
117: 'Numpad8', // numpad8
118: 'Numpad9' // numpad9
},
modifierKeyBitmask: 0b11111111_00000000, // Bitmask that includes all modifier keys and none of the triggers
triggerKeyBitmask: 0b11111111, // Bitmask that includes all trigger keys and none of the modifiers
shortcutRe: /^\s*?(?:(?:^|\s|\+)(?:alt|option|cmd|command|meta|ctrl|control|shift|cmdorctrl|commandorcontrol|backspace|capslock|del|delete|down|end|enter|return|esc|escape|home|insert|left|pagedown|pageup|right|space|spacebar|tab|up|plus|\d|[a-z]|f(?:\d|1\d|2[0-4])|numpad\d|[!"#$%&'()*+,./:;<=>?@[\]^_`{|}~-]))+\s*$/i // Regex that matches a shortcut
};
/* EXPORT */
export default Consts; | the_stack |
export { flatbuffers };
declare global {
namespace flatbuffers {
type Offset = number;
interface Table {
bb: ByteBuffer|null;
bb_pos: number;
}
const SIZEOF_SHORT: number;
const SIZEOF_INT: number;
const FILE_IDENTIFIER_LENGTH: number;
const SIZE_PREFIX_LENGTH: number;
enum Encoding { UTF8_BYTES, UTF16_STRING }
const int32: Int32Array;
const float32: Float32Array;
const float64: Float64Array;
const isLittleEndian: boolean;
////////////////////////////////////////////////////////////////////////////////
class Long {
low: number;
high: number;
static ZERO: Long;
constructor(low: number, high: number);
toFloat64(): number;
equals(other: any): boolean;
static create(low: number, high: number): Long;
}
////////////////////////////////////////////////////////////////////////////////
class Builder {
constructor(initial_size?: number);
/**
* Reset all the state in this FlatBufferBuilder
* so it can be reused to construct another buffer.
*/
clear(): void;
/**
* In order to save space, fields that are set to their default value
* don't get serialized into the buffer. Forcing defaults provides a
* way to manually disable this optimization.
*
* @param forceDefaults true always serializes default values
*/
forceDefaults(forceDefaults: boolean): void;
/**
* Get the ByteBuffer representing the FlatBuffer. Only call this after you've
* called finish(). The actual data starts at the ByteBuffer's current position,
* not necessarily at 0.
*/
dataBuffer(): ByteBuffer;
/**
* Get the ByteBuffer representing the FlatBuffer. Only call this after you've
* called finish(). The actual data starts at the ByteBuffer's current position,
* not necessarily at 0.
*/
asUint8Array(): Uint8Array;
/**
* Prepare to write an element of `size` after `additional_bytes` have been
* written, e.g. if you write a string, you need to align such the int length
* field is aligned to 4 bytes, and the string data follows it directly. If all
* you need to do is alignment, `additional_bytes` will be 0.
*
* @param size This is the of the new element to write
* @param additional_bytes The padding size
*/
prep(size: number, additional_bytes: number): void;
pad(byte_size: number): void;
writeInt8(value: number): void;
writeInt16(value: number): void;
writeInt32(value: number): void;
writeInt64(value: Long): void;
writeFloat32(value: number): void;
writeFloat64(value: number): void;
addInt8(value: number): void;
addInt16(value: number): void;
addInt32(value: number): void;
addInt64(value: Long): void;
addFloat32(value: number): void;
addFloat64(value: number): void;
addFieldInt8(voffset: number, value: number, defaultValue: number): void;
addFieldInt16(voffset: number, value: number, defaultValue: number): void;
addFieldInt32(voffset: number, value: number, defaultValue: number): void;
addFieldInt64(voffset: number, value: Long, defaultValue: Long): void;
addFieldFloat32(voffset: number, value: number, defaultValue: number): void;
addFieldFloat64(voffset: number, value: number, defaultValue: number): void;
addFieldOffset(voffset: number, value: Offset, defaultValue: Offset): void;
/**
* Structs are stored inline, so nothing additional is being added. `d` is always 0.
*/
addFieldStruct(voffset: number, value: Offset, defaultValue: Offset): void;
/**
* Structures are always stored inline, they need to be created right
* where they're used. You'll get this assertion failure if you
* created it elsewhere.
*
* @param obj The offset of the created object
*/
nested(obj: Offset): void;
/**
* Should not be creating any other object, string or vector
* while an object is being constructed
*/
notNested(): void;
/**
* Set the current vtable at `voffset` to the current location in the buffer.
*/
slot(voffset: number): void;
/**
* @returns Offset relative to the end of the buffer.
*/
offset(): Offset;
/**
* Doubles the size of the backing ByteBuffer and copies the old data towards
* the end of the new buffer (since we build the buffer backwards).
*
* @param bb The current buffer with the existing data
* @returns A new byte buffer with the old data copied
* to it. The data is located at the end of the buffer.
*/
static growByteBuffer(bb: ByteBuffer): ByteBuffer;
/**
* Adds on offset, relative to where it will be written.
*
* @param offset The offset to add
*/
addOffset(offset: Offset): void;
/**
* Start encoding a new object in the buffer. Users will not usually need to
* call this directly. The FlatBuffers compiler will generate helper methods
* that call this method internally.
*/
startObject(numfields: number): void;
/**
* Finish off writing the object that is under construction.
*
* @returns The offset to the object inside `dataBuffer`
*/
endObject(): Offset;
finish(root_table: Offset, file_identifier?: string, size_prefix?: boolean): void;
finishSizePrefixed(root_table: Offset, file_identifier?: string): void;
/**
* This checks a required field has been set in a given table that has
* just been constructed.
*/
requiredField(table: Offset, field: number): void;
/**
* Start a new array/vector of objects. Users usually will not call
* this directly. The FlatBuffers compiler will create a start/end
* method for vector types in generated code.
*
* @param elem_size The size of each element in the array
* @param num_elems The number of elements in the array
* @param alignment The alignment of the array
*/
startVector(elem_size: number, num_elems: number, alignment: number): void;
/**
* Finish off the creation of an array and all its elements. The array must be
* created with `startVector`.
*
* @returns The offset at which the newly created array
* starts.
*/
endVector(): Offset;
/**
* Encode the string `s` in the buffer using UTF-8. If a Uint8Array is passed
* instead of a string, it is assumed to contain valid UTF-8 encoded data.
*
* @param s The string to encode
* @return The offset in the buffer where the encoded string starts
*/
createString(s: string|Uint8Array): Offset;
/**
* Convenience function for creating Long objects.
*/
createLong(low: number, high: number): Long;
}
////////////////////////////////////////////////////////////////////////////////
class ByteBuffer {
constructor(bytes: Uint8Array);
static allocate(byte_size: number): ByteBuffer;
clear(): void;
bytes(): Uint8Array;
position(): number;
setPosition(position: number): void;
capacity(): number;
readInt8(offset: number): number;
readUint8(offset: number): number;
readInt16(offset: number): number;
readUint16(offset: number): number;
readInt32(offset: number): number;
readUint32(offset: number): number;
readInt64(offset: number): Long;
readUint64(offset: number): Long;
readFloat32(offset: number): number;
readFloat64(offset: number): number;
writeInt8(offset: number, value: number): void;
writeUint8(offset: number, value: number): void;
writeInt16(offset: number, value: number): void;
writeUint16(offset: number, value: number): void;
writeInt32(offset: number, value: number): void;
writeUint32(offset: number, value: number): void;
writeInt64(offset: number, value: Long): void;
writeUint64(offset: number, value: Long): void;
writeFloat32(offset: number, value: number): void;
writeFloat64(offset: number, value: number): void;
getBufferIdentifier(): string;
/**
* Look up a field in the vtable, return an offset into the object, or 0 if the
* field is not present.
*/
__offset(bb_pos: number, vtable_offset: number): number;
/**
* Initialize any Table-derived type to point to the union at the given offset.
*/
__union<T extends Table>(t: T, offset: number): T;
/**
* Create a JavaScript string from UTF-8 data stored inside the FlatBuffer.
* This allocates a new string and converts to wide chars upon each access.
*
* To avoid the conversion to UTF-16, pass flatbuffers.Encoding.UTF8_BYTES as
* the "optionalEncoding" argument. This is useful for avoiding conversion to
* and from UTF-16 when the data will just be packaged back up in another
* FlatBuffer later on.
*
* @param optionalEncoding Defaults to UTF16_STRING
*/
__string(offset: number, optionalEncoding?: Encoding): string|Uint8Array;
/**
* Retrieve the relative offset stored at "offset"
*/
__indirect(offset: number): number;
/**
* Get the start of data of a vector whose offset is stored at "offset" in this object.
*/
__vector(offset: number): number;
/**
* Get the length of a vector whose offset is stored at "offset" in this object.
*/
__vector_len(offset: number): number;
__has_identifier(ident: string): boolean;
/**
* Convenience function for creating Long objects.
*/
createLong(low: number, high: number): Long;
}
}
} | the_stack |
export interface SyncProxyOrganizationResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 创建流程签署人入参
*/
export interface FlowApproverInfo {
/**
* 签署人姓名
*/
Name: string;
/**
* 签署人手机号,脱敏显示
*/
Mobile: string;
/**
* 经办人身份证号
*/
IdCardNumber?: string;
/**
* 签署完前端跳转的url,暂未使用
*/
JumpUrl?: string;
/**
* 签署截止时间
*/
Deadline?: number;
/**
* 签署完回调url
*/
CallbackUrl?: string;
/**
* 签署人类型,PERSON和ORGANIZATION
*/
ApproverType?: string;
/**
* 用户侧第三方id
*/
OpenId?: string;
}
/**
* PrepareFlows返回参数结构体
*/
export interface PrepareFlowsResponse {
/**
* 待发起文件确认页
*/
ConfirmUrl: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 此结构体 (TemplateInfo) 用于描述模板的信息。
*/
export interface TemplateInfo {
/**
* 模板ID
*/
TemplateId: string;
/**
* 模板名字
*/
TemplateName: string;
/**
* 模板描述信息
*/
Description: string;
/**
* 模板控件信息结构
*/
Components: Array<Component>;
/**
* 签署区模板信息结构
*/
SignComponents: Array<Component>;
/**
* 模板的创建者信息
*/
Creator: string;
/**
* 模板创建的时间戳(精确到秒)
*/
CreatedOn: number;
/**
* 模板类型:1-静默签;2-静默签授权;3-普通模版
*/
TemplateType: number;
/**
* 模板中的流程参与人信息
*/
Recipients: Array<Recipient>;
}
/**
* DescribeTemplates返回参数结构体
*/
export interface DescribeTemplatesResponse {
/**
* 模板详情
*/
Templates: Array<TemplateInfo>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* SyncProxyOrganizationOperators请求参数结构体
*/
export interface SyncProxyOrganizationOperatorsRequest {
/**
* 操作类型,新增:"CREATE",修改:"UPDATE",离职:"RESIGN"
*/
OperatorType: string;
/**
* 应用信息
*/
Agent: Agent;
/**
* 经办人信息列表
*/
ProxyOrganizationOperators: Array<ProxyOrganizationOperator>;
/**
* 操作者的信息
*/
Operator?: UserInfo;
}
/**
* CreateSignUrls请求参数结构体
*/
export interface CreateSignUrlsRequest {
/**
* 渠道应用相关信息
*/
Agent: Agent;
/**
* 所签署合同ID数组
*/
FlowIds: Array<string>;
/**
* 操作者的信息
*/
Operator?: UserInfo;
/**
* 签署链接类型,默认:“WEIXINAPP”-直接跳小程序; “CHANNEL”-跳转H5页面; “APP”-第三方APP或小程序跳转电子签小程序;
*/
Endpoint?: string;
/**
* 签署完成后H5引导页跳转URL
*/
JumpUrl?: string;
}
/**
* 此结构体 (Component) 用于描述控件属性。
*/
export interface Component {
/**
* 控件编号
注:
当GenerateMode=3时,通过"^"来决定是否使用关键字整词匹配能力。
例:
当GenerateMode=3时,如果传入关键字"^甲方签署^",则会在PDF文件中有且仅有"甲方签署"关键字的地方进行对应操作。
如传入的关键字为"甲方签署",则PDF文件中每个出现关键字的位置都会执行相应操作。
创建控件时,此值为空
查询时返回完整结构
*/
ComponentId?: string;
/**
* 如果是Component控件类型,则可选的字段为:
TEXT - 普通文本控件;
DATE - 普通日期控件;跟TEXT相比会有校验逻辑
如果是SignComponent控件类型,则可选的字段为
SIGN_SEAL - 签署印章控件;
SIGN_DATE - 签署日期控件;
SIGN_SIGNATURE - 用户签名控件;
SIGN_PERSONAL_SEAL - 个人签署印章控件;
表单域的控件不能作为印章和签名控件
*/
ComponentType?: string;
/**
* 控件简称
*/
ComponentName?: string;
/**
* 定义控件是否为必填项,默认为false
*/
ComponentRequired?: boolean;
/**
* 控件所属文件的序号 (文档中文件的排列序号)
*/
FileIndex?: number;
/**
* 控件生成的方式:
NORMAL - 普通控件
FIELD - 表单域
KEYWORD - 关键字
*/
GenerateMode?: string;
/**
* 参数控件宽度,默认100,单位px
表单域和关键字转换控件不用填
*/
ComponentWidth?: number;
/**
* 参数控件高度,默认100,单位px
表单域和关键字转换控件不用填
*/
ComponentHeight?: number;
/**
* 参数控件所在页码
*/
ComponentPage?: number;
/**
* 参数控件X位置,单位px
*/
ComponentPosX?: number;
/**
* 参数控件Y位置,单位px
*/
ComponentPosY?: number;
/**
* 参数控件样式,json格式表述
不同类型的控件会有部分非通用参数
TEXT控件可以指定字体
例如:{"FontSize":12}
*/
ComponentExtra?: string;
/**
* 印章 ID,传参 DEFAULT_COMPANY_SEAL 表示使用默认印章。
控件填入内容,印章控件里面,如果是手写签名内容为PNG图片格式的base64编码
*/
ComponentValue?: string;
/**
* 日期签署控件的字号,默认为 12
签署区日期控件会转换成图片格式并带存证,需要通过字体决定图片大小
*/
ComponentDateFontSize?: number;
/**
* 控件所属文档的Id, 模块相关接口为空值
*/
DocumentId?: string;
/**
* 控件描述
*/
ComponentDescription?: string;
}
/**
* 签署链接内容
*/
export interface SignUrlInfo {
/**
* 签署链接
注意:此字段可能返回 null,表示取不到有效值。
*/
SignUrl: string;
/**
* 链接失效时间
注意:此字段可能返回 null,表示取不到有效值。
*/
Deadline: number;
/**
* 当流程为顺序签署此参数有效时,数字越小优先级越高,暂不支持并行签署 可选
注意:此字段可能返回 null,表示取不到有效值。
*/
SignOrder: number;
/**
* 签署人编号
注意:此字段可能返回 null,表示取不到有效值。
*/
SignId: string;
/**
* 自定义用户编号
注意:此字段可能返回 null,表示取不到有效值。
*/
CustomUserId: string;
/**
* 用户姓名
注意:此字段可能返回 null,表示取不到有效值。
*/
Name: string;
/**
* 用户手机号码
注意:此字段可能返回 null,表示取不到有效值。
*/
Mobile: string;
/**
* 签署参与者机构名字
注意:此字段可能返回 null,表示取不到有效值。
*/
OrganizationName: string;
/**
* 参与者类型:
ORGANIZATION 企业经办人
PERSON 自然人
注意:此字段可能返回 null,表示取不到有效值。
*/
ApproverType: string;
/**
* 经办人身份证号
注意:此字段可能返回 null,表示取不到有效值。
*/
IdCardNumber: string;
/**
* 签署链接对应流程Id
注意:此字段可能返回 null,表示取不到有效值。
*/
FlowId: string;
/**
* 企业经办人 用户在渠道的编号
注意:此字段可能返回 null,表示取不到有效值。
*/
OpenId: string;
}
/**
* CreateConsoleLoginUrl请求参数结构体
*/
export interface CreateConsoleLoginUrlRequest {
/**
* 应用信息
此接口Agent.ProxyOrganizationOpenId 和 Agent. ProxyOperator.OpenId 必填
*/
Agent: Agent;
/**
* 渠道侧合作企业名称
*/
ProxyOrganizationName: string;
/**
* 渠道侧合作企业统一社会信用代码
*/
UniformSocialCreditCode?: string;
/**
* 渠道侧合作企业经办人的姓名
*/
ProxyOperatorName?: string;
/**
* 操作者的信息
*/
Operator?: UserInfo;
/**
* 控制台指定模块,文件/合同管理:"DOCUMENT",模版管理:"TEMPLATE",印章管理:"SEAL",组织架构/人员:"OPERATOR",空字符串:"账号信息"
*/
Module?: string;
/**
* 控制台指定模块Id
*/
ModuleId?: string;
}
/**
* CreateFlowsByTemplates返回参数结构体
*/
export interface CreateFlowsByTemplatesResponse {
/**
* 多个合同ID
*/
FlowIds: Array<string>;
/**
* 渠道的业务信息,限制1024字符
*/
CustomerData: Array<string>;
/**
* 创建消息,对应多个合同ID,
成功为“”,创建失败则对应失败消息
*/
ErrorMessages: Array<string>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 合作企业经办人列表信息
*/
export interface ProxyOrganizationOperator {
/**
* 经办人ID(渠道颁发)
*/
Id: string;
/**
* 经办人姓名
*/
Name?: string;
/**
* 经办人身份证件类型
用户证件类型:默认ID_CARD
1. ID_CARD - 居民身份证
2. HOUSEHOLD_REGISTER - 户口本
3. TEMP_ID_CARD - 临时居民身份证
*/
IdCardType?: string;
/**
* 经办人身份证号
*/
IdCardNumber?: string;
/**
* 经办人手机号
*/
Mobile?: string;
}
/**
* SyncProxyOrganizationOperators返回参数结构体
*/
export interface SyncProxyOrganizationOperatorsResponse {
/**
* Status 同步状态,全部同步失败接口会直接报错
1-成功
2-部分成功
注意:此字段可能返回 null,表示取不到有效值。
*/
Status: number;
/**
* 同步失败经办人及其失败原因
注意:此字段可能返回 null,表示取不到有效值。
*/
FailedList: Array<SyncFailReason>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeTemplates请求参数结构体
*/
export interface DescribeTemplatesRequest {
/**
* 渠道应用相关信息
*/
Agent: Agent;
/**
* 操作者的信息
*/
Operator?: UserInfo;
/**
* 模版唯一标识
*/
TemplateId?: string;
}
/**
* CreateConsoleLoginUrl返回参数结构体
*/
export interface CreateConsoleLoginUrlResponse {
/**
* 控制台url
*/
ConsoleUrl: string;
/**
* 渠道合作企业是否认证开通腾讯电子签。
当渠道合作企业未完成认证开通腾讯电子签,建议先调用同步企业信息(SyncProxyOrganization)和同步经办人信息(SyncProxyOrganizationOperators)接口成功后再跳转到登录页面。
*/
IsActivated: boolean;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateFlowsByTemplates请求参数结构体
*/
export interface CreateFlowsByTemplatesRequest {
/**
* 渠道应用相关信息
*/
Agent: Agent;
/**
* 多个合同(流程)信息
*/
FlowInfos: Array<FlowInfo>;
/**
* 操作者的信息
*/
Operator?: UserInfo;
}
/**
* SyncProxyOrganization请求参数结构体
*/
export interface SyncProxyOrganizationRequest {
/**
* 应用信息
此接口Agent.ProxyOrganizationOpenId必填
*/
Agent: Agent;
/**
* 渠道侧合作企业名称
*/
ProxyOrganizationName: string;
/**
* 渠道侧合作企业统一社会信用代码
*/
UniformSocialCreditCode?: string;
/**
* 营业执照正面照(PNG或JPG) base64格式, 大小不超过5M
*/
BusinessLicense?: string;
/**
* 操作者的信息
*/
Operator?: UserInfo;
}
/**
* PrepareFlows请求参数结构体
*/
export interface PrepareFlowsRequest {
/**
* 渠道应用相关信息
*/
Agent: Agent;
/**
* 多个合同(流程)信息
*/
FlowInfos: Array<FlowInfo>;
/**
* 操作完成后的跳转地址
*/
JumpUrl: string;
/**
* 操作者的信息
*/
Operator?: UserInfo;
}
/**
* 用量明细
*/
export interface UsageDetail {
/**
* 渠道侧合作企业唯一标识
*/
ProxyOrganizationOpenId: string;
/**
* 消耗量
*/
Usage: number;
/**
* 日期,当需要汇总数据时日期为空
注意:此字段可能返回 null,表示取不到有效值。
*/
Date: string;
}
/**
* CreateSignUrls返回参数结构体
*/
export interface CreateSignUrlsResponse {
/**
* 签署参与者签署H5链接信息数组
*/
SignUrlInfos: Array<SignUrlInfo>;
/**
* 生成失败时的错误信息,成功返回”“,顺序和出参SignUrlInfos保持一致
*/
ErrorMessages: Array<string>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 同步经办人失败原因
*/
export interface SyncFailReason {
/**
* 经办人Id
*/
Id: string;
/**
* 失败原因
例如:Id不符合规范、证件号码不合法等
注意:此字段可能返回 null,表示取不到有效值。
*/
Message: string;
}
/**
* DescribeUsage请求参数结构体
*/
export interface DescribeUsageRequest {
/**
* 应用信息
*/
Agent: Agent;
/**
* 开始时间 eg:2021-03-21
*/
StartDate: string;
/**
* 结束时间 eg:2021-06-21
开始时间到结束时间的区间长度小于等于90天
*/
EndDate: string;
/**
* 操作者的信息
*/
Operator?: UserInfo;
/**
* 是否汇总数据,默认不汇总
不汇总:返回在统计区间内渠道下所有企业的每日明细,即每个企业N条数据,N为统计天数
汇总:返回在统计区间内渠道下所有企业的汇总后数据,即每个企业一条数据
*/
NeedAggregate?: boolean;
/**
* 单次返回的最多条目数量,默认为1000,且不能超过1000
*/
Limit?: number;
/**
* 偏移量,默认是0
*/
Offset?: number;
}
/**
* 签署参与者信息
*/
export interface Recipient {
/**
* 签署人唯一标识
*/
RecipientId?: string;
/**
* 签署方类型:ENTERPRISE-企业INDIVIDUAL-自然人
*/
RecipientType?: string;
/**
* 描述
*/
Description?: string;
/**
* 签署方备注信息
*/
RoleName?: string;
/**
* 是否需要校验
*/
RequireValidation?: boolean;
/**
* 是否必须填写
*/
RequireSign?: boolean;
/**
* 签署类型
*/
SignType?: number;
/**
* 签署顺序:数字越小优先级越高
*/
RoutingOrder?: number;
}
/**
* 应用相关信息
*/
export interface Agent {
/**
* 腾讯电子签颁发给渠道的应用ID,32位字符串
*/
AppId: string;
/**
* 腾讯电子签颁发给渠道侧合作企业的企业ID
*/
ProxyOrganizationId?: string;
/**
* 腾讯电子签颁发给渠道侧合作企业的应用ID
*/
ProxyAppId?: string;
/**
* 渠道/平台合作企业经办人(操作员)
*/
ProxyOperator?: UserInfo;
/**
* 渠道/平台合作企业的企业ID
*/
ProxyOrganizationOpenId?: string;
}
/**
* 此结构 (FormField) 用于描述内容控件填充结构。
*/
export interface FormField {
/**
* 表单域或控件的Value
*/
ComponentValue: string;
/**
* 表单域或控件的ID,跟ComponentName二选一,不能全为空
注意:此字段可能返回 null,表示取不到有效值。
*/
ComponentId?: string;
/**
* 控件的名字,跟ComponentId二选一,不能全为空
注意:此字段可能返回 null,表示取不到有效值。
*/
ComponentName?: string;
}
/**
* 此结构体 (FlowInfo) 用于描述流程信息。
*/
export interface FlowInfo {
/**
* 合同名字
*/
FlowName: string;
/**
* 签署截止时间戳,超过有效签署时间则该签署流程失败
*/
Deadline: number;
/**
* 模版ID
*/
TemplateId?: string;
/**
* 合同类型:
1. “劳务”
2. “销售”
3. “租赁”
4. “其他”
*/
FlowType?: string;
/**
* 回调地址
*/
CallbackUrl?: string;
/**
* 多个签署人信息
*/
FlowApprovers?: Array<FlowApproverInfo>;
/**
* 表单K-V对列表
*/
FormFields?: Array<FormField>;
/**
* 合同描述
*/
FlowDescription?: string;
/**
* 渠道的业务信息,限制1024字符
*/
CustomerData?: string;
}
/**
* 接口调用者信息
*/
export interface UserInfo {
/**
* 自定义用户编号
*/
CustomUserId?: string;
/**
* 用户的来源渠道
*/
Channel?: string;
/**
* 用户在渠道的编号
*/
OpenId?: string;
/**
* 用户真实IP
*/
ClientIp?: string;
/**
* 用户代理IP
*/
ProxyIp?: string;
}
/**
* DescribeUsage返回参数结构体
*/
export interface DescribeUsageResponse {
/**
* 用量明细条数
*/
Total: number;
/**
* 用量明细
注意:此字段可能返回 null,表示取不到有效值。
*/
Details: Array<UsageDetail>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: 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 a resource to create an AWS Firewall Manager policy. You need to be using AWS organizations and have enabled the Firewall Manager administrator account.
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const exampleRuleGroup = new aws.wafregional.RuleGroup("exampleRuleGroup", {metricName: "WAFRuleGroupExample"});
* const examplePolicy = new aws.fms.Policy("examplePolicy", {
* excludeResourceTags: false,
* remediationEnabled: false,
* resourceTypeLists: ["AWS::ElasticLoadBalancingV2::LoadBalancer"],
* securityServicePolicyData: {
* type: "WAF",
* managedServiceData: exampleRuleGroup.id.apply(id => JSON.stringify({
* type: "WAF",
* ruleGroups: [{
* id: id,
* overrideAction: {
* type: "COUNT",
* },
* }],
* defaultAction: {
* type: "BLOCK",
* },
* overrideCustomerWebACLAssociation: false,
* })),
* },
* });
* ```
*
* ## Import
*
* Firewall Manager policies can be imported using the policy ID, e.g.
*
* ```sh
* $ pulumi import aws:fms/policy:Policy example 5be49585-a7e3-4c49-dde1-a179fe4a619a
* ```
*/
export class Policy extends pulumi.CustomResource {
/**
* Get an existing Policy 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?: PolicyState, opts?: pulumi.CustomResourceOptions): Policy {
return new Policy(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'aws:fms/policy:Policy';
/**
* Returns true if the given object is an instance of Policy. 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 Policy {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === Policy.__pulumiType;
}
public /*out*/ readonly arn!: pulumi.Output<string>;
/**
* If true, the request will also perform a clean-up process. Defaults to `true`. More information can be found here [AWS Firewall Manager delete policy](https://docs.aws.amazon.com/fms/2018-01-01/APIReference/API_DeletePolicy.html)
*/
public readonly deleteAllPolicyResources!: pulumi.Output<boolean | undefined>;
/**
* A map of lists of accounts and OU's to exclude from the policy.
*/
public readonly excludeMap!: pulumi.Output<outputs.fms.PolicyExcludeMap | undefined>;
/**
* A boolean value, if true the tags that are specified in the `resourceTags` are not protected by this policy. If set to false and resourceTags are populated, resources that contain tags will be protected by this policy.
*/
public readonly excludeResourceTags!: pulumi.Output<boolean>;
/**
* A map of lists of accounts and OU's to include in the policy.
*/
public readonly includeMap!: pulumi.Output<outputs.fms.PolicyIncludeMap | undefined>;
/**
* The friendly name of the AWS Firewall Manager Policy.
*/
public readonly name!: pulumi.Output<string>;
/**
* A unique identifier for each update to the policy.
*/
public /*out*/ readonly policyUpdateToken!: pulumi.Output<string>;
/**
* A boolean value, indicates if the policy should automatically applied to resources that already exist in the account.
*/
public readonly remediationEnabled!: pulumi.Output<boolean | undefined>;
/**
* A map of resource tags, that if present will filter protections on resources based on the exclude_resource_tags.
*/
public readonly resourceTags!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* A resource type to protect. Conflicts with `resourceTypeList`. See the [FMS API Reference](https://docs.aws.amazon.com/fms/2018-01-01/APIReference/API_Policy.html#fms-Type-Policy-ResourceType) for more information about supported values.
*/
public readonly resourceType!: pulumi.Output<string>;
/**
* A list of resource types to protect. Conflicts with `resourceType`. See the [FMS API Reference](https://docs.aws.amazon.com/fms/2018-01-01/APIReference/API_Policy.html#fms-Type-Policy-ResourceType) for more information about supported values.
*/
public readonly resourceTypeLists!: pulumi.Output<string[]>;
/**
* The objects to include in Security Service Policy Data. Documented below.
*/
public readonly securityServicePolicyData!: pulumi.Output<outputs.fms.PolicySecurityServicePolicyData>;
/**
* Create a Policy 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: PolicyArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: PolicyArgs | PolicyState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as PolicyState | undefined;
inputs["arn"] = state ? state.arn : undefined;
inputs["deleteAllPolicyResources"] = state ? state.deleteAllPolicyResources : undefined;
inputs["excludeMap"] = state ? state.excludeMap : undefined;
inputs["excludeResourceTags"] = state ? state.excludeResourceTags : undefined;
inputs["includeMap"] = state ? state.includeMap : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["policyUpdateToken"] = state ? state.policyUpdateToken : undefined;
inputs["remediationEnabled"] = state ? state.remediationEnabled : undefined;
inputs["resourceTags"] = state ? state.resourceTags : undefined;
inputs["resourceType"] = state ? state.resourceType : undefined;
inputs["resourceTypeLists"] = state ? state.resourceTypeLists : undefined;
inputs["securityServicePolicyData"] = state ? state.securityServicePolicyData : undefined;
} else {
const args = argsOrState as PolicyArgs | undefined;
if ((!args || args.excludeResourceTags === undefined) && !opts.urn) {
throw new Error("Missing required property 'excludeResourceTags'");
}
if ((!args || args.securityServicePolicyData === undefined) && !opts.urn) {
throw new Error("Missing required property 'securityServicePolicyData'");
}
inputs["deleteAllPolicyResources"] = args ? args.deleteAllPolicyResources : undefined;
inputs["excludeMap"] = args ? args.excludeMap : undefined;
inputs["excludeResourceTags"] = args ? args.excludeResourceTags : undefined;
inputs["includeMap"] = args ? args.includeMap : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["remediationEnabled"] = args ? args.remediationEnabled : undefined;
inputs["resourceTags"] = args ? args.resourceTags : undefined;
inputs["resourceType"] = args ? args.resourceType : undefined;
inputs["resourceTypeLists"] = args ? args.resourceTypeLists : undefined;
inputs["securityServicePolicyData"] = args ? args.securityServicePolicyData : undefined;
inputs["arn"] = undefined /*out*/;
inputs["policyUpdateToken"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(Policy.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering Policy resources.
*/
export interface PolicyState {
arn?: pulumi.Input<string>;
/**
* If true, the request will also perform a clean-up process. Defaults to `true`. More information can be found here [AWS Firewall Manager delete policy](https://docs.aws.amazon.com/fms/2018-01-01/APIReference/API_DeletePolicy.html)
*/
deleteAllPolicyResources?: pulumi.Input<boolean>;
/**
* A map of lists of accounts and OU's to exclude from the policy.
*/
excludeMap?: pulumi.Input<inputs.fms.PolicyExcludeMap>;
/**
* A boolean value, if true the tags that are specified in the `resourceTags` are not protected by this policy. If set to false and resourceTags are populated, resources that contain tags will be protected by this policy.
*/
excludeResourceTags?: pulumi.Input<boolean>;
/**
* A map of lists of accounts and OU's to include in the policy.
*/
includeMap?: pulumi.Input<inputs.fms.PolicyIncludeMap>;
/**
* The friendly name of the AWS Firewall Manager Policy.
*/
name?: pulumi.Input<string>;
/**
* A unique identifier for each update to the policy.
*/
policyUpdateToken?: pulumi.Input<string>;
/**
* A boolean value, indicates if the policy should automatically applied to resources that already exist in the account.
*/
remediationEnabled?: pulumi.Input<boolean>;
/**
* A map of resource tags, that if present will filter protections on resources based on the exclude_resource_tags.
*/
resourceTags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* A resource type to protect. Conflicts with `resourceTypeList`. See the [FMS API Reference](https://docs.aws.amazon.com/fms/2018-01-01/APIReference/API_Policy.html#fms-Type-Policy-ResourceType) for more information about supported values.
*/
resourceType?: pulumi.Input<string>;
/**
* A list of resource types to protect. Conflicts with `resourceType`. See the [FMS API Reference](https://docs.aws.amazon.com/fms/2018-01-01/APIReference/API_Policy.html#fms-Type-Policy-ResourceType) for more information about supported values.
*/
resourceTypeLists?: pulumi.Input<pulumi.Input<string>[]>;
/**
* The objects to include in Security Service Policy Data. Documented below.
*/
securityServicePolicyData?: pulumi.Input<inputs.fms.PolicySecurityServicePolicyData>;
}
/**
* The set of arguments for constructing a Policy resource.
*/
export interface PolicyArgs {
/**
* If true, the request will also perform a clean-up process. Defaults to `true`. More information can be found here [AWS Firewall Manager delete policy](https://docs.aws.amazon.com/fms/2018-01-01/APIReference/API_DeletePolicy.html)
*/
deleteAllPolicyResources?: pulumi.Input<boolean>;
/**
* A map of lists of accounts and OU's to exclude from the policy.
*/
excludeMap?: pulumi.Input<inputs.fms.PolicyExcludeMap>;
/**
* A boolean value, if true the tags that are specified in the `resourceTags` are not protected by this policy. If set to false and resourceTags are populated, resources that contain tags will be protected by this policy.
*/
excludeResourceTags: pulumi.Input<boolean>;
/**
* A map of lists of accounts and OU's to include in the policy.
*/
includeMap?: pulumi.Input<inputs.fms.PolicyIncludeMap>;
/**
* The friendly name of the AWS Firewall Manager Policy.
*/
name?: pulumi.Input<string>;
/**
* A boolean value, indicates if the policy should automatically applied to resources that already exist in the account.
*/
remediationEnabled?: pulumi.Input<boolean>;
/**
* A map of resource tags, that if present will filter protections on resources based on the exclude_resource_tags.
*/
resourceTags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* A resource type to protect. Conflicts with `resourceTypeList`. See the [FMS API Reference](https://docs.aws.amazon.com/fms/2018-01-01/APIReference/API_Policy.html#fms-Type-Policy-ResourceType) for more information about supported values.
*/
resourceType?: pulumi.Input<string>;
/**
* A list of resource types to protect. Conflicts with `resourceType`. See the [FMS API Reference](https://docs.aws.amazon.com/fms/2018-01-01/APIReference/API_Policy.html#fms-Type-Policy-ResourceType) for more information about supported values.
*/
resourceTypeLists?: pulumi.Input<pulumi.Input<string>[]>;
/**
* The objects to include in Security Service Policy Data. Documented below.
*/
securityServicePolicyData: pulumi.Input<inputs.fms.PolicySecurityServicePolicyData>;
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { Applications } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { GraphRbacManagementClient } from "../graphRbacManagementClient";
import {
Application,
ApplicationsListNextOptionalParams,
ApplicationsListOptionalParams,
DirectoryObjectUnion,
ApplicationsListOwnersNextOptionalParams,
ApplicationsListOwnersOptionalParams,
KeyCredential,
ApplicationsListKeyCredentialsOptionalParams,
PasswordCredential,
ApplicationsListPasswordCredentialsOptionalParams,
ApplicationCreateParameters,
ApplicationsCreateOptionalParams,
ApplicationsCreateResponse,
ApplicationsListResponse,
ApplicationsDeleteOptionalParams,
ApplicationsGetOptionalParams,
ApplicationsGetResponse,
ApplicationUpdateParameters,
ApplicationsPatchOptionalParams,
ApplicationsListOwnersResponse,
AddOwnerParameters,
ApplicationsAddOwnerOptionalParams,
ApplicationsRemoveOwnerOptionalParams,
ApplicationsListKeyCredentialsResponse,
KeyCredentialsUpdateParameters,
ApplicationsUpdateKeyCredentialsOptionalParams,
ApplicationsListPasswordCredentialsResponse,
PasswordCredentialsUpdateParameters,
ApplicationsUpdatePasswordCredentialsOptionalParams,
ApplicationsGetServicePrincipalsIdByAppIdOptionalParams,
ApplicationsGetServicePrincipalsIdByAppIdResponse,
ApplicationsListNextResponse,
ApplicationsListOwnersNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing Applications operations. */
export class ApplicationsImpl implements Applications {
private readonly client: GraphRbacManagementClient;
/**
* Initialize a new instance of the class Applications class.
* @param client Reference to the service client
*/
constructor(client: GraphRbacManagementClient) {
this.client = client;
}
/**
* Lists applications by filter parameters.
* @param options The options parameters.
*/
public list(
options?: ApplicationsListOptionalParams
): PagedAsyncIterableIterator<Application> {
const iter = this.listPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listPagingPage(options);
}
};
}
private async *listPagingPage(
options?: ApplicationsListOptionalParams
): AsyncIterableIterator<Application[]> {
let result = await this._list(options);
yield result.value || [];
let continuationToken = result.odataNextLink;
while (continuationToken) {
result = await this._listNext(continuationToken, options);
continuationToken = result.odataNextLink;
yield result.value || [];
}
}
private async *listPagingAll(
options?: ApplicationsListOptionalParams
): AsyncIterableIterator<Application> {
for await (const page of this.listPagingPage(options)) {
yield* page;
}
}
/**
* The owners are a set of non-admin users who are allowed to modify this object.
* @param applicationObjectId The object ID of the application for which to get owners.
* @param options The options parameters.
*/
public listOwners(
applicationObjectId: string,
options?: ApplicationsListOwnersOptionalParams
): PagedAsyncIterableIterator<DirectoryObjectUnion> {
const iter = this.listOwnersPagingAll(applicationObjectId, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listOwnersPagingPage(applicationObjectId, options);
}
};
}
private async *listOwnersPagingPage(
applicationObjectId: string,
options?: ApplicationsListOwnersOptionalParams
): AsyncIterableIterator<DirectoryObjectUnion[]> {
let result = await this._listOwners(applicationObjectId, options);
yield result.value || [];
let continuationToken = result.odataNextLink;
while (continuationToken) {
result = await this._listOwnersNext(
applicationObjectId,
continuationToken,
options
);
continuationToken = result.odataNextLink;
yield result.value || [];
}
}
private async *listOwnersPagingAll(
applicationObjectId: string,
options?: ApplicationsListOwnersOptionalParams
): AsyncIterableIterator<DirectoryObjectUnion> {
for await (const page of this.listOwnersPagingPage(
applicationObjectId,
options
)) {
yield* page;
}
}
/**
* Get the keyCredentials associated with an application.
* @param applicationObjectId Application object ID.
* @param options The options parameters.
*/
public listKeyCredentials(
applicationObjectId: string,
options?: ApplicationsListKeyCredentialsOptionalParams
): PagedAsyncIterableIterator<KeyCredential> {
const iter = this.listKeyCredentialsPagingAll(applicationObjectId, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listKeyCredentialsPagingPage(applicationObjectId, options);
}
};
}
private async *listKeyCredentialsPagingPage(
applicationObjectId: string,
options?: ApplicationsListKeyCredentialsOptionalParams
): AsyncIterableIterator<KeyCredential[]> {
let result = await this._listKeyCredentials(applicationObjectId, options);
yield result.value || [];
}
private async *listKeyCredentialsPagingAll(
applicationObjectId: string,
options?: ApplicationsListKeyCredentialsOptionalParams
): AsyncIterableIterator<KeyCredential> {
for await (const page of this.listKeyCredentialsPagingPage(
applicationObjectId,
options
)) {
yield* page;
}
}
/**
* Get the passwordCredentials associated with an application.
* @param applicationObjectId Application object ID.
* @param options The options parameters.
*/
public listPasswordCredentials(
applicationObjectId: string,
options?: ApplicationsListPasswordCredentialsOptionalParams
): PagedAsyncIterableIterator<PasswordCredential> {
const iter = this.listPasswordCredentialsPagingAll(
applicationObjectId,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listPasswordCredentialsPagingPage(
applicationObjectId,
options
);
}
};
}
private async *listPasswordCredentialsPagingPage(
applicationObjectId: string,
options?: ApplicationsListPasswordCredentialsOptionalParams
): AsyncIterableIterator<PasswordCredential[]> {
let result = await this._listPasswordCredentials(
applicationObjectId,
options
);
yield result.value || [];
}
private async *listPasswordCredentialsPagingAll(
applicationObjectId: string,
options?: ApplicationsListPasswordCredentialsOptionalParams
): AsyncIterableIterator<PasswordCredential> {
for await (const page of this.listPasswordCredentialsPagingPage(
applicationObjectId,
options
)) {
yield* page;
}
}
/**
* Gets a list of applications from the current tenant.
* @param nextLink Next link for the list operation.
* @param options The options parameters.
*/
public listNext(
nextLink: string,
options?: ApplicationsListNextOptionalParams
): PagedAsyncIterableIterator<Application> {
const iter = this.listNextPagingAll(nextLink, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listNextPagingPage(nextLink, options);
}
};
}
private async *listNextPagingPage(
nextLink: string,
options?: ApplicationsListNextOptionalParams
): AsyncIterableIterator<Application[]> {
let result = await this._listNext(nextLink, options);
yield result.value || [];
let continuationToken = result.odataNextLink;
while (continuationToken) {
result = await this._listNext(continuationToken, options);
continuationToken = result.odataNextLink;
yield result.value || [];
}
}
private async *listNextPagingAll(
nextLink: string,
options?: ApplicationsListNextOptionalParams
): AsyncIterableIterator<Application> {
for await (const page of this.listNextPagingPage(nextLink, options)) {
yield* page;
}
}
/**
* Create a new application.
* @param parameters The parameters for creating an application.
* @param options The options parameters.
*/
create(
parameters: ApplicationCreateParameters,
options?: ApplicationsCreateOptionalParams
): Promise<ApplicationsCreateResponse> {
return this.client.sendOperationRequest(
{ parameters, options },
createOperationSpec
);
}
/**
* Lists applications by filter parameters.
* @param options The options parameters.
*/
private _list(
options?: ApplicationsListOptionalParams
): Promise<ApplicationsListResponse> {
return this.client.sendOperationRequest({ options }, listOperationSpec);
}
/**
* Delete an application.
* @param applicationObjectId Application object ID.
* @param options The options parameters.
*/
delete(
applicationObjectId: string,
options?: ApplicationsDeleteOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ applicationObjectId, options },
deleteOperationSpec
);
}
/**
* Get an application by object ID.
* @param applicationObjectId Application object ID.
* @param options The options parameters.
*/
get(
applicationObjectId: string,
options?: ApplicationsGetOptionalParams
): Promise<ApplicationsGetResponse> {
return this.client.sendOperationRequest(
{ applicationObjectId, options },
getOperationSpec
);
}
/**
* Update an existing application.
* @param applicationObjectId Application object ID.
* @param parameters Parameters to update an existing application.
* @param options The options parameters.
*/
patch(
applicationObjectId: string,
parameters: ApplicationUpdateParameters,
options?: ApplicationsPatchOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ applicationObjectId, parameters, options },
patchOperationSpec
);
}
/**
* The owners are a set of non-admin users who are allowed to modify this object.
* @param applicationObjectId The object ID of the application for which to get owners.
* @param options The options parameters.
*/
private _listOwners(
applicationObjectId: string,
options?: ApplicationsListOwnersOptionalParams
): Promise<ApplicationsListOwnersResponse> {
return this.client.sendOperationRequest(
{ applicationObjectId, options },
listOwnersOperationSpec
);
}
/**
* Add an owner to an application.
* @param applicationObjectId The object ID of the application to which to add the owner.
* @param parameters The URL of the owner object, such as
* https://graph.windows.net/0b1f9851-1bf0-433f-aec3-cb9272f093dc/directoryObjects/f260bbc4-c254-447b-94cf-293b5ec434dd.
* @param options The options parameters.
*/
addOwner(
applicationObjectId: string,
parameters: AddOwnerParameters,
options?: ApplicationsAddOwnerOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ applicationObjectId, parameters, options },
addOwnerOperationSpec
);
}
/**
* Remove a member from owners.
* @param applicationObjectId The object ID of the application from which to remove the owner.
* @param ownerObjectId Owner object id
* @param options The options parameters.
*/
removeOwner(
applicationObjectId: string,
ownerObjectId: string,
options?: ApplicationsRemoveOwnerOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ applicationObjectId, ownerObjectId, options },
removeOwnerOperationSpec
);
}
/**
* Get the keyCredentials associated with an application.
* @param applicationObjectId Application object ID.
* @param options The options parameters.
*/
private _listKeyCredentials(
applicationObjectId: string,
options?: ApplicationsListKeyCredentialsOptionalParams
): Promise<ApplicationsListKeyCredentialsResponse> {
return this.client.sendOperationRequest(
{ applicationObjectId, options },
listKeyCredentialsOperationSpec
);
}
/**
* Update the keyCredentials associated with an application.
* @param applicationObjectId Application object ID.
* @param parameters Parameters to update the keyCredentials of an existing application.
* @param options The options parameters.
*/
updateKeyCredentials(
applicationObjectId: string,
parameters: KeyCredentialsUpdateParameters,
options?: ApplicationsUpdateKeyCredentialsOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ applicationObjectId, parameters, options },
updateKeyCredentialsOperationSpec
);
}
/**
* Get the passwordCredentials associated with an application.
* @param applicationObjectId Application object ID.
* @param options The options parameters.
*/
private _listPasswordCredentials(
applicationObjectId: string,
options?: ApplicationsListPasswordCredentialsOptionalParams
): Promise<ApplicationsListPasswordCredentialsResponse> {
return this.client.sendOperationRequest(
{ applicationObjectId, options },
listPasswordCredentialsOperationSpec
);
}
/**
* Update passwordCredentials associated with an application.
* @param applicationObjectId Application object ID.
* @param parameters Parameters to update passwordCredentials of an existing application.
* @param options The options parameters.
*/
updatePasswordCredentials(
applicationObjectId: string,
parameters: PasswordCredentialsUpdateParameters,
options?: ApplicationsUpdatePasswordCredentialsOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ applicationObjectId, parameters, options },
updatePasswordCredentialsOperationSpec
);
}
/**
* Gets an object id for a given application id from the current tenant.
* @param applicationID The application ID.
* @param options The options parameters.
*/
getServicePrincipalsIdByAppId(
applicationID: string,
options?: ApplicationsGetServicePrincipalsIdByAppIdOptionalParams
): Promise<ApplicationsGetServicePrincipalsIdByAppIdResponse> {
return this.client.sendOperationRequest(
{ applicationID, options },
getServicePrincipalsIdByAppIdOperationSpec
);
}
/**
* Gets a list of applications from the current tenant.
* @param nextLink Next link for the list operation.
* @param options The options parameters.
*/
private _listNext(
nextLink: string,
options?: ApplicationsListNextOptionalParams
): Promise<ApplicationsListNextResponse> {
return this.client.sendOperationRequest(
{ nextLink, options },
listNextOperationSpec
);
}
/**
* ListOwnersNext
* @param applicationObjectId The object ID of the application for which to get owners.
* @param nextLink The nextLink from the previous successful call to the ListOwners method.
* @param options The options parameters.
*/
private _listOwnersNext(
applicationObjectId: string,
nextLink: string,
options?: ApplicationsListOwnersNextOptionalParams
): Promise<ApplicationsListOwnersNextResponse> {
return this.client.sendOperationRequest(
{ applicationObjectId, nextLink, options },
listOwnersNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const createOperationSpec: coreClient.OperationSpec = {
path: "/{tenantID}/applications",
httpMethod: "POST",
responses: {
201: {
bodyMapper: Mappers.Application
},
default: {
bodyMapper: Mappers.GraphError
}
},
requestBody: Parameters.parameters,
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host, Parameters.tenantID],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const listOperationSpec: coreClient.OperationSpec = {
path: "/{tenantID}/applications",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ApplicationListResult
},
default: {
bodyMapper: Mappers.GraphError
}
},
queryParameters: [Parameters.apiVersion, Parameters.filter],
urlParameters: [Parameters.$host, Parameters.tenantID],
headerParameters: [Parameters.accept],
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path: "/{tenantID}/applications/{applicationObjectId}",
httpMethod: "DELETE",
responses: {
204: {},
default: {
bodyMapper: Mappers.GraphError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.tenantID,
Parameters.applicationObjectId
],
headerParameters: [Parameters.accept],
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path: "/{tenantID}/applications/{applicationObjectId}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.Application
},
default: {
bodyMapper: Mappers.GraphError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.tenantID,
Parameters.applicationObjectId
],
headerParameters: [Parameters.accept],
serializer
};
const patchOperationSpec: coreClient.OperationSpec = {
path: "/{tenantID}/applications/{applicationObjectId}",
httpMethod: "PATCH",
responses: {
204: {},
default: {
bodyMapper: Mappers.GraphError
}
},
requestBody: Parameters.parameters1,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.tenantID,
Parameters.applicationObjectId
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const listOwnersOperationSpec: coreClient.OperationSpec = {
path: "/{tenantID}/applications/{applicationObjectId}/owners",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.DirectoryObjectListResult
},
default: {
bodyMapper: Mappers.GraphError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.tenantID,
Parameters.applicationObjectId
],
headerParameters: [Parameters.accept],
serializer
};
const addOwnerOperationSpec: coreClient.OperationSpec = {
path: "/{tenantID}/applications/{applicationObjectId}/$links/owners",
httpMethod: "POST",
responses: {
204: {},
default: {
bodyMapper: Mappers.GraphError
}
},
requestBody: Parameters.parameters2,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.tenantID,
Parameters.applicationObjectId
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const removeOwnerOperationSpec: coreClient.OperationSpec = {
path:
"/{tenantID}/applications/{applicationObjectId}/$links/owners/{ownerObjectId}",
httpMethod: "DELETE",
responses: {
204: {},
default: {
bodyMapper: Mappers.GraphError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.tenantID,
Parameters.applicationObjectId,
Parameters.ownerObjectId
],
headerParameters: [Parameters.accept],
serializer
};
const listKeyCredentialsOperationSpec: coreClient.OperationSpec = {
path: "/{tenantID}/applications/{applicationObjectId}/keyCredentials",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.KeyCredentialListResult
},
default: {
bodyMapper: Mappers.GraphError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.tenantID,
Parameters.applicationObjectId
],
headerParameters: [Parameters.accept],
serializer
};
const updateKeyCredentialsOperationSpec: coreClient.OperationSpec = {
path: "/{tenantID}/applications/{applicationObjectId}/keyCredentials",
httpMethod: "PATCH",
responses: {
204: {},
default: {
bodyMapper: Mappers.GraphError
}
},
requestBody: Parameters.parameters3,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.tenantID,
Parameters.applicationObjectId
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const listPasswordCredentialsOperationSpec: coreClient.OperationSpec = {
path: "/{tenantID}/applications/{applicationObjectId}/passwordCredentials",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.PasswordCredentialListResult
},
default: {
bodyMapper: Mappers.GraphError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.tenantID,
Parameters.applicationObjectId
],
headerParameters: [Parameters.accept],
serializer
};
const updatePasswordCredentialsOperationSpec: coreClient.OperationSpec = {
path: "/{tenantID}/applications/{applicationObjectId}/passwordCredentials",
httpMethod: "PATCH",
responses: {
204: {},
default: {
bodyMapper: Mappers.GraphError
}
},
requestBody: Parameters.parameters4,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.tenantID,
Parameters.applicationObjectId
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const getServicePrincipalsIdByAppIdOperationSpec: coreClient.OperationSpec = {
path: "/{tenantID}/servicePrincipalsByAppId/{applicationID}/objectId",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ServicePrincipalObjectResult
},
default: {
bodyMapper: Mappers.GraphError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.tenantID,
Parameters.applicationID
],
headerParameters: [Parameters.accept],
serializer
};
const listNextOperationSpec: coreClient.OperationSpec = {
path: "/{tenantID}/{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ApplicationListResult
},
default: {
bodyMapper: Mappers.GraphError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host, Parameters.tenantID, Parameters.nextLink],
headerParameters: [Parameters.accept],
serializer
};
const listOwnersNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.DirectoryObjectListResult
},
default: {
bodyMapper: Mappers.GraphError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.tenantID,
Parameters.nextLink,
Parameters.applicationObjectId
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import { Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges, ViewEncapsulation } from '@angular/core';
import {
BpmUserService,
CardViewDateItemModel,
CardViewMapItemModel,
CardViewTextItemModel,
CardViewBaseItemModel,
TranslationService,
AppConfigService,
CardViewIntItemModel,
CardViewItemLengthValidator
} from '@alfresco/adf-core';
import { TaskDetailsModel } from '../models/task-details.model';
import { TaskDescriptionValidator } from '../validators/task-description.validator';
@Component({
selector: 'adf-task-header',
templateUrl: './task-header.component.html',
styleUrls: ['./task-header.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class TaskHeaderComponent implements OnChanges, OnInit {
/** The name of the form. */
@Input()
formName: string = null;
/** (required) Details related to the task. */
@Input()
taskDetails: TaskDetailsModel;
/** Toggles display of the claim/release button. */
@Input()
showClaimRelease = true;
/** Emitted when the task is claimed. */
@Output()
claim: EventEmitter<any> = new EventEmitter<any>();
/** Emitted when the task is unclaimed (ie, requeue). */
@Output()
unclaim: EventEmitter<any> = new EventEmitter<any>();
private currentUserId: number;
properties: any [] = [];
inEdit: boolean = false;
displayDateClearAction = false;
dateFormat: string;
dateLocale: string;
constructor(private bpmUserService: BpmUserService,
private translationService: TranslationService,
private appConfig: AppConfigService) {
this.dateFormat = this.appConfig.get('dateValues.defaultDateFormat');
this.dateLocale = this.appConfig.get('dateValues.defaultDateLocale');
}
ngOnInit() {
this.loadCurrentBpmUserId();
this.initData();
}
ngOnChanges(changes: SimpleChanges) {
const taskDetailsChange = changes['taskDetails'];
if (taskDetailsChange?.currentValue?.id !== taskDetailsChange?.previousValue?.id) {
this.initData();
} else {
this.refreshData();
}
}
private initDefaultProperties(parentInfoMap): any[] {
return [
new CardViewTextItemModel(
{
label: 'ADF_TASK_LIST.PROPERTIES.ASSIGNEE',
value: this.taskDetails.getFullName(),
key: 'assignee',
default: this.translationService.instant('ADF_TASK_LIST.PROPERTIES.ASSIGNEE_DEFAULT'),
clickable: !this.isCompleted(),
icon: 'create'
}
),
new CardViewTextItemModel(
{
label: 'ADF_TASK_LIST.PROPERTIES.STATUS',
value: this.getTaskStatus(),
key: 'status'
}
),
new CardViewIntItemModel(
{
label: 'ADF_TASK_LIST.PROPERTIES.PRIORITY',
value: this.taskDetails.priority,
key: 'priority',
editable: true,
validators: [new CardViewItemLengthValidator(1, 10)]
}
),
new CardViewDateItemModel(
{
label: 'ADF_TASK_LIST.PROPERTIES.DUE_DATE',
value: this.taskDetails.dueDate,
key: 'dueDate',
default: this.translationService.instant('ADF_TASK_LIST.PROPERTIES.DUE_DATE_DEFAULT'),
editable: true,
format: this.dateFormat,
locale: this.dateLocale
}
),
new CardViewTextItemModel(
{
label: 'ADF_TASK_LIST.PROPERTIES.CATEGORY',
value: this.taskDetails.category,
key: 'category',
default: this.translationService.instant('ADF_TASK_LIST.PROPERTIES.CATEGORY_DEFAULT')
}
),
new CardViewMapItemModel(
{
label: 'ADF_TASK_LIST.PROPERTIES.PARENT_NAME',
value: parentInfoMap,
key: 'parentName',
default: this.translationService.instant('ADF_TASK_LIST.PROPERTIES.PARENT_NAME_DEFAULT'),
clickable: true
}
),
new CardViewDateItemModel(
{
label: 'ADF_TASK_LIST.PROPERTIES.CREATED',
value: this.taskDetails.created,
key: 'created',
format: this.dateFormat,
locale: this.dateLocale
}
),
new CardViewTextItemModel(
{
label: 'ADF_TASK_LIST.PROPERTIES.DURATION',
value: this.getTaskDuration(),
key: 'duration'
}
),
new CardViewTextItemModel(
{
label: 'ADF_TASK_LIST.PROPERTIES.PARENT_TASK_ID',
value: this.taskDetails.parentTaskId,
key: 'parentTaskId'
}
),
new CardViewDateItemModel(
{
label: 'ADF_TASK_LIST.PROPERTIES.END_DATE',
value: this.taskDetails.endDate,
key: 'endDate',
format: this.dateFormat,
locale: this.dateLocale
}
),
new CardViewTextItemModel(
{
label: 'ADF_TASK_LIST.PROPERTIES.ID',
value: this.taskDetails.id,
key: 'id'
}
),
new CardViewTextItemModel(
{
label: 'ADF_TASK_LIST.PROPERTIES.DESCRIPTION',
value: this.taskDetails.description,
key: 'description',
default: this.translationService.instant('ADF_TASK_LIST.PROPERTIES.DESCRIPTION_DEFAULT'),
multiline: true,
editable: true,
validators: [new TaskDescriptionValidator()]
}
),
new CardViewTextItemModel(
{
label: 'ADF_TASK_LIST.PROPERTIES.FORM_NAME',
value: this.formName,
key: 'formName',
default: this.translationService.instant('ADF_TASK_LIST.PROPERTIES.FORM_NAME_DEFAULT'),
clickable: this.isFormClickable(),
icon: 'create'
}
)
];
}
/**
* Refresh the card data
*/
initData() {
if (this.taskDetails) {
const parentInfoMap = this.getParentInfo();
const defaultProperties = this.initDefaultProperties(parentInfoMap);
const filteredProperties: string[] = this.appConfig.get('adf-task-header.presets.properties');
this.properties = defaultProperties.filter((cardItem) => this.isValidSelection(filteredProperties, cardItem));
}
}
/**
* Refresh the card data
*/
refreshData() {
this.properties = this.properties.map((cardItem) => {
if (cardItem.key === 'formName' && cardItem.value !== this.formName) {
return new CardViewTextItemModel({
label: 'ADF_TASK_LIST.PROPERTIES.FORM_NAME',
value: this.formName,
key: 'formName',
default: this.translationService.instant('ADF_TASK_LIST.PROPERTIES.FORM_NAME_DEFAULT'),
clickable: this.isFormClickable(),
icon: 'create'
});
} else {
return cardItem;
}
});
}
private isValidSelection(filteredProperties: string[], cardItem: CardViewBaseItemModel): boolean {
return filteredProperties ? filteredProperties.indexOf(cardItem.key) >= 0 : true;
}
/**
* Loads current bpm userId
*/
private loadCurrentBpmUserId(): void {
this.bpmUserService.getCurrentUserInfo().subscribe((res) => {
this.currentUserId = res ? +res.id : null;
});
}
/**
* Return the process parent information
*/
getParentInfo(): Map<string, string> {
if (this.taskDetails.processInstanceId && this.taskDetails.processDefinitionName) {
return new Map([[this.taskDetails.processInstanceId, this.taskDetails.processDefinitionName]]);
}
return new Map();
}
/**
* Does the task have an assignee
*/
public hasAssignee(): boolean {
return !!this.taskDetails.assignee;
}
/**
* Returns true if the task is assigned to logged in user
*/
public isAssignedTo(userId: number): boolean {
return this.hasAssignee() ? this.taskDetails.assignee.id === userId : false;
}
/**
* Return true if the task assigned
*/
public isAssignedToCurrentUser(): boolean {
return this.hasAssignee() && this.isAssignedTo(this.currentUserId);
}
/**
* Return true if the user is a candidate member
*/
isCandidateMember(): boolean {
return this.taskDetails.managerOfCandidateGroup || this.taskDetails.memberOfCandidateGroup || this.taskDetails.memberOfCandidateUsers;
}
/**
* Return true if the task claimable
*/
public isTaskClaimable(): boolean {
return !this.hasAssignee() && this.isCandidateMember();
}
/**
* Return true if the task claimed by candidate member.
*/
public isTaskClaimedByCandidateMember(): boolean {
return this.isCandidateMember() && this.isAssignedToCurrentUser() && !this.isCompleted();
}
/**
* Returns task's status
*/
getTaskStatus(): string {
return (this.taskDetails && this.taskDetails.isCompleted()) ? 'Completed' : 'Running';
}
onClaimTask(taskId: string) {
this.claim.emit(taskId);
}
onUnclaimTask(taskId: string) {
this.unclaim.emit(taskId);
}
/**
* Returns true if the task is completed
*/
isCompleted(): boolean {
return this.taskDetails && !!this.taskDetails.endDate;
}
isFormClickable(): boolean {
return !!this.formName && !this.isCompleted();
}
getTaskDuration(): string {
return this.taskDetails.duration ? `${this.taskDetails.duration} ms` : '';
}
} | the_stack |
import * as Octokit from "@octokit/rest";
import * as fs from "fs";
import * as path from "path";
import { commands, ConfigurationChangeEvent, ConfigurationTarget, DocumentSelector, ExtensionContext, extensions, FileSystemWatcher, IndentAction, languages, TextDocument, Uri, window, workspace, WorkspaceConfiguration } from "vscode";
import { COMPONENT_FILE_GLOB } from "./entities/component";
import { Scope } from "./entities/scope";
import { decreasingIndentingTags, goToMatchingTag, nonClosingTags, nonIndentingTags } from "./entities/tag";
import { parseVariableAssignments, Variable } from "./entities/variable";
import * as cachedEntity from "./features/cachedEntities";
import CFMLDocumentColorProvider from "./features/colorProvider";
import { foldAllFunctions, openActiveApplicationFile, refreshGlobalDefinitionCache, refreshWorkspaceDefinitionCache } from "./features/commands";
import { CommentType, toggleComment } from "./features/comment";
import CFMLCompletionItemProvider from "./features/completionItemProvider";
import CFMLDefinitionProvider from "./features/definitionProvider";
import DocBlockCompletions from "./features/docBlocker/docCompletionProvider";
import CFMLDocumentLinkProvider from "./features/documentLinkProvider";
import CFMLDocumentSymbolProvider from "./features/documentSymbolProvider";
import CFMLHoverProvider from "./features/hoverProvider";
import CFMLSignatureHelpProvider from "./features/signatureHelpProvider";
import CFMLTypeDefinitionProvider from "./features/typeDefinitionProvider";
import CFMLWorkspaceSymbolProvider from "./features/workspaceSymbolProvider";
import CFDocsService from "./utils/cfdocs/cfDocsService";
import { APPLICATION_CFM_GLOB, isCfcFile } from "./utils/contextUtil";
import { DocumentStateContext, getDocumentStateContext } from "./utils/documentUtil";
export const LANGUAGE_ID: string = "cfml";
const DOCUMENT_SELECTOR: DocumentSelector = [
{
language: LANGUAGE_ID,
scheme: "file"
},
{
language: LANGUAGE_ID,
scheme: "untitled"
}
];
const octokit = new Octokit();
const httpSuccessStatusCode: number = 200;
export let extensionContext: ExtensionContext;
/**
* Gets a ConfigurationTarget enumerable based on a string representation
* @param target A string representing a configuration target
*/
export function getConfigurationTarget(target: string): ConfigurationTarget {
let configTarget: ConfigurationTarget;
switch (target) {
case "Global":
configTarget = ConfigurationTarget.Global;
break;
case "Workspace":
configTarget = ConfigurationTarget.Workspace;
break;
case "WorkspaceFolder":
configTarget = ConfigurationTarget.WorkspaceFolder;
break;
default:
configTarget = ConfigurationTarget.Global;
}
return configTarget;
}
/**
* Gets the latest CommandBox Server schema from the CommandBox git repository
*/
async function getLatestCommandBoxServerSchema(): Promise<void> {
const cmdboxServerSchemaFileName: string = "server.schema.json";
const cmdboxServerSchemaFilePath: string = path.join(extensionContext.extensionPath, "resources", "schemas", cmdboxServerSchemaFileName);
try {
const cmdboxServerSchemaResult = await octokit.repos.getContents({
owner: "Ortus-Solutions",
repo: "commandbox",
path: `src/cfml/system/config/${cmdboxServerSchemaFileName}`,
ref: "master"
});
if (cmdboxServerSchemaResult && cmdboxServerSchemaResult.hasOwnProperty("status") && cmdboxServerSchemaResult.status === httpSuccessStatusCode && cmdboxServerSchemaResult.data.type === "file") {
const resultText: string = new Buffer(cmdboxServerSchemaResult.data.content, cmdboxServerSchemaResult.data.encoding).toString("utf8");
fs.writeFileSync(cmdboxServerSchemaFilePath, resultText);
}
} catch (err) {
console.error(err);
}
}
/**
* This method is called when the extension is activated.
* @param context The context object for this extension.
*/
export function activate(context: ExtensionContext): void {
extensionContext = context;
languages.setLanguageConfiguration(LANGUAGE_ID, {
indentationRules: {
increaseIndentPattern: new RegExp(`<(?!\\?|(?:${nonIndentingTags.join("|")})\\b|[^>]*\\/>)([-_.A-Za-z0-9]+)(?=\\s|>)\\b[^>]*>(?!.*<\\/\\1>)|<!--(?!.*-->)|\\{[^}\"']*$`, "i"),
decreaseIndentPattern: new RegExp(`^\\s*(<\\/[-_.A-Za-z0-9]+\\b[^>]*>|-?-->|\\}|<(${decreasingIndentingTags.join("|")})\\b[^>]*>)`, "i")
},
onEnterRules: [
{
// e.g. /** | */
beforeText: /^\s*\/\*\*(?!\/)([^\*]|\*(?!\/))*$/,
afterText: /^\s*\*\/$/,
action: { indentAction: IndentAction.IndentOutdent, appendText: " * " }
},
{
// e.g. /** ...|
beforeText: /^\s*\/\*\*(?!\/)([^\*]|\*(?!\/))*$/,
action: { indentAction: IndentAction.None, appendText: " * " }
},
{
// e.g. * ...|
beforeText: /^(\t|(\ \ ))*\ \*(\ ([^\*]|\*(?!\/))*)?$/,
action: { indentAction: IndentAction.None, appendText: "* " }
},
{
// e.g. */|
beforeText: /^(\t|(\ \ ))*\ \*\/\s*$/,
action: { indentAction: IndentAction.None, removeText: 1 }
},
{
// e.g. <cfloop> | </cfloop>
beforeText: new RegExp(`<(?!(?:${nonIndentingTags.join("|")})\\b)([_:\\w][_:\\w-.\\d]*)([^/>]*(?!/)>)[^<]*$`, "i"),
afterText: new RegExp(`^(<\\/([_:\\w][_:\\w-.\\d]*)\\s*>|<(?:${decreasingIndentingTags.join("|")})\\b)`, "i"),
action: { indentAction: IndentAction.IndentOutdent }
}
]
});
getLatestCommandBoxServerSchema();
context.subscriptions.push(commands.registerCommand("cfml.refreshGlobalDefinitionCache", refreshGlobalDefinitionCache));
context.subscriptions.push(commands.registerCommand("cfml.refreshWorkspaceDefinitionCache", refreshWorkspaceDefinitionCache));
context.subscriptions.push(commands.registerCommand("cfml.toggleLineComment", toggleComment(CommentType.Line)));
context.subscriptions.push(commands.registerCommand("cfml.toggleBlockComment", toggleComment(CommentType.Block)));
context.subscriptions.push(commands.registerCommand("cfml.openActiveApplicationFile", openActiveApplicationFile));
context.subscriptions.push(commands.registerCommand("cfml.goToMatchingTag", goToMatchingTag));
context.subscriptions.push(commands.registerCommand("cfml.openCfDocs", CFDocsService.openCfDocsForCurrentWord));
context.subscriptions.push(commands.registerCommand("cfml.openEngineDocs", CFDocsService.openEngineDocsForCurrentWord));
context.subscriptions.push(commands.registerCommand("cfml.foldAllFunctions", foldAllFunctions));
context.subscriptions.push(languages.registerHoverProvider(DOCUMENT_SELECTOR, new CFMLHoverProvider()));
context.subscriptions.push(languages.registerDocumentSymbolProvider(DOCUMENT_SELECTOR, new CFMLDocumentSymbolProvider()));
context.subscriptions.push(languages.registerSignatureHelpProvider(DOCUMENT_SELECTOR, new CFMLSignatureHelpProvider(), "(", ","));
context.subscriptions.push(languages.registerDocumentLinkProvider(DOCUMENT_SELECTOR, new CFMLDocumentLinkProvider()));
context.subscriptions.push(languages.registerWorkspaceSymbolProvider(new CFMLWorkspaceSymbolProvider()));
context.subscriptions.push(languages.registerCompletionItemProvider(DOCUMENT_SELECTOR, new CFMLCompletionItemProvider(), "."));
context.subscriptions.push(languages.registerCompletionItemProvider(DOCUMENT_SELECTOR, new DocBlockCompletions(), "*", "@", "."));
context.subscriptions.push(languages.registerDefinitionProvider(DOCUMENT_SELECTOR, new CFMLDefinitionProvider()));
context.subscriptions.push(languages.registerTypeDefinitionProvider(DOCUMENT_SELECTOR, new CFMLTypeDefinitionProvider()));
context.subscriptions.push(languages.registerColorProvider(DOCUMENT_SELECTOR, new CFMLDocumentColorProvider()));
context.subscriptions.push(workspace.onDidSaveTextDocument((document: TextDocument) => {
if (isCfcFile(document)) {
cachedEntity.cacheComponentFromDocument(document);
} else if (path.basename(document.fileName) === "Application.cfm") {
const documentStateContext: DocumentStateContext = getDocumentStateContext(document);
const thisApplicationVariables: Variable[] = parseVariableAssignments(documentStateContext, documentStateContext.docIsScript);
const thisApplicationFilteredVariables: Variable[] = thisApplicationVariables.filter((variable: Variable) => {
return [Scope.Application, Scope.Session, Scope.Request].includes(variable.scope);
});
cachedEntity.setApplicationVariables(document.uri, thisApplicationFilteredVariables);
}
}));
const componentWatcher: FileSystemWatcher = workspace.createFileSystemWatcher(COMPONENT_FILE_GLOB, false, true, false);
componentWatcher.onDidCreate((componentUri: Uri) => {
workspace.openTextDocument(componentUri).then((document: TextDocument) => {
cachedEntity.cacheComponentFromDocument(document);
});
});
componentWatcher.onDidDelete((componentUri: Uri) => {
cachedEntity.clearCachedComponent(componentUri);
const fileName: string = path.basename(componentUri.fsPath);
if (fileName === "Application.cfc") {
cachedEntity.removeApplicationVariables(componentUri);
}
});
context.subscriptions.push(componentWatcher);
const applicationCfmWatcher: FileSystemWatcher = workspace.createFileSystemWatcher(APPLICATION_CFM_GLOB, false, true, false);
context.subscriptions.push(applicationCfmWatcher);
applicationCfmWatcher.onDidCreate((applicationUri: Uri) => {
workspace.openTextDocument(applicationUri).then((document: TextDocument) => {
const documentStateContext: DocumentStateContext = getDocumentStateContext(document);
const thisApplicationVariables: Variable[] = parseVariableAssignments(documentStateContext, documentStateContext.docIsScript);
const thisApplicationFilteredVariables: Variable[] = thisApplicationVariables.filter((variable: Variable) => {
return [Scope.Application, Scope.Session, Scope.Request].includes(variable.scope);
});
cachedEntity.setApplicationVariables(applicationUri, thisApplicationFilteredVariables);
});
});
applicationCfmWatcher.onDidDelete((applicationUri: Uri) => {
cachedEntity.removeApplicationVariables(applicationUri);
});
context.subscriptions.push(workspace.onDidChangeConfiguration((evt: ConfigurationChangeEvent) => {
if (evt.affectsConfiguration("cfml.globalDefinitions") || evt.affectsConfiguration("cfml.cfDocs") || evt.affectsConfiguration("cfml.engine")) {
commands.executeCommand("cfml.refreshGlobalDefinitionCache");
}
}));
const cfmlSettings: WorkspaceConfiguration = workspace.getConfiguration("cfml");
const autoCloseTagExt = extensions.getExtension("formulahendry.auto-close-tag");
const enableAutoCloseTags: boolean = cfmlSettings.get<boolean>("autoCloseTags.enable", true);
if (autoCloseTagExt) {
const autoCloseTagsSettings: WorkspaceConfiguration = workspace.getConfiguration("auto-close-tag", null);
const autoCloseLanguages: string[] = autoCloseTagsSettings.get<string[]>("activationOnLanguage");
const autoCloseExcludedTags: string[] = autoCloseTagsSettings.get<string[]>("excludedTags");
if (enableAutoCloseTags) {
if (!autoCloseLanguages.includes(LANGUAGE_ID)) {
autoCloseLanguages.push(LANGUAGE_ID);
autoCloseTagsSettings.update(
"activationOnLanguage",
autoCloseLanguages,
getConfigurationTarget(cfmlSettings.get<string>("autoCloseTags.configurationTarget"))
);
}
nonClosingTags.filter((tagName: string) => {
// Consider ignoring case
return !autoCloseExcludedTags.includes(tagName);
}).forEach((tagName: string) => {
autoCloseExcludedTags.push(tagName);
});
autoCloseTagsSettings.update(
"excludedTags",
autoCloseExcludedTags,
getConfigurationTarget(cfmlSettings.get<string>("autoCloseTags.configurationTarget"))
);
} else {
const index: number = autoCloseLanguages.indexOf(LANGUAGE_ID);
if (index !== -1) {
autoCloseLanguages.splice(index, 1);
autoCloseTagsSettings.update(
"activationOnLanguage",
autoCloseLanguages,
getConfigurationTarget(cfmlSettings.get<string>("autoCloseTags.configurationTarget"))
);
}
}
} else if (enableAutoCloseTags) {
window.showInformationMessage("You have the autoCloseTags setting enabled, but do not have the necessary extension installed/enabled.", "Install/Enable Extension", "Disable Setting").then(
(selection: string) => {
if (selection === "Install/Enable Extension") {
commands.executeCommand("extension.open", "formulahendry.auto-close-tag");
} else if (selection === "Disable Setting") {
cfmlSettings.update(
"autoCloseTags.enable",
false,
getConfigurationTarget(cfmlSettings.get<string>("autoCloseTags.configurationTarget"))
);
}
}
);
}
commands.executeCommand("cfml.refreshGlobalDefinitionCache");
commands.executeCommand("cfml.refreshWorkspaceDefinitionCache");
}
/**
* This method is called when the extension is deactivated.
*/
export function deactivate(): void {
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import * as assert from "assert";
import * as semver from "semver";
import * as dashboard from "../../cloudwatch/dashboard";
import { Metric } from "../../cloudwatch/metric";
import { Widget } from "../../cloudwatch/widget";
import { AlarmAnnotation, HorizontalAnnotation, VerticalAnnotation } from "../../cloudwatch/widgets_annotations";
import { ColumnWidget, RowWidget } from "../../cloudwatch/widgets_flow";
import { LineGraphMetricWidget, SingleNumberMetricWidget, StackedAreaGraphMetricWidget } from "../../cloudwatch/widgets_graph";
import { ExpressionWidgetMetric, TextWidget } from "../../cloudwatch/widgets_simple";
async function bodyJson(...widgets: Widget[]) {
return await toJson({ widgets });
}
async function toJson(body: dashboard.DashboardArgs) {
const op = dashboard.getDashboardBody(body, pulumi.output("us-east-2")).apply(b => JSON.stringify(b, null, 4));
return await (<any>op).promise();
}
describe("dashboard", () => {
it("empty", async () => {
const json = await bodyJson();
assert.equal(json, `{
"widgets": []
}`);
});
it("period override", async () => {
const json = await toJson({ periodOverride: "auto", widgets: [] });
assert.equal(json, `{
"periodOverride": "auto",
"widgets": []
}`);
});
describe("annotations", () => {
describe("alarms", () => {
if (semver.gte(process.version, "10.0.0")) {
it("multiple alarms", async () => {
await assert.rejects(async () => {
await bodyJson(new SingleNumberMetricWidget({
annotations: [new AlarmAnnotation("some_arn"), new AlarmAnnotation("some_arn")],
}));
});
});
}
it("single", async () => {
const json = await bodyJson(new SingleNumberMetricWidget({
annotations: [new AlarmAnnotation("some_arn")],
}));
assert.equal(json, `{
"widgets": [
{
"x": 0,
"y": 0,
"width": 6,
"height": 6,
"type": "metric",
"properties": {
"annotations": {
"alarms": [
"some_arn"
]
},
"period": 300,
"region": "us-east-2",
"view": "singleValue",
"stacked": false
}
}
]
}`);
});
});
describe("horizontal", () => {
if (semver.gte(process.version, "10.0.0")) {
it("fill and band", async () => {
await assert.rejects(async () => {
await bodyJson(new SingleNumberMetricWidget({
annotations: [new HorizontalAnnotation({
fill: "above",
aboveEdge: { value: 10 },
belowEdge: { value: 5 },
})],
}));
});
});
}
it("single", async () => {
const json = await bodyJson(new SingleNumberMetricWidget({
annotations: [new HorizontalAnnotation({
aboveEdge: { value: 10 },
})],
}));
assert.equal(json, `{
"widgets": [
{
"x": 0,
"y": 0,
"width": 6,
"height": 6,
"type": "metric",
"properties": {
"annotations": {
"horizontal": [
{
"value": 10
}
]
},
"period": 300,
"region": "us-east-2",
"view": "singleValue",
"stacked": false
}
}
]
}`);
});
it("band", async () => {
const json = await bodyJson(new SingleNumberMetricWidget({
annotations: [new HorizontalAnnotation({
aboveEdge: { value: 10 },
belowEdge: { value: 5 },
})],
}));
assert.equal(json, `{
"widgets": [
{
"x": 0,
"y": 0,
"width": 6,
"height": 6,
"type": "metric",
"properties": {
"annotations": {
"horizontal": [
{
"value": 10
},
{
"value": 5
}
]
},
"period": 300,
"region": "us-east-2",
"view": "singleValue",
"stacked": false
}
}
]
}`);
});
});
describe("vertical", () => {
if (semver.gte(process.version, "10.0.0")) {
it("fill and band", async () => {
await assert.rejects(async () => {
await bodyJson(new SingleNumberMetricWidget({
annotations: [new VerticalAnnotation({
fill: "after",
beforeEdge: { value: "10" },
afterEdge: { value: "5" },
})],
}));
});
});
}
it("single", async () => {
const json = await bodyJson(new SingleNumberMetricWidget({
annotations: [new VerticalAnnotation({
beforeEdge: { value: "10" },
})],
}));
assert.equal(json, `{
"widgets": [
{
"x": 0,
"y": 0,
"width": 6,
"height": 6,
"type": "metric",
"properties": {
"annotations": {
"vertical": [
{
"value": "10"
}
]
},
"period": 300,
"region": "us-east-2",
"view": "singleValue",
"stacked": false
}
}
]
}`);
});
it("band", async () => {
const json = await bodyJson(new SingleNumberMetricWidget({
annotations: [new VerticalAnnotation({
beforeEdge: { value: "10" },
afterEdge: { value: "5" },
})],
}));
assert.equal(json, `{
"widgets": [
{
"x": 0,
"y": 0,
"width": 6,
"height": 6,
"type": "metric",
"properties": {
"annotations": {
"vertical": [
{
"value": "10"
},
{
"value": "5"
}
]
},
"period": 300,
"region": "us-east-2",
"view": "singleValue",
"stacked": false
}
}
]
}`);
});
});
});
describe("text widgets", () => {
it("string constructor", async () => {
const json = await bodyJson(new TextWidget("text"));
assert.equal(json, `{
"widgets": [
{
"x": 0,
"y": 0,
"width": 6,
"height": 6,
"type": "text",
"properties": {
"markdown": "text"
}
}
]
}`);
});
it("custom constructor", async () => {
const json = await bodyJson(new TextWidget({ markdown: "text", width: 2, height: 1 }));
assert.equal(json, `{
"widgets": [
{
"x": 0,
"y": 0,
"width": 2,
"height": 1,
"type": "text",
"properties": {
"markdown": "text"
}
}
]
}`);
});
});
describe("flow widgets", () => {
describe("horizontal", () => {
it("two widgets", async () => {
const json = await bodyJson(new TextWidget("hello"), new TextWidget("world"));
assert.equal(json, `{
"widgets": [
{
"x": 0,
"y": 0,
"width": 6,
"height": 6,
"type": "text",
"properties": {
"markdown": "hello"
}
},
{
"x": 6,
"y": 0,
"width": 6,
"height": 6,
"type": "text",
"properties": {
"markdown": "world"
}
}
]
}`);
});
it("multiple widgets with wrapping", async () => {
const json = await bodyJson(
new TextWidget("hello"),
new TextWidget("world"),
new TextWidget({ markdown: "goodnight", height: 1, width: 18 }),
new TextWidget({ markdown: "moon", height: 3, width: 6 }),
new TextWidget({ markdown: "!", height: 5, width: 1 }));
assert.equal(json, `{
"widgets": [
{
"x": 0,
"y": 0,
"width": 6,
"height": 6,
"type": "text",
"properties": {
"markdown": "hello"
}
},
{
"x": 6,
"y": 0,
"width": 6,
"height": 6,
"type": "text",
"properties": {
"markdown": "world"
}
},
{
"x": 0,
"y": 6,
"width": 18,
"height": 1,
"type": "text",
"properties": {
"markdown": "goodnight"
}
},
{
"x": 18,
"y": 6,
"width": 6,
"height": 3,
"type": "text",
"properties": {
"markdown": "moon"
}
},
{
"x": 0,
"y": 9,
"width": 1,
"height": 5,
"type": "text",
"properties": {
"markdown": "!"
}
}
]
}`);
});
it("multiple rows with wrapping", async () => {
const json = await bodyJson(
new RowWidget(
new TextWidget({ markdown: "hello", height: 4 }),
new TextWidget({ markdown: "world", height: 3 }),
new RowWidget(
new TextWidget({ markdown: "goodnight", height: 1, width: 10 }),
new TextWidget({ markdown: "moon", height: 3, width: 10 }),
new TextWidget({ markdown: "!", height: 5, width: 10 })),
new RowWidget(new TextWidget("byebye"))));
assert.equal(json, `{
"widgets": [
{
"x": 0,
"y": 0,
"width": 6,
"height": 4,
"type": "text",
"properties": {
"markdown": "hello"
}
},
{
"x": 6,
"y": 0,
"width": 6,
"height": 3,
"type": "text",
"properties": {
"markdown": "world"
}
},
{
"x": 0,
"y": 4,
"width": 10,
"height": 1,
"type": "text",
"properties": {
"markdown": "goodnight"
}
},
{
"x": 10,
"y": 4,
"width": 10,
"height": 3,
"type": "text",
"properties": {
"markdown": "moon"
}
},
{
"x": 0,
"y": 7,
"width": 10,
"height": 5,
"type": "text",
"properties": {
"markdown": "!"
}
},
{
"x": 0,
"y": 12,
"width": 6,
"height": 6,
"type": "text",
"properties": {
"markdown": "byebye"
}
}
]
}`);
});
});
describe("vertical", () => {
it("two widgets", async () => {
const json = await bodyJson(
new ColumnWidget(new TextWidget("hello"), new TextWidget("world")));
assert.equal(json, `{
"widgets": [
{
"x": 0,
"y": 0,
"width": 6,
"height": 6,
"type": "text",
"properties": {
"markdown": "hello"
}
},
{
"x": 0,
"y": 6,
"width": 6,
"height": 6,
"type": "text",
"properties": {
"markdown": "world"
}
}
]
}`);
});
it("multiple widgets without wrapping", async () => {
const json = await bodyJson(new ColumnWidget(
new TextWidget("hello"),
new TextWidget("world"),
new TextWidget({ markdown: "goodnight", height: 1, width: 18 }),
new TextWidget({ markdown: "moon", height: 3, width: 6 }),
new TextWidget({ markdown: "!", height: 5, width: 1 })));
assert.equal(json, `{
"widgets": [
{
"x": 0,
"y": 0,
"width": 6,
"height": 6,
"type": "text",
"properties": {
"markdown": "hello"
}
},
{
"x": 0,
"y": 6,
"width": 6,
"height": 6,
"type": "text",
"properties": {
"markdown": "world"
}
},
{
"x": 0,
"y": 12,
"width": 18,
"height": 1,
"type": "text",
"properties": {
"markdown": "goodnight"
}
},
{
"x": 0,
"y": 13,
"width": 6,
"height": 3,
"type": "text",
"properties": {
"markdown": "moon"
}
},
{
"x": 0,
"y": 16,
"width": 1,
"height": 5,
"type": "text",
"properties": {
"markdown": "!"
}
}
]
}`);
});
it("multiple columns without wrapping", async () => {
const json = await bodyJson(
new ColumnWidget(
new TextWidget({ markdown: "hello", height: 4 }),
new TextWidget({ markdown: "world", height: 3 })),
new ColumnWidget(
new TextWidget({ markdown: "goodnight", height: 1, width: 10 }),
new TextWidget({ markdown: "moon", height: 3, width: 10 }),
new TextWidget({ markdown: "!", height: 5, width: 10 })),
new ColumnWidget(new TextWidget("byebye")),
new ColumnWidget(new TextWidget("byebye2")));
assert.equal(json, `{
"widgets": [
{
"x": 0,
"y": 0,
"width": 6,
"height": 4,
"type": "text",
"properties": {
"markdown": "hello"
}
},
{
"x": 0,
"y": 4,
"width": 6,
"height": 3,
"type": "text",
"properties": {
"markdown": "world"
}
},
{
"x": 6,
"y": 0,
"width": 10,
"height": 1,
"type": "text",
"properties": {
"markdown": "goodnight"
}
},
{
"x": 6,
"y": 1,
"width": 10,
"height": 3,
"type": "text",
"properties": {
"markdown": "moon"
}
},
{
"x": 6,
"y": 4,
"width": 10,
"height": 5,
"type": "text",
"properties": {
"markdown": "!"
}
},
{
"x": 16,
"y": 0,
"width": 6,
"height": 6,
"type": "text",
"properties": {
"markdown": "byebye"
}
},
{
"x": 0,
"y": 9,
"width": 6,
"height": 6,
"type": "text",
"properties": {
"markdown": "byebye2"
}
}
]
}`);
});
});
});
describe("metric widgets", () => {
describe("single number", () => {
if (semver.gte(process.version, "10.0.0")) {
it("empty metrics", async () => {
await assert.rejects(async () => {
const json = await bodyJson(new SingleNumberMetricWidget({}));
});
});
it("invalid period", async () => {
await assert.rejects(async () => {
const json = await bodyJson(new SingleNumberMetricWidget({
metrics: [new Metric({ namespace: "AWS/EC2", name: "NetworkIn", period: 5 })],
}));
});
});
}
it("single metric", async () => {
const json = await bodyJson(new SingleNumberMetricWidget({
metrics: [new Metric({
namespace: "AWS/Lambda",
name: "Invocations",
})],
}));
assert.equal(json, `{
"widgets": [
{
"x": 0,
"y": 0,
"width": 6,
"height": 6,
"type": "metric",
"properties": {
"metrics": [
[
"AWS/Lambda",
"Invocations",
{
"stat": "Average",
"period": 300,
"visible": true,
"yAxis": "left"
}
]
],
"period": 300,
"region": "us-east-2",
"view": "singleValue",
"stacked": false
}
}
]
}`);
});
it("stat", async () => {
const json = await bodyJson(new SingleNumberMetricWidget({
metrics: [new Metric({
namespace: "AWS/Lambda",
name: "Invocations",
statistic: "SampleCount",
})],
}));
assert.equal(json, `{
"widgets": [
{
"x": 0,
"y": 0,
"width": 6,
"height": 6,
"type": "metric",
"properties": {
"metrics": [
[
"AWS/Lambda",
"Invocations",
{
"stat": "SampleCount",
"period": 300,
"visible": true,
"yAxis": "left"
}
]
],
"period": 300,
"region": "us-east-2",
"view": "singleValue",
"stacked": false
}
}
]
}`);
});
it("extended stat", async () => {
const json = await bodyJson(new SingleNumberMetricWidget({
metrics: [new Metric({
namespace: "AWS/Lambda",
name: "Invocations",
extendedStatistic: 99,
})],
}));
assert.equal(json, `{
"widgets": [
{
"x": 0,
"y": 0,
"width": 6,
"height": 6,
"type": "metric",
"properties": {
"metrics": [
[
"AWS/Lambda",
"Invocations",
{
"stat": "p99",
"period": 300,
"visible": true,
"yAxis": "left"
}
]
],
"period": 300,
"region": "us-east-2",
"view": "singleValue",
"stacked": false
}
}
]
}`);
});
it("multiple metrics", async () => {
const json = await bodyJson(new SingleNumberMetricWidget({
metrics: [
new Metric({ namespace: "AWS/Lambda", name: "Invocations", yAxis: "right" }),
new Metric({ namespace: "AWS/EC2", name: "NetworkIn", period: 60 }),
],
}));
assert.equal(json, `{
"widgets": [
{
"x": 0,
"y": 0,
"width": 6,
"height": 6,
"type": "metric",
"properties": {
"metrics": [
[
"AWS/Lambda",
"Invocations",
{
"stat": "Average",
"period": 300,
"visible": true,
"yAxis": "right"
}
],
[
"AWS/EC2",
"NetworkIn",
{
"stat": "Average",
"period": 60,
"visible": true,
"yAxis": "left"
}
]
],
"period": 300,
"region": "us-east-2",
"view": "singleValue",
"stacked": false
}
}
]
}`);
});
it("with dimension", async () => {
const json = await bodyJson(new SingleNumberMetricWidget({
metrics: [new Metric({
namespace: "AWS/Lambda",
name: "Invocations",
dimensions: {
FunctionName: "MyFunc",
Hello: "world",
},
})],
}));
assert.equal(json, `{
"widgets": [
{
"x": 0,
"y": 0,
"width": 6,
"height": 6,
"type": "metric",
"properties": {
"metrics": [
[
"AWS/Lambda",
"Invocations",
"FunctionName",
"MyFunc",
"Hello",
"world",
{
"stat": "Average",
"period": 300,
"visible": true,
"yAxis": "left"
}
]
],
"period": 300,
"region": "us-east-2",
"view": "singleValue",
"stacked": false
}
}
]
}`);
});
it("alarm annotation", async () => {
const json = await bodyJson(new SingleNumberMetricWidget({
metrics: [new Metric({
namespace: "AWS/Lambda",
name: "Invocations",
})],
annotations: [new AlarmAnnotation("some_arn")],
}));
assert.equal(json, `{
"widgets": [
{
"x": 0,
"y": 0,
"width": 6,
"height": 6,
"type": "metric",
"properties": {
"metrics": [
[
"AWS/Lambda",
"Invocations",
{
"stat": "Average",
"period": 300,
"visible": true,
"yAxis": "left"
}
]
],
"annotations": {
"alarms": [
"some_arn"
]
},
"period": 300,
"region": "us-east-2",
"view": "singleValue",
"stacked": false
}
}
]
}`);
});
});
describe("stacked area graph", () => {
it("single metric", async () => {
const json = await bodyJson(new StackedAreaGraphMetricWidget({
metrics: [new Metric({
namespace: "AWS/Lambda",
name: "Invocations",
})],
}));
assert.equal(json, `{
"widgets": [
{
"x": 0,
"y": 0,
"width": 6,
"height": 6,
"type": "metric",
"properties": {
"metrics": [
[
"AWS/Lambda",
"Invocations",
{
"stat": "Average",
"period": 300,
"visible": true,
"yAxis": "left"
}
]
],
"period": 300,
"region": "us-east-2",
"view": "timeSeries",
"stacked": true
}
}
]
}`);
});
});
describe("line graph", () => {
it("single metric", async () => {
const json = await bodyJson(new LineGraphMetricWidget({
metrics: [new Metric({
namespace: "AWS/Lambda",
name: "Invocations",
})],
}));
assert.equal(json, `{
"widgets": [
{
"x": 0,
"y": 0,
"width": 6,
"height": 6,
"type": "metric",
"properties": {
"metrics": [
[
"AWS/Lambda",
"Invocations",
{
"stat": "Average",
"period": 300,
"visible": true,
"yAxis": "left"
}
]
],
"period": 300,
"region": "us-east-2",
"view": "timeSeries",
"stacked": false
}
}
]
}`);
});
});
});
describe("realworld", () => {
it("realword 1", async () => {
const json = await toJson({
start: "-PT6H",
periodOverride: "inherit",
widgets: [
new LineGraphMetricWidget({
width: 12, height: 6,
period: 300,
statistic: "Average",
title: "EC2 Instance CPU",
metrics: [
new Metric({
namespace: "AWS/EC2",
name: "DiskReadBytes",
dimensions: {
InstanceId: "i-123",
},
}),
new ExpressionWidgetMetric("SUM(METRICS())", "Sum of DiskReadbytes", "e3"),
],
}),
new LineGraphMetricWidget({
width: 18, height: 9,
period: 300,
statistic: "Average",
title: "EC2 Instance CPU",
metrics: [
new ExpressionWidgetMetric("SEARCH('{AWS/EC2,InstanceId} MetricName=\"CPUUtilization\"', 'Average', 300)", undefined, "e1"),
],
}),
],
});
assert.equal(json, `{
"start": "-PT6H",
"periodOverride": "inherit",
"widgets": [
{
"x": 0,
"y": 0,
"width": 12,
"height": 6,
"type": "metric",
"properties": {
"stat": "Average",
"metrics": [
[
"AWS/EC2",
"DiskReadBytes",
"InstanceId",
"i-123",
{
"stat": "Average",
"period": 300,
"visible": true,
"yAxis": "left"
}
],
[
{
"expression": "SUM(METRICS())",
"label": "Sum of DiskReadbytes",
"id": "e3"
}
]
],
"title": "EC2 Instance CPU",
"period": 300,
"region": "us-east-2",
"view": "timeSeries",
"stacked": false
}
},
{
"x": 0,
"y": 6,
"width": 18,
"height": 9,
"type": "metric",
"properties": {
"stat": "Average",
"metrics": [
[
{
"expression": "SEARCH('{AWS/EC2,InstanceId} MetricName=\\"CPUUtilization\\"', 'Average', 300)",
"id": "e1"
}
]
],
"title": "EC2 Instance CPU",
"period": 300,
"region": "us-east-2",
"view": "timeSeries",
"stacked": false
}
}
]
}`);
});
it("realword 2", async () => {
const json = await bodyJson(new StackedAreaGraphMetricWidget({
width: 12, height: 6,
period: 300,
statistic: "Average",
title: "EC2 Instance CPU",
yAxis: { left: { min: 0, max: 100 }, right: { min: 50 } },
annotations: [new HorizontalAnnotation({
aboveEdge: {
"label": "Critical range",
"value": 20,
},
"visible": true,
"color": "#9467bd",
"fill": "above",
"yAxis": "right",
})],
metrics: [
new Metric({
namespace: "AWS/EC2",
name: "CPUUtilization",
dimensions: {
InstanceId: "i-012345",
},
}),
new Metric({
namespace: "AWS/EC2",
name: "NetworkIn",
dimensions: {
InstanceId: "i-012345",
},
yAxis: "right",
label: "NetworkIn",
period: 3600,
statistic: "Maximum",
}),
],
}));
assert.equal(json, `{
"widgets": [
{
"x": 0,
"y": 0,
"width": 12,
"height": 6,
"type": "metric",
"properties": {
"stat": "Average",
"metrics": [
[
"AWS/EC2",
"CPUUtilization",
"InstanceId",
"i-012345",
{
"stat": "Average",
"period": 300,
"visible": true,
"yAxis": "left"
}
],
[
"AWS/EC2",
"NetworkIn",
"InstanceId",
"i-012345",
{
"stat": "Maximum",
"label": "NetworkIn",
"period": 3600,
"visible": true,
"yAxis": "right"
}
]
],
"annotations": {
"horizontal": [
{
"fill": "above",
"color": "#9467bd",
"label": "Critical range",
"value": 20,
"visible": true,
"yAxis": "right"
}
]
},
"title": "EC2 Instance CPU",
"period": 300,
"region": "us-east-2",
"view": "timeSeries",
"stacked": true,
"yAxis": {
"left": {
"min": 0,
"max": 100
},
"right": {
"min": 50
}
}
}
}
]
}`);
});
});
}); | the_stack |
import {createPopper, StrictModifiers, Modifier} from '@popperjs/core';
import {currentInput} from './bindGlobalEventListeners';
import {isIE11} from './browser';
import {TIPPY_DEFAULT_APPEND_TO, TOUCH_OPTIONS} from './constants';
import {
actualContains,
div,
getOwnerDocument,
isCursorOutsideInteractiveBorder,
isMouseEvent,
setTransitionDuration,
setVisibilityState,
updateTransitionEndListener,
} from './dom-utils';
import {defaultProps, evaluateProps, getExtendedPassedProps} from './props';
import {getChildren} from './template';
import {
Content,
Instance,
LifecycleHooks,
PopperElement,
Props,
ReferenceElement,
} from './types';
import {ListenerObject, PopperTreeData, PopperChildren} from './types-internal';
import {
arrayFrom,
debounce,
getValueAtIndexOrReturn,
invokeWithArgsOrReturn,
normalizeToArray,
pushIfUnique,
splitBySpaces,
unique,
removeUndefinedProps,
} from './utils';
import {createMemoryLeakWarning, errorWhen, warnWhen} from './validation';
let idCounter = 1;
let mouseMoveListeners: ((event: MouseEvent) => void)[] = [];
// Used by `hideAll()`
export let mountedInstances: Instance[] = [];
export default function createTippy(
reference: ReferenceElement,
passedProps: Partial<Props>
): Instance {
const props = evaluateProps(reference, {
...defaultProps,
...getExtendedPassedProps(removeUndefinedProps(passedProps)),
});
// ===========================================================================
// 🔒 Private members
// ===========================================================================
let showTimeout: any;
let hideTimeout: any;
let scheduleHideAnimationFrame: number;
let isVisibleFromClick = false;
let didHideDueToDocumentMouseDown = false;
let didTouchMove = false;
let ignoreOnFirstUpdate = false;
let lastTriggerEvent: Event | undefined;
let currentTransitionEndListener: (event: TransitionEvent) => void;
let onFirstUpdate: () => void;
let listeners: ListenerObject[] = [];
let debouncedOnMouseMove = debounce(onMouseMove, props.interactiveDebounce);
let currentTarget: Element;
// ===========================================================================
// 🔑 Public members
// ===========================================================================
const id = idCounter++;
const popperInstance = null;
const plugins = unique(props.plugins);
const state = {
// Is the instance currently enabled?
isEnabled: true,
// Is the tippy currently showing and not transitioning out?
isVisible: false,
// Has the instance been destroyed?
isDestroyed: false,
// Is the tippy currently mounted to the DOM?
isMounted: false,
// Has the tippy finished transitioning in?
isShown: false,
};
const instance: Instance = {
// properties
id,
reference,
popper: div(),
popperInstance,
props,
state,
plugins,
// methods
clearDelayTimeouts,
setProps,
setContent,
show,
hide,
hideWithInteractivity,
enable,
disable,
unmount,
destroy,
};
// TODO: Investigate why this early return causes a TDZ error in the tests —
// it doesn't seem to happen in the browser
/* istanbul ignore if */
if (!props.render) {
if (__DEV__) {
errorWhen(true, 'render() function has not been supplied.');
}
return instance;
}
// ===========================================================================
// Initial mutations
// ===========================================================================
const {popper, onUpdate} = props.render(instance);
popper.setAttribute('data-__NAMESPACE_PREFIX__-root', '');
popper.id = `__NAMESPACE_PREFIX__-${instance.id}`;
instance.popper = popper;
reference._tippy = instance;
popper._tippy = instance;
const pluginsHooks = plugins.map((plugin) => plugin.fn(instance));
const hasAriaExpanded = reference.hasAttribute('aria-expanded');
addListeners();
handleAriaExpandedAttribute();
handleStyles();
invokeHook('onCreate', [instance]);
if (props.showOnCreate) {
scheduleShow();
}
// Prevent a tippy with a delay from hiding if the cursor left then returned
// before it started hiding
popper.addEventListener('mouseenter', () => {
if (instance.props.interactive && instance.state.isVisible) {
instance.clearDelayTimeouts();
}
});
popper.addEventListener('mouseleave', (event) => {
if (
instance.props.interactive &&
instance.props.trigger.indexOf('mouseenter') >= 0
) {
getDocument().addEventListener('mousemove', debouncedOnMouseMove);
debouncedOnMouseMove(event);
}
});
return instance;
// ===========================================================================
// 🔒 Private methods
// ===========================================================================
function getNormalizedTouchSettings(): [string | boolean, number] {
const {touch} = instance.props;
return Array.isArray(touch) ? touch : [touch, 0];
}
function getIsCustomTouchBehavior(): boolean {
return getNormalizedTouchSettings()[0] === 'hold';
}
function getIsDefaultRenderFn(): boolean {
// @ts-ignore
return !!instance.props.render?.$$tippy;
}
function getCurrentTarget(): Element {
return currentTarget || reference;
}
function getDocument(): Document {
const parent = getCurrentTarget().parentNode as Element;
return parent ? getOwnerDocument(parent) : document;
}
function getDefaultTemplateChildren(): PopperChildren {
return getChildren(popper);
}
function getDelay(isShow: boolean): number {
// For touch or keyboard input, force `0` delay for UX reasons
// Also if the instance is mounted but not visible (transitioning out),
// ignore delay
if (
(instance.state.isMounted && !instance.state.isVisible) ||
currentInput.isTouch ||
(lastTriggerEvent && lastTriggerEvent.type === 'focus')
) {
return 0;
}
return getValueAtIndexOrReturn(
instance.props.delay,
isShow ? 0 : 1,
defaultProps.delay
);
}
function handleStyles(): void {
popper.style.pointerEvents =
instance.props.interactive && instance.state.isVisible ? '' : 'none';
popper.style.zIndex = `${instance.props.zIndex}`;
}
function invokeHook(
hook: keyof LifecycleHooks,
args: [Instance, any?],
shouldInvokePropsHook = true
): void {
pluginsHooks.forEach((pluginHooks) => {
if (pluginHooks[hook]) {
pluginHooks[hook]!(...args);
}
});
if (shouldInvokePropsHook) {
instance.props[hook](...args);
}
}
function handleAriaContentAttribute(): void {
const {aria} = instance.props;
if (!aria.content) {
return;
}
const attr = `aria-${aria.content}`;
const id = popper.id;
const nodes = normalizeToArray(instance.props.triggerTarget || reference);
nodes.forEach((node) => {
const currentValue = node.getAttribute(attr);
if (instance.state.isVisible) {
node.setAttribute(attr, currentValue ? `${currentValue} ${id}` : id);
} else {
const nextValue = currentValue && currentValue.replace(id, '').trim();
if (nextValue) {
node.setAttribute(attr, nextValue);
} else {
node.removeAttribute(attr);
}
}
});
}
function handleAriaExpandedAttribute(): void {
if (hasAriaExpanded || !instance.props.aria.expanded) {
return;
}
const nodes = normalizeToArray(instance.props.triggerTarget || reference);
nodes.forEach((node) => {
if (instance.props.interactive) {
node.setAttribute(
'aria-expanded',
instance.state.isVisible && node === getCurrentTarget()
? 'true'
: 'false'
);
} else {
node.removeAttribute('aria-expanded');
}
});
}
function cleanupInteractiveMouseListeners(): void {
getDocument().removeEventListener('mousemove', debouncedOnMouseMove);
mouseMoveListeners = mouseMoveListeners.filter(
(listener) => listener !== debouncedOnMouseMove
);
}
function onDocumentPress(event: MouseEvent | TouchEvent): void {
// Moved finger to scroll instead of an intentional tap outside
if (currentInput.isTouch) {
if (didTouchMove || event.type === 'mousedown') {
return;
}
}
const actualTarget =
(event.composedPath && event.composedPath()[0]) || event.target;
// Clicked on interactive popper
if (
instance.props.interactive &&
actualContains(popper, actualTarget as Element)
) {
return;
}
// Clicked on the event listeners target
if (actualContains(getCurrentTarget(), actualTarget as Element)) {
if (currentInput.isTouch) {
return;
}
if (
instance.state.isVisible &&
instance.props.trigger.indexOf('click') >= 0
) {
return;
}
} else {
invokeHook('onClickOutside', [instance, event]);
}
if (instance.props.hideOnClick === true) {
instance.clearDelayTimeouts();
instance.hide();
// `mousedown` event is fired right before `focus` if pressing the
// currentTarget. This lets a tippy with `focus` trigger know that it
// should not show
didHideDueToDocumentMouseDown = true;
setTimeout(() => {
didHideDueToDocumentMouseDown = false;
});
// The listener gets added in `scheduleShow()`, but this may be hiding it
// before it shows, and hide()'s early bail-out behavior can prevent it
// from being cleaned up
if (!instance.state.isMounted) {
removeDocumentPress();
}
}
}
function onTouchMove(): void {
didTouchMove = true;
}
function onTouchStart(): void {
didTouchMove = false;
}
function addDocumentPress(): void {
const doc = getDocument();
doc.addEventListener('mousedown', onDocumentPress, true);
doc.addEventListener('touchend', onDocumentPress, TOUCH_OPTIONS);
doc.addEventListener('touchstart', onTouchStart, TOUCH_OPTIONS);
doc.addEventListener('touchmove', onTouchMove, TOUCH_OPTIONS);
}
function removeDocumentPress(): void {
const doc = getDocument();
doc.removeEventListener('mousedown', onDocumentPress, true);
doc.removeEventListener('touchend', onDocumentPress, TOUCH_OPTIONS);
doc.removeEventListener('touchstart', onTouchStart, TOUCH_OPTIONS);
doc.removeEventListener('touchmove', onTouchMove, TOUCH_OPTIONS);
}
function onTransitionedOut(duration: number, callback: () => void): void {
onTransitionEnd(duration, () => {
if (
!instance.state.isVisible &&
popper.parentNode &&
popper.parentNode.contains(popper)
) {
callback();
}
});
}
function onTransitionedIn(duration: number, callback: () => void): void {
onTransitionEnd(duration, callback);
}
function onTransitionEnd(duration: number, callback: () => void): void {
const box = getDefaultTemplateChildren().box;
function listener(event: TransitionEvent): void {
if (event.target === box) {
updateTransitionEndListener(box, 'remove', listener);
callback();
}
}
// Make callback synchronous if duration is 0
// `transitionend` won't fire otherwise
if (duration === 0) {
return callback();
}
updateTransitionEndListener(box, 'remove', currentTransitionEndListener);
updateTransitionEndListener(box, 'add', listener);
currentTransitionEndListener = listener;
}
function on(
eventType: string,
handler: EventListener,
options: boolean | Record<string, unknown> = false
): void {
const nodes = normalizeToArray(instance.props.triggerTarget || reference);
nodes.forEach((node) => {
node.addEventListener(eventType, handler, options);
listeners.push({node, eventType, handler, options});
});
}
function addListeners(): void {
if (getIsCustomTouchBehavior()) {
on('touchstart', onTrigger, {passive: true});
on('touchend', onMouseLeave as EventListener, {passive: true});
}
splitBySpaces(instance.props.trigger).forEach((eventType) => {
if (eventType === 'manual') {
return;
}
on(eventType, onTrigger);
switch (eventType) {
case 'mouseenter':
on('mouseleave', onMouseLeave as EventListener);
break;
case 'focus':
on(isIE11 ? 'focusout' : 'blur', onBlurOrFocusOut as EventListener);
break;
case 'focusin':
on('focusout', onBlurOrFocusOut as EventListener);
break;
}
});
}
function removeListeners(): void {
listeners.forEach(({node, eventType, handler, options}: ListenerObject) => {
node.removeEventListener(eventType, handler, options);
});
listeners = [];
}
function onTrigger(event: Event): void {
let shouldScheduleClickHide = false;
if (
!instance.state.isEnabled ||
isEventListenerStopped(event) ||
didHideDueToDocumentMouseDown
) {
return;
}
const wasFocused = lastTriggerEvent?.type === 'focus';
lastTriggerEvent = event;
currentTarget = event.currentTarget as Element;
handleAriaExpandedAttribute();
if (!instance.state.isVisible && isMouseEvent(event)) {
// If scrolling, `mouseenter` events can be fired if the cursor lands
// over a new target, but `mousemove` events don't get fired. This
// causes interactive tooltips to get stuck open until the cursor is
// moved
mouseMoveListeners.forEach((listener) => listener(event));
}
// Toggle show/hide when clicking click-triggered tooltips
if (
event.type === 'click' &&
(instance.props.trigger.indexOf('mouseenter') < 0 ||
isVisibleFromClick) &&
instance.props.hideOnClick !== false &&
instance.state.isVisible
) {
shouldScheduleClickHide = true;
} else {
scheduleShow(event);
}
if (event.type === 'click') {
isVisibleFromClick = !shouldScheduleClickHide;
}
if (shouldScheduleClickHide && !wasFocused) {
scheduleHide(event);
}
}
function onMouseMove(event: MouseEvent): void {
const target = event.target as Node;
const isCursorOverReferenceOrPopper =
getCurrentTarget().contains(target) || popper.contains(target);
if (event.type === 'mousemove' && isCursorOverReferenceOrPopper) {
return;
}
const popperTreeData = getNestedPopperTree()
.concat(popper)
.map((popper) => {
const instance = popper._tippy!;
const state = instance.popperInstance?.state;
if (state) {
return {
popperRect: popper.getBoundingClientRect(),
popperState: state,
props,
};
}
return null;
})
.filter(Boolean) as PopperTreeData[];
if (isCursorOutsideInteractiveBorder(popperTreeData, event)) {
cleanupInteractiveMouseListeners();
scheduleHide(event);
}
}
function onMouseLeave(event: MouseEvent): void {
const shouldBail =
isEventListenerStopped(event) ||
(instance.props.trigger.indexOf('click') >= 0 && isVisibleFromClick);
if (shouldBail) {
return;
}
if (instance.props.interactive) {
instance.hideWithInteractivity(event);
return;
}
scheduleHide(event);
}
function onBlurOrFocusOut(event: FocusEvent): void {
if (
instance.props.trigger.indexOf('focusin') < 0 &&
event.target !== getCurrentTarget()
) {
return;
}
// If focus was moved to within the popper
if (
instance.props.interactive &&
event.relatedTarget &&
popper.contains(event.relatedTarget as Element)
) {
return;
}
scheduleHide(event);
}
function isEventListenerStopped(event: Event): boolean {
return currentInput.isTouch
? getIsCustomTouchBehavior() !== event.type.indexOf('touch') >= 0
: false;
}
function createPopperInstance(): void {
destroyPopperInstance();
const {
popperOptions,
placement,
offset,
getReferenceClientRect,
moveTransition,
} = instance.props;
const arrow = getIsDefaultRenderFn() ? getChildren(popper).arrow : null;
const computedReference = getReferenceClientRect
? {
getBoundingClientRect: getReferenceClientRect,
contextElement:
getReferenceClientRect.contextElement || getCurrentTarget(),
}
: reference;
const tippyModifier: Modifier<'$$tippy', Record<string, unknown>> = {
name: '$$tippy',
enabled: true,
phase: 'beforeWrite',
requires: ['computeStyles'],
fn({state}) {
if (getIsDefaultRenderFn()) {
const {box} = getDefaultTemplateChildren();
['placement', 'reference-hidden', 'escaped'].forEach((attr) => {
if (attr === 'placement') {
box.setAttribute('data-placement', state.placement);
} else {
if (state.attributes.popper[`data-popper-${attr}`]) {
box.setAttribute(`data-${attr}`, '');
} else {
box.removeAttribute(`data-${attr}`);
}
}
});
state.attributes.popper = {};
}
},
};
type TippyModifier = Modifier<'$$tippy', Record<string, unknown>>;
type ExtendedModifiers = StrictModifiers | Partial<TippyModifier>;
const modifiers: Array<ExtendedModifiers> = [
{
name: 'offset',
options: {
offset,
},
},
{
name: 'preventOverflow',
options: {
padding: {
top: 2,
bottom: 2,
left: 5,
right: 5,
},
},
},
{
name: 'flip',
options: {
padding: 5,
},
},
{
name: 'computeStyles',
options: {
adaptive: !moveTransition,
},
},
tippyModifier,
];
if (getIsDefaultRenderFn() && arrow) {
modifiers.push({
name: 'arrow',
options: {
element: arrow,
padding: 3,
},
});
}
modifiers.push(...(popperOptions?.modifiers || []));
instance.popperInstance = createPopper<ExtendedModifiers>(
computedReference,
popper,
{
...popperOptions,
placement,
onFirstUpdate,
modifiers,
}
);
}
function destroyPopperInstance(): void {
if (instance.popperInstance) {
instance.popperInstance.destroy();
instance.popperInstance = null;
}
}
function mount(): void {
const {appendTo} = instance.props;
let parentNode: any;
// By default, we'll append the popper to the triggerTargets's parentNode so
// it's directly after the reference element so the elements inside the
// tippy can be tabbed to
// If there are clipping issues, the user can specify a different appendTo
// and ensure focus management is handled correctly manually
const node = getCurrentTarget();
if (
(instance.props.interactive && appendTo === TIPPY_DEFAULT_APPEND_TO) ||
appendTo === 'parent'
) {
parentNode = node.parentNode;
} else {
parentNode = invokeWithArgsOrReturn(appendTo, [node]);
}
// The popper element needs to exist on the DOM before its position can be
// updated as Popper needs to read its dimensions
if (!parentNode.contains(popper)) {
parentNode.appendChild(popper);
}
createPopperInstance();
/* istanbul ignore else */
if (__DEV__) {
// Accessibility check
warnWhen(
instance.props.interactive &&
appendTo === defaultProps.appendTo &&
node.nextElementSibling !== popper,
[
'Interactive tippy element may not be accessible via keyboard',
'navigation because it is not directly after the reference element',
'in the DOM source order.',
'\n\n',
'Using a wrapper <div> or <span> tag around the reference element',
'solves this by creating a new parentNode context.',
'\n\n',
'Specifying `appendTo: document.body` silences this warning, but it',
'assumes you are using a focus management solution to handle',
'keyboard navigation.',
'\n\n',
'See: https://atomiks.github.io/tippyjs/v6/accessibility/#interactivity',
].join(' ')
);
}
}
function getNestedPopperTree(): PopperElement[] {
return arrayFrom(
popper.querySelectorAll('[data-__NAMESPACE_PREFIX__-root]')
);
}
function scheduleShow(event?: Event): void {
instance.clearDelayTimeouts();
if (event) {
invokeHook('onTrigger', [instance, event]);
}
addDocumentPress();
let delay = getDelay(true);
const [touchValue, touchDelay] = getNormalizedTouchSettings();
if (currentInput.isTouch && touchValue === 'hold' && touchDelay) {
delay = touchDelay;
}
if (delay) {
showTimeout = setTimeout(() => {
instance.show();
}, delay);
} else {
instance.show();
}
}
function scheduleHide(event: Event): void {
instance.clearDelayTimeouts();
invokeHook('onUntrigger', [instance, event]);
if (!instance.state.isVisible) {
removeDocumentPress();
return;
}
// For interactive tippies, scheduleHide is added to a document.body handler
// from onMouseLeave so must intercept scheduled hides from mousemove/leave
// events when trigger contains mouseenter and click, and the tip is
// currently shown as a result of a click.
if (
instance.props.trigger.indexOf('mouseenter') >= 0 &&
instance.props.trigger.indexOf('click') >= 0 &&
['mouseleave', 'mousemove'].indexOf(event.type) >= 0 &&
isVisibleFromClick
) {
return;
}
const delay = getDelay(false);
if (delay) {
hideTimeout = setTimeout(() => {
if (instance.state.isVisible) {
instance.hide();
}
}, delay);
} else {
// Fixes a `transitionend` problem when it fires 1 frame too
// late sometimes, we don't want hide() to be called.
scheduleHideAnimationFrame = requestAnimationFrame(() => {
instance.hide();
});
}
}
// ===========================================================================
// 🔑 Public methods
// ===========================================================================
function enable(): void {
instance.state.isEnabled = true;
}
function disable(): void {
// Disabling the instance should also hide it
// https://github.com/atomiks/tippy.js-react/issues/106
instance.hide();
instance.state.isEnabled = false;
}
function clearDelayTimeouts(): void {
clearTimeout(showTimeout);
clearTimeout(hideTimeout);
cancelAnimationFrame(scheduleHideAnimationFrame);
}
function setProps(partialProps: Partial<Props>): void {
/* istanbul ignore else */
if (__DEV__) {
warnWhen(instance.state.isDestroyed, createMemoryLeakWarning('setProps'));
}
if (instance.state.isDestroyed) {
return;
}
invokeHook('onBeforeUpdate', [instance, partialProps]);
removeListeners();
const prevProps = instance.props;
const nextProps = evaluateProps(reference, {
...prevProps,
...removeUndefinedProps(partialProps),
ignoreAttributes: true,
});
instance.props = nextProps;
addListeners();
if (prevProps.interactiveDebounce !== nextProps.interactiveDebounce) {
cleanupInteractiveMouseListeners();
debouncedOnMouseMove = debounce(
onMouseMove,
nextProps.interactiveDebounce
);
}
// Ensure stale aria-expanded attributes are removed
if (prevProps.triggerTarget && !nextProps.triggerTarget) {
normalizeToArray(prevProps.triggerTarget).forEach((node) => {
node.removeAttribute('aria-expanded');
});
} else if (nextProps.triggerTarget) {
reference.removeAttribute('aria-expanded');
}
handleAriaExpandedAttribute();
handleStyles();
if (onUpdate) {
onUpdate(prevProps, nextProps);
}
if (instance.popperInstance) {
createPopperInstance();
// Fixes an issue with nested tippies if they are all getting re-rendered,
// and the nested ones get re-rendered first.
// https://github.com/atomiks/tippyjs-react/issues/177
// TODO: find a cleaner / more efficient solution(!)
getNestedPopperTree().forEach((nestedPopper) => {
// React (and other UI libs likely) requires a rAF wrapper as it flushes
// its work in one
requestAnimationFrame(nestedPopper._tippy!.popperInstance!.forceUpdate);
});
}
invokeHook('onAfterUpdate', [instance, partialProps]);
}
function setContent(content: Content): void {
instance.setProps({content});
}
function show(): void {
/* istanbul ignore else */
if (__DEV__) {
warnWhen(instance.state.isDestroyed, createMemoryLeakWarning('show'));
}
// Early bail-out
const isAlreadyVisible = instance.state.isVisible;
const isDestroyed = instance.state.isDestroyed;
const isDisabled = !instance.state.isEnabled;
const isTouchAndTouchDisabled =
currentInput.isTouch && !instance.props.touch;
const duration = getValueAtIndexOrReturn(
instance.props.duration,
0,
defaultProps.duration
);
if (
isAlreadyVisible ||
isDestroyed ||
isDisabled ||
isTouchAndTouchDisabled
) {
return;
}
// Normalize `disabled` behavior across browsers.
// Firefox allows events on disabled elements, but Chrome doesn't.
// Using a wrapper element (i.e. <span>) is recommended.
if (getCurrentTarget().hasAttribute('disabled')) {
return;
}
invokeHook('onShow', [instance], false);
if (instance.props.onShow(instance) === false) {
return;
}
instance.state.isVisible = true;
if (getIsDefaultRenderFn()) {
popper.style.visibility = 'visible';
}
handleStyles();
addDocumentPress();
if (!instance.state.isMounted) {
popper.style.transition = 'none';
}
// If flipping to the opposite side after hiding at least once, the
// animation will use the wrong placement without resetting the duration
if (getIsDefaultRenderFn()) {
const {box, content} = getDefaultTemplateChildren();
setTransitionDuration([box, content], 0);
}
onFirstUpdate = (): void => {
if (!instance.state.isVisible || ignoreOnFirstUpdate) {
return;
}
ignoreOnFirstUpdate = true;
// reflow
void popper.offsetHeight;
popper.style.transition = instance.props.moveTransition;
if (getIsDefaultRenderFn() && instance.props.animation) {
const {box, content} = getDefaultTemplateChildren();
setTransitionDuration([box, content], duration);
setVisibilityState([box, content], 'visible');
}
handleAriaContentAttribute();
handleAriaExpandedAttribute();
pushIfUnique(mountedInstances, instance);
// certain modifiers (e.g. `maxSize`) require a second update after the
// popper has been positioned for the first time
instance.popperInstance?.forceUpdate();
instance.state.isMounted = true;
invokeHook('onMount', [instance]);
if (instance.props.animation && getIsDefaultRenderFn()) {
onTransitionedIn(duration, () => {
instance.state.isShown = true;
invokeHook('onShown', [instance]);
});
}
};
mount();
}
function hide(): void {
/* istanbul ignore else */
if (__DEV__) {
warnWhen(instance.state.isDestroyed, createMemoryLeakWarning('hide'));
}
// Early bail-out
const isAlreadyHidden = !instance.state.isVisible;
const isDestroyed = instance.state.isDestroyed;
const isDisabled = !instance.state.isEnabled;
const duration = getValueAtIndexOrReturn(
instance.props.duration,
1,
defaultProps.duration
);
if (isAlreadyHidden || isDestroyed || isDisabled) {
return;
}
invokeHook('onHide', [instance], false);
if (instance.props.onHide(instance) === false) {
return;
}
instance.state.isVisible = false;
instance.state.isShown = false;
ignoreOnFirstUpdate = false;
isVisibleFromClick = false;
if (getIsDefaultRenderFn()) {
popper.style.visibility = 'hidden';
}
cleanupInteractiveMouseListeners();
removeDocumentPress();
handleStyles();
if (getIsDefaultRenderFn()) {
const {box, content} = getDefaultTemplateChildren();
if (instance.props.animation) {
setTransitionDuration([box, content], duration);
setVisibilityState([box, content], 'hidden');
}
}
handleAriaContentAttribute();
handleAriaExpandedAttribute();
if (instance.props.animation) {
if (getIsDefaultRenderFn()) {
onTransitionedOut(duration, instance.unmount);
}
} else {
instance.unmount();
}
}
function hideWithInteractivity(event: MouseEvent): void {
/* istanbul ignore else */
if (__DEV__) {
warnWhen(
instance.state.isDestroyed,
createMemoryLeakWarning('hideWithInteractivity')
);
}
getDocument().addEventListener('mousemove', debouncedOnMouseMove);
pushIfUnique(mouseMoveListeners, debouncedOnMouseMove);
debouncedOnMouseMove(event);
}
function unmount(): void {
/* istanbul ignore else */
if (__DEV__) {
warnWhen(instance.state.isDestroyed, createMemoryLeakWarning('unmount'));
}
if (instance.state.isVisible) {
instance.hide();
}
if (!instance.state.isMounted) {
return;
}
destroyPopperInstance();
// If a popper is not interactive, it will be appended outside the popper
// tree by default. This seems mainly for interactive tippies, but we should
// find a workaround if possible
getNestedPopperTree().forEach((nestedPopper) => {
nestedPopper._tippy!.unmount();
});
if (popper.parentNode) {
popper.parentNode.removeChild(popper);
}
mountedInstances = mountedInstances.filter((i) => i !== instance);
instance.state.isMounted = false;
invokeHook('onHidden', [instance]);
}
function destroy(): void {
/* istanbul ignore else */
if (__DEV__) {
warnWhen(instance.state.isDestroyed, createMemoryLeakWarning('destroy'));
}
if (instance.state.isDestroyed) {
return;
}
instance.clearDelayTimeouts();
instance.unmount();
removeListeners();
delete reference._tippy;
instance.state.isDestroyed = true;
invokeHook('onDestroy', [instance]);
}
} | the_stack |
import { IFunctionFormulaInfo } from './types';
import { generateFormulaInfo } from './utils';
/**
* An array that contains the result_type and the variations of arguments (number and types) supported by all the notion formulas
*/
export const generateNotionFunctionFormulaInfoArray = (): IFunctionFormulaInfo[] => [
generateFormulaInfo('Switches between two options based on another value.', 'if', [
[ 'number', [ 'checkbox', 'number', 'number' ] ],
[ 'text', [ 'checkbox', 'text', 'text' ] ],
[ 'checkbox', [ 'checkbox', 'checkbox', 'checkbox' ] ],
[ 'date', [ 'checkbox', 'date', 'date' ] ]
]),
generateFormulaInfo(
'Adds two numbers and returns their sum, or concatenates two strings.',
'add',
[ [ 'text', [ 'text', 'text' ] ], [ 'number', [ 'number', 'number' ] ] ],
'+'
),
generateFormulaInfo('Returns the absolute value of a number', 'abs', [ [ 'number', [ 'number' ] ] ]),
generateFormulaInfo('Returns the cube root of a number.', 'cbrt', [ [ 'number', [ 'number' ] ] ]),
generateFormulaInfo('Negates a number.', 'unaryMinus', [ [ 'number', [ 'number' ] ] ], '-'),
generateFormulaInfo(
'Converts its argument into a number.',
'unaryPlus',
[ [ 'number', [ 'checkbox' ] ], [ 'number', [ 'text' ] ], [ 'number', [ 'number' ] ] ],
'+'
),
generateFormulaInfo('Returns the smallest integer greater than or equal to a number.', 'ceil', [
[ 'number', [ 'number' ] ]
]),
generateFormulaInfo(
"Returns E^x, where x is the argument, and E is Euler's constant (2.718…), the base of the natural logarithm.",
'exp',
[ [ 'number', [ 'number' ] ] ]
),
generateFormulaInfo('Returns the largest integer less than or equal to a number.', 'floor', [
[ 'number', [ 'number' ] ]
]),
generateFormulaInfo('Returns the natural logarithm of a number.', 'ln', [ [ 'number', [ 'number' ] ] ]),
generateFormulaInfo('Returns the base 10 logarithm of a number.', 'log10', [ [ 'number', [ 'number' ] ] ]),
generateFormulaInfo('Returns the base 2 logarithm of a number.', 'log2', [ [ 'number', [ 'number' ] ] ]),
{
description: 'Returns the largest of zero or more numbers.',
function_name: 'max',
signatures: [
{
result_type: 'number',
variadic: 'number'
}
]
},
{
description: 'Returns the smallest of zero or more numbers.',
function_name: 'min',
signatures: [
{
result_type: 'number',
variadic: 'number'
}
]
},
generateFormulaInfo('Returns the value of a number rounded to the nearest integer.', 'round', [
[ 'number', [ 'number' ] ]
]),
generateFormulaInfo('Returns the sign of the x, indicating whether x is positive, negative or zero.', 'sign', [
[ 'number', [ 'number' ] ]
]),
generateFormulaInfo('Returns the positive square root of a number.', 'sqrt', [ [ 'number', [ 'number' ] ] ]),
generateFormulaInfo(
'Returns true if its arguments are equal, and false otherwise.',
'equal',
[
[ 'checkbox', [ 'number', 'number' ] ],
[ 'checkbox', [ 'text', 'text' ] ],
[ 'checkbox', [ 'checkbox', 'checkbox' ] ],
[ 'checkbox', [ 'date', 'date' ] ]
],
'=='
),
generateFormulaInfo(
'Returns false if its arguments are equal, and true otherwise.',
'unequal',
[
[ 'checkbox', [ 'number', 'number' ] ],
[ 'checkbox', [ 'text', 'text' ] ],
[ 'checkbox', [ 'checkbox', 'checkbox' ] ],
[ 'checkbox', [ 'date', 'date' ] ]
],
'!='
),
generateFormulaInfo(
'Returns the logical AND of its two arguments.',
'and',
[ [ 'checkbox', [ 'checkbox', 'checkbox' ] ] ],
'and'
),
generateFormulaInfo(
'Returns the logical OR of its two arguments.',
'or',
[ [ 'checkbox', [ 'checkbox', 'checkbox' ] ] ],
'or'
),
generateFormulaInfo(
'Returns true if the first argument is larger than the second.',
'larger',
[
[ 'checkbox', [ 'number', 'number' ] ],
[ 'checkbox', [ 'text', 'text' ] ],
[ 'checkbox', [ 'checkbox', 'checkbox' ] ],
[ 'checkbox', [ 'date', 'date' ] ]
],
'>'
),
generateFormulaInfo(
'Returns true if the first argument is larger than or equal to than the second.',
'largerEq',
[
[ 'checkbox', [ 'number', 'number' ] ],
[ 'checkbox', [ 'text', 'text' ] ],
[ 'checkbox', [ 'checkbox', 'checkbox' ] ],
[ 'checkbox', [ 'date', 'date' ] ]
],
'>='
),
generateFormulaInfo(
'Returns true if the first argument is smaller than the second.',
'smaller',
[
[ 'checkbox', [ 'number', 'number' ] ],
[ 'checkbox', [ 'text', 'text' ] ],
[ 'checkbox', [ 'checkbox', 'checkbox' ] ],
[ 'checkbox', [ 'date', 'date' ] ]
],
'<'
),
generateFormulaInfo(
'Returns true if the first argument is smaller than or equal to than the second.',
'smallerEq',
[
[ 'checkbox', [ 'number', 'number' ] ],
[ 'checkbox', [ 'text', 'text' ] ],
[ 'checkbox', [ 'checkbox', 'checkbox' ] ],
[ 'checkbox', [ 'date', 'date' ] ]
],
'<='
),
generateFormulaInfo('Returns the logical NOT of its argument.', 'not', [ [ 'checkbox', [ 'checkbox' ] ] ], 'not'),
generateFormulaInfo(
'Subtracts two numbers and returns their difference.',
'subtract',
[ [ 'number', [ 'number', 'number' ] ] ],
'-'
),
generateFormulaInfo(
'Multiplies two numbers and returns their product.',
'multiply',
[ [ 'number', [ 'number', 'number' ] ] ],
'*'
),
generateFormulaInfo(
'Divides two numbers and returns their quotient.',
'divide',
[ [ 'number', [ 'number', 'number' ] ] ],
'/'
),
generateFormulaInfo(
'Returns base to the exponent power, that is, base exponent.',
'pow',
[ [ 'number', [ 'number', 'number' ] ] ],
'^'
),
generateFormulaInfo(
'Divides two numbers and returns their remainder.',
'mod',
[ [ 'number', [ 'number', 'number' ] ] ],
'%'
),
{
description: 'Concatenates its arguments and returns the result.',
function_name: 'concat',
signatures: [
{
result_type: 'text',
variadic: 'text'
}
]
},
{
description: 'Inserts the first argument between the rest and returns their concatenation.',
function_name: 'join',
signatures: [
{
result_type: 'text',
variadic: 'text'
}
]
},
generateFormulaInfo(
'Extracts a substring from a string from the start index (inclusively) to the end index (optional and exclusively).',
'slice',
[ [ 'text', [ 'text', 'number' ] ], [ 'text', [ 'text', 'number', 'number' ] ] ]
),
generateFormulaInfo('Returns the length of a string.', 'length', [ [ 'number', [ 'text' ] ] ]),
generateFormulaInfo('Formats its argument as a string.', 'format', [
[ 'text', [ 'text' ] ],
[ 'text', [ 'date' ] ],
[ 'text', [ 'number' ] ],
[ 'text', [ 'checkbox' ] ]
]),
generateFormulaInfo('Parses a number from text.', 'toNumber', [
[ 'number', [ 'text' ] ],
[ 'number', [ 'date' ] ],
[ 'number', [ 'number' ] ],
[ 'number', [ 'checkbox' ] ]
]),
generateFormulaInfo('Returns true if the second argument is found in the first.', 'contains', [
[ 'checkbox', [ 'text', 'text' ] ]
]),
generateFormulaInfo('Replaces the first match of a regular expression with a new value.', 'replace', [
[ 'text', [ 'text', 'text', 'text' ] ],
[ 'text', [ 'number', 'text', 'text' ] ],
[ 'text', [ 'checkbox', 'text', 'text' ] ]
]),
generateFormulaInfo('Replaces all matches of a regular expression with a new value.', 'replaceAll', [
[ 'text', [ 'text', 'text', 'text' ] ],
[ 'text', [ 'number', 'text', 'text' ] ],
[ 'text', [ 'checkbox', 'text', 'text' ] ]
]),
generateFormulaInfo('Tests if a string matches a regular expression.', 'test', [
[ 'checkbox', [ 'text', 'text' ] ],
[ 'checkbox', [ 'number', 'text' ] ],
[ 'checkbox', [ 'checkbox', 'text' ] ]
]),
generateFormulaInfo('Tests if a value is empty.', 'empty', [
[ 'checkbox', [ 'text' ] ],
[ 'checkbox', [ 'number' ] ],
[ 'checkbox', [ 'checkbox' ] ],
[ 'checkbox', [ 'date' ] ]
]),
generateFormulaInfo('Returns the start of a date range.', 'start', [ [ 'date', [ 'date' ] ] ]),
generateFormulaInfo('Returns the end of a date range.', 'end', [ [ 'date', [ 'date' ] ] ]),
generateFormulaInfo('Returns the current date and time.', 'now', [ [ 'date', [] ] ]),
generateFormulaInfo(
'Returns a date constructed from a Unix millisecond timestamp, corresponding to the number of milliseconds since January 1, 1970.',
'fromTimestamp',
[ [ 'date', [ 'number' ] ] ]
),
generateFormulaInfo(
'Add to a date. The last argument, unit, can be one of: "years", "quarters", "months", "weeks", "days", "hours", "minutes", "seconds", or "milliseconds".',
'dateAdd',
[ [ 'date', [ 'date', 'number', 'text' ] ] ]
),
generateFormulaInfo(
'Subtract from a date. The last argument, unit, can be one of: "years", "quarters", "months", "weeks", "days", "hours", "minutes", "seconds", or "milliseconds".',
'dateSubtract',
[ [ 'date', [ 'date', 'number', 'text' ] ] ]
),
generateFormulaInfo(
'Returns the time between two dates. The last argument, unit, can be one of: "years", "quarters", "months", "weeks", "days", "hours", "minutes", "seconds", or "milliseconds".',
'dateBetween',
[ [ 'number', [ 'date', 'date', 'text' ] ] ]
),
generateFormulaInfo('Format a date using the Moment standard time format string.', 'formatDate', [
[ 'text', [ 'date', 'text' ] ]
]),
generateFormulaInfo(
'Returns an integer number from a Unix millisecond timestamp, corresponding to the number of milliseconds since January 1, 1970.',
'timestamp',
[ [ 'number', [ 'date' ] ] ]
),
generateFormulaInfo(
'Returns an integer number, between 0 and 59, corresponding to minutes in the given date.',
'minute',
[ [ 'number', [ 'date' ] ] ]
),
generateFormulaInfo(
'Returns an integer number, between 0 and 23, corresponding to hour for the given date.',
'hour',
[ [ 'number', [ 'date' ] ] ]
),
generateFormulaInfo(
'Returns an integer number, between 1 and 31, corresponding to day of the month for the given.',
'date',
[ [ 'number', [ 'date' ] ] ]
),
generateFormulaInfo(
'Returns an integer number corresponding to the day of the week for the given date: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on.',
'day',
[ [ 'number', [ 'date' ] ] ]
),
generateFormulaInfo(
'Returns an integer number, between 0 and 11, corresponding to month in the given date according to local time. 0 corresponds to January, 1 to February, and so on.',
'month',
[ [ 'number', [ 'date' ] ] ]
),
generateFormulaInfo('Returns a number corresponding to the year of the given date.', 'year', [
[ 'number', [ 'date' ] ]
])
]; | the_stack |
import { PortablePath } from '@yarnpkg/fslib';
import querystring from 'querystring';
import { Configuration } from './Configuration';
import { Workspace } from './Workspace';
import { Ident, Descriptor, Locator, Package } from './types';
/**
* Creates a package ident.
*
* @param scope The package scope without the `@` prefix (eg. `types`)
* @param name The name of the package
*/
export declare function makeIdent(scope: string | null, name: string): Ident;
/**
* Creates a package descriptor.
*
* @param ident The base ident (see `makeIdent`)
* @param range The range to attach (eg. `^1.0.0`)
*/
export declare function makeDescriptor(ident: Ident, range: string): Descriptor;
/**
* Creates a package locator.
*
* @param ident The base ident (see `makeIdent`)
* @param range The reference to attach (eg. `1.0.0`)
*/
export declare function makeLocator(ident: Ident, reference: string): Locator;
/**
* Turns a compatible source to an ident. You won't really have to use this
* function since by virtue of structural inheritance all descriptors and
* locators are already valid idents.
*
* This function is only useful if you absolutely need to remove the non-ident
* fields from a structure before storing it somewhere.
*
* @param source The data structure to convert into an ident.
*/
export declare function convertToIdent(source: Descriptor | Locator | Package): Ident;
/**
* Turns a descriptor into a locator.
*
* Note that this process may be unsafe, as descriptors may reference multiple
* packages, putting them at odd with locators' expected semantic. Only makes
* sense when used with single-resolution protocols, for instance `file:`.
*
* @param descriptor The descriptor to convert into a locator.
*/
export declare function convertDescriptorToLocator(descriptor: Descriptor): Locator;
/**
* Turns a locator into a descriptor.
*
* This should be safe to do regardless of the locator, since all locator
* references are expected to be valid descriptor ranges.
*
* @param locator The locator to convert into a descriptor.
*/
export declare function convertLocatorToDescriptor(locator: Locator): Descriptor;
/**
* Turns a package structure into a simple locator. You won't often need to
* call this function since packages are already valid locators by virtue of
* structural inheritance.
*
* This function is only useful if you absolutely need to remove the
* non-locator fields from a structure before storing it somewhere.
*
* @param pkg The package to convert into a locator.
*/
export declare function convertPackageToLocator(pkg: Package): Locator;
/**
* Deep copies a package then change its locator to something else.
*
* @param pkg The source package
* @param locator Its new new locator
*/
export declare function renamePackage(pkg: Package, locator: Locator): Package;
/**
* Deep copies a package. The copy will share the same locator as the original.
*
* @param pkg The source package
*/
export declare function copyPackage(pkg: Package): Package;
/**
* Creates a new virtual descriptor from a non virtual one.
*
* @param descriptor The descriptor to virtualize
* @param entropy A hash that provides uniqueness to this virtualized descriptor (normally a locator hash)
*/
export declare function virtualizeDescriptor(descriptor: Descriptor, entropy: string): Descriptor;
/**
* Creates a new virtual package from a non virtual one.
*
* @param pkg The package to virtualize
* @param entropy A hash that provides uniqueness to this virtualized package (normally a locator hash)
*/
export declare function virtualizePackage(pkg: Package, entropy: string): Package;
/**
* Returns `true` if the descriptor is virtual.
*/
export declare function isVirtualDescriptor(descriptor: Descriptor): boolean;
/**
* Returns `true` if the locator is virtual.
*/
export declare function isVirtualLocator(locator: Locator): boolean;
/**
* Returns a new devirtualized descriptor based on a virtualized descriptor
*/
export declare function devirtualizeDescriptor(descriptor: Descriptor): Descriptor;
/**
* Returns a new devirtualized locator based on a virtualized locator
* @param locator the locator
*/
export declare function devirtualizeLocator(locator: Locator): Locator;
/**
* Some descriptors only make sense when bound with some internal state. For
* instance that would be the case for the `file:` ranges, which require to
* be bound to their parent packages in order to resolve relative paths from
* the right location.
*
* This function will apply the specified parameters onto the requested
* descriptor, but only if it didn't get bound before (important to handle the
* case where we replace a descriptor by another, since when that happens the
* replacement has probably been already bound).
*
* @param descriptor The original descriptor
* @param params The parameters to encode in the range
*/
export declare function bindDescriptor(descriptor: Descriptor, params: {
[key: string]: string;
}): Descriptor;
/**
* Some locators only make sense when bound with some internal state. For
* instance that would be the case for the `file:` references, which require to
* be bound to their parent packages in order to resolve relative paths from
* the right location.
*
* This function will apply the specified parameters onto the requested
* locator, but only if it didn't get bound before (important to handle the
* case where we replace a locator by another, since when that happens the
* replacement has probably been already bound).
*
* @param locator The original locator
* @param params The parameters to encode in the reference
*/
export declare function bindLocator(locator: Locator, params: {
[key: string]: string;
}): Locator;
/**
* Returns `true` if the idents are equal
*/
export declare function areIdentsEqual(a: Ident, b: Ident): boolean;
/**
* Returns `true` if the descriptors are equal
*/
export declare function areDescriptorsEqual(a: Descriptor, b: Descriptor): boolean;
/**
* Returns `true` if the locators are equal
*/
export declare function areLocatorsEqual(a: Locator, b: Locator): boolean;
/**
* Virtual packages are considered equivalent when they belong to the same
* package identity and have the same dependencies. Note that equivalence
* is not the same as equality, as the references may be different.
*/
export declare function areVirtualPackagesEquivalent(a: Package, b: Package): boolean;
/**
* Parses a string into an ident.
*
* Throws an error if the ident cannot be parsed.
*
* @param string The ident string (eg. `@types/lodash`)
*/
export declare function parseIdent(string: string): Ident;
/**
* Parses a string into an ident.
*
* Returns `null` if the ident cannot be parsed.
*
* @param string The ident string (eg. `@types/lodash`)
*/
export declare function tryParseIdent(string: string): Ident | null;
/**
* Parses a `string` into a descriptor
*
* Throws an error if the descriptor cannot be parsed.
*
* @param string The descriptor string (eg. `lodash@^1.0.0`)
* @param strict If `false`, the range is optional (`unknown` will be used as fallback)
*/
export declare function parseDescriptor(string: string, strict?: boolean): Descriptor;
/**
* Parses a `string` into a descriptor
*
* Returns `null` if the descriptor cannot be parsed.
*
* @param string The descriptor string (eg. `lodash@^1.0.0`)
* @param strict If `false`, the range is optional (`unknown` will be used as fallback)
*/
export declare function tryParseDescriptor(string: string, strict?: boolean): Descriptor | null;
/**
* Parses a `string` into a locator
*
* Throws an error if the locator cannot be parsed.
*
* @param string The locator `string` (eg. `lodash@1.0.0`)
* @param strict If `false`, the reference is optional (`unknown` will be used as fallback)
*/
export declare function parseLocator(string: string, strict?: boolean): Locator;
/**
* Parses a `string` into a locator
*
* Returns `null` if the locator cannot be parsed.
*
* @param string The locator string (eg. `lodash@1.0.0`)
* @param strict If `false`, the reference is optional (`unknown` will be used as fallback)
*/
export declare function tryParseLocator(string: string, strict?: boolean): Locator | null;
declare type ParseRangeOptions = {
/** Throw an error if bindings are missing */
requireBindings?: boolean;
/** Throw an error if the protocol is missing or is not the specified one */
requireProtocol?: boolean | string;
/** Throw an error if the source is missing */
requireSource?: boolean;
/** Whether to parse the selector as a query string */
parseSelector?: boolean;
};
declare type ParseRangeReturnType<Opts extends ParseRangeOptions> = ({
params: Opts extends {
requireBindings: true;
} ? querystring.ParsedUrlQuery : querystring.ParsedUrlQuery | null;
}) & ({
protocol: Opts extends {
requireProtocol: true | string;
} ? string : string | null;
}) & ({
source: Opts extends {
requireSource: true;
} ? string : string | null;
}) & ({
selector: Opts extends {
parseSelector: true;
} ? querystring.ParsedUrlQuery : string;
});
/**
* Parses a range into its constituents. Ranges typically follow these forms,
* with both `protocol` and `bindings` being optionals:
*
* <protocol>:<selector>::<bindings>
* <protocol>:<source>#<selector>::<bindings>
*
* The selector is intended to "refine" the source, and is required. The source
* itself is optional (for instance we don't need it for npm packages, but we
* do for git dependencies).
*/
export declare function parseRange<Opts extends ParseRangeOptions>(range: string, opts?: Opts): ParseRangeReturnType<Opts>;
/**
* File-style ranges are bound to a parent locators that we need in order to
* resolve relative paths to the location of their parent packages. This
* function wraps `parseRange` to automatically extract the parent locator
* from the bindings and return it along with the selector.
*/
export declare function parseFileStyleRange(range: string, { protocol }: {
protocol: string;
}): {
parentLocator: Locator;
path: PortablePath;
};
/**
* Turn the components returned by `parseRange` back into a string. Check
* `parseRange` for more details.
*/
export declare function makeRange({ protocol, source, selector, params }: {
protocol: string | null;
source: string | null;
selector: string;
params: querystring.ParsedUrlQuery | null;
}): string;
/**
* Some bindings are internal-only and not meant to be displayed anywhere (for
* instance that's the case with the parent locator bound to the `file:` ranges).
*
* this function strips them from a range.
*/
export declare function convertToManifestRange(range: string): string;
/**
* @deprecated Prefer using `stringifyIdent`
*/
export declare function requirableIdent(ident: Ident): string;
/**
* Returns a string from an ident (eg. `@types/lodash`).
*/
export declare function stringifyIdent(ident: Ident): string;
/**
* Returns a string from a descriptor (eg. `@types/lodash@^1.0.0`).
*/
export declare function stringifyDescriptor(descriptor: Descriptor): string;
/**
* Returns a string from a descriptor (eg. `@types/lodash@1.0.0`).
*/
export declare function stringifyLocator(locator: Locator): string;
/**
* Returns a string from an ident, formatted as a slug (eg. `@types-lodash`).
*/
export declare function slugifyIdent(ident: Ident): string;
/**
* Returns a string from a locator, formatted as a slug (eg. `@types-lodash-npm-1.0.0-abcdef1234`).
*/
export declare function slugifyLocator(locator: Locator): import("@yarnpkg/fslib").Filename;
/**
* Returns a string that is suitable to be printed to stdout. Based on the
* configuration it may include color sequences.
*
* @param configuration Reference configuration
* @param ident The ident to pretty print
*/
export declare function prettyIdent(configuration: Configuration, ident: Ident): string;
/**
* Returns a string that is suitable to be printed to stdout. Based on the
* configuration it may include color sequences.
*
* @param configuration Reference configuration
* @param ident The range to pretty print
*/
export declare function prettyRange(configuration: Configuration, range: string): string;
/**
* Returns a string that is suitable to be printed to stdout. Based on the
* configuration it may include color sequences.
*
* @param configuration Reference configuration
* @param descriptor The descriptor to pretty print
*/
export declare function prettyDescriptor(configuration: Configuration, descriptor: Descriptor): string;
/**
* Returns a string that is suitable to be printed to stdout. Based on the
* configuration it may include color sequences.
*
* @param configuration Reference configuration
* @param reference The reference to pretty print
*/
export declare function prettyReference(configuration: Configuration, reference: string): string;
/**
* Returns a string that is suitable to be printed to stdout. Based on the
* configuration it may include color sequences.
*
* @param configuration Reference configuration
* @param locator The locator to pretty print
*/
export declare function prettyLocator(configuration: Configuration, locator: Locator): string;
/**
* Returns a string that is suitable to be printed to stdout. It will never
* be colored.
*
* @param locator The locator to pretty print
*/
export declare function prettyLocatorNoColors(locator: Locator): string;
/**
* Sorts a list of descriptors, first by their idents then by their ranges.
*/
export declare function sortDescriptors(descriptors: Iterable<Descriptor>): Descriptor[];
/**
* Returns a string that is suitable to be printed to stdout. Based on the
* configuration it may include color sequences.
*
* @param configuration Reference configuration
* @param workspace The workspace to pretty print
*/
export declare function prettyWorkspace(configuration: Configuration, workspace: Workspace): string;
/**
* Returns a string that is suitable to be printed to stdout. Based on the
* configuration it may include color sequences.
*
* @param configuration Reference configuration
* @param descriptor The descriptor to pretty print
* @param locator The locator is resolves to
*/
export declare function prettyResolution(configuration: Configuration, descriptor: Descriptor, locator: Locator | null): string;
/**
* Returns a string that is suitable to be printed to stdout. Based on the
* configuration it may include color sequences.
*
* @param configuration Reference configuration
* @param locator The locator to pretty print
* @param descriptor The descriptor that depends on it
*/
export declare function prettyDependent(configuration: Configuration, locator: Locator, descriptor: Descriptor | null): string;
/**
* The presence of a `node_modules` directory in the path is extremely common
* in the JavaScript ecosystem to denote whether a path belongs to a vendor
* or not. I considered using a more generic path for packages that aren't
* always JS-only (such as when using the Git fetcher), but that unfortunately
* caused various JS apps to start showing errors when working with git repos.
*
* As a result, all packages from all languages will follow this convention. At
* least it'll be consistent, and linkers will always have the ability to remap
* them to a different location if that's a critical requirement.
*/
export declare function getIdentVendorPath(ident: Ident): PortablePath;
export {}; | the_stack |
export interface AureliaClassDecorators {
customElement: string;
useView: string;
noView: string;
}
type AureliaClassDecoratorPossibilites =
| 'customElement'
| 'useView'
| 'noView'
| '';
interface DecoratorInfo {
decoratorName: AureliaClassDecoratorPossibilites;
decoratorArgument: string;
}
import * as fs from 'fs';
import * as Path from 'path';
import { kebabCase } from 'lodash';
import { SyntaxKind, ts } from 'ts-morph';
import { getElementNameFromClassDeclaration } from '../../common/className';
import {
VALUE_CONVERTER_SUFFIX,
AureliaClassTypes,
AureliaDecorator,
AureliaViewModel,
} from '../../common/constants';
import { UriUtils } from '../../common/view/uri-utils';
import { Optional } from '../regions/ViewRegions';
import { IAureliaClassMember, IAureliaComponent } from './AureliaProgram';
export function getAureliaComponentInfoFromClassDeclaration(
sourceFile: ts.SourceFile,
checker: ts.TypeChecker
): Optional<IAureliaComponent, 'viewRegions'> | undefined {
let result: Optional<IAureliaComponent, 'viewRegions'> | undefined;
let targetClassDeclaration: ts.ClassDeclaration | undefined;
sourceFile.forEachChild((node) => {
const isClassDeclaration = ts.isClassDeclaration(node);
if (!isClassDeclaration) return;
const fulfillsAureliaConventions =
classDeclarationHasUseViewOrNoView(node) ||
hasCustomElementNamingConvention(node) ||
hasValueConverterNamingConvention(node);
const validForAurelia = isNodeExported(node) && fulfillsAureliaConventions;
if (validForAurelia) {
targetClassDeclaration = node;
if (node.name == null) return;
const symbol = checker.getSymbolAtLocation(node.name);
let documentation = '';
if (symbol != null) {
// console.log('No symbol found for: ', node.name.getText());
documentation = ts.displayPartsToString(
symbol.getDocumentationComment(checker)
);
}
// Value Converter
const isValueConverterModel = checkValueConverter(targetClassDeclaration);
if (isValueConverterModel) {
const valueConverterName = targetClassDeclaration.name
?.getText()
.replace(VALUE_CONVERTER_SUFFIX, '')
.toLocaleLowerCase();
result = {
documentation,
className: targetClassDeclaration.name?.getText() ?? '',
valueConverterName,
baseViewModelFileName: Path.parse(sourceFile.fileName).name,
viewModelFilePath: UriUtils.toSysPath(sourceFile.fileName),
type: AureliaClassTypes.VALUE_CONVERTER,
sourceFile,
};
return;
}
// Standard Component
const { fileName } = targetClassDeclaration.getSourceFile();
const conventionViewFilePath = fileName.replace(/.[jt]s$/, '.html');
let viewFilePath: string = '';
if (fs.existsSync(conventionViewFilePath)) {
viewFilePath = UriUtils.toSysPath(conventionViewFilePath);
} else {
viewFilePath =
getTemplateImportPathFromCustomElementDecorator(
targetClassDeclaration,
sourceFile
) ?? '';
}
// TODO: better way to filter out non aurelia classes?
if (viewFilePath === '') return;
const resultClassMembers = getAureliaViewModelClassMembers(
targetClassDeclaration,
checker
);
const viewModelName = getElementNameFromClassDeclaration(
targetClassDeclaration
);
// Decorator
const customElementDecorator = getCustomElementDecorator(
targetClassDeclaration
);
let decoratorComponentName;
let decoratorStartOffset;
let decoratorEndOffset;
if (customElementDecorator) {
// get argument for name property in decorator
customElementDecorator.expression.forEachChild((decoratorChild) => {
// @customElement('empty-view')
if (ts.isStringLiteral(decoratorChild)) {
decoratorComponentName = decoratorChild
.getText()
.replace(/['"]/g, '');
decoratorStartOffset = decoratorChild.getStart() + 1; // start quote
decoratorEndOffset = decoratorChild.getEnd(); // include the last character, ie. the end quote
}
// @customElement({ name: 'my-view', template })
else if (ts.isObjectLiteralExpression(decoratorChild)) {
decoratorChild.forEachChild((decoratorArgument) => {
if (!ts.isPropertyAssignment(decoratorArgument)) return;
decoratorArgument.forEachChild((decoratorProp) => {
if (!ts.isStringLiteral(decoratorProp)) {
// TODO: What if name is not a string? --> Notify users [ISSUE-8Rh31VAG]
return;
}
decoratorComponentName = decoratorProp
.getText()
.replace(/['"]/g, '');
decoratorStartOffset = decoratorProp.getStart() + 1; // start quote
decoratorEndOffset = decoratorProp.getEnd(); // include the last character, ie. the end quote
});
});
}
});
}
result = {
documentation,
className: targetClassDeclaration.name?.getText() ?? '',
componentName: viewModelName,
decoratorComponentName,
decoratorStartOffset,
decoratorEndOffset,
baseViewModelFileName: Path.parse(sourceFile.fileName).name,
viewModelFilePath: UriUtils.toSysPath(sourceFile.fileName),
viewFilePath,
type: AureliaClassTypes.CUSTOM_ELEMENT,
classMembers: resultClassMembers,
sourceFile,
};
}
});
return result;
}
function checkValueConverter(targetClassDeclaration: ts.ClassDeclaration) {
const isValueConverterName = targetClassDeclaration.name
?.getText()
.includes(VALUE_CONVERTER_SUFFIX);
return Boolean(isValueConverterName);
}
function isNodeExported(node: ts.ClassDeclaration): boolean {
return (ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Export) !== 0;
}
export function getClassDecoratorInfos(
classDeclaration: ts.ClassDeclaration
): DecoratorInfo[] {
const classDecoratorInfos: DecoratorInfo[] = [];
const aureliaDecorators = ['customElement', 'useView', 'noView'];
classDeclaration.decorators?.forEach((decorator) => {
const result: DecoratorInfo = {
decoratorName: '',
decoratorArgument: '',
};
decorator.expression.forEachChild((decoratorChild) => {
const childName =
decoratorChild.getText() as AureliaClassDecoratorPossibilites;
const isAureliaDecorator = aureliaDecorators.includes(childName);
if (isAureliaDecorator) {
if (ts.isIdentifier(decoratorChild)) {
result.decoratorName = childName;
}
}
// @customElement({name:>'my-name'<})
else if (ts.isObjectLiteralExpression(decoratorChild)) {
decoratorChild.forEachChild((decoratorArgChild) => {
// {>name:'my-name'<}
if (ts.isPropertyAssignment(decoratorArgChild)) {
if (decoratorArgChild.name.getText() === 'name') {
let value = decoratorArgChild.getLastToken()?.getText();
if (value == null) return;
result.decoratorArgument = value;
}
}
});
} else if (ts.isToken(decoratorChild)) {
result.decoratorArgument = childName;
}
});
const withoutQuotes = result.decoratorArgument.replace(/['"]/g, '');
result.decoratorArgument = withoutQuotes;
classDecoratorInfos.push(result);
});
return classDecoratorInfos.filter((info) => info.decoratorName !== '');
}
function getAureliaViewModelClassMembers(
classDeclaration: ts.ClassDeclaration,
checker: ts.TypeChecker
): IAureliaClassMember[] {
const classMembers: IAureliaClassMember[] = [];
classDeclaration.forEachChild((classMember) => {
// Constructor members
if (ts.isConstructorDeclaration(classMember)) {
const constructorMember = classMember;
constructorMember.forEachChild((constructorArgument) => {
if (constructorArgument.kind !== SyntaxKind.Parameter) return;
const hasModifier = getConstructorHasModifier(constructorArgument);
if (hasModifier === false) return;
constructorArgument.forEachChild((argumentPart) => {
if (argumentPart.kind !== SyntaxKind.Identifier) return;
const name = argumentPart.getText();
const symbol = checker.getSymbolAtLocation(argumentPart);
const commentDoc = ts.displayPartsToString(
symbol?.getDocumentationComment(checker)
);
const result: IAureliaClassMember = {
name,
documentation: commentDoc,
isBindable: false,
syntaxKind: argumentPart.kind,
start: constructorArgument.getStart(),
end: constructorArgument.getEnd(),
};
classMembers.push(result);
});
});
}
// Class Members
else if (
ts.isPropertyDeclaration(classMember) ||
ts.isGetAccessorDeclaration(classMember) ||
ts.isMethodDeclaration(classMember)
) {
const classMemberName = classMember.name?.getText();
const isBindable = classMember.decorators?.find((decorator) => {
return decorator.getText().includes('@bindable');
});
// Get bindable type. If bindable type is undefined, we set it to be "unknown".
const memberType =
classMember.type?.getText() !== undefined
? classMember.type?.getText()
: 'unknown';
const memberTypeText =
'' + `${isBindable ? 'Bindable ' : ''}` + `Type: \`${memberType}\``;
// Add comment documentation if available
const symbol = checker.getSymbolAtLocation(classMember.name);
const commentDoc = ts.displayPartsToString(
symbol?.getDocumentationComment(checker)
);
let defaultValueText: string = '';
if (ts.isPropertyDeclaration(classMember)) {
// Add default values. The value can be undefined, but that is correct in most cases.
const defaultValue = classMember.initializer?.getText() ?? '';
defaultValueText = `Default value: \`${defaultValue}\``;
}
// Concatenate documentation parts with spacing
const documentation = `${commentDoc}\n\n${memberTypeText}\n\n${defaultValueText}`;
const result: IAureliaClassMember = {
name: classMemberName,
documentation,
isBindable: Boolean(isBindable),
syntaxKind: ts.isPropertyDeclaration(classMember)
? ts.SyntaxKind.VariableDeclaration
: ts.SyntaxKind.MethodDeclaration,
start: classMember.getStart(),
end: classMember.getEnd(),
};
classMembers.push(result);
}
});
return classMembers;
}
function getConstructorHasModifier(constructorArgument: ts.Node) {
let hasModifier = false;
constructorArgument.forEachChild((argumentPart) => {
if (hasModifier === true) return;
const isPrivate = argumentPart.kind === SyntaxKind.PrivateKeyword;
const isPublic = argumentPart.kind === SyntaxKind.PublicKeyword;
const isProtected = argumentPart.kind === SyntaxKind.ProtectedKeyword;
const isReadonly = argumentPart.kind === SyntaxKind.ReadonlyKeyword;
hasModifier = isPrivate || isPublic || isProtected || isReadonly;
});
return hasModifier;
}
/**
* classDeclarationHasUseViewOrNoView checks whether a classDeclaration has a useView or noView
*
* @param classDeclaration - ClassDeclaration to check
*/
function classDeclarationHasUseViewOrNoView(
classDeclaration: ts.ClassDeclaration
): boolean {
if (!classDeclaration.decorators) return false;
const hasViewDecorator = classDeclaration.decorators.some((decorator) => {
const result =
decorator.getText().includes('@useView') ||
decorator.getText().includes('@noView');
return result;
});
return hasViewDecorator;
}
/**
* [refactor]: also get other decorators
*/
export function getCustomElementDecorator(
classDeclaration: ts.ClassDeclaration
) {
const target = classDeclaration.decorators?.find((decorator) => {
const result = decorator
.getText()
.includes(AureliaDecorator.CUSTOM_ELEMENT);
return result;
});
return target;
}
/**
* MyClassCustomelement
*
* \@customElement(...)
* MyClass
*/
function hasCustomElementNamingConvention(
classDeclaration: ts.ClassDeclaration
): boolean {
const hasCustomElementDecorator =
classDeclaration.decorators?.some((decorator) => {
const decoratorName = decorator.getText();
const result =
decoratorName.includes(AureliaDecorator.CUSTOM_ELEMENT) ||
decoratorName.includes('name');
return result;
}) ?? false;
const className = classDeclaration.name?.getText();
const hasCustomElementNamingConvention = Boolean(
className?.includes(AureliaClassTypes.CUSTOM_ELEMENT)
);
const { fileName } = classDeclaration.getSourceFile();
const baseName = Path.parse(fileName).name;
const isCorrectFileAndClassConvention =
kebabCase(baseName) === kebabCase(className);
return (
hasCustomElementDecorator ||
hasCustomElementNamingConvention ||
isCorrectFileAndClassConvention
);
}
/**
* MyClassValueConverter
*
* \@valueConverter(...)
* MyClass
*/
function hasValueConverterNamingConvention(
classDeclaration: ts.ClassDeclaration
): boolean {
const hasValueConverterDecorator =
classDeclaration.decorators?.some((decorator) => {
const result = decorator
.getText()
.includes(AureliaDecorator.VALUE_CONVERTER);
return result;
}) ?? false;
const hasValueConverterNamingConvention = Boolean(
classDeclaration.name?.getText().includes(AureliaClassTypes.VALUE_CONVERTER)
);
return hasValueConverterDecorator || hasValueConverterNamingConvention;
}
function getTemplateImportPathFromCustomElementDecorator(
classDeclaration: ts.ClassDeclaration,
sourceFile: ts.SourceFile
): string | undefined {
if (!classDeclaration.decorators) return;
const customElementDecorator = classDeclaration.decorators.find(
(decorator) => {
const result = decorator
.getText()
.includes(AureliaDecorator.CUSTOM_ELEMENT);
return result;
}
);
if (!customElementDecorator) return;
const hasTemplateProp = customElementDecorator
.getText()
.includes(AureliaViewModel.TEMPLATE);
if (!hasTemplateProp) return;
let templateImportPath = '';
const templateImport = sourceFile.statements.find((statement) => {
const isImport = statement.kind === ts.SyntaxKind.ImportDeclaration;
if (!isImport) {
return false;
}
let foundTemplateImport = false;
statement.getChildren().forEach((child) => {
if (child.kind === ts.SyntaxKind.ImportClause) {
if (child.getText().includes(AureliaViewModel.TEMPLATE)) {
foundTemplateImport = true;
}
}
});
return foundTemplateImport;
});
templateImport?.getChildren().forEach((child) => {
if (child.kind === ts.SyntaxKind.StringLiteral) {
templateImportPath = child.getText().replace(/['"]/g, '');
}
});
templateImportPath = Path.resolve(
Path.dirname(UriUtils.toSysPath(sourceFile.fileName)),
templateImportPath
);
return templateImportPath;
} | the_stack |
module Apiman {
export var ApiImplController = _module.controller("Apiman.ApiImplController",
['$q', '$rootScope', '$scope', '$location', 'PageLifecycle', 'ApiEntityLoader', 'OrgSvcs', 'ApimanSvcs', '$routeParams', 'EntityStatusSvc', 'Logger', 'Configuration',
($q, $rootScope, $scope, $location, PageLifecycle, ApiEntityLoader, OrgSvcs, ApimanSvcs, $routeParams, EntityStatusSvc, Logger, Configuration) => {
var params = $routeParams;
$scope.organizationId = params.org;
$scope.tab = 'impl';
$scope.version = params.version;
$scope.typeOptions = ["rest", "soap"];
$scope.contentTypeOptions = ["json", "xml"];
$scope.updatedApi = new Object();
$scope.apiSecurity = new Object();
$scope.showMetrics = Configuration.ui.metrics;
$scope.saved = false;
$scope.saving = false;
var pageData = ApiEntityLoader.getCommonData($scope, $location);
if (params.version != null) {
pageData = angular.extend(pageData, {
gateways: $q(function(resolve, reject) {
ApimanSvcs.query({ entityType: 'gateways' }, resolve, reject);
})
});
}
$scope.isEntityDisabled = EntityStatusSvc.isEntityDisabled;
// API Security Type Options
$scope.apiSecurityTypeOptions = [
{
label: 'None',
i18nKey: 'none',
type: 'none'
},
{
label: 'MTLS/Two-Way-SSL',
i18nKey: 'mtls',
type: 'mtls'
},
{
label: 'BASIC Authentication',
i18nKey: 'basic-auth',
type: 'basic'
}
];
var epValue = function(endpointProperties, key) {
if (endpointProperties && endpointProperties[key]) {
return endpointProperties[key];
} else {
return null;
}
};
var toApiSecurity = function(version) {
var rval:any = {};
rval.type = version.endpointProperties['authorization.type'];
if (!rval.type) {
rval.type = 'none';
}
if (rval.type == 'mssl') {
rval.type = 'mtls';
}
if (rval.type == 'basic') {
rval.basic = {
username: epValue(version.endpointProperties, 'basic-auth.username'),
password: epValue(version.endpointProperties, 'basic-auth.password'),
confirmPassword: epValue(version.endpointProperties, 'basic-auth.password'),
requireSSL: 'true' === epValue(version.endpointProperties, 'basic-auth.requireSSL')
};
}
return rval;
};
var toEndpointProperties = function(apiSecurity) {
var rval:any = {};
if (apiSecurity.type == 'none') {
return rval;
}
rval['authorization.type'] = apiSecurity.type;
if (apiSecurity.type == 'basic' && apiSecurity.basic) {
rval['basic-auth.username'] = apiSecurity.basic.username;
rval['basic-auth.password'] = apiSecurity.basic.password;
if (apiSecurity.basic.requireSSL) {
rval['basic-auth.requireSSL'] = 'true';
} else {
rval['basic-auth.requireSSL'] = 'false';
}
}
return rval;
};
// Validates depending on the endpoint type selected
$scope.checkValid = function() {
var valid = true;
if (!$scope.updatedApi.endpoint) {
valid = false;
}
if (!$scope.updatedApi.endpointType) {
valid = false;
}
if ($scope.apiSecurity.type == 'basic' && $scope.apiSecurity.basic) {
if (!$scope.apiSecurity.basic.password) {
valid = false;
}
if ($scope.apiSecurity.basic.password != $scope.apiSecurity.basic.confirmPassword) {
valid = false;
}
} else if ($scope.apiSecurity.type == 'basic' && !$scope.apiSecurity.basic) {
valid = false;
}
$scope.isValid = valid;
return valid;
};
// This function checks for changes to the updateApi model
// and compares the new value to the original value. If they are all the same,
// the Save button will remain disabled.
$scope.$watch('updatedApi', function(newValue) {
if ($scope.version) {
var dirty = false;
if (newValue.endpoint != $scope.version.endpoint) {
dirty = true;
}
if (newValue.endpointType != $scope.version.endpointType) {
dirty = true;
}
if (newValue.endpointContentType != $scope.version.endpointContentType) {
dirty = true;
}
if (newValue.parsePayload != $scope.version.parsePayload) {
dirty = true;
}
if (newValue.disableKeysStrip != $scope.version.disableKeysStrip)
{
dirty = true;
}
if (newValue.gateways && newValue.gateways.length > 0) {
dirty = true;
}
if ($scope.version.endpointProperties && newValue.endpointProperties) {
if (!angular.equals($scope.version.endpointProperties, newValue.endpointProperties)) {
Logger.debug('Dirty due to EP:');
Logger.debug(' $scope.version: {0}', $scope.version);
Logger.debug(' $scope.version.EP: {0}', $scope.version.endpointProperties);
Logger.debug(' newValue.EP: {0}', newValue.endpointProperties);
dirty = true;
}
}
$scope.checkValid();
$rootScope.isDirty = dirty;
}
}, true);
$scope.$watch('apiSecurity', function(newValue) {
if (newValue) {
$scope.updatedApi.endpointProperties = toEndpointProperties(newValue);
$scope.checkValid();
}
}, true);
// Used, as you'd guess, to compare originally selected values to new values
function arraysAreEqual(one, two) {
return (one.join('') == two.join(''));
}
$scope.$watch('selectedGateways', function(newValue) {
if (newValue) {
var alreadySet = false;
var newSelectedArray = [];
// Iterate over each selected value, push into an empty array with proper formatting
for(var i = 0; i < newValue.length; i++) {
newSelectedArray.push({gatewayId: newValue[i].id});
}
// Will need to compare newly selected gateways to available gateways again
// by plucking gatewayId values, inserting into an array, and comparing them
var pluckedAfter = _.map(newSelectedArray, 'gatewayId');
var pluckedBefore = _.map($scope.version.gateways, 'gatewayId');
var compare = arraysAreEqual(pluckedAfter, pluckedBefore);
if(compare === true) {
alreadySet = true;
}
if (!alreadySet) {
$scope.updatedApi.gateways = newSelectedArray;
} else {
delete $scope.updatedApi.gateways;
}
}
});
$scope.setEndpointProperties = function(newValue) {
if (newValue) {
$scope.updatedApi.endpointProperties = toEndpointProperties(newValue);
$scope.checkValid();
}
};
$scope.reset = function() {
if (!$scope.version.endpointType) {
$scope.version.endpointType = 'rest';
}
if (!$scope.version.endpointContentType) {
$scope.version.endpointContentType = 'json';
}
$scope.apiSecurity = toApiSecurity($scope.version);
$scope.updatedApi.endpoint = $scope.version.endpoint;
$scope.updatedApi.endpointType = $scope.version.endpointType;
$scope.updatedApi.endpointContentType = $scope.version.endpointContentType;
$scope.updatedApi.endpointProperties = angular.copy($scope.version.endpointProperties);
$scope.updatedApi.parsePayload = $scope.version.parsePayload;
$scope.updatedApi.disableKeysStrip = $scope.version.disableKeysStrip;
// Gateway Handling
delete $scope.updatedApi.gateways;
$scope.selectedGateways = [];
// Match up currently associated gateways for this API with available gateways
// to provide additional information, other than just the ID, about each gateway
if ($scope.version.gateways && $scope.version.gateways.length > 0) {
for(var i = 0; i < $scope.gateways.length; i++) {
for(var j = 0; j < $scope.version.gateways.length; j++) {
// Check if IDs match
if($scope.gateways[i].id === $scope.version.gateways[j].gatewayId) {
// Add gateway to selected gateway array
$scope.selectedGateways.push($scope.gateways[i]);
}
}
}
}
$rootScope.isDirty = false;
// Automatically set the selected gateway if there's only one and the
// gateway is not already set.
if ((!$scope.version.gateways || $scope.version.gateways.length == 0)
&& ($scope.gateways && $scope.gateways.length === 1)) {
$scope.autoGateway = true;
$scope.selectedGateways[0] = $scope.gateways[0];
}
};
$scope.saveApi = function() {
$scope.invalidEndpoint = false;
$scope.saving = true;
OrgSvcs.update({ organizationId: params.org, entityType: 'apis', entityId:params.api, versionsOrActivity: 'versions', version: params.version }, $scope.updatedApi, function(reply) {
$rootScope.isDirty = false;
$scope.autoGateway = false;
$scope.saved = true;
$scope.saving = false;
$scope.version = reply;
EntityStatusSvc.setEntityStatus(reply.status);
}, PageLifecycle.handleError);
};
// Endpoint Validation
$scope.invalidEndpoint = false;
$scope.validateEndpoint = function() {
var first7 = $scope.updatedApi.endpoint.substring(0, 7);
var first8 = $scope.updatedApi.endpoint.substring(0, 8);
var re = new RegExp('^(http|https):\/\/', 'i');
// Test first 7 letters for http:// first
if(re.test(first7) === true) {
$scope.saveApi();
} else {
// If it fails, test first 8 letters for https:// next
if(re.test(first8) === true) {
$scope.saveApi();
} else {
console.log('Invalid input.');
$scope.invalidEndpoint = true;
}
}
};
PageLifecycle.loadPage('ApiImpl', 'apiView', pageData, $scope, function() {
$scope.reset();
PageLifecycle.setPageTitle('api-impl', [ $scope.api.name ]);
// $scope.gateways - list of available gateways
// $scope.version.gateways - list of gateways for this specific version
// $scope.selectedGateway - list of currently selected gateways (with `name`, `ID`, etc.)
// $scope.updatedApi.gateways - what we submit to the API, with only the `gatewayId`
});
}]);
} | the_stack |
declare module '@rn-components-kit/icon' {
import * as React from 'react';
import {ViewStyle} from 'react-native';
interface Props {
/**
* Allow you to customize style
*/
style?: ViewStyle;
/**
* Determines the icon's color
* default: '#333'
*/
color?: string;
/**
* Determines the icon's size
* default: 15
*/
size?: number;
/**
* Icon type, integrated in Ant-Design Preset(https://ant.design/components/icon/)
*/
type: (
'check-circle' |
'ci' |
'dollar' |
'compass' |
'close-circle' |
'frown' |
'info-circle' |
'left-circle' |
'down-circle' |
'euro' |
'copyright' |
'minus-circle' |
'meh' |
'plus-circle' |
'play-circle' |
'question-circle' |
'pound' |
'right-circle' |
'smile' |
'trademark' |
'time-circle' |
'time-out' |
'earth' |
'yuan' |
'up-circle' |
'warning-circle' |
'sync' |
'transaction' |
'undo' |
'redo' |
'reload' |
'reload-time' |
'message' |
'dashboard' |
'issues-close' |
'poweroff' |
'logout' |
'pie-chart' |
'setting' |
'eye' |
'location' |
'edit-square' |
'export' |
'save' |
'import' |
'app-store' |
'close-square' |
'down-square' |
'layout' |
'left-square' |
'play-square' |
'control' |
'code-library' |
'detail' |
'minus-square' |
'plus-square' |
'right-square' |
'project' |
'wallet' |
'up-square' |
'calculator' |
'interation' |
'check-square' |
'border' |
'border-outer' |
'border-top' |
'border-bottom' |
'border-left' |
'border-right' |
'border-inner' |
'border-verticle' |
'border-horizontal' |
'radius-bottomleft' |
'radius-bottomright' |
'radius-upleft' |
'radius-upright' |
'radius-setting' |
'add-user' |
'delete-team' |
'delete-user' |
'addteam' |
'user' |
'team' |
'area-chart' |
'line-chart' |
'bar-chart' |
'point-map' |
'container' |
'database' |
'sever' |
'mobile' |
'tablet' |
'red-envelope' |
'book' |
'file-done' |
'reconciliation' |
'file--exception' |
'file-sync' |
'file-search' |
'solution' |
'file-protect' |
'file-add' |
'file-excel' |
'file-exclamation' |
'file-pdf' |
'file-image' |
'file-markdown' |
'file-unknown' |
'file-ppt' |
'file-word' |
'file' |
'file-zip' |
'file-text' |
'file-copy' |
'snippets' |
'audit' |
'diff' |
'batch-folding' |
'security-scan' |
'property-safety' |
'safety-certificate' |
'insurance' |
'alert' |
'delete' |
'hourglass' |
'bulb' |
'experiment' |
'bell' |
'trophy' |
'rest' |
'usb' |
'skin' |
'home' |
'bank' |
'filter' |
'funnel-plot' |
'like' |
'unlike' |
'unlock' |
'lock' |
'customer-service' |
'flag' |
'money-collect' |
'medicinebox' |
'shop' |
'rocket' |
'shopping' |
'folder' |
'folder-open' |
'folder-add' |
'deployment-unit' |
'account-book' |
'contacts' |
'carry-out' |
'calendar-check' |
'calendar' |
'scan' |
'select' |
'box-plot' |
'build' |
'sliders' |
'laptop' |
'barcode' |
'camera' |
'cluster' |
'gateway' |
'car' |
'printer' |
'read' |
'cloud-server' |
'cloud-upload' |
'cloud' |
'cloud-download' |
'cloud-sync' |
'video' |
'notification' |
'sound' |
'radar-chart' |
'qrcode' |
'fund' |
'image' |
'mail' |
'table' |
'id-card' |
'credit-card' |
'heart' |
'block' |
'error' |
'star' |
'gold' |
'heat-map' |
'wifi' |
'attachment' |
'edit' |
'key' |
'api' |
'disconnect' |
'highlight' |
'monitor' |
'link' |
'man' |
'percentage' |
'pushpin' |
'phone' |
'shake' |
'tag' |
'wrench' |
'tags' |
'scissor' |
'mr' |
'share' |
'branches' |
'fork' |
'shrink' |
'arrawsalt' |
'vertical-right' |
'vertical-left' |
'right' |
'left' |
'up' |
'down' |
'fullscreen' |
'fullscreen-exit' |
'doubleleft' |
'double-right' |
'arrowright' |
'arrowup' |
'arrowleft' |
'arrowdown' |
'upload' |
'colum-height' |
'vertical-align-botto' |
'vertical-align-middl' |
'totop' |
'vertical-align-top' |
'download' |
'sort-descending' |
'sort-ascending' |
'fall' |
'swap' |
'stock' |
'rise' |
'indent' |
'outdent' |
'menu' |
'unordered-list' |
'ordered-list' |
'align-right' |
'align-center' |
'align-left' |
'pic-center' |
'pic-right' |
'pic-left' |
'bold' |
'font-colors' |
'exclaimination' |
'font-size' |
'infomation' |
'line-height' |
'strikethrough' |
'underline' |
'number' |
'italic' |
'code' |
'column-width' |
'check' |
'ellipsis' |
'dash' |
'close' |
'enter' |
'line' |
'minus' |
'question' |
'rollback' |
'small-dash' |
'pause' |
'bg-colors' |
'crown' |
'drag' |
'desktop' |
'gift' |
'stop' |
'fire' |
'thunderbolt' |
'check-circle-fill' |
'left-circle-fill' |
'down-circle-fill' |
'minus-circle-fill' |
'close-circle-fill' |
'info-circle-fill' |
'up-circle-fill' |
'right-circle-fill' |
'plus-circle-fill' |
'question-circle-fill' |
'euro-circle-fill' |
'frown-fill' |
'copyright-circle-fil' |
'ci-circle-fill' |
'compass-fill' |
'dollar-circle-fill' |
'poweroff-circle-fill' |
'meh-fill' |
'play-circle-fill' |
'pound-circle-fill' |
'smile-fill' |
'stop-fill' |
'warning-circle-fill' |
'time-circle-fill' |
'trademark-circle-fil' |
'yuan-circle-fill' |
'heart-fill' |
'pie-chart-circle-fil' |
'dashboard-fill' |
'message-fill' |
'check-square-fill' |
'down-square-fill' |
'minus-square-fill' |
'close-square-fill' |
'code-library-fill' |
'left-square-fill' |
'play-square-fill' |
'up-square-fill' |
'right-square-fill' |
'plus-square-fill' |
'account-book-fill' |
'carry-out-fill' |
'calendar-fill' |
'calculator-fill' |
'interation-fill' |
'project-fill' |
'detail-fill' |
'save-fill' |
'wallet-fill' |
'control-fill' |
'layout-fill' |
'app-store-fill' |
'mobile-fill' |
'tablet-fill' |
'book-fill' |
'red-envelope-fill' |
'safety-certificate-fill' |
'property-safety-fill' |
'insurance-fill' |
'security-scan-fill' |
'file-exclamation-fil' |
'file-add-fill' |
'file-fill' |
'file-excel-fill' |
'file-markdown-fill' |
'file-text-fill' |
'file-ppt-fill' |
'file-unknown-fill' |
'file-word-fill' |
'file-zip-fill' |
'file-pdf-fill' |
'file-image-fill' |
'diff-fill' |
'file-copy-fill' |
'snippets-fill' |
'batch-folding-fill' |
'reconciliation-fill' |
'folder-add-fill' |
'folder-fill' |
'folder-open-fill' |
'database-fill' |
'container-fill' |
'sever-fill' |
'calendar-check-fill' |
'image-fill' |
'id-card-fill' |
'credit-card-fill' |
'fund-fill' |
'read-fill' |
'contacts-fill' |
'delete-fill' |
'notification-fill' |
'flag-fill' |
'money-collect-fill' |
'medicine-box-fill' |
'rest-fill' |
'shopping-fill' |
'skin-fill' |
'video-fill' |
'sound-fill' |
'bulb-fill' |
'bell-fill' |
'filter-fill' |
'fire-fill' |
'funnel-plot-fill' |
'gift-fill' |
'hourglass-fill' |
'home-fill' |
'trophy-fill' |
'location-fill' |
'cloud-fill' |
'customer-service-fill' |
'experiment-fill' |
'eye-fill' |
'like-fill' |
'lock-fill' |
'unlike-fill' |
'star-fill' |
'unlock-fill' |
'alert-fill' |
'api-fill' |
'highlight-fill' |
'phone-fill' |
'edit-fill' |
'pushpin-fill' |
'rocket-fill' |
'thunderbolt-fill' |
'tag-fill' |
'wrench-fill' |
'tags-fill' |
'bank-fill' |
'camera-fill' |
'error-fill' |
'crown-fill' |
'mail-fill' |
'car-fill' |
'printer-fill' |
'shop-fill' |
'setting-fill' |
'usb-fill' |
'golden-fill' |
'build-fill' |
'box-plot-fill' |
'sliders-fill' |
'alibaba' |
'alibabacloud' |
'ant-design' |
'ant-cloud' |
'behance' |
'google-plus' |
'medium' |
'google' |
'ie' |
'amazon' |
'slack' |
'alipay' |
'taobao' |
'zhihu' |
'html5' |
'linkedin' |
'yahoo' |
'facebook' |
'skype' |
'codesandbox' |
'chrome' |
'codepen' |
'aliwangwang' |
'apple' |
'android' |
'sketch' |
'gitlab' |
'dribbble' |
'instagram' |
'reddit' |
'windows' |
'yuque' |
'youtube' |
'gitlab-fill' |
'dropbox' |
'dingtalk' |
'android-fill' |
'apple-fill' |
'html5-fill' |
'windows-fill' |
'qq' |
'twitter' |
'skype-fill' |
'weibo' |
'yuque-fill' |
'youtube-fill' |
'yahoo-fill' |
'wechat-fill' |
'chrome-fill' |
'alipay-circle-fill' |
'aliwangwang-fill' |
'behance-circle-fill' |
'amazon-circle-fill' |
'codepen-circle-fill' |
'codesandbox-circle-fill' |
'dropbox-circle-fill' |
'github-fill' |
'dribbble-circle-fill' |
'google-plus-circle-fill' |
'medium-circle-fill' |
'qq-circle-fill' |
'ie-circle-fill' |
'google-circle-fill' |
'dingtalk-circle-fill' |
'sketch-circle-fill' |
'slack-circle-fill' |
'twitter-circle-fill' |
'taobao-circle-fill' |
'weibo-circle-fill' |
'zhihu-circle-fill' |
'reddit-circle-fill' |
'alipay-square-fill' |
'dingtalk-square-fill' |
'codesandbox-square-fill' |
'behance-square-fill' |
'amazon-square-fill' |
'codepen-square-fill' |
'dribbble-square-fill' |
'dropbox-square-fill' |
'facebook-fill' |
'google-plus-square-fill' |
'google-square-fill' |
'instagram-fill' |
'ie-square-fill' |
'medium-square-fill' |
'linkedin-fill' |
'qq-square-fill' |
'reddit-square-fill' |
'twitter-square-fill' |
'sketch-square-fill' |
'slack-square-fill' |
'taobao-square-fill' |
'weibo-square-fill' |
'zhihu-square-fill' |
'zoom-out' |
'apartment' |
'audio' |
'audio-fill' |
'robot' |
'zoom-in' |
'robot-fill' |
'bug-fill' |
'bug' |
'audio-static' |
'comment' |
'signal-fill' |
'verified' |
'shortcut-fill' |
'videocamera-add' |
'switch-user' |
'whatsapp' |
'appstore-add' |
'caret-down' |
'backward' |
'caret-up' |
'caret-right' |
'caret-left' |
'fast-backward' |
'forward' |
'fast-forward' |
'search' |
'retweet' |
'login' |
'step-backward' |
'step-forward' |
'swap-right' |
'swap-left' |
'woman' |
'plus' |
'eye-close-fill' |
'eye-close' |
'clear' |
'collapse' |
'expand' |
'delete-column' |
'merge-cells' |
'subnode' |
'rotate-left' |
'rotate-right' |
'insert-row-below' |
'insert-row-above' |
'solit-cells' |
'format-painter' |
'insert-row-right' |
'format-painter-fill' |
'insert-row-left' |
'translate' |
'delete-row' |
'sister-node'
);
}
export const Icon: React.SFC<Props>;
} | the_stack |
import * as React from 'react';
import { PureComponent } from 'react';
import {
ArrowKeyStepper,
AutoSizer,
Grid,
Index,
CollectionCellRendererParams,
IndexRange,
CellMeasurerProps,
Size,
TableHeaderProps,
} from 'react-virtualized';
// Default tree-shaken CJS exports built by babel and output to react-virtualized/dist<commonjs>/<ComponentName>
import AutoSizerCJS from 'react-virtualized/dist/commonjs/AutoSizer';
import ArrowKeyStepperCJS from 'react-virtualized/dist/commonjs/ArrowKeyStepper';
import GridCJS from 'react-virtualized/dist/commonjs/Grid';
// Default tree-shaken ES exports built by babel and output to react-virtualized/dist<es>/<ComponentName>
import AutoSizerESM from 'react-virtualized/dist/es/AutoSizer';
import ArrowKeyStepperESM from 'react-virtualized/dist/es/ArrowKeyStepper';
import GridESM from 'react-virtualized/dist/es/Grid';
export class ArrowKeyStepperExample extends PureComponent<any, any> {
render() {
const { mode } = this.state;
return (
<ArrowKeyStepper columnCount={100} mode={mode as 'edges'} rowCount={100}>
{({ onSectionRendered, scrollToColumn, scrollToRow }) => (
<div>
<AutoSizer disableHeight>
{({ width }) => (
<Grid
className={'styles.Grid'}
columnWidth={this._getColumnWidth}
columnCount={100}
height={200}
onSectionRendered={onSectionRendered}
cellRenderer={({ columnIndex, key, rowIndex, style }) =>
this._cellRenderer({
columnIndex,
key,
rowIndex,
scrollToColumn,
scrollToRow,
style,
})
}
rowHeight={this._getRowHeight}
rowCount={100}
scrollToColumn={scrollToColumn}
scrollToRow={scrollToRow}
width={width}
/>
)}
</AutoSizer>
</div>
)}
</ArrowKeyStepper>
);
}
_getColumnWidth({ index }: Index) {
return (1 + (index % 3)) * 60;
}
_getRowHeight({ index }: Index) {
return (1 + (index % 3)) * 30;
}
_cellRenderer({ columnIndex, key, rowIndex, scrollToColumn, scrollToRow, style }: any) {
return (
<div className={'className'} key={key} style={style}>
{`r:${rowIndex}, c:${columnIndex}`}
</div>
);
}
}
export class ArrowKeyStepperCJSExample extends PureComponent<any, any> {
render() {
const { mode } = this.state;
return (
<ArrowKeyStepperCJS columnCount={100} mode={mode as 'edges'} rowCount={100}>
{({ onSectionRendered, scrollToColumn, scrollToRow }) => (
<div>
<AutoSizerCJS disableHeight>
{({ width }) => (
<GridCJS
className={'styles.Grid'}
columnWidth={this._getColumnWidth}
columnCount={100}
height={200}
onSectionRendered={onSectionRendered}
cellRenderer={({ columnIndex, key, rowIndex, style }) =>
this._cellRenderer({
columnIndex,
key,
rowIndex,
scrollToColumn,
scrollToRow,
style,
})
}
rowHeight={this._getRowHeight}
rowCount={100}
scrollToColumn={scrollToColumn}
scrollToRow={scrollToRow}
width={width}
/>
)}
</AutoSizerCJS>
</div>
)}
</ArrowKeyStepperCJS>
);
}
_getColumnWidth({ index }: Index) {
return (1 + (index % 3)) * 60;
}
_getRowHeight({ index }: Index) {
return (1 + (index % 3)) * 30;
}
_cellRenderer({ columnIndex, key, rowIndex, scrollToColumn, scrollToRow, style }: any) {
return (
<div className={'className'} key={key} style={style}>
{`r:${rowIndex}, c:${columnIndex}`}
</div>
);
}
}
export class ArrowKeyStepperESMExample extends PureComponent<any, any> {
render() {
const { mode } = this.state;
return (
<ArrowKeyStepperESM columnCount={100} mode={mode as 'edges'} rowCount={100}>
{({ onSectionRendered, scrollToColumn, scrollToRow }) => (
<div>
<AutoSizerESM disableHeight>
{({ width }) => (
<GridESM
className={'styles.Grid'}
columnWidth={this._getColumnWidth}
columnCount={100}
height={200}
onSectionRendered={onSectionRendered}
cellRenderer={({ columnIndex, key, rowIndex, style }) =>
this._cellRenderer({
columnIndex,
key,
rowIndex,
scrollToColumn,
scrollToRow,
style,
})
}
rowHeight={this._getRowHeight}
rowCount={100}
scrollToColumn={scrollToColumn}
scrollToRow={scrollToRow}
width={width}
/>
)}
</AutoSizerESM>
</div>
)}
</ArrowKeyStepperESM>
);
}
_getColumnWidth({ index }: Index) {
return (1 + (index % 3)) * 60;
}
_getRowHeight({ index }: Index) {
return (1 + (index % 3)) * 30;
}
_cellRenderer({ columnIndex, key, rowIndex, scrollToColumn, scrollToRow, style }: any) {
return (
<div className={'className'} key={key} style={style}>
{`r:${rowIndex}, c:${columnIndex}`}
</div>
);
}
}
import { List } from 'react-virtualized';
export class AutoSizerExample extends PureComponent<any, any> {
render() {
const { list } = this.context;
const { hideDescription } = this.state;
return (
<AutoSizer>
{({ width, height }) => (
<List
className={'styles.List'}
height={height}
rowCount={list.size}
rowHeight={30}
rowRenderer={this._rowRenderer}
width={width}
/>
)}
</AutoSizer>
);
}
_rowRenderer({ index, key, style }: any) {
const { list } = this.context;
const row = list.get(index);
return (
<div key={key} className={'styles.row'} style={style}>
{row.name}
</div>
);
}
}
import ListCJS from 'react-virtualized/dist/commonjs/List';
export class AutoSizerCJSExample extends PureComponent<any, any> {
render() {
const { list } = this.context;
const { hideDescription } = this.state;
return (
<AutoSizerCJS>
{({ width, height }) => (
<ListCJS
className={'styles.List'}
height={height}
rowCount={list.size}
rowHeight={30}
rowRenderer={this._rowRenderer}
width={width}
/>
)}
</AutoSizerCJS>
);
}
_rowRenderer({ index, key, style }: any) {
const { list } = this.context;
const row = list.get(index);
return (
<div key={key} className={'styles.row'} style={style}>
{row.name}
</div>
);
}
}
import ListESM from 'react-virtualized/dist/commonjs/List';
export class AutoSizerESMExample extends PureComponent<any, any> {
render() {
const { list } = this.context;
const { hideDescription } = this.state;
return (
<AutoSizerESM>
{({ width, height }) => (
<ListESM
className={'styles.List'}
height={height}
rowCount={list.size}
rowHeight={30}
rowRenderer={this._rowRenderer}
width={width}
/>
)}
</AutoSizerESM>
);
}
_rowRenderer({ index, key, style }: any) {
const { list } = this.context;
const row = list.get(index);
return (
<div key={key} className={'styles.row'} style={style}>
{row.name}
</div>
);
}
}
import {} from 'react';
import { CellMeasurer, CellMeasurerCache, ListRowProps } from 'react-virtualized';
export class DynamicHeightList extends PureComponent<any> {
_cache: CellMeasurerCache;
constructor(props: any, context: any) {
super(props, context);
this._cache = new CellMeasurerCache({
fixedWidth: true,
minHeight: 50,
});
}
render() {
const { width } = this.props;
return (
<List
className={'styles.BodyGrid'}
deferredMeasurementCache={this._cache}
height={400}
overscanRowCount={0}
rowCount={1000}
rowHeight={this._cache.rowHeight}
rowRenderer={this._rowRenderer}
width={width}
/>
);
}
_rowRenderer({ index, isScrolling, key, parent, style }: ListRowProps) {
const { getClassName, list } = this.props;
const datum = list.get(index % list.size);
const classNames = getClassName({ columnIndex: 0, rowIndex: index });
const imageWidth = 300;
const imageHeight = datum.size * 2;
const source = `http://fillmurray.com/${imageWidth}/${imageHeight}`;
return (
<CellMeasurer cache={this._cache} columnIndex={0} key={key} rowIndex={index} parent={parent}>
{({ measure }) => (
<div className={classNames} style={style}>
<img
onLoad={measure}
src={source}
style={{
width: imageWidth,
}}
/>
</div>
)}
</CellMeasurer>
);
}
}
import { Collection } from 'react-virtualized';
// Defines a pattern of sizes and positions for a range of 10 rotating cells
// These cells cover an area of 600 (wide) x 400 (tall)
const GUTTER_SIZE = 3;
const CELL_WIDTH = 75;
export class CollectionExample extends PureComponent<any, any> {
context: any;
state: any;
_columnYMap: any;
constructor(props: any, context: any) {
super(props, context);
this.context = context;
this.state = {
cellCount: context.list.size,
columnCount: this._getColumnCount(context.list.size),
height: 300,
horizontalOverscanSize: 0,
scrollToCell: undefined,
showScrollingPlaceholder: false,
verticalOverscanSize: 0,
};
this._columnYMap = [];
}
render() {
const {
cellCount,
height,
horizontalOverscanSize,
scrollToCell,
showScrollingPlaceholder,
verticalOverscanSize,
} = this.state;
return (
<AutoSizer disableHeight>
{({ width }) => (
<Collection
cellCount={cellCount}
cellRenderer={this._cellRenderer}
cellSizeAndPositionGetter={this._cellSizeAndPositionGetter}
className={'styles.collection'}
height={height}
horizontalOverscanSize={horizontalOverscanSize}
noContentRenderer={this._noContentRenderer}
scrollToCell={scrollToCell}
verticalOverscanSize={verticalOverscanSize}
width={width}
/>
)}
</AutoSizer>
);
}
_cellRenderer({ index, isScrolling, key, style }: CollectionCellRendererParams) {
const { list } = this.context;
const { showScrollingPlaceholder } = this.state;
const datum = list.get(index % list.size);
return (
<div className={'styles.cell'} key={key} style={style}>
{showScrollingPlaceholder && isScrolling ? '...' : index}
</div>
);
}
_cellSizeAndPositionGetter({ index }: Index) {
const { list } = this.context;
const { columnCount } = this.state;
const columnPosition = index % (columnCount || 1);
const datum = list.get(index % list.size);
// Poor man's Masonry layout; columns won't all line up equally with the bottom.
const height = datum.size;
const width = CELL_WIDTH;
const x = columnPosition * (GUTTER_SIZE + width);
const y = this._columnYMap[columnPosition] || 0;
this._columnYMap[columnPosition] = y + height + GUTTER_SIZE;
return {
height,
width,
x,
y,
};
}
_getColumnCount(cellCount: number) {
return Math.round(Math.sqrt(cellCount));
}
_noContentRenderer() {
return <div className={'styles.noCells'}>No cells</div>;
}
}
import { ColumnSizer } from 'react-virtualized';
export class ColumnSizerExample extends PureComponent<any, any> {
render() {
const { columnMaxWidth, columnMinWidth, columnCount } = this.state;
return (
<div>
<AutoSizer disableHeight>
{({ width }) => (
<ColumnSizer
columnMaxWidth={columnMaxWidth}
columnMinWidth={columnMinWidth}
columnCount={columnCount}
key="GridColumnSizer"
width={width}
>
{({ adjustedWidth, getColumnWidth, registerChild }) => (
<div
className={'styles.GridContainer'}
style={{
height: 50,
width: adjustedWidth,
}}
>
<Grid
ref={registerChild}
columnWidth={getColumnWidth}
columnCount={columnCount}
height={50}
noContentRenderer={this._noContentRenderer}
cellRenderer={this._cellRenderer}
rowHeight={50}
rowCount={1}
width={adjustedWidth}
/>
</div>
)}
</ColumnSizer>
)}
</AutoSizer>
</div>
);
}
_noContentRenderer() {
return <div className={'styles.noCells'}>No cells</div>;
}
_cellRenderer({ columnIndex, key, rowIndex, style }: GridCellProps) {
const className = columnIndex === 0 ? 'styles.firstCell' : 'styles.cell';
return (
<div className={className} key={key} style={style}>
{`R:${rowIndex}, C:${columnIndex}`}
</div>
);
}
}
export class GridExample extends PureComponent<any, any> {
state = {
columnCount: 1000,
height: 300,
overscanColumnCount: 0,
overscanRowCount: 10,
rowHeight: 40,
rowCount: 1000,
scrollToColumn: undefined,
scrollToRow: undefined,
useDynamicRowHeight: false,
};
render() {
const {
columnCount,
height,
overscanColumnCount,
overscanRowCount,
rowHeight,
rowCount,
scrollToColumn,
scrollToRow,
useDynamicRowHeight,
} = this.state;
return (
<AutoSizer disableHeight>
{({ width }) => (
<Grid
cellRenderer={this._cellRenderer}
className={'styles.BodyGrid'}
columnWidth={this._getColumnWidth}
columnCount={columnCount}
height={height}
noContentRenderer={this._noContentRenderer}
overscanColumnCount={overscanColumnCount}
overscanRowCount={overscanRowCount}
rowHeight={useDynamicRowHeight ? this._getRowHeight : rowHeight}
rowCount={rowCount}
scrollToColumn={scrollToColumn}
scrollToRow={scrollToRow}
width={width}
/>
)}
</AutoSizer>
);
}
_cellRenderer(params: GridCellProps) {
if (params.columnIndex === 0) {
return this._renderLeftSideCell(params);
} else {
return this._renderBodyCell(params);
}
}
_getColumnWidth({ index }: Index) {
switch (index) {
case 0:
return 50;
case 1:
return 100;
case 2:
return 300;
default:
return 80;
}
}
_getDatum(index: number) {
const { list } = this.context;
return list.get(index % list.size);
}
_getRowClassName(row: number) {
return row % 2 === 0 ? 'styles.evenRow' : 'styles.oddRow';
}
_getRowHeight({ index }: Index) {
return this._getDatum(index).size;
}
_noContentRenderer() {
return <div className={'styles.noCells'}>No cells</div>;
}
_renderBodyCell({ columnIndex, key, rowIndex, style }: GridCellProps) {
const rowClass = this._getRowClassName(rowIndex);
const datum = this._getDatum(rowIndex);
let content;
switch (columnIndex) {
case 1:
content = datum.name;
break;
case 2:
content = datum.random;
break;
default:
content = `r:${rowIndex}, c:${columnIndex}`;
break;
}
return (
<div className={'classNames'} key={key} style={style}>
{content}
</div>
);
}
_renderLeftSideCell({ key, rowIndex, style }: GridCellProps) {
const datum = this._getDatum(rowIndex);
// Don't modify styles.
// These are frozen by React now (as of 16.0.0).
// Since Grid caches and re-uses them, they aren't safe to modify.
style = {
...style,
backgroundColor: datum.color,
};
return (
<div className={'classNames'} key={key} style={style}>
{datum.name.charAt(0)}
</div>
);
}
}
export class GridCJSExample extends PureComponent<any, any> {
state = {
columnCount: 1000,
height: 300,
overscanColumnCount: 0,
overscanRowCount: 10,
rowHeight: 40,
rowCount: 1000,
scrollToColumn: undefined,
scrollToRow: undefined,
useDynamicRowHeight: false,
};
render() {
const {
columnCount,
height,
overscanColumnCount,
overscanRowCount,
rowHeight,
rowCount,
scrollToColumn,
scrollToRow,
useDynamicRowHeight,
} = this.state;
return (
<AutoSizer disableHeight>
{({ width }) => (
<GridCJS
cellRenderer={this._cellRenderer}
className={'styles.BodyGrid'}
columnWidth={this._getColumnWidth}
columnCount={columnCount}
height={height}
noContentRenderer={this._noContentRenderer}
overscanColumnCount={overscanColumnCount}
overscanRowCount={overscanRowCount}
rowHeight={useDynamicRowHeight ? this._getRowHeight : rowHeight}
rowCount={rowCount}
scrollToColumn={scrollToColumn}
scrollToRow={scrollToRow}
width={width}
/>
)}
</AutoSizer>
);
}
_cellRenderer(params: GridCellProps) {
if (params.columnIndex === 0) {
return this._renderLeftSideCell(params);
} else {
return this._renderBodyCell(params);
}
}
_getColumnWidth({ index }: Index) {
switch (index) {
case 0:
return 50;
case 1:
return 100;
case 2:
return 300;
default:
return 80;
}
}
_getDatum(index: number) {
const { list } = this.context;
return list.get(index % list.size);
}
_getRowClassName(row: number) {
return row % 2 === 0 ? 'styles.evenRow' : 'styles.oddRow';
}
_getRowHeight({ index }: Index) {
return this._getDatum(index).size;
}
_noContentRenderer() {
return <div className={'styles.noCells'}>No cells</div>;
}
_renderBodyCell({ columnIndex, key, rowIndex, style }: GridCellProps) {
const rowClass = this._getRowClassName(rowIndex);
const datum = this._getDatum(rowIndex);
let content;
switch (columnIndex) {
case 1:
content = datum.name;
break;
case 2:
content = datum.random;
break;
default:
content = `r:${rowIndex}, c:${columnIndex}`;
break;
}
return (
<div className={'classNames'} key={key} style={style}>
{content}
</div>
);
}
_renderLeftSideCell({ key, rowIndex, style }: GridCellProps) {
const datum = this._getDatum(rowIndex);
// Don't modify styles.
// These are frozen by React now (as of 16.0.0).
// Since Grid caches and re-uses them, they aren't safe to modify.
style = {
...style,
backgroundColor: datum.color,
};
return (
<div className={'classNames'} key={key} style={style}>
{datum.name.charAt(0)}
</div>
);
}
}
import { InfiniteLoader } from 'react-virtualized';
const STATUS_LOADING = 1;
const STATUS_LOADED = 2;
export class InfiniteLoaderExample extends PureComponent<any, any> {
_timeoutIds = new Set<number>();
componentWillUnmount() {
this._timeoutIds.forEach(clearTimeout);
}
render() {
const { list } = this.context;
const { loadedRowCount, loadingRowCount } = this.state;
return (
<InfiniteLoader isRowLoaded={this._isRowLoaded} loadMoreRows={this._loadMoreRows} rowCount={list.size}>
{({ onRowsRendered, registerChild }) => (
<AutoSizer disableHeight>
{({ width }) => (
<List
ref={registerChild}
className={'styles.List'}
height={200}
onRowsRendered={onRowsRendered}
rowCount={list.size}
rowHeight={30}
rowRenderer={this._rowRenderer}
width={width}
/>
)}
</AutoSizer>
)}
</InfiniteLoader>
);
}
_isRowLoaded({ index }: Index) {
const { loadedRowsMap } = this.state;
return !!loadedRowsMap[index]; // STATUS_LOADING or STATUS_LOADED
}
_loadMoreRows({ startIndex, stopIndex }: IndexRange) {
const { loadedRowsMap, loadingRowCount } = this.state;
const increment = stopIndex - startIndex + 1;
for (let i = startIndex; i <= stopIndex; i++) {
loadedRowsMap[i] = STATUS_LOADING;
}
this.setState({
loadingRowCount: loadingRowCount + increment,
});
const timeoutId = setTimeout(() => {
const { loadedRowCount, loadingRowCount } = this.state;
this._timeoutIds.delete(timeoutId);
for (let i = startIndex; i <= stopIndex; i++) {
loadedRowsMap[i] = STATUS_LOADED;
}
this.setState({
loadingRowCount: loadingRowCount - increment,
loadedRowCount: loadedRowCount + increment,
});
promiseResolver();
}, 1000 + Math.round(Math.random() * 2000));
this._timeoutIds.add(timeoutId);
let promiseResolver: () => void;
return new Promise<void>(resolve => {
promiseResolver = resolve;
});
}
_rowRenderer({ index, key, style }: ListRowProps) {
const { list } = this.context;
const { loadedRowsMap } = this.state;
const row = list.get(index);
const content = loadedRowsMap[index] === STATUS_LOADED
? row.name
: <div className={'styles.placeholder'} style={{ width: row.size }} />;
return (
<div className={'styles.row'} key={key} style={style}>
{content}
</div>
);
}
}
export class ListExample extends PureComponent<any, any> {
constructor(props: any, context: any) {
super(props, context);
this.state = {
listHeight: 300,
listRowHeight: 50,
overscanRowCount: 10,
rowCount: context.list.size,
scrollToIndex: undefined,
showScrollingPlaceholder: false,
useDynamicRowHeight: false,
};
}
render() {
const {
listHeight,
listRowHeight,
overscanRowCount,
rowCount,
scrollToIndex,
showScrollingPlaceholder,
useDynamicRowHeight,
} = this.state;
return (
<AutoSizer disableHeight>
{({ width }) => (
<List
ref="List"
className={'styles.List'}
height={listHeight}
overscanRowCount={overscanRowCount}
noRowsRenderer={this._noRowsRenderer}
rowCount={rowCount}
rowHeight={useDynamicRowHeight ? this._getRowHeight : listRowHeight}
rowRenderer={this._rowRenderer}
scrollToIndex={scrollToIndex}
width={width}
/>
)}
</AutoSizer>
);
}
_getDatum(index: number) {
const { list } = this.context;
return list.get(index % list.size);
}
_getRowHeight({ index }: Index) {
return this._getDatum(index).size;
}
_noRowsRenderer() {
return <div className={'styles.noRows'}>No rows</div>;
}
_rowRenderer({ index, isScrolling, key, style }: ListRowProps) {
const { showScrollingPlaceholder, useDynamicRowHeight } = this.state;
if (showScrollingPlaceholder && isScrolling) {
return (
<div className={'cn(styles.row, styles.isScrollingPlaceholder)'} key={key} style={style}>
Scrolling...
</div>
);
}
const datum = this._getDatum(index);
let additionalContent;
if (useDynamicRowHeight) {
switch (datum.size) {
case 75:
additionalContent = <div>It is medium-sized.</div>;
break;
case 100:
additionalContent = (
<div>
It is large-sized.
<br />
It has a 3rd row.
</div>
);
break;
}
}
return (
<div className={'styles.row'} key={key} style={style}>
<div
className={'styles.letter'}
style={{
backgroundColor: datum.color,
}}
>
{datum.name.charAt(0)}
</div>
<div>
<div className={'styles.name'}>{datum.name}</div>
<div className={'styles.index'}>This is row {index}</div>
{additionalContent}
</div>
{useDynamicRowHeight && <span className={'styles.height'}>{datum.size}px</span>}
</div>
);
}
}
import {
WindowScroller,
createMasonryCellPositioner as createCellPositioner,
Positioner,
Masonry,
MasonryCellProps,
} from 'react-virtualized';
export class GridExample2 extends PureComponent<any, any> {
_columnCount: number;
_cache: CellMeasurerCache;
_columnHeights: any;
_width = 0;
_height = 0;
_scrollTop?: number | undefined;
_cellPositioner: Positioner;
_masonry: Masonry;
constructor(props: any, context: any) {
super(props, context);
this._columnCount = 0;
this._cache = new CellMeasurerCache({
defaultHeight: 250,
defaultWidth: 200,
fixedWidth: true,
});
this._columnHeights = {};
this.state = {
columnWidth: 200,
height: 300,
gutterSize: 10,
windowScrollerEnabled: false,
};
this._cellRenderer = this._cellRenderer.bind(this);
this._onResize = this._onResize.bind(this);
this._renderAutoSizer = this._renderAutoSizer.bind(this);
this._renderMasonry = this._renderMasonry.bind(this);
this._setMasonryRef = this._setMasonryRef.bind(this);
}
render() {
const { columnWidth, height, gutterSize, windowScrollerEnabled } = this.state;
const child = windowScrollerEnabled ? (
<WindowScroller>{this._renderAutoSizer}</WindowScroller>
) : (
this._renderAutoSizer({ height })
);
return <div>{child}</div>;
}
_calculateColumnCount() {
const { columnWidth, gutterSize } = this.state;
this._columnCount = Math.floor(this._width / (columnWidth + gutterSize));
}
_cellRenderer({ index, key, parent, style }: MasonryCellProps) {
const { list } = this.context;
const { columnWidth } = this.state;
const datum = list.get(index % list.size);
return (
<CellMeasurer cache={this._cache} index={index} key={key} parent={parent}>
<div
className={'styles.Cell'}
style={{
...style,
width: columnWidth,
}}
>
<div
style={{
backgroundColor: datum.color,
borderRadius: '0.5rem',
height: datum.size * 3,
marginBottom: '0.5rem',
width: '100%',
}}
/>
{datum.random}
</div>
</CellMeasurer>
);
}
_initCellPositioner() {
if (typeof this._cellPositioner === 'undefined') {
const { columnWidth, gutterSize } = this.state;
this._cellPositioner = createCellPositioner({
cellMeasurerCache: this._cache,
columnCount: this._columnCount,
columnWidth,
spacer: gutterSize,
});
}
}
_onResize({ height, width }: Size) {
this._width = width;
this._columnHeights = {};
this._calculateColumnCount();
this._resetCellPositioner();
this._masonry.recomputeCellPositions();
}
_renderAutoSizer({ height, scrollTop }: { height: number; scrollTop?: number | undefined }) {
this._height = height;
this._scrollTop = scrollTop;
return (
<AutoSizer disableHeight onResize={this._onResize}>
{this._renderMasonry}
</AutoSizer>
);
}
_renderMasonry({ width }: Size) {
this._width = width;
this._calculateColumnCount();
this._initCellPositioner();
const { height, windowScrollerEnabled } = this.state;
return (
<Masonry
autoHeight={windowScrollerEnabled}
cellCount={1000}
cellMeasurerCache={this._cache}
cellPositioner={this._cellPositioner}
cellRenderer={this._cellRenderer}
height={windowScrollerEnabled ? this._height : height}
ref={this._setMasonryRef}
scrollTop={this._scrollTop}
width={width}
/>
);
}
_resetCellPositioner() {
const { columnWidth, gutterSize } = this.state;
this._cellPositioner.reset({
columnCount: this._columnCount,
columnWidth,
spacer: gutterSize,
});
}
_setMasonryRef(ref: any) {
this._masonry = ref;
}
}
import { MultiGrid } from 'react-virtualized';
const STYLE: React.CSSProperties = {
border: '1px solid #ddd',
overflow: 'hidden',
};
const STYLE_BOTTOM_LEFT_GRID: React.CSSProperties = {
borderRight: '2px solid #aaa',
backgroundColor: '#f7f7f7',
};
const STYLE_TOP_LEFT_GRID: React.CSSProperties = {
borderBottom: '2px solid #aaa',
borderRight: '2px solid #aaa',
fontWeight: 'bold',
};
const STYLE_TOP_RIGHT_GRID: React.CSSProperties = {
borderBottom: '2px solid #aaa',
fontWeight: 'bold',
};
export class MultiGridExample extends PureComponent<{}, any> {
state = {
fixedColumnCount: 2,
fixedRowCount: 1,
scrollToColumn: 0,
scrollToRow: 0,
};
render() {
return (
<AutoSizer disableHeight>
{({ width }) => (
<MultiGrid
{...this.state}
cellRenderer={this._cellRenderer}
columnWidth={75}
columnCount={50}
height={300}
rowHeight={40}
rowCount={100}
style={STYLE}
styleBottomLeftGrid={STYLE_BOTTOM_LEFT_GRID}
styleTopLeftGrid={STYLE_TOP_LEFT_GRID}
styleTopRightGrid={STYLE_TOP_RIGHT_GRID}
width={width}
/>
)}
</AutoSizer>
);
}
_cellRenderer({ columnIndex, key, rowIndex, style }: GridCellProps) {
return (
<div className={'styles.Cell'} key={key} style={style}>
{columnIndex}, {rowIndex}
</div>
);
}
}
import { ScrollSync } from 'react-virtualized';
const LEFT_COLOR_FROM = hexToRgb('#471061');
const LEFT_COLOR_TO = hexToRgb('#BC3959');
const TOP_COLOR_FROM = hexToRgb('#000000');
const TOP_COLOR_TO = hexToRgb('#333333');
function scrollbarSize() {
return 42;
}
export class GridExample3 extends PureComponent<{}, any> {
state = {
columnWidth: 75,
columnCount: 50,
height: 300,
overscanColumnCount: 0,
overscanRowCount: 5,
rowHeight: 40,
rowCount: 100,
};
render() {
const {
columnCount,
columnWidth,
height,
overscanColumnCount,
overscanRowCount,
rowHeight,
rowCount,
} = this.state;
return (
<ScrollSync>
{({ clientHeight, clientWidth, onScroll, scrollHeight, scrollLeft, scrollTop, scrollWidth }) => {
const x = scrollLeft / (scrollWidth - clientWidth);
const y = scrollTop / (scrollHeight - clientHeight);
const leftBackgroundColor = mixColors(LEFT_COLOR_FROM, LEFT_COLOR_TO, y);
const leftColor = '#ffffff';
const topBackgroundColor = mixColors(TOP_COLOR_FROM, TOP_COLOR_TO, x);
const topColor = '#ffffff';
const middleBackgroundColor = mixColors(leftBackgroundColor, topBackgroundColor, 0.5);
const middleColor = '#ffffff';
return (
<div className={'styles.GridRow'}>
<div
className={'styles.LeftSideGridContainer'}
style={{
position: 'absolute',
left: 0,
top: 0,
color: leftColor,
backgroundColor: `rgb(${topBackgroundColor.r},${topBackgroundColor.g},${topBackgroundColor.b})`,
}}
>
<Grid
cellRenderer={this._renderLeftHeaderCell}
className={'styles.HeaderGrid'}
width={columnWidth}
height={rowHeight}
rowHeight={rowHeight}
columnWidth={columnWidth}
rowCount={1}
columnCount={1}
/>
</div>
<div
className={'styles.LeftSideGridContainer'}
style={{
position: 'absolute',
left: 0,
top: rowHeight,
color: leftColor,
backgroundColor: `rgb(${leftBackgroundColor.r},${leftBackgroundColor.g},${leftBackgroundColor.b})`,
}}
>
<Grid
overscanColumnCount={overscanColumnCount}
overscanRowCount={overscanRowCount}
cellRenderer={this._renderLeftSideCell}
columnWidth={columnWidth}
columnCount={1}
className={'styles.LeftSideGrid'}
height={height - scrollbarSize()}
rowHeight={rowHeight}
rowCount={rowCount}
scrollTop={scrollTop}
width={columnWidth}
/>
</div>
<div className={'styles.GridColumn'}>
<AutoSizer disableHeight>
{({ width }) => (
<div>
<div
style={{
backgroundColor: `rgb(${topBackgroundColor.r},${topBackgroundColor.g},${topBackgroundColor.b})`,
color: topColor,
height: rowHeight,
width: width - scrollbarSize(),
}}
>
<Grid
className={'styles.HeaderGrid'}
columnWidth={columnWidth}
columnCount={columnCount}
height={rowHeight}
overscanColumnCount={overscanColumnCount}
cellRenderer={this._renderHeaderCell}
rowHeight={rowHeight}
rowCount={1}
scrollLeft={scrollLeft}
width={width - scrollbarSize()}
/>
</div>
<div
style={{
backgroundColor: `rgb(${middleBackgroundColor.r},${middleBackgroundColor.g},${middleBackgroundColor.b})`,
color: middleColor,
height,
width,
}}
>
<Grid
className={'styles.BodyGrid'}
columnWidth={columnWidth}
columnCount={columnCount}
height={height}
onScroll={onScroll}
overscanColumnCount={overscanColumnCount}
overscanRowCount={overscanRowCount}
cellRenderer={this._renderBodyCell}
rowHeight={rowHeight}
rowCount={rowCount}
width={width}
/>
</div>
</div>
)}
</AutoSizer>
</div>
</div>
);
}}
</ScrollSync>
);
}
_renderBodyCell(params: GridCellProps) {
if (params.columnIndex < 1) {
return;
}
return this._renderLeftSideCell(params);
}
_renderHeaderCell(params: GridCellProps) {
if (params.columnIndex < 1) {
return;
}
return this._renderLeftHeaderCell(params);
}
_renderLeftHeaderCell({ columnIndex, key, rowIndex, style }: GridCellProps) {
return (
<div className={'styles.headerCell'} key={key} style={style}>
{`C${columnIndex}`}
</div>
);
}
_renderLeftSideCell({ columnIndex, key, rowIndex, style }: GridCellProps) {
return (
<div className={'classNames'} key={key} style={style}>
{`R${rowIndex}, C${columnIndex}`}
</div>
);
}
}
function hexToRgb(hex: string) {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result
? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16),
}
: null;
}
/**
* Ported from sass implementation in C
* https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209
*/
function mixColors(color1: any, color2: any, amount: any) {
const weight1 = amount;
const weight2 = 1 - amount;
const r = Math.round(weight1 * color1.r + weight2 * color2.r);
const g = Math.round(weight1 * color1.g + weight2 * color2.g);
const b = Math.round(weight1 * color1.b + weight2 * color2.b);
return { r, g, b };
}
import { Column, Table, SortDirection, SortIndicator } from 'react-virtualized';
export class TableExample extends PureComponent<{}, any> {
state = {
disableHeader: false,
headerHeight: 30,
height: 270,
hideIndexRow: false,
overscanRowCount: 10,
rowHeight: 40,
rowCount: 1000,
scrollToIndex: undefined,
sortBy: 'index',
sortDirection: SortDirection.ASC,
useDynamicRowHeight: false,
};
render() {
const {
disableHeader,
headerHeight,
height,
hideIndexRow,
overscanRowCount,
rowHeight,
rowCount,
scrollToIndex,
sortBy,
sortDirection,
useDynamicRowHeight,
} = this.state;
const { list } = this.context;
const sortedList = list;
const rowGetter = ({ index }: Index) => this._getDatum(sortedList, index);
return (
<div>
<AutoSizer disableHeight>
{({ width }) => (
<Table
ref="Table"
disableHeader={disableHeader}
headerClassName={'styles.headerColumn'}
headerHeight={headerHeight}
height={height}
noRowsRenderer={this._noRowsRenderer}
overscanRowCount={overscanRowCount}
rowClassName={this._rowClassName}
rowHeight={useDynamicRowHeight ? this._getRowHeight : rowHeight}
rowGetter={rowGetter}
rowCount={rowCount}
scrollToIndex={scrollToIndex}
sort={this._sort}
sortBy={sortBy}
sortDirection={sortDirection}
width={width}
>
{!hideIndexRow && (
<Column
label="Index"
cellDataGetter={({ columnData, dataKey, rowData }) => rowData.index}
dataKey="index"
disableSort={!this._isSortEnabled()}
defaultSortDirection={SortDirection.DESC}
width={60}
/>
)}
<Column
dataKey="name"
disableSort={!this._isSortEnabled()}
defaultSortDirection={SortDirection.ASC}
headerRenderer={this._headerRenderer}
width={90}
/>
<Column
width={210}
disableSort
label="The description label is really long so that it will be truncated"
dataKey="random"
className={'styles.exampleColumn'}
cellRenderer={({ cellData, columnData, dataKey, rowData, rowIndex }) => cellData}
flexGrow={1}
/>
</Table>
)}
</AutoSizer>
</div>
);
}
_getDatum(list: any, index: number) {
return list.get(index % list.size);
}
_getRowHeight({ index }: Index) {
const { list } = this.context;
return this._getDatum(list, index).size;
}
_headerRenderer({ columnData, dataKey, disableSort, label, sortBy, sortDirection }: TableHeaderProps) {
return (
<div>
Full Name
{sortBy === dataKey && <SortIndicator sortDirection={sortDirection} />}
</div>
);
}
_isSortEnabled() {
const { list } = this.context;
const { rowCount } = this.state;
return rowCount <= list.size;
}
_noRowsRenderer() {
return <div className={'styles.noRows'}>No rows</div>;
}
_rowClassName({ index }: Index) {
if (index < 0) {
return 'styles.headerRow';
} else {
return index % 2 === 0 ? 'styles.evenRow' : 'styles.oddRow';
}
}
_sort({ sortBy, sortDirection }: { sortBy: string; sortDirection: SortDirectionType }) {
this.setState({ sortBy, sortDirection });
}
}
import { TableCellProps } from 'react-virtualized';
export class DynamicHeightTableColumnExample extends PureComponent<any, any> {
_cache = new CellMeasurerCache({
fixedWidth: true,
minHeight: 25,
});
render() {
const { width } = this.props;
return (
<Table
deferredMeasurementCache={this._cache}
headerHeight={20}
height={400}
overscanRowCount={2}
rowClassName={'styles.tableRow'}
rowHeight={this._cache.rowHeight}
rowGetter={this._rowGetter}
rowCount={1000}
width={width}
>
<Column className={'styles.tableColumn'} dataKey="name" label="Name" width={125} />
<Column className={'styles.tableColumn'} dataKey="color" label="Color" width={75} />
<Column
width={width - 200}
dataKey="random"
label="Dynamic text"
cellRenderer={this._columnCellRenderer}
/>
</Table>
);
}
_columnCellRenderer(args: TableCellProps) {
const { list } = this.props;
const datum = list.get(args.rowIndex % list.size);
const content = args.rowIndex % 5 === 0 ? '' : datum.randomLong;
return (
<CellMeasurer
cache={this._cache}
columnIndex={0}
key={args.dataKey}
parent={args.parent}
rowIndex={args.rowIndex}
>
<div
className={'styles.tableColumn'}
style={{
whiteSpace: 'normal',
}}
>
{content}
</div>
</CellMeasurer>
);
}
_rowGetter({ index }: Index) {
const { list } = this.props;
return list.get(index % list.size);
}
}
export class WindowScrollerExample extends PureComponent<{}, any> {
_windowScroller: WindowScroller;
state = {
showHeaderText: true,
};
render() {
const { list, isScrollingCustomElement, customElement } = this.context;
const { showHeaderText } = this.state;
return (
<div className={'styles.WindowScrollerWrapper'}>
<WindowScroller ref={this._setRef} scrollElement={isScrollingCustomElement ? customElement : null}>
{({ height, isScrolling, scrollTop, onChildScroll }) => (
<AutoSizer disableHeight>
{({ width }) => (
<List
onScroll={onChildScroll}
autoHeight
className={'styles.List'}
height={height}
isScrolling={isScrolling}
overscanRowCount={2}
rowCount={list.size}
rowHeight={30}
rowRenderer={params =>
this._rowRenderer({
...params,
isScrolling,
})
}
scrollTop={scrollTop}
width={width}
/>
)}
</AutoSizer>
)}
</WindowScroller>
</div>
);
}
_rowRenderer({ index, isScrolling, isVisible, key, style }: ListRowProps) {
const { list } = this.context;
const row = list.get(index);
return (
<div key={key} className={'className'} style={style}>
{row.name}
</div>
);
}
_setRef(windowScroller: any) {
this._windowScroller = windowScroller;
}
}
import { GridCellProps, GridCellRangeProps, SortParams, SortDirectionType } from 'react-virtualized';
export class GridCellRangeRendererExample extends PureComponent<{}, any> {
state = {
columnWidth: 75,
columnCount: 50,
height: 300,
rowHeight: 40,
rowCount: 100,
};
render() {
const { columnCount, columnWidth, height, rowHeight, rowCount } = this.state;
return (
<Grid
cellRangeRenderer={this._cellRangeRenderer}
cellRenderer={(props: GridCellProps): React.ReactNode => (
<div key={props.key} style={props.style}>
I'm a table cell
</div>
)}
columnCount={columnCount}
columnWidth={columnWidth}
height={height}
rowCount={rowCount}
rowHeight={rowHeight}
width={columnWidth}
/>
);
}
_cellRangeRenderer({
cellCache, // Temporary cell cache used while scrolling
cellRenderer, // Cell renderer prop supplied to Grid
columnSizeAndPositionManager, // @see CellSizeAndPositionManager,
columnStartIndex, // Index of first column (inclusive) to render
columnStopIndex, // Index of last column (inclusive) to render
horizontalOffsetAdjustment, // Horizontal pixel offset (required for scaling)
isScrolling, // The Grid is currently being scrolled
rowSizeAndPositionManager, // @see CellSizeAndPositionManager,
rowStartIndex, // Index of first column (inclusive) to render
rowStopIndex, // Index of last column (inclusive) to render
scrollLeft, // Current horizontal scroll offset of Grid
scrollTop, // Current vertical scroll offset of Grid
styleCache, // Temporary style (size & position) cache used while scrolling
verticalOffsetAdjustment, // Vertical pixel offset (required for scaling)
parent,
visibleColumnIndices,
visibleRowIndices,
}: GridCellRangeProps): React.ReactNode[] {
const renderedCells: React.ReactNode[] = [];
const style: React.CSSProperties = {};
for (let rowIndex = rowStartIndex; rowIndex <= rowStopIndex; rowIndex++) {
// This contains :offset (top) and :size (height) information for the cell
const rowDatum = rowSizeAndPositionManager.getSizeAndPositionOfCell(rowIndex);
for (let columnIndex = columnStartIndex; columnIndex <= columnStopIndex; columnIndex++) {
// This contains :offset (left) and :size (width) information for the cell
const columnDatum = columnSizeAndPositionManager.getSizeAndPositionOfCell(columnIndex);
// Be sure to adjust cell position in case the total set of cells is too large to be supported by the browser natively.
// In this case, Grid will shift cells as a user scrolls to increase cell density.
const left = columnDatum.offset + horizontalOffsetAdjustment;
const top = rowDatum.offset + verticalOffsetAdjustment;
// The rest of the information you need to render the cell are contained in the data.
// Be sure to provide unique :key attributes.
const key = `${rowIndex}-${columnIndex}`;
const height = rowDatum.size;
const width = columnDatum.size;
const isVisible =
columnIndex >= visibleColumnIndices.start &&
columnIndex <= visibleColumnIndices.stop &&
rowIndex >= visibleRowIndices.start &&
rowIndex <= visibleRowIndices.stop;
// Now render your cell and additional UI as you see fit.
// Add all rendered children to the :renderedCells Array.
const gridCellProps: GridCellProps = {
columnIndex,
isScrolling,
isVisible,
key,
parent,
rowIndex,
style,
};
renderedCells.push(cellRenderer(gridCellProps));
}
}
return renderedCells;
}
} | the_stack |
import { NexusGenArgTypes } from "../generated/nexus";
import { buildWhere } from "./buildWhere";
import { IntrospectionResult, Resource } from "./constants/interfaces";
import { getTestIntrospection } from "./testUtils/getTestIntrospection";
import { OurOptions } from "./types";
describe("buildWhere", () => {
let testIntrospection: IntrospectionResult;
let testUserResource: Resource;
let testBlogPostResource: Resource;
let testFilterResource: Resource;
const options: OurOptions = {};
beforeAll(async () => {
testIntrospection = await getTestIntrospection();
testUserResource = testIntrospection.resources.find(
(r) => r.type.kind === "OBJECT" && r.type.name === "User",
);
testBlogPostResource = testIntrospection.resources.find(
(r) => r.type.kind === "OBJECT" && r.type.name === "BlogPost",
);
testFilterResource = testIntrospection.resources.find(
(r) => r.type.kind === "OBJECT" && r.type.name === "FilteringTest",
);
});
describe("can handle true case insensitive string search", () => {
it("will use case insensitive search if available", async () => {
const filter = {
firstName: "fooBar",
};
const result = buildWhere(
filter,
testUserResource,
testIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
firstName: {
contains: "fooBar",
mode: "insensitive",
},
});
});
it("returns where with multiple cases on older Prisma versions", async () => {
// current test schema + introspection is running on sufficient Prisma version (../generated/schema.graphql contains QueryMode enum)
// for testing the original pseudo case insensitive version (which should be used on clients with < 2.8.0 Prisma) we need to imitate the older version
// manually deleting the enum from introspection should be enough (supportsCaseInsensitive() returns false then)
const oldPrismaTestIntrospection = Object.assign(
{},
testIntrospection,
options,
);
oldPrismaTestIntrospection.types =
oldPrismaTestIntrospection.types.filter(
(type) => type.kind !== "ENUM" || type.name !== "QueryMode",
);
const filter = {
firstName: "aBc",
};
const result = buildWhere(
filter,
testUserResource,
oldPrismaTestIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
OR: [
{
firstName: {
contains: "aBc",
},
},
{
firstName: {
contains: "abc",
},
},
{
firstName: {
contains: "ABc",
},
},
],
});
});
});
describe("properly handles suffixed fields", () => {
describe("separating suffix from field name", () => {
it("valid suffix gets separated", async () => {
const filter = {
intField_gt: "12",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
intField: {
gt: 12,
},
});
});
it("invalid suffix gets ignored", async () => {
const filter = {
intField_bt: "12", // "bigger than"
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
intField_bt: {
equals: 12,
},
});
});
it("allows underscores in field name with valid suffix", async () => {
const filter = {
snake_field_gt: "12",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
snake_field: {
gt: 12,
},
});
});
it("allows underscores in field name with invalid suffix", async () => {
const filter = {
snake_field_bt: "12", // "bigger than"
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
snake_field_bt: {
equals: 12,
},
});
});
});
describe("reverts to handling original field when", () => {
it("no comparator is provided", async () => {
const filter = {
intField: "12",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
intField: {
equals: 12,
},
});
});
it("no comparator is recognized", async () => {
const filter = {
intField_bt: "12",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
intField_bt: {
equals: 12,
},
});
});
it("separated field doesn't exist", async () => {
const filter = {
myIntField_gt: "12",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({});
});
it("separated field exists but its type doesn't support comparison", async () => {
const filter = {
boolField_gt: "12",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({});
});
it("value is an object", async () => {
const filter = {
intField_gt: {
value: "12",
},
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({});
});
it("value is an array", async () => {
const filter = {
intField_gt: ["12", "13"],
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({});
});
});
it("in case of conflict favors comparison", async () => {
const filter = {
intField_lt: "12",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
// intField is Int
// intField_lt is String
// => picks lt comparison on Int
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
intField: {
lt: 12,
},
});
});
it("works with Boolean fields and explicit equal comparison", async () => {
const filter = {
boolField_equals: "true",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
boolField: {
equals: true,
},
});
});
describe("works with String fields", () => {
it("equals", async () => {
const filter = {
stringField_equals: "aBc",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
stringField: {
equals: "aBc",
mode: "insensitive",
},
});
});
it("greater than", async () => {
const filter = {
stringField_gt: "aBc",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
stringField: {
gt: "aBc",
mode: "insensitive",
},
});
});
it("greater than or equal", async () => {
const filter = {
stringField_gte: "aBc",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
stringField: {
gte: "aBc",
mode: "insensitive",
},
});
});
it("lesser than", async () => {
const filter = {
stringField_lt: "aBc",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
stringField: {
lt: "aBc",
mode: "insensitive",
},
});
});
it("lesser than or equal", async () => {
const filter = {
stringField_lte: "aBc",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
stringField: {
lte: "aBc",
mode: "insensitive",
},
});
});
it("contains", async () => {
const filter = {
stringField_contains: "aBc",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
stringField: {
contains: "aBc",
mode: "insensitive",
},
});
});
it("starts with", async () => {
const filter = {
stringField_startsWith: "aBc",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
stringField: {
startsWith: "aBc",
mode: "insensitive",
},
});
});
it("ends with", async () => {
const filter = {
stringField_endsWith: "aBc",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
stringField: {
endsWith: "aBc",
mode: "insensitive",
},
});
});
});
describe("works with Int fields", () => {
it("equals", async () => {
const filter = {
intField_equals: "12",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
intField: {
equals: 12,
},
});
});
it("greater than", async () => {
const filter = {
intField_gt: "12",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
intField: {
gt: 12,
},
});
});
it("greater than or equal", async () => {
const filter = {
intField_gte: "12",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
intField: {
gte: 12,
},
});
});
it("lesser than", async () => {
const filter = {
intField_lt: "12",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
intField: {
lt: 12,
},
});
});
it("lesser than or equal", async () => {
const filter = {
intField_lte: "12",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
intField: {
lte: 12,
},
});
});
});
describe("works with Float fields", () => {
it("equals", async () => {
const filter = {
floatField_equals: "12.34",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
floatField: {
equals: 12.34,
},
});
});
it("greater than", async () => {
const filter = {
floatField_gt: "12.34",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
floatField: {
gt: 12.34,
},
});
});
it("greater than or equal", async () => {
const filter = {
floatField_gte: "12.34",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
floatField: {
gte: 12.34,
},
});
});
it("lesser than", async () => {
const filter = {
floatField_lt: "12.34",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
floatField: {
lt: 12.34,
},
});
});
it("lesser than or equal", async () => {
const filter = {
floatField_lte: "12.34",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
floatField: {
lte: 12.34,
},
});
});
});
describe("works with DateTime fields", () => {
it("equals", async () => {
const filter = {
dateTimeField_equals: "2020-12-30",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
dateTimeField: {
equals: new Date("2020-12-30"),
},
});
});
it("greater than", async () => {
const filter = {
dateTimeField_gt: "2020-12-30",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
dateTimeField: {
gt: new Date("2020-12-30"),
},
});
});
it("greater than or equal", async () => {
const filter = {
dateTimeField_gte: "2020-12-30",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
dateTimeField: {
gte: new Date("2020-12-30"),
},
});
});
it("lesser than", async () => {
const filter = {
dateTimeField_lt: "2020-12-30",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
dateTimeField: {
lt: new Date("2020-12-30"),
},
});
});
it("lesser than or equal", async () => {
const filter = {
dateTimeField_lte: "2020-12-30",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
dateTimeField: {
lte: new Date("2020-12-30"),
},
});
});
});
});
it("can handle simple float values", async () => {
const filter = {
floatField: "12.34",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
floatField: {
equals: 12.34,
},
});
});
it("can handle simple datetime values", async () => {
const filter = {
dateTimeField: "2020-12-30",
};
const result = buildWhere(
filter,
testFilterResource,
testIntrospection,
options,
);
expect(result).toEqual<
NexusGenArgTypes["Query"]["filteringTests"]["where"]
>({
dateTimeField: {
equals: new Date("2020-12-30"),
},
});
});
// below are previous tests which shouldn't be changed and should pass
it("can handle simple int values", async () => {
const filter = {
yearOfBirth: 1879,
};
const result = buildWhere(
filter,
testUserResource,
testIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
yearOfBirth: {
equals: 1879,
},
});
});
it("can handle simple boolean values", async () => {
const filter = {
wantsNewsletter: true,
};
const result = buildWhere(
filter,
testUserResource,
testIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
wantsNewsletter: {
equals: true,
},
});
});
it("arrays are interpreted as or", async () => {
const filter = {
yearOfBirth: [1879, 1920],
};
const result = buildWhere(
filter,
testUserResource,
testIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
OR: [
{
yearOfBirth: {
equals: 1879,
},
},
{
yearOfBirth: {
equals: 1920,
},
},
],
});
});
it("passes the raw query if its compatible", async () => {
//
const filter = {
AND: [
{
yearOfBirth: {
equals: 1879,
},
},
{
OR: [
{
firstName: {
contains: "bert",
},
},
{
lastName: {
contains: "stein",
},
},
],
},
],
};
const result = buildWhere(
filter,
testUserResource,
testIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
AND: [
{
yearOfBirth: {
equals: 1879,
},
},
{
OR: [
{
firstName: {
contains: "bert",
},
},
{
lastName: {
contains: "stein",
},
},
],
},
],
});
});
it("handles mix of raw and simple filters", async () => {
//
const filter = {
yearOfBirth: 1879,
roles: {
some: {
id: {
equals: "admin",
},
},
},
OR: [
{
firstName: "fooBar",
},
{
lastName: {
startsWith: "Ein",
},
},
{
firstName: {
equals: "Albert",
},
},
],
};
const result = buildWhere(
filter,
testUserResource,
testIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
AND: [
{
yearOfBirth: {
equals: 1879,
},
},
{
roles: {
some: {
id: {
equals: "admin",
},
},
},
},
{
OR: [
{
firstName: {
contains: "fooBar",
mode: "insensitive",
},
},
{
lastName: {
startsWith: "Ein",
},
},
{
firstName: {
equals: "Albert",
},
},
],
},
],
});
});
it("handles mixes of arrays as well", async () => {
const filter = {
yearOfBirth: [1879, 1920],
firstName: ["albert", "niels"],
};
const result = buildWhere(
filter,
testUserResource,
testIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
AND: [
{
OR: [
{
yearOfBirth: {
equals: 1879,
},
},
{
yearOfBirth: {
equals: 1920,
},
},
],
},
{
OR: [
{
firstName: {
contains: "albert",
mode: "insensitive",
},
},
{
firstName: {
contains: "niels",
mode: "insensitive",
},
},
],
},
],
});
});
it("allows to filter for enums", async () => {
const filter = {
gender: "MALE",
};
const result = buildWhere(
filter,
testUserResource,
testIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
gender: {
equals: "MALE",
},
});
});
it("allows to filter for multiple enums", async () => {
const filter = {
gender: ["MALE", "FEMALE"],
};
const result = buildWhere(
filter,
testUserResource,
testIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
OR: [
{
gender: {
equals: "MALE",
},
},
{
gender: {
equals: "FEMALE",
},
},
],
});
});
it("allows to filter for one related id in a 1-1 relation", async () => {
const filter = {
userSocialMedia: "foo",
};
const result = buildWhere(
filter,
testUserResource,
testIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
userSocialMedia: {
id: {
equals: "foo",
},
},
});
});
it("allows to filter for related ids in a 1-1 reation", async () => {
const filter = {
userSocialMedia: ["foo", "bar"],
};
const result = buildWhere(
filter,
testUserResource,
testIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
userSocialMedia: {
id: {
in: ["foo", "bar"],
},
},
});
});
it("allows to filter for one related id in a 1-many relation", async () => {
const filter = {
author: "einstein-id",
};
const result = buildWhere(
filter,
testBlogPostResource,
testIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["blogPosts"]["where"]>({
author: {
id: {
equals: "einstein-id",
},
},
});
});
it("allows to filter for related ids in a 1-many reation", async () => {
const filter = {
author: ["einstein-id", "oppenheimer-id"],
};
const result = buildWhere(
filter,
testBlogPostResource,
testIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["blogPosts"]["where"]>({
author: {
id: {
in: ["einstein-id", "oppenheimer-id"],
},
},
});
});
it("allows to filter for one related id in a n-to-m reation", async () => {
const filter = {
roles: "admin",
};
const result = buildWhere(
filter,
testUserResource,
testIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
roles: {
some: {
id: {
equals: "admin",
},
},
},
});
});
it("allows to filter for related ids in a n-to-m reation", async () => {
const filter = {
roles: ["admin", "member"],
};
const result = buildWhere(
filter,
testUserResource,
testIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
roles: {
some: {
id: {
in: ["admin", "member"],
},
},
},
});
});
it("allows to filter for null relation values", async () => {
const filter = {
roles: {
some: {
NOT: null,
},
},
};
const result = buildWhere(
filter,
testUserResource,
testIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
roles: {
some: {
NOT: null,
},
},
});
});
it("allows to filter by deeply nested relations", async () => {
const filter = {
roles: {
some: {
users: {
every: {
address: {
equals: "asd",
},
},
},
},
},
};
const result = buildWhere(
filter,
testUserResource,
testIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
roles: {
some: {
users: {
every: {
address: {
equals: "asd",
},
},
},
},
},
});
});
it("allows to use prisma graphql filters", async () => {
const filter = {
yearOfBirth: {
lte: 2020,
gte: 1900,
},
};
const result = buildWhere(
filter,
testUserResource,
testIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
yearOfBirth: {
lte: 2020,
gte: 1900,
},
});
});
it("allows to filter nested data as well", async () => {
//
const filter = {
OR: [
{
firstName: "fooBar",
},
{
userSocialMedia: {
instagram: "fooBar",
},
},
],
};
const result = buildWhere(
filter,
testUserResource,
testIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
OR: [
{
firstName: {
contains: "fooBar",
mode: "insensitive",
},
},
{
userSocialMedia: {
instagram: {
contains: "fooBar",
mode: "insensitive",
},
},
},
],
});
});
it("allows to NOT find certain fields", async () => {
const filter = {
NOT: [
{
yearOfBirth: 1879,
},
],
};
const result = buildWhere(
filter,
testUserResource,
testIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
NOT: [
{
yearOfBirth: {
equals: 1879,
},
},
],
});
});
describe("q", () => {
it("is a special query that searches all text fields", () => {
const filter = {
q: "stein",
};
const result = buildWhere(
filter,
testUserResource,
testIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
AND: [
{
OR: [
{
email: {
contains: "stein",
mode: "insensitive",
},
},
{
firstName: {
contains: "stein",
mode: "insensitive",
},
},
{
lastName: {
contains: "stein",
mode: "insensitive",
},
},
],
},
],
});
});
it("does an AND connection on multiple terms", () => {
const filter = {
q: "albert stein",
};
const result = buildWhere(
filter,
testUserResource,
testIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
AND: [
{
OR: [
{
email: {
contains: "albert",
mode: "insensitive",
},
},
{
firstName: {
contains: "albert",
mode: "insensitive",
},
},
{
lastName: {
contains: "albert",
mode: "insensitive",
},
},
],
},
{
OR: [
{
email: {
contains: "stein",
mode: "insensitive",
},
},
{
firstName: {
contains: "stein",
mode: "insensitive",
},
},
{
lastName: {
contains: "stein",
mode: "insensitive",
},
},
],
},
],
});
});
it("also searches int fields if it is a number", () => {
const filter = {
q: "albert 1879",
};
const result = buildWhere(
filter,
testUserResource,
testIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
AND: [
{
OR: [
{
email: {
contains: "albert",
mode: "insensitive",
},
},
{
firstName: {
contains: "albert",
mode: "insensitive",
},
},
{
lastName: {
contains: "albert",
mode: "insensitive",
},
},
],
},
{
OR: [
{
email: {
contains: "1879",
mode: "insensitive",
},
},
{
firstName: {
contains: "1879",
mode: "insensitive",
},
},
{
lastName: {
contains: "1879",
mode: "insensitive",
},
},
{
yearOfBirth: {
equals: 1879,
},
},
],
},
],
});
});
});
describe("custom filters", () => {
it("supports custom filters", () => {
const options: OurOptions = {
filters: {
millenials: (millenials?: boolean) =>
millenials === true
? {
AND: [
{
yearOfBirth: {
gte: 1981,
},
},
{
yearOfBirth: {
lte: 1996,
},
},
],
}
: millenials === false
? {
OR: [
{
yearOfBirth: {
lt: 1981,
},
},
{
yearOfBirth: {
gt: 1996,
},
},
],
}
: undefined,
},
};
const result = buildWhere(
{
millenials: true,
},
testUserResource,
testIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
AND: [
{
yearOfBirth: {
gte: 1981,
},
},
{
yearOfBirth: {
lte: 1996,
},
},
],
});
const result2 = buildWhere(
{
millenials: false,
},
testUserResource,
testIntrospection,
options,
);
expect(result2).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
OR: [
{
yearOfBirth: {
lt: 1981,
},
},
{
yearOfBirth: {
gt: 1996,
},
},
],
});
const result3 = buildWhere(
{
millenials: null,
},
testUserResource,
testIntrospection,
options,
);
expect(result3).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({});
});
it("custom filters work alongside other filters", () => {
const options: OurOptions = {
filters: {
millenials: (millenials?: boolean) =>
millenials === true
? {
AND: [
{
yearOfBirth: {
gte: 1981,
},
},
{
yearOfBirth: {
lte: 1996,
},
},
],
}
: millenials === false
? {
OR: [
{
yearOfBirth: {
lt: 1981,
},
},
{
yearOfBirth: {
gt: 1996,
},
},
],
}
: undefined,
},
};
const result = buildWhere(
{
millenials: true,
firstName: "Albert",
},
testUserResource,
testIntrospection,
options,
);
expect(result).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
AND: [
{
AND: [
{
yearOfBirth: {
gte: 1981,
},
},
{
yearOfBirth: {
lte: 1996,
},
},
],
},
{
firstName: {
contains: "Albert",
mode: "insensitive",
},
},
],
});
const result2 = buildWhere(
{
millenials: false,
firstName: "Albert",
},
testUserResource,
testIntrospection,
options,
);
expect(result2).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
AND: [
{
OR: [
{
yearOfBirth: {
lt: 1981,
},
},
{
yearOfBirth: {
gt: 1996,
},
},
],
},
{
firstName: {
contains: "Albert",
mode: "insensitive",
},
},
],
});
const result3 = buildWhere(
{
millenials: null,
firstName: "Albert",
},
testUserResource,
testIntrospection,
options,
);
expect(result3).toEqual<NexusGenArgTypes["Query"]["users"]["where"]>({
AND: [
{}, // does currently not remove empty objects, but they don't hurt
{
firstName: {
contains: "Albert",
mode: "insensitive",
},
},
],
});
});
});
}); | the_stack |
import * as React from 'react';
import {
clone,
get,
isObjectLike,
} from 'lodash';
import freeze from 'deep-freeze-node';
import {
BasicProps, BindItem,
ContainerContextType, ContainerNodeOptions, ContainerSetDataOption,
TaskConfig, defaultData, ESFunc,
ProviderSourceConfig,
RCREContextType
} from '../../types';
import {connect} from 'react-redux';
import {$parent} from '../util/compat';
import {
ASYNC_LOAD_DATA_FAIL_PAYLOAD,
ASYNC_LOAD_DATA_PROGRESS_PAYLOAD,
ASYNC_LOAD_DATA_SUCCESS_PAYLOAD,
containerActionCreators, SYNC_LOAD_DATA_FAIL_PAYLOAD, SYNC_LOAD_DATA_SUCCESS_PAYLOAD
} from './action';
import {RootState} from '../../data/reducers';
import {DataProvider} from '../DataProvider/Controller';
import {compileExpressionString, isExpression, parseExpressionString} from '../util/vm';
import {DataCustomer} from '../DataCustomer/index';
import {ContainerNode} from '../Service/ContainerDepGraph';
import {ContainerContext} from '../context';
import {getRuntimeContext} from '../util/util';
import {polyfill} from 'react-lifecycles-compat';
export interface ContainerProps extends ContainerNodeOptions {
/**
* 数据模型Key
*/
model: string;
/**
* 初始化数据
*/
data?: defaultData;
/**
* container 继承属性映射
*/
props?: {
[key: string]: ESFunc
};
/**
* 自动同步子级的对应属性的值到父级
* @deprecated
*/
bind?: BindItem[];
/**
* 自定义内部的属性值,只需指定父级的Key,根据ExpressionString来计算出传入到父级的值
*/
export?: {
[parent: string]: ESFunc;
} | string;
/**
* dataProvider配置
*/
dataProvider?: ProviderSourceConfig[];
/**
* dataCustomer配置
*/
dataCustomer?: TaskConfig;
task?: TaskConfig;
/**
* 子级组件
*/
children?: any;
}
export interface ConnectContainerProps extends ContainerProps, BasicProps {
/**
* 当前Container组件的数据模型
*/
$data?: any;
}
class Container extends React.PureComponent<ConnectContainerProps, {}> {
static displayName = 'RCREContainer';
private dataProvider: DataProvider;
private dataCustomer: DataCustomer;
// private event: EventNode;
private isUnmount: boolean;
constructor(props: ConnectContainerProps, context: RCREContextType) {
super(props);
this.dataProvider = new DataProvider(props.dataProvider || []);
this.dataCustomer = new DataCustomer(props.containerContext.dataCustomer);
this.isUnmount = false;
this.$setData = this.$setData.bind(this);
this.initContainerGraph(props);
this.initTask(props);
this.initDefaultData(props);
}
private initTask(props: ConnectContainerProps) {
const defaultCustomer = {
mode: 'pass',
name: '$SELF_PASS_CUSTOMER',
config: {
model: props.model,
assign: {}
}
};
const defaultParentCustomer = {
mode: 'pass',
name: '$PARENT_PASS_CUSTOMER',
config: {
model: props.containerContext.model,
assign: {}
}
};
let dataCustomer = props.dataCustomer || props.task;
if (!dataCustomer) {
dataCustomer = {
customers: [],
groups: []
};
}
let customers: any[] = dataCustomer.customers || dataCustomer.tasks || [];
let groups = dataCustomer.groups || dataCustomer.taskMap || [];
if (!Array.isArray(customers)) {
console.error('DataCustomer: customer属性必须是个数组');
return;
}
customers = [defaultCustomer, defaultParentCustomer].concat(customers);
this.dataCustomer.initCustomerConfig({
customers: customers,
groups: groups
});
}
private getContextCollection() {
return {
rcre: this.props.rcreContext,
container: this.props.containerContext,
iterator: this.props.iteratorContext,
form: this.props.formContext
};
}
private initDefaultData(props: ContainerProps) {
let data = this.props.data || {};
let defaultValue = {};
let runTime = getRuntimeContext({
$data: data,
} as ContainerContextType, this.props.rcreContext, {
iteratorContext: this.props.iteratorContext
});
data = compileExpressionString(data, runTime, [], true);
Object.assign(defaultValue, data);
this.props.rcreContext.store.dispatch(containerActionCreators.initContainer({
model: this.props.model,
data: defaultValue
}, this.getContextCollection()));
}
private initContainerGraph(props: ConnectContainerProps) {
let model = props.model;
let context = props.rcreContext;
if (!context.containerGraph.has(model)) {
let node = new ContainerNode(model, props.props, props.export, props.bind, {
syncDelete: props.syncDelete,
forceSyncDelete: props.forceSyncDelete,
clearDataToParentsWhenDestroy: props.clearDataToParentsWhenDestroy,
noNilToParent: props.noNilToParent
});
context.containerGraph.set(model, node);
if (this.props.containerContext.model && context.containerGraph.has(this.props.model)) {
let parentNode = context.containerGraph.get(this.props.containerContext.model)!;
parentNode.addChild(node);
}
} else {
console.warn('检测到有重复的container组件。model: ' + this.props.model);
}
}
componentWillUpdate(nextProps: ContainerProps) {
let store = this.props.rcreContext.store;
const providerActions = {
asyncLoadDataProgress: (payload: ASYNC_LOAD_DATA_PROGRESS_PAYLOAD) =>
store.dispatch(containerActionCreators.asyncLoadDataProgress(payload)),
asyncLoadDataSuccess: (payload: ASYNC_LOAD_DATA_SUCCESS_PAYLOAD) =>
store.dispatch(containerActionCreators.asyncLoadDataSuccess(payload)),
asyncLoadDataFail: (payload: ASYNC_LOAD_DATA_FAIL_PAYLOAD) =>
store.dispatch(containerActionCreators.asyncLoadDataFail(payload)),
syncLoadDataSuccess: (payload: SYNC_LOAD_DATA_SUCCESS_PAYLOAD) =>
store.dispatch(containerActionCreators.syncLoadDataSuccess(payload)),
syncLoadDataFail: (payload: SYNC_LOAD_DATA_FAIL_PAYLOAD) =>
store.dispatch(containerActionCreators.syncLoadDataFail(payload))
};
if (this.props.dataProvider) {
this.dataProvider.requestForData(nextProps.model, this.props.dataProvider, providerActions, nextProps, this.getContextCollection());
}
}
componentWillUnmount() {
this.props.rcreContext.store.dispatch(containerActionCreators.clearData({
model: this.props.model,
context: this.getContextCollection()
}));
this.dataProvider.providerCache = {};
let node = this.props.rcreContext.containerGraph.get(this.props.model);
if (node && node.parent) {
let parentNode = node.parent;
parentNode.removeChild(node);
}
this.props.rcreContext.containerGraph.delete(this.props.model);
this.isUnmount = true;
this.dataProvider.depose();
this.dataCustomer.depose();
this.depose();
// this.event.trigger('componentWillUnMount');
}
private depose() {
delete this.dataProvider;
delete this.dataCustomer;
delete this.$setData;
this.isUnmount = true;
}
$setData(name: string, value: any, options: ContainerSetDataOption = {}) {
if (this.isUnmount) {
return;
}
// IMPORTANT, 删除这个代码会引发严重的Bug
if (isObjectLike(value)) {
value = clone(value);
}
this.props.rcreContext.store.dispatch(containerActionCreators.setData({
name: String(name),
value: value,
options: options
}, this.props.model, this.getContextCollection()));
if (options.forceUpdate) {
this.forceUpdate();
}
}
$setMultiData = (items: {name: string, value: any}[]) => {
if (this.isUnmount) {
return;
}
items = items.map(item => {
// IMPORTANT, 删除这个代码会引发严重的Bug
if (isObjectLike(item.value)) {
item.value = clone(item.value);
}
return item;
});
this.props.rcreContext.store.dispatch(containerActionCreators.setMultiData(
items,
this.props.model,
this.getContextCollection()
));
}
$deleteData = (name: string) => {
this.props.rcreContext.store.dispatch(
containerActionCreators.deleteData({
name: name
}, this.props.model, this.getContextCollection())
);
}
TEST_setData(name: string, value: any) {
this.$setData(name, value);
}
render() {
if (!this.props.model) {
return <div className="err-text">Container: model should defined in container like components</div>;
}
if (!this.props.children) {
return <div className="err-text">Container: children props must be specific in Container Component</div>;
}
let data = this.props.$data;
if (process.env.NODE_ENV !== 'production') {
freeze(data);
}
// 初始化的时候,React-Redux无法给予最新的$data
if (data === undefined) {
let state: RootState = this.props.rcreContext.store.getState();
let model = this.props.model;
data = state.$rcre.container[model] || {};
}
let childElements = this.props.children;
// 通过这样的方式强制子级组件更新
const context = {
model: this.props.model,
$data: data,
$parent: $parent,
dataCustomer: this.dataCustomer,
$setData: this.$setData,
$getData: function (nameStr: string) {
if (!this.$data) {
return null;
}
if (typeof nameStr !== 'string') {
nameStr = String(nameStr);
}
return get(this.$data, nameStr);
},
$deleteData: this.$deleteData,
$setMultiData: this.$setMultiData,
};
return (
<ContainerContext.Provider value={context}>
{childElements}
</ContainerContext.Provider>
);
}
}
const mapStateToProps = (state: RootState, props: ConnectContainerProps) => {
let model = props.model;
if (isExpression(model)) {
let runTime = getRuntimeContext({} as ContainerContextType, props.rcreContext, {
iteratorContext: props.iteratorContext,
});
model = parseExpressionString(model, runTime);
}
let $data = state.$rcre.container[model];
return {
$data: $data
};
};
polyfill(Container);
export const RCREContainer = connect(mapStateToProps)(Container); | the_stack |
import {Auth, API} from 'aws-amplify';
import {ActionRule, Label} from './pages/settings/ActionRuleSettingsTab';
import {Action} from './pages/settings/ActionSettingsTab';
import {Bank, BankMember} from './messages/BankMessages';
import {toDate} from './utils/DateTimeUtils';
import {ContentType, getContentTypeForString} from './utils/constants';
async function getAuthorizationToken(): Promise<string> {
const currentSession = await Auth.currentSession();
const accessToken = currentSession.getAccessToken();
const jwtToken = accessToken.getJwtToken();
return jwtToken;
}
async function apiGet<T>(
route: string,
params = {},
responseType = null,
): Promise<T> {
return API.get('hma_api', route, {
responseType,
headers: {
Authorization: await getAuthorizationToken(),
},
queryStringParameters: params,
});
}
async function apiPost<T>(route: string, body = {}, params = {}): Promise<T> {
return API.post('hma_api', route, {
body,
headers: {
Authorization: await getAuthorizationToken(),
},
queryStringParameters: params,
});
}
async function apiPut<T>(route: string, body = {}, params = {}): Promise<T> {
return API.put('hma_api', route, {
body,
headers: {
Authorization: await getAuthorizationToken(),
},
queryStringParameters: params,
});
}
async function apiDelete<T>(route: string, params = {}): Promise<T> {
return API.del('hma_api', route, {
headers: {
Authorization: await getAuthorizationToken(),
},
queryStringParameters: params,
});
}
type MatchSummaries = {match_summaries: MatchDetails[]};
export async function fetchAllMatches(): Promise<MatchSummaries> {
return apiGet('matches/');
}
export async function fetchMatchesFromSignal(
signalSource: string,
signalId: string,
): Promise<MatchSummaries> {
return apiGet('matches/', {
signal_q: signalId,
signal_source: signalSource,
});
}
export async function fetchMatchesFromContent(
contentId: string,
): Promise<MatchSummaries> {
return apiGet('matches/', {content_q: contentId});
}
export type MatchDetails = {
content_id: string;
content_hash: string;
signal_id: string;
signal_hash: string;
signal_source: string;
signal_type: string;
updated_at: string;
metadata: {
privacy_group_id: string;
tags: string[];
opinion: string;
pending_opinion_change: string;
}[];
};
type Matches = {match_details: MatchDetails[]};
export async function fetchMatchDetails(contentId: string): Promise<Matches> {
return apiGet('matches/match/', {content_id: contentId});
}
export type HashDetails = {
content_hash: string;
updated_at: string;
};
export async function fetchHashDetails(
contentId: string,
): Promise<HashDetails> {
return apiGet('content/hash/', {content_id: contentId});
}
export async function fetchPreviewURL(
contentId: string,
): Promise<{preview_url: string}> {
return apiGet('content/preview-url/', {content_id: contentId});
}
export type ContentActionHistoryRecord = {
action_label: string;
performed_at: string;
};
type ContentActionHistoryRecords = {
action_history: Array<ContentActionHistoryRecord>;
};
export async function fetchContentActionHistory(
contentId: string,
): Promise<ContentActionHistoryRecords> {
return apiGet('content/action-history/', {content_id: contentId});
}
export type ContentDetails = {
content_id: string;
content_type: string;
content_ref: string;
content_ref_type: string;
submission_times: Array<string>;
created_at: string;
updated_at: string;
additional_fields: Array<string>;
};
export async function fetchContentDetails(
contentId: string,
): Promise<ContentDetails> {
return apiGet('content/', {
content_id: contentId,
});
}
type ContentPipelineProgress = {
content_type: string;
content_preview_url: string;
submitted_at: string;
hashed_at: string;
matched_at: string;
action_evaluated_at: string;
action_performed_at: string;
};
export async function fetchContentPipelineProgress(
contentId: string,
): Promise<ContentPipelineProgress> {
return apiGet('content/pipeline-progress/', {
content_id: contentId,
});
}
export async function fetchDashboardCardSummary(
path: string,
): Promise<Response> {
return apiGet(`${path}`);
}
export type StatsCard = {
time_span_count: number;
time_span: string;
graph_data: Array<[number, number]>;
last_updated: string;
};
type StatsResponse = {
card: StatsCard;
};
export async function fetchStats(
statName: string,
timeSpan: string,
): Promise<StatsResponse> {
return apiGet('stats/', {stat_name: statName, time_span: timeSpan});
}
export async function requestSignalOpinionChange(
signalId: string,
signalSource: string,
privacyGroupId: string,
opinionChange: string,
): Promise<void> {
apiPost(
'/matches/request-signal-opinion-change/',
{},
{
signal_id: signalId,
signal_source: signalSource,
privacy_group_id: privacyGroupId,
opinion_change: opinionChange,
},
);
}
export async function submitContentViaURL(
contentId: string,
contentType: string,
additionalFields: string[],
contentURL: string,
forceResubmit: boolean,
): Promise<Response> {
return apiPost('submit/url/', {
content_id: contentId,
content_type: contentType,
additional_fields: additionalFields,
content_url: contentURL,
force_resubmit: forceResubmit,
});
}
export async function submitContentViaPutURLUpload(
contentId: string,
contentType: string,
additionalFields: string[],
content: File,
forceResubmit: boolean,
): Promise<Response> {
const submitResponse = await apiPost<{presigned_url: string}>(
'submit/put-url/',
{
content_id: contentId,
content_type: contentType,
additional_fields: additionalFields,
file_type: content.type,
force_resubmit: forceResubmit,
},
);
const requestOptions = {
method: 'PUT',
body: content,
};
// Content object was created. Now the content itself needs to be uploaded to s3
// using the put url in the response.
const result = await fetch(submitResponse.presigned_url, requestOptions);
return result;
}
type DatasetSummariesResponse = {
threat_exchange_datasets: Array<Dataset>;
};
export async function fetchAllDatasets(): Promise<DatasetSummariesResponse> {
return apiGet('datasets/');
}
export async function syncAllDatasets(): Promise<{response: string}> {
return apiPost('datasets/sync');
}
export async function deleteDataset(key: string): Promise<{response: string}> {
return apiPost(`datasets/delete/${key}`);
}
export type PrivacyGroup = {
privacyGroupId: string;
localFetcherActive: boolean;
localWriteBack: boolean;
localMatcherActive: boolean;
};
type Dataset = {
privacy_group_id: string;
privacy_group_name: string;
description: string;
fetcher_active: boolean;
matcher_active: boolean;
write_back: boolean;
in_use: boolean;
hash_count: number;
match_count: number;
};
export async function updateDataset(
privacyGroupId: string,
fetcherActive: boolean,
writeBack: boolean,
matcherActive: boolean,
): Promise<Dataset> {
return apiPost('datasets/update', {
privacy_group_id: privacyGroupId,
fetcher_active: fetcherActive,
write_back: writeBack,
matcher_active: matcherActive,
});
}
export async function createDataset(
privacyGroupId: string,
privacyGroupName: string,
description = '',
fetcherActive = false,
writeBack = false,
matcherActive = true,
): Promise<{response: string}> {
return apiPost('datasets/create', {
privacy_group_id: privacyGroupId,
privacy_group_name: privacyGroupName,
description,
fetcher_active: fetcherActive,
write_back: writeBack,
matcher_active: matcherActive,
});
}
export async function fetchHashCount(): Promise<Response> {
return apiGet('hash-counts');
}
// This class should be kept in sync with python class ActionPerformer (hmalib.common.configs.actioner.ActionPerformer)
type BackendActionPerformer = {
name: string;
config_subtype: string;
url: string;
headers: string;
};
type AllActions = {
error_message: string;
actions_response: Array<BackendActionPerformer>;
};
export async function fetchAllActions(): Promise<Action[]> {
return apiGet<AllActions>('actions/').then(response => {
if (response && !response.error_message && response.actions_response) {
return response.actions_response.map(
action =>
({
name: action.name,
config_subtype: action.config_subtype,
params: {url: action.url, headers: action.headers},
} as Action),
);
}
return [];
});
}
export async function createAction(
newAction: Action,
): Promise<{response: string}> {
return apiPost('actions/', {
name: newAction.name,
config_subtype: newAction.config_subtype,
fields: newAction.params,
});
}
export async function updateAction(
old_name: string,
old_config_subtype: string,
updatedAction: Action,
): Promise<{response: string}> {
return apiPut(`actions/${old_name}/${old_config_subtype}`, {
name: updatedAction.name,
config_subtype: updatedAction.config_subtype,
fields: updatedAction.params,
});
}
export async function deleteAction(name: string): Promise<{response: string}> {
return apiDelete(`actions/${name}`);
}
// We need two different ActionRule types because the mackend model (must (not) have labels) is different
// from the Frontend model (classification conditions).
// This class should be kept in sync with python class ActionRule (hmalib.common.configs.evaluator.ActionRule)
type BackendActionRule = {
name: string;
must_have_labels: Label[];
must_not_have_labels: Label[];
action_label: {
key: string;
value: string;
};
};
const convertToBackendActionRule = (frontend_action_rule: ActionRule) =>
({
name: frontend_action_rule.name,
must_have_labels: frontend_action_rule.must_have_labels,
must_not_have_labels: frontend_action_rule.must_not_have_labels,
action_label: {
key: 'Action',
value: frontend_action_rule.action_name,
},
} as BackendActionRule);
type AllActionRules = {
error_message: string;
action_rules: Array<BackendActionRule>;
};
export async function fetchAllActionRules(): Promise<ActionRule[]> {
return apiGet<AllActionRules>('action-rules/').then(response => {
if (response && response.error_message === '' && response.action_rules) {
const fetchedActionRules = response.action_rules.map(
backend_action_rule =>
new ActionRule(
backend_action_rule.name,
backend_action_rule.action_label.value,
backend_action_rule.must_have_labels,
backend_action_rule.must_not_have_labels,
),
);
return fetchedActionRules;
}
return [];
});
}
export async function addActionRule(actionRule: ActionRule): Promise<Response> {
const backendActionRule = convertToBackendActionRule(actionRule);
return apiPost('action-rules/', {
action_rule: backendActionRule,
});
}
export async function updateActionRule(
oldName: string,
actionRule: ActionRule,
): Promise<Response> {
const backendActionRule = convertToBackendActionRule(actionRule);
return apiPut(`action-rules/${oldName}`, {
action_rule: backendActionRule,
});
}
export async function deleteActionRule(name: string): Promise<Response> {
return apiDelete(`action-rules/${name}`);
}
// Banks APIs
type BankWithStringDates = Bank & {
created_at: string;
updated_at: string;
};
type AllBanksResponse = {
banks: BankWithStringDates[];
};
export async function fetchAllBanks(): Promise<Bank[]> {
return apiGet<AllBanksResponse>('banks/get-all-banks').then(response =>
response.banks.map(item => ({
bank_id: item.bank_id!,
bank_name: item.bank_name!,
bank_description: item.bank_description!,
created_at: toDate(item.created_at)!,
updated_at: toDate(item.updated_at)!,
})),
);
}
export async function fetchBank(bankId: string): Promise<Bank> {
return apiGet<BankWithStringDates>(`banks/get-bank/${bankId}`).then(
response => ({
bank_id: response.bank_id!,
bank_name: response.bank_name!,
bank_description: response.bank_description!,
created_at: toDate(response.created_at)!,
updated_at: toDate(response.updated_at)!,
}),
);
}
export async function createBank(
bankName: string,
bankDescription: string,
): Promise<void> {
return apiPost('banks/create-bank', {
bank_name: bankName,
bank_description: bankDescription,
});
}
export async function updateBank(
bankId: string,
bankName: string,
bankDescription: string,
): Promise<Bank> {
return apiPost<BankWithStringDates>(`banks/update-bank/${bankId}`, {
bank_name: bankName,
bank_description: bankDescription,
}).then(response => ({
bank_id: response.bank_id!,
bank_name: response.bank_name!,
bank_description: response.bank_description!,
created_at: toDate(response.created_at)!,
updated_at: toDate(response.updated_at)!,
}));
}
type BankMemberWithSerializedTypes = BankMember & {
content_type: string;
created_at: string;
updated_at: string;
};
type BankMembersPage = {
bank_members: BankMemberWithSerializedTypes[];
continuation_token: string;
};
export async function fetchBankMembersPage(
bankId: string,
contentType: ContentType,
continuationToken?: string,
): Promise<[BankMember[], string]> {
const url =
continuationToken === undefined
? `banks/get-members/${bankId}?content_type=${contentType}`
: `banks/get-members/${bankId}?content_type=${contentType}&continuation_token=${continuationToken}`;
return apiGet<BankMembersPage>(url).then(response => [
response.bank_members.map(member => ({
bank_id: member.bank_id,
bank_member_id: member.bank_member_id,
content_type: getContentTypeForString(member.content_type),
storage_bucket: member.storage_bucket,
storage_key: member.storage_key,
raw_content: member.raw_content,
preview_url: member.preview_url,
notes: member.notes,
created_at: toDate(member.created_at)!,
updated_at: toDate(member.updated_at)!,
})),
response.continuation_token,
]);
}
type MediaUploadURLResponse = {
upload_url: string;
storage_bucket: string;
storage_key: string;
};
export async function fetchMediaUploadURL(
mediaType: string,
extension: string,
): Promise<MediaUploadURLResponse> {
return apiPost<MediaUploadURLResponse>('banks/get-media-upload-url', {
media_type: mediaType,
extension,
});
}
export async function addBankMember(
bankId: string,
contentType: ContentType,
storageBucket: string,
storageKey: string,
notes: string,
): Promise<BankMember> {
return apiPost<BankMemberWithSerializedTypes>(`banks/add-member/${bankId}`, {
content_type: contentType,
storage_bucket: storageBucket,
storage_key: storageKey,
notes,
}).then(response => ({
bank_id: response.bank_id,
bank_member_id: response.bank_member_id,
content_type: getContentTypeForString(response.content_type),
storage_bucket: response.storage_bucket,
storage_key: response.storage_key,
preview_url: response.preview_url,
notes: response.notes,
created_at: toDate(response.created_at)!,
updated_at: toDate(response.updated_at)!,
}));
} | the_stack |
import {LitElement, css, html, CSSResultGroup, TemplateResult} from 'lit';
import {customElement, property, query} from 'lit/decorators.js';
import {classMap} from 'lit/directives/class-map.js';
import {generateElementName, nextFrame} from './test-helpers';
import {
animate,
Animate,
Options,
CSSValues,
fadeIn,
flyAbove,
flyBelow,
} from '../animate.js';
import {assert} from '@esm-bundle/chai';
// Note, since tests are not built with production support, detect DEV_MODE
// by checking if warning API is available.
const DEV_MODE = !!LitElement.enableWarning;
if (DEV_MODE) {
LitElement.disableWarning?.('change-in-update');
}
/**
* TODO
* 1. work out when onStart/onComplete and animates run
* 2. disabled: does this call onStart/onComplete: should not.
* 3. controller tests
* 4. remove `scaleUp` and maybe `reset` and `commit`.
*/
suite('Animate', () => {
let el;
let container: HTMLElement;
let theAnimate: Animate | undefined;
let animateProps: CSSValues | undefined;
let frames: Keyframe[] | undefined;
let animateElement: Element | undefined;
const onStart = (animate: Animate) => {
theAnimate = animate;
animateElement = animate.element;
};
const onComplete = (animate: Animate) => {
animateProps = animate.animatingProperties!;
frames = animate.frames!;
};
const generateAnimateElement = (
options: Options = {onStart, onComplete},
extraCss?: CSSResultGroup,
childTemplate?: () => TemplateResult
) => {
const styles: CSSResultGroup = [
css`
* {
box-sizing: border-box;
}
div {
display: inline-block;
outline: 1px dotted black;
position: relative;
}
.container {
height: 200px;
width: 200px;
}
.shift {
left: 200px;
top: 200px;
opacity: 0;
}
`,
];
if (extraCss !== undefined) {
styles.push(extraCss);
}
@customElement(generateElementName())
class A extends LitElement {
@property() shift = false;
@query('div') div!: HTMLDivElement;
static override styles = styles;
override render() {
return html`<div
class="container ${classMap({shift: this.shift})}"
${animate(options)}
>
Animate ${childTemplate?.()}
</div>`;
}
}
return A;
};
setup(async () => {
theAnimate = undefined;
animateProps = undefined;
frames = undefined;
animateElement = undefined;
container = document.createElement('div');
document.body.appendChild(container);
});
teardown(() => {
if (container && container.parentNode) {
container.parentNode.removeChild(container);
}
});
// TODO(sorvell): when should onComplete go?
test('onStart/onComplete', async () => {
let completeEl;
const onComplete = (animate: Animate) => {
completeEl = animate.element;
};
const El = generateAnimateElement({onStart, onComplete});
el = new El();
container.appendChild(el);
await el.updateComplete;
assert.ok(theAnimate!);
assert.equal(el.div, animateElement);
await theAnimate!.finished;
el.shift = true;
await el.updateComplete;
await theAnimate!.finished;
assert.equal(el.div, completeEl);
});
test('animates layout change', async () => {
const El = generateAnimateElement();
el = new El();
container.appendChild(el);
await el.updateComplete;
const b = el.getBoundingClientRect();
const r1 = el.div.getBoundingClientRect();
assert.equal(r1.left - b.left, 0);
assert.equal(r1.top - b.top, 0);
el.shift = true;
await el.updateComplete;
await theAnimate!.finished;
assert.ok(frames!);
assert.equal(
(frames![0].transform as string).trim(),
'translateX(-200px) translateY(-200px)'
);
assert.equal(frames![1].opacity, 0);
const r2 = el.div.getBoundingClientRect();
assert.equal(r2.left - b.left, 200);
assert.equal(r2.top - b.top, 200);
theAnimate = undefined;
frames = undefined;
el.shift = false;
await el.updateComplete;
await theAnimate!.finished;
const r3 = el.div.getBoundingClientRect();
assert.ok(frames!);
assert.equal(
(frames![0].transform as string).trim(),
'translateX(200px) translateY(200px)'
);
assert.equal(r3.left - r2.left, -200);
assert.equal(r3.top - r2.top, -200);
assert.deepEqual(animateProps, {left: 200, top: 200});
});
test('sets animate animationOptions', async () => {
const duration = 10;
const easing = 'linear';
const fill = 'both';
const El = generateAnimateElement({
onStart,
keyframeOptions: {
duration,
easing,
fill,
},
});
el = new El();
container.appendChild(el);
await el.updateComplete;
el.shift = true;
await el.updateComplete;
await nextFrame();
const timing = theAnimate?.webAnimation?.effect?.getTiming();
assert.equal(timing?.duration, duration);
assert.equal(timing?.easing, easing);
assert.equal(timing?.fill, fill);
});
// TODO(sorvell): `theAnimate` ideally is not defined here but it's tricky to
// marshal options and not have onStart fire. Perhaps change onStart to
// onBeforeStart?
test('disabled', async () => {
const options = {
onStart,
onComplete,
disabled: true,
};
const El = generateAnimateElement(options);
el = new El();
container.appendChild(el);
await el.updateComplete;
el.shift = true;
await el.updateComplete;
await theAnimate?.finished;
assert.notOk(frames);
options.disabled = false;
el.shift = false;
await el.updateComplete;
await theAnimate?.finished;
assert.ok(frames);
theAnimate = frames = undefined;
options.disabled = true;
el.shift = true;
await el.updateComplete;
await (theAnimate as unknown as Animate)?.finished;
assert.notOk(frames);
});
test('guard', async () => {
let guardValue = 0;
const guard = () => guardValue;
const El = generateAnimateElement({
onStart,
onComplete,
guard,
keyframeOptions: {duration: 10},
});
el = new El();
container.appendChild(el);
await el.updateComplete;
el.shift = true;
await el.updateComplete;
await theAnimate?.finished;
assert.ok(frames);
// guardValue not changed, so should not run again.
el.shift = false;
theAnimate = frames = undefined;
await el.updateComplete;
await (theAnimate as unknown as Animate)?.finished;
assert.notOk(frames);
// guardValue changed, so should run.
guardValue = 1;
el.shift = true;
theAnimate = frames = undefined;
await el.updateComplete;
await theAnimate!.finished;
assert.ok(frames);
// guardValue not changed, so should not run again.
el.shift = false;
theAnimate = frames = undefined;
await el.updateComplete;
await (theAnimate as unknown as Animate)?.finished;
assert.notOk(frames);
// guardValue changed, so should run.
guardValue = 2;
el.shift = true;
theAnimate = frames = undefined;
await el.updateComplete;
await theAnimate!.finished;
assert.ok(frames);
});
test('guard - array', async () => {
let guardValue = [1, 2, 3];
const guard = () => guardValue;
const El = generateAnimateElement({
onStart,
onComplete,
guard,
keyframeOptions: {duration: 10},
});
el = new El();
container.appendChild(el);
await el.updateComplete;
el.shift = true;
await el.updateComplete;
await theAnimate?.finished;
assert.ok(frames);
// guardValue not changed, so should not run again.
el.shift = false;
theAnimate = frames = undefined;
await el.updateComplete;
await (theAnimate as unknown as Animate)?.finished;
assert.notOk(frames);
// guardValue changed, so should run.
guardValue = [1, 2, 3, 4];
el.shift = true;
theAnimate = frames = undefined;
await el.updateComplete;
await theAnimate!.finished;
assert.ok(frames);
// guardValue not changed, so should not run again.
el.shift = false;
theAnimate = frames = undefined;
await el.updateComplete;
await (theAnimate as unknown as Animate)?.finished;
assert.notOk(frames);
// guardValue changed, so should run.
guardValue = [1, 2];
el.shift = true;
theAnimate = frames = undefined;
await el.updateComplete;
await theAnimate!.finished;
assert.ok(frames);
});
test('sets animate properties', async () => {
const El = generateAnimateElement(
{
onStart,
onComplete,
properties: ['left', 'color'],
},
css`
.shift {
opacity: 1;
color: orange;
background: blue;
}
`
);
el = new El();
container.appendChild(el);
await el.updateComplete;
el.shift = true;
await el.updateComplete;
await theAnimate!.finished;
assert.ok(frames!);
assert.deepEqual(animateProps, {left: -200});
assert.equal((frames![0].transform as string).trim(), 'translateX(-200px)');
assert.equal((frames![0].color as string).trim(), 'rgb(0, 0, 0)');
assert.notOk(frames![0].background);
assert.equal((frames![1].color as string).trim(), 'rgb(255, 165, 0)');
});
test('adjusts for ancestor position', async () => {
let shiftChild = false;
let shiftGChild = false;
let childAnimateProps: CSSValues;
let gChildAnimate: Animate, gChildAnimateProps: CSSValues;
const childComplete = (animate: Animate) => {
childAnimateProps = animate.animatingProperties!;
};
const gChildStart = (animate: Animate) => (gChildAnimate = animate);
const gChildComplete = (animate: Animate) => {
gChildAnimateProps = animate.animatingProperties!;
};
const El = generateAnimateElement(
{
keyframeOptions: {fill: 'both'},
},
css`
.shift {
height: 100px;
width: 100px;
}
.child {
position: absolute;
right: 0;
width: 100px;
}
.shiftChild {
left: 0;
top: 20px;
}
.gChild {
position: absolute;
right: 0;
width: 50px;
}
.shiftGChild {
left: 0;
top: 20px;
}
`,
() => html`<div
class="child ${classMap({shiftChild})}"
${animate({onComplete: childComplete})}
>
Child
<div
class="gChild ${classMap({shiftGChild})}"
${animate({onStart: gChildStart, onComplete: gChildComplete})}
>
GChild
</div>
</div>`
);
el = new El();
container.appendChild(el);
await el.updateComplete;
await gChildAnimate!.finished;
el.shift = true;
shiftChild = true;
shiftGChild = true;
await el.updateComplete;
await gChildAnimate!.finished;
assert.deepEqual(childAnimateProps!, {
left: 50,
top: -20,
width: 0.5,
height: 0.5,
});
assert.deepEqual(gChildAnimateProps!, {left: 50, top: -20});
el.shift = false;
shiftChild = false;
shiftGChild = false;
await el.updateComplete;
await gChildAnimate!.finished;
assert.deepEqual(childAnimateProps!, {
left: -100,
top: 40,
width: 2,
height: 2,
});
assert.deepEqual(gChildAnimateProps!, {left: -50, top: 20});
});
test('animates in', async () => {
const El = generateAnimateElement({
onStart,
onComplete,
in: [{transform: 'translateX(-100px)'}],
});
el = new El();
container.appendChild(el);
await el.updateComplete;
await theAnimate!.finished;
assert.ok(frames);
// no properties calculated when animateping in.
assert.notOk(animateProps);
assert.equal((frames![0].transform as string).trim(), 'translateX(-100px)');
});
test('onFrames', async () => {
const mod = 'translateX(100px) translateY(100px)';
const onFrames = (animate: Animate) => {
if (animate.frames === undefined) {
return;
}
animate.frames[0].transform! = mod;
return animate.frames!;
};
const El = generateAnimateElement({
onStart,
onComplete,
onFrames,
});
el = new El();
container.appendChild(el);
await el.updateComplete;
await theAnimate!.finished;
el.shift = true;
await el.updateComplete;
await theAnimate!.finished;
assert.ok(frames);
assert.deepEqual(frames![0].transform, mod);
});
test('animates in, skipInitial', async () => {
const El = generateAnimateElement({
onStart,
onComplete,
in: fadeIn,
skipInitial: true,
});
el = new El();
container.appendChild(el);
await el.updateComplete;
assert.notOk(theAnimate);
assert.notOk(frames);
});
test('animates out', async () => {
let shouldRender = true;
let disconnectAnimate: Animate, disconnectFrames: Keyframe[];
const onDisconnectStart = (animate: Animate) => {
disconnectAnimate = animate;
};
const onDisconnectComplete = (animate: Animate) => {
disconnectFrames = animate.frames!;
};
const outFrames = flyBelow;
const El = generateAnimateElement(
undefined,
undefined,
() =>
html`${shouldRender
? html`<div
${animate({
onStart: onDisconnectStart,
onComplete: onDisconnectComplete,
out: outFrames,
})}
>
Out
</div>`
: ''}`
);
el = new El();
container.appendChild(el);
await el.updateComplete;
await disconnectAnimate!.finished;
shouldRender = false;
el.requestUpdate();
await el.updateComplete;
await disconnectAnimate!.finished;
assert.equal(disconnectFrames!, outFrames);
});
test('animates out, stabilizeOut', async () => {
let shouldRender = true;
let disconnectAnimate: Animate;
let disconnectElement: HTMLElement;
let startCalls = 0;
const onStart = (animate: Animate) => {
startCalls++;
disconnectAnimate = animate;
disconnectElement = animate.element;
const p = disconnectElement!.parentElement!.getBoundingClientRect();
const r = disconnectElement!.getBoundingClientRect();
const s =
disconnectElement!.previousElementSibling!.getBoundingClientRect();
if (!shouldRender) {
assert.equal(
r.bottom - p.top,
options.stabilizeOut ? r.height : s.height
);
}
};
const options = {
onStart,
out: flyBelow,
stabilizeOut: false,
};
const El = generateAnimateElement(
undefined,
undefined,
() =>
html`<div
style="vertical-align: bottom; height: ${shouldRender
? '0px'
: '100px'}"
></div>
${shouldRender ? html`<div ${animate(options)}>Out</div>` : ''}`
);
el = new El();
container.appendChild(el);
await el.updateComplete;
await disconnectAnimate!.finished;
assert.equal(startCalls, 1);
shouldRender = false;
el.requestUpdate();
await el.updateComplete;
await disconnectAnimate!.finished;
assert.equal(startCalls, 2);
shouldRender = true;
el.requestUpdate();
await el.updateComplete;
await disconnectAnimate!.finished;
assert.equal(startCalls, 3);
options.stabilizeOut = true;
shouldRender = false;
el.requestUpdate();
await el.updateComplete;
await disconnectAnimate!.finished;
assert.equal(startCalls, 4);
});
test('animates in based on an element that animated out', async () => {
let shouldRender = true;
let oneAnimate: Animate | undefined, twoAnimate: Animate | undefined;
let oneFrames: Keyframe[] | undefined, twoFrames: Keyframe[] | undefined;
const onOneStart = (animate: Animate) => {
oneAnimate = animate;
};
const onOneComplete = (animate: Animate) => {
oneFrames = animate.frames;
};
const onTwoStart = (animate: Animate) => {
twoAnimate = animate;
};
const onTwoComplete = (animate: Animate) => {
twoFrames = animate.frames;
};
const El = generateAnimateElement(
undefined,
css`
.one {
position: absolute;
top: 20px;
width: 50px;
}
.two {
position: absolute;
top: 40px;
width: 50px;
}
`,
() =>
html`${shouldRender
? html`<div
class="one"
${animate({
id: '1',
inId: '2',
onStart: onOneStart,
onComplete: onOneComplete,
out: flyAbove,
in: fadeIn,
skipInitial: true,
})}
>
Out
</div>`
: html`<div
class="two"
${animate({
id: '2',
inId: '1',
onStart: onTwoStart,
onComplete: onTwoComplete,
in: fadeIn,
out: flyBelow,
})}
>
In
</div>`}`
);
el = new El();
container.appendChild(el);
await el.updateComplete;
await oneAnimate?.finished;
await twoAnimate?.finished;
shouldRender = false;
el.requestUpdate();
oneFrames = twoFrames = undefined;
await el.updateComplete;
await twoAnimate?.finished;
assert.equal(oneFrames, flyAbove);
assert.equal(
(twoFrames![0].transform! as string).trim(),
'translateY(-20px)'
);
oneFrames = twoFrames = undefined;
shouldRender = true;
el.requestUpdate();
await el.updateComplete;
await twoAnimate?.finished;
assert.equal(twoFrames, flyBelow);
assert.equal(
(oneFrames![0].transform! as string).trim(),
'translateY(20px)'
);
});
}); | the_stack |
* @module SelectionSet
*/
import { BeEvent, Id64, Id64Arg, Id64String } from "@itwin/core-bentley";
import { IModelApp } from "./IModelApp";
import { IModelConnection } from "./IModelConnection";
/** Identifies the type of changes made to the [[SelectionSet]] to produce a [[SelectionSetEvent]].
* @public
* @extensions
*/
export enum SelectionSetEventType {
/** Elements have been added to the set. */
Add,
/** Elements have been removed from the set. */
Remove,
/** Some elements have been added to the set and others have been removed. */
Replace,
/** All elements are about to be removed from the set. */
Clear,
}
/** Passed to [[SelectionSet.onChanged]] event listeners when elements are added to the selection set.
* @public
* @extensions
*/
export interface SelectAddEvent {
type: SelectionSetEventType.Add;
/** The Ids of the elements added to the set. */
added: Id64Arg;
/** The affected SelectionSet. */
set: SelectionSet;
}
/** Passed to [[SelectionSet.onChanged]] event listeners when elements are removed from the selection set.
* @public
* @extensions
*/
export interface SelectRemoveEvent {
/** The type of operation that produced this event. */
type: SelectionSetEventType.Remove | SelectionSetEventType.Clear;
/** The element Ids removed from the set. */
removed: Id64Arg;
/** The affected SelectionSet. */
set: SelectionSet;
}
/** Passed to [[SelectionSet.onChanged]] event listeners when elements are simultaneously added to and removed from the selection set.
* @public
* @extensions
*/
export interface SelectReplaceEvent {
type: SelectionSetEventType.Replace;
/** The element Ids added to the set. */
added: Id64Arg;
/** The element Ids removed from the set. */
removed: Id64Arg;
/** The affected SelectionSet. */
set: SelectionSet;
}
/** Payload sent to [[SelectionSet.onChanged]] event listeners to describe how the contents of the set have changed.
* The `type` property of the event serves as a type assertion. For example, the following code will output the added and/or removed Ids:
* ```ts
* processSelectionSetEvent(ev: SelectionSetEvent): void {
* if (SelectionSetEventType.Add === ev.type || SelectionSetEventType.Replace === ev.type)
* console.log("Added " + ev.added.size + " elements");
*
* if (SelectionSetEventType.Add !== ev.type)
* console.log("Removed " + ev.removed.size + " elements");
* }
* ```
* @public
* @extensions
*/
export type SelectionSetEvent = SelectAddEvent | SelectRemoveEvent | SelectReplaceEvent;
/** Tracks a set of hilited entities. When the set changes, notifies ViewManager so that symbology overrides can be updated in active Viewports.
* @internal
*/
class HilitedIds extends Id64.Uint32Set {
protected _iModel: IModelConnection;
protected _changing = false;
public constructor(iModel: IModelConnection) {
super();
this._iModel = iModel;
}
public override add(low: number, high: number) {
super.add(low, high);
this.onChanged();
}
public override delete(low: number, high: number) {
super.delete(low, high);
this.onChanged();
}
public override clear() {
super.clear();
this.onChanged();
}
public override addIds(ids: Id64Arg) {
this.change(() => super.addIds(ids));
}
public override deleteIds(ids: Id64Arg) {
this.change(() => super.deleteIds(ids));
}
protected onChanged() {
if (!this._changing)
IModelApp.viewManager.onSelectionSetChanged(this._iModel);
}
protected change(func: () => void) {
const changing = this._changing;
this._changing = false;
func();
this._changing = changing;
this.onChanged();
}
}
/** Keeps the set of hilited elements in sync with the selection set.
* @internal
*/
class HilitedElementIds extends HilitedIds {
private _removeListener?: () => void;
public constructor(iModel: IModelConnection, syncWithSelectionSet = true) {
super(iModel);
this.wantSyncWithSelectionSet = syncWithSelectionSet;
}
public get wantSyncWithSelectionSet(): boolean { return undefined !== this._removeListener; }
public set wantSyncWithSelectionSet(want: boolean) {
if (want === this.wantSyncWithSelectionSet)
return;
if (want) {
const set = this._iModel.selectionSet;
this._removeListener = set.onChanged.addListener((ev) => this.change(() => this.processSelectionSetEvent(ev)));
this.processSelectionSetEvent({
set,
type: SelectionSetEventType.Add,
added: set.elements,
});
} else {
this._removeListener!();
this._removeListener = undefined;
}
}
private processSelectionSetEvent(ev: SelectionSetEvent): void {
if (SelectionSetEventType.Add !== ev.type)
this.deleteIds(ev.removed);
if (ev.type === SelectionSetEventType.Add || ev.type === SelectionSetEventType.Replace)
this.addIds(ev.added);
}
}
/** A set of *hilited* elements for an [[IModelConnection]], by element id.
* Hilited elements are displayed with a customizable hilite effect within a [[Viewport]].
* The set exposes 3 types of elements in 3 separate collections: geometric elements, subcategories, and geometric models.
* @note Typically, elements are hilited by virtue of their presence in the IModelConnection's [[SelectionSet]]. The HiliteSet allows additional
* elements to be displayed with the hilite effect without adding them to the [[SelectionSet]]. If you add elements to the HiliteSet directly, you
* are also responsible for removing them as appropriate.
* @note Support for subcategories and geometric models in the HiliteSet is currently `beta`.
* @see [[IModelConnection.hilited]] for the HiliteSet associated with an iModel.
* @see [Hilite.Settings]($common) for customization of the hilite effect.
* @public
* @extensions
*/
export class HiliteSet {
private readonly _elements: HilitedElementIds;
/** The set of hilited subcategories.
* @beta
*/
public readonly subcategories: Id64.Uint32Set;
/** The set of hilited [[GeometricModelState]]s.
* @beta
*/
public readonly models: Id64.Uint32Set;
/** The set of hilited elements. */
public get elements(): Id64.Uint32Set { return this._elements; }
/** Construct a HiliteSet
* @param iModel The iModel containing the entities to be hilited.
* @param syncWithSelectionSet If true, the contents of the `elements` set will be synchronized with those in the `iModel`'s [[SelectionSet]].
* @internal
*/
public constructor(public iModel: IModelConnection, syncWithSelectionSet = true) {
this._elements = new HilitedElementIds(iModel, syncWithSelectionSet);
this.subcategories = new HilitedIds(iModel);
this.models = new HilitedIds(iModel);
}
/** Control whether the hilited elements will be synchronized with the contents of the [[SelectionSet]].
* By default they are synchronized. Applications that override this take responsibility for managing the set of hilited entities.
* When turning synchronization off, the contents of the HiliteSet will remain unchanged.
* When turning synchronization on, the current contents of the HiliteSet will be preserved, and the contents of the selection set will be added to them.
*/
public get wantSyncWithSelectionSet(): boolean { return this._elements.wantSyncWithSelectionSet; }
public set wantSyncWithSelectionSet(want: boolean) { this._elements.wantSyncWithSelectionSet = want; }
/** Remove all elements from the hilited set. */
public clear() {
this.elements.clear();
this.subcategories.clear();
this.models.clear();
}
/** Returns true if nothing is hilited. */
public get isEmpty(): boolean { return this.elements.isEmpty && this.subcategories.isEmpty && this.models.isEmpty; }
/** Toggle the hilited state of one or more elements.
* @param arg the ID(s) of the elements whose state is to be toggled.
* @param onOff True to add the elements to the hilited set, false to remove them.
*/
public setHilite(arg: Id64Arg, onOff: boolean): void {
for (const id of Id64.iterable(arg)) {
if (onOff)
this.elements.addId(id);
else
this.elements.deleteId(id);
}
IModelApp.viewManager.onSelectionSetChanged(this.iModel);
}
}
/** A set of *currently selected* elements for an IModelConnection.
* Selected elements are displayed with a customizable hilite effect within a [[Viewport]].
* @see [Hilite.Settings]($common) for customization of the hilite effect.
* @public
* @extensions
*/
export class SelectionSet {
private _elements = new Set<string>();
/** The IDs of the selected elements.
* @note Do not modify this set directly. Instead, use methods like [[SelectionSet.add]].
*/
public get elements(): Set<string> { return this._elements; }
/** Called whenever elements are added or removed from this SelectionSet */
public readonly onChanged = new BeEvent<(ev: SelectionSetEvent) => void>();
public constructor(public iModel: IModelConnection) { }
private sendChangedEvent(ev: SelectionSetEvent) {
IModelApp.viewManager.onSelectionSetChanged(this.iModel);
this.onChanged.raiseEvent(ev);
}
/** Get the number of entries in this selection set. */
public get size() { return this.elements.size; }
/** Check whether there are any selected elements. */
public get isActive() { return this.size !== 0; }
/** Return true if elemId is in this SelectionSet.
* @see [[isSelected]]
*/
public has(elemId?: string) { return !!elemId && this.elements.has(elemId); }
/** Query whether an Id is in the selection set.
* @see [[has]]
*/
public isSelected(elemId?: Id64String): boolean { return !!elemId && this.elements.has(elemId); }
/** Clear current selection set.
* @note raises the [[onChanged]] event with [[SelectionSetEventType.Clear]].
*/
public emptyAll(): void {
if (!this.isActive)
return;
const removed = this._elements;
this._elements = new Set<string>();
this.sendChangedEvent({ set: this, type: SelectionSetEventType.Clear, removed });
}
/**
* Add one or more Ids to the current selection set.
* @param elem The set of Ids to add.
* @returns true if any elements were added.
*/
public add(elem: Id64Arg): boolean {
return this._add(elem);
}
private _add(elem: Id64Arg, sendEvent = true): boolean {
const oldSize = this.elements.size;
for (const id of Id64.iterable(elem))
this.elements.add(id);
const changed = oldSize !== this.elements.size;
if (sendEvent && changed)
this.sendChangedEvent({ type: SelectionSetEventType.Add, set: this, added: elem });
return changed;
}
/**
* Remove one or more Ids from the current selection set.
* @param elem The set of Ids to remove.
* @returns true if any elements were removed.
*/
public remove(elem: Id64Arg): boolean {
return this._remove(elem);
}
private _remove(elem: Id64Arg, sendEvent = true): boolean {
const oldSize = this.elements.size;
for (const id of Id64.iterable(elem))
this.elements.delete(id);
const changed = oldSize !== this.elements.size;
if (sendEvent && changed)
this.sendChangedEvent({ type: SelectionSetEventType.Remove, set: this, removed: elem });
return changed;
}
/**
* Add one set of Ids, and remove another set of Ids. Any Ids that are in both sets are removed.
* @returns True if any Ids were either added or removed.
*/
public addAndRemove(adds: Id64Arg, removes: Id64Arg): boolean {
const added = this._add(adds, false);
const removed = this._remove(removes, false);
if (added && removed)
this.sendChangedEvent({ type: SelectionSetEventType.Replace, set: this, added: adds, removed: removes });
else if (added)
this.sendChangedEvent({ type: SelectionSetEventType.Add, set: this, added: adds });
else if (removed)
this.sendChangedEvent({ type: SelectionSetEventType.Remove, set: this, removed: removes });
return (added || removed);
}
/** Invert the state of a set of Ids in the SelectionSet */
public invert(elem: Id64Arg): boolean {
const elementsToAdd = new Set<string>();
const elementsToRemove = new Set<string>();
for (const id of Id64.iterable(elem)) {
if (this.elements.has(id))
elementsToRemove.add(id);
else
elementsToAdd.add(id);
}
return this.addAndRemove(elementsToAdd, elementsToRemove);
}
/** Change selection set to be the supplied set of Ids. */
public replace(elem: Id64Arg): void {
if (areEqual(this.elements, elem))
return;
const removed = this._elements;
this._elements = new Set<string>();
this._add(elem, false);
if (0 < removed.size) {
for (const id of Id64.iterable(elem)) {
if (removed.has(id))
removed.delete(id);
}
}
this.sendChangedEvent({ type: SelectionSetEventType.Replace, set: this, added: elem, removed });
}
}
function areEqual(lhs: Set<string>, rhs: Id64Arg): boolean {
// Size is unreliable if input can contain duplicates...
if (Array.isArray(rhs))
rhs = Id64.toIdSet(rhs);
if (lhs.size !== Id64.sizeOf(rhs))
return false;
for (const id of Id64.iterable(rhs))
if (!lhs.has(id))
return false;
return true;
} | the_stack |
import type { ImageOptions, PswpInterface } from '@/types';
import type { EditorInterface, NodeInterface } from '@aomao/engine';
import {
$,
isEngine,
escape,
sanitizeUrl,
Tooltip,
isMobile,
Resizer,
CardType,
} from '@aomao/engine';
import PhotoSwipe from 'photoswipe';
import { ImageValue } from '..';
import Pswp from '../pswp';
import './index.css';
export type Status = 'uploading' | 'done' | 'error';
export type Size = {
width: number;
height: number;
naturalWidth: number;
naturalHeight: number;
};
export type Options = {
/**
* 卡片根节点
*/
root: NodeInterface;
/**
* 容器
*/
container: NodeInterface;
/**
* 状态
* uploading 上传中
* done 上传完成
* error 错误
*/
status: Status;
/**
* 图标链接
*/
src: string;
/**
* 标题
*/
alt?: string;
/**
* 链接
*/
link?: {
href: string;
target?: string;
};
display?: CardType;
/**
* 错误消息
*/
message?: string;
/**
* 样式名称,多个以空格隔空
*/
className?: string;
/**
* 图片大小
*/
size?: Size;
/**
* 上传进度
*/
percent?: number;
/**
* 图片渲染前调用
* @param status 状态
* @param src 图片地址
* @returns 图片地址
*/
onBeforeRender?: (status: 'uploading' | 'done', src: string) => string;
onChange?: (size?: Size, loaded?: boolean) => void;
onError?: () => void;
onLoad?: () => void;
enableResizer?: boolean;
maxHeight?: number | undefined;
};
export const winPixelRatio = window.devicePixelRatio;
let pswp: PswpInterface | undefined = undefined;
class Image {
private editor: EditorInterface;
options: Options;
root: NodeInterface;
private progress: NodeInterface;
private image: NodeInterface;
private detail: NodeInterface;
private meta: NodeInterface;
private maximize: NodeInterface;
private bg: NodeInterface;
resizer?: Resizer;
private pswp: PswpInterface;
src: string;
status: Status;
size: Size;
maxWidth: number;
maxHeight: number | undefined;
rate: number = 1;
isLoad: boolean = false;
message: string | undefined;
constructor(editor: EditorInterface, options: Options) {
this.editor = editor;
this.options = options;
this.src = this.options.src;
this.size = this.options.size || {
width: 0,
height: 0,
naturalHeight: 0,
naturalWidth: 0,
};
this.maxHeight = this.options.maxHeight;
this.status = this.options.status;
this.root = $(this.renderTemplate());
this.progress = this.root.find('.data-image-progress');
this.image = this.root.find('img');
this.detail = this.root.find('.data-image-detail');
this.meta = this.root.find('.data-image-meta');
this.maximize = this.root.find('.data-image-maximize');
this.bg = this.root.find('.data-image-bg');
this.maxWidth = this.getMaxWidth();
this.pswp = pswp || new Pswp(editor);
this.message = this.options.message;
pswp = this.pswp;
}
renderTemplate(message?: string) {
const { link, percent, className, onBeforeRender } = this.options;
if (this.status === 'error') {
return `<span class="data-image-error" style="max-width:${
this.maxWidth
}px"><span class="data-icon data-icon-error"></span>${
message || this.options.message
}<span class="data-icon data-icon-copy"></span></span>`;
}
const src = onBeforeRender
? onBeforeRender(this.status, this.options.src)
: this.options.src;
const progress = `<span class="data-image-progress">
<i class="data-anticon">
<svg viewBox="0 0 1024 1024" class="data-anticon-spin" data-icon="loading" width="1em" height="1em" fill="currentColor" aria-hidden="true">
<path d="M988 548c-19.9 0-36-16.1-36-36 0-59.4-11.6-117-34.6-171.3a440.45 440.45 0 0 0-94.3-139.9 437.71 437.71 0 0 0-139.9-94.3C629 83.6 571.4 72 512 72c-19.9 0-36-16.1-36-36s16.1-36 36-36c69.1 0 136.2 13.5 199.3 40.3C772.3 66 827 103 874 150c47 47 83.9 101.8 109.7 162.7 26.7 63.1 40.2 130.2 40.2 199.3.1 19.9-16 36-35.9 36z"></path>
</svg>
</i>
<span class="percent">${percent || 0}%</span>
</span>`;
const alt = escape(this.options.alt || '');
const attr = !!alt ? ` alt="${alt}" title="${alt}" ` : '';
//加上 data-drag-image 样式可以拖动图片
let img = `<img src="${sanitizeUrl(src)}" class="${
className || ''
} data-drag-image" ${attr}/>`;
//只读渲染加载链接
if (link && !isEngine(this.editor)) {
const target = link.target || '_blank';
img = `<a href="${sanitizeUrl(
link.href,
)}" target="${target}">${img}</a>`;
}
//全屏图标
let maximize =
'<span class="data-image-maximize" style="display: none;"><span class="data-icon data-icon-maximize"></span></span>';
return `
<span class="data-image">
<span class="data-image-content data-image-loading">
<span class="data-image-detail">
<span class="data-image-meta">
${img}
${progress}
<span class="data-image-bg"></span>
${maximize}
</span>
</span>
</span>
</span>`;
}
bindErrorEvent(node: NodeInterface) {
const editor = this.editor;
const copyNode = node.find('.data-icon-copy');
copyNode.on('mouseenter', () => {
Tooltip.show(
copyNode,
editor.language.get('image', 'errorMessageCopy').toString(),
);
});
copyNode.on('mouseleave', () => {
Tooltip.hide();
});
copyNode.on('click', (event: MouseEvent) => {
event.stopPropagation();
event.preventDefault();
Tooltip.hide();
editor.clipboard.copy(
this.message || this.options.message || 'Error message',
);
editor.messageSuccess(
'copy',
editor.language.get('copy', 'success').toString(),
);
});
}
setProgressPercent(percent: number) {
this.progress.find('.percent').html(`${percent}%`);
}
imageLoadCallback() {
const editor = this.editor;
const root = editor.card.closest(this.root);
if (!root || this.status === 'uploading') {
return;
}
if (this.status === 'done') {
const contentNode = this.root.find('.data-image-content');
contentNode.addClass('data-image-loaded');
contentNode.removeClass('data-image-loading');
}
const img = this.image.get<HTMLImageElement>();
if (!img) return;
const { naturalWidth, naturalHeight } = img;
this.rate = naturalHeight / naturalWidth;
this.size.naturalWidth = naturalWidth;
this.size.naturalHeight = naturalHeight;
if (!this.size.width) this.size.width = naturalWidth;
if (!this.size.height) this.size.height = naturalHeight;
this.resetSize();
this.image.css('visibility', 'visible');
this.detail.css('height', '');
this.detail.css('width', '');
const { onChange } = this.options;
if (isEngine(editor) && onChange) {
onChange(this.size, true);
}
window.removeEventListener('resize', this.onWindowResize);
window.addEventListener('resize', this.onWindowResize);
editor.off('editor:resize', this.onWindowResize);
editor.on('editor:resize', this.onWindowResize);
// 重新调整拖动层尺寸
if (this.resizer) {
this.resizer.setSize(img.clientWidth, img.clientHeight);
}
this.isLoad = true;
if (this.options.onLoad) {
this.options.onLoad();
}
}
onWindowResize = () => {
if (!isEngine(this.editor)) return;
this.maxWidth = this.getMaxWidth();
this.resetSize();
const image = this.image.get<HTMLElement>();
if (!image) return;
const { clientWidth, clientHeight } = image;
if (this.resizer) {
this.resizer.maxWidth = this.maxWidth;
this.resizer.setSize(clientWidth, clientHeight);
}
};
imageLoadError() {
if (this.status === 'uploading') return;
this.status = 'error';
const { container } = this.options;
container.empty();
container.append(
this.renderTemplate(
this.editor.language.get('image', 'loadError').toString(),
),
);
this.detail.css('width', '');
this.detail.css('height', '');
this.bindErrorEvent(container);
const { onError } = this.options;
if (onError) onError();
this.isLoad = true;
}
getMaxWidth(node: NodeInterface = this.options.root) {
const block = this.editor.block.closest(node).get<HTMLElement>();
if (!block) return 0;
return block.clientWidth - 6;
}
/**
* 重置大小
*/
resetSize() {
this.meta.css({
'background-color': '',
width: '',
//height: '',
});
this.image.css({
width: '',
//height: '',
});
const img = this.image.get<HTMLImageElement>();
if (!img) return;
let { width, height } = this.size;
if (!height) {
height = Math.round(this.rate * width);
} else if (!width) {
width = Math.round(height / this.rate);
} else if (width && height) {
// 修正非正常的比例
height = Math.round(this.rate * width);
this.size.height = height;
} else {
const { clientWidth, clientHeight } = img;
width = clientWidth;
height = clientHeight;
const { naturalWidth, naturalHeight } = this.size;
// fix:svg 图片宽度 300px 问题
if (this.isSvg() && naturalWidth && naturalHeight) {
width = naturalWidth;
height = naturalHeight;
}
}
if (width > this.maxWidth) {
width = this.maxWidth;
height = Math.round(width * this.rate);
}
if (this.options.enableResizer === false) {
this.image.css('width', '');
} else {
this.image.css('width', `${width}px`);
//this.image.css('height', `${height}px`);
}
}
changeSize(width: number, height: number) {
if (width < 24) {
width = 24;
height = width * this.rate;
}
if (width > this.maxWidth) {
width = this.maxWidth;
height = width * this.rate;
}
if (height < 24) {
height = 24;
width = height / this.rate;
}
width = Math.round(width);
height = Math.round(height);
this.size.width = width;
this.size.height = height;
this.image.css({
width: `${width}px`,
//height: `${height}px`,
});
const { onChange } = this.options;
if (onChange) onChange(this.size);
this.destroyEditor();
this.renderEditor();
}
changeUrl(url: string) {
if (this.src !== url) {
this.src = url;
this.isLoad = false;
this.image.attributes('src', this.getSrc());
}
}
getSrc = () => {
const { onBeforeRender } = this.options;
return onBeforeRender && this.status !== 'error'
? onBeforeRender(this.status, this.src)
: this.src;
};
isSvg() {
return (
this.src.split('?')[0].endsWith('.svg') ||
this.src.startsWith('data:image/svg+xml')
);
}
openZoom = (event: MouseEvent | TouchEvent) => {
event.preventDefault();
event.stopPropagation();
const editor = this.editor;
const imageArray: PhotoSwipe.Item[] = [];
const cardRoot = editor.card.closest(this.root);
let rootIndex = 0;
editor.container
.find('[data-card-key="image"]')
.toArray()
.filter((image) => {
return image.find('img').length > 0;
})
.forEach((imageNode, index) => {
const card = editor.card.find<ImageValue>(imageNode);
const value = card?.getValue();
if (!card || !value) return;
const image = card.getCenter().find('img');
const imageWidth = parseInt(image.css('width'));
const imageHeight = parseInt(image.css('height'));
const size = value.size;
const naturalWidth = size
? size.naturalWidth || this.size.naturalWidth
: imageWidth * winPixelRatio;
const naturalHeight = size
? size.naturalHeight || this.size.naturalHeight
: imageHeight * winPixelRatio;
let src = value['src'];
const { onBeforeRender } = this.options;
if (onBeforeRender) src = onBeforeRender('done', src);
const msrc = image.attributes('src');
imageArray.push({
src,
msrc,
w: naturalWidth,
h: naturalHeight,
});
if (cardRoot?.equal(imageNode)) {
rootIndex = index;
}
});
this.pswp.open(imageArray, rootIndex);
};
closeZoom() {
this.pswp?.close();
}
renderEditor() {
const img = this.image.get<HTMLElement>();
if (!img) return;
const { clientWidth, clientHeight } = img;
if (!clientWidth || !clientHeight) {
return;
}
const editor = this.editor;
this.maxWidth = this.getMaxWidth();
this.rate = clientHeight / clientWidth;
if (isMobile || !isEngine(editor) || editor.readonly) return;
if (this.options.enableResizer === false) {
return;
}
// 拖动调整图片大小
const resizer = new Resizer({
imgUrl: this.getSrc(),
width: clientWidth,
height: clientHeight,
rate: this.rate,
maxWidth: this.maxWidth,
onChange: ({ width, height }) => this.changeSize(width, height),
});
const resizerNode = resizer.render();
this.root.find('.data-image-detail').append(resizerNode);
this.resizer = resizer;
this.resizer.on('dblclick', this.openZoom);
}
destroyEditor() {
this.resizer?.off('dblclick', this.openZoom);
this.resizer?.destroy();
}
destroy() {
window.removeEventListener('resize', this.onWindowResize);
this.editor.off('editor:resize', this.onWindowResize);
this.destroyEditor();
this.image.off('click', this.openZoom);
this.image.off('dblclick', this.openZoom);
this.maximize.off('click', this.openZoom);
}
focus = () => {
if (!isEngine(this.editor)) {
return;
}
this.root.addClass('data-image-active');
if (this.status === 'done') {
this.destroyEditor();
this.renderEditor();
}
};
blur = () => {
if (!isEngine(this.editor)) {
return;
}
this.root.removeClass('data-image-active');
if (this.status === 'done') {
this.destroyEditor();
}
};
render(loadingBg?: string) {
// 阅读模式不展示错误
const { container, display, enableResizer } = this.options;
if (display === CardType.BLOCK) {
this.root.addClass('data-image-blcok');
}
const editor = this.editor;
if (enableResizer === false) {
this.root.addClass('data-image-disable-resize');
}
if (this.status === 'error' && isEngine(editor)) {
this.root = $(
this.renderTemplate(
this.message ||
editor.language.get<string>('image', 'uploadError'),
),
);
this.bindErrorEvent(this.root);
container.empty().append(this.root);
this.progress.remove();
return;
}
if (this.status === 'uploading') {
this.progress.show();
container.empty().append(this.root);
} else {
this.progress.remove();
}
if (this.status === 'done' && this.isLoad) {
const contentNode = this.root.find('.data-image-content');
contentNode.addClass('data-image-loaded');
contentNode.removeClass('data-image-loading');
}
if (this.status === 'done' && !this.isLoad) {
if (!this.root.inEditor()) container.empty().append(this.root);
}
this.maxWidth = this.getMaxWidth();
let { width, height } = this.size;
if ((width && height) || !this.src) {
if (width > this.maxWidth) {
width = this.maxWidth;
height = Math.round((width * height) / this.size.width);
} else if (!this.src && !width && !height) {
width = this.maxWidth;
height = this.maxWidth / 2;
}
if (this.src) {
if (this.options.enableResizer === false) {
this.image.css({
width: '100%',
});
} else {
this.image.css({
width: width + 'px',
//height: height + 'px',
});
}
const { onChange } = this.options;
if (width > 0 && height > 0) {
this.size = { ...this.size, width, height };
if (onChange) onChange(this.size);
}
}
if (this.options.enableResizer === false) {
this.bg.css({
width: '100%',
});
} else {
this.bg.css({
width: width + 'px',
height: height + 'px',
});
}
if (loadingBg) {
this.bg.css('background-image', `url(${loadingBg})`);
}
}
this.image.on('load', () => this.imageLoadCallback());
this.image.on('error', () => this.imageLoadError());
if (!isMobile) {
this.root.on('mouseenter', () => {
this.maximize.show();
});
this.root.on('mouseleave', () => {
this.maximize.hide();
});
}
if (!isEngine(editor) || editor.readonly) {
const link = this.image.closest('a');
// 无链接
if (link.length === 0) {
this.image.on('click', this.openZoom);
}
}
this.maximize.on('click', this.openZoom);
if (isEngine(editor) || !this.root.inEditor()) {
this.image.on('dblclick', this.openZoom);
}
}
}
export default Image; | the_stack |
* AppUpdateDevice请求参数结构体
*/
export interface AppUpdateDeviceRequest {
/**
* 访问Token
*/
AccessToken: string
/**
* 产品Id
*/
ProductId: string
/**
* 设备名称
*/
DeviceName: string
/**
* 设备别名
*/
AliasName?: string
}
/**
* GetDevice返回参数结构体
*/
export interface GetDeviceResponse {
/**
* 设备信息
*/
Device?: Device
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* GetDeviceData返回参数结构体
*/
export interface GetDeviceDataResponse {
/**
* 设备数据
*/
DeviceData?: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* AppResetPassword返回参数结构体
*/
export interface AppResetPasswordResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DeleteRule请求参数结构体
*/
export interface DeleteRuleRequest {
/**
* 规则Id
*/
RuleId: string
}
/**
* ActivateRule返回参数结构体
*/
export interface ActivateRuleResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* UpdateRule请求参数结构体
*/
export interface UpdateRuleRequest {
/**
* 规则Id
*/
RuleId: string
/**
* 名称
*/
Name?: string
/**
* 描述
*/
Description?: string
/**
* 查询
*/
Query?: RuleQuery
/**
* 转发动作列表
*/
Actions?: Array<Action>
/**
* 数据类型(0:文本,1:二进制)
*/
DataType?: number
}
/**
* 设备签名
*/
export interface DeviceSignature {
/**
* 设备名称
*/
DeviceName: string
/**
* 设备签名
*/
DeviceSignature: string
}
/**
* AppGetDevices请求参数结构体
*/
export interface AppGetDevicesRequest {
/**
* 访问Token
*/
AccessToken: string
}
/**
* AppGetDeviceData返回参数结构体
*/
export interface AppGetDeviceDataResponse {
/**
* 设备数据。
*/
DeviceData?: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* GetTopic返回参数结构体
*/
export interface GetTopicResponse {
/**
* Topic信息
*/
Topic?: Topic
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DeactivateRule返回参数结构体
*/
export interface DeactivateRuleResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* IssueDeviceControl请求参数结构体
*/
export interface IssueDeviceControlRequest {
/**
* 产品Id
*/
ProductId: string
/**
* 设备名称
*/
DeviceName: string
/**
* 控制数据(json)
*/
ControlData: string
/**
* 是否发送metadata字段
*/
Metadata?: boolean
}
/**
* GetDeviceStatistics请求参数结构体
*/
export interface GetDeviceStatisticsRequest {
/**
* 产品Id列表
*/
Products?: Array<string>
/**
* 开始日期
*/
StartDate?: string
/**
* 结束日期
*/
EndDate?: string
}
/**
* ResetDevice返回参数结构体
*/
export interface ResetDeviceResponse {
/**
* 设备信息
*/
Device?: Device
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* GetDeviceLog返回参数结构体
*/
export interface GetDeviceLogResponse {
/**
* 设备日志
*/
DeviceLog?: Array<DeviceLogEntry>
/**
* 查询游标
*/
ScrollId?: string
/**
* 游标超时
*/
ScrollTimeout?: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* AddRule请求参数结构体
*/
export interface AddRuleRequest {
/**
* 名称
*/
Name: string
/**
* 描述
*/
Description: string
/**
* 查询
*/
Query?: RuleQuery
/**
* 转发动作列表
*/
Actions?: Array<Action>
/**
* 数据类型(0:文本,1:二进制)
*/
DataType?: number
}
/**
* ResetDevice请求参数结构体
*/
export interface ResetDeviceRequest {
/**
* 产品Id
*/
ProductId: string
/**
* 设备名称
*/
DeviceName: string
}
/**
* 转发到第三方http(s)服务
*/
export interface ServiceAction {
/**
* 服务url地址
*/
Url: string
}
/**
* 数据模版
*/
export interface DataTemplate {
/**
* 数字类型
注意:此字段可能返回 null,表示取不到有效值。
*/
Number?: NumberData
/**
* 字符串类型
注意:此字段可能返回 null,表示取不到有效值。
*/
String?: StringData
/**
* 枚举类型
注意:此字段可能返回 null,表示取不到有效值。
*/
Enum?: EnumData
/**
* 布尔类型
注意:此字段可能返回 null,表示取不到有效值。
*/
Bool?: BoolData
}
/**
* DeleteTopic请求参数结构体
*/
export interface DeleteTopicRequest {
/**
* TopicId
*/
TopicId: string
/**
* 产品Id
*/
ProductId: string
}
/**
* AddProduct返回参数结构体
*/
export interface AddProductResponse {
/**
* 产品信息
*/
Product?: Product
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* UpdateProduct返回参数结构体
*/
export interface UpdateProductResponse {
/**
* 更新后的产品信息
*/
Product?: Product
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 数据历史条目
*/
export interface DataHistoryEntry {
/**
* 日志id
*/
Id: string
/**
* 时间戳
*/
Timestamp: number
/**
* 设备名称
*/
DeviceName: string
/**
* 数据
*/
Data: string
}
/**
* AppGetDevice返回参数结构体
*/
export interface AppGetDeviceResponse {
/**
* 绑定设备详情
*/
AppDevice?: AppDeviceDetail
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* UpdateRule返回参数结构体
*/
export interface UpdateRuleResponse {
/**
* 规则
*/
Rule?: Rule
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 绑定设备详情
*/
export interface AppDeviceDetail {
/**
* 设备Id
*/
DeviceId: string
/**
* 所属产品Id
*/
ProductId: string
/**
* 设备名称
*/
DeviceName: string
/**
* 别名
*/
AliasName: string
/**
* 地区
*/
Region: string
/**
* 创建时间
*/
CreateTime: string
/**
* 更新时间
*/
UpdateTime: string
/**
* 设备信息(json)
*/
DeviceInfo: string
/**
* 数据模板
*/
DataTemplate: Array<DataTemplate>
}
/**
* GetDeviceStatistics返回参数结构体
*/
export interface GetDeviceStatisticsResponse {
/**
* 统计数据
*/
DeviceStatistics?: Array<DeviceStatData>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* UnassociateSubDeviceFromGatewayProduct返回参数结构体
*/
export interface UnassociateSubDeviceFromGatewayProductResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* Topic
*/
export interface Topic {
/**
* TopicId
*/
TopicId: string
/**
* Topic名称
*/
TopicName: string
/**
* 产品Id
*/
ProductId: string
/**
* 消息最大生命周期
*/
MsgLife: number
/**
* 消息最大大小
*/
MsgSize: number
/**
* 消息最大数量
*/
MsgCount: number
/**
* 已删除
*/
Deleted: number
/**
* Topic完整路径
*/
Path: string
/**
* 创建时间
*/
CreateTime: string
/**
* 更新时间
*/
UpdateTime: string
}
/**
* AssociateSubDeviceToGatewayProduct返回参数结构体
*/
export interface AssociateSubDeviceToGatewayProductResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* GetProduct请求参数结构体
*/
export interface GetProductRequest {
/**
* 产品Id
*/
ProductId: string
}
/**
* AppGetToken请求参数结构体
*/
export interface AppGetTokenRequest {
/**
* 用户名
*/
UserName: string
/**
* 密码
*/
Password: string
/**
* TTL
*/
Expire?: number
}
/**
* GetRule请求参数结构体
*/
export interface GetRuleRequest {
/**
* 规则Id
*/
RuleId: string
}
/**
* DeleteProduct请求参数结构体
*/
export interface DeleteProductRequest {
/**
* 产品Id
*/
ProductId: string
}
/**
* AppGetUser请求参数结构体
*/
export interface AppGetUserRequest {
/**
* 访问Token
*/
AccessToken: string
}
/**
* GetProducts返回参数结构体
*/
export interface GetProductsResponse {
/**
* Product列表
*/
Products?: Array<ProductEntry>
/**
* Product总数
*/
Total?: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* AppGetDevice请求参数结构体
*/
export interface AppGetDeviceRequest {
/**
* 访问Token
*/
AccessToken: string
/**
* 产品Id
*/
ProductId: string
/**
* 设备名称
*/
DeviceName: string
}
/**
* GetDataHistory请求参数结构体
*/
export interface GetDataHistoryRequest {
/**
* 产品Id
*/
ProductId: string
/**
* 设备名称列表,允许最多一次100台
*/
DeviceNames: Array<string>
/**
* 查询开始时间
*/
StartTime: string
/**
* 查询结束时间
*/
EndTime: string
/**
* 查询数据量
*/
Size?: number
/**
* 时间排序(desc/asc)
*/
Order?: string
/**
* 查询游标
*/
ScrollId?: string
}
/**
* AddTopic返回参数结构体
*/
export interface AddTopicResponse {
/**
* Topic信息
*/
Topic?: Topic
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* AddProduct请求参数结构体
*/
export interface AddProductRequest {
/**
* 产品名称,同一区域产品名称需唯一,支持中文、英文字母、中划线和下划线,长度不超过31个字符,中文占两个字符
*/
Name: string
/**
* 产品描述
*/
Description: string
/**
* 数据模版
*/
DataTemplate?: Array<DataTemplate>
/**
* 产品版本(native表示基础版,template表示高级版,默认值为template)
*/
DataProtocol?: string
/**
* 设备认证方式(1:动态令牌,2:签名直连鉴权)
*/
AuthType?: number
/**
* 通信方式(other/wifi/cellular/nb-iot)
*/
CommProtocol?: string
/**
* 产品的设备类型(device: 直连设备;sub_device:子设备;gateway:网关设备)
*/
DeviceType?: string
}
/**
* 产品条目
*/
export interface ProductEntry {
/**
* 产品Id
*/
ProductId: string
/**
* 产品Key
*/
ProductKey: string
/**
* AppId
*/
AppId: number
/**
* 产品名称
*/
Name: string
/**
* 产品描述
*/
Description: string
/**
* 连接域名
*/
Domain: string
/**
* 鉴权类型(0:直连,1:Token)
*/
AuthType: number
/**
* 数据协议(native/template)
*/
DataProtocol: string
/**
* 删除(0未删除)
*/
Deleted: number
/**
* 备注
*/
Message: string
/**
* 创建时间
*/
CreateTime: string
/**
* 通信方式
*/
CommProtocol: string
/**
* 地域
*/
Region: string
/**
* 设备类型
*/
DeviceType: string
}
/**
* GetRules返回参数结构体
*/
export interface GetRulesResponse {
/**
* 规则列表
*/
Rules?: Array<Rule>
/**
* 规则总数
*/
Total?: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DeleteDevice请求参数结构体
*/
export interface DeleteDeviceRequest {
/**
* 产品Id
*/
ProductId: string
/**
* 设备名称
*/
DeviceName: string
}
/**
* AssociateSubDeviceToGatewayProduct请求参数结构体
*/
export interface AssociateSubDeviceToGatewayProductRequest {
/**
* 子设备产品Id
*/
SubDeviceProductId: string
/**
* 网关产品Id
*/
GatewayProductId: string
}
/**
* GetDeviceSignatures返回参数结构体
*/
export interface GetDeviceSignaturesResponse {
/**
* 设备绑定签名列表
*/
DeviceSignatures?: Array<DeviceSignature>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 查询
*/
export interface RuleQuery {
/**
* 字段
*/
Field: string
/**
* 过滤规则
*/
Condition: string
/**
* Topic
注意:此字段可能返回 null,表示取不到有效值。
*/
Topic?: string
/**
* 产品Id
注意:此字段可能返回 null,表示取不到有效值。
*/
ProductId?: string
}
/**
* 应用用户
*/
export interface AppUser {
/**
* 应用Id
*/
ApplicationId: string
/**
* 用户名
*/
UserName: string
/**
* 昵称
*/
NickName: string
/**
* 创建时间
*/
CreateTime: string
/**
* 修改时间
*/
UpdateTime: string
}
/**
* 布尔类型数据
*/
export interface BoolData {
/**
* 名称
*/
Name: string
/**
* 描述
*/
Desc: string
/**
* 读写模式
*/
Mode: string
/**
* 取值列表
*/
Range: Array<boolean>
}
/**
* PublishMsg请求参数结构体
*/
export interface PublishMsgRequest {
/**
* Topic
*/
Topic: string
/**
* 消息内容
*/
Message: string
/**
* Qos(目前QoS支持0与1)
*/
Qos?: number
}
/**
* GetProducts请求参数结构体
*/
export interface GetProductsRequest {
/**
* 偏移
*/
Offset?: number
/**
* 长度
*/
Length?: number
}
/**
* AddTopic请求参数结构体
*/
export interface AddTopicRequest {
/**
* 产品Id
*/
ProductId: string
/**
* Topic名称
*/
TopicName: string
}
/**
* AppGetDeviceStatuses请求参数结构体
*/
export interface AppGetDeviceStatusesRequest {
/**
* 访问Token
*/
AccessToken: string
/**
* 设备Id列表(单次限制1000个设备)
*/
DeviceIds: Array<string>
}
/**
* 设备日志条目
*/
export interface DeviceLogEntry {
/**
* 日志id
*/
Id: string
/**
* 日志内容
*/
Msg: string
/**
* 状态码
*/
Code: string
/**
* 时间戳
*/
Timestamp: number
/**
* 设备名称
*/
DeviceName: string
/**
* 设备动作
*/
Method: string
}
/**
* GetDebugLog请求参数结构体
*/
export interface GetDebugLogRequest {
/**
* 产品Id
*/
ProductId: string
/**
* 设备名称列表,最大支持100台
*/
DeviceNames: Array<string>
/**
* 查询开始时间
*/
StartTime: string
/**
* 查询结束时间
*/
EndTime: string
/**
* 查询数据量
*/
Size?: number
/**
* 时间排序(desc/asc)
*/
Order?: string
/**
* 查询游标
*/
ScrollId?: string
/**
* 日志类型(shadow/action/mqtt)
*/
Type?: string
}
/**
* GetDevice请求参数结构体
*/
export interface GetDeviceRequest {
/**
* 产品Id
*/
ProductId: string
/**
* 设备名称
*/
DeviceName: string
}
/**
* GetDeviceData请求参数结构体
*/
export interface GetDeviceDataRequest {
/**
* 产品Id
*/
ProductId: string
/**
* 设备名称
*/
DeviceName: string
}
/**
* DeactivateRule请求参数结构体
*/
export interface DeactivateRuleRequest {
/**
* 规则Id
*/
RuleId: string
}
/**
* GetTopic请求参数结构体
*/
export interface GetTopicRequest {
/**
* TopicId
*/
TopicId: string
/**
* 产品Id
*/
ProductId: string
}
/**
* GetDevices返回参数结构体
*/
export interface GetDevicesResponse {
/**
* 设备列表
*/
Devices?: Array<DeviceEntry>
/**
* 设备总数
*/
Total?: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 数字类型数据
*/
export interface NumberData {
/**
* 名称
*/
Name: string
/**
* 描述
*/
Desc: string
/**
* 读写模式
*/
Mode: string
/**
* 取值范围
*/
Range: Array<number>
}
/**
* GetDevices请求参数结构体
*/
export interface GetDevicesRequest {
/**
* 产品Id
*/
ProductId: string
/**
* 偏移
*/
Offset?: number
/**
* 长度
*/
Length?: number
/**
* 关键字查询
*/
Keyword?: string
}
/**
* AppGetToken返回参数结构体
*/
export interface AppGetTokenResponse {
/**
* 访问Token
*/
AccessToken?: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* GetProduct返回参数结构体
*/
export interface GetProductResponse {
/**
* 产品信息
*/
Product?: Product
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* AppAddUser请求参数结构体
*/
export interface AppAddUserRequest {
/**
* 用户名
*/
UserName: string
/**
* 密码
*/
Password: string
}
/**
* AddRule返回参数结构体
*/
export interface AddRuleResponse {
/**
* 规则
*/
Rule?: Rule
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* AppDeleteDevice返回参数结构体
*/
export interface AppDeleteDeviceResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* AppIssueDeviceControl请求参数结构体
*/
export interface AppIssueDeviceControlRequest {
/**
* 访问Token
*/
AccessToken: string
/**
* 产品Id
*/
ProductId: string
/**
* 设备名称
*/
DeviceName: string
/**
* 控制数据(json)
*/
ControlData: string
/**
* 是否发送metadata字段
*/
Metadata?: boolean
}
/**
* 设备状态
*/
export interface DeviceStatus {
/**
* 设备名称
*/
DeviceName: string
/**
* 设备状态(inactive, online, offline)
*/
Status: string
/**
* 首次上线时间
注意:此字段可能返回 null,表示取不到有效值。
*/
FirstOnline: string
/**
* 最后上线时间
注意:此字段可能返回 null,表示取不到有效值。
*/
LastOnline: string
/**
* 上线次数
*/
OnlineTimes: number
}
/**
* DeleteProduct返回参数结构体
*/
export interface DeleteProductResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* AppGetUser返回参数结构体
*/
export interface AppGetUserResponse {
/**
* 用户信息
*/
AppUser?: AppUser
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* AppUpdateUser请求参数结构体
*/
export interface AppUpdateUserRequest {
/**
* 访问Token
*/
AccessToken: string
/**
* 昵称
*/
NickName?: string
}
/**
* GetDebugLog返回参数结构体
*/
export interface GetDebugLogResponse {
/**
* 调试日志
*/
DebugLog?: Array<DebugLogEntry>
/**
* 查询游标
*/
ScrollId?: string
/**
* 游标超时
*/
ScrollTimeout?: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* AppUpdateUser返回参数结构体
*/
export interface AppUpdateUserResponse {
/**
* 应用用户
*/
AppUser?: AppUser
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 设备
*/
export interface Device {
/**
* 产品Id
*/
ProductId: string
/**
* 设备名称
*/
DeviceName: string
/**
* 设备密钥
*/
DeviceSecret: string
/**
* 更新时间
*/
UpdateTime: string
/**
* 创建时间
*/
CreateTime: string
/**
* 设备信息(json)
*/
DeviceInfo: string
}
/**
* GetRules请求参数结构体
*/
export interface GetRulesRequest {
/**
* 偏移
*/
Offset?: number
/**
* 长度
*/
Length?: number
}
/**
* 规则
*/
export interface Rule {
/**
* 规则Id
*/
RuleId: string
/**
* AppId
*/
AppId: number
/**
* 名称
*/
Name: string
/**
* 描述
*/
Description: string
/**
* 查询
*/
Query: RuleQuery
/**
* 转发
*/
Actions: Array<Action>
/**
* 已启动
*/
Active: number
/**
* 已删除
*/
Deleted: number
/**
* 创建时间
*/
CreateTime: string
/**
* 更新时间
*/
UpdateTime: string
/**
* 消息顺序
*/
MsgOrder: number
/**
* 数据类型(0:文本,1:二进制)
*/
DataType: number
}
/**
* IssueDeviceControl返回参数结构体
*/
export interface IssueDeviceControlResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* GetDataHistory返回参数结构体
*/
export interface GetDataHistoryResponse {
/**
* 数据历史
*/
DataHistory?: Array<DataHistoryEntry>
/**
* 查询游标
*/
ScrollId?: string
/**
* 查询游标超时
*/
ScrollTimeout?: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 规则引擎转发动作
*/
export interface Action {
/**
* 转发至topic
注意:此字段可能返回 null,表示取不到有效值。
*/
Topic?: TopicAction
/**
* 转发至第三发
注意:此字段可能返回 null,表示取不到有效值。
*/
Service?: ServiceAction
/**
* 转发至第三发Ckafka
注意:此字段可能返回 null,表示取不到有效值。
*/
Ckafka?: CkafkaAction
}
/**
* PublishMsg返回参数结构体
*/
export interface PublishMsgResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* AppGetDevices返回参数结构体
*/
export interface AppGetDevicesResponse {
/**
* 绑定设备列表
*/
Devices?: Array<AppDevice>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 转发至Ckafka
*/
export interface CkafkaAction {
/**
* 实例Id
*/
InstanceId: string
/**
* topic名称
*/
TopicName: string
/**
* 地域
*/
Region: string
}
/**
* AddDevice请求参数结构体
*/
export interface AddDeviceRequest {
/**
* 产品Id
*/
ProductId: string
/**
* 设备名称,唯一标识某产品下的一个设备
*/
DeviceName: string
}
/**
* UpdateProduct请求参数结构体
*/
export interface UpdateProductRequest {
/**
* 产品Id
*/
ProductId: string
/**
* 产品名称
*/
Name?: string
/**
* 产品描述
*/
Description?: string
/**
* 数据模版
*/
DataTemplate?: Array<DataTemplate>
}
/**
* DeleteRule返回参数结构体
*/
export interface DeleteRuleResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* GetDeviceSignatures请求参数结构体
*/
export interface GetDeviceSignaturesRequest {
/**
* 产品ID
*/
ProductId: string
/**
* 设备名称列表(单次限制1000个设备)
*/
DeviceNames: Array<string>
/**
* 过期时间
*/
Expire?: number
}
/**
* GetRule返回参数结构体
*/
export interface GetRuleResponse {
/**
* 规则
*/
Rule?: Rule
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* AppUpdateDevice返回参数结构体
*/
export interface AppUpdateDeviceResponse {
/**
* 设备信息
*/
AppDevice?: AppDevice
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 产品
*/
export interface Product {
/**
* 产品Id
*/
ProductId: string
/**
* 产品Key
*/
ProductKey: string
/**
* AppId
*/
AppId: number
/**
* 产品名称
*/
Name: string
/**
* 产品描述
*/
Description: string
/**
* 连接域名
*/
Domain: string
/**
* 产品规格
*/
Standard: number
/**
* 鉴权类型(0:直连,1:Token)
*/
AuthType: number
/**
* 删除(0未删除)
*/
Deleted: number
/**
* 备注
*/
Message: string
/**
* 创建时间
*/
CreateTime: string
/**
* 更新时间
*/
UpdateTime: string
/**
* 数据模版
*/
DataTemplate: Array<DataTemplate>
/**
* 数据协议(native/template)
*/
DataProtocol: string
/**
* 直连用户名
*/
Username: string
/**
* 直连密码
*/
Password: string
/**
* 通信方式
*/
CommProtocol: string
/**
* qps
*/
Qps: number
/**
* 地域
*/
Region: string
/**
* 产品的设备类型
*/
DeviceType: string
/**
* 关联的产品列表
*/
AssociatedProducts: Array<string>
}
/**
* 设备日志条目
*/
export interface DebugLogEntry {
/**
* 日志id
*/
Id: string
/**
* 行为(事件)
*/
Event: string
/**
* shadow/action/mqtt, 分别表示:影子/规则引擎/上下线日志
*/
LogType: string
/**
* 时间戳
*/
Timestamp: number
/**
* success/fail
*/
Result: string
/**
* 日志详细内容
*/
Data: string
/**
* 数据来源topic
*/
Topic: string
/**
* 设备名称
*/
DeviceName: string
}
/**
* GetDeviceStatuses请求参数结构体
*/
export interface GetDeviceStatusesRequest {
/**
* 产品ID
*/
ProductId: string
/**
* 设备名称列表(单次限制1000个设备)
*/
DeviceNames: Array<string>
}
/**
* GetDeviceStatuses返回参数结构体
*/
export interface GetDeviceStatusesResponse {
/**
* 设备状态列表
*/
DeviceStatuses?: Array<DeviceStatus>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* UnassociateSubDeviceFromGatewayProduct请求参数结构体
*/
export interface UnassociateSubDeviceFromGatewayProductRequest {
/**
* 子设备产品Id
*/
SubDeviceProductId: string
/**
* 网关设备产品Id
*/
GatewayProductId: string
}
/**
* AppDeleteDevice请求参数结构体
*/
export interface AppDeleteDeviceRequest {
/**
* 访问Token
*/
AccessToken: string
/**
* 产品Id
*/
ProductId: string
/**
* 设备名称
*/
DeviceName: string
}
/**
* 数字类型数据
*/
export interface StringData {
/**
* 名称
*/
Name: string
/**
* 描述
*/
Desc: string
/**
* 读写模式
*/
Mode: string
/**
* 长度范围
*/
Range: Array<number>
}
/**
* AppGetDeviceStatuses返回参数结构体
*/
export interface AppGetDeviceStatusesResponse {
/**
* 设备状态
*/
DeviceStatuses?: Array<DeviceStatus>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* GetTopics返回参数结构体
*/
export interface GetTopicsResponse {
/**
* Topic列表
*/
Topics?: Array<Topic>
/**
* Topic总数
*/
Total?: number
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* AppGetDeviceData请求参数结构体
*/
export interface AppGetDeviceDataRequest {
/**
* 访问Token
*/
AccessToken: string
/**
* 产品Id
*/
ProductId: string
/**
* 设备名称
*/
DeviceName: string
}
/**
* AppAddUser返回参数结构体
*/
export interface AppAddUserResponse {
/**
* 应用用户
*/
AppUser?: AppUser
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 设备条目
*/
export interface DeviceEntry {
/**
* 产品Id
*/
ProductId: string
/**
* 设备名称
*/
DeviceName: string
/**
* 设备密钥
*/
DeviceSecret: string
/**
* 创建时间
*/
CreateTime: string
}
/**
* GetDeviceLog请求参数结构体
*/
export interface GetDeviceLogRequest {
/**
* 产品Id
*/
ProductId: string
/**
* 设备名称列表,最大支持100台
*/
DeviceNames: Array<string>
/**
* 查询开始时间
*/
StartTime: string
/**
* 查询结束时间
*/
EndTime: string
/**
* 查询数据量
*/
Size?: number
/**
* 时间排序(desc/asc)
*/
Order?: string
/**
* 查询游标
*/
ScrollId?: string
/**
* 日志类型(comm/status)
*/
Type?: string
}
/**
* AddDevice返回参数结构体
*/
export interface AddDeviceResponse {
/**
* 设备信息
*/
Device?: Device
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ActivateRule请求参数结构体
*/
export interface ActivateRuleRequest {
/**
* 规则Id
*/
RuleId: string
}
/**
* AppResetPassword请求参数结构体
*/
export interface AppResetPasswordRequest {
/**
* 访问Token
*/
AccessToken: string
/**
* 旧密码
*/
OldPassword: string
/**
* 新密码
*/
NewPassword: string
}
/**
* DeleteTopic返回参数结构体
*/
export interface DeleteTopicResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 绑定设备
*/
export interface AppDevice {
/**
* 设备Id
*/
DeviceId: string
/**
* 所属产品Id
*/
ProductId: string
/**
* 设备名称
*/
DeviceName: string
/**
* 别名
*/
AliasName: string
/**
* 地区
*/
Region: string
/**
* 创建时间
*/
CreateTime: string
/**
* 更新时间
*/
UpdateTime: string
}
/**
* GetTopics请求参数结构体
*/
export interface GetTopicsRequest {
/**
* 产品Id
*/
ProductId: string
/**
* 偏移
*/
Offset?: number
/**
* 长度
*/
Length?: number
}
/**
* 设备统计数据
*/
export interface DeviceStatData {
/**
* 时间点
*/
Datetime: string
/**
* 在线设备数
*/
DeviceOnline: number
/**
* 激活设备数
*/
DeviceActive: number
/**
* 设备总数
*/
DeviceTotal: number
}
/**
* 枚举类型数据
*/
export interface EnumData {
/**
* 名称
*/
Name: string
/**
* 描述
*/
Desc: string
/**
* 读写模式
*/
Mode: string
/**
* 取值列表
*/
Range: Array<string>
}
/**
* DeleteDevice返回参数结构体
*/
export interface DeleteDeviceResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* AppSecureAddDevice返回参数结构体
*/
export interface AppSecureAddDeviceResponse {
/**
* 绑定设备信息
*/
AppDevice?: AppDevice
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* AppSecureAddDevice请求参数结构体
*/
export interface AppSecureAddDeviceRequest {
/**
* 访问Token
*/
AccessToken: string
/**
* 设备签名
*/
DeviceSignature: string
}
/**
* AppIssueDeviceControl返回参数结构体
*/
export interface AppIssueDeviceControlResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 转发到topic动作
*/
export interface TopicAction {
/**
* 目标topic
*/
Topic: string
} | the_stack |
import { baseComponent, baseComponentEventMap, baseComponentSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..';
export interface ojButton<SP extends ojButtonSettableProperties = ojButtonSettableProperties> extends baseComponent<SP> {
chroming: 'full' | 'half' | 'outlined';
disabled: boolean;
display: 'all' | 'icons';
onChromingChanged: ((event: JetElementCustomEvent<ojButton<SP>["chroming"]>) => any) | null;
onDisabledChanged: ((event: JetElementCustomEvent<ojButton<SP>["disabled"]>) => any) | null;
onDisplayChanged: ((event: JetElementCustomEvent<ojButton<SP>["display"]>) => any) | null;
onOjAction: ((event: ojButton.ojAction) => any) | null;
addEventListener<T extends keyof ojButtonEventMap<SP>>(type: T, listener: (this: HTMLElement, ev: ojButtonEventMap<SP>[T]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
getProperty<T extends keyof ojButtonSettableProperties>(property: T): ojButton<SP>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojButtonSettableProperties>(property: T, value: ojButtonSettableProperties[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojButtonSettableProperties>): void;
setProperties(properties: ojButtonSettablePropertiesLenient): void;
}
export namespace ojButton {
interface ojAction extends CustomEvent<{
[propName: string]: any;
}> {
}
}
export interface ojButtonEventMap<SP extends ojButtonSettableProperties = ojButtonSettableProperties> extends baseComponentEventMap<SP> {
'ojAction': ojButton.ojAction;
'chromingChanged': JetElementCustomEvent<ojButton<SP>["chroming"]>;
'disabledChanged': JetElementCustomEvent<ojButton<SP>["disabled"]>;
'displayChanged': JetElementCustomEvent<ojButton<SP>["display"]>;
}
export interface ojButtonSettableProperties extends baseComponentSettableProperties {
chroming: 'full' | 'half' | 'outlined';
disabled: boolean;
display: 'all' | 'icons';
}
export interface ojButtonSettablePropertiesLenient extends Partial<ojButtonSettableProperties> {
[key: string]: any;
}
export interface ojButtonset<SP extends ojButtonsetSettableProperties = ojButtonsetSettableProperties> extends baseComponent<SP> {
addEventListener<T extends keyof ojButtonsetEventMap<SP>>(type: T, listener: (this: HTMLElement, ev: ojButtonsetEventMap<SP>[T]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
getProperty<T extends keyof ojButtonsetSettableProperties>(property: T): ojButtonset<SP>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojButtonsetSettableProperties>(property: T, value: ojButtonsetSettableProperties[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojButtonsetSettableProperties>): void;
setProperties(properties: ojButtonsetSettablePropertiesLenient): void;
}
// These interfaces are empty but required to keep the event chain intact. Avoid lint-rule
// tslint:disable-next-line no-empty-interface
export interface ojButtonsetEventMap<SP extends ojButtonsetSettableProperties = ojButtonsetSettableProperties> extends baseComponentEventMap<SP> {
}
// These interfaces are empty but required to keep the component chain intact. Avoid lint-rule
// tslint:disable-next-line no-empty-interface
export interface ojButtonsetSettableProperties extends baseComponentSettableProperties {
}
export interface ojButtonsetSettablePropertiesLenient extends Partial<ojButtonsetSettableProperties> {
[key: string]: any;
}
export interface ojButtonsetMany extends ojButtonset<ojButtonsetManySettableProperties> {
chroming: 'full' | 'half' | 'outlined';
disabled: boolean;
display: 'all' | 'icons';
focusManagement: 'oneTabstop' | 'none';
value: any[] | null;
onChromingChanged: ((event: JetElementCustomEvent<ojButtonsetMany["chroming"]>) => any) | null;
onDisabledChanged: ((event: JetElementCustomEvent<ojButtonsetMany["disabled"]>) => any) | null;
onDisplayChanged: ((event: JetElementCustomEvent<ojButtonsetMany["display"]>) => any) | null;
onFocusManagementChanged: ((event: JetElementCustomEvent<ojButtonsetMany["focusManagement"]>) => any) | null;
onValueChanged: ((event: JetElementCustomEvent<ojButtonsetMany["value"]>) => any) | null;
addEventListener<T extends keyof ojButtonsetManyEventMap>(type: T, listener: (this: HTMLElement, ev: ojButtonsetManyEventMap[T]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
getProperty<T extends keyof ojButtonsetManySettableProperties>(property: T): ojButtonsetMany[T];
getProperty(property: string): any;
setProperty<T extends keyof ojButtonsetManySettableProperties>(property: T, value: ojButtonsetManySettableProperties[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojButtonsetManySettableProperties>): void;
setProperties(properties: ojButtonsetManySettablePropertiesLenient): void;
}
export interface ojButtonsetManyEventMap extends ojButtonsetEventMap<ojButtonsetManySettableProperties> {
'chromingChanged': JetElementCustomEvent<ojButtonsetMany["chroming"]>;
'disabledChanged': JetElementCustomEvent<ojButtonsetMany["disabled"]>;
'displayChanged': JetElementCustomEvent<ojButtonsetMany["display"]>;
'focusManagementChanged': JetElementCustomEvent<ojButtonsetMany["focusManagement"]>;
'valueChanged': JetElementCustomEvent<ojButtonsetMany["value"]>;
}
export interface ojButtonsetManySettableProperties extends ojButtonsetSettableProperties {
chroming: 'full' | 'half' | 'outlined';
disabled: boolean;
display: 'all' | 'icons';
focusManagement: 'oneTabstop' | 'none';
value: any[] | null;
}
export interface ojButtonsetManySettablePropertiesLenient extends Partial<ojButtonsetManySettableProperties> {
[key: string]: any;
}
export interface ojButtonsetOne extends ojButtonset<ojButtonsetOneSettableProperties> {
chroming: 'full' | 'half' | 'outlined';
disabled: boolean;
display: 'all' | 'icons';
focusManagement: 'oneTabstop' | 'none';
value: any;
onChromingChanged: ((event: JetElementCustomEvent<ojButtonsetOne["chroming"]>) => any) | null;
onDisabledChanged: ((event: JetElementCustomEvent<ojButtonsetOne["disabled"]>) => any) | null;
onDisplayChanged: ((event: JetElementCustomEvent<ojButtonsetOne["display"]>) => any) | null;
onFocusManagementChanged: ((event: JetElementCustomEvent<ojButtonsetOne["focusManagement"]>) => any) | null;
onValueChanged: ((event: JetElementCustomEvent<ojButtonsetOne["value"]>) => any) | null;
addEventListener<T extends keyof ojButtonsetOneEventMap>(type: T, listener: (this: HTMLElement, ev: ojButtonsetOneEventMap[T]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
getProperty<T extends keyof ojButtonsetOneSettableProperties>(property: T): ojButtonsetOne[T];
getProperty(property: string): any;
setProperty<T extends keyof ojButtonsetOneSettableProperties>(property: T, value: ojButtonsetOneSettableProperties[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojButtonsetOneSettableProperties>): void;
setProperties(properties: ojButtonsetOneSettablePropertiesLenient): void;
}
export interface ojButtonsetOneEventMap extends ojButtonsetEventMap<ojButtonsetOneSettableProperties> {
'chromingChanged': JetElementCustomEvent<ojButtonsetOne["chroming"]>;
'disabledChanged': JetElementCustomEvent<ojButtonsetOne["disabled"]>;
'displayChanged': JetElementCustomEvent<ojButtonsetOne["display"]>;
'focusManagementChanged': JetElementCustomEvent<ojButtonsetOne["focusManagement"]>;
'valueChanged': JetElementCustomEvent<ojButtonsetOne["value"]>;
}
export interface ojButtonsetOneSettableProperties extends ojButtonsetSettableProperties {
chroming: 'full' | 'half' | 'outlined';
disabled: boolean;
display: 'all' | 'icons';
focusManagement: 'oneTabstop' | 'none';
value: any;
}
export interface ojButtonsetOneSettablePropertiesLenient extends Partial<ojButtonsetOneSettableProperties> {
[key: string]: any;
}
export interface ojMenuButton extends ojButton<ojMenuButtonSettableProperties> {
chroming: 'full' | 'half' | 'outlined';
disabled: boolean;
display: 'all' | 'icons';
onChromingChanged: ((event: JetElementCustomEvent<ojMenuButton["chroming"]>) => any) | null;
onDisabledChanged: ((event: JetElementCustomEvent<ojMenuButton["disabled"]>) => any) | null;
onDisplayChanged: ((event: JetElementCustomEvent<ojMenuButton["display"]>) => any) | null;
onOjAction: ((event: ojMenuButton.ojAction) => any) | null;
addEventListener<T extends keyof ojMenuButtonEventMap>(type: T, listener: (this: HTMLElement, ev: ojMenuButtonEventMap[T]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
getProperty<T extends keyof ojMenuButtonSettableProperties>(property: T): ojMenuButton[T];
getProperty(property: string): any;
setProperty<T extends keyof ojMenuButtonSettableProperties>(property: T, value: ojMenuButtonSettableProperties[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojMenuButtonSettableProperties>): void;
setProperties(properties: ojMenuButtonSettablePropertiesLenient): void;
}
export namespace ojMenuButton {
interface ojAction extends CustomEvent<{
[propName: string]: any;
}> {
}
}
export interface ojMenuButtonEventMap extends ojButtonEventMap<ojMenuButtonSettableProperties> {
'ojAction': ojMenuButton.ojAction;
'chromingChanged': JetElementCustomEvent<ojMenuButton["chroming"]>;
'disabledChanged': JetElementCustomEvent<ojMenuButton["disabled"]>;
'displayChanged': JetElementCustomEvent<ojMenuButton["display"]>;
}
export interface ojMenuButtonSettableProperties extends ojButtonSettableProperties {
chroming: 'full' | 'half' | 'outlined';
disabled: boolean;
display: 'all' | 'icons';
}
export interface ojMenuButtonSettablePropertiesLenient extends Partial<ojMenuButtonSettableProperties> {
[key: string]: any;
} | the_stack |
import 'mocha'
import { expect } from 'chai'
import { spy } from 'sinon'
import * as path from 'path'
const proxyquire = require('proxyquire').noPreserveCache()
const utils = require('../utils/utils')
const jsYamlLoader = require('./js-yaml-loader')
function setUpStub (fileExists?, fileContent?) {
const fileMock: any = {}
if (typeof fileExists !== 'undefined') {
fileMock.fileExistsSync = function () {
return !!fileExists
}
}
const fsMock: any = {}
if (typeof fileContent !== 'undefined') {
fsMock.readFileSync = function () {
return fileContent
}
}
const configLoader = proxyquire('./js-yaml-loader', {
'./file-utils': fileMock,
'fs': fsMock
})
spy(fileMock, 'fileExistsSync')
spy(fsMock, 'readFileSync')
return {
configLoader,
fileMock
}
}
describe.skip('js-yaml-loader', () => {
afterEach(() => {
global.deepstreamConfDir = null
global.deepstreamLibDir = null
global.deepstreamCLI = null
})
describe('js-yaml-loader loads and parses json files', () => {
const jsonLoader = {
load: jsYamlLoader.readAndParseFile
}
it('initialises the loader', () => {
expect(typeof jsonLoader.load).to.equal('function')
})
it('errors if invoked with an invalid path', (done) => {
jsonLoader.load(null, (err, result) => {
expect(err.toString()).to.contain('path')
expect(result).to.equal(undefined)
done()
})
})
it('successfully loads and parses a valid JSON file', (done) => {
jsonLoader.load('./src/test/config/basic-valid-json.json', (err, result) => {
expect(err).to.equal(null)
expect(result).to.deep.equal({ pet: 'pug' })
done()
})
})
it('errors when trying to load non existant file', (done) => {
jsonLoader.load('./src/test/config/does-not-exist.json', (err, result) => {
expect(err.toString()).to.contain('no such file or directory')
expect(result).to.equal(undefined)
done()
})
})
})
describe('js-yaml-loader', () => {
it('loads the default yml file', () => {
const loader = jsYamlLoader
const result = loader.loadConfig()
let defaultYamlConfig = result.config
expect(result.file).to.deep.equal(path.join('conf', 'config.yml'))
// TODO
// expect(defaultYamlConfig.serverName).to.have.type('string')
defaultYamlConfig = utils.merge(defaultYamlConfig, {
permission: { type: 'none', options: null },
authentication: null,
plugins: null,
serverName: null,
logger: null
})
expect(defaultYamlConfig).not.to.equal(null)
})
it('tries to load yaml, js and json file and then default', () => {
const stub = setUpStub(false)
expect(() => {
stub.configLoader.loadConfig()
}).to.throw()
expect(stub.fileMock.fileExistsSync).to.have.callCount(28)
expect(stub.fileMock.fileExistsSync).to.have.been.calledWith(path.join('conf', 'config.js'))
expect(stub.fileMock.fileExistsSync).to.have.been.calledWith(path.join('conf', 'config.json'))
expect(stub.fileMock.fileExistsSync).to.have.been.calledWith(path.join('conf', 'config.yml'))
expect(stub.fileMock.fileExistsSync).to.have.been.calledWith('/etc/deepstream/config.js')
expect(stub.fileMock.fileExistsSync).to.have.been.calledWith('/etc/deepstream/config.json')
expect(stub.fileMock.fileExistsSync).to.have.been.calledWith('/etc/deepstream/config.yml')
})
it('load a custom yml file path', () => {
const stub = setUpStub()
const config = stub.configLoader.loadConfig('./src/test/config/config.yml').config
expect(stub.fileMock.fileExistsSync).to.have.callCount(1)
expect(stub.fileMock.fileExistsSync).to.have.been.calledWith('./src/test/config/config.yml')
expect(config.serverName).not.to.equal(undefined)
expect(config.serverName).not.to.deep.equal('')
expect(config.serverName).not.to.deep.equal('UUID')
expect(config.port).to.deep.equal(1337)
expect(config.host).to.deep.equal('1.2.3.4')
expect(config.colors).to.deep.equal(false)
expect(config.showLogo).to.deep.equal(false)
// TODO
// expect(config.logLevel).to.deep.equal(C.LOG_LEVEL.ERROR)
})
it('loads a missing custom yml file path', () => {
const stub = setUpStub()
expect(() => {
stub.configLoader.loadConfig(null, { config: './src/test/config/does-not-exist.yml' })
}).to.throw('Configuration file not found at: ./src/test/config/does-not-exist.yml')
})
it('load a custom json file path', () => {
const stub = setUpStub(true, JSON.stringify({ port: 1001 }))
const config = stub.configLoader.loadConfig(null, { config: './foo.json' }).config
expect(stub.fileMock.fileExistsSync).to.have.callCount(1)
expect(stub.fileMock.fileExistsSync).to.have.been.calledWith('./foo.json')
expect(config.port).to.deep.equal(1001)
})
it('load a custom js file path', () => {
const stub = setUpStub()
let config = stub.configLoader.loadConfig(null, { config: './src/test/config/config.js' }).config
expect(stub.fileMock.fileExistsSync).to.have.callCount(1)
expect(stub.fileMock.fileExistsSync).to.have.been.calledWith('./src/test/config/config.js')
expect(config.port).to.deep.equal(1002)
config = stub.configLoader.loadConfig(null, { config: path.join(process.cwd(), 'src/test/config/config.js') }).config
expect(stub.fileMock.fileExistsSync).to.have.callCount(2)
expect(stub.fileMock.fileExistsSync).to.have.been.calledWith(path.join(process.cwd(), 'test/test/config/config.js'))
expect(config.port).to.deep.equal(1002)
})
it('fails if the custom file format is not supported', () => {
const stub = setUpStub(true, 'content doesnt matter here')
expect(() => {
// tslint:disable-next-line:no-unused-expression
stub.configLoader.loadConfig(null, { config: './config.foo' }).config
}).to.throw('.foo is not supported as configuration file')
})
it('fails if the custom file was not found', () => {
const stub = setUpStub(false)
expect(() => {
// tslint:disable-next-line:no-unused-expression
stub.configLoader.loadConfig(null, { config: './not-existing-config' }).config
}).to.throw('Configuration file not found at: ./not-existing-config')
expect(stub.fileMock.fileExistsSync).to.have.callCount(1)
expect(stub.fileMock.fileExistsSync).to.have.been.calledWith('./not-existing-config')
})
it('fails if the yaml file is invalid', () => {
const stub = setUpStub()
expect(() => {
// tslint:disable-next-line:no-unused-expression
stub.configLoader.loadConfig(null, { config: './src/test/config/config-broken.yml' }).config
}).to.throw(/asdsad: ooops/)
expect(stub.fileMock.fileExistsSync).to.have.callCount(1)
expect(stub.fileMock.fileExistsSync).to.have.been.calledWith('./src/test/config/config-broken.yml')
})
it('fails if the js file is invalid', () => {
const stub = setUpStub()
expect(() => {
// tslint:disable-next-line:no-unused-expression
stub.configLoader.loadConfig(null, { config: './src/test/config/config-broken.js' }).config
}).to.throw(/foobarBreaksIt is not defined/)
expect(stub.fileMock.fileExistsSync).to.have.callCount(1)
expect(stub.fileMock.fileExistsSync).to.have.been.calledWith('./src/test/config/config-broken.js')
})
})
describe('supports environment variable substitution', () => {
let configLoader
beforeEach(() => {
process.env.ENVIRONMENT_VARIABLE_TEST_1 = 'an_environment_variable_value'
process.env.ENVIRONMENT_VARIABLE_TEST_2 = 'another_environment_variable_value'
process.env.EXAMPLE_HOST = 'host'
process.env.EXAMPLE_PORT = '1234'
configLoader = jsYamlLoader
})
it('does environment variable substitution for yaml', () => {
const config = configLoader.loadConfig(null, { config: './src/test/config/config.yml' }).config
expect(config.environmentvariable).to.equal('an_environment_variable_value')
expect(config.another.environmentvariable).to.equal('another_environment_variable_value')
// expect(config.thisenvironmentdoesntexist).to.equal('DOESNT_EXIST')
expect(config.multipleenvs).to.equal('host:1234')
})
it('does environment variable substitution for json', () => {
const config = configLoader.loadConfig(null, { config: './src/test/config/json-with-env-variables.json' }).config
expect(config.environmentvariable).to.equal('an_environment_variable_value')
expect(config.another.environmentvariable).to.equal('another_environment_variable_value')
// expect(config.thisenvironmentdoesntexist).to.equal('DOESNT_EXIST')
expect(config.multipleenvs).to.equal('host:1234')
})
})
describe('merges in deepstreamCLI options', () => {
let configLoader
beforeEach(() => {
global.deepstreamCLI = {
port: 5555
}
configLoader = jsYamlLoader
})
afterEach(() => {
delete process.env.deepstreamCLI
})
it('does cli substitution', () => {
const config = configLoader.loadConfig().config
expect(config.connectionEndpoints.websocket.options.port).to.deep.equal(5555)
})
})
describe('load plugins by relative path property', () => {
let services
beforeEach(() => {
const fileMock = {
fileExistsSync () {
return true
}
}
const fsMock = {
readFileSync (filePath) {
if (filePath === './config.json') {
return `{
"plugins": {
"logger": {
"path": "./logger"
},
"cache": {
"path": "./cache",
"options": { "foo": 3, "bar": 4 }
}
}
}`
}
throw new Error(`should not require any other file: ${filePath}`)
}
}
const loggerModule = function (options) { return options }
loggerModule['@noCallThru'] = true
loggerModule['@global'] = true
class CacheModule {
public options: any
constructor (options) {
this.options = options
}
}
CacheModule['@noCallThru'] = true
CacheModule['@global'] = true
const configLoader = proxyquire('./js-yaml-loader', {
'fs': fsMock,
'./file-utils': fileMock,
[path.resolve('./logger')]: loggerModule,
[path.resolve('./cache')]: CacheModule
})
services = configLoader.loadConfig(null, { config: './config.json' }).services
})
it('load plugins', () => {
expect(services.cache.options).to.deep.equal({ foo: 3, bar: 4 })
})
})
describe.skip('load plugins by path property (npm module style)', () => {
let services
beforeEach(() => {
const fileMock = {
fileExistsSync () {
return true
}
}
const fsMock = {
readFileSync (filePath) {
if (filePath === './config.json') {
return `{
"plugins": {
"cache": {
"path": "foo-bar-qox",
"options": { "foo": 3, "bar": 4 }
}
}
}`
}
throw new Error(`should not require any other file: ${filePath}`)
}
}
// tslint:disable-next-line:max-classes-per-file
class FooBar {
public options: any
constructor (options) {
this.options = options
}
}
FooBar['@noCallThru'] = true
FooBar['@global'] = true
const configLoader = proxyquire('./js-yaml-loader', {
'fs': fsMock,
'./file-utils': fileMock,
'foo-bar-qox': FooBar
})
services = configLoader.loadConfig(null, { config: './config.json' }).services
})
it('load plugins', () => {
expect(services.cache.options).to.deep.equal({ foo: 3, bar: 4 })
})
})
describe('load plugins by name with a name convention', () => {
let services
beforeEach(() => {
const fileMock = {
fileExistsSync () {
return true
}
}
const fsMock = {
readFileSync (filePath) {
if (filePath === './config.json') {
return `{
"plugins": {
"cache": {
"name": "super-cache",
"options": { "foo": 5, "bar": 6 }
},
"storage": {
"name": "super-storage",
"options": { "foo": 7, "bar": 8 }
}
}
}`
}
throw new Error(`should not require any other file: ${filePath}`)
}
}
// tslint:disable-next-line:max-classes-per-file
class SuperCache {
public options: any
constructor (options) {
this.options = options
}
}
SuperCache['@noCallThru'] = true
SuperCache['@global'] = true
// tslint:disable-next-line:max-classes-per-file
class SuperStorage {
public options: any
constructor (options) {
this.options = options
}
}
SuperStorage['@noCallThru'] = true
SuperStorage['@global'] = true
const configLoader = proxyquire('./js-yaml-loader', {
'fs': fsMock,
'./file-utils': fileMock,
'deepstream.io-cache-super-cache': SuperCache,
'deepstream.io-storage-super-storage': SuperStorage
})
services = configLoader.loadConfig(null, {
config: './config.json'
}).services
})
it('load plugins', () => {
expect(services.cache.options).to.deep.equal({ foo: 5, bar: 6 })
expect(services.storage.options).to.deep.equal({ foo: 7, bar: 8 })
})
})
describe('load plugins by name with a name convention with lib prefix', () => {
let services
beforeEach(() => {
const fileMock = {
fileExistsSync () {
return true
}
}
const fsMock = {
readFileSync (filePath) {
if (filePath === './config.json') {
return `{
"plugins": {
"cache": {
"name": "super-cache",
"options": { "foo": -1, "bar": -2 }
},
"storage": {
"name": "super-storage",
"options": { "foo": -3, "bar": -4 }
}
}
}`
}
throw new Error(`should not require any other file: ${filePath}`)
}
}
// tslint:disable-next-line:max-classes-per-file
class SuperCache {
public options: any
constructor (options) {
this.options = options
}
}
SuperCache['@noCallThru'] = true
SuperCache['@global'] = true
// tslint:disable-next-line:max-classes-per-file
class SuperStorage {
public options: any
constructor (options) {
this.options = options
}
}
SuperStorage['@noCallThru'] = true
SuperStorage['@global'] = true
// tslint:disable-next-line:max-classes-per-file
class HTTPMock {
public options: any
constructor (options) {
this.options = options
}
}
HTTPMock['@noCallThru'] = true
HTTPMock['@global'] = true
const configLoader = proxyquire('./js-yaml-loader', {
'fs': fsMock,
'./file-utils': fileMock,
[path.resolve(process.cwd(), 'foobar', 'deepstream.io-cache-super-cache')]: SuperCache,
[path.resolve(process.cwd(), 'foobar', 'deepstream.io-storage-super-storage')]: SuperStorage,
[path.resolve(process.cwd(), 'foobar', 'deepstream.io-connection-http')]: HTTPMock
})
services = configLoader.loadConfig(null, {
config: './config.json',
libDir: 'foobar'
}).services
})
it('load plugins', () => {
expect(services.cache.options).to.deep.equal({ foo: -1, bar: -2 })
expect(services.storage.options).to.deep.equal({ foo: -3, bar: -4 })
})
})
describe('load plugins by name with a name convention with an absolute lib prefix', () => {
let services
beforeEach(() => {
const fileMock = {
fileExistsSync () {
return true
}
}
const fsMock = {
readFileSync (filePath) {
if (filePath === './config.json') {
return `{
"plugins": {
"cache": {
"name": "super-cache",
"options": { "foo": -1, "bar": -2 }
},
"storage": {
"name": "super-storage",
"options": { "foo": -3, "bar": -4 }
}
}
}`
}
throw new Error(`should not require any other file: ${filePath}`)
}
}
// tslint:disable-next-line:max-classes-per-file
class SuperCache {
public options: any
constructor (options) {
this.options = options
}
}
SuperCache['@noCallThru'] = true
SuperCache['@global'] = true
// tslint:disable-next-line:max-classes-per-file
class SuperStorage {
public options: any
constructor (options) {
this.options = options
}
}
SuperStorage['@noCallThru'] = true
SuperStorage['@global'] = true
// tslint:disable-next-line:max-classes-per-file
class HTTPMock {
public options: any
constructor (options) {
this.options = options
}
}
HTTPMock['@noCallThru'] = true
HTTPMock['@global'] = true
const configLoader = proxyquire('./js-yaml-loader', {
'fs': fsMock,
'./file-utils': fileMock,
[path.resolve('/foobar', 'deepstream.io-cache-super-cache')]: SuperCache,
[path.resolve('/foobar', 'deepstream.io-storage-super-storage')]: SuperStorage,
[path.resolve('/foobar', 'deepstream.io-connection-http')]: HTTPMock
})
services = configLoader.loadConfig(null, {
config: './config.json',
libDir: '/foobar'
}).services
})
it('load plugins', () => {
expect(services.cache.options).to.deep.equal({ foo: -1, bar: -2 })
expect(services.storage.options).to.deep.equal({ foo: -3, bar: -4 })
})
})
}) | the_stack |
import { IRenderFunction } from "@uifabric/utilities/lib";
import { getClient, IProjectPageService } from "azure-devops-extension-api";
import {
QueryHierarchyItem,
WorkItemTrackingRestClient
} from "azure-devops-extension-api/WorkItemTracking";
import * as DevOps from "azure-devops-extension-sdk";
import { Dropdown, IDropdownOption } from "office-ui-fabric-react/lib/Dropdown";
import {
ISelectableOption,
SelectableOptionMenuItemType
} from "office-ui-fabric-react/lib/utilities/selectableOption/SelectableOption.types";
import * as React from "react";
import "./queryPicker.scss";
import { Button } from "azure-devops-ui/Button";
interface IQueryOption extends ISelectableOption {
hasChildren: boolean;
isExpanded: boolean;
level: number;
queryTreeItem: IQueryTreeItem;
}
interface IQueryTreeItem {
parentId: string | null;
item: QueryHierarchyItem;
childrenFetched: boolean;
isExpanded: boolean;
}
export interface IQueryPickerProps {
defaultSelectedQueryId?: string;
onChanged?(queryId: string): void;
}
export interface IQueryPickerState {
options: IQueryOption[];
isLoading: boolean;
}
export class QueryPicker extends React.Component<
IQueryPickerProps,
IQueryPickerState
> {
private queryTree: IQueryTreeItem[] = [];
private queryTreeLookup: { [key: string]: IQueryTreeItem } = {};
constructor(props: IQueryPickerProps) {
super(props);
this.state = {
options: [],
isLoading: true
};
}
async componentDidMount() {
const { defaultSelectedQueryId } = this.props;
const projectService: IProjectPageService = await DevOps.getService<
IProjectPageService
>("ms.vss-tfs-web.tfs-page-data-service");
const project = await projectService.getProject();
const queryItems = await getClient(
WorkItemTrackingRestClient
).getQueries(project!.id, 4, 0);
// Only take Shared Queries
this._mapQueryItems(queryItems.filter(x => x.isPublic));
if (defaultSelectedQueryId) {
await this.setInitial(defaultSelectedQueryId);
}
this._updateState();
this.setState({
isLoading: false
});
}
private async setInitial(id: string): Promise<void> {
const client = getClient(WorkItemTrackingRestClient);
// If selected query id is given, build up tree
const projectService: IProjectPageService = await DevOps.getService<
IProjectPageService
>("ms.vss-tfs-web.tfs-page-data-service");
const project = await projectService.getProject();
const queryItem = await client.getQuery(project!.id, id, 4, 0);
// Retrieve parent elements
const path = queryItem.path;
const pathSegments = path.split("/");
// Remove own element since it's not a folder
pathSegments.pop();
let parent: IQueryTreeItem | null = null;
for (let i = 0; i < pathSegments.length; ++i) {
let parentQueryItem = await client.getQuery(
project!.id,
pathSegments.slice(0, i + 1).join("/"),
4,
1
);
if (this.queryTreeLookup[parentQueryItem.id]) {
parent = this.queryTreeLookup[parentQueryItem.id];
} else {
parent = this._mapQueryItem(
parent && parent.item.id,
parentQueryItem
);
}
for (const childItem of parentQueryItem.children) {
this._mapQueryItem(parentQueryItem.id as string, childItem);
}
parent.isExpanded = true;
parent.childrenFetched = true;
}
}
render(): JSX.Element {
const { defaultSelectedQueryId } = this.props;
const { isLoading, options } = this.state;
return (
<Dropdown
label={"Select query"}
placeHolder={isLoading ? "Loading..." : "Select query"}
options={options}
onRenderItem={
this._onRenderItem as IRenderFunction<ISelectableOption>
}
onRenderOption={
this._onRenderOption as IRenderFunction<ISelectableOption>
}
onChanged={
this._onChanged as (
option: IDropdownOption,
index?: number
) => void
}
disabled={isLoading}
selectedKey={
(!isLoading && defaultSelectedQueryId) || undefined
}
/>
);
}
private _onChanged = (option: IQueryOption) => {
const { onChanged } = this.props;
if (onChanged) {
onChanged(option.queryTreeItem.item.id);
}
};
private _buildOptions(): IQueryOption[] {
const result: IQueryOption[] = [];
const stack: IQueryTreeItem[] = [];
stack.push(...this.queryTree.slice(0).reverse());
while (stack.length > 0) {
const l = stack.length;
for (let i = 0; i < l; ++i) {
const treeItem = stack.pop()!;
let level = 0;
let parentId = treeItem.parentId;
while (parentId) {
++level;
parentId = this.queryTreeLookup[parentId].parentId;
}
result.push({
key: treeItem.item.id,
text: treeItem.item.name,
hasChildren: treeItem.item.hasChildren,
isExpanded: treeItem.isExpanded,
level,
queryTreeItem: treeItem,
itemType: treeItem.item.hasChildren
? SelectableOptionMenuItemType.Header
: SelectableOptionMenuItemType.Normal
});
if (treeItem.item.hasChildren && treeItem.isExpanded) {
if (treeItem.childrenFetched) {
stack.push(
...treeItem.item.children
.map(c => this.queryTreeLookup[c.id])
.reverse()
);
} else {
// Add dummy loading item if loading children
result.push({
key: treeItem.item.id + "-loading",
text: "Loading...",
hasChildren: false,
isExpanded: false,
// Indent by one level
level: level + 1,
queryTreeItem: treeItem
});
}
}
}
}
return result;
}
private _onRenderItem = (
item: IQueryOption | undefined,
defaultRender: (props: IQueryOption | undefined) => JSX.Element
): JSX.Element => {
if (
item &&
item.key &&
this.queryTreeLookup[item.key] &&
this.queryTreeLookup[item.key].item.hasChildren
) {
return (
<div className="query-option" key={item.queryTreeItem.item.id}>
{this._onRenderOption(item)}
</div>
);
}
return defaultRender(item);
};
private _onRenderOption = (option: IQueryOption): JSX.Element => {
const marginLeft = option.level * 10;
return (
<div
className="query-item"
key={option.queryTreeItem.item.id}
style={{
paddingLeft: (option.hasChildren && marginLeft) || 0
}}
>
{option.hasChildren && (
<Button
subtle={true}
iconProps={{
iconName: option.isExpanded
? "ChevronDown"
: "ChevronRight"
}}
onClick={ev => this._toggle(ev, option)}
/>
)}
{!option.hasChildren && (
<div
className="query-item--spacer"
style={{ marginLeft }}
/>
)}
<div>{option.text}</div>
</div>
);
};
private _mapQueryItems(queryItems: QueryHierarchyItem[]) {
for (const queryItem of queryItems) {
this.queryTree.push(this._mapQueryItem(null, queryItem));
}
}
private _mapQueryItem(
parentId: string | null,
queryItem: QueryHierarchyItem
): IQueryTreeItem {
let parentItem: IQueryTreeItem | null = null;
if (parentId) {
parentItem = this.queryTreeLookup[parentId];
}
const treeItem: IQueryTreeItem = {
parentId: parentId,
item: queryItem,
childrenFetched: false,
isExpanded: false
};
if (parentItem) {
if (!parentItem.item.children) {
parentItem.item.children = [];
}
if (!parentItem.item.children.some(i => i.id === queryItem.id)) {
parentItem.item.children.push(queryItem);
// Ensure children are sorted
parentItem.item.children.sort(comparer);
}
}
this.queryTreeLookup[queryItem.id] = treeItem;
return treeItem;
}
/** Expand/collapse a node */
private _toggle = async (
ev: React.MouseEvent<any> | React.KeyboardEvent<any>,
option: IQueryOption
) => {
// Do this first before React reuses the event (this saves persisting)
ev.preventDefault();
ev.stopPropagation();
const queryTreeItem = this.queryTreeLookup[option.key];
queryTreeItem.isExpanded = !queryTreeItem.isExpanded;
if (!queryTreeItem.childrenFetched) {
const projectService: IProjectPageService = await DevOps.getService<
IProjectPageService
>("ms.vss-tfs-web.tfs-page-data-service");
const project = await projectService.getProject();
getClient(WorkItemTrackingRestClient)
.getQuery(project!.id, option.key as string, 4, 1)
.then(queryItem => {
// Add in items
queryTreeItem.childrenFetched = true;
for (const childItem of queryItem.children) {
this._mapQueryItem(option.key as string, childItem);
}
this._updateState();
});
}
this._updateState();
};
private _updateState() {
// Re-build options
this.setState({
options: this._buildOptions()
});
}
}
function comparer(a: QueryHierarchyItem, b: QueryHierarchyItem): number {
if (a.isFolder && !b.isFolder) {
return -1;
} else if (!a.isFolder && b.isFolder) {
return 1;
}
return a.name.localeCompare(b.name);
} | the_stack |
import path from 'path';
const { exec, fixture, testFixture, testFixtureStdio } = require('./utils.js');
test('[vercel dev] validate redirects', async () => {
const directory = fixture('invalid-redirects');
const output = await exec(directory);
expect(output.exitCode).toBe(1);
expect(output.stderr).toMatch(
/Invalid vercel\.json - `redirects\[0\].statusCode` should be integer/m
);
});
test('[vercel dev] validate headers', async () => {
const directory = fixture('invalid-headers');
const output = await exec(directory);
expect(output.exitCode).toBe(1);
expect(output.stderr).toMatch(
/Invalid vercel\.json - `headers\[0\].headers\[0\].value` should be string/m
);
});
test('[vercel dev] validate mixed routes and rewrites', async () => {
const directory = fixture('invalid-mixed-routes-rewrites');
const output = await exec(directory);
expect(output.exitCode).toBe(1);
expect(output.stderr).toMatch(
/If `rewrites`, `redirects`, `headers`, `cleanUrls` or `trailingSlash` are used, then `routes` cannot be present./m
);
expect(output.stderr).toMatch(/vercel\.link\/mix-routing-props/m);
});
// Test seems unstable: It won't return sometimes.
test('[vercel dev] validate env var names', async () => {
const directory = fixture('invalid-env-var-name');
const { dev } = await testFixture(directory, { stdio: 'pipe' });
try {
let stderr = '';
dev.stderr.setEncoding('utf8');
await new Promise<void>((resolve, reject) => {
dev.stderr.on('data', (b: any) => {
stderr += b.toString();
if (
stderr.includes('Ignoring env var "1" because name is invalid') &&
stderr.includes(
'Ignoring build env var "_a" because name is invalid'
) &&
stderr.includes(
'Env var names must start with letters, and can only contain alphanumeric characters and underscores'
)
) {
resolve();
}
});
dev.on('error', reject);
dev.on('exit', resolve);
});
} finally {
dev.kill('SIGTERM');
}
});
test(
'[vercel dev] test rewrites with segments serve correct content',
testFixtureStdio('test-rewrites-with-segments', async (testPath: any) => {
await testPath(200, '/api/users/first', 'first');
await testPath(200, '/api/fourty-two', '42');
await testPath(200, '/rand', '42');
await testPath(200, '/api/dynamic', 'dynamic');
await testPath(404, '/api');
})
);
test(
'[vercel dev] test rewrites serve correct content',
testFixtureStdio('test-rewrites', async (testPath: any) => {
await testPath(200, '/hello', 'Hello World');
})
);
test(
'[vercel dev] test rewrites and redirects serve correct external content',
testFixtureStdio(
'test-external-rewrites-and-redirects',
async (testPath: any) => {
const vcRobots = `https://vercel.com/robots.txt`;
await testPath(200, '/rewrite', /User-Agent: \*/m);
await testPath(308, '/redirect', `Redirecting to ${vcRobots} (308)`, {
Location: vcRobots,
});
await testPath(307, '/tempRedirect', `Redirecting to ${vcRobots} (307)`, {
Location: vcRobots,
});
}
)
);
test(
'[vercel dev] test rewrites and redirects is case sensitive',
testFixtureStdio('test-routing-case-sensitive', async (testPath: any) => {
await testPath(200, '/Path', 'UPPERCASE');
await testPath(200, '/path', 'lowercase');
await testPath(308, '/GoTo', 'Redirecting to /upper.html (308)', {
Location: '/upper.html',
});
await testPath(308, '/goto', 'Redirecting to /lower.html (308)', {
Location: '/lower.html',
});
})
);
test(
'[vercel dev] test cleanUrls serve correct content',
testFixtureStdio('test-clean-urls', async (testPath: any) => {
await testPath(200, '/', 'Index Page');
await testPath(200, '/about', 'About Page');
await testPath(200, '/sub', 'Sub Index Page');
await testPath(200, '/sub/another', 'Sub Another Page');
await testPath(200, '/style.css', 'body { color: green }');
await testPath(308, '/index.html', 'Redirecting to / (308)', {
Location: '/',
});
await testPath(308, '/about.html', 'Redirecting to /about (308)', {
Location: '/about',
});
await testPath(308, '/sub/index.html', 'Redirecting to /sub (308)', {
Location: '/sub',
});
await testPath(
308,
'/sub/another.html',
'Redirecting to /sub/another (308)',
{ Location: '/sub/another' }
);
})
);
test(
'[vercel dev] test cleanUrls serve correct content when using `outputDirectory`',
testFixtureStdio(
'test-clean-urls-with-output-directory',
async (testPath: any) => {
await testPath(200, '/', 'Index Page');
await testPath(200, '/about', 'About Page');
await testPath(200, '/sub', 'Sub Index Page');
await testPath(200, '/sub/another', 'Sub Another Page');
await testPath(200, '/style.css', 'body { color: green }');
await testPath(308, '/index.html', 'Redirecting to / (308)', {
Location: '/',
});
await testPath(308, '/about.html', 'Redirecting to /about (308)', {
Location: '/about',
});
await testPath(308, '/sub/index.html', 'Redirecting to /sub (308)', {
Location: '/sub',
});
await testPath(
308,
'/sub/another.html',
'Redirecting to /sub/another (308)',
{ Location: '/sub/another' }
);
}
)
);
test(
'[vercel dev] should serve custom 404 when `cleanUrls: true`',
testFixtureStdio('test-clean-urls-custom-404', async (testPath: any) => {
await testPath(200, '/', 'This is the home page');
await testPath(200, '/about', 'The about page');
await testPath(200, '/contact/me', 'Contact Me Subdirectory');
await testPath(404, '/nothing', 'Custom 404 Page');
await testPath(404, '/nothing/', 'Custom 404 Page');
})
);
test(
'[vercel dev] test cleanUrls and trailingSlash serve correct content',
testFixtureStdio('test-clean-urls-trailing-slash', async (testPath: any) => {
await testPath(200, '/', 'Index Page');
await testPath(200, '/about/', 'About Page');
await testPath(200, '/sub/', 'Sub Index Page');
await testPath(200, '/sub/another/', 'Sub Another Page');
await testPath(200, '/style.css', 'body { color: green }');
//TODO: fix this test so that location is `/` instead of `//`
//await testPath(308, '/index.html', 'Redirecting to / (308)', { Location: '/' });
await testPath(308, '/about.html', 'Redirecting to /about/ (308)', {
Location: '/about/',
});
await testPath(308, '/sub/index.html', 'Redirecting to /sub/ (308)', {
Location: '/sub/',
});
await testPath(
308,
'/sub/another.html',
'Redirecting to /sub/another/ (308)',
{
Location: '/sub/another/',
}
);
})
);
test(
'[vercel dev] test cors headers work with OPTIONS',
testFixtureStdio('test-cors-routes', async (testPath: any) => {
const headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers':
'Content-Type, Authorization, Accept, Content-Length, Origin, User-Agent',
'Access-Control-Allow-Methods':
'GET, POST, OPTIONS, HEAD, PATCH, PUT, DELETE',
};
await testPath(200, '/', 'status api', headers, { method: 'GET' });
await testPath(200, '/', 'status api', headers, { method: 'POST' });
await testPath(200, '/api/status.js', 'status api', headers, {
method: 'GET',
});
await testPath(200, '/api/status.js', 'status api', headers, {
method: 'POST',
});
await testPath(204, '/', '', headers, { method: 'OPTIONS' });
await testPath(204, '/api/status.js', '', headers, { method: 'OPTIONS' });
})
);
test(
'[vercel dev] test trailingSlash true serve correct content',
testFixtureStdio('test-trailing-slash', async (testPath: any) => {
await testPath(200, '/', 'Index Page');
await testPath(200, '/index.html', 'Index Page');
await testPath(200, '/about.html', 'About Page');
await testPath(200, '/sub/', 'Sub Index Page');
await testPath(200, '/sub/index.html', 'Sub Index Page');
await testPath(200, '/sub/another.html', 'Sub Another Page');
await testPath(200, '/style.css', 'body { color: green }');
await testPath(308, '/about.html/', 'Redirecting to /about.html (308)', {
Location: '/about.html',
});
await testPath(308, '/style.css/', 'Redirecting to /style.css (308)', {
Location: '/style.css',
});
await testPath(308, '/sub', 'Redirecting to /sub/ (308)', {
Location: '/sub/',
});
})
);
test(
'[vercel dev] should serve custom 404 when `trailingSlash: true`',
testFixtureStdio('test-trailing-slash-custom-404', async (testPath: any) => {
await testPath(200, '/', 'This is the home page');
await testPath(200, '/about.html', 'The about page');
await testPath(200, '/contact/', 'Contact Subdirectory');
await testPath(404, '/nothing/', 'Custom 404 Page');
})
);
test(
'[vercel dev] test trailingSlash false serve correct content',
testFixtureStdio('test-trailing-slash-false', async (testPath: any) => {
await testPath(200, '/', 'Index Page');
await testPath(200, '/index.html', 'Index Page');
await testPath(200, '/about.html', 'About Page');
await testPath(200, '/sub', 'Sub Index Page');
await testPath(200, '/sub/index.html', 'Sub Index Page');
await testPath(200, '/sub/another.html', 'Sub Another Page');
await testPath(200, '/style.css', 'body { color: green }');
await testPath(308, '/about.html/', 'Redirecting to /about.html (308)', {
Location: '/about.html',
});
await testPath(308, '/sub/', 'Redirecting to /sub (308)', {
Location: '/sub',
});
await testPath(
308,
'/sub/another.html/',
'Redirecting to /sub/another.html (308)',
{
Location: '/sub/another.html',
}
);
})
);
test(
'[vercel dev] throw when invalid builder routes detected',
testFixtureStdio(
'invalid-builder-routes',
async (testPath: any) => {
await testPath(
500,
'/',
/Route at index 0 has invalid `src` regular expression/m
);
},
{ skipDeploy: true }
)
);
test(
'[vercel dev] support legacy `@now` scope runtimes',
testFixtureStdio('legacy-now-runtime', async (testPath: any) => {
await testPath(200, '/', /A simple deployment with the Vercel API!/m);
})
);
test(
'[vercel dev] 00-list-directory',
testFixtureStdio(
'00-list-directory',
async (testPath: any) => {
await testPath(200, '/', /Files within/m);
await testPath(200, '/', /test[0-3]\.txt/m);
await testPath(200, '/', /\.well-known/m);
await testPath(200, '/.well-known/keybase.txt', 'proof goes here');
},
{ projectSettings: { directoryListing: true } }
)
);
test(
'[vercel dev] 01-node',
testFixtureStdio('01-node', async (testPath: any) => {
await testPath(200, '/', /A simple deployment with the Vercel API!/m);
})
); | the_stack |
import { $ } from '@aomao/engine';
import type {
PluginEntry,
CardEntry,
PluginOptions,
NodeInterface,
} from '@aomao/engine';
//引入插件 begin
import Redo from '@aomao/plugin-redo';
// import type { RedoOptions } from '@aomao/plugin-redo';
import Undo from '@aomao/plugin-undo';
// import type { UndoOptions } from '@aomao/plugin-undo';
import Bold from '@aomao/plugin-bold';
// import type { BoldOptions } from '@aomao/plugin-bold';
import Code from '@aomao/plugin-code';
// import type { CodeOptions } from '@aomao/plugin-code';
import Backcolor from '@aomao/plugin-backcolor';
// import type { BackcolorOptions } from '@aomao/plugin-backcolor';
import Fontcolor from '@aomao/plugin-fontcolor';
// import type { FontcolorOptions } from '@aomao/plugin-fontcolor';
import Fontsize from '@aomao/plugin-fontsize';
import type { FontsizeOptions } from '@aomao/plugin-fontsize';
import Italic from '@aomao/plugin-italic';
import type { ItalicOptions } from '@aomao/plugin-italic';
import Underline from '@aomao/plugin-underline';
// import type { UnderlineOptions } from '@aomao/plugin-underline';
import Hr, { HrComponent } from '@aomao/plugin-hr';
// import type { HrOptions } from '@aomao/plugin-hr';
import Tasklist, { CheckboxComponent } from '@aomao/plugin-tasklist';
// import type { TasklistOptions } from '@aomao/plugin-tasklist';
import Orderedlist from '@aomao/plugin-orderedlist';
// import type { OrderedlistOptions } from '@aomao/plugin-orderedlist';
import Unorderedlist from '@aomao/plugin-unorderedlist';
// import type { UnorderedlistOptions } from '@aomao/plugin-unorderedlist';
import Indent from '@aomao/plugin-indent';
// import type { IndentOptions } from '@aomao/plugin-indent';
import Heading from '@aomao/plugin-heading';
// import type { HeadingOptions } from '@aomao/plugin-heading';
import Strikethrough from '@aomao/plugin-strikethrough';
// import type { StrikethroughOptions } from '@aomao/plugin-strikethrough';
import Sub from '@aomao/plugin-sub';
// import type { SubOptions } from '@aomao/plugin-sub';
import Sup from '@aomao/plugin-sup';
// import type { SupOptions } from '@aomao/plugin-sup';
import Alignment from '@aomao/plugin-alignment';
// import type { AlignmentOptions } from '@aomao/plugin-alignment';
import Mark from '@aomao/plugin-mark';
// import type { MarkOptions } from '@aomao/plugin-mark';
import Quote from '@aomao/plugin-quote';
// import type { QuoteOptions } from '@aomao/plugin-quote';
import PaintFormat from '@aomao/plugin-paintformat';
// import type { PaintformatOptions } from '@aomao/plugin-paintformat';
import RemoveFormat from '@aomao/plugin-removeformat';
// import type { RemoveformatOptions } from '@aomao/plugin-removeformat';
import SelectAll from '@aomao/plugin-selectall';
// import type { SelectAllOptions } from '@aomao/plugin-selectall';
import Link from '@aomao/plugin-link';
// import type { LinkOptions } from '@aomao/plugin-link';
import Codeblock, { CodeBlockComponent } from '@aomao/plugin-codeblock';
// import type { CodeblockOptions } from '@aomao/plugin-codeblock';
import Image, { ImageComponent, ImageUploader } from '@aomao/plugin-image';
import type { ImageOptions } from '@aomao/plugin-image';
import Table, { TableComponent } from '@aomao/plugin-table';
import type { TableOptions } from '@aomao/plugin-table';
import MarkRange from '@aomao/plugin-mark-range';
import type { MarkRangeOptions } from '@aomao/plugin-mark-range';
import File, { FileComponent, FileUploader } from '@aomao/plugin-file';
import type { FileOptions } from '@aomao/plugin-file';
import Video, { VideoComponent, VideoUploader } from '@aomao/plugin-video';
import type { VideoOptions, VideoUploaderOptions } from '@aomao/plugin-video';
import Math, { MathComponent } from '@aomao/plugin-math';
import type { MathOptions } from '@aomao/plugin-math';
import Fontfamily from '@aomao/plugin-fontfamily';
import type { FontfamilyOptions } from '@aomao/plugin-fontfamily';
import Status, { StatusComponent } from '@aomao/plugin-status';
// import type { StatusOptions } from '@aomao/plugin-status';
import LineHeight from '@aomao/plugin-line-height';
import type { LineHeightOptions } from '@aomao/plugin-line-height';
import Mention, { MentionComponent } from '@aomao/plugin-mention';
import type { MentionOptions } from '@aomao/plugin-mention';
import Embed, { EmbedComponent } from '@aomao/plugin-embed';
// import type { EmbedOptions } from '@aomao/plugin-embed'
import Test, { TestComponent } from './plugins/test';
import {
ToolbarPlugin,
ToolbarComponent,
fontFamilyDefaultData,
} from '@aomao/toolbar';
import type { ToolbarOptions } from '@aomao/toolbar';
import ReactDOM from 'react-dom';
import Loading from '../loading';
import Empty from 'antd/es/empty';
import 'antd/es/empty/style';
import { ImageUploaderOptions } from 'plugins/image/dist/uploader';
export const plugins: Array<PluginEntry> = [
Redo,
Undo,
Bold,
Code,
Backcolor,
Fontcolor,
Fontsize,
Italic,
Underline,
Hr,
Tasklist,
Orderedlist,
Unorderedlist,
Indent,
Heading,
Strikethrough,
Sub,
Sup,
Alignment,
Mark,
Quote,
PaintFormat,
RemoveFormat,
SelectAll,
Link,
Codeblock,
Image,
ImageUploader,
Table,
MarkRange,
File,
FileUploader,
Video,
VideoUploader,
Math,
ToolbarPlugin,
Fontfamily,
Status,
LineHeight,
Mention,
Embed,
Test,
];
export const cards: CardEntry[] = [
HrComponent,
CheckboxComponent,
CodeBlockComponent,
ImageComponent,
TableComponent,
FileComponent,
VideoComponent,
MathComponent,
ToolbarComponent,
StatusComponent,
MentionComponent,
TestComponent,
EmbedComponent,
];
export const tableOptions: TableOptions = {
overflow: {
maxLeftWidth: () => {
// 编辑区域位置
const rect = $('.am-engine')
.get<HTMLElement>()
?.getBoundingClientRect();
const editorLeft = rect?.left || 0;
// 减去大纲的宽度
const width = editorLeft - $('.data-toc-wrapper').width();
// 留 16px 的间隔
return width <= 0 ? 0 : width - 16;
},
maxRightWidth: () => {
// 编辑区域位置
const rect = $('.am-engine')
.get<HTMLElement>()
?.getBoundingClientRect();
const editorRigth = (rect?.right || 0) - (rect?.width || 0);
// 减去评论区域的宽度
const width = editorRigth - $('.doc-comment-layer').width();
// 留 16px 的间隔
return width <= 0 ? 0 : width - 16;
},
},
};
export const markRangeOptions: MarkRangeOptions = {
//标记类型集合
keys: ['comment'],
};
export const italicOptions: ItalicOptions = {
// 默认为 _ 下划线,这里修改为单个 * 号
markdown: '*',
};
export const imageOptions: ImageOptions = {
onBeforeRender: (status: string, url: string) => {
if (!url || url.indexOf('http') === 0) return url;
return url + `?token=12323`;
},
};
export const imageUploaderOptions: ImageUploaderOptions = {
file: {
action: '/api/upload/image',
headers: { Authorization: '213434' },
},
remote: {
action: '/api/upload/image',
},
isRemote: (src: string) => false,
};
export const fileOptions: FileOptions = {
action: '/api/upload/file',
};
export const videoOptions: VideoOptions = {
onBeforeRender: (status: string, url: string) => {
return url;
},
};
export const videoUploaderOptions: VideoUploaderOptions = {
action: '/api/upload/video',
limitSize: 1024 * 1024 * 50,
};
export const mathOptions: MathOptions = {
action: '/api/latex',
parse: (res: any) => {
if (res.success) return { result: true, data: res.svg };
return { result: false, data: '' };
},
};
export const mentionOptions: MentionOptions = {
action: '/api/user/search',
onLoading: (root: NodeInterface) => {
return ReactDOM.render(<Loading />, root.get<HTMLElement>()!);
},
onEmpty: (root: NodeInterface) => {
return ReactDOM.render(<Empty />, root.get<HTMLElement>()!);
},
onClick: (root: NodeInterface, { key, name }) => {
console.log('mention click:', key, '-', name);
},
onMouseEnter: (layout: NodeInterface, { name }) => {
ReactDOM.render(
<div style={{ padding: 5 }}>
<p>This is name: {name}</p>
<p>配置 mention 插件的 onMouseEnter 方法</p>
<p>此处使用 ReactDOM.render 自定义渲染</p>
<p>Use ReactDOM.render to customize rendering here</p>
</div>,
layout.get<HTMLElement>()!,
);
},
};
export const fontsizeOptions: FontsizeOptions = {
//配置粘贴后需要过滤的字体大小
filter: (fontSize: string) => {
return (
[
'12px',
'13px',
'14px',
'15px',
'16px',
'19px',
'22px',
'24px',
'29px',
'32px',
'40px',
'48px',
].indexOf(fontSize) > -1
);
},
};
export const fontfamilyOptions: FontfamilyOptions = {
//配置粘贴后需要过滤的字体
filter: (fontfamily: string) => {
const item = fontFamilyDefaultData.find((item) =>
fontfamily
.split(',')
.some(
(name) =>
item.value
.toLowerCase()
.indexOf(name.replace(/"/, '').toLowerCase()) > -1,
),
);
return item ? item.value : false;
},
};
export const lineHeightOptions: LineHeightOptions = {
//配置粘贴后需要过滤的行高
filter: (lineHeight: string) => {
if (lineHeight === '14px') return '1';
if (lineHeight === '16px') return '1.15';
if (lineHeight === '21px') return '1.5';
if (lineHeight === '28px') return '2';
if (lineHeight === '35px') return '2.5';
if (lineHeight === '42px') return '3';
// 不满足条件就移除掉
return ['1', '1.15', '1.5', '2', '2.5', '3'].indexOf(lineHeight) > -1;
},
};
export const toolbarOptions: ToolbarOptions = {
// popup: {
// items: [
// ['undo', 'redo'],
// {
// icon: 'text',
// items: [
// 'bold',
// 'italic',
// 'strikethrough',
// 'underline',
// 'fontsize',
// 'fontcolor',
// 'backcolor',
// 'moremark',
// ],
// },
// [
// {
// type: 'button',
// name: 'image-uploader',
// icon: 'image',
// },
// 'link',
// 'tasklist',
// 'heading',
// ],
// {
// icon: 'more',
// items: [
// {
// type: 'button',
// name: 'video-uploader',
// icon: 'video',
// },
// {
// type: 'button',
// name: 'file-uploader',
// icon: 'attachment',
// },
// {
// type: 'button',
// name: 'table',
// icon: 'table',
// },
// {
// type: 'button',
// name: 'math',
// icon: 'math',
// },
// {
// type: 'button',
// name: 'codeblock',
// icon: 'codeblock',
// },
// {
// type: 'button',
// name: 'orderedlist',
// icon: 'ordered-list',
// },
// {
// type: 'button',
// name: 'unordered-list',
// icon: 'unordered-list',
// },
// {
// type: 'button',
// name: 'hr',
// icon: 'hr',
// },
// {
// type: 'button',
// name: 'quote',
// icon: 'quote',
// },
// ],
// },
// ]
// }
};
export const pluginConfig: Record<string, PluginOptions> = {
[ToolbarPlugin.pluginName]: toolbarOptions,
[Table.pluginName]: tableOptions,
[MarkRange.pluginName]: markRangeOptions,
[Italic.pluginName]: italicOptions,
[Image.pluginName]: imageOptions,
[ImageUploader.pluginName]: imageUploaderOptions,
[FileUploader.pluginName]: fileOptions,
[VideoUploader.pluginName]: videoUploaderOptions,
[Video.pluginName]: videoOptions,
[Math.pluginName]: mathOptions,
[Mention.pluginName]: mentionOptions,
[Fontsize.pluginName]: fontsizeOptions,
[Fontfamily.pluginName]: fontfamilyOptions,
[LineHeight.pluginName]: lineHeightOptions,
}; | the_stack |
import _ from 'lodash'
import $ from 'jquery'
import Promise from 'bluebird'
import debugFn from 'debug'
import $dom from '../dom'
import $elements from '../dom/elements'
import $errUtils from '../cypress/error_utils'
const debug = debugFn('cypress:driver:actionability')
const delay = 50
const getFixedOrStickyEl = $dom.getFirstFixedOrStickyPositionParent
const getStickyEl = $dom.getFirstStickyPositionParent
const dispatchPrimedChangeEvents = function (state) {
// if we have a changeEvent, dispatch it
let changeEvent
changeEvent = state('changeEvent')
if (changeEvent) {
return changeEvent()
}
}
const scrollBehaviorOptionsMap = {
top: 'start',
bottom: 'end',
center: 'center',
nearest: 'nearest',
}
const getPositionFromArguments = function (positionOrX, y, options) {
let position; let x
if (_.isObject(positionOrX)) {
options = positionOrX
position = null
} else if (_.isObject(y)) {
options = y
position = positionOrX
y = null
x = null
} else if (_.every([positionOrX, y], _.isFinite)) {
position = null
x = positionOrX
} else if (_.isString(positionOrX)) {
position = positionOrX
}
return { options, position, x, y }
}
const ensureElIsNotCovered = function (cy, win, $el, fromElViewport, options, log, onScroll) {
let $elAtCoords = null
const getElementAtPointFromViewport = function (fromElViewport) {
// get the element at point from the viewport based
// on the desired x/y normalized coordinations
let elAtCoords
elAtCoords = $dom.getElementAtPointFromViewport(win.document, fromElViewport.x, fromElViewport.y)
if (elAtCoords) {
return $elAtCoords = $dom.wrap(elAtCoords)
}
}
const ensureDescendents = function (fromElViewport) {
// figure out the deepest element we are about to interact
// with at these coordinates
$elAtCoords = getElementAtPointFromViewport(fromElViewport)
debug('elAtCoords', $elAtCoords)
debug('el has pointer-events none?')
cy.ensureElDoesNotHaveCSS($el, 'pointer-events', 'none', log)
debug('is descendent of elAtCoords?')
cy.ensureDescendents($el, $elAtCoords, log)
return $elAtCoords
}
const ensureDescendentsAndScroll = function () {
try {
// use the initial coords fromElViewport
return ensureDescendents(fromElViewport)
} catch (err) {
// if scrolling to element is off we re-throw as there is nothing to do
if (options.scrollBehavior === false) {
throw err
}
// if we're being covered by a fixed position element then
// we're going to attempt to continously scroll the element
// from underneath this fixed position element until we can't
// anymore
const $fixed = getFixedOrStickyEl($elAtCoords)
debug('elAtCoords is fixed', !!$fixed)
// if we dont have a fixed position
// then just bail, cuz we need to retry async
if (!$fixed) {
throw err
}
const scrollContainerPastElement = function ($container, $fixed) {
// get the width + height of the $fixed
// since this is what we are scrolling past!
const { width, height } = $dom.getElementPositioning($fixed)
// what is this container currently scrolled?
// using jquery here which normalizes window scroll props
const currentScrollTop = $container.scrollTop()
const currentScrollLeft = $container.scrollLeft()
if (onScroll) {
const type = $dom.isWindow($container) ? 'window' : 'container'
onScroll($container, type)
}
// TODO: right here we could set all of the scrollable
// containers on the log and include their scroll
// positions.
//
// then the runner could ask the driver to scroll each one
// into its correct position until it passed
// if $dom.isWindow($container)
// log.set("scrollBy", { x: -width, y: -height })
// we want to scroll in the opposite direction (up not down)
// so just decrease the scrolled positions
$container.scrollTop((currentScrollTop - height))
return $container.scrollLeft((currentScrollLeft - width))
}
const getAllScrollables = function (scrollables, $el) {
// nudge algorithm
// starting at the element itself
// walk up until and find all of the scrollable containers
// until we reach null
// then push in the window
const $scrollableContainer = $dom.getFirstScrollableParent($el)
if ($scrollableContainer) {
scrollables.push($scrollableContainer)
// recursively iterate
return getAllScrollables(scrollables, $scrollableContainer)
}
// we're out of scrollable elements
// so just push in $(win)
scrollables.push($(win))
return scrollables
}
// we want to scroll all of our containers until
// this element becomes unhidden or retry async
const scrollContainers = function (scrollables) {
// hold onto all the elements we've scrolled
// past in this cycle
const elementsScrolledPast = []
// pull off scrollables starting with the most outer
// container which is window
const $scrollableContainer = scrollables.pop()
// we've reach the end of all the scrollables
if (!$scrollableContainer) {
// bail and just retry async
throw err
}
const possiblyScrollMultipleTimes = function ($fixed) {
// if we got something AND
let needle
if ($fixed && ((needle = $fixed.get(0), !elementsScrolledPast.includes(needle)))) {
elementsScrolledPast.push($fixed.get(0))
scrollContainerPastElement($scrollableContainer, $fixed)
try {
// now that we've changed scroll positions
// we must recalculate whether this element is covered
// since the element's top / left positions change.
({ fromElViewport } = getCoordinatesForEl(cy, $el, options))
// this is a relative calculation based on the viewport
// so these are the only coordinates we care about
return ensureDescendents(fromElViewport)
} catch (err) {
// we failed here, but before scrolling the next container
// we need to first verify that the element covering up
// is the same one as before our scroll
$elAtCoords = getElementAtPointFromViewport(fromElViewport)
if ($elAtCoords) {
// get the fixed element again
$fixed = getFixedOrStickyEl($elAtCoords)
// and possibly recursively scroll past it
// if we haven't see it before
return possiblyScrollMultipleTimes($fixed)
}
// getElementAtPoint was falsey, so target element is no longer in the viewport
throw err
}
} else {
return scrollContainers(scrollables)
}
}
return possiblyScrollMultipleTimes($fixed)
}
// start nudging
return scrollContainers(
getAllScrollables([], $el),
)
}
}
try {
ensureDescendentsAndScroll()
} catch (error) {
const err = error
if (log) {
log.set({
consoleProps () {
const obj = {}
obj['Tried to Click'] = $dom.getElements($el)
_.extend(obj, err.consoleProps)
return obj
},
})
}
throw err
}
// return the final $elAtCoords
return $elAtCoords
}
const getCoordinatesForEl = function (cy, $el, options) {
// determine if this element is animating
if (_.isFinite(options.x) && _.isFinite(options.y)) {
return $dom.getElementCoordinatesByPositionRelativeToXY($el, options.x, options.y)
}
// Cypress.dom.getElementCoordinatesByPosition($el, options.position)
return $dom.getElementCoordinatesByPosition($el, options.position)
}
const ensureNotAnimating = function (cy, $el, coordsHistory, animationDistanceThreshold) {
// if we dont have at least 2 points, we throw this error to force a
// retry, which will get us another point.
// this error is purposefully generic because if the actionability
//check times out, this error is the one displayed to the user and
// saying something like "coordsHistory must be at least 2 sets
// of coords" is not very useful.
// that would only happen if the actionability check times out, which
// shouldn't happen with default timeouts, but could theoretically
// on a very, very slow system
// https://github.com/cypress-io/cypress/issues/3738
if (coordsHistory.length < 2) {
$errUtils.throwErrByPath('dom.actionability_failed', {
args: {
node: $dom.stringify($el),
cmd: cy.state('current').get('name'),
},
})
}
// verify that our element is not currently animating
// by verifying it is still at the same coordinates within
// 5 pixels of x/y
cy.ensureElementIsNotAnimating($el, coordsHistory, animationDistanceThreshold)
}
const verify = function (cy, $el, options, callbacks) {
_.defaults(options, {
ensure: {
position: true,
visibility: true,
notDisabled: true,
notCovered: true,
notAnimating: true,
notReadonly: false,
custom: false,
},
})
const win = $dom.getWindowByElement($el.get(0))
const { _log, force, position } = options
const { onReady, onScroll } = callbacks
if (!onReady) {
throw new Error('actionability.verify must be passed an onReady callback')
}
// if we have a position we must validate
// this ahead of time else bail early
if (options.ensure.position && position) {
try {
cy.ensureValidPosition(position, _log)
} catch (error) {
// cannot proceed, give up
const err = error
return Promise.reject(err)
}
}
// scroll-behavior: smooth delays scrolling and causes the actionability
// check to fail, so the only solution is to remove the behavior and
// make scrolling occur instantly. we do this by adding a style tag
// and then removing it after we finish scrolling
// https://github.com/cypress-io/cypress/issues/3200
const addScrollBehaviorFix = () => {
let style
try {
const doc = $el.get(0).ownerDocument
style = doc.createElement('style')
style.innerHTML = '* { scroll-behavior: inherit !important; }'
// there's guaranteed to be a <script> tag, so that's the safest thing
// to query for and add the style tag after
doc.querySelector('script').after(style)
} catch (err) {
// the above shouldn't error, but out of an abundance of caution, we
// ignore any errors since this fix isn't worth failing the test over
}
return () => {
if (style) style.remove()
}
}
return Promise.try(() => {
const coordsHistory = []
const runAllChecks = function () {
let $elAtCoords
if (force !== true) {
// ensure it's attached
cy.ensureAttached($el, null, _log)
// ensure its 'receivable'
if (options.ensure.notDisabled) {
cy.ensureNotDisabled($el, _log)
}
if (options.scrollBehavior !== false) {
// scroll the element into view
const scrollBehavior = scrollBehaviorOptionsMap[options.scrollBehavior]
const removeScrollBehaviorFix = addScrollBehaviorFix()
debug('scrollIntoView:', $el[0])
$el.get(0).scrollIntoView({ block: scrollBehavior })
removeScrollBehaviorFix()
if (onScroll) {
onScroll($el, 'element')
}
}
// ensure its visible
if (options.ensure.visibility) {
cy.ensureVisibility($el, _log)
}
if (options.ensure.notReadonly) {
cy.ensureNotReadonly($el, _log)
}
if (_.isFunction(options.custom)) {
options.custom($el, _log)
}
}
// now go get all the coords for this element
const coords = getCoordinatesForEl(cy, $el, options)
// if force is true OR waitForAnimations is false
// then do not perform these additional ensures...
if ((options.ensure.notAnimating) && (force !== true) && (options.waitForAnimations !== false)) {
// store the coords that were absolute
// from the window or from the viewport for sticky elements
// (see https://github.com/cypress-io/cypress/pull/1478)
const sticky = !!getStickyEl($el)
coordsHistory.push(sticky ? coords.fromElViewport : coords.fromElWindow)
// then we ensure the element isnt animating
ensureNotAnimating(cy, $el, coordsHistory, options.animationDistanceThreshold)
}
if (force !== true) {
// now that we know our element isn't animating its time
// to figure out if it's being covered by another element.
// this calculation is relative from the viewport so we
// only care about fromElViewport coords
$elAtCoords = options.ensure.notCovered && ensureElIsNotCovered(cy, win, $el, coords.fromElViewport, options, _log, onScroll)
}
// pass our final object into onReady
const finalCoords = getCoordinatesForEl(cy, $el, options)
let finalEl
// When a contenteditable element is selected, we don't go deeper,
// because it is treated as a rich text field to users.
if ($elements.hasContenteditableAttr($el.get(0))) {
finalEl = $el
} else {
finalEl = $elAtCoords != null ? $elAtCoords : $el
}
return onReady(finalEl, finalCoords)
}
// we cannot enforce async promises here because if our
// element passes every single check, we MUST fire the event
// synchronously else we risk the state changing between
// the checks and firing the event!
const retryActionability = () => {
try {
return runAllChecks()
} catch (err) {
options.error = err
return cy.retry(retryActionability, options)
}
}
return retryActionability()
})
}
export default {
delay,
verify,
dispatchPrimedChangeEvents,
getPositionFromArguments,
} | the_stack |
import {
CalculatorData,
DAY_0,
calculate,
calculateLocationPersonAverage,
defaultValues,
} from 'data/calculate'
import {
BUDGET_ONE_PERCENT,
RiskProfile,
RiskProfilesUnaffectedByVaccines,
housemateMult,
personRiskMultiplier,
} from 'data/data'
import { prepopulated } from 'data/prepopulated'
const MILLISECONDS_PER_DAY = 1000 * 60 * 60 * 24
// The reported prevalence in |baseTestData|
const REPORTED_PREVALENCE = 0.003
// The expected adjusted prevalence in |baseTestData|
const PREVALENCE = 0.006
const dateAfterDay0 = (daysAfterDay0: number) => {
const date = new Date()
date.setTime(DAY_0.getTime() + daysAfterDay0 * MILLISECONDS_PER_DAY)
return date
}
// Prevailance is PREVALENCE (2x prevalance ratio)
const baseTestData = {
riskBudget: BUDGET_ONE_PERCENT,
useManualEntry: 0,
subLocation: 'mock city',
topLocation: 'mock state',
population: '1,000,000',
casesPastWeek: 2999, // will add 1 in pseudocount
casesIncreasingPercentage: 0,
positiveCasePercentage: 0,
// prevalance ratio = 1000 / (10 + i) * positivity_rate ** 0.5 + 2 = 25 * positivity_rate ** 0.5 + 2
prevalanceDataDate: dateAfterDay0(30),
unvaccinatedPrevalenceRatio: 2,
percentFullyVaccinated: 40,
averageFullyVaccinatedMultiplier: 0.1,
symptomsChecked: 'no',
}
// Variables that should be ignored for repeated/partner interactions.
const repeatedDontCare = {
setting: 'indoor',
distance: 'sixFt',
duration: 60,
theirMask: 'none',
yourMask: 'none',
voice: 'normal',
}
// Wrapper for calculate that just returns expectedValue
const calcValue = (data: CalculatorData) => {
const result = calculate(data)
if (!result) {
return null
}
return result.expectedValue
}
const testData: (partial: Partial<CalculatorData>) => CalculatorData = (
partial,
) => {
return {
...defaultValues,
...baseTestData,
...partial,
}
}
describe('calculateLocationPersonAverage', () => {
it.each`
positiveCasePercentage | result
${0} | ${PREVALENCE}
${4} | ${REPORTED_PREVALENCE * (0.04 ** 0.5 * 25 + 2)}
${6} | ${REPORTED_PREVALENCE * (0.06 ** 0.5 * 25 + 2)}
${16} | ${REPORTED_PREVALENCE * (0.16 ** 0.5 * 25 + 2)}
${100} | ${REPORTED_PREVALENCE * (25 + 2)}
${null} | ${REPORTED_PREVALENCE * (25 + 2)}
`(
'should compensate for underreporting, positiveCasePercentage = $positiveCasePercentage',
({ positiveCasePercentage, result }) => {
expect(
calculateLocationPersonAverage(testData({ positiveCasePercentage })),
).toBeCloseTo(result * 1e6)
},
)
it.each`
day | result
${0} | ${REPORTED_PREVALENCE * ((0.25 ** 0.5 * 1000) / 10 + 2)}
${25} | ${REPORTED_PREVALENCE * ((0.25 ** 0.5 * 1000) / 35 + 2)}
${50} | ${REPORTED_PREVALENCE * ((0.25 ** 0.5 * 1000) / 60 + 2)}
${300} | ${REPORTED_PREVALENCE * ((0.25 ** 0.5 * 1000) / 310 + 2)}
`(
'should reduce the effect of positiveCasePercentage as 1000 / (days + 10), days = $day',
({ day, result }) => {
expect(
calculateLocationPersonAverage(
testData({
positiveCasePercentage: 25,
prevalanceDataDate: dateAfterDay0(day),
}),
),
).toBeCloseTo(result * 1e6)
},
)
it.each`
casesIncreasingPercentage | result
${0} | ${PREVALENCE}
${-20} | ${PREVALENCE}
${10} | ${PREVALENCE * 1.1}
${50} | ${PREVALENCE * 1.5}
${100} | ${PREVALENCE * 2.0}
${200} | ${PREVALENCE * 2.0}
`(
'should compensate for time delay',
({ casesIncreasingPercentage, result }) => {
expect(
calculateLocationPersonAverage(testData({ casesIncreasingPercentage })),
).toBeCloseTo(result * 1e6)
},
)
})
describe('calculate', () => {
it('produces same results as by hand', () => {
const scenario = 'outdoorMasked2'
const data: CalculatorData = testData(prepopulated[scenario])
const response = calcValue(data)
// average * 2 people * outdoor * 1 hr * their mask * your mask
expect(response).toBeCloseTo(
((PREVALENCE * 2) / 20) * 0.14 * (1 / 3) * (2 / 3) * 1e6,
)
})
it.each`
scenario | result
${'outdoorMasked2'} | ${19}
${'indoorUnmasked2'} | ${1680}
${'1person_15minCarRide'} | ${210}
${'oneNightStand'} | ${3600}
${'liveInPartner_noContacts'} | ${42}
${'60minShopping'} | ${93}
${'60minShoppingFew'} | ${56}
${'60minShoppingCrowded'} | ${187}
${'planeRide'} | ${765}
${'planeRideMiddleSeatEmpty'} | ${373}
${'restaurantOutdoors'} | ${472.5}
${'restaurantIndoors'} | ${9450}
${'bar'} | ${54000}
${'largeOutdoorParty'} | ${2240}
${'smallIndoorParty25'} | ${63000}
${'outdoorMaskedWithCovidPositive'} | ${1555.6}
${'indoorUnmaskedWithCovidPositive'} | ${140000}
${'votingInPerson'} | ${6}
`('should return $result for $scenario', ({ scenario, result }) => {
const data: CalculatorData = testData(prepopulated[scenario])
expect(calcValue(data)).toBeCloseTo(result, 0)
})
it('should produce a self-consistent living alone risk profile', () => {
const data = testData({
...baseTestData,
riskProfile: 'average',
interaction: 'oneTime',
personCount: 10,
setting: 'indoor',
distance: 'sixFt',
duration: 60,
theirMask: 'basic',
yourMask: 'surgical',
voice: 'silent',
})
expect(calcValue(data)).toBeCloseTo(
PREVALENCE *
1e6 *
personRiskMultiplier({
riskProfile: RiskProfile['livingAlone'],
isHousemate: false,
symptomsChecked: 'no',
}),
)
})
it('should handle large risks', () => {
const data = testData({
riskProfile: 'hasCovid',
interaction: 'repeated',
personCount: 1,
...repeatedDontCare,
})
const oneTime = calculate(data)
expect(oneTime?.expectedValue).toBeCloseTo(0.4e6)
expect(oneTime?.lowerBound).toBeCloseTo(133333, 0)
// TODO(beshaya): Write a test that doesn't saturated upper bounds.
expect(oneTime?.upperBound).toBeCloseTo(1e6)
const twoTimes = calculate({ ...data, personCount: 2 })
// Should apply 1 - (1-p)^2 rather than multiplying by 2
expect(twoTimes?.expectedValue).toBeCloseTo(0.64e6)
expect(twoTimes?.lowerBound).toBeCloseTo(248888.8, 0)
expect(twoTimes?.upperBound).toBeCloseTo(1e6)
})
it.each`
profile | points
${RiskProfilesUnaffectedByVaccines.DECI_PERCENT} | ${1e6 / 1000 / 50}
${RiskProfilesUnaffectedByVaccines.ONE_PERCENT} | ${1e6 / 100 / 50}
${RiskProfilesUnaffectedByVaccines.HAS_COVID} | ${1e6}
`(
'should treat $profile as independent of prevalence',
({ profile, points }) => {
const data = testData({
...baseTestData,
...repeatedDontCare,
riskProfile: profile,
interaction: 'repeated',
personCount: 1,
})
const expected = points * housemateMult
expect(calcValue(data)).toBeCloseTo(expected)
expect(
calcValue({
...data,
positiveCasePercentage: baseTestData.positiveCasePercentage * 10,
}),
).toBeCloseTo(expected)
},
)
describe('Interaction: workplace', () => {
const workplace = testData({
...baseTestData,
...repeatedDontCare,
riskProfile: 'average',
interaction: 'workplace',
personCount: 1,
})
it('should behave the same as a one time interaction', () => {
const oneTime: CalculatorData = {
...workplace,
interaction: 'oneTime',
}
expect(calcValue(workplace)).toEqual(calcValue(oneTime))
})
})
describe('Interaction: partner', () => {
const partner = testData(prepopulated['liveInPartner_noContacts'])
const unvaccinatedPartner = { ...partner, theirVaccine: 'unvaccinated' }
const vaccinatedPartner = { ...partner, theirVaccine: 'vaccinated' }
it('should not be affected by these multipliers', () => {
const bonuses: CalculatorData = {
...unvaccinatedPartner,
setting: 'outdoor',
distance: 'tenFt',
duration: 1,
theirMask: 'filtered',
yourMask: 'filtered',
voice: 'silent',
}
expect(calcValue(unvaccinatedPartner)).toEqual(calcValue(bonuses))
})
it('should apply 60% risk for an unvaccinated partner', () => {
expect(calcValue(unvaccinatedPartner)).toBeCloseTo(
PREVALENCE *
0.6 *
1e6 *
personRiskMultiplier({
riskProfile: RiskProfile['livingAlone'],
isHousemate: false,
symptomsChecked: 'no',
}),
)
})
it('should apply 30% risk for a partner with unknown vax status', () => {
expect(calcValue(partner)).toBeCloseTo(
0.5 * (calcValue(unvaccinatedPartner) || -1),
)
})
it('should apply 6% risk for a vaccinated partner', () => {
expect(calcValue(vaccinatedPartner)).toBeCloseTo(
0.1 * (calcValue(unvaccinatedPartner) || -1),
)
})
})
describe('Interaction: housemate', () => {
const base = testData({
riskProfile: 'average',
interaction: 'repeated',
personCount: 1,
})
const housemate: CalculatorData = {
...base,
setting: 'indoor',
distance: 'normal',
duration: 120,
theirMask: 'none',
yourMask: 'none',
voice: 'normal',
}
it('should not be affected by multipliers', () => {
const bonuses: CalculatorData = {
...base,
setting: 'outdoor',
distance: 'tenFt',
duration: 1,
theirMask: 'filtered',
yourMask: 'filtered',
voice: 'silent',
}
expect(calcValue(housemate)).toBeCloseTo(calcValue(bonuses)!)
})
it('should apply 40% risk', () => {
// average * 0.4
expect(calcValue(housemate)).toBeCloseTo(PREVALENCE * 0.4 * 1e6)
})
it('should remove the risk from the user for risk profiles including housemates', () => {
const housemateData = testData({
riskProfile: 'closedPod4',
interaction: 'repeated',
})
const equivalentOneTime = testData({
riskProfile: 'closdedPod4',
interaction: 'oneTime',
duration: 60 * 5,
})
expect(calcValue(housemateData)).toBeCloseTo(
(calcValue(equivalentOneTime)! * (1 + 0.45 * 2)) / (1 + 0.45 / 3),
)
})
})
describe('Distance: intimate', () => {
const indoorIntimate: CalculatorData = testData(
prepopulated['oneNightStand'],
)
it('should not give a bonus for outdoors', () => {
const outdoorIntimate: CalculatorData = {
...indoorIntimate,
setting: 'outdoor',
}
expect(calcValue(outdoorIntimate)).toEqual(calcValue(indoorIntimate))
})
it('should not give a bonus for masks', () => {
const unmaskedIntimate = testData({
...prepopulated['oneNightStand'],
yourMask: 'none',
theirMask: 'none',
})
const maskedIntimate: CalculatorData = {
...unmaskedIntimate,
yourMask: 'n95',
theirMask: 'filtered',
}
expect(calcValue(unmaskedIntimate)).toEqual(calcValue(maskedIntimate))
})
it('should be at least 12% (20 min) transfer risk.', () => {
const twentyMinuteIntimate: CalculatorData = {
...indoorIntimate,
duration: 20,
}
const oneMinuteIntimate: CalculatorData = {
...twentyMinuteIntimate,
duration: 1,
}
const thirtyMinuteIntimate: CalculatorData = {
...twentyMinuteIntimate,
duration: 30,
}
expect(calcValue(oneMinuteIntimate)).toEqual(
calcValue(twentyMinuteIntimate),
)
expect(calcValue(thirtyMinuteIntimate)).toBeCloseTo(
calcValue(twentyMinuteIntimate)! * 1.5,
)
})
it('should not exceed live-in-partner risk,', () => {
const tenHourIntimate: CalculatorData = {
...indoorIntimate,
duration: 600,
}
const partnerIntimate: CalculatorData = {
...indoorIntimate,
interaction: 'partner',
}
expect(calcValue(tenHourIntimate)).toBeCloseTo(
calcValue(partnerIntimate)!,
)
})
it('should not apply talking multiplier', () => {
const kissingTalking = testData({
...prepopulated['oneNightStand'],
voice: 'normal',
})
const kissingSilent: CalculatorData = {
...kissingTalking,
voice: 'silent',
}
const kissingLoudTalking: CalculatorData = {
...kissingTalking,
voice: 'loud',
}
expect(calcValue(kissingTalking)).toEqual(calcValue(kissingSilent))
expect(calcValue(kissingTalking)).toEqual(calcValue(kissingLoudTalking))
})
})
describe('Distance: close', () => {
it.each`
duration | setting | result | scenario
${120} | ${'indoor'} | ${3360} | ${'should be 18% per hour'}
${1} | ${'indoor'} | ${3360 / 120} | ${'should not have a minimum risk'}
${120} | ${'outdoor'} | ${3360} | ${'should not give an outdoors bonus'}
`(' $scenario', ({ duration, setting, result }) => {
const data: CalculatorData = testData({
personCount: 1,
interaction: 'oneTime',
riskProfile: 'average',
distance: 'close',
theirMask: 'none',
yourMask: 'none',
voice: 'normal',
setting,
duration,
})
expect(calcValue(data)).toBeCloseTo(result)
})
})
describe('yourVaccine', () => {
const noVaccineScenario = testData(prepopulated['1person_15minCarRide'])
const noVaccineValue = calcValue(noVaccineScenario)
it.each`
type | doses | multiplier
${'pfizer'} | ${0} | ${1}
${'pfizer'} | ${1} | ${0.76}
${'pfizer'} | ${2} | ${0.17}
${'moderna'} | ${0} | ${1}
${'moderna'} | ${1} | ${0.76}
${'moderna'} | ${2} | ${0.17}
${'astraZeneca'} | ${0} | ${1}
${'astraZeneca'} | ${1} | ${0.76}
${'astraZeneca'} | ${2} | ${0.47}
${'johnson'} | ${0} | ${1}
${'johnson'} | ${1} | ${0.36}
`(
'$doses doses of $type should give a multiplier of $multiplier',
({ type, doses, multiplier }) => {
const data: CalculatorData = {
...noVaccineScenario,
yourVaccineDoses: doses,
yourVaccineType: type,
}
expect(calcValue(data)! / noVaccineValue!).toBeCloseTo(multiplier)
},
)
it('Should apply vaccine reduction after activity max', () => {
const noVaccineLongScenario = { ...noVaccineScenario, duration: 100000 }
const vaccineLongScenario = {
...noVaccineLongScenario,
yourVaccineDoses: 2,
yourVaccineType: 'pfizer',
}
expect(calcValue(vaccineLongScenario)).toBeCloseTo(
calcValue(noVaccineLongScenario)! * 0.17,
)
})
it('Should apply vaccine multiplier to housemates activities', () => {
const noVaccineHousemate: CalculatorData = {
...noVaccineScenario,
interaction: 'repeated',
}
const vaccineHousemate = {
...noVaccineHousemate,
yourVaccineDoses: 2,
yourVaccineType: 'pfizer',
}
expect(calcValue(vaccineHousemate)).toBeCloseTo(
calcValue(noVaccineHousemate)! * 0.17,
)
})
it('Should apply vaccine multiplier to partner activities', () => {
const noVaccinePartner = testData(
prepopulated['liveInPartner_noContacts'],
)
const vaccinePartner = {
...noVaccinePartner,
yourVaccineDoses: 2,
yourVaccineType: 'pfizer',
}
expect(calcValue(vaccinePartner)).toBeCloseTo(
calcValue(noVaccinePartner)! * 0.17,
)
})
})
describe('theirVaccine', () => {
const noVaccineScenario = testData(prepopulated['1person_15minCarRide'])
const defaultValue = calcValue(noVaccineScenario)!
it('Should use "undefined" by default', () => {
expect(noVaccineScenario.theirVaccine).toEqual('undefined')
})
it('Should increase risk for unvaccinated people', () => {
expect(
calcValue({ ...noVaccineScenario, theirVaccine: 'unvaccinated' }),
).toEqual(defaultValue * 2)
})
it('Should decrease risk for vaccinated people', () => {
expect(
calcValue({ ...noVaccineScenario, theirVaccine: 'vaccinated' }),
).toEqual(defaultValue * 2 * 0.1)
})
})
describe('percentFullyVaccinated', () => {
const defaultScenario = {
...testData(prepopulated['1person_15minCarRide']),
averageFullyVaccinatedMultiplier: 0.4,
percentFullyVaccinated: 40,
unvaccinatedPrevalenceRatio: null,
}
const defaultUnvaccinatedPrevalenceRatio = 1 / (0.4 * 0.4 + 0.6)
it.each`
theirVaccine
${'vaccinated'}
${'unvaccinated'}
`(
'Should decrease risk for lower vaccination rate when interacting with $theirVaccine people',
({ theirVaccine }) => {
const defaultValue = calcValue({ ...defaultScenario, theirVaccine })!
const value = calcValue({
...defaultScenario,
theirVaccine,
percentFullyVaccinated: defaultScenario.percentFullyVaccinated! / 2,
})
const expectedUnvaccinatedPrevalenceRatio = 1 / (0.4 * 0.2 + 0.8)
expect(value).toBeCloseTo(
defaultValue *
(expectedUnvaccinatedPrevalenceRatio /
defaultUnvaccinatedPrevalenceRatio),
)
},
)
it.each`
theirVaccine
${'vaccinated'}
${'unvaccinated'}
`(
'Should increase risk for higher vaccination rate when interacting with $theirVaccine people',
({ theirVaccine }) => {
const defaultValue = calcValue({ ...defaultScenario, theirVaccine })!
const value = calcValue({
...defaultScenario,
theirVaccine,
percentFullyVaccinated: defaultScenario.percentFullyVaccinated! * 2,
})
const expectedUnvaccinatedPrevalenceRatio = 1 / (0.4 * 0.8 + 0.2)
expect(value).toBeCloseTo(
defaultValue *
(expectedUnvaccinatedPrevalenceRatio /
defaultUnvaccinatedPrevalenceRatio),
)
},
)
it('Should not change risk if theirVaccine is undefined', () => {
const defaultValue = calcValue({
...defaultScenario,
theirVaccine: 'undefined',
})!
const value = calcValue({
...defaultScenario,
theirVaccine: 'undefined',
percentFullyVaccinated: defaultScenario.percentFullyVaccinated! * 2,
})
expect(value).toEqual(defaultValue)
})
it('Should not change risk if unvaccinatedPrevalenceRatio is available', () => {
const defaultValue = calcValue({
...defaultScenario,
theirVaccine: 'vaccinated',
unvaccinatedPrevalenceRatio: 0.2,
})!
const value = calcValue({
...defaultScenario,
theirVaccine: 'vaccinated',
unvaccinatedPrevalenceRatio: 0.2,
percentFullyVaccinated: defaultScenario.percentFullyVaccinated! * 2,
})
expect(value).toEqual(defaultValue)
})
})
}) | the_stack |
import "jest-extended";
import { Console } from "@arkecosystem/core-test-framework";
import { Command } from "@packages/core/src/commands/network-generate";
import envPaths from "env-paths";
import fs from "fs-extra";
import { join } from "path";
import prompts from "prompts";
const paths = envPaths("myn", { suffix: "core" });
const configCore = join(paths.config, "testnet");
const configCrypto = join(configCore, "crypto");
let cli;
beforeEach(() => (cli = new Console()));
afterEach(() => jest.resetAllMocks());
describe("GenerateCommand", () => {
it("should generate a new configuration", async () => {
const existsSync = jest.spyOn(fs, "existsSync").mockImplementation();
const ensureDirSync = jest.spyOn(fs, "ensureDirSync").mockImplementation();
const writeJSONSync = jest.spyOn(fs, "writeJSONSync").mockImplementation();
const writeFileSync = jest.spyOn(fs, "writeFileSync").mockImplementation();
await cli
.withFlags({
network: "testnet",
premine: "120000000000",
delegates: "47",
blocktime: "9",
maxTxPerBlock: "122",
maxBlockPayload: "123444",
rewardHeight: "23000",
rewardAmount: "66000",
pubKeyHash: "168",
wif: "27",
token: "myn",
symbol: "my",
explorer: "myex.io",
distribute: "true",
})
.execute(Command);
expect(existsSync).toHaveBeenCalledWith(configCore);
expect(existsSync).toHaveBeenCalledWith(configCrypto);
expect(ensureDirSync).toHaveBeenCalledWith(configCore);
expect(ensureDirSync).toHaveBeenCalledWith(configCrypto);
expect(writeJSONSync).toHaveBeenCalledTimes(8); // 5x Core + 2x Crypto + App
expect(writeFileSync).toHaveBeenCalledTimes(2); // index.ts && .env
expect(writeJSONSync).toHaveBeenCalledWith(
expect.stringContaining("crypto/milestones.json"),
[
{
height: 1,
reward: "0",
activeDelegates: 47,
blocktime: 9,
block: {
version: 0,
idFullSha256: true,
maxTransactions: 122,
maxPayload: 123444,
},
epoch: expect.any(String),
fees: {
staticFees: {
transfer: 10000000,
secondSignature: 500000000,
delegateRegistration: 2500000000,
vote: 100000000,
multiSignature: 500000000,
ipfs: 500000000,
multiPayment: 10000000,
delegateResignation: 2500000000,
htlcLock: 10000000,
htlcClaim: 0,
htlcRefund: 0,
},
},
vendorFieldLength: 255,
multiPaymentLimit: 256,
aip11: true,
},
{
height: 23000,
reward: 66000,
},
],
{ spaces: 4 },
);
});
it("should throw if the core configuration destination already exists", async () => {
jest.spyOn(fs, "existsSync").mockReturnValueOnce(true);
await expect(
cli
.withFlags({
network: "testnet",
premine: "120000000000",
delegates: "47",
blocktime: "9",
maxTxPerBlock: "122",
maxBlockPayload: "123444",
rewardHeight: "23000",
rewardAmount: "66000",
pubKeyHash: "168",
wif: "27",
token: "myn",
symbol: "my",
explorer: "myex.io",
distribute: "true",
})
.execute(Command),
).rejects.toThrow(`${configCore} already exists.`);
});
it("should throw if the crypto configuration destination already exists", async () => {
jest.spyOn(fs, "existsSync").mockReturnValueOnce(false).mockReturnValueOnce(true);
await expect(
cli
.withFlags({
network: "testnet",
premine: "120000000000",
delegates: "47",
blocktime: "9",
maxTxPerBlock: "122",
maxBlockPayload: "123444",
rewardHeight: "23000",
rewardAmount: "66000",
pubKeyHash: "168",
wif: "27",
token: "myn",
symbol: "my",
explorer: "myex.io",
distribute: "true",
})
.execute(Command),
).rejects.toThrow(`${configCrypto} already exists.`);
});
it("should throw if the properties are not confirmed", async () => {
prompts.inject([
"testnet",
"120000000000",
"47",
"9",
"122",
"123444",
"23000",
"66000",
"168",
"27",
"myn",
"my",
"myex.io",
true,
false,
]);
await expect(cli.execute(Command)).rejects.toThrow("You'll need to confirm the input to continue.");
});
it("should throw if string property is undefined", async () => {
prompts.inject([
"undefined",
"120000000000",
"47",
"9",
"122",
"123444",
"23000",
"66000",
"168",
"27",
"myn",
"m",
"myex.io",
true,
true,
]);
await expect(cli.execute(Command)).rejects.toThrow("Flag network is required.");
});
it("should throw if numeric property is Nan", async () => {
prompts.inject([
"testnet",
"120000000000",
"47",
"9",
"122",
"123444",
"23000",
"66000",
"168",
Number.NaN,
"myn",
"m",
"myex.io",
true,
true,
]);
await expect(cli.execute(Command)).rejects.toThrow("Flag wif is required.");
});
it("should generate a new configuration if the properties are confirmed", async () => {
const existsSync = jest.spyOn(fs, "existsSync").mockImplementation();
const ensureDirSync = jest.spyOn(fs, "ensureDirSync").mockImplementation();
const writeJSONSync = jest.spyOn(fs, "writeJSONSync").mockImplementation();
const writeFileSync = jest.spyOn(fs, "writeFileSync").mockImplementation();
prompts.inject([
"testnet",
"120000000000",
"47",
"9",
"122",
"123444",
"23000",
"66000",
168,
"27",
"myn",
"my",
"myex.io",
true,
true,
]);
await cli.execute(Command);
expect(existsSync).toHaveBeenCalledWith(configCore);
expect(existsSync).toHaveBeenCalledWith(configCrypto);
expect(ensureDirSync).toHaveBeenCalledWith(configCore);
expect(ensureDirSync).toHaveBeenCalledWith(configCrypto);
expect(writeJSONSync).toHaveBeenCalledTimes(8); // 5x Core + 2x Crypto + App
expect(writeFileSync).toHaveBeenCalledTimes(2); // index.ts && .env
});
it("should generate a new configuration if the properties are confirmed and distribute is set to false", async () => {
const existsSync = jest.spyOn(fs, "existsSync").mockImplementation();
const ensureDirSync = jest.spyOn(fs, "ensureDirSync").mockImplementation();
const writeJSONSync = jest.spyOn(fs, "writeJSONSync").mockImplementation();
const writeFileSync = jest.spyOn(fs, "writeFileSync").mockImplementation();
prompts.inject([
"testnet",
"120000000000",
"47",
"9",
"122",
"123444",
"23000",
"66000",
168,
"27",
"myn",
"my",
"myex.io",
false,
true,
]);
await cli.withFlags({ distribute: false }).execute(Command);
expect(existsSync).toHaveBeenCalledWith(configCore);
expect(existsSync).toHaveBeenCalledWith(configCrypto);
expect(ensureDirSync).toHaveBeenCalledWith(configCore);
expect(ensureDirSync).toHaveBeenCalledWith(configCrypto);
expect(writeJSONSync).toHaveBeenCalledTimes(8); // 5x Core + 2x Crypto + App
expect(writeFileSync).toHaveBeenCalledTimes(2); // index.ts && .env
});
it("should generate a new configuration with additional flags", async () => {
const existsSync = jest.spyOn(fs, "existsSync").mockImplementation();
const ensureDirSync = jest.spyOn(fs, "ensureDirSync").mockImplementation();
const writeJSONSync = jest.spyOn(fs, "writeJSONSync").mockImplementation();
const writeFileSync = jest.spyOn(fs, "writeFileSync").mockImplementation();
await cli
.withFlags({
network: "testnet",
premine: "120000000000",
delegates: "47",
blocktime: "9",
maxTxPerBlock: "122",
maxBlockPayload: "123444",
rewardHeight: "23000",
rewardAmount: "66000",
pubKeyHash: "168",
vendorFieldLength: "64",
wif: "27",
token: "myn",
symbol: "my",
explorer: "myex.io",
distribute: "true",
epoch: "2020-11-04T00:00:00.000Z",
htlcEnabled: true,
feeStaticTransfer: 1,
feeStaticSecondSignature: 2,
feeStaticDelegateRegistration: 3,
feeStaticVote: 4,
feeStaticMultiSignature: 5,
feeStaticIpfs: 6,
feeStaticMultiPayment: 7,
feeStaticDelegateResignation: 8,
feeStaticHtlcLock: 9,
feeStaticHtlcClaim: 10,
feeStaticHtlcRefund: 11,
feeDynamicEnabled: true,
feeDynamicMinFeePool: 100,
feeDynamicMinFeeBroadcast: 200,
feeDynamicBytesTransfer: 1,
feeDynamicBytesSecondSignature: 2,
feeDynamicBytesDelegateRegistration: 3,
feeDynamicBytesVote: 4,
feeDynamicBytesMultiSignature: 5,
feeDynamicBytesIpfs: 6,
feeDynamicBytesMultiPayment: 7,
feeDynamicBytesDelegateResignation: 8,
feeDynamicBytesHtlcLock: 9,
feeDynamicBytesHtlcClaim: 10,
feeDynamicBytesHtlcRefund: 11,
coreDBHost: "127.0.0.1",
coreDBPort: 3001,
coreDBUsername: "username",
coreDBPassword: "password",
coreDBDatabase: "database",
coreP2PPort: 3002,
coreAPIPort: 3003,
coreWebhooksPort: 3004,
coreMonitorPort: 3005,
peers: "127.0.0.1:4444,127.0.0.2",
})
.execute(Command);
expect(existsSync).toHaveBeenCalledWith(configCore);
expect(existsSync).toHaveBeenCalledWith(configCrypto);
expect(ensureDirSync).toHaveBeenCalledWith(configCore);
expect(ensureDirSync).toHaveBeenCalledWith(configCrypto);
expect(writeJSONSync).toHaveBeenCalledTimes(8); // 5x Core + 2x Crypto + App
expect(writeFileSync).toHaveBeenCalledTimes(2); // index.ts && .env
expect(writeJSONSync).toHaveBeenCalledWith(
expect.stringContaining("crypto/milestones.json"),
[
{
height: 1,
reward: "0",
activeDelegates: 47,
blocktime: 9,
block: {
version: 0,
idFullSha256: true,
maxTransactions: 122,
maxPayload: 123444,
},
epoch: "2020-11-04T00:00:00.000Z",
fees: {
staticFees: {
transfer: 1,
secondSignature: 2,
delegateRegistration: 3,
vote: 4,
multiSignature: 5,
ipfs: 6,
multiPayment: 7,
delegateResignation: 8,
htlcLock: 9,
htlcClaim: 10,
htlcRefund: 11,
},
},
vendorFieldLength: 64,
multiPaymentLimit: 256,
htlcEnabled: true,
aip11: true,
},
{
height: 23000,
reward: 66000,
},
],
{ spaces: 4 },
);
});
it("should generate a new configuration using force option", async () => {
const existsSync = jest.spyOn(fs, "existsSync").mockImplementation();
const ensureDirSync = jest.spyOn(fs, "ensureDirSync").mockImplementation();
const writeJSONSync = jest.spyOn(fs, "writeJSONSync").mockImplementation();
const writeFileSync = jest.spyOn(fs, "writeFileSync").mockImplementation();
await cli
.withFlags({
token: "myn",
force: true,
})
.execute(Command);
expect(existsSync).toHaveBeenCalledWith(configCore);
expect(existsSync).toHaveBeenCalledWith(configCrypto);
expect(ensureDirSync).toHaveBeenCalledWith(configCore);
expect(ensureDirSync).toHaveBeenCalledWith(configCrypto);
expect(writeJSONSync).toHaveBeenCalledTimes(8); // 5x Core + 2x Crypto + App
expect(writeFileSync).toHaveBeenCalledTimes(2); // index.ts && .env
});
it("should overwrite if overwriteConfig is set", async () => {
const existsSync = jest.spyOn(fs, "existsSync").mockImplementation();
const ensureDirSync = jest.spyOn(fs, "ensureDirSync").mockImplementation();
const writeJSONSync = jest.spyOn(fs, "writeJSONSync").mockImplementation();
const writeFileSync = jest.spyOn(fs, "writeFileSync").mockImplementation();
await cli
.withFlags({
network: "testnet",
premine: "120000000000",
delegates: "47",
blocktime: "9",
maxTxPerBlock: "122",
maxBlockPayload: "123444",
rewardHeight: "23000",
rewardAmount: "66000",
pubKeyHash: "168",
wif: "27",
token: "myn",
symbol: "my",
explorer: "myex.io",
distribute: "true",
overwriteConfig: "true",
})
.execute(Command);
expect(existsSync).not.toHaveBeenCalled();
expect(existsSync).not.toHaveBeenCalled();
expect(ensureDirSync).toHaveBeenCalledWith(configCore);
expect(ensureDirSync).toHaveBeenCalledWith(configCrypto);
expect(writeJSONSync).toHaveBeenCalledTimes(8); // 5x Core + 2x Crypto + App
expect(writeFileSync).toHaveBeenCalledTimes(2); // index.ts && .env
});
it("should generate crypto on custom path", async () => {
const existsSync = jest.spyOn(fs, "existsSync").mockImplementation();
const ensureDirSync = jest.spyOn(fs, "ensureDirSync").mockImplementation();
const writeJSONSync = jest.spyOn(fs, "writeJSONSync").mockImplementation();
const writeFileSync = jest.spyOn(fs, "writeFileSync").mockImplementation();
await cli
.withFlags({
network: "testnet",
premine: "120000000000",
delegates: "47",
blocktime: "9",
maxTxPerBlock: "122",
maxBlockPayload: "123444",
rewardHeight: "23000",
rewardAmount: "66000",
pubKeyHash: "168",
wif: "27",
token: "myn",
symbol: "my",
explorer: "myex.io",
distribute: "true",
configPath: "/path/to/config",
})
.execute(Command);
expect(existsSync).toHaveBeenCalledWith("/path/to/config/testnet");
expect(existsSync).toHaveBeenCalledWith("/path/to/config/testnet/crypto");
expect(ensureDirSync).toHaveBeenCalledWith("/path/to/config/testnet");
expect(ensureDirSync).toHaveBeenCalledWith("/path/to/config/testnet/crypto");
expect(writeJSONSync).toHaveBeenCalledTimes(8); // 5x Core + 2x Crypto + App
expect(writeFileSync).toHaveBeenCalledTimes(2); // index.ts && .env
});
it("should allow empty peers", async () => {
const existsSync = jest.spyOn(fs, "existsSync").mockImplementation();
const ensureDirSync = jest.spyOn(fs, "ensureDirSync").mockImplementation();
const writeJSONSync = jest.spyOn(fs, "writeJSONSync").mockImplementation();
const writeFileSync = jest.spyOn(fs, "writeFileSync").mockImplementation();
await cli
.withFlags({
network: "testnet",
premine: "120000000000",
delegates: "47",
blocktime: "9",
maxTxPerBlock: "122",
maxBlockPayload: "123444",
rewardHeight: "23000",
rewardAmount: "66000",
pubKeyHash: "168",
wif: "27",
token: "myn",
symbol: "my",
explorer: "myex.io",
distribute: "true",
peers: "",
})
.execute(Command);
expect(existsSync).toHaveBeenCalledWith(configCore);
expect(existsSync).toHaveBeenCalledWith(configCrypto);
expect(ensureDirSync).toHaveBeenCalledWith(configCore);
expect(ensureDirSync).toHaveBeenCalledWith(configCrypto);
expect(writeJSONSync).toHaveBeenCalledTimes(8); // 5x Core + 2x Crypto + App
expect(writeFileSync).toHaveBeenCalledTimes(2); // index.ts && .env
});
}); | the_stack |
import { FILL_RULE, Path, PATH } from './utils/Path';
import { SVGGraphicsNode } from './SVGGraphicsNode';
import { buildPath } from './utils/buildPath';
import { graphicsUtils } from '@pixi/graphics';
import dPathParser from 'd-path-parser';
graphicsUtils.FILL_COMMANDS[PATH] = buildPath;
/**
* Draws SVG <path /> elements.
*
* @public
*/
export class SVGPathNode extends SVGGraphicsNode
{
private currentPath2: Path;
private startPath(): void
{
if (this.currentPath2)
{
const pts = this.currentPath2.points;
if (pts.length > 0)
{
this.currentPath2.closeContour();
}
}
else
{
this.currentPath2 = new Path();
}
}
private finishPath(): void
{
if (this.currentPath2)
{
this.currentPath2.closeContour();
}
}
// @ts-expect-error
get currentPath(): any
{
return this.currentPath2;
}
set currentPath(nothing: any)
{
if (nothing)
{
throw new Error('currentPath cannot be set');
}
// readonly
}
closePath(): any
{
this.currentPath2.points.push(this.currentPath2.points[0], this.currentPath2.points[1])
this.finishPath();
return this;
}
checkPath(): void
{
if (this.currentPath2.points.find((e) => isNaN(e)) !== undefined)
{
throw new Error('NaN is bad');
}
}
// Redirect moveTo, lineTo, ... onto paths!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! :P
startPoly = this.startPath;
finishPoly = this.finishPath;
/**
* Embeds the `SVGPathElement` into this node.
*
* @param element - the path to draw
*/
embedPath(element: SVGPathElement): this
{
const d = element.getAttribute('d');
// Parse path commands using d-path-parser. This is an inefficient solution that causes excess memory allocation
// and should be optimized in the future.
const commands = dPathParser(d.trim());
// Current point
let x = 0;
let y = 0;
for (let i = 0, j = commands.length; i < j; i++)
{
const lastCommand = commands[i - 1];
const command = commands[i];
if (isNaN(x) || isNaN(y))
{
throw new Error('Data corruption');
}
// Taken from: https://github.com/bigtimebuddy/pixi-svg/blob/main/src/SVG.js
// Copyright Matt Karl
switch (command.code)
{
case 'm': {
this.moveTo(
x += command.end.x,
y += command.end.y,
);
break;
}
case 'M': {
this.moveTo(
x = command.end.x,
y = command.end.y,
);
break;
}
case 'H': {
this.lineTo(x = command.value, y);
break;
}
case 'h': {
this.lineTo(x += command.value, y);
break;
}
case 'V': {
this.lineTo(x, y = command.value);
break;
}
case 'v': {
this.lineTo(x, y += command.value);
break;
}
case 'z':
case 'Z': {
x = this.currentPath2?.points[0] || 0;
y = this.currentPath2?.points[1] || 0;
this.closePath();
break;
}
case 'L': {
this.lineTo(
x = command.end.x,
y = command.end.y,
);
break;
}
case 'l': {
this.lineTo(
x += command.end.x,
y += command.end.y,
);
break;
}
case 'C': {
this.bezierCurveTo(
command.cp1.x,
command.cp1.y,
command.cp2.x,
command.cp2.y,
x = command.end.x,
y = command.end.y,
);
break;
}
case 'c': {
const currX = x;
const currY = y;
this.bezierCurveTo(
currX + command.cp1.x,
currY + command.cp1.y,
currX + command.cp2.x,
currY + command.cp2.y,
x += command.end.x,
y += command.end.y,
);
break;
}
case 's':
case 'S': {
const cp1 = { x, y };
const lastCode = commands[i - 1] ? commands[i - 1].code : null;
if (i > 0 && (lastCode === 's' || lastCode === 'S' || lastCode === 'c' || lastCode === 'C'))
{
const lastCommand = commands[i - 1];
const lastCp2 = { ...(lastCommand.cp2 || lastCommand.cp) };
if (commands[i - 1].relative)
{
lastCp2.x += (x - lastCommand.end.x);
lastCp2.y += (y - lastCommand.end.y);
}
cp1.x = (2 * x) - lastCp2.x;
cp1.y = (2 * y) - lastCp2.y;
}
const cp2 = { x: command.cp.x , y: command.cp.y };
if (command.relative)
{
cp2.x += x;
cp2.y += y;
x += command.end.x;
y += command.end.y;
}
else
{
x = command.end.x;
y = command.end.y;
}
this.bezierCurveTo(
cp1.x,
cp1.y,
cp2.x,
cp2.y,
x,
y,
);
break;
}
case 'q': {
const currX = x;
const currY = y;
this.quadraticCurveTo(
currX + command.cp.x,
currY + command.cp.y,
x += command.end.x,
y += command.end.y,
);
break;
}
case 'Q': {
this.quadraticCurveTo(
command.cp.x,
command.cp.y,
x = command.end.x,
y = command.end.y,
);
break;
}
case 'A':
this.ellipticArcTo(
x = command.end.x,
y = command.end.y,
command.radii.x,
command.radii.y,
(command.rotation || 0) * Math.PI / 180,
!command.clockwise,
command.large,
);
break;
case 'a':
this.ellipticArcTo(
x += command.end.x,
y += command.end.y,
command.radii.x,
command.radii.y,
(command.rotation || 0) * Math.PI / 180,
!command.clockwise,
command.large,
);
break;
case 't':
case 'T': {
let cx: number;
let cy: number;
if (lastCommand && lastCommand.cp)
{
let lcx = lastCommand.cp.x;
let lcy = lastCommand.cp.y;
if (lastCommand.relative)
{
const lx = x - lastCommand.end.x;
const ly = y - lastCommand.end.y;
lcx += lx;
lcy += ly;
}
cx = (2 * x) - lcx;
cy = (2 * y) - lcy;
}
else
{
cx = x;
cy = y;
}
if (command.code === 't')
{
this.quadraticCurveTo(
cx,
cy,
x += command.end.x,
y += command.end.y,
);
}
else
{
this.quadraticCurveTo(
cx,
cy,
x = command.end.x,
y = command.end.y,
);
}
break;
}
default: {
console.warn('[PIXI.SVG] Draw command not supported:', command.code, command);
break;
}
}
}
if (this.currentPath2)
{
this.currentPath2.fillRule = element.getAttribute('fill-rule') as FILL_RULE || this.currentPath2.fillRule;
this.drawShape(this.currentPath2 as any);
this.currentPath2 = null;
}
return this;
}
} | the_stack |
import * as React from 'react';
import { debounce, distance, styled, themed, StandardProps } from 'precise-ui';
import PdfJs from '../utils/PdfJs';
import { PageViewMode, PageType } from '../types/Page';
import { PDFViewerPage } from './PDFViewerPage';
import { dataURItoUint8Array, isDataURI } from '../utils/hacks';
import { PDFViewerToolbar, ToolbarLabelProps } from './PDFViewerToolbar';
import { PDFViewerTouchToolbar } from './PDFViewerTouchToolbar';
import { PDFWorker } from './PDFWorker';
interface FullscreenableElement {
fullscreen: boolean;
}
const DocumentWrapper = styled.div`
background-color: #fff;
position: relative;
width: 100%;
// Thanks chrome for Android for not calculating the viewport size correctly depending
// on whether you show or not the address bar. But no worries, we'll do it manually
// We also set 2 times the padding-top for those browsers without var or min compatibility
padding-top: 56.25%;
padding-top: min(56.25%, calc(var(--vh, 1vh) * 90)); /* 16:9 Aspect Ratio */
overflow: hidden;
${({ fullscreen }: FullscreenableElement) =>
fullscreen &&
`
padding-top: 0;
top: 0;
left: 0;
right: 0;
bottom: 0;
height: auto;
position: fixed;
z-index: 100500;
`};
`;
const Document = styled.div`
position: absolute;
top: 0;
left: 0;
bottom: 40px;
right: 0;
background-color: ${themed(({ theme = {} }: StandardProps) => theme.ui2)};
padding: ${distance.medium};
overflow: scroll;
touch-action: pan-x pan-y;
`;
const PageWrapper = styled.div`
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
`;
export interface PDFViewerProps {
/**
* URL to the file to be loaded
*/
url?: string;
/**
* Service workser URL
*/
workerUrl?: string;
/**
* Function event triggered when a document fully loads successfully
*
* @param document
*/
onLoadSuccess?(document: PdfJs.PdfDocument): void;
/**
* Function event triggered when a document fails to load
*
* @param error
*/
onLoadError?(error: unknown): void;
/**
* Function event triggered when the current page changes
*
* @param currentPage
* @param totalPages
*/
onPageChanged?(currentPage: number, totalPages: number): void;
/**
* Optional object containing all labels used in the toolbar, in case localization is needed.
*/
toolbarLabels?: ToolbarLabelProps;
/**
* Disable text selection for rendered pages
*/
disableSelect?: boolean;
}
// const defaultWorkerUrl = 'https://unpkg.com/pdfjs-dist@2.4.456/build/pdf.worker.min.js';
const defaultWorkerUrl = 'https://unpkg.com/pdfjs-dist@2.4.456/es5/build/pdf.worker.js';
/**
* The `Document` is a wrapper to load PDFs and render all the pages
*/
export const PDFViewer: React.FC<PDFViewerProps> = props => {
const { url, workerUrl = defaultWorkerUrl } = props;
const documentRef = React.useRef<HTMLDivElement>();
const [document, setDocument] = React.useState<PdfJs.PdfDocument>();
const [loading, setLoading] = React.useState(true);
const [pages, setPages] = React.useState<Array<PageType>>([]);
const [currentPage, setCurrentPage] = React.useState(1);
const [currentViewMode, setCurrentViewMode] = React.useState<PageViewMode>(PageViewMode.DEFAULT);
const [currentScale, setCurrentScale] = React.useState(1);
const [fullscreen, setFullscreen] = React.useState(false);
const deviceAgent = navigator.userAgent.toLowerCase();
const isTouchDevice =
deviceAgent.match(/(iphone|ipod|ipad)/) ||
deviceAgent.match(/(android)/) ||
deviceAgent.match(/(iemobile)/) ||
deviceAgent.match(/iphone/i) ||
deviceAgent.match(/ipad/i) ||
deviceAgent.match(/ipod/i) ||
deviceAgent.match(/blackberry/i) ||
deviceAgent.match(/bada/i) ||
(deviceAgent.match(/Mac/) && navigator.maxTouchPoints && navigator.maxTouchPoints > 2); // iPad PRO, apple thinks it should behave like a desktop Safari, and so here we are...
/**
* Every time a new file is set we load the new document
*/
React.useEffect(() => {
loadDocument();
}, [url]);
/**
* Effect to re-calculate page size and re-render after entering / exiting fullscreen
*/
React.useEffect(() => {
zoomToPageView(pages[currentPage], currentViewMode);
}, [fullscreen]);
/**
* Effect responsible for registering/unregistering the resize spy to determine the rendering sizes
*/
React.useLayoutEffect(() => {
const handleResize = debounce(() => {
zoomToPageView(pages[currentPage], currentViewMode);
// Fix chrome on Android address bar issue by setting the right viewport height with good old fashion JS
// Then we set the value in the --vh custom property to the root of the document
const vh = window.innerHeight * 0.01;
window.document.documentElement.style.setProperty('--vh', `${vh}px`);
}, 500);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
});
React.useEffect(() => {
props.onPageChanged && props.onPageChanged(currentPage, pages.length);
}, [currentPage]);
/**
* Finds a document source.
*/
async function findDocumentSource(url: string) {
if (isDataURI(url)) {
const fileUint8Array = dataURItoUint8Array(url);
return { data: fileUint8Array };
}
return { url };
}
/**
* Loads the PDF into the pdfjs library
*/
async function loadDocument() {
// Reset all values for the new document
setLoading(true);
setPages([]);
setCurrentScale(1);
setCurrentViewMode(PageViewMode.DEFAULT);
setCurrentPage(1);
if (!url) {
return;
}
try {
const source = await findDocumentSource(url);
const d = await PdfJs.getDocument(source).promise;
onLoadSuccess(d);
} catch (error) {
onLoadError(error);
}
}
/**
* Event triggered when the document finished loading
*
* @param document
*/
function onLoadSuccess(document: PdfJs.PdfDocument) {
setDocument(document);
if (props.onLoadSuccess) {
props.onLoadSuccess(document);
}
const _pages = [...new Array(document.numPages)].map(() => {
return {
ratio: 0,
loaded: false,
} as PageType;
});
setPages(_pages);
setLoading(false);
}
/**
* Even triggered in case the document failed to load
*
* @param error
*/
function onLoadError(error: unknown) {
setDocument(undefined);
setLoading(false);
if (props.onLoadError) {
props.onLoadError(error);
} else {
throw error;
}
}
/**
* Touch events here
*/
window['touchInfo'] = {
startX: 0,
startY: 0,
startDistance: 0,
};
const touchInfo = window['touchInfo'];
/**
* Event triggered on double touch
*/
function onDocumentDoubleTouch() {
if (isTouchDevice) {
switchFullscreenMode();
}
}
let currentPinchScale = currentScale;
/**
* Event triggered when the user puts a finger on the screen
* We only care here about events with 2 fingers on them so we can control pinch to zoom
*
* @param e
*/
function onDocumentTouchStart(e: React.TouchEvent<HTMLDivElement>) {
if (e.touches.length > 1) {
const startX = (e.touches[0].pageX + e.touches[1].pageX) / 2;
const startY = (e.touches[0].pageY + e.touches[1].pageY) / 2;
Object.assign(touchInfo, {
startX,
startY,
startDistance: Math.hypot(e.touches[1].pageX - e.touches[0].pageX, e.touches[1].pageY - e.touches[0].pageY),
});
} else {
Object.assign(touchInfo, {
startX: 0,
startY: 0,
startDistance: 0,
});
}
}
/**
* Event triggered when the user moves the finger around the screen
* Since we only control pinch to zoom, we need to track how the distance between the fingers changed over time
* Then we use that distance to calculate the relative scale and apply that scale using transforms
* to avoid expensive re-renders, once the user let go the fingers we do a proper rendering of the PDF document
*
* @param e
*/
function onDocumentTouchMove(e: React.TouchEvent<HTMLDivElement>) {
if (!isTouchDevice || touchInfo.startDistance <= 0 || e.touches.length < 2) {
return;
}
const pinchDistance = Math.hypot(e.touches[1].pageX - e.touches[0].pageX, e.touches[1].pageY - e.touches[0].pageY);
const originX = touchInfo.startX + documentRef.current.scrollLeft;
const originY = touchInfo.startY + documentRef.current.scrollTop;
currentPinchScale = pinchDistance / touchInfo.startDistance;
// Adjust for min and max parameters over the absolute zoom (current zoom + pitch zoom)
const absScale = currentPinchScale * currentScale;
currentPinchScale = Math.min(Math.max(absScale, 0.2), 2.5) / currentScale;
// Here we simulate the zooming effect with transform, not perfect, but better than a re-render
documentRef.current.style.transform = `scale(${currentPinchScale})`;
documentRef.current.style.transformOrigin = `${originX}px ${originY}px`;
}
/**
* Event triggered when the user ends a touch event
* If all went good and we are ending a pinch to zoom event we need to queue a rendering of the PDF pages
* using the new zoom level
*/
function onDocumentTouchEnd() {
if (!isTouchDevice || touchInfo.startDistance <= 0) return;
documentRef.current.style.transform = `none`;
documentRef.current.style.transformOrigin = `unset`;
const rect = documentRef.current.getBoundingClientRect();
const dx = touchInfo.startX - rect.left;
const dy = touchInfo.startY - rect.top;
// I don't like this, but we need to make sure we change the scrolling after the re-rendering with the new zoom levels
setTimeout(() => {
documentRef.current.scrollLeft += dx * (currentPinchScale - 1);
documentRef.current.scrollTop += dy * (currentPinchScale - 1);
}, 0);
Object.assign(touchInfo, {
startDistance: 0,
startX: 0,
startY: 0,
});
onScaleChange(currentPinchScale * currentScale);
}
/**
* Event triggered when the touch event gets cancelled
* In this case we need to restart our touchInfo data so other things can continue as they were
*/
function onTouchCancel() {
if (isTouchDevice) {
Object.assign(touchInfo, {
startDistance: 0,
startX: 0,
startY: 0,
});
}
}
/**
* Event triggered when a page visibility changes
*
* @param pageNumber
* @param ratio
*/
const onPageVisibilityChanged = (pageNumber: number, ratio: number): boolean => {
// Ignore page change during pinch to zoom event
// This needs to be done as page changes trigger a re-rendering
// which conflicts with all the pinch to zoom events
if (isTouchDevice && window['touchInfo'].startDistance > 0) return false;
// Calculate in which page we are right now based on the scrolling position
if (pages && pages.length) {
pages[pageNumber - 1].ratio = ratio;
const maxRatioPage = pages.reduce((maxIndex, item, index, array) => {
return item.ratio > array[maxIndex].ratio ? index : maxIndex;
}, 0);
setCurrentPage(maxRatioPage + 1);
} else {
setCurrentPage(1);
}
return true;
};
/**
* Event triggered when a page loaded
*
* @param pageNumber
* @param width
* @param height
*/
const onPageLoaded = (pageNumber: number, width: number, height: number): void => {
if (pages && pages.length) {
pages[pageNumber - 1] = {
...pages[pageNumber - 1],
loaded: true,
width,
height,
};
setPages([...pages]);
// On the first time we default the view to the first page
if (pageNumber === 1) {
zoomToPageView(pages[0], currentViewMode);
}
}
};
/**
* End of Touch events
*/
/**
* Event triggered when the user manually changes the zoom level
* @param scale
*/
function onScaleChange(scale: number) {
setCurrentViewMode(PageViewMode.DEFAULT);
zoomToScale(scale);
}
/**
* Function used to navigate to a specific page
*
* @param pageNum
*/
function navigateToPage(pageNum: number) {
pageNum = Math.min(Math.max(pageNum, 1), pages.length);
const ref = pages[pageNum - 1].ref; // Convert to index from pageNumber
if (ref && documentRef.current) {
setCurrentPage(pageNum);
documentRef.current.scrollTo
? documentRef.current.scrollTo(0, ref.offsetTop - 20)
: (documentRef.current.scrollTop = ref.offsetTop - 20);
}
}
/**
* Zooms the page to the given scale
*
* @param scale
*/
function zoomToScale(scale: number) {
setCurrentScale(Math.min(Math.max(scale, 0.2), 2.5));
}
/**
* Zooms the page according to the page view mode
*
* @param pageProps
* @param viewMode
*/
function zoomToPageView(pageProps: PageType, viewMode: PageViewMode) {
if (!documentRef.current || !pageProps || !pageProps.ref) {
return;
}
const pageElement = pageProps.ref.firstChild as HTMLDivElement;
const pageWidth = pageProps.width || pageElement.offsetWidth;
const pageHeight = pageProps.height || pageElement.offsetHeight;
const landscape = pageWidth > pageHeight;
switch (viewMode) {
case PageViewMode.DEFAULT: {
if (landscape) {
const desiredWidth = Math.round(documentRef.current.offsetWidth - 32);
zoomToScale(desiredWidth / pageWidth);
} else {
const desiredWidth = Math.round((documentRef.current.offsetWidth - 32) * 0.7);
zoomToScale(desiredWidth / pageWidth);
}
break;
}
case PageViewMode.FIT_TO_WIDTH: {
const desiredWidth = Math.round(documentRef.current.offsetWidth - 32);
zoomToScale(desiredWidth / pageWidth);
break;
}
case PageViewMode.FIT_TO_HEIGHT: {
const desiredHeight = Math.round(documentRef.current.offsetHeight - 32);
zoomToScale(desiredHeight / pageHeight);
break;
}
default:
break;
}
}
/**
* Event triggered when the view mode changes
*/
function onViewModeChange(viewMode: PageViewMode) {
setCurrentViewMode(viewMode);
zoomToPageView(pages[currentPage], viewMode);
}
/**
* Enables / Disables fullscreen mode
*/
function switchFullscreenMode() {
setFullscreen(!fullscreen);
}
return (
<PDFWorker workerUrl={workerUrl}>
<DocumentWrapper fullscreen={fullscreen}>
<Document
ref={documentRef}
onTouchStart={onDocumentTouchStart}
onTouchEnd={onDocumentTouchEnd}
onTouchMove={onDocumentTouchMove}
onTouchCancel={onTouchCancel}
onDoubleClick={onDocumentDoubleTouch}>
{loading ? (
<PageWrapper>
<PDFViewerPage
onPageLoaded={onPageLoaded}
onPageVisibilityChanged={onPageVisibilityChanged}
pageNumber={1}
loaded={false}
scale={1}
/>
</PageWrapper>
) : (
document &&
pages.map((_, index: number) => (
<PageWrapper ref={(ref: HTMLDivElement | null) => (pages[index].ref = ref)} key={index}>
<PDFViewerPage
onPageLoaded={onPageLoaded}
onPageVisibilityChanged={onPageVisibilityChanged}
disableSelect={props.disableSelect}
document={document}
loaded={pages[index].loaded}
pageNumber={index + 1}
scale={currentScale}
/>
</PageWrapper>
))
)}
</Document>
{!loading && !isTouchDevice && (
<PDFViewerToolbar
labels={props.toolbarLabels}
currentPage={currentPage}
currentViewMode={currentViewMode}
numPages={pages.length}
currentScale={currentScale}
fullscreen={fullscreen}
onPageChange={navigateToPage}
onScaleChange={onScaleChange}
onViewModeChange={onViewModeChange}
onFullscreenChange={switchFullscreenMode}
/>
)}
{!loading && isTouchDevice && (
<PDFViewerTouchToolbar
labels={props.toolbarLabels}
currentPage={currentPage}
currentViewMode={currentViewMode}
numPages={pages.length}
currentScale={currentScale}
fullscreen={fullscreen}
onPageChange={navigateToPage}
onScaleChange={onScaleChange}
onViewModeChange={onViewModeChange}
onFullscreenChange={switchFullscreenMode}
/>
)}
</DocumentWrapper>
</PDFWorker>
);
};
PDFViewer.displayName = 'PDFViewer'; | the_stack |
import { DSL,Layer } from './types';
const insert = (newLayer:Layer, layers:Layer[]) => {
const { x: nx, y: ny, width: nwidth, height: nheight } = newLayer.structure;
if (!layers || layers.length === 0) {
layers[0] = newLayer;
return;
}
let pos = -1;
for (let index = 0; index < layers.length; index++) {
const layer = layers[index];
const { x, y, width, height } = layer.structure;
// TODO 误差量
if (x <= nx + 1 && x + width + 1 >= nx + nwidth
&& y <= ny + 1 && y + height + 1 >= ny + nheight) {
// if (!layer.children) layer.children = [];
// insert(newLayer, layer.children);
// return;
pos = index;
}
}
if (pos !== -1) {
const layer = layers[pos];
if (!layer.children) layer.children = [];
insert(newLayer, layer.children);
} else {
layers.push(newLayer);
}
}
const pow2 = (n:number) => {
return Math.pow(n, 2);
}
function sortData(data:Layer[]) {
const newData = [];
const offset = 20000;
// data.sort(({ x: x1, y: y1 }, { x: x2, y: y2 }) => {
// return (Math.pow(x1, 2) + Math.pow(y1 + offset, 2)) - (Math.pow(x2, 2) + Math.pow(y2 + offset, 2));
// }).sort(({ x: x1, y: y1, height: height1 }, { x: x2, y: y2, height: height2 }) => {
// if ((y1 >= y2 && y1 + height1 <= y2 + height2) || (y1 <= y2 && y1 + height1 >= y2 + height2)) {
// return x1 - x2;
// }
// return (Math.pow(x1, 2) + Math.pow(y1 + offset, 2)) - (Math.pow(x2, 2) + Math.pow(y2 + offset, 2));
// })
// .forEach((layer, i) => {
// layer.index = i;
// insert(layer, newData);
// });
// return newData;
const len = data.length;
for (let i = 0; i < len; i++) {
for (let j = 0; j < len - 1; j++) {
const { x: x1, y: y1, width: width1, height: height1 } = data[j].structure;
const { x: x2, y: y2, width: width2, height: height2 } = data[j + 1].structure;
if (x1 === x2 && y1 === y2) {
if (width1 * height1 < width2 * height2) {
[data[j], data[j + 1]] = [data[j + 1], data[j]];
}
} else if ((y1 >= y2 && y1 + height1 <= y2 + height2) ||
(y1 <= y2 && y1 + height1 >= y2 + height2)) {
if (x1 > x2) {
[data[j], data[j + 1]] = [data[j + 1], data[j]];
}
} else if ((pow2(x1) + pow2(y1 + offset)) > (pow2(x2) + pow2(y2 + offset))) {
[data[j], data[j + 1]] = [data[j + 1], data[j]];
}
}
}
data.forEach((layer, i) => {
layer.structure.zIndex = i;
insert(layer, newData);
});
return newData;
}
const getXYWH = (arr) => {
let ax = arr[0].x;
let ay = arr[0].y;
let awidth = arr[0].width;
let aheight = arr[0].height;
for (let { x, y, width, height } of arr) {
if (x < ax) ax = x;
if (y < ay) ay = y;
if (x + width > ax + awidth) awidth = x + width - ax;
if (y + height > ay + aheight) aheight = y + height - ay;
}
return {
x: ax,
y: ay,
width: awidth,
height: aheight,
}
}
const getMax = (arr:DSL, edgeFlag = true) => {
// 分组
const arrMap = new Map();
arr.forEach((d) => {
const { width, height } = d.structure;
const wh = `${width},${height}`;
const { n, nArr } = arrMap.get(wh) || { n: 0, nArr: [] };
nArr.push(d);
arrMap.set(wh, {
n: n + 1,
nArr,
});
});
let maxKey = null;
let maxN = 0;
const arrWide = getXYWH(arr);
let len = arr.length;
while (len) {
len--;
for (const [key, { n }] of arrMap) {
if (n > maxN) {
maxN = n;
maxKey = key;
}
}
if (maxN === 1) break;
const maxArr = arr.filter(({ structure }) => {
const { width, height } =structure;
// 大小容差
return `${width},${height}` === maxKey;
});
const overlappingFlag = arr.reduce((prev, curr) => {
if (!prev) return curr;
if (prev === true) return true;
const { x: px, y: py, width: pwidth, height: pheight } = prev;
const { x, y, width, height } = curr.structure;
return !(px > x + width || px + pwidth < x || py > y + height || py + pheight < y)}, false);
// const maxArrWide = getXYWH(maxArr);
const { structure: { x, y }, type } = maxArr[0];
if (type === 'Text') {
arrMap.delete(maxKey);
maxN = 1;
} else if (edgeFlag && x !== arrWide.x && y !== arrWide.y) {
arrMap.delete(maxKey);
maxN = 1;
} else if (overlappingFlag === true) {
arrMap.delete(maxKey);
maxN = 1;
} else {
break;
}
}
return { maxKey, maxN };
}
const groupData = (arr: Layer[], p?: Layer) => {
if (!arr || arr.length === 0) return;
if (arr.length <= 1) {
if (arr[0].children) {
groupData(arr[0].children, arr[0]);
}
return;
}
let { maxKey, maxN } = getMax(arr);
const groupLayers:any = [];
for (let i = 0; i < arr.length; i++) {
const d = arr[i];
// if (d.id === '9a2sea9u') debugger;
if (d.textContainer !== true && d.children && d.children.length > 0) groupData(d.children, d);
if (maxN === 1 || d.sign === '__li') {
groupLayers[i] = d;
continue;
}
const { width: dWidth, height: dHeight } = d.structure;
if (!groupLayers[0]) groupLayers[0] = [];
if (groupLayers.length <= 1 && `${dWidth},${dHeight}` !== maxKey) {
groupLayers[0].push(d);
continue;
}
// TODO
if (!groupLayers[1]) groupLayers[1] = [];
if (`${dWidth},${dHeight}` === maxKey) {
groupLayers[1].push([d]);
groupLayers[1].sign = '__list';
} else {
const liLayers = groupLayers[1];
if (liLayers.length > 1 && liLayers[liLayers.length - 1].length === liLayers[0].length) {
groupLayers[2] = arr.slice(i);
break;
}
liLayers[liLayers.length - 1].push(d);
}
}
if (maxN > groupLayers[1].length) {
groupLayers.length = 0;
groupLayers.push([...arr]);
}
// if (p && p.id === '5sj0hqpc') debugger;
if (groupLayers[1] && Array.isArray(groupLayers[1]) && groupLayers[1][0].sign === '__list') {
const overlappingFlag = groupLayers[1].reduce((prev, curr) => {
if (!prev) return curr;
if (prev === true) return true;
const { x: px, y: py, width: pwidth, height: pheight } = getXYWH(prev);
const { x, y, width, height } = getXYWH(curr);
return !(px > x + width || px + pwidth < x ||
py > y + height || py + pheight < y)
}, false);
if (overlappingFlag === true) {
groupLayers.length = 0;
groupLayers.push([...arr]);
}
}
if (maxN === 1) {
const { width: mwidth, height: mheight } = getXYWH(arr);
const segArr = [];
arr.forEach((d, i) => {
if ((d.structure.width === mwidth && d.structure.height < 5) ||
(d.structure.height === mheight && d.structure.width < 5)) segArr.push(i);
});
// TODO 如果第一个或者最后一个不分组
// TODO 此处判断有待优化
if (segArr.length > 0 && segArr.length < arr.length) {
// debugger;
groupLayers.length = 0;
const newArr = [...arr];
segArr.reduce((pv, cv, idx) => {
groupLayers.push([...newArr.slice(pv, cv)]);
if (p && p.sign === '__li') groupLayers[groupLayers.length - 1].sign = '__li';
groupLayers.push([...newArr.slice(cv, cv + 1)]);
if (cv === newArr.length - 1) return;
if (idx === segArr.length - 1) {
groupLayers.push([...newArr.slice(cv + 1)]);
if (p && p.sign === '__li') groupLayers[groupLayers.length - 1].sign = '__li';
}
return cv + 1;
}, 0);
} else if (p && p.sign === '__li') {
const __groupLayers = [];
const YA = [];
const fullWidthArr = [];
for (let i = 0; i < arr.length; i++) {
const d = arr[i];
// if (d.id === 'lomlu25m') debugger;
let flag = true;
let { width: dWidth, x: dX } = d.structure;
if (i === 0) {
YA[0] = { width: dWidth, x: dX };
}
if (p && dWidth === p.structure.width) {
fullWidthArr.push(d);
continue;
}
// TODO 先小后大 处理
for (let j = 0; j < YA.length; j++) {
const { x: yX, width: yWidth } = YA[j];
// if (!(yX > dX || yX + yWidth < dX + dWidth)) {
if (!(yX > dX + dWidth || yX + yWidth < dX)) {
if (!__groupLayers[j]) __groupLayers[j] = [];
__groupLayers[j].push(d);
flag = false;
break;
}
}
if (flag) {
YA.push({ width: dWidth, x: dX });
const pos = YA.length - 1;
if (!__groupLayers[pos]) __groupLayers[pos] = [];
__groupLayers[pos].push(d);
}
}
if (YA.length > 1) {
groupLayers.length = 0;
groupLayers.push(...__groupLayers.filter(l => !!l));
groupLayers.push(fullWidthArr);
}
}
}
if (p) {
if (!Array.isArray(groupLayers[0])) {
return p.children = groupLayers;
}
// if (p && p.id === '5sj0hqpc') debugger;
p.children = groupLayers.filter((gls) => gls.length > 0).map((gls) => {
if (gls.length === 1) {
return gls[0];
}
// TODO
const c = gls.map(gl => {
if (!Array.isArray(gl)) return gl;
if (gl.length === 1) {
if (gls.sign === '__list') gl[0].sign = '__li';
return gl[0];
}
return {
sign: gls.sign === '__list' ? '__li' : '__oth',
...getXYWH(gl),
children: gl,
};
});
const cp = {
sign: gls.sign ? gls.sign : '__oth',
...getXYWH(c),
children: c,
}
return cp;
});
// if (p && p.id === '5sj0hqpc') debugger;
if (p.children.length === 1 && p.children[0].sign) {
p.children = p.children[0].children;
}
p.children.forEach((pc) => {
if (pc.sign === '__list') {
pc.children.forEach((pcc) => {
// debugger;
pcc.children && groupData(pcc.children, pcc);
});
return;
}
if (pc.children && pc.children.length > 0 && pc.children[0].sign !== '__li') {
pc.children && groupData(pc.children, pc);
}
});
}
}
const domFormat = (data:DSL) => {
const [artboard, ...childData] = data;
const newData = sortData(childData);
groupData(newData);
artboard.children = newData;
return [artboard];
}
export default domFormat; | the_stack |
import { DeepOmit } from "../lib";
import { complexNestedRequired, complexNestedUndefined } from "./const";
import { TsVersion } from "./ts-version";
import { ComplexNestedPartial, ComplexNestedRequired } from "./types";
function testDeepOmitInRequiredObject() {
let obj1: DeepOmit<ComplexNestedRequired, {}>;
obj1 = complexNestedRequired;
// @ts-expect-error missed nested
obj1 = { simple: complexNestedRequired.simple };
let obj2: DeepOmit<ComplexNestedRequired, { simple: true }>;
// @ts-expect-error
obj2 = {};
// @ts-expect-error
obj2 = { nested: undefined };
obj2 = {
// @ts-expect-error
nested: complexNestedUndefined.nested,
};
obj2 = { nested: complexNestedRequired.nested };
let obj2_1: DeepOmit<ComplexNestedRequired, { simple: never }>;
// @ts-expect-error
obj2_1 = {};
// @ts-expect-error
obj2_1 = { nested: undefined };
obj2_1 = {
// @ts-expect-error
nested: complexNestedUndefined.nested,
};
obj2_1 = { nested: complexNestedRequired.nested };
{
const {
nested: { date, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj3: DeepOmit<ComplexNestedRequired, { nested: { date: true } }>;
// @ts-expect-error
obj3 = {};
// @ts-expect-error
obj3 = { simple: undefined };
// @ts-expect-error
obj3 = { nested: undefined };
// @ts-expect-error
obj3 = { simple: undefined, nested: undefined };
// @ts-expect-error
obj3 = { simple: undefined, nested: complexNestedRequiredNested };
// @ts-expect-error
obj3 = { simple: complexNestedRequired.simple, nested: undefined };
obj3 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { date, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj3_1: DeepOmit<ComplexNestedRequired, { nested: { date: never } }>;
// @ts-expect-error
obj3_1 = {};
// @ts-expect-error
obj3_1 = { simple: undefined };
// @ts-expect-error
obj3_1 = { nested: undefined };
// @ts-expect-error
obj3_1 = { simple: undefined, nested: undefined };
// @ts-expect-error
obj3_1 = { simple: undefined, nested: complexNestedRequiredNested };
// @ts-expect-error
obj3_1 = { simple: complexNestedRequired.simple, nested: undefined };
obj3_1 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { func, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj4: DeepOmit<ComplexNestedRequired, { nested: { func: true } }>;
// @ts-expect-error
obj4 = {};
// @ts-expect-error
obj4 = { simple: undefined };
// @ts-expect-error
obj4 = { nested: undefined };
// @ts-expect-error
obj4 = { simple: undefined, nested: undefined };
// @ts-expect-error
obj4 = { simple: undefined, nested: complexNestedRequiredNested };
// @ts-expect-error
obj4 = { simple: complexNestedRequired.simple, nested: undefined };
obj4 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { func, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj4_1: DeepOmit<ComplexNestedRequired, { nested: { func: never } }>;
// @ts-expect-error
obj4_1 = {};
// @ts-expect-error
obj4_1 = { simple: undefined };
// @ts-expect-error
obj4_1 = { nested: undefined };
// @ts-expect-error
obj4_1 = { simple: undefined, nested: undefined };
// @ts-expect-error
obj4_1 = { simple: undefined, nested: complexNestedRequiredNested };
// @ts-expect-error
obj4_1 = { simple: complexNestedRequired.simple, nested: undefined };
obj4_1 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { array, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj5: DeepOmit<ComplexNestedRequired, { nested: { array: true } }>;
// @ts-expect-error
obj5 = {};
// @ts-expect-error
obj5 = { simple: undefined };
// @ts-expect-error
obj5 = { nested: undefined };
// @ts-expect-error
obj5 = { simple: undefined, nested: undefined };
// @ts-expect-error
obj5 = { simple: undefined, nested: complexNestedRequiredNested };
// @ts-expect-error
obj5 = { simple: complexNestedRequired.simple, nested: undefined };
obj5 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { array, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj5_1: DeepOmit<ComplexNestedRequired, { nested: { array: never } }>;
// @ts-expect-error
obj5_1 = {};
// @ts-expect-error
obj5_1 = { simple: undefined };
// @ts-expect-error
obj5_1 = { nested: undefined };
// @ts-expect-error
obj5_1 = { simple: undefined, nested: undefined };
// @ts-expect-error
obj5_1 = { simple: undefined, nested: complexNestedRequiredNested };
// @ts-expect-error
obj5_1 = { simple: complexNestedRequired.simple, nested: undefined };
obj5_1 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { tuple, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj6: DeepOmit<ComplexNestedRequired, { nested: { tuple: true } }>;
// @ts-expect-error
obj6 = {};
// @ts-expect-error
obj6 = { simple: undefined };
// @ts-expect-error
obj6 = { nested: undefined };
// @ts-expect-error
obj6 = { simple: undefined, nested: undefined };
// @ts-expect-error
obj6 = { simple: undefined, nested: complexNestedRequiredNested };
// @ts-expect-error
obj6 = { simple: complexNestedRequired.simple, nested: undefined };
obj6 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { tuple, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj6_1: DeepOmit<ComplexNestedRequired, { nested: { tuple: never } }>;
// @ts-expect-error
obj6_1 = {};
// @ts-expect-error
obj6_1 = { simple: undefined };
// @ts-expect-error
obj6_1 = { nested: undefined };
// @ts-expect-error
obj6_1 = { simple: undefined, nested: undefined };
// @ts-expect-error
obj6_1 = { simple: undefined, nested: complexNestedRequiredNested };
// @ts-expect-error
obj6_1 = { simple: complexNestedRequired.simple, nested: undefined };
obj6_1 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { set, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj7: DeepOmit<ComplexNestedRequired, { nested: { set: true } }>;
// @ts-expect-error
obj7 = {};
// @ts-expect-error
obj7 = { simple: undefined };
// @ts-expect-error
obj7 = { nested: undefined };
// @ts-expect-error
obj7 = { simple: undefined, nested: undefined };
// @ts-expect-error
obj7 = { simple: undefined, nested: complexNestedRequiredNested };
// @ts-expect-error
obj7 = { simple: complexNestedRequired.simple, nested: undefined };
obj7 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { set, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj7_1: DeepOmit<ComplexNestedRequired, { nested: { set: never } }>;
// @ts-expect-error
obj7_1 = {};
// @ts-expect-error
obj7_1 = { simple: undefined };
// @ts-expect-error
obj7_1 = { nested: undefined };
// @ts-expect-error
obj7_1 = { simple: undefined, nested: undefined };
// @ts-expect-error
obj7_1 = { simple: undefined, nested: complexNestedRequiredNested };
// @ts-expect-error
obj7_1 = { simple: complexNestedRequired.simple, nested: undefined };
obj7_1 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { map, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj8: DeepOmit<ComplexNestedRequired, { nested: { map: true } }>;
// @ts-expect-error
obj8 = {};
// @ts-expect-error
obj8 = { simple: undefined };
// @ts-expect-error
obj8 = { nested: undefined };
// @ts-expect-error
obj8 = { simple: undefined, nested: undefined };
// @ts-expect-error
obj8 = { simple: undefined, nested: complexNestedRequiredNested };
// @ts-expect-error
obj8 = { simple: complexNestedRequired.simple, nested: undefined };
obj8 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { map, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj8_1: DeepOmit<ComplexNestedRequired, { nested: { map: never } }>;
// @ts-expect-error
obj8_1 = {};
// @ts-expect-error
obj8_1 = { simple: undefined };
// @ts-expect-error
obj8_1 = { nested: undefined };
// @ts-expect-error
obj8_1 = { simple: undefined, nested: undefined };
// @ts-expect-error
obj8_1 = { simple: undefined, nested: complexNestedRequiredNested };
// @ts-expect-error
obj8_1 = { simple: complexNestedRequired.simple, nested: undefined };
obj8_1 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { promise, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj9: DeepOmit<ComplexNestedRequired, { nested: { promise: true } }>;
// @ts-expect-error
obj9 = {};
// @ts-expect-error
obj9 = { simple: undefined };
// @ts-expect-error
obj9 = { nested: undefined };
// @ts-expect-error
obj9 = { simple: undefined, nested: undefined };
// @ts-expect-error
obj9 = { simple: undefined, nested: complexNestedRequiredNested };
// @ts-expect-error
obj9 = { simple: complexNestedRequired.simple, nested: undefined };
obj9 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { promise, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj9_1: DeepOmit<ComplexNestedRequired, { nested: { promise: never } }>;
// @ts-expect-error
obj9_1 = {};
// @ts-expect-error
obj9_1 = { simple: undefined };
// @ts-expect-error
obj9_1 = { nested: undefined };
// @ts-expect-error
obj9_1 = { simple: undefined, nested: undefined };
// @ts-expect-error
obj9_1 = { simple: undefined, nested: complexNestedRequiredNested };
// @ts-expect-error
obj9_1 = { simple: complexNestedRequired.simple, nested: undefined };
obj9_1 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { date, array, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj10: DeepOmit<ComplexNestedRequired, { nested: { date: true; array: true } }>;
// @ts-expect-error
obj10 = {};
// @ts-expect-error
obj10 = { simple: undefined };
// @ts-expect-error
obj10 = { nested: undefined };
// @ts-expect-error
obj10 = { simple: undefined, nested: undefined };
// @ts-expect-error
obj10 = { simple: undefined, nested: complexNestedRequiredNested };
// @ts-expect-error
obj10 = { simple: complexNestedRequired.simple, nested: undefined };
obj10 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
}
function testDeepOmitInPartialObject() {
let obj1: DeepOmit<ComplexNestedPartial, {}>;
obj1 = complexNestedRequired;
obj1 = { simple: complexNestedRequired.simple };
let obj2: DeepOmit<ComplexNestedPartial, { simple: true }>;
obj2 = {};
obj2 = { nested: undefined };
obj2 = {
nested: complexNestedUndefined.nested,
};
obj2 = { nested: complexNestedRequired.nested };
let obj2_1: DeepOmit<ComplexNestedPartial, { simple: never }>;
obj2_1 = {};
obj2_1 = { nested: undefined };
obj2_1 = {
nested: complexNestedUndefined.nested,
};
obj2_1 = { nested: complexNestedRequired.nested };
{
const {
nested: { date, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj3: DeepOmit<ComplexNestedPartial, { nested: { date: true } }>;
obj3 = {};
obj3 = { simple: undefined };
obj3 = { nested: undefined };
obj3 = { simple: undefined, nested: undefined };
obj3 = { simple: undefined, nested: complexNestedRequiredNested };
obj3 = { simple: complexNestedRequired.simple, nested: undefined };
obj3 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { date, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj3_1: DeepOmit<ComplexNestedPartial, { nested: { date: never } }>;
obj3_1 = {};
obj3_1 = { simple: undefined };
obj3_1 = { nested: undefined };
obj3_1 = { simple: undefined, nested: undefined };
obj3_1 = { simple: undefined, nested: complexNestedRequiredNested };
obj3_1 = { simple: complexNestedRequired.simple, nested: undefined };
obj3_1 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { func, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj4: DeepOmit<ComplexNestedPartial, { nested: { func: true } }>;
obj4 = {};
obj4 = { simple: undefined };
obj4 = { nested: undefined };
obj4 = { simple: undefined, nested: undefined };
obj4 = { simple: undefined, nested: complexNestedRequiredNested };
obj4 = { simple: complexNestedRequired.simple, nested: undefined };
obj4 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { func, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj4_1: DeepOmit<ComplexNestedPartial, { nested: { func: never } }>;
obj4_1 = {};
obj4_1 = { simple: undefined };
obj4_1 = { nested: undefined };
obj4_1 = { simple: undefined, nested: undefined };
obj4_1 = { simple: undefined, nested: complexNestedRequiredNested };
obj4_1 = { simple: complexNestedRequired.simple, nested: undefined };
obj4_1 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { array, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj5: DeepOmit<ComplexNestedPartial, { nested: { array: true } }>;
obj5 = {};
obj5 = { simple: undefined };
obj5 = { nested: undefined };
obj5 = { simple: undefined, nested: undefined };
obj5 = { simple: undefined, nested: complexNestedRequiredNested };
obj5 = { simple: complexNestedRequired.simple, nested: undefined };
obj5 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { array, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj5_1: DeepOmit<ComplexNestedPartial, { nested: { array: never } }>;
obj5_1 = {};
obj5_1 = { simple: undefined };
obj5_1 = { nested: undefined };
obj5_1 = { simple: undefined, nested: undefined };
obj5_1 = { simple: undefined, nested: complexNestedRequiredNested };
obj5_1 = { simple: complexNestedRequired.simple, nested: undefined };
obj5_1 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { tuple, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj6: DeepOmit<ComplexNestedPartial, { nested: { tuple: true } }>;
obj6 = {};
obj6 = { simple: undefined };
obj6 = { nested: undefined };
obj6 = { simple: undefined, nested: undefined };
obj6 = { simple: undefined, nested: complexNestedRequiredNested };
obj6 = { simple: complexNestedRequired.simple, nested: undefined };
obj6 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { tuple, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj6_1: DeepOmit<ComplexNestedPartial, { nested: { tuple: never } }>;
obj6_1 = {};
obj6_1 = { simple: undefined };
obj6_1 = { nested: undefined };
obj6_1 = { simple: undefined, nested: undefined };
obj6_1 = { simple: undefined, nested: complexNestedRequiredNested };
obj6_1 = { simple: complexNestedRequired.simple, nested: undefined };
obj6_1 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { set, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj7: DeepOmit<ComplexNestedPartial, { nested: { set: true } }>;
obj7 = {};
obj7 = { simple: undefined };
obj7 = { nested: undefined };
obj7 = { simple: undefined, nested: undefined };
obj7 = { simple: undefined, nested: complexNestedRequiredNested };
obj7 = { simple: complexNestedRequired.simple, nested: undefined };
obj7 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { set, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj7_1: DeepOmit<ComplexNestedPartial, { nested: { set: never } }>;
obj7_1 = {};
obj7_1 = { simple: undefined };
obj7_1 = { nested: undefined };
obj7_1 = { simple: undefined, nested: undefined };
obj7_1 = { simple: undefined, nested: complexNestedRequiredNested };
obj7_1 = { simple: complexNestedRequired.simple, nested: undefined };
obj7_1 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { map, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj8: DeepOmit<ComplexNestedPartial, { nested: { map: true } }>;
obj8 = {};
obj8 = { simple: undefined };
obj8 = { nested: undefined };
obj8 = { simple: undefined, nested: undefined };
obj8 = { simple: undefined, nested: complexNestedRequiredNested };
obj8 = { simple: complexNestedRequired.simple, nested: undefined };
obj8 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { map, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj8_1: DeepOmit<ComplexNestedPartial, { nested: { map: never } }>;
obj8_1 = {};
obj8_1 = { simple: undefined };
obj8_1 = { nested: undefined };
obj8_1 = { simple: undefined, nested: undefined };
obj8_1 = { simple: undefined, nested: complexNestedRequiredNested };
obj8_1 = { simple: complexNestedRequired.simple, nested: undefined };
obj8_1 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { promise, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj9: DeepOmit<ComplexNestedPartial, { nested: { promise: true } }>;
obj9 = {};
obj9 = { simple: undefined };
obj9 = { nested: undefined };
obj9 = { simple: undefined, nested: undefined };
obj9 = { simple: undefined, nested: complexNestedRequiredNested };
obj9 = { simple: complexNestedRequired.simple, nested: undefined };
obj9 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { promise, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj9_1: DeepOmit<ComplexNestedPartial, { nested: { promise: never } }>;
obj9_1 = {};
obj9_1 = { simple: undefined };
obj9_1 = { nested: undefined };
obj9_1 = { simple: undefined, nested: undefined };
obj9_1 = { simple: undefined, nested: complexNestedRequiredNested };
obj9_1 = { simple: complexNestedRequired.simple, nested: undefined };
obj9_1 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
const {
nested: { date, array, ...complexNestedRequiredNested },
} = complexNestedRequired;
let obj10: DeepOmit<ComplexNestedPartial, { nested: { date: true; array: true } }>;
obj10 = {};
obj10 = { simple: undefined };
obj10 = { nested: undefined };
obj10 = { simple: undefined, nested: undefined };
obj10 = { simple: undefined, nested: complexNestedRequiredNested };
obj10 = { simple: complexNestedRequired.simple, nested: undefined };
obj10 = { simple: complexNestedRequired.simple, nested: complexNestedRequiredNested };
}
{
type MapType = Map<
string,
{
name: string;
age: number;
}
>;
// @ts-expect-error ❌ Type 'number' is not assignable to type 'string'
let map: DeepOmit<MapType, Map<number, { age: true }>>;
}
{
type MapType = Map<
string,
{
name: string;
age: number;
}
>;
let map: DeepOmit<MapType, Map<string, { name: true }>>;
map = new Map<string, { age: number }>();
// @ts-expect-error Property 'age' is missing in type '{ name: string; }' but required in type '{ age: number; }'
map = new Map<string, { name: string }>();
// we still can extend value type
map = new Map<
string,
{
name: string;
age: number;
}
>();
// @ts-expect-error Type 'number' is not assignable to type 'string'
map = new Map<number, {}>();
map.set("key", { age: 1 });
}
{
type MapType = ReadonlyMap<
string,
{
name: string;
age: number;
}
>;
// @ts-expect-error ❌ Type 'number' is not assignable to type 'string'
let map: DeepOmit<MapType, ReadonlyMap<number, { age: true }>>;
}
{
type MapType = ReadonlyMap<
string,
{
name: string;
age: number;
}
>;
let map: DeepOmit<MapType, ReadonlyMap<string, { name: true }>>;
map = new Map<string, { age: number }>();
// @ts-expect-error Property 'age' is missing in type '{ name: string; }' but required in type '{ age: number; }'
map = new Map<string, { name: string }>();
// we still can extend value type
map = new Map<
string,
{
name: string;
age: number;
}
>();
// @ts-expect-error Type 'number' is not assignable to type 'string'
map = new Map<number, {}>();
// @ts-expect-error Property 'set' does not exist on type 'ReadonlyMap<string, { age: number; }>'
map.set("key", { age: 1 });
}
{
type MapType = WeakMap<
{ a: string },
{
name: string;
age: number;
}
>;
let map: DeepOmit<
MapType,
// for TypeScript 4.1 and 4.2 it's working though, so breaking it on purpose
// @ts-expect-error ❌ Type 'number' is not assignable to type 'string'
TsVersion extends "4.1" | "4.2" ? { breakingOnPurpose: true } : WeakMap<{ a: number }, { age: true }>
>;
}
{
type MapType = WeakMap<
{ a: string },
{
name: string;
age: number;
}
>;
let map: DeepOmit<MapType, WeakMap<{ a: string }, { name: true }>>;
map = new WeakMap<{ a: string }, { age: number }>();
// @ts-expect-error Property 'age' is missing in type '{ name: string; }' but required in type '{ age: number; }'
map = new Map<{ a: string }, { name: string }>();
// we still can extend value type
map = new Map<
{ a: string },
{
name: string;
age: number;
}
>();
// @ts-expect-error Type 'number' is not assignable to type 'string'
map = new Map<{ a: number }, {}>();
map.set({ a: "key" }, { age: 1 });
}
{
type SetType = Set<{
name: string;
age: number;
}>;
let set: DeepOmit<SetType, Set<{ name: true }>>;
set = new Set<{ age: number }>();
// @ts-expect-error Property 'age' is missing in type '{ name: string; }' but required in type '{ age: number; }'
set = new Set<{ name: string }>();
// we still can extend value type
set = new Set<{
name: string;
age: number;
}>();
// @ts-expect-error Type 'number' is not assignable to type 'string'
set = new Set<{}>();
set.add({ age: 1 });
}
{
type ReadonlySetType = ReadonlySet<{
name: string;
age: number;
}>;
let set: DeepOmit<ReadonlySetType, ReadonlySet<{ name: true }>>;
set = new Set<{ age: number }>();
// @ts-expect-error Property 'age' is missing in type '{ name: string; }' but required in type '{ age: number; }'
set = new Set<{ name: string }>();
// we still can extend value type
set = new Set<{
name: string;
age: number;
}>();
// @ts-expect-error Type 'number' is not assignable to type 'string'
set = new Set<{}>();
// @ts-expect-error Property 'add' does not exist on type 'ReadonlySet<{ age: number; }>'
set.add({ age: 1 });
}
{
type WeakSetType = WeakSet<{
name: string;
age: number;
}>;
let set: DeepOmit<WeakSetType, WeakSet<{ name: true }>>;
set = new WeakSet<{ age: number }>();
// @ts-expect-error Property 'age' is missing in type '{ name: string; }' but required in type '{ age: number; }'
set = new WeakSet<{ name: string }>();
// we still can extend value type
set = new WeakSet<{
name: string;
age: number;
}>();
// we even can use it that way for WeekSet
set = new WeakSet<{}>();
set.add({ age: 1 });
}
{
type ArrayType = Array<{
name: string;
age: number;
}>;
let arr: DeepOmit<ArrayType, Array<{ name: true }>>;
arr = new Array<{ age: number }>();
// @ts-expect-error Property 'age' is missing in type '{ name: string; }' but required in type '{ age: number; }'
arr = new Array<{ name: string }>();
// we still can extend value type
arr = new Array<{
name: string;
age: number;
}>();
// @ts-expect-error Property 'age' is missing in type '{}' but required in type '{ age: number; }'
arr = new Array<{}>();
arr.push({ age: 1 });
}
{
type PromiseType = Promise<{
name: string;
age: number;
}>;
let promise: DeepOmit<PromiseType, Promise<{ name: true }>>;
promise = new Promise<{ age: number }>(() => {});
// @ts-expect-error Property 'age' is missing in type '{ name: string; }' but required in type '{ age: number; }'
promise = new Promise<{ name: string }>(() => {});
// we still can extend value type
promise = new Promise<{
name: string;
age: number;
}>(() => {});
// @ts-expect-error Property 'age' is missing in type '{}' but required in type '{ age: number; }'
promise = new Promise<{}>(() => {});
}
} | the_stack |
import * as cdm from '../../../objectModel/TypeScript';
import { cdmStatusLevel } from '../../../objectModel/TypeScript/internal';
/**
* This sample demonstrates how to model a set of common scenarios using projections.
* The projections feature provides a way to customize the definition of a logical entity by influencing how the entity is resolved by the object model.
* Here we will model three common use cases for using projections that are associated with the directives 'referenceOnly', 'structured' and 'normalized'.
* A single logical definition can be resolved into multiple physical layouts. The directives are used to instruct the ObjectModel about how it should to
* resolve the logical definition provided. To achieve this, we define projections that run conditionally, depending on the directives provided when
* calling createResolvedEntityAsync.
* To get an overview of the projections feature as well as all of the supported operations refer to the link below.
* https://docs.microsoft.com/en-us/common-data-model/sdk/convert-logical-entities-resolved-entities#projection-overview
*/
async function runSample() {
// Make a corpus, the corpus is the collection of all documents and folders created or discovered while navigating objects and paths
const corpus = new cdm.types.CdmCorpusDefinition();
console.log('Configure storage adapters.');
// Configure storage adapters to point at the target local manifest location and at the fake public standards
const pathFromExeToExampleRoot: string = 'C:/repos/CDM.ObjectModel/samples/';
// const pathFromExeToExampleRoot: string = '../../';
corpus.storage.mount('local', new cdm.types.LocalAdapter(pathFromExeToExampleRoot + '8-logical-manipulation-using-projections/sample-data'));
// set callback to receive error and warning logs.
corpus.setEventCallback( (level, message) => { console.log(message) }, cdmStatusLevel.warning);
corpus.storage.defaultNamespace = 'local'; // local is our default. so any paths that start out navigating without a device tag will assume local
// Fake cdm, normaly use the CDM Standards adapter
// mount it as the 'cdm' device, not the default so must use 'cdm:/folder' to get there
corpus.storage.mount('cdm', new cdm.types.LocalAdapter(pathFromExeToExampleRoot + 'example-public-standards'));
console.log('Create logical entity definition.');
const logicalFolder = await corpus.fetchObjectAsync<cdm.types.CdmFolderDefinition>('local:/');
const logicalDoc: cdm.types.CdmDocumentDefinition = logicalFolder.documents.push('Person.cdm.json');
logicalDoc.imports.push('Address.cdm.json');
const entity = logicalDoc.definitions.push('Person') as cdm.types.CdmEntityDefinition;
// Add 'name' data typed attribute.
const nameAttr = entity.attributes.push('name') as cdm.types.CdmTypeAttributeDefinition;
nameAttr.dataType = new cdm.types.CdmDataTypeReference(corpus.ctx, 'string', true);
// Add 'age' data typed attribute.
const ageAttr = entity.attributes.push('age') as cdm.types.CdmTypeAttributeDefinition;
ageAttr.dataType = new cdm.types.CdmDataTypeReference(corpus.ctx, 'string', true);
// Add 'address' entity typed attribute.
const entityAttr = new cdm.types.CdmEntityAttributeDefinition(corpus.ctx, 'address');
entityAttr.entity = new cdm.types.CdmEntityReference(corpus.ctx, 'Address', true);
applyArrayExpansion(entityAttr, 1, 3, '{m}{A}{o}', 'countAttribute');
applyDefaultBehavior(entityAttr, 'addressFK', 'address');
entity.attributes.push(entityAttr);
// Add 'email' data typed attribute.
const emailAttr = entity.attributes.push('email') as cdm.types.CdmTypeAttributeDefinition;
emailAttr.dataType = new cdm.types.CdmDataTypeReference(corpus.ctx, 'string', true);
// Save the logical definition of Person.
await entity.inDocument.saveAsAsync('Person.cdm.json');
console.log('Get \'resolved\' folder where the resolved entities will be saved.');
const resolvedFolder = await corpus.fetchObjectAsync<cdm.types.CdmFolderDefinition>('local:/resolved/');
const resOpt = new cdm.types.resolveOptions(entity);
// To get more information about directives and their meaning refer to
// https://docs.microsoft.com/en-us/common-data-model/sdk/convert-logical-entities-resolved-entities#directives-guidance-and-the-resulting-resolved-shapes
// We will start by resolving this entity with the 'normalized' direcitve.
// This directive will be used on this and the next two examples so we can analize the resolved entity
// without the array expansion.
console.log('Resolving logical entity with normalized directive.');
resOpt.directives = new cdm.types.AttributeResolutionDirectiveSet(new Set<string>([ 'normalized' ]));
const resNormalizedEntity = await entity.createResolvedEntityAsync(`normalized_${entity.entityName}`, resOpt, resolvedFolder);
await resNormalizedEntity.inDocument.saveAsAsync(`${resNormalizedEntity.entityName}.cdm.json`);
// Another common scenario is to resolve an entity using the 'referenceOnly' directive.
// This directives is used to replace the relationships with a foreign key.
console.log('Resolving logical entity with referenceOnly directive.');
resOpt.directives = new cdm.types.AttributeResolutionDirectiveSet(new Set<string>([ 'normalized', 'referenceOnly' ]));
const resReferenceOnlyEntity = await entity.createResolvedEntityAsync(`referenceOnly_${entity.entityName}`, resOpt, resolvedFolder);
await resReferenceOnlyEntity.inDocument.saveAsAsync(`${resReferenceOnlyEntity.entityName}.cdm.json`);
// When dealing with structured data, like Json or parquet, it sometimes necessary to represent the idea that
// a property can hold a complex object. The shape of the complex object is defined by the source entity pointed by the
// entity attribute and we use the 'structured' directive to resolve the entity attribute as an attribute group.
console.log('Resolving logical entity with structured directive.');
resOpt.directives = new cdm.types.AttributeResolutionDirectiveSet(new Set<string>([ 'normalized', 'structured' ]));
const resStructuredEntity = await entity.createResolvedEntityAsync(`structured_${entity.entityName}`, resOpt, resolvedFolder);
await resStructuredEntity.inDocument.saveAsAsync(`${resStructuredEntity.entityName}.cdm.json`);
// Now let us remove the 'normalized' directive so the array expansion operation can run.
console.log('Resolving logical entity without directives (array expansion).');
resOpt.directives = new cdm.types.AttributeResolutionDirectiveSet(new Set<string>([ ]));
const resArrayEntity = await entity.createResolvedEntityAsync(`array_expansion_${entity.entityName}`, resOpt, resolvedFolder);
await resArrayEntity.inDocument.saveAsAsync(`${resArrayEntity.entityName}.cdm.json`);
}
/**
* Applies the replaceAsForeignKey and addAttributeGroup operations to the entity attribute provided.
* @param name entityAttr
* @param name fkAttrName
* @param name attrGroupName
*/
function applyDefaultBehavior(entityAttr: cdm.types.CdmEntityAttributeDefinition, fkAttrName: string, attrGroupName: string) {
const ctx = entityAttr.ctx;
const projection = new cdm.types.CdmProjection(ctx);
// Link for the Source property documentation.
// https://docs.microsoft.com/en-us/common-data-model/sdk/convert-logical-entities-resolved-entities#source
projection.source = entityAttr.entity;
// Link for the RunSequentially property documentation.
// https://docs.microsoft.com/en-us/common-data-model/sdk/convert-logical-entities-resolved-entities#run-sequentially
projection.runSequentially = true;
entityAttr.entity = new cdm.types.CdmEntityReference(ctx, projection, false);
if (fkAttrName) {
const foreignKeyAttr = new cdm.types.CdmTypeAttributeDefinition(ctx, fkAttrName);
foreignKeyAttr.dataType = new cdm.types.CdmDataTypeReference(ctx, 'entityId', true);
// Link for the ReplaceAsForeignKey operation documentation.
// https://docs.microsoft.com/en-us/common-data-model/sdk/projections/replaceasforeignkey
const replaceAsFKOperation = new cdm.types.CdmOperationReplaceAsForeignKey(ctx);
replaceAsFKOperation.condition = 'referenceOnly';
replaceAsFKOperation.reference = 'addressLine';
replaceAsFKOperation.replaceWith = foreignKeyAttr;
projection.operations.push(replaceAsFKOperation);
}
if (attrGroupName) {
// Link for the AddAttributeGroup operation documentation.
// https://docs.microsoft.com/en-us/common-data-model/sdk/projections/addattributegroup
const addAttrGroupOperation = new cdm.types.CdmOperationAddAttributeGroup(ctx);
addAttrGroupOperation.condition = 'structured';
addAttrGroupOperation.attributeGroupName = attrGroupName;
projection.operations.push(addAttrGroupOperation);
}
}
/**
* Applies the arrayExpansion operation to the entity attribute provided.
* It also takes care of applying a renameAttributes operation and optionally applying a addCountAttribute operation.
* @param name entityAttr
* @param name startOrdinal
* @param name endOrdinal
* @param name renameFormat
* @param name countAttName
*/
function applyArrayExpansion(entityAttr: cdm.types.CdmEntityAttributeDefinition, startOrdinal: number, endOrdinal: number, renameFormat: string, countAttName?: string) {
const ctx: cdm.types.CdmCorpusContext = entityAttr.ctx;
const projection = new cdm.types.CdmProjection(ctx);
projection.source = entityAttr.entity;
projection.runSequentially = true;
// Link for the Condition property documentation.
// https://docs.microsoft.com/en-us/common-data-model/sdk/convert-logical-entities-resolved-entities#condition
projection.condition = '!normalized';
entityAttr.entity = new cdm.types.CdmEntityReference(ctx, projection, false);
// Link for the ArrayExpansion operation documentation.
// https://docs.microsoft.com/en-us/common-data-model/sdk/projections/arrayexpansion
const arrExpansionOperation = new cdm.types.CdmOperationArrayExpansion(ctx);
arrExpansionOperation.startOrdinal = startOrdinal;
arrExpansionOperation.endOrdinal = endOrdinal;
projection.operations.push(arrExpansionOperation);
// Link for the RenameAttributes operation documentation.
// https://docs.microsoft.com/en-us/common-data-model/sdk/projections/renameattributes
// Doing an ArrayExpansion without a RenameAttributes afterwards will result in the expanded attributes being merged in the final resolved entity.
// This is because ArrayExpansion does not rename the attributes it expands by default. The expanded attributes end up with the same name and gets merged.
// Example: We expand A to A[1], A[2], A[3], but A[1], A[2], A[3] are still named "A".
const renameAttrsOperation = new cdm.types.CdmOperationRenameAttributes(ctx);
renameAttrsOperation.renameFormat = renameFormat;
projection.operations.push(renameAttrsOperation);
if (countAttName) {
const countAttribute = new cdm.types.CdmTypeAttributeDefinition(ctx, countAttName);
countAttribute.dataType = new cdm.types.CdmDataTypeReference(ctx, 'integer', true);
// Link for the AddCountAttribute operation documentation.
// https://docs.microsoft.com/en-us/common-data-model/sdk/projections/addcountattribute
// It is recommended, but not mandated, to be used with the ArrayExpansion operation to provide an ArrayExpansion a count attribute that
// represents the total number of expanded elements. AddCountAttribute can also be used by itself.
const addCountAttrOperation = new cdm.types.CdmOperationAddCountAttribute(ctx);
addCountAttrOperation.countAttribute = countAttribute;
projection.operations.push(addCountAttrOperation);
}
}
runSample(); | the_stack |
import {OrchestratorHelper} from './orchestratorhelper';
import {Utility} from './utility';
import * as fs from 'fs-extra';
import * as path from 'path';
const ReadText: any = require('read-text-file');
export class OrchestratorDataSource {
public Type: string = '';
public Id: string = '';
public Version: string = '';
public Key: string = '';
public Endpoint: string = '';
public RoutingName: string = '';
public FilePath: string = '';
// eslint-disable-next-line max-params
constructor(id: string, key: string, version: string, endpoint: string, type: string, routingName: string, filePath: string) {
this.Id = id;
this.Key = key;
this.Version = version;
this.Endpoint = endpoint;
this.Type = type;
this.FilePath = filePath;
this.RoutingName = routingName;
}
public update(input: OrchestratorDataSource) {
this.Key = input.Key;
if (input.Version.length > 0 && input.Version !== this.Version) {
this.Version = input.Version;
}
if (input.Endpoint.length > 0 && input.Endpoint !== this.Endpoint) {
this.Endpoint = input.Endpoint;
}
if (input.RoutingName.length > 0 && input.RoutingName !== this.RoutingName) {
this.RoutingName = input.RoutingName;
}
if (input.FilePath.length > 0 && input.FilePath !== this.FilePath) {
this.FilePath = input.FilePath;
}
}
}
export class OrchestratorDataSourceSettings {
public hierarchical: boolean = false;
public inputs: OrchestratorDataSource[] = [];
public path: string;
constructor(inputs: any, hierarchical: boolean, path: string) {
for (const input of inputs) {
this.inputs.push(new OrchestratorDataSource(
input.id,
input.key,
input.version,
input.endpoint,
input.type,
input.routingName,
input.filePath));
}
this.hierarchical = hierarchical;
this.path = path;
}
public hasDataSource(input: OrchestratorDataSource, updateExisting: boolean = true): boolean {
for (const existingSource of this.inputs) {
if (existingSource.Type !== input.Type) {
continue;
}
switch (input.Type) {
case 'luis':
case 'qna':
if (input.Id === existingSource.Id) {
if (updateExisting) {
existingSource.update(input);
}
return true;
}
break;
case 'file':
if (input.FilePath === existingSource.FilePath) {
if (updateExisting) {
existingSource.update(input);
}
return true;
}
break;
default:
throw new Error('Invalid input type');
}
}
return false;
}
public remove(input: OrchestratorDataSource): OrchestratorDataSource | null {
let i: number;
for (i = 0; i < this.inputs.length; i++) {
const existingSource: OrchestratorDataSource = this.inputs[i];
if (existingSource.Type !== input.Type) {
continue;
}
switch (input.Type) {
case 'luis':
case 'qna':
if (input.Id === existingSource.Id) {
this.inputs.splice(i, 1);
return input;
}
break;
case 'file':
if (input.FilePath === existingSource.FilePath) {
this.inputs.splice(i, 1);
return input;
}
break;
default:
throw new Error('Invalid input type');
}
}
return null;
}
}
export class OrchestratorSettings {
public static OrchestratorSettingsFileName: string = 'orchestratorsettings.json';
public constructor() {
this.ModelPath = '';
this.EntityModelPath = '';
this.SnapshotPath = '';
this.SettingsPath = '';
this.DataSources = new OrchestratorDataSourceSettings([], false, '');
}
public static hasBaseModelSettings(settingsDir: string) {
const settingsFile: string = path.join(settingsDir, OrchestratorSettings.OrchestratorSettingsFileName);
if (OrchestratorHelper.exists(settingsFile)) {
const settings: any = JSON.parse(OrchestratorSettings.readFile(settingsFile));
return settings.modelPath && settings.modelPath.length > 0;
}
return false;
}
public hasDataSource(input: OrchestratorDataSource): boolean {
return this.DataSources.hasDataSource(input);
}
public addUpdateDataSource(data: OrchestratorDataSource) {
this.DataSources.inputs.push(data);
}
public static getCurrent(): OrchestratorSettings {
if (!OrchestratorSettings.Current) {
OrchestratorSettings.Current = new OrchestratorSettings();
}
return OrchestratorSettings.Current;
}
public static Current: OrchestratorSettings;
public ModelPath: string;
public EntityModelPath: string;
public SnapshotPath: string;
public SettingsPath: string;
public DataSources: OrchestratorDataSourceSettings;
public static readFile(filePath: string): string {
return ReadText.readSync(filePath);
}
public static writeToFile(filePath: string, content: string): string {
fs.writeFileSync(filePath, content);
return filePath;
}
// eslint-disable-next-line max-params
public init(
settingsDir: string,
baseModelPath: string,
entityBaseModelPath: string,
snapshotPath: string,
hierarchical: boolean = false,
hasDataSources: boolean = false,
settingsFileName: string = OrchestratorSettings.OrchestratorSettingsFileName): void {
settingsDir = path.resolve(settingsDir);
const settingsFile: string = path.join(settingsDir, settingsFileName);
this.SettingsPath = settingsFile;
const settingsFileExists: boolean = OrchestratorHelper.exists(settingsFile);
try {
let settings: any;
if (settingsFileExists) {
settings = JSON.parse(OrchestratorSettings.readFile(settingsFile));
if (settings.dataSources && settings.dataSources.inputs.length > 0) {
hasDataSources = true;
}
}
if (hasDataSources) {
this.ensureDataSources(hierarchical, settings, settingsDir);
}
this.SnapshotPath = OrchestratorSettings.ensureSnapshotPath(snapshotPath, settingsDir, settings);
this.ModelPath = OrchestratorSettings.ensureBaseModelPath(baseModelPath, settings);
entityBaseModelPath = OrchestratorSettings.ensureEntityBaseModelPath(entityBaseModelPath, settings);
if (!Utility.isEmptyString(entityBaseModelPath)) {
this.EntityModelPath = entityBaseModelPath;
}
} catch (error) {
Utility.debuggingLog(`Failed initializing settings ${error.message}`);
}
}
public persist() {
if (this.SettingsPath.length === 0) {
throw new Error('settings not initialized.');
}
try {
const settings: any = (this.EntityModelPath) ? {
modelPath: this.ModelPath,
entityModelPath: this.EntityModelPath,
snapshotPath: this.SnapshotPath,
dataSources: this.DataSources,
} : {
modelPath: this.ModelPath,
snapshotPath: this.SnapshotPath,
dataSources: this.DataSources,
};
OrchestratorSettings.writeToFile(this.SettingsPath, OrchestratorHelper.jsonStringify(settings));
} catch (error) {
throw new Error(error);
}
}
static ensureEntityBaseModelPath(entityBaseModelPath: string, settings: any): string {
if (!Utility.isEmptyString(entityBaseModelPath)) {
entityBaseModelPath = path.resolve(entityBaseModelPath);
if (!OrchestratorHelper.exists(entityBaseModelPath)) {
Utility.debuggingLog(`Invalid entity model path ${entityBaseModelPath}`);
throw new Error('Invalid entity model path');
}
} else if (settings && 'entityModelPath' in settings) {
entityBaseModelPath = path.resolve(settings.entityModelPath);
}
return entityBaseModelPath;
}
static ensureBaseModelPath(baseModelPath: string, settings: any): string {
if (!Utility.isEmptyString(baseModelPath)) {
baseModelPath = path.resolve(baseModelPath);
if (!OrchestratorHelper.exists(baseModelPath)) {
Utility.debuggingLog(`Invalid model path ${baseModelPath}`);
throw new Error('Invalid model path');
}
} else if (!settings || !settings.modelPath || settings.modelPath.length === 0) {
throw new Error('Missing model path');
} else {
baseModelPath = path.resolve(settings.modelPath);
}
return baseModelPath;
}
static ensureSnapshotPath(snapshotPath: string, defaultSnapshotPath: string, settings: any): string {
if (!Utility.isEmptyString(snapshotPath)) {
snapshotPath = path.resolve(snapshotPath);
if (!OrchestratorHelper.exists(snapshotPath)) {
let snapshotDir: string = path.dirname(snapshotPath);
let snapshotFile: string = path.basename(snapshotPath);
if (!snapshotFile.includes('.')) {
snapshotDir = snapshotPath;
snapshotFile = OrchestratorHelper.SnapshotFileName;
}
fs.mkdirSync(snapshotDir, {recursive: true});
snapshotPath = path.join(snapshotDir, snapshotFile);
}
} else if (!settings || !settings.snapshotPath || settings.snapshotPath.length === 0) {
snapshotPath = defaultSnapshotPath;
} else {
snapshotPath = settings.snapshotPath;
}
return snapshotPath;
}
ensureDataSources(hierarchical: boolean, settings: any, settingsFolder: string) {
try {
let inputs: OrchestratorDataSource[] = [];
let dataSourcePath: string = path.join(settingsFolder, 'dataSources');
if (!OrchestratorHelper.exists(dataSourcePath)) {
fs.mkdirSync(dataSourcePath, {recursive: true});
}
if (!settings) {
this.DataSources = new OrchestratorDataSourceSettings(inputs, hierarchical, dataSourcePath);
return;
}
const dataSourceSettings: any = settings.dataSources;
if (dataSourceSettings) {
if (dataSourceSettings.inputs) {
inputs = dataSourceSettings.inputs;
}
hierarchical = dataSourceSettings.hierarchical;
dataSourcePath = path.resolve(dataSourceSettings.path);
}
this.DataSources = new OrchestratorDataSourceSettings(inputs, hierarchical, dataSourcePath);
} catch {
this.DataSources = new OrchestratorDataSourceSettings([], false, '');
}
}
} | the_stack |
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable, throwError, timer, Subject } from 'rxjs';
import { retry, catchError, shareReplay, switchMap, takeUntil } from 'rxjs/operators';
import { environment } from '../../../environments/environment';
const CACHE_SIZE = 1;
const REFRESH_INTERVAL = 10000;
@Injectable({
providedIn: 'root'
})
export class ApiService {
private actionsCache$: Observable<any>;
private reloadActions$ = new Subject<void>();
// Define API
apiURL = environment.BASE_URL;
// Http Options
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
constructor(private http: HttpClient) { }
// Custom Actions API Start
requestActions(): Observable<any> {
if (!this.actionsCache$) {
// Set up timer that ticks every X milliseconds
const timer$ = timer(0, REFRESH_INTERVAL);
// For each tick make an http request to fetch new data
this.actionsCache$ = timer$.pipe(
switchMap(_ => this.requestGetActions()),
takeUntil(this.reloadActions$),
shareReplay(CACHE_SIZE)
);
}
return this.actionsCache$;
}
forceActionsCacheReload(type: string) {
if (type === 'reset') {
// Calling next will complete the current cache instance
this.reloadActions$.next();
// Setting the cache to null will create a new cache the
this.actionsCache$ = null;
} else if (type === 'finish') {
// Calling next will complete the current cache instance
this.reloadActions$.next();
}
}
requestGetActions() {
return this.http.get(this.apiURL + '/custom_actions', this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
createAction(stub: any) {
// tslint:disable-next-line: max-line-length
return this.http.post(this.apiURL + '/custom_actions', JSON.stringify(stub), this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
editAction(stub: any) {
// tslint:disable-next-line: max-line-length
return this.http.put(this.apiURL + '/custom_actions', JSON.stringify(stub), this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
deleteAction(objectId: any) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
body: {
object_id: objectId,
}
};
// tslint:disable-next-line: max-line-length
return this.http.delete(this.apiURL + '/custom_actions', httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
// Custom Action API End
// Refresh DB API Start
refreshAppDB() {
// tslint:disable-next-line: max-line-length
return this.http.get(this.apiURL + '/refresh_db', this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
// Refresh DB API End
// Conversations API Start
private conversationsCache$: Observable<any>;
private reloadConversations$ = new Subject<void>();
requestConversations(pageIndex: number, pageSize: number): Observable<any> {
if (!this.conversationsCache$) {
// Set up timer that ticks every X milliseconds
const timer$ = timer(0, REFRESH_INTERVAL);
// For each tick make an http request to fetch new data
this.conversationsCache$ = timer$.pipe(
switchMap(_ => this.requestGetConversations(pageIndex, pageSize)),
takeUntil(this.reloadConversations$),
shareReplay(CACHE_SIZE)
);
}
return this.conversationsCache$;
}
requestGetConversations(pageIndex: number, pageSize: number) {
return this.http.get(this.apiURL + '/all_conversations/' + pageIndex + '/' + pageSize, this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
requestConversationChats(conversationId: string) {
return this.http.get(this.apiURL + '/conversation/' + conversationId, this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
forceConversationsCacheReload(type: string) {
if (type === 'reset') {
// Calling next will complete the current cache instance
this.reloadConversations$.next();
// Setting the cache to null will create a new cache the
this.conversationsCache$ = null;
} else if (type === 'finish') {
// Calling next will complete the current cache instance
this.reloadConversations$.next();
}
}
// Conversations API End
// Projects API Start
private projectsCache$: Observable<any>;
private reloadProjects$ = new Subject<void>();
requestProjects(): Observable<any> {
if (!this.projectsCache$) {
// Set up timer that ticks every X milliseconds
const timer$ = timer(0, REFRESH_INTERVAL);
// For each tick make an http request to fetch new data
this.projectsCache$ = timer$.pipe(
switchMap(_ => this.requestGetProjects()),
takeUntil(this.reloadProjects$),
shareReplay(CACHE_SIZE)
);
}
return this.projectsCache$;
}
forceProjectsCacheReload(type: string) {
if (type === 'reset') {
// Calling next will complete the current cache instance
this.reloadProjects$.next();
// Setting the cache to null will create a new cache the
this.projectsCache$ = null;
} else if (type === 'finish') {
// Calling next will complete the current cache instance
this.reloadProjects$.next();
}
}
requestGetProjects() {
return this.http.get(this.apiURL + '/projects', this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
createProject(stub: any) {
// tslint:disable-next-line: max-line-length
return this.http.post(this.apiURL + '/projects', JSON.stringify(stub), this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
editProject(stub: any) {
// tslint:disable-next-line: max-line-length
return this.http.put(this.apiURL + '/projects', JSON.stringify(stub), this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
deleteProject(objectId: any) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
body: {
object_id: objectId,
}
};
// tslint:disable-next-line: max-line-length
return this.http.delete(this.apiURL + '/projects', httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
copyProject(stub: any) {
// tslint:disable-next-line: max-line-length
return this.http.post(this.apiURL + '/copy_project', JSON.stringify(stub), this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
// Projects API Start
// Domains API Start
private domainsCache$: Observable<any>;
private reloadDomains$ = new Subject<void>();
requestDomains(projectObjectId: string): Observable<any> {
if (!this.domainsCache$) {
// Set up timer that ticks every X milliseconds
const timer$ = timer(0, REFRESH_INTERVAL);
// For each tick make an http request to fetch new data
this.domainsCache$ = timer$.pipe(
switchMap(_ => this.requestGetDomains(projectObjectId)),
takeUntil(this.reloadDomains$),
shareReplay(CACHE_SIZE)
);
}
return this.domainsCache$;
}
forceDomainsCacheReload(type: string) {
if (type === 'reset') {
// Calling next will complete the current cache instance
this.reloadDomains$.next();
// Setting the cache to null will create a new cache the
this.domainsCache$ = null;
} else if (type === 'finish') {
// Calling next will complete the current cache instance
this.reloadDomains$.next();
}
}
requestGetDomains(projectObjectId: string) {
return this.http.get(this.apiURL + '/domains/' + projectObjectId, this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
createDomain(stub: any, projectObjectId: string) {
// tslint:disable-next-line: max-line-length
return this.http.post(this.apiURL + '/domains/' + projectObjectId, JSON.stringify(stub), this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
editDomain(stub: any, projectObjectId: string) {
// tslint:disable-next-line: max-line-length
return this.http.put(this.apiURL + '/domains/' + projectObjectId, JSON.stringify(stub), this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
deleteDomain(objectId: any, projectObjectId: string) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
body: {
object_id: objectId,
}
};
// tslint:disable-next-line: max-line-length
return this.http.delete(this.apiURL + '/domains/' + projectObjectId, httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
// Domains API End
// Intents API Start
private intentsCache$: Observable<any>;
private reloadIntents$ = new Subject<void>();
private intentDetailsCache$: Observable<any>;
private reloadIntentDetails$ = new Subject<void>();
requestIntents(projectObjectId: string, domainObjectId: string): Observable<any> {
if (!this.intentsCache$) {
// Set up timer that ticks every X milliseconds
const timer$ = timer(0, REFRESH_INTERVAL);
// For each tick make an http request to fetch new data
this.intentsCache$ = timer$.pipe(
switchMap(_ => this.requestGetIntents(projectObjectId, domainObjectId)),
takeUntil(this.reloadIntents$),
shareReplay(CACHE_SIZE)
);
}
return this.intentsCache$;
}
requestIntentDetails(intentObjectId: string): Observable<any> {
if (!this.intentDetailsCache$) {
// Set up timer that ticks every X milliseconds
const timer$ = timer(0, REFRESH_INTERVAL);
// For each tick make an http request to fetch new data
this.intentDetailsCache$ = timer$.pipe(
switchMap(_ => this.requestGetIntentDetails(intentObjectId)),
takeUntil(this.reloadIntentDetails$),
shareReplay(CACHE_SIZE)
);
}
return this.intentDetailsCache$;
}
forceIntentsCacheReload(type: string) {
if (type === 'reset') {
// Calling next will complete the current cache instance
this.reloadIntents$.next();
// Setting the cache to null will create a new cache the
this.intentsCache$ = null;
} else if (type === 'finish') {
// Calling next will complete the current cache instance
this.reloadIntents$.next();
}
}
forceIntentDetailsCacheReload(type: string) {
if (type === 'reset') {
// Calling next will complete the current cache instance
this.reloadIntentDetails$.next();
// Setting the cache to null will create a new cache the
this.intentDetailsCache$ = null;
} else if (type === 'finish') {
// Calling next will complete the current cache instance
this.reloadIntentDetails$.next();
}
}
requestGetIntents(projectObjectId: string, domainObjectId: string) {
let params = new HttpParams()
.set('project_id', projectObjectId)
.set('domain_id', domainObjectId);
return this.http.get(this.apiURL + '/intents', { params })
.pipe(
retry(1),
catchError(this.handleError)
);
}
requestGetIntentDetails(intentObjectId: string) {
return this.http.get(this.apiURL + '/intent_details/' + intentObjectId, this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
createIntent(stub: any) {
// tslint:disable-next-line: max-line-length
return this.http.post(this.apiURL + '/intents', JSON.stringify(stub), this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
createIntentText(stub: any, intentObjectId: string) {
// tslint:disable-next-line: max-line-length
return this.http.post(this.apiURL + '/intent_details/' + intentObjectId, JSON.stringify(stub), this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
editIntent(stub: any) {
// tslint:disable-next-line: max-line-length
return this.http.put(this.apiURL + '/intents', JSON.stringify(stub), this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
editIntentText(stub: any, intentObjectId: string) {
// tslint:disable-next-line: max-line-length
return this.http.put(this.apiURL + '/intent_details/' + intentObjectId, JSON.stringify(stub), this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
deleteIntent(stub: object) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
body: stub
};
// tslint:disable-next-line: max-line-length
return this.http.delete(this.apiURL + '/intents', httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
deleteIntentText(stub: object, intentObjectId: string) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
body: stub
};
// tslint:disable-next-line: max-line-length
return this.http.delete(this.apiURL + '/intent_details/' + intentObjectId, httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
// Intents API End
// Responses API Start
private responsesCache$: Observable<any>;
private reloadResponses$ = new Subject<void>();
private responseDetailsCache$: Observable<any>;
private reloadResponseDetails$ = new Subject<void>();
requestResponses(projectObjectId: string, domainObjectId: string): Observable<any> {
if (!this.responsesCache$) {
// Set up timer that ticks every X milliseconds
const timer$ = timer(0, REFRESH_INTERVAL);
// For each tick make an http request to fetch new data
this.responsesCache$ = timer$.pipe(
switchMap(_ => this.requestGetResponses(projectObjectId, domainObjectId)),
takeUntil(this.reloadResponses$),
shareReplay(CACHE_SIZE)
);
}
return this.responsesCache$;
}
requestResponseDetails(responseObjectId: string): Observable<any> {
if (!this.responseDetailsCache$) {
// Set up timer that ticks every X milliseconds
const timer$ = timer(0, REFRESH_INTERVAL);
// For each tick make an http request to fetch new data
this.responseDetailsCache$ = timer$.pipe(
switchMap(_ => this.requestGetResponseDetails(responseObjectId)),
takeUntil(this.reloadResponseDetails$),
shareReplay(CACHE_SIZE)
);
}
return this.responseDetailsCache$;
}
forceResponsesCacheReload(type: string) {
if (type === 'reset') {
// Calling next will complete the current cache instance
this.reloadResponses$.next();
// Setting the cache to null will create a new cache the
this.responsesCache$ = null;
} else if (type === 'finish') {
// Calling next will complete the current cache instance
this.reloadResponses$.next();
}
}
forceResponseDetailsCacheReload(type: string) {
if (type === 'reset') {
// Calling next will complete the current cache instance
this.reloadResponseDetails$.next();
// Setting the cache to null will create a new cache the
this.responseDetailsCache$ = null;
} else if (type === 'finish') {
// Calling next will complete the current cache instance
this.reloadResponseDetails$.next();
}
}
requestGetResponses(projectObjectId: string, domainObjectId: string) {
let params = new HttpParams()
.set('project_id', projectObjectId)
.set('domain_id', domainObjectId);
return this.http.get(this.apiURL + '/responses', { params })
.pipe(
retry(1),
catchError(this.handleError)
);
}
requestGetResponseDetails(responseObjectId: string) {
return this.http.get(this.apiURL + '/responses_details/' + responseObjectId, this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
createResponse(stub: any) {
// tslint:disable-next-line: max-line-length
return this.http.post(this.apiURL + '/responses', JSON.stringify(stub), this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
createResponseText(stub: any, responseObjectId: string) {
return this.http.post(this.apiURL + '/responses_details/' + responseObjectId, JSON.stringify(stub), this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
editResponse(stub: any) {
// tslint:disable-next-line: max-line-length
return this.http.put(this.apiURL + '/responses', JSON.stringify(stub), this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
deleteResponse(stub: object) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
body: stub
};
// tslint:disable-next-line: max-line-length
return this.http.delete(this.apiURL + '/responses', httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
deleteResponseText(stub: object, responseObjectId: string) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
body: stub
};
// tslint:disable-next-line: max-line-length
return this.http.delete(this.apiURL + '/responses_details/' + responseObjectId, httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
// Responses API End
// Stories API Start
private storiesCache$: Observable<any>;
private reloadStories$ = new Subject<void>();
private storyDetailsCache$: Observable<any>;
private reloadStoryDetails$ = new Subject<void>();
requestStories(projectObjectId: string, domainObjectId: string): Observable<any> {
if (!this.storiesCache$) {
// Set up timer that ticks every X milliseconds
const timer$ = timer(0, REFRESH_INTERVAL);
// For each tick make an http request to fetch new data
this.storiesCache$ = timer$.pipe(
switchMap(_ => this.requestGetStories(projectObjectId, domainObjectId)),
takeUntil(this.reloadStories$),
shareReplay(CACHE_SIZE)
);
}
return this.storiesCache$;
}
requestStoryDetails(storyObjectId: string): Observable<any> {
if (!this.storyDetailsCache$) {
// Set up timer that ticks every X milliseconds
const timer$ = timer(0, REFRESH_INTERVAL);
// For each tick make an http request to fetch new data
this.storyDetailsCache$ = timer$.pipe(
switchMap(_ => this.requestGetStoryDetails(storyObjectId)),
takeUntil(this.reloadStoryDetails$),
shareReplay(CACHE_SIZE)
);
}
return this.storyDetailsCache$;
}
forceStoriesCacheReload(type: string) {
if (type === 'reset') {
// Calling next will complete the current cache instance
this.reloadStories$.next();
// Setting the cache to null will create a new cache the
this.storiesCache$ = null;
} else if (type === 'finish') {
// Calling next will complete the current cache instance
this.reloadStories$.next();
}
}
forceStoryDetailsCacheReload(type: string) {
if (type === 'reset') {
// Calling next will complete the current cache instance
this.reloadStoryDetails$.next();
// Setting the cache to null will create a new cache the
this.storyDetailsCache$ = null;
} else if (type === 'finish') {
// Calling next will complete the current cache instance
this.reloadStoryDetails$.next();
}
}
requestGetStories(projectObjectId: string, domainObjectId: string) {
let params = new HttpParams()
.set('project_id', projectObjectId)
.set('domain_id', domainObjectId);
return this.http.get(this.apiURL + '/story', { params })
.pipe(
retry(1),
catchError(this.handleError)
);
}
requestGetStoryDetails(storyObjectId: string) {
return this.http.get(this.apiURL + '/story_details/' + storyObjectId, this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
createStory(stub: any) {
// tslint:disable-next-line: max-line-length
return this.http.post(this.apiURL + '/story', JSON.stringify(stub), this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
insertStoryDetails(stub: any, storyObjectId: string) {
return this.http.post(this.apiURL + '/story_details/' + storyObjectId, JSON.stringify(stub), this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
editStory(stub: any) {
// tslint:disable-next-line: max-line-length
return this.http.put(this.apiURL + '/story', JSON.stringify(stub), this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
updateStoryDetails(stub: any, storyObjectId: string) {
return this.http.put(this.apiURL + '/story_details/' + storyObjectId, JSON.stringify(stub), this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
deleteStory(stub: object) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
body: stub
};
// tslint:disable-next-line: max-line-length
return this.http.delete(this.apiURL + '/story', httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
deleteStoryDetails(stub: object, storyObjectId: string) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
body: stub
};
// tslint:disable-next-line: max-line-length
return this.http.delete(this.apiURL + '/story_details/' + storyObjectId, httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
// Stories API End
// Entities API Start
private entiitesCache$: Observable<any>;
private reloadEntities$ = new Subject<void>();
requestEntities(projectObjectId: string): Observable<any> {
if (!this.entiitesCache$) {
// Set up timer that ticks every X milliseconds
const timer$ = timer(0, REFRESH_INTERVAL);
// For each tick make an http request to fetch new data
this.entiitesCache$ = timer$.pipe(
switchMap(_ => this.requestGetEntities(projectObjectId)),
takeUntil(this.reloadEntities$),
shareReplay(CACHE_SIZE)
);
}
return this.entiitesCache$;
}
forceEntitiesCacheReload(type: string) {
if (type === 'reset') {
// Calling next will complete the current cache instance
this.reloadEntities$.next();
// Setting the cache to null will create a new cache the
this.entiitesCache$ = null;
} else if (type === 'finish') {
// Calling next will complete the current cache instance
this.reloadEntities$.next();
}
}
requestGetEntities(projectObjectId: string) {
return this.http.get(this.apiURL + '/entities/' + projectObjectId, this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
createEntity(stub: any, projectObjectId: string) {
// tslint:disable-next-line: max-line-length
return this.http.post(this.apiURL + '/entities/' + projectObjectId, JSON.stringify(stub), this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
editEntity(stub: any, projectObjectId: string) {
// tslint:disable-next-line: max-line-length
return this.http.put(this.apiURL + '/entities/' + projectObjectId, JSON.stringify(stub), this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
deleteEntity(objectId: string, projectObjectId: string) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
body: {
object_id: objectId,
}
};
// tslint:disable-next-line: max-line-length
return this.http.delete(this.apiURL + '/entities/' + projectObjectId, httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
// Entities API End
// Import Export Projects API Start
importProject(projectStub: any) {
// tslint:disable-next-line: max-line-length
return this.http.post(this.apiURL + '/import_model', JSON.stringify(projectStub), this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
exportProject(projectName: any) {
// tslint:disable-next-line: max-line-length
return this.http.post(this.apiURL + '/export_model', JSON.stringify({project_name: projectName}), this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
//Import Export Projects API End
// Entities API Start
private trainingCache$: Observable<any>;
private reloadTraining$ = new Subject<void>();
checkModelTrainStatus(trainTaskId: string): Observable<any> {
if (!this.trainingCache$) {
// Set up timer that ticks every X milliseconds
const timer$ = timer(0, REFRESH_INTERVAL);
// For each tick make an http request to fetch new data
this.trainingCache$ = timer$.pipe(
switchMap(_ => this.checkModelTrainingStatus(trainTaskId)),
takeUntil(this.reloadTraining$),
shareReplay(CACHE_SIZE)
);
}
return this.trainingCache$;
}
forceModelTrainingCacheReload(type: string) {
if (type === 'reset') {
// Calling next will complete the current cache instance
this.reloadTraining$.next();
// Setting the cache to null will create a new cache the
this.trainingCache$ = null;
} else if (type === 'finish') {
// Calling next will complete the current cache instance
this.reloadTraining$.next();
}
}
requestModelTraining(projectObjectId: string) {
return this.http.get(this.apiURL + '/train/' + projectObjectId, this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
checkModelTrainingStatus(trainTaskId: string) {
return this.http.get(this.apiURL + '/task_status/' + trainTaskId, this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
getModelTrainingResult(trainTaskId: string) {
return this.http.get(this.apiURL + '/task_result/' + trainTaskId, this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
deployTrainedModel(modelPublishPath: string) {
return this.http.get(this.apiURL + '/publish_model?model_path=' + modelPublishPath, this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
tryNowTrainedModel(modelPublishPath: string, sessionId: string) {
return this.http.get(this.apiURL + '/try_now?model_path=' + modelPublishPath + '&session_id=' + sessionId, this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
tryNowModel(sessionId: string, chatMessage: string) {
// tslint:disable-next-line: max-line-length
return this.http.post(this.apiURL + '/try_now', JSON.stringify({sessionId: sessionId, message: chatMessage}), this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
clearCache(cacheName: string) {
// tslint:disable-next-line: max-line-length
return this.http.get(this.apiURL + '/clear_cache/' + cacheName, this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
);
}
// Entities API End
// Error handling
handleError(error) {
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
// Get client-side error
errorMessage = error.error.message;
} else {
// Get server-side error
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
window.alert(errorMessage);
return throwError(errorMessage);
}
} | the_stack |
import {BoxrecCommonTablesColumnsClass} from "../../../boxrec-common-tables/boxrec-common-tables-columns.class";
import {BoxrecTitles} from "../../../boxrec-common-tables/boxrec-common.constants";
import {OutputGetter, OutputInterface} from "../../../decorators/output.decorator";
import {convertFractionsToNumber, parseHeight, trimRemoveLineBreaks} from "../../../helpers";
import {BoxrecBasic, BoxrecJudge, Record, Stance, WinLossDraw} from "../../boxrec.constants";
import {WeightDivision} from "../../champions/boxrec.champions.constants";
import {BoxingBoutOutcome, BoxingBoutOutcomeKeys} from "../boxrec.event.constants";
import {BoxrecPageEvent} from "../boxrec.page.event";
import {
BoutPageBoutOutcome,
BoutPageLast6,
BoutPageOutcome,
BoxrecEventBoutOutput
} from "./boxrec.event.bout.constants";
/**
* Parse a BoxRec bout page
* Note: because BoxRec is using inline styles for a lot of things, can't guarantee perfect results. Report issues
* <pre>http://boxrec.com/en/event/726555/2037455</pre>
*/
@OutputGetter([
"bouts", "commission", "date", "division", "doctors", "firstBoxer", "firstBoxerAge",
"firstBoxerHeight", "firstBoxerKOs", "firstBoxerLast6", "firstBoxerPointsAfter",
"firstBoxerPointsBefore", "firstBoxerRanking", "firstBoxerReach", "firstBoxerRecord",
"firstBoxerStance", "id", "inspector", "judges", "location", "matchmakers", "media",
"numberOfBouts", "numberOfRounds", "outcome", "promoters", "rating", "referee",
"secondBoxer", "secondBoxerAge", "secondBoxerHeight", "secondBoxerKOs",
"secondBoxerLast6", "secondBoxerPointsAfter", "secondBoxerPointsBefore",
"secondBoxerRanking", "secondBoxerReach", "secondBoxerRecord", "secondBoxerStance",
"television", "titles",
])
export class BoxrecPageEventBout extends BoxrecPageEvent implements OutputInterface {
output: BoxrecEventBoutOutput;
private static parseOutcome(outcomeStr: string): BoutPageOutcome {
const trimmedOutcomeStr: string = trimRemoveLineBreaks(outcomeStr);
const matches: RegExpMatchArray | null = trimmedOutcomeStr.match(/^(\w+)\s(\w+)$/);
const outcomeObj: BoutPageOutcome = {
outcome: null,
outcomeByWayOf: null,
};
if (matches) {
const firstMatch: string = matches[1];
const secondMatch: string = matches[2];
const values: any = BoxingBoutOutcome;
// the outcome table column is flipped depending if they are the first or second boxer
if (firstMatch.length > 1) {
// is the first boxer
outcomeObj.outcomeByWayOf = values[firstMatch] as BoxingBoutOutcome;
outcomeObj.outcome = BoxrecCommonTablesColumnsClass.parseOutcome(secondMatch);
} else {
// is the second boxer
outcomeObj.outcomeByWayOf = values[secondMatch] as BoxingBoutOutcome;
outcomeObj.outcome = BoxrecCommonTablesColumnsClass.parseOutcome(firstMatch);
}
}
return outcomeObj;
}
get date(): string | null {
let date: string | null = this.$(".page h2:nth-child(1) a").text();
if (date) {
date = trimRemoveLineBreaks(date);
return new Date(date).toISOString().slice(0, 10);
}
return date;
}
get division(): WeightDivision | null {
return BoxrecCommonTablesColumnsClass.parseDivision(this.parseDivision("division"));
}
get firstBoxer(): BoxrecBasic {
const boxer: string = this.parseBoxers("first");
return BoxrecCommonTablesColumnsClass.parseNameAndId(boxer);
}
get firstBoxerAge(): number | null {
return this.parseBoxerAge(1);
}
get firstBoxerHeight(): number[] | null {
return this.parseBoxerHeight(1);
}
get firstBoxerKOs(): number {
return this.getKOs(1);
}
get firstBoxerLast6(): BoutPageLast6[] {
return this.parseLast6Object(true);
}
get firstBoxerPointsAfter(): number | null {
return this.parsePoints(false, 1);
}
get firstBoxerPointsBefore(): number | null {
return this.parsePoints(true, 1);
}
get firstBoxerRanking(): number | null {
return this.parseRankingData(1);
}
get firstBoxerReach(): number[] | null {
return this.parseBoxerReach(1);
}
get firstBoxerRecord(): Record {
return this.getRecord(1);
}
get firstBoxerStance(): Stance | null {
return this.parseBoxerStance(1);
}
get judges(): BoxrecJudge[] {
const judges: BoxrecJudge[] = [];
const judgesArr: string[] = this.parseJudges();
judgesArr.forEach(item => {
const judgeEl: Cheerio = this.$(`<tr>${item}</tr>`);
const judgeObj: BoxrecJudge = {
id: null,
name: null,
scorecard: [],
};
const firstRating: string | null = judgeEl.find("td:nth-child(1)").text();
const nameAndId: string | null = judgeEl.find("td:nth-child(2)").html();
const secondRating: string | null = judgeEl.find("td:nth-child(3)").text();
if (firstRating) {
judgeObj.scorecard[0] = parseInt(firstRating, 10);
}
if (nameAndId) {
const {id, name} = BoxrecCommonTablesColumnsClass.parseNameAndId(nameAndId);
judgeObj.id = id;
judgeObj.name = name;
}
if (secondRating) {
judgeObj.scorecard[1] = parseInt(secondRating, 10);
}
judges.push(judgeObj);
});
return judges;
}
/**
* Returns a number of rounds sanctioned for this bout if it has that number
* @returns {number | null}
*/
get numberOfRounds(): number | null {
const numberOfRounds: string = this.parseDivision("numberOfRounds");
if (numberOfRounds) {
return parseInt(numberOfRounds, 10);
}
return null;
}
get outcome(): BoutPageBoutOutcome {
const outcome: BoutPageBoutOutcome = {
boxer: {
id: null,
name: null,
},
outcome: null,
outcomeByWayOf: null
};
const objRow: Cheerio[] = this.getBoxersSideObjRow();
const textWon: Cheerio = objRow[0].find(".textWon");
const textWonSecond: Cheerio = objRow[1].find(".textWon");
const textDraw: Cheerio = objRow[0].find(".textDrawn");
if (textWon.length === 1 || textWonSecond.length === 1) {
let boxerStr: string = "";
let outcomeString: string | undefined;
if (textWon.length === 1) {
// first boxer won
boxerStr = this.$.html(objRow[0].find(".personLink")[0]);
outcomeString = textWon[0].children[0].data;
} else {
// second boxer won
boxerStr = this.$.html(objRow[0].find(".personLink")[1]);
outcomeString = textWonSecond[0].children[0].data;
}
if (outcomeString) {
const outcomeResult: BoutPageOutcome = this.parseOutcomeOfBout(outcomeString);
outcome.outcome = outcomeResult.outcome;
outcome.outcomeByWayOf = outcomeResult.outcomeByWayOf;
}
const boxer: BoxrecBasic = BoxrecCommonTablesColumnsClass.parseNameAndId(boxerStr);
outcome.boxer.id = boxer.id;
outcome.boxer.name = boxer.name;
} else if (textDraw.length === 2) {
// outcome was a draw
outcome.outcome = WinLossDraw.draw;
// i'm assuming the first boxer should always have the draw info
const firstBoxerDrawText: string | undefined = textDraw[0].children[0].data;
if (firstBoxerDrawText) {
const outcomeResult: BoutPageOutcome = this.parseOutcomeOfBout(firstBoxerDrawText);
outcome.outcomeByWayOf = outcomeResult.outcomeByWayOf;
}
}
return outcome;
}
get rating(): number | null {
let starRating: string | null = this.$(".starRating").parent().html();
if (starRating) {
starRating = `<div>${starRating}</div>`;
return BoxrecCommonTablesColumnsClass.parseRating(starRating);
}
return null;
}
get referee(): BoxrecBasic {
const refereeLink: string = this.$.html(this.$(".responseLessDataTable a:nth-child(1)").get(0));
return BoxrecCommonTablesColumnsClass.parseReferee(refereeLink);
}
get secondBoxer(): BoxrecBasic {
const boxer: string = this.parseBoxers("second");
return BoxrecCommonTablesColumnsClass.parseNameAndId(boxer);
}
get secondBoxerAge(): number | null {
return this.parseBoxerAge(3);
}
get secondBoxerHeight(): number[] | null {
return this.parseBoxerHeight(3);
}
get secondBoxerKOs(): number {
return this.getKOs(3);
}
get secondBoxerLast6(): BoutPageLast6[] {
return this.parseLast6Object(false);
}
get secondBoxerPointsAfter(): number | null {
return this.parsePoints(false, 3);
}
get secondBoxerPointsBefore(): number | null {
return this.parsePoints(true, 3);
}
get secondBoxerRanking(): number | null {
return this.parseRankingData(3);
}
get secondBoxerReach(): number[] | null {
return this.parseBoxerReach(3);
}
get secondBoxerRecord(): Record {
return this.getRecord(3);
}
get secondBoxerStance(): Stance | null {
return this.parseBoxerStance(3);
}
get titles(): BoxrecTitles[] {
const titles: string | null = this.parseTitles();
return BoxrecCommonTablesColumnsClass.parseTitles(titles || "");
}
// this is different than the others found on date/event page
protected getPeopleTable(): Cheerio {
return this.$("h1").parent().find("table").last().find("tbody tr");
}
/**
* Searches page for table columns with `b` tag where the text matches
* @param {string} textToFind
* @returns {Cheerio}
*/
private findColumnByText(textToFind: string = ""): Cheerio {
const filteredCheerio: Cheerio = this.$("td b").filter((index: number, elem: CheerioElement) => {
return this.$(elem).text().trim() === textToFind;
});
if (filteredCheerio.length > 1) {
throw new Error("found two columns with the same name, please report this");
}
return filteredCheerio;
}
private getBoxersSideObjRow(): Cheerio[] {
const boxers: Cheerio[] = [];
this.$("table .personLink").each((i: number, elem: CheerioElement) => {
const href: string = this.$(elem).attr("href");
if (href.includes("boxer") && boxers.length < 2) {
boxers.push(this.$(elem).parent().parent().parent());
}
});
return boxers;
}
private getKOs(tableColumn: number): number {
const knockouts: string = this.parseMiddleRowByText("KOs", tableColumn) as string;
return parseInt(knockouts, 10);
}
private getRecord(tableColumn: number): Record {
const won: string = this.parseMiddleRowByText("won", tableColumn) as string;
const lost: string = this.parseMiddleRowByText("lost", tableColumn) as string;
const drawn: string = this.parseMiddleRowByText("drawn", tableColumn) as string;
return {
draw: parseInt(drawn, 10),
loss: parseInt(lost, 10),
win: parseInt(won, 10),
};
}
private parseBoxerAge(tableColumn: number): number | null {
const text: string = this.parseMiddleRowByText("age", tableColumn) as string;
if (text) {
return parseInt(text, 10);
}
return null;
}
private parseBoxerHeight(tableColumn: number): number[] | null {
let text: string = this.parseMiddleRowByText("height", tableColumn) as string;
text = trimRemoveLineBreaks(text); // found there was a line break at the end of this text and double spaces
return parseHeight(text);
}
private parseBoxerReach(tableColumn: number): number[] | null {
let text: string = this.parseMiddleRowByText("reach", tableColumn) as string;
text = trimRemoveLineBreaks(text); // found there was a line break at the end of this text and double spaces
let reach: number[] | null = null;
if (text) {
const regex: RegExp = /^(\d{2})(¼|½|¾)?(?:″|\&\#x2033\;)\s(?:\/|\&\#xA0\;\s)\s(?:\/|\&\#xA0\;)?(\d{3})cm$/;
const reachMatch: RegExpMatchArray | null = text.match(regex);
if (reachMatch) {
const [, inches, fraction, centimeters] = reachMatch;
let parsedInches: number = parseInt(inches, 10);
if (fraction) {
parsedInches += convertFractionsToNumber(fraction);
}
reach = [
parsedInches,
parseInt(centimeters, 10),
];
}
}
return reach;
}
/**
* Parses the boxer row
* @param {number} tableColumn needs to be the first or third column
* @returns {Stance | null}
*/
private parseBoxerStance(tableColumn: number): Stance | null {
const text: string = this.parseMiddleRowByText("stance", tableColumn) as string;
if (text) {
return trimRemoveLineBreaks(text) as Stance;
}
return null;
}
private parseBoxers(boxer: "first" | "second"): string {
const name: string[] = [];
const alreadyAdded: string[] = [];
this.$("table a").each((i: number, elem: CheerioElement) => {
const href: string = this.$(elem).attr("href");
if (name.length < 2 && href.includes("boxer") && !alreadyAdded.find(item => item === href)) {
alreadyAdded.push(href);
name.push(this.$.html(this.$(elem)));
}
});
if (boxer === "first" && name[0]) {
return name[0];
} else if (boxer === "second" && name[1]) {
return name[1];
}
return "";
}
private parseDivision(type: "division" | "numberOfRounds"): string {
const h2: CheerioElement = this.$("h2").get(1);
if (h2) {
const division: string | undefined = h2.children[0].data; // ex. Middleweight Contest, 12 Rounds
if (division) {
const divisionMatches: RegExpMatchArray | null = division.match(/^(\w+).*\,\s?(\d{1,2})?/);
if (!divisionMatches) {
return "";
}
if (type === "division" && divisionMatches[1]) {
return divisionMatches[1];
}
// I assume there's some matches where we know the division but not the number of rounds
if (type === "numberOfRounds" && divisionMatches[2]) {
return divisionMatches[2];
}
}
}
return "";
}
private parseJudges(): string[] {
const links: Cheerio = this.$(".responseLessDataTable a");
const judges: string[] = [];
links.each((i: number, elem: CheerioElement) => {
const href: string = this.$(elem).attr("href");
if (href.includes("judge")) {
const judgeString: string = this.$.html(this.$(elem).parent().parent());
judges.push(judgeString);
}
});
return judges;
}
private parseLast6(boxer: "first" | "second"): string[] {
let ranking: Cheerio = this.parseMiddleRowByText("last 6") as Cheerio;
const boxerArr: string[] = [];
for (let i: number = 0; i < 6; i++) {
ranking = ranking.next();
const tableFirst: Cheerio = ranking.find("td:nth-child(1) table");
const tableSecond: Cheerio = ranking.find("td:nth-child(3) table");
if (tableFirst && boxer === "first") {
const firstBoxerTable: string = this.$.html(tableFirst);
boxerArr.push(firstBoxerTable);
}
if (tableSecond && boxer === "second") {
const secondBoxerTable: string = this.$.html(tableSecond);
boxerArr.push(secondBoxerTable);
}
}
return boxerArr;
}
private parseLast6Object(isFirstBoxer: boolean): BoutPageLast6[] {
const parsedBoxerLast6: BoutPageLast6[] = [];
const last6: string[] = this.parseLast6(isFirstBoxer ? "first" : "second");
for (const last of last6) {
const obj: BoutPageLast6 = {
date: null,
id: null,
name: null,
outcome: null,
outcomeByWayOf: null,
};
const table: Cheerio = this.$(last);
let idName: BoxrecBasic = {
id: null,
name: null,
};
let outcomeStr: string | null = null;
if (isFirstBoxer) {
const idNameStr: string = this.$.html(table.find("td:nth-child(1) a"));
idName = BoxrecCommonTablesColumnsClass.parseNameAndId(idNameStr);
} else {
outcomeStr = table.find("td:nth-child(1) span").html();
}
const dateStr: string = this.$.html(table.find("td:nth-child(2) a"));
const date: string | null = BoxrecCommonTablesColumnsClass.parseNameAndId(dateStr).name;
if (isFirstBoxer) {
outcomeStr = table.find("td:nth-child(3) span").html();
} else {
const idNameStr: string = this.$.html(table.find("td:nth-child(3) a"));
idName = BoxrecCommonTablesColumnsClass.parseNameAndId(idNameStr);
}
if (outcomeStr) {
const {outcome, outcomeByWayOf} = BoxrecPageEventBout.parseOutcome(outcomeStr);
obj.outcome = outcome;
obj.outcomeByWayOf = outcomeByWayOf;
}
obj.id = idName.id;
obj.name = idName.name;
if (date) {
obj.date = date;
}
parsedBoxerLast6.push(obj);
}
return parsedBoxerLast6;
}
/**
* Used to get the string of the table row where the stats are to the left/right of it (ex. age, height)
* @param {string} textToFind
* @param {number} tableColumn
* @returns {Cheerio | string}
*/
private parseMiddleRowByText(textToFind: string = "", tableColumn: number = -1): Cheerio | string {
// the returned elem is `td b` so we go up 2 and then find the column we want
const filteredRow: Cheerio = this.findColumnByText(textToFind).parent().parent();
if (tableColumn >= 0) {
return filteredRow.find(`td:nth-child(${tableColumn})`).text();
}
// if no table column is specified we return the entire row
return filteredRow;
}
private parseOutcomeOfBout(outcomeText: string): BoutPageOutcome {
const splitDrawText: string[] = outcomeText.split(" ");
const outcomeKeys: string[] = Object.keys(BoxingBoutOutcome);
const foundKey: string | undefined = outcomeKeys.find(item => item === splitDrawText[1]);
// if it finds the key in the enum, we can return it as that type
if (foundKey) {
const outcomeByWayOf: BoxingBoutOutcome = BoxingBoutOutcome[foundKey as BoxingBoutOutcomeKeys];
return {
outcome: WinLossDraw.win,
outcomeByWayOf,
};
}
return {
outcome: null,
outcomeByWayOf: null,
};
}
private parsePoints(beforePoints: boolean = true, tableColumn: number): number | null {
const strToSearch: string = beforePoints ? "before fight" : "after fight";
const points: string = this.parseMiddleRowByText(strToSearch, tableColumn) as string;
const pointsParsed: RegExpMatchArray | null = points.match(/[\d\,]+/);
if (pointsParsed) {
pointsParsed[0] = pointsParsed[0].replace(",", "");
return parseInt(pointsParsed[0], 10);
}
return null;
}
private parseRanking(): string {
const ranking: Cheerio = this.parseMiddleRowByText("ranking") as Cheerio;
return this.$.html(ranking.next());
}
private parseRankingData(columnNumber: number = 1): number | null {
const ranking: Cheerio = this.$(this.parseRanking());
const td: Cheerio = ranking.find(`td:nth-child(${columnNumber})`);
if (td.text()) {
return parseInt(td.text(), 10);
}
return null;
}
private parseTitles(): string | null {
return this.$(".titleColor").html();
}
} | the_stack |
import { pxToNumber } from "../../../common/css";
import { createStylesheetText } from "../../../common/stylesheets";
import { fontSizeThemeVariable } from "../../../common/theme";
import { cleanTitle } from "../../../overlay/outline/parse";
import { PageModifier, trackModifierExecution } from "../_interface";
export const lindyContainerClass = "lindy-text-container";
export const lindyHeadingContainerClass = "lindy-heading-container";
export const lindyImageContainerClass = "lindy-image-container";
export const lindyMainContentContainerClass = "lindy-main-text-container";
export const lindyMainHeaderContainerClass = "lindy-main-header-container";
export const lindyFirstMainContainerClass = "lindy-first-main-container";
const globalTextElementSelector = "p, font";
const globalHeadingSelector =
"h1, h2, h3, h4, header, [class*='head' i], [class*='title' i]";
const headingClassWordlist = ["header", "heading", "title", "article-details"]; // be careful here
const globalImageSelector = "img, picture, figure, video";
const headingTags = globalHeadingSelector.split(", ");
// DOM elements that contain more than this fraction of the entire page text will never be removed
// by the ContentBlockModifier, and their style will be cleaned up more strictly.
const mainContentFractionThreshold = 0.4; // 0.47 on https://www.whichev.net/2022/03/29/theion-sulphur-crystal-batteries-promise-breakthrough-in-energy-density/
// Skip the main text detection if the page contains less than these number of chars
const mainContentMinLength = 500; // 205 on https://huggingface.co/spaces/loubnabnl/code-generation-models
/*
Find and iterate upon text elements and their parent containers in the article DOM.
This is done so that we can:
- Remove x margin from elements that contain the article text. We then apply a standardized margin on the <body> tag itself.
- Remove horizontal layouts in elements that contain the article text, and side margin left over from horizontal partitioning.
- Remove borders, shadows, and background colors from elements that contain article text.
- Get the current font size of the main text elements.
*/
@trackModifierExecution
export default class TextContainerModifier implements PageModifier {
private cleanPageTitle = cleanTitle(document.title)
.slice(0, 15) // match only beginning
.toLowerCase();
private usedTextElementSelector: string = globalTextElementSelector; // may get updated if page uses different html elements
// text containers to put on a seperate CSS GPU layer to animate their position
private animationLayerElements: [
HTMLElement,
{
nodeBox: DOMRect;
afterNodeBox: DOMRect;
stackType: string;
parentLayer: HTMLElement;
parentLayerStyle: CSSStyleDeclaration;
}
][] = [];
private inlineStyleTweaks: [HTMLElement, Partial<CSSStyleDeclaration>][] =
[];
// Remember background colors on text containers
private backgroundColors = [];
// Text paragraph samples
private mainFontSize: number;
public mainTextColor: string;
private exampleMainFontSizeElement: HTMLElement;
// Iterate DOM to apply text container classes and populate the state above
public foundMainContentElement = false;
public foundMainHeadingElement = false;
private bodyContentLength: number;
async iterateDom() {
this.bodyContentLength = document.body.innerText.length;
if (this.bodyContentLength < mainContentMinLength) {
// set large number so all fractions are small -> foundMainContentElement stays false
this.bodyContentLength = 1000000;
}
// Apply to text nodes
let validTextNodeCount = 0;
document.body
.querySelectorAll(globalTextElementSelector)
.forEach((elem: HTMLElement) => {
if (this.processElement(elem, "text")) {
validTextNodeCount += 1;
}
});
// try with div fallback selector (more performance intensive)
if (validTextNodeCount < 5) {
// e.g. using div as text containers on https://www.apple.com/newsroom/2022/06/apple-unveils-all-new-macbook-air-supercharged-by-the-new-m2-chip/
console.log("Using div as text elem selector");
document.body
.querySelectorAll("div")
.forEach((elem: HTMLElement) => {
this.processElement(elem, "text");
});
this.usedTextElementSelector = `${globalTextElementSelector}, div`;
}
// Apply to heading nodes
this.validatedNodes = new Set(); // reset phase-internal state
document.body
.querySelectorAll(globalHeadingSelector)
.forEach((elem: HTMLElement) => {
this.processElement(elem, "header");
});
this.headingParagraphNodes.forEach((elem: HTMLElement) => {
this.processElement(elem, "header");
});
// search images
this.validatedNodes = new Set();
document.body
.querySelectorAll(globalImageSelector)
.forEach((elem: HTMLElement) => {
this.processElement(elem, "image");
});
// Just use the most common font size for now
// Note that the actual font size might be changed by responsive styles
// @ts-ignore
this.mainFontSize = Object.keys(this.paragraphFontSizes).reduce(
(a, b) =>
this.paragraphFontSizes[a] > this.paragraphFontSizes[b] ? a : b,
0
);
this.exampleMainFontSizeElement =
this.exampleNodePerFontSize[this.mainFontSize];
if (this.exampleMainFontSizeElement) {
this.mainTextColor = window.getComputedStyle(
this.exampleMainFontSizeElement
).color;
}
this.animationLayerCandidates.push([
document.body,
{
nodeBox: document.body.getBoundingClientRect(),
stackType: "text",
},
]);
}
assignClassnames() {
// batch className changes to only do one reflow
this.nodeClasses.forEach((classes, node) => {
node.classList.add(...classes);
});
// apply first-main class to all candidates, as often detects multiple
this.firstMainTextContainerCandidates.map((elem) => {
elem.classList.add(lindyFirstMainContainerClass);
});
this.firstMainHeaderCandidates.map((elem) => {
elem.classList.add(lindyFirstMainContainerClass);
// use parent elem as first header element to not block siblings
elem.parentElement.classList.add(lindyFirstMainContainerClass);
});
this.watchElementClassnames();
}
// Process text or heading elements and iterate upwards
private paragraphFontSizes: { [size: number]: number } = {};
private exampleNodePerFontSize: { [size: number]: HTMLElement } = {};
private processElement(
elem: HTMLElement,
elementType: "text" | "header" | "image"
): boolean {
// Ignore invisible nodes
// Note: iterateDOM is called before content block, so may not catch all hidden nodes (e.g. in footer)
if (elem.offsetHeight === 0) {
return false;
}
const activeStyle = window.getComputedStyle(elem);
if (elementType === "text") {
let textContentLength: number;
if (elem.tagName === "DIV") {
// use only direct node text to start iteration at leaf nodes
textContentLength = [...elem.childNodes]
.filter((node) => node.nodeType === Node.TEXT_NODE)
.map((node) => node.nodeValue)
.join("").length;
} else {
textContentLength = elem.innerText.length;
}
// exclude small text nodes
if (textContentLength < 50) {
return false;
}
// parse text element font size
const fontSize = parseFloat(activeStyle.fontSize);
if (this.paragraphFontSizes[fontSize]) {
this.paragraphFontSizes[fontSize] += 1;
// Save largest element as example (small paragraphs might have header-specific line height)
if (
elem.innerText.length >
this.exampleNodePerFontSize[fontSize].innerText.length
) {
this.exampleNodePerFontSize[fontSize] = elem;
}
} else {
this.paragraphFontSizes[fontSize] = 1;
this.exampleNodePerFontSize[fontSize] = elem;
}
}
// iterate parent containers (don't start with elem for text containers)
const iterationStart =
elementType === "header" || elementType === "image"
? elem
: elem.parentElement;
const hasValidTextChain = this.prepareIterateParents(
iterationStart,
elementType
);
// check all leaf nodes if should create layer
const nodeBox = elem.getBoundingClientRect();
this.checkShouldCreateAnimationLayer(elem, elementType, nodeBox, true);
return hasValidTextChain;
}
// iteration state
private validatedNodes: Set<HTMLElement> = new Set(); // nodes processed in the current phase of prepareIterateParents()
private mainStackElements: Set<HTMLElement> = new Set(); // nodes that have the main text or header container class applied
private headingParagraphNodes: HTMLElement[] = [];
// DOM changes to perform (batched to avoid multiple reflows)
private nodeClasses: Map<HTMLElement, string[]> = new Map();
private firstMainTextContainerCandidates: HTMLElement[] = [];
private firstMainHeaderCandidates: HTMLElement[] = [];
// map paragraphs nodes and iterate their parent nodes
private prepareIterateParents(
startElem: HTMLElement,
stackType: "text" | "header" | "image"
): boolean {
// calls for headings happen after text elements -> mark entire stack as heading later
// Iterate upwards in DOM tree from paragraph node
let currentElem = startElem;
let currentStack: HTMLElement[] = [];
while (currentElem !== document.body) {
if (
this.mainStackElements.has(currentElem) ||
// don't go into parents if already validated them (only for text containers since their mainStack state doesn't change for parents)
(stackType === "text" && this.validatedNodes.has(currentElem))
) {
// process stack until now
break;
}
if (
stackType === "text" &&
this.shouldExcludeAsTextContainer(currentElem)
) {
// remove entire current stack
return false;
}
// exclude image captions
if (
stackType !== "image" &&
["FIGURE", "PICTURE"].includes(currentElem.tagName)
) {
return false;
}
// handle text elements that are part of headings
if (stackType === "text") {
if (
headingTags.includes(currentElem.tagName.toLowerCase()) ||
headingClassWordlist.some((word) =>
currentElem.className.toLowerCase().includes(word)
)
) {
// double check to exclude matches on main text containers
// e.g. on https://pharmaphorum.com/views-and-analysis/how-celebrity-investor-mark-cuban-is-tackling-out-of-control-drug-prices/
const pageContentFraction =
currentElem.innerText.length / this.bodyContentLength;
if (!(pageContentFraction > mainContentFractionThreshold)) {
// handle heading nodes later, after all text containers are assigned
this.headingParagraphNodes.push(startElem);
return false;
}
}
}
// iterate upwards
currentStack.push(currentElem);
currentElem = currentElem.parentElement;
}
let isMainStack = false; // main stack determined based on leaf elements for headings, based on intermediate parent size for text elements
// check element position
if (
(stackType === "header" || stackType === "image") &&
currentStack.length > 0
) {
// for headings check tagName, content & if on first page
// this should exclude heading elements that are part of "related articles" sections
const pos = startElem.getBoundingClientRect(); // TODO measure performance
const top = pos.top + window.scrollY;
const isOnFirstPage = top < window.innerHeight * 2 && top >= 0;
// hidden above page e.g. for https://www.city-journal.org/san-francisco-recalls-da-chesa-boudin
// e.g. just below fold on https://spectrum.ieee.org/commodore-64
if (stackType === "header") {
const linkElem =
startElem.parentElement.tagName === "A"
? startElem.parentElement
: startElem.firstElementChild;
// main stack state determined by leaf element
isMainStack =
isOnFirstPage &&
(linkElem?.tagName !== "A" ||
linkElem.href === window.location.href) &&
((startElem.tagName === "H1" &&
startElem.innerText?.length >= 15) ||
startElem.innerText
?.slice(0, 30)
.toLowerCase()
.includes(this.cleanPageTitle));
if (isMainStack) {
this.foundMainHeadingElement = true;
this.firstMainHeaderCandidates.push(startElem);
}
} else if (stackType === "image") {
if (!isOnFirstPage || pos.height < 250) {
return false;
}
}
}
// perform modifications on valid text element stack
for (const currentElem of currentStack) {
const activeStyle = window.getComputedStyle(currentElem);
// abort based on activeStyle (leaves children behind, but better than nothing)
if (
activeStyle.visibility === "hidden" ||
activeStyle.opacity === "0"
) {
return false;
}
// check if element is main text or header
if (
stackType === "text" &&
!isMainStack &&
currentElem !== document.body
) {
// for text containers, consider the fraction of the page text
const pageContentFraction =
currentElem.innerText.length / this.bodyContentLength;
isMainStack =
pageContentFraction > mainContentFractionThreshold;
if (isMainStack) {
this.foundMainContentElement = true;
this.firstMainTextContainerCandidates.push(currentElem);
}
}
// parse background color from main text element stacks
if (isMainStack && stackType === "text") {
if (
// don't take default background color
!activeStyle.backgroundColor.includes("rgba(0, 0, 0, 0)") &&
// don't consider transparent colors
!activeStyle.backgroundColor.includes("0.") &&
!activeStyle.backgroundColor.includes("%") &&
activeStyle.position !== "fixed"
) {
// Remember background colors on text containers
// console.log(activeStyle.backgroundColor, elem);
this.backgroundColors.push(activeStyle.backgroundColor);
}
}
// save classes to add
const currentNodeClasses: string[] = [];
if (stackType === "header") {
currentNodeClasses.push(lindyHeadingContainerClass);
if (isMainStack && currentElem !== document.body) {
currentNodeClasses.push(lindyMainHeaderContainerClass);
}
} else if (stackType === "text") {
currentNodeClasses.push(lindyContainerClass);
if (isMainStack) {
currentNodeClasses.push(lindyMainContentContainerClass);
}
} else if (stackType === "image") {
currentNodeClasses.push(lindyImageContainerClass);
}
// apply override classes (but not text container) e.g. for text elements on theatlantic.com
const overrideClasses = this._getNodeOverrideClasses(
currentElem,
activeStyle,
stackType,
isMainStack
);
currentNodeClasses.push(...overrideClasses);
this.nodeClasses.set(currentElem, [
...(this.nodeClasses.get(currentElem) || []),
...currentNodeClasses,
]);
const nodeBox = currentElem.getBoundingClientRect();
this.prepareInlineStyleTweaks(currentElem, stackType, nodeBox);
// creating layers for some container elements creates better results in case we don't detect all content elements
this.checkShouldCreateAnimationLayer(
currentElem,
stackType,
nodeBox,
false
);
this.validatedNodes.add(currentElem); // add during second iteration to ignore aborted stacks
if (isMainStack) {
// skip processing in next iteration phase (respect main text elems when checking headers)
this.mainStackElements.add(currentElem);
}
}
return true;
}
applyContainerStyles() {
// Removing margin and cleaning up background, shadows etc
createStylesheetText(
this.getTextElementChainOverrideStyle(),
"lindy-text-chain-override"
);
this.inlineStyleTweaks.forEach(([elem, style]) => {
for (const [key, value] of Object.entries(style)) {
elem.style[key] = value;
}
});
}
prepareTransitionOut() {
this.animationLayerElements.map(([node, {}]) => {
node.style.setProperty(
"transition",
"margin-left 0.4s cubic-bezier(0.33, 1, 0.68, 1)"
);
});
}
transitionOut() {
this.classNamesObserver.disconnect();
document
.querySelectorAll(".lindy-text-chain-override")
.forEach((e) => e.remove());
}
afterTransitionOut() {
document
.querySelectorAll(".lindy-font-size, .lindy-node-overrides")
.forEach((e) => e.remove());
}
private getTextElementChainOverrideStyle() {
// :not(#fakeID#fakeID) used to override stubborn site styles
return `
/* clean up all text containers */
.${lindyContainerClass}:not(#fakeID#fakeID),
.${lindyHeadingContainerClass}:not(#fakeID#fakeID),
.${lindyContainerClass}:not(#fakeID#fakeID) > :is(
${this.usedTextElementSelector},
${globalHeadingSelector}
) {
width: 100% !important;
min-width: 0 !important;
min-height: 0 !important;
max-width: calc(var(--lindy-pagewidth) - 2 * 50px) !important;
max-height: none !important;
margin-left: 0 !important;
margin-right: 0 !important;
padding-left: 0 !important;
padding-right: 0 !important;
border: none !important;
background: none !important;
box-shadow: none !important;
z-index: 1 !important;
overflow: visible !important;
}
/* more strict cleanup for main text containers */
.${lindyMainContentContainerClass}:not(#fakeID#fakeID):not(body) {
position: relative !important;
margin-top: 0 !important;
margin-bottom: 0 !important;
padding-top: 0 !important;
padding-bottom: 0 !important;
top: 0 !important;
}
/* clean up headings */
.${lindyHeadingContainerClass}:not(#fakeID#fakeID):not(body),
.${lindyHeadingContainerClass}:not(#fakeID#fakeID) > * {
color: black !important;
background: none !important;
-webkit-text-fill-color: unset !important;
text-shadow: none !important;
box-shadow: none !important;
position: relative !important;
top: 0 !important;
margin-left: 0 !important;
margin-right: 0 !important;
padding-left: 0 !important;
padding-right: 0 !important;
height: auto;
float: none !important;
}
/* heading style tweaks */
.${lindyHeadingContainerClass}:before,
.${lindyHeadingContainerClass}:after {
display: none !important;
}
.${lindyHeadingContainerClass}:first-child, .${lindyMainHeaderContainerClass} {
margin-top: 0 !important;
padding-top: 0 !important;
margin-bottom: 0 !important;
}
.${lindyHeadingContainerClass}:not(#fakeID#fakeID) a {
color: black !important;
background: none !important;
}
/* image container cleanup */
.${lindyImageContainerClass}:not(#fakeID#fakeID) {
width: 100% !important;
margin-left: 0 !important;
margin-right: 0 !important;
padding-left: 0 !important;
padding-right: 0 !important;
border: none !important;
/* y padding often used to make space for images, e.g. on theintercept or variety.com */
height: auto !important;
backdrop-filter: none !important; /* prevent implicit GPU layer */
top: 0 !important;
left: 0 !important;
}
/* block siblings of main text containers */
.${lindyMainContentContainerClass}:not(.${lindyFirstMainContainerClass}) > :not(
.${lindyMainContentContainerClass},
.${lindyImageContainerClass},
.${
this.foundMainHeadingElement
? lindyMainHeaderContainerClass
: lindyHeadingContainerClass
}
) {
display: none !important;
}
`;
// /* block siblings of main header containers */
// .${lindyMainHeaderContainerClass}:not(.${lindyFirstMainContainerClass}) > :not(
// .${lindyHeadingContainerClass},
// .${lindyImageContainerClass},
// .${lindyContainerClass}
// ) {
// display: none !important;
// }
}
// set text color variable only when dark mode enabled, otherwise overwrites color (even if css var not set)
public setTextDarkModeVariable(darkModeEnabled: boolean) {
if (!darkModeEnabled) {
document
.querySelectorAll(".lindy-dark-mode-text")
.forEach((e) => e.remove());
return;
}
const css = `
.${lindyContainerClass}:not(#fakeID#fakeID#fakeID),
.${lindyContainerClass}:not(#fakeID#fakeID#fakeID) > :is(${this.usedTextElementSelector}, .${globalHeadingSelector}),
.${lindyHeadingContainerClass}:not(#fakeID#fakeID#fakeID),
.${lindyHeadingContainerClass}:not(#fakeID#fakeID#fakeID) > * {
color: var(--lindy-dark-theme-text-color) !important;
}
.${lindyHeadingContainerClass}:not(#fakeID#fakeID#fakeID) a {
color: var(--lindy-dark-theme-text-color) !important;
}
`;
createStylesheetText(css, "lindy-dark-mode-text");
}
private relativeLineHeight: string;
private fontSizeNormalizationScale: number = 1;
measureFontProperties() {
if (!this.exampleMainFontSizeElement) {
return;
}
const activeStyle = window.getComputedStyle(
this.exampleMainFontSizeElement
);
// Convert line-height to relative and specify override in case it was set as px
if (activeStyle.lineHeight.includes("px")) {
this.relativeLineHeight = (
pxToNumber(activeStyle.lineHeight) /
pxToNumber(activeStyle.fontSize)
).toFixed(2);
} else {
this.relativeLineHeight = activeStyle.lineHeight;
}
// Measure size of font x-height (height of lowercase chars)
const measureDiv = document.createElement("div");
measureDiv.innerText = "x";
measureDiv.style.margin = "0";
measureDiv.style.padding = "0";
measureDiv.style.fontSize = "20px";
measureDiv.style.height = "1ex";
measureDiv.style.lineHeight = "0";
measureDiv.style.visibility = "hidden";
measureDiv.style.contain = "strict";
this.exampleMainFontSizeElement.style.contain = "layout style paint";
this.exampleMainFontSizeElement.appendChild(measureDiv);
const xHeight = measureDiv.getBoundingClientRect().height;
measureDiv.remove();
this.exampleMainFontSizeElement.style.removeProperty("contain");
this.fontSizeNormalizationScale = 1;
if (xHeight && xHeight !== 0) {
this.fontSizeNormalizationScale = 10 / xHeight;
}
}
// Adjust main font according to theme
setTextFontOverride() {
const fontSize = `calc(var(${fontSizeThemeVariable}) * ${this.fontSizeNormalizationScale.toFixed(
2
)})`;
const fontSizeStyle = `.${lindyContainerClass}, .${lindyContainerClass} > :is(${this.usedTextElementSelector}, a, ol, ul) {
position: relative !important;
font-size: ${fontSize} !important;
line-height: ${this.relativeLineHeight} !important;
}`;
// setCssThemeVariable("--lindy-original-font-size", activeStyle.fontSize);
createStylesheetText(fontSizeStyle, "lindy-font-size");
}
public originalBackgroundColor: string;
processBackgroundColors() {
if (
this.backgroundColors.length > 0 &&
this.backgroundColors[0] !== "rgba(0, 0, 0, 0)"
) {
this.originalBackgroundColor = this.backgroundColors[0];
}
}
// Collect overrides for specific container elements (insert as stylesheet for easy unpatching)
private overrideCssDeclarations = [
// hide sidebar siblings, e.g. on https://www.thespacereview.com/article/4384/1
`.${lindyContainerClass} > td:not(.${lindyContainerClass}) {
display: none !important;
}`,
// Remove horizontal flex partitioning, e.g. https://www.nationalgeographic.com/science/article/the-controversial-quest-to-make-a-contagious-vaccine
`.lindy-text-remove-horizontal-flex { display: block !important; }`,
// Remove grids, e.g. https://www.washingtonpost.com/business/2022/02/27/bp-russia-rosneft-ukraine or https://www.trickster.dev/post/decrypting-your-own-https-traffic-with-wireshark/
`.lindy-text-remove-grid {
display: block !important;
grid-template-columns: 1fr !important;
grid-template-areas: none !important;
column-gap: 0 !important;
}`,
`.lindy-header-font-size-max {
font-size: 50px !important;
line-height: 1em !important;
}`,
...["margin-top", "margin-bottom", "padding-top", "padding-bottom"].map(
(property) => `.lindy-clean-${property}:not(#fakeID#fakeID#fakeID) {
${property}: 10px !important;
}`
),
];
// Get classes from overrideCssDeclarations to apply to a certain node
private _getNodeOverrideClasses(
node: HTMLElement,
activeStyle: CSSStyleDeclaration,
stackType: "text" | "header" | "image",
isMainStack: boolean
): string[] {
// batch creation of unique node selectors if required
const classes = [];
if (
(stackType === "text" || (stackType === "header" && isMainStack)) &&
activeStyle.display === "flex" &&
activeStyle.flexDirection === "row"
) {
classes.push("lindy-text-remove-horizontal-flex");
}
if (stackType === "header" && activeStyle.fontSize > "50px") {
// put maximum on header font size
// e.g. WP template uses 6em on https://blog.relyabilit.ie/the-curse-of-systems-thinkers/
classes.push("lindy-header-font-size-max");
}
if (stackType === "header" || stackType === "image") {
[
"margin-top",
"margin-bottom",
"padding-top",
"padding-bottom",
].map((property) => {
const value = activeStyle.getPropertyValue(property);
const valueFloat = parseFloat(value.replace("px", ""));
if (value.startsWith("-")) {
classes.push(`lindy-clean-${property}`);
return;
}
if (
valueFloat >= 60 &&
(stackType !== "image" ||
valueFloat < node.scrollHeight * 0.9)
) {
// remove large margins (e.g. on https://progressive.org/magazine/bipartisan-rejection-school-choice-bryant/)
// skip this if margin contributes >= 90% of an image's height (e.g. on https://www.cnbc.com/2022/06/20/what-is-staked-ether-steth-and-why-is-it-causing-havoc-in-crypto.html)
classes.push(`lindy-clean-${property}`);
return;
}
});
}
if (activeStyle.display === "grid") {
classes.push("lindy-text-remove-grid");
}
return classes;
}
private prepareInlineStyleTweaks(
node: HTMLElement,
stackType: string,
nodeBox: DOMRect
) {
const styleTweaks: Partial<CSSStyleDeclaration> = {};
const parentStyle = window.getComputedStyle(node.parentElement);
// flex and grid layouts are removed via _getNodeOverrideClasses() above, so save max-width on children to retain width without siblings
if (
(parentStyle.display === "flex" &&
parentStyle.flexDirection === "row") ||
parentStyle.display === "grid"
) {
styleTweaks.maxWidth = `${nodeBox.width}px`;
}
if (Object.keys(styleTweaks).length > 0) {
this.inlineStyleTweaks.push([node, styleTweaks]);
}
}
// stage elements to put on animation layers, with their original page position
// know actual parent layers for each layer only once content block done
private animationLayerCandidates: [
HTMLElement,
{ nodeBox: DOMRect; stackType: string }
][] = [];
private checkShouldCreateAnimationLayer(
node: HTMLElement,
stackType: string,
nodeBox: DOMRect,
isLeafElement: boolean
) {
// only animate elements in (or above) viewport for performance
if (nodeBox.top > window.scrollY + window.innerHeight * 1.5) {
return;
}
if (stackType === "image" && !isLeafElement) {
// further filtered down in prepareAnimation()
return;
}
// tentative x and y offsets
const parentBox = node.parentElement.getBoundingClientRect();
const leftOffset = nodeBox.left - parentBox.left;
const topOffset = 0; // nodeBox.top - parentBox.top;
// layer candidates are further pruned in prepareAnimation() based on blocked elems & parent offsets
if (stackType === "image" || leftOffset !== 0 || topOffset !== 0) {
// console.log(leftOffset, node);
this.animationLayerCandidates.push([node, { nodeBox, stackType }]);
}
}
prepareAnimation() {
// filter to visible elements, and read after-content-block DOM position
const layerElements: Map<
HTMLElement,
{
nodeBox: DOMRect;
afterNodeBox: DOMRect;
stackType: string;
parentLayer: HTMLElement;
parentLayerStyle: CSSStyleDeclaration;
}
> = new Map();
this.animationLayerCandidates.forEach(
([node, { nodeBox, stackType }]) => {
const afterNodeBox = node.getBoundingClientRect();
if (afterNodeBox.height === 0) {
// ignore blocked elements
return;
}
if (node === document.body) {
// body is not animated, so need to include its movement into child layers
nodeBox = afterNodeBox; // pretend body stayed in place
}
layerElements.set(node, {
nodeBox,
afterNodeBox,
stackType,
parentLayer: null, // set below
parentLayerStyle: null,
});
}
);
// populate parent layer for each layer
layerElements.forEach((properties, node) => {
let parentLayer = node.parentElement;
while (parentLayer && !layerElements.has(parentLayer)) {
parentLayer = parentLayer.parentElement;
}
const parentLayerStyle =
parentLayer && window.getComputedStyle(parentLayer);
layerElements.set(node, {
...properties,
parentLayer,
parentLayerStyle,
});
});
// filter out unnecessary layers
layerElements.forEach((properties, node) => {
if (
node === document.body ||
properties.parentLayer === document.body
) {
// allow all top-level layers
return;
}
const parentLayerProps = layerElements.get(properties.parentLayer);
if (!parentLayerProps) {
// console.log("no valid parent", node, properties.parentLayer);
return;
}
// only keep one layer per image chain (often matches containers by classname)
if (
properties.stackType === "image" &&
parentLayerProps.stackType === "image"
) {
layerElements.delete(node);
return;
}
// container styles collapsed layers (parent has no other content)
// e.g. on https://www.nbcnews.com/business/business-news/tesla-racism-lawsuit-worker-rejects-15-million-payout-rcna34655
if (
properties.afterNodeBox.top ===
parentLayerProps?.afterNodeBox.top &&
properties.afterNodeBox.height ===
parentLayerProps?.afterNodeBox.height
) {
// console.log("delete", properties.parentLayer);
layerElements.set(node, {
...properties,
parentLayer: parentLayerProps.parentLayer,
parentLayerStyle: parentLayerProps.parentLayerStyle,
});
layerElements.delete(properties.parentLayer);
return;
}
});
this.animationLayerElements = [...layerElements.entries()].filter(
([node]) => node !== document.body
);
// put text containers in same place as before content block, but positioned using CSS transforms
this.animationLayerElements.forEach(([node, layerProps]) => {
const parentLayerProps = layerElements.get(layerProps.parentLayer);
if (!parentLayerProps) {
// console.log("no valid parent", node);
return;
}
// console.log(
// "layer",
// layerProps.stackType,
// node,
// layerProps.parentLayer
// );
// get x and y offsets
// allow negative e.g. on https://www.statnews.com/2019/06/25/alzheimers-cabal-thwarted-progress-toward-cure/
const beforeLeftOffset =
layerProps.nodeBox.left - parentLayerProps.nodeBox.left;
const afterLeftOffset =
layerProps.afterNodeBox.left -
parentLayerProps.afterNodeBox.left;
const leftOffset = beforeLeftOffset - afterLeftOffset;
const beforeTopOffset =
layerProps.nodeBox.top - parentLayerProps.nodeBox.top;
const afterTopOffset =
layerProps.afterNodeBox.top - parentLayerProps.afterNodeBox.top;
const topOffset = beforeTopOffset - afterTopOffset;
let transform = `translate(${leftOffset}px, ${topOffset}px)`;
// animate header image width (not for text elements for performance)
if (layerProps.stackType === "image") {
const scaleX =
layerProps.nodeBox.width / layerProps.afterNodeBox.width;
transform += ` scale(${scaleX})`;
node.style.setProperty("transform-origin", "top left");
}
node.style.setProperty("transform", transform);
node.style.setProperty("left", "0"); // e.g. xkcd.com
node.style.setProperty("display", "block"); // can only animate blocks?
// put on new layer
node.style.setProperty("will-change", "transform");
});
// Display fixes with visible layout shift (e.g. removing horizontal partitioning)
createStylesheetText(
this.overrideCssDeclarations.join("\n"),
"lindy-text-node-overrides"
);
}
executeAnimation() {
this.animationLayerElements.map(([node, { stackType }]) => {
node.style.setProperty(
"transition",
"transform 0.4s cubic-bezier(0.33, 1, 0.68, 1)"
);
let transform = `translate(0, 0)`;
if (stackType === "image") {
transform += ` scale(1)`;
}
node.style.setProperty("transform", transform);
});
}
// very carefully exclude elements as text containers to avoid incorrect main container selection for small articles
// this doesn't mean these elements will be removed, but they might
private shouldExcludeAsTextContainer(node: HTMLElement) {
if (["BLOCKQUOTE", "CODE", "PRE"].includes(node.tagName)) {
// leave style of quotes intact
// e.g. https://knowledge.wharton.upenn.edu/article/how-price-shocks-in-formative-years-scar-consumption-for-life/
return true;
}
if (
[
"module-moreStories", // https://news.yahoo.com/thailand-legalizes-growing-consumption-marijuana-135808124.html
"comments", // https://leslefts.blogspot.com/2013/11/the-great-medieval-water-myth.html
].includes(node.id) ||
node.getAttribute("aria-hidden") === "true"
) {
return true;
}
return false;
}
// Make sure the classes we added do not get removed by the site JS (e.g. on techcrunch.com)
private classNamesObserver: MutationObserver;
private watchElementClassnames() {
if (document.body.classList.contains("notion-body")) {
// notion undos all className changes, see e.g. https://abhinavsharma.com/blog/google-alternatives
this.foundMainContentElement = false;
this.foundMainHeadingElement = false;
return;
}
this.classNamesObserver = new MutationObserver((mutations) =>
mutations.forEach((mutation) => {
const target = mutation.target as HTMLElement;
if (this.nodeClasses.has(target)) {
const removedClasses = this.nodeClasses
.get(target)
.filter(
(className) => !target.classList.contains(className)
);
if (removedClasses.length > 0) {
target.classList.add(...removedClasses);
}
}
})
);
this.classNamesObserver.observe(document.body, {
subtree: true,
attributeFilter: ["class"],
});
}
} | the_stack |
'use strict';
import * as vscode from 'vscode';
import * as path from 'path';
import { JsonOutlineProvider } from './jsonOutline';
import {SelCommand} from './SelCommand'
import { Builder, By, Browser} from 'selenium-webdriver';
import { PageViewProvider } from './PageView';
import { DebuggerViewProvider } from './DebuggerViewProvider';
const engine = require('engine.io');
let driver = null, selCommand:SelCommand = null, server, extSocket
let browser = vscode.workspace.getConfiguration('browsers').get('browser')
vscode.commands.executeCommand('setContext', 'BrowserName', browser);
vscode.workspace.onDidChangeConfiguration(() => {
browser = vscode.workspace.getConfiguration('browsers').get('browser');
vscode.commands.executeCommand('setContext', 'BrowserName', browser);
});
export function activate(context: vscode.ExtensionContext) {
const jsonOutlineProvider = new JsonOutlineProvider(context);
vscode.window.registerTreeDataProvider('locators', jsonOutlineProvider);
vscode.commands.registerCommand('locators.refresh', () => jsonOutlineProvider.refresh());
vscode.commands.registerCommand('extension.openJsonSelection', range => jsonOutlineProvider.select(range));
vscode.commands.registerCommand('pageView.startChrome', startDriver);
vscode.commands.registerCommand('pageView.startFirefox', startDriver);
vscode.commands.registerCommand('pageView.startEdge', startDriver);
async function startDriver(){
let started = false
if(!driver){
if(browser == "Chrome"){
try {
//driver = new Builder().forBrowser('chrome').build();
const builder = new Builder().withCapabilities({
browserName: 'chrome',
'goog:chromeOptions': {
// Don't set it to headless as extensions dont work in general
// when used in headless mode
args: [`load-extension=${path.join(__dirname + '../../build')}`],
},
})
driver = await builder.build()
started = true
vscode.commands.executeCommand('setContext', 'ChromeEnabled', true);
} catch (error) {
vscode.window.showErrorMessage(error.message);
}
}
else if(browser == "Firefox"){
try {
driver = await new Builder().forBrowser(Browser.FIREFOX).build();
started = true
} catch (error) {
vscode.window.showErrorMessage(error.message);
}
}
else if(browser == "Edge"){
try {
driver = await new Builder().forBrowser(Browser.EDGE).build();
started = true
} catch (error) {
vscode.window.showErrorMessage(error.message);
}
}
else if(browser == "IE"){
try {
driver = await new Builder().forBrowser(Browser.INTERNET_EXPLORER).build();
await driver.manage().setTimeouts({implicit: 3})
started = true
} catch (error) {
vscode.window.showErrorMessage(error.message);
}
}
else if(browser == "Safari"){
try {
driver = await new Builder().forBrowser(Browser.SAFARI).build();
started = true
} catch (error) {
vscode.window.showErrorMessage(error.message);
}
}
if(started){
selCommand = new SelCommand(driver);
DebuggerViewProvider.selCommand = selCommand
vscode.commands.executeCommand('setContext', 'WebdriverEnabled', true);
jsonOutlineProvider.refresh()
}
}
else{
await selCommand.showBrowser()
}
}
vscode.commands.registerCommand('pageView.stopDriver', async () => {
try {
await driver.quit()
} catch (error) {
vscode.window.showErrorMessage(error.message);
}
driver = null
vscode.commands.executeCommand('setContext', 'WebdriverEnabled', false);
vscode.commands.executeCommand('setContext', 'ChromeEnabled', false);
jsonOutlineProvider.refresh()
});
vscode.commands.registerCommand('extension.highlight', async offset => {
let locator = jsonOutlineProvider.getLocator(offset)
let text = await selCommand.highlight(locator)
if(text) {
vscode.window.showInformationMessage(text);
}
});
vscode.commands.registerCommand('extension.isDisplayed', async offset => {
let locator = jsonOutlineProvider.getLocator(offset)
let text = await selCommand.isDisplayed(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('extension.isEnabled', async offset => {
let locator = jsonOutlineProvider.getLocator(offset)
let text = await selCommand.isEnabled(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('extension.isSelected', async offset => {
let locator = jsonOutlineProvider.getLocator(offset)
let text = await selCommand.isSelected(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('extension.getText', async offset => {
let locator = jsonOutlineProvider.getLocator(offset)
let text = await selCommand.getText(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('extension.getAttribute', async offset => {
let locator = jsonOutlineProvider.getLocator(offset)
let text = await selCommand.getAttribute(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('extension.getCssValue', async offset => {
let locator = jsonOutlineProvider.getLocator(offset)
let text = await selCommand.getCssValue(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('extension.getElementInfo', async offset => {
let locator = jsonOutlineProvider.getLocator(offset)
let text = await selCommand.getElementInfo(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('extension.hideElement', async offset => {
let locator = jsonOutlineProvider.getLocator(offset)
let text = await selCommand.hideElement(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('extension.showElement', async offset => {
let locator = jsonOutlineProvider.getLocator(offset)
let text = await selCommand.showElement(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('extension.click', async offset => {
let locator = jsonOutlineProvider.getLocator(offset)
let text = await selCommand.click(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('extension.jsClick', async offset => {
let locator = jsonOutlineProvider.getLocator(offset)
let text = await selCommand.jsClick(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('extension.clear', async offset => {
let locator = jsonOutlineProvider.getLocator(offset)
let text = await selCommand.clear(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('extension.sendKeys', async offset => {
let locator = jsonOutlineProvider.getLocator(offset)
let text = await selCommand.sendKeys(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('extension.hover', async offset => {
let locator = jsonOutlineProvider.getLocator(offset)
let text = await selCommand.hover(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('extension.jsHover', async offset => {
let locator = jsonOutlineProvider.getLocator(offset)
let text = await selCommand.jsHover(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('extension.updateElement', async offset => {
let locator = await selCommand.selectElement()
jsonOutlineProvider.updateLocator(locator, offset)
});
vscode.commands.registerCommand('extension.generateElement', async () => {
let jsonElement = await selCommand.generateElement()
jsonOutlineProvider.addElement(jsonElement)
});
vscode.commands.registerCommand('extension.generateElements', async () => {
let jsonElements = await selCommand.generateElements()
jsonOutlineProvider.addElements(jsonElements)
});
vscode.commands.registerCommand('extension.generateAllElements', async () => {
let jsonElements = await selCommand.generateAllElements()
jsonOutlineProvider.addElements(jsonElements)
});
vscode.commands.registerCommand('extension.getCurrentUrl', async () => {
let text = await selCommand.getCurrentUrl()
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('extension.runBatchScript', async () => {
await selCommand.runJsScript()
});
vscode.commands.registerCommand('extension.closeTab', async () => {
await selCommand.closeTab()
});
vscode.commands.registerCommand('extension.switchToMainTab', async () => {
await selCommand.switchToMainTab()
});
vscode.commands.registerCommand('extension.switchToNextTab', async () => {
await selCommand.switchToNextTab()
});
vscode.commands.registerCommand('extension.switchToFrame', async () => {
let text = await selCommand.switchToFrame()
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('extension.switchToParentFrame', async () => {
let text = await selCommand.switchToParentFrame()
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('extension.switchToDefaultContent', async () => {
let text = await selCommand.switchToDefaultContent()
vscode.window.showInformationMessage(text);
});
const pageViewProvider = new PageViewProvider(context);
vscode.window.registerTreeDataProvider('pageView', pageViewProvider);
vscode.commands.registerCommand('pageView.highlight', async node => {
let text = await selCommand.highlight(node.item)
if(text) {
vscode.window.showInformationMessage(text);
}
});
vscode.commands.registerCommand('pageView.codeGen', async viewPath => {
vscode.window.activeTextEditor.insertSnippet(new vscode.SnippetString(viewPath))
});
vscode.commands.registerCommand('pageView.openFile', async node => {
vscode.window.showTextDocument(vscode.Uri.file(path.join(pageViewProvider.locatorDir, node.viewPath.replace(/\./, '/') + '.json')))
});
vscode.commands.registerCommand('pageView.refresh', () => pageViewProvider.refresh());
const webViewProvider = new DebuggerViewProvider(context.extensionUri);
vscode.window.registerWebviewViewProvider(DebuggerViewProvider.viewType, webViewProvider);
vscode.commands.registerCommand('debugView.isDisplayed', async () => {
let locator = webViewProvider.getLocator()
let text = await selCommand.isDisplayed(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('debugView.isEnabled', async () => {
let locator = webViewProvider.getLocator()
let text = await selCommand.isEnabled(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('debugView.isSelected', async () => {
let locator = webViewProvider.getLocator()
let text = await selCommand.isSelected(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('debugView.getText', async () => {
let locator = webViewProvider.getLocator()
let text = await selCommand.getText(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('debugView.getAttribute', async () => {
let locator = webViewProvider.getLocator()
let text = await selCommand.getAttribute(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('debugView.getCssValue', async () => {
let locator = webViewProvider.getLocator()
let text = await selCommand.getCssValue(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('debugView.getElementInfo', async () => {
let locator = webViewProvider.getLocator()
let text = await selCommand.getElementInfo(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('debugView.hideElement', async () => {
let locator = webViewProvider.getLocator()
let text = await selCommand.hideElement(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('debugView.showElement', async () => {
let locator = webViewProvider.getLocator()
let text = await selCommand.showElement(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('debugView.click', async () => {
let locator = webViewProvider.getLocator()
let text = await selCommand.click(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('debugView.jsClick', async () => {
let locator = webViewProvider.getLocator()
let text = await selCommand.jsClick(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('debugView.clear', async () => {
let locator = webViewProvider.getLocator()
let text = await selCommand.clear(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('debugView.sendKeys', async () => {
let locator = webViewProvider.getLocator()
let text = await selCommand.sendKeys(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('debugView.hover', async () => {
let locator = webViewProvider.getLocator()
let text = await selCommand.hover(locator)
vscode.window.showInformationMessage(text);
});
vscode.commands.registerCommand('debugView.jsHover', async () => {
let locator = webViewProvider.getLocator()
let text = await selCommand.jsHover(locator)
vscode.window.showInformationMessage(text);
});
} | the_stack |
import axios, { AxiosRequestConfig } from 'axios';
import { PinoLogger } from 'nestjs-pino';
import BigNumber from 'bignumber.js';
import * as fcl from '@onflow/fcl';
import * as sdk from '@onflow/sdk';
import { NftError } from './NftError';
import { HarmonyAddress } from '@harmony-js/crypto';
import {
CeloBurnErc721,
CeloDeployErc721,
CeloMintErc721,
CeloMintMultipleErc721,
CeloTransferErc721,
CeloUpdateCashbackErc721,
convertAddressFromHex,
Currency,
EthBurnErc721,
EthDeployErc721,
EthMintErc721,
EthMintMultipleErc721,
EthTransferErc721,
FlowBurnNft,
FlowDeployNft,
FlowMintMultipleNft,
FlowMintNft,
FlowTransferNft,
getFlowNftMetadata,
getFlowNftTokenByAddress,
OneBurn721,
OneDeploy721,
OneMint721,
OneMintMultiple721,
OneTransfer721,
OneUpdateCashback721,
prepareBscBurnBep721SignedTransaction,
prepareBscDeployBep721SignedTransaction,
prepareBscMintBep721SignedTransaction,
prepareBscMintBepCashback721SignedTransaction,
prepareBscMintMultipleBep721SignedTransaction,
prepareBscMintMultipleCashbackBep721SignedTransaction,
prepareBscTransferBep721SignedTransaction,
prepareBscUpdateCashbackForAuthorErc721SignedTransaction,
prepareCeloBurnErc721SignedTransaction,
prepareCeloDeployErc721SignedTransaction,
prepareCeloMintCashbackErc721SignedTransaction,
prepareCeloMintErc721SignedTransaction,
prepareCeloMintMultipleCashbackErc721SignedTransaction,
prepareCeloMintMultipleErc721SignedTransaction,
prepareCeloTransferErc721SignedTransaction,
prepareCeloUpdateCashbackForAuthorErc721SignedTransaction,
prepareEthBurnErc721SignedTransaction,
prepareEthDeployErc721SignedTransaction,
prepareEthMintCashbackErc721SignedTransaction,
prepareEthMintErc721SignedTransaction,
prepareEthMintMultipleCashbackErc721SignedTransaction,
prepareEthMintMultipleErc721SignedTransaction,
prepareEthTransferErc721SignedTransaction,
prepareEthUpdateCashbackForAuthorErc721SignedTransaction, preparePolygonBurnErc721SignedTransaction,
preparePolygonDeployErc721SignedTransaction,
preparePolygonMintCashbackErc721SignedTransaction,
preparePolygonMintErc721SignedTransaction,
preparePolygonMintMultipleCashbackErc721SignedTransaction,
preparePolygonMintMultipleErc721SignedTransaction,
preparePolygonTransferErc721SignedTransaction,
preparePolygonUpdateCashbackForAuthorErc721SignedTransaction,
prepareTronBurnTrc721SignedTransaction,
prepareTronDeployTrc721SignedTransaction,
prepareTronMintCashbackTrc721SignedTransaction,
prepareTronMintMultipleTrc721SignedTransaction,
prepareTronMintTrc721SignedTransaction,
prepareTronTransferTrc721SignedTransaction,
prepareTronUpdateCashbackForAuthorTrc721SignedTransaction,
sendFlowNftBurnToken,
sendFlowNftMintMultipleToken,
sendFlowNftMintToken,
sendFlowNftTransferToken,
TransactionHash,
TronBurnTrc721,
TronDeployTrc721,
TronMintMultipleTrc721,
TronMintTrc721,
TronTransferTrc721,
TronUpdateCashbackTrc721,
UpdateCashbackErc721,
EgldTransaction,
EgldEsdtTransaction,
egldGetTransaction,
prepareEgldTransferNftSignedTransaction,
prepareEgldCreateNftOrSftSignedTransaction,
prepareEgldAddOrBurnNftQuantitySignedTransaction,
prepareEgldDeployNftOrSftSignedTransaction,
prepareCeloMintErc721ProvenanceSignedTransaction,
prepareBscMintBep721ProvenanceSignedTransaction,
prepareOneMint721ProvenanceSignedTransaction,
prepareEthMintErc721ProvenanceSignedTransaction,
preparePolygonMintErc721ProvenanceSignedTransaction,
prepareCeloMintMultipleErc721ProvenanceSignedTransaction,
prepareBscMintMultipleBep721ProvenanceSignedTransaction,
prepareOneMintMultiple721ProvenanceSignedTransaction,
prepareEthMintMultipleErc721ProvenanceSignedTransaction,
preparePolygonMintMultipleErc721ProvenanceSignedTransaction,
sendSmartContractReadMethodInvocationTransaction,
sendCeloSmartContractReadMethodInvocationTransaction,
sendBscSmartContractReadMethodInvocationTransaction,
sendPolygonSmartContractReadMethodInvocationTransaction,
sendOneSmartContractReadMethodInvocationTransaction,
SmartContractReadMethodInvocation
} from '@tatumio/tatum';
import erc721Provenance_abi from '@tatumio/tatum/dist/src/contracts/erc721Provenance/erc721Provenance_abi';
import erc721_abi from '@tatumio/tatum/dist/src/contracts/erc721/erc721_abi';
import Web3 from 'web3';
import { Transaction, TransactionReceipt } from 'web3-eth';
import { FlowTxType, } from '@tatumio/tatum/dist/src/transaction/flow';
import {
prepareOneBurn721SignedTransaction,
prepareOneDeploy721SignedTransaction,
prepareOneMint721SignedTransaction,
prepareOneMintCashback721SignedTransaction,
prepareOneMintMultiple721SignedTransaction,
prepareOneMintMultipleCashback721SignedTransaction,
prepareOneTransfer721SignedTransaction,
prepareOneUpdateCashbackForAuthor721SignedTransaction
} from '@tatumio/tatum/dist/src/transaction/one';
import { ChainEgldEsdtTransaction } from './dto/ChainEgldEsdtTransaction'
export abstract class NftService {
protected constructor(protected readonly logger: PinoLogger) {
}
protected abstract storeKMSTransaction(txData: string, currency: string, signatureId: string[], index?: number): Promise<string>;
protected abstract isTestnet(): Promise<boolean>;
protected abstract wrapFlowCall(operation: (proposer: any, payer: any) => Promise<any>): Promise<any>;
protected abstract getTronClient(testnet: boolean): Promise<any>;
protected abstract getNodesUrl(chain: Currency, testnet: boolean): Promise<string[]>;
protected abstract broadcast(chain: Currency, txData: string, signatureId?: string);
protected abstract deployFlowNft(testnet: boolean, body: FlowDeployNft): Promise<TransactionHash>;
protected abstract getMintBuiltInData(body: CeloMintErc721 | EthMintErc721 | TronMintTrc721 | OneMint721): Promise<CeloMintErc721 | EthMintErc721 | TronMintTrc721 | OneMint721 | undefined>;
public async getMetadataErc721(chain: Currency, token: string, contractAddress: string, account?: string, nonce?: string): Promise<{ data: string }> {
if (chain === Currency.FLOW) {
if (!account) {
throw new NftError(`Account address must be present.`, 'nft.erc721.failed');
}
try {
return { data: await getFlowNftMetadata(await this.isTestnet(), account, token, contractAddress) };
} catch (e) {
this.logger.error(e);
throw new NftError(`Unable to obtain information for token. ${e}`, 'nft.erc721.failed');
}
} else if (chain === Currency.TRON) {
const client = await this.getClient(chain, await this.isTestnet());
client.setAddress(contractAddress);
const c = await client.contract().at(contractAddress);
try {
return { data: await c.tokenURI(token).call() };
} catch (e) {
this.logger.error(e);
throw new NftError(`Unable to obtain information for token. ${e}`, 'nft.erc721.failed');
}
} else if (chain === Currency.EGLD) {
return await this.GetNftDataForAddress(chain, token, contractAddress, nonce, await this.isTestnet())
}
// @ts-ignore
const c = new (await this.getClient(chain, await this.isTestnet())).eth.Contract(erc721_abi, chain === Currency.ONE ? new HarmonyAddress(contractAddress).basicHex : contractAddress);
try {
return { data: await c.methods.tokenURI(token).call() };
} catch (e) {
this.logger.error(e);
throw new NftError(`Unable to obtain information for token. ${e}`, 'nft.erc721.failed');
}
}
public async getRoyaltyErc721(chain: Currency, token: string, contractAddress: string, nonce?: string) {
if (chain === Currency.FLOW) {
throw new NftError(`Unsupported chain ${chain}.`, 'unsupported.chain');
}
else if (chain === Currency.TRON) {
const client = await this.getClient(chain, await this.isTestnet());
client.setAddress(contractAddress);
const c = await client.contract().at(contractAddress);
try {
const [addresses, values] = await Promise.all([c.tokenCashbackRecipients(token).call(), c.tokenCashbackValues(token).call()]);
return { addresses: addresses.map(a => convertAddressFromHex(a)), values: values.map(c => new BigNumber(c._hex).dividedBy(1e6).toString(10)) };
} catch (e) {
this.logger.error(e);
throw new NftError(`Unable to obtain information for token. ${e}`, 'nft.erc721.failed');
}
} else if (chain === Currency.EGLD) {
const data = await this.GetNftDataForAddress(chain, token, contractAddress, nonce, await this.isTestnet())
return { addresses: [token], values: [data?.royalties] }
}
// @ts-ignore
const c = new (await this.getClient(chain, await this.isTestnet())).eth.Contract(erc721_abi, chain === Currency.ONE ? new HarmonyAddress(contractAddress).basicHex : contractAddress);
try {
const [addresses, values] = await Promise.all([c.methods.tokenCashbackRecipients(token).call(), c.methods.tokenCashbackValues(token).call()]);
return { addresses, values: values.map(c => new BigNumber(c).dividedBy(1e18).toString(10)) };
} catch (e) {
this.logger.error(e);
throw new NftError(`Unable to obtain information for token. ${e}`, 'nft.erc721.failed');
}
}
public async getProvenanceData(chain: Currency, contractAddress: string, tokenId: string) {
try {
const testnet = await this.isTestnet();
const provider = (await this.getNodesUrl(chain, testnet))[0];
const body = new SmartContractReadMethodInvocation()
const result = [];
let txData;
body.contractAddress = contractAddress
body.params = [tokenId]
body.methodName = 'getTokenData'
body.methodABI = erc721Provenance_abi.find((a: any) => a.name === 'getTokenData')
switch (chain) {
case Currency.ETH:
txData = await sendSmartContractReadMethodInvocationTransaction(body);
break;
case Currency.CELO:
txData = await sendCeloSmartContractReadMethodInvocationTransaction(testnet, body, provider);
case Currency.BSC:
txData = await sendBscSmartContractReadMethodInvocationTransaction(body);
break;
case Currency.ONE:
txData = await sendOneSmartContractReadMethodInvocationTransaction(testnet, body, provider);
break;
case Currency.MATIC:
txData = await sendPolygonSmartContractReadMethodInvocationTransaction(testnet, body, provider);
break;
default:
throw new NftError(`Unsupported chain ${chain}.`, 'unsupported.chain');
}
for (let i = 0; i < txData.data.length; i++) {
const t = txData.data[i].split("'''###'''", 2)
result.push({ provenanaceData: t[0], tokenPrice: t[1] })
}
return result
} catch (e) {
this.logger.error(e);
throw new NftError(`Unable to obtain information for token. ${e}`, 'nft.erc721.failed');
}
}
public async getTokensOfOwner(chain: Currency, address: string, contractAddress: string, nonce?: string | undefined) {
if (chain === Currency.FLOW) {
try {
return (await getFlowNftTokenByAddress(await this.isTestnet(), address, contractAddress)).map(e => `${e}`);
} catch (e) {
this.logger.error(e);
throw new NftError(`Unable to obtain information for token. ${e}`, 'nft.erc721.failed');
}
} else if (chain === Currency.TRON) {
const client = await this.getClient(chain, await this.isTestnet());
client.setAddress(contractAddress);
const c = await client.contract().at(contractAddress);
try {
return { data: (await c.tokensOfOwner(address).call()).map(c => new BigNumber(c._hex).toString(10)) };
} catch (e) {
this.logger.error(e);
throw new NftError(`Unable to obtain information for token. ${e}`, 'nft.erc721.failed');
}
} else if (chain === Currency.EGLD) {
return { data: [(await this.GetNftDataForAddress(chain, address, contractAddress, nonce, await this.isTestnet()))?.creator] }
}
// @ts-ignore
const c = new (await this.getClient(chain, await this.isTestnet())).eth.Contract(erc721_abi, chain === Currency.ONE ? new HarmonyAddress(contractAddress).basicHex : contractAddress);
try {
return { data: await c.methods.tokensOfOwner(address).call() };
} catch (e) {
this.logger.error(e);
throw new NftError(`Unable to obtain information for token. ${e}`, 'nft.erc721.failed');
}
}
public async getContractAddress(chain: Currency, txId: string) {
if (chain === Currency.FLOW) {
try {
await this.getClient(chain, await this.isTestnet());
const tx = await sdk.send(sdk.build([sdk.getTransaction(txId)]));
const { args } = await sdk.decode(tx);
if (args && args.length) {
return { contractAddress: args[0].value };
}
} catch (e) {
this.logger.error(e);
}
throw new NftError('Transaction not found. Possible not exists or is still pending.', 'tx.not.found');
} else if (chain === Currency.TRON) {
try {
const tx = await (await this.getClient(chain, await this.isTestnet())).trx.getTransactionInfo(txId);
return { contractAddress: convertAddressFromHex(tx.contract_address) };
} catch (e) {
this.logger.error(e);
throw new NftError('Transaction not found. Possible not exists or is still pending.', 'tx.not.found');
}
} else if (chain === Currency.EGLD) {
throw new NftError(`Unsupported chain ${chain}.`, 'unsupported.chain');
}
try {
const web3 = await this.getClient(chain, await this.isTestnet());
const { contractAddress } = await web3.eth.getTransactionReceipt(txId);
return { contractAddress };
} catch (e) {
this.logger.error(e);
throw new NftError('Transaction not found. Possible not exists or is still pending.', 'tx.not.found');
}
}
public async getTransaction(chain: Currency, txId: string): Promise<Transaction & TransactionReceipt | EgldTransaction> {
if (chain === Currency.FLOW) {
try {
await this.getClient(chain, await this.isTestnet());
const tx = await sdk.send(sdk.build([sdk.getTransaction(txId)]));
const decoded = await sdk.decode(tx);
try {
const txStatus = await sdk.send(sdk.build([sdk.getTransactionStatus(txId)]));
return { ...decoded, ...await sdk.decode(txStatus) };
} catch (e) {
this.logger.warn(e);
}
return decoded;
} catch (e) {
this.logger.error(e);
}
throw new NftError('Transaction not found. Possible not exists or is still pending.', 'tx.not.found');
} else if (chain === Currency.TRON) {
try {
return await (await this.getClient(chain, await this.isTestnet())).trx.getTransactionInfo(txId);
} catch (e) {
this.logger.error(e);
throw new NftError('Transaction not found. Possible not exists or is still pending.', 'tx.not.found');
}
} else if (chain === Currency.EGLD) {
try {
return await egldGetTransaction(txId);
} catch (e) {
this.logger.error(e);
throw new NftError('Transaction not found. Possible not exists or is still pending.', 'tx.not.found');
}
}
try {
const web3 = await this.getClient(chain, await this.isTestnet());
const { r, s, v, hash, ...transaction } = (await web3.eth.getTransaction(txId)) as any;
let receipt: TransactionReceipt = undefined;
try {
receipt = await web3.eth.getTransactionReceipt(hash);
} catch (_) {
transaction.transactionHash = hash;
}
return { ...transaction, ...receipt };
} catch (e) {
this.logger.error(e);
throw new NftError('Transaction not found. Possible not exists or is still pending.', 'tx.not.found');
}
}
public async transferErc721(
body: CeloTransferErc721 | EthTransferErc721 | FlowTransferNft | TronTransferTrc721 | OneTransfer721 | ChainEgldEsdtTransaction
): Promise<TransactionHash | { signatureId: string }> {
const testnet = await this.isTestnet();
let txData;
const { chain } = body;
const provider = (await this.getNodesUrl(chain, testnet))[0];
switch (chain) {
case Currency.ETH:
txData = await prepareEthTransferErc721SignedTransaction(body as EthTransferErc721, provider);
break;
case Currency.ONE:
txData = await prepareOneTransfer721SignedTransaction(testnet, body as OneTransfer721, provider);
break;
case Currency.MATIC:
txData = await preparePolygonTransferErc721SignedTransaction(testnet, body as EthTransferErc721, provider);
break;
case Currency.TRON:
await this.getClient(chain, await this.isTestnet());
txData = await prepareTronTransferTrc721SignedTransaction(testnet, body as TronTransferTrc721);
break;
case Currency.BSC:
txData = await prepareBscTransferBep721SignedTransaction(body as EthTransferErc721, provider);
break;
case Currency.CELO:
txData = await prepareCeloTransferErc721SignedTransaction(testnet, body as CeloTransferErc721, provider);
break;
case Currency.EGLD:
txData = await prepareEgldTransferNftSignedTransaction(body as EgldEsdtTransaction, provider);
break;
case Currency.FLOW:
if (body.signatureId) {
txData = JSON.stringify({ type: FlowTxType.TRANSFER_NFT, body });
} else {
return this.wrapFlowCall(async (proposer, payer) =>
await sendFlowNftTransferToken(testnet, body as FlowTransferNft, proposer, payer));
}
break;
// case Currency.XDC:
// txData = await prepareXdcTransferErc721SignedTransaction(body, (await this.getNodesUrl(chain, testnet))[0]);
// break;
default:
throw new NftError(`Unsupported chain ${chain}.`, 'unsupported.chain');
}
if (body.signatureId) {
return { signatureId: await this.storeKMSTransaction(txData, chain, [body.signatureId], body.index) };
} else {
return this.broadcast(chain, txData);
}
}
public async mintErc721(
body: CeloMintErc721 | EthMintErc721 | FlowMintNft | TronMintTrc721 | OneMint721 | ChainEgldEsdtTransaction
): Promise<TransactionHash | { signatureId: string } | { txId: string, tokenId: number }> {
const testnet = await this.isTestnet();
let txData;
const { chain } = body;
const provider = (await this.getNodesUrl(chain, testnet))[0];
switch (chain) {
case Currency.ETH: {
const builtInBody = await this.getMintBuiltInData(body as EthMintErc721)
if ((body as EthMintErc721).provenance) {
txData = await prepareEthMintErc721ProvenanceSignedTransaction((builtInBody || body) as EthMintErc721, provider);
} else {
if (!(body as EthMintErc721).authorAddresses) {
txData = await prepareEthMintErc721SignedTransaction((builtInBody || body) as EthMintErc721, provider);
} else {
txData = await prepareEthMintCashbackErc721SignedTransaction((builtInBody || body) as EthMintErc721, provider);
}
}
break;
}
case Currency.MATIC: {
const builtInBody = await this.getMintBuiltInData(body as EthMintErc721)
if ((body as EthMintErc721).provenance) {
txData = await preparePolygonMintErc721ProvenanceSignedTransaction(testnet, (builtInBody || body) as EthMintErc721, provider);
} else {
if (!(body as EthMintErc721).authorAddresses) {
txData = await preparePolygonMintErc721SignedTransaction(testnet, (builtInBody || body) as EthMintErc721, provider);
} else {
txData = await preparePolygonMintCashbackErc721SignedTransaction(testnet, (builtInBody || body) as EthMintErc721, provider);
}
}
break;
}
case Currency.ONE: {
const builtInBody = await this.getMintBuiltInData(body as OneMint721)
if ((body as OneMint721).provenance) {
txData = await prepareOneMint721ProvenanceSignedTransaction(testnet, (builtInBody || body) as OneMint721, provider);
} else {
if (!(body as OneMint721).authorAddresses) {
txData = await prepareOneMint721SignedTransaction(testnet, (builtInBody || body) as OneMint721, provider);
} else {
txData = await prepareOneMintCashback721SignedTransaction(testnet, (builtInBody || body) as OneMint721, provider);
}
}
break;
}
case Currency.BSC: {
const builtInBody = await this.getMintBuiltInData(body as EthMintErc721)
if ((body as EthMintErc721).provenance) {
txData = await prepareBscMintBep721ProvenanceSignedTransaction((builtInBody || body) as EthMintErc721, provider);
} else {
if (!(body as EthMintErc721).authorAddresses) {
txData = await prepareBscMintBep721SignedTransaction((builtInBody || body) as EthMintErc721, provider);
} else {
txData = await prepareBscMintBepCashback721SignedTransaction((builtInBody || body) as EthMintErc721, provider);
}
}
break;
}
case Currency.TRON:
await this.getClient(chain, await this.isTestnet());
if (!(body as TronMintTrc721).authorAddresses) {
txData = await prepareTronMintTrc721SignedTransaction(testnet, body as TronMintTrc721);
} else {
txData = await prepareTronMintCashbackTrc721SignedTransaction(testnet, body as TronMintTrc721);
}
break;
case Currency.CELO: {
const builtInBody = await this.getMintBuiltInData(body as CeloMintErc721)
if ((body as CeloMintErc721).provenance) {
txData = await prepareCeloMintErc721ProvenanceSignedTransaction(testnet, (builtInBody || body) as CeloMintErc721, provider);
} else {
if (!(body as CeloMintErc721).authorAddresses) {
txData = await prepareCeloMintErc721SignedTransaction(testnet, (builtInBody || body) as CeloMintErc721, provider);
} else {
txData = await prepareCeloMintCashbackErc721SignedTransaction(testnet, (builtInBody || body) as CeloMintErc721, provider);
}
}
break;
}
case Currency.EGLD:
txData = await prepareEgldCreateNftOrSftSignedTransaction(body as EgldEsdtTransaction, provider)
break;
case Currency.FLOW:
if (body.signatureId) {
txData = JSON.stringify({ type: FlowTxType.MINT_NFT, body });
} else {
return this.wrapFlowCall(async (proposer, payer) => await sendFlowNftMintToken(testnet, body as FlowMintNft, proposer, payer));
}
break;
// case Currency.XDC:
// if (!(body as EthMintErc721).authorAddresses) {
// txData = await prepareXdcMintErc721SignedTransaction(body as EthMintErc721, provider);
// } else {
// txData = await prepareXdcMintErcCashback721SignedTransaction(body as EthMintErc721, provider);
// }
// break;
default:
throw new NftError(`Unsupported chain ${chain}.`, 'unsupported.chain');
}
if (body.signatureId) {
return { signatureId: await this.storeKMSTransaction(txData, chain, [body.signatureId], body.index) };
} else {
return this.broadcast(chain, txData);
}
}
public async mintMultipleErc721(
body: CeloMintMultipleErc721 | EthMintMultipleErc721 | FlowMintMultipleNft | TronMintMultipleTrc721 | OneMintMultiple721
): Promise<TransactionHash | { signatureId: string } | { txId: string, tokenId: number[] }> {
const testnet = await this.isTestnet();
let txData;
const { chain } = body;
const provider = (await this.getNodesUrl(chain, testnet))[0];
switch (chain) {
case Currency.ETH:
if ((body as EthMintMultipleErc721).provenance) {
txData = await prepareEthMintMultipleErc721ProvenanceSignedTransaction(body as EthMintMultipleErc721, provider);
} else {
if (!(body as EthMintMultipleErc721).authorAddresses) {
txData = await prepareEthMintMultipleErc721SignedTransaction(body as EthMintMultipleErc721, provider);
} else {
txData = await prepareEthMintMultipleCashbackErc721SignedTransaction(body as EthMintMultipleErc721, provider);
}
}
break;
case Currency.MATIC:
if ((body as EthMintMultipleErc721).provenance) {
txData = await preparePolygonMintMultipleErc721ProvenanceSignedTransaction(testnet, body as EthMintMultipleErc721, provider);
} else {
if (!(body as EthMintMultipleErc721).authorAddresses) {
txData = await preparePolygonMintMultipleErc721SignedTransaction(testnet, body as EthMintMultipleErc721, provider);
} else {
txData = await preparePolygonMintMultipleCashbackErc721SignedTransaction(testnet, body as EthMintMultipleErc721, provider);
}
}
break;
case Currency.ONE:
if ((body as OneMintMultiple721).provenance) {
txData = await prepareOneMintMultiple721ProvenanceSignedTransaction(testnet, body as OneMintMultiple721, provider);
} else {
if (!(body as OneMintMultiple721).authorAddresses) {
txData = await prepareOneMintMultiple721SignedTransaction(testnet, body as OneMintMultiple721, provider);
} else {
txData = await prepareOneMintMultipleCashback721SignedTransaction(testnet, body as OneMintMultiple721, provider);
}
}
break;
case Currency.TRON:
await this.getClient(chain, await this.isTestnet());
if (!(body as TronMintMultipleTrc721).authorAddresses) {
txData = await prepareTronMintMultipleTrc721SignedTransaction(testnet, body as TronMintMultipleTrc721);
} else {
throw new NftError(`Unsupported chain ${chain}.`, 'unsupported.chain');
}
break;
case Currency.BSC:
if ((body as EthMintMultipleErc721).provenance) {
txData = await prepareBscMintMultipleBep721ProvenanceSignedTransaction(body as EthMintMultipleErc721, provider);
} else {
if (!(body as EthMintMultipleErc721).authorAddresses) {
txData = await prepareBscMintMultipleBep721SignedTransaction(body as EthMintMultipleErc721, provider);
} else {
txData = await prepareBscMintMultipleCashbackBep721SignedTransaction(body as EthMintMultipleErc721, provider);
}
}
break;
case Currency.CELO:
if ((body as CeloMintMultipleErc721).provenance) {
txData = await prepareCeloMintMultipleErc721ProvenanceSignedTransaction(testnet, body as CeloMintMultipleErc721, provider);
} else {
if (!(body as CeloMintMultipleErc721).authorAddresses) {
txData = await prepareCeloMintMultipleErc721SignedTransaction(testnet, body as CeloMintMultipleErc721, provider);
} else {
txData = await prepareCeloMintMultipleCashbackErc721SignedTransaction(testnet, body as CeloMintMultipleErc721, provider);
}
}
break;
case Currency.EGLD:
// txData = await prepareEgldCreateNftOrSftSignedTransaction(body as EgldEsdtTransaction, provider)
throw new NftError(`Unsupported chain ${chain}.`, 'unsupported.chain');
case Currency.FLOW:
if (body.signatureId) {
txData = JSON.stringify({ type: FlowTxType.MINT_MULTIPLE_NFT, body });
} else {
return this.wrapFlowCall(async (proposer, payer) => await sendFlowNftMintMultipleToken(testnet, body as FlowMintMultipleNft, proposer, payer));
}
break;
// case Currency.XDC:
// if (!(body as EthMintMultipleErc721).authorAddresses) {
// txData = await prepareXdcMintMultipleErc721SignedTransaction(body as EthMintMultipleErc721, provider);
// } else {
// txData = await prepareXdcMintMultipleCashbackErc721SignedTransaction(body as EthMintMultipleErc721, provider);
// }
// break;
default:
throw new NftError(`Unsupported chain ${chain}.`, 'unsupported.chain');
}
if (body.signatureId) {
return { signatureId: await this.storeKMSTransaction(txData, chain, [body.signatureId], body.index) };
} else {
return this.broadcast(chain, txData);
}
}
public async updateCashbackForAuthor(body: CeloUpdateCashbackErc721 | UpdateCashbackErc721 | TronUpdateCashbackTrc721 | OneUpdateCashback721): Promise<TransactionHash | { signatureId: string }> {
const testnet = await this.isTestnet();
let txData;
const { chain } = body;
switch (chain) {
case Currency.ETH:
txData = await prepareEthUpdateCashbackForAuthorErc721SignedTransaction(body, (await this.getNodesUrl(chain, testnet))[0]);
break;
case Currency.MATIC:
txData = await preparePolygonUpdateCashbackForAuthorErc721SignedTransaction(testnet, body, (await this.getNodesUrl(chain, testnet))[0]);
break;
case Currency.ONE:
txData = await prepareOneUpdateCashbackForAuthor721SignedTransaction(testnet, body as OneUpdateCashback721, (await this.getNodesUrl(chain, testnet))[0]);
break;
case Currency.TRON:
await this.getClient(chain, await this.isTestnet());
txData = await prepareTronUpdateCashbackForAuthorTrc721SignedTransaction(testnet, body as TronUpdateCashbackTrc721);
break;
case Currency.BSC:
txData = await prepareBscUpdateCashbackForAuthorErc721SignedTransaction(body, (await this.getNodesUrl(chain, testnet))[0]);
break;
case Currency.CELO:
txData = await prepareCeloUpdateCashbackForAuthorErc721SignedTransaction(testnet, body as CeloUpdateCashbackErc721, (await this.getNodesUrl(chain, testnet))[0]);
break;
case Currency.EGLD:
throw new NftError(`Unsupported chain ${chain}.`, 'unsupported.chain');
// case Currency.XDC:
// txData = await prepareXdcUpdateCashbackForAuthorErc721SignedTransaction(body, (await this.getNodesUrl(chain, testnet))[0]);
// break;
default:
throw new NftError(`Unsupported chain ${chain}.`, 'unsupported.chain');
}
if (body.signatureId) {
return { signatureId: await this.storeKMSTransaction(txData, chain, [body.signatureId], body.index) };
} else {
return this.broadcast(chain, txData);
}
}
public async burnErc721(
body: CeloBurnErc721 | EthBurnErc721 | FlowBurnNft | TronBurnTrc721 | OneBurn721 | ChainEgldEsdtTransaction
): Promise<TransactionHash | { signatureId: string }> {
const testnet = await this.isTestnet();
let txData;
const { chain } = body;
const provider = (await this.getNodesUrl(chain, testnet))[0];
switch (chain) {
case Currency.ETH:
txData = await prepareEthBurnErc721SignedTransaction(body as EthBurnErc721, provider);
break;
case Currency.MATIC:
txData = await preparePolygonBurnErc721SignedTransaction(testnet, body as EthBurnErc721, provider);
break;
case Currency.ONE:
txData = await prepareOneBurn721SignedTransaction(testnet, body as OneBurn721, provider);
break;
case Currency.TRON:
await this.getClient(chain, await this.isTestnet());
txData = await prepareTronBurnTrc721SignedTransaction(testnet, body as TronBurnTrc721);
break;
case Currency.BSC:
txData = await prepareBscBurnBep721SignedTransaction(body as EthBurnErc721, provider);
break;
case Currency.CELO:
txData = await prepareCeloBurnErc721SignedTransaction(testnet, body as CeloBurnErc721, provider);
break;
case Currency.EGLD:
txData = await prepareEgldAddOrBurnNftQuantitySignedTransaction(body as EgldEsdtTransaction, provider)
break;
case Currency.FLOW:
if (body.signatureId) {
txData = JSON.stringify({ type: FlowTxType.BURN_NFT, body });
} else {
return this.wrapFlowCall(async (proposer, payer) => await sendFlowNftBurnToken(testnet, body as FlowBurnNft, proposer, payer));
}
break;
// case Currency.XDC:
// txData = await prepareXdcBurnErc721SignedTransaction(body, (await this.getNodesUrl(chain, testnet))[0]);
// break;
default:
throw new NftError(`Unsupported chain ${chain}.`, 'unsupported.chain');
}
if (body.signatureId) {
return { signatureId: await this.storeKMSTransaction(txData, chain, [body.signatureId], body.index) };
} else {
return this.broadcast(chain, txData);
}
}
public async deployErc721(
body: CeloDeployErc721 | EthDeployErc721 | FlowDeployNft | TronDeployTrc721 | OneDeploy721 | ChainEgldEsdtTransaction
): Promise<TransactionHash | { signatureId: string }> {
const testnet = await this.isTestnet();
let txData;
const { chain } = body;
const provider = (await this.getNodesUrl(chain, testnet))[0];
switch (chain) {
case Currency.ETH:
txData = await prepareEthDeployErc721SignedTransaction(body as EthDeployErc721, provider);
break;
case Currency.MATIC:
txData = await preparePolygonDeployErc721SignedTransaction(testnet, body as EthDeployErc721, provider);
break;
case Currency.ONE:
txData = await prepareOneDeploy721SignedTransaction(testnet, body as OneDeploy721, provider);
break;
case Currency.BSC:
txData = await prepareBscDeployBep721SignedTransaction(body as EthDeployErc721, provider);
break;
case Currency.TRON:
await this.getClient(chain, await this.isTestnet());
txData = await prepareTronDeployTrc721SignedTransaction(testnet, body as TronDeployTrc721);
break;
case Currency.CELO:
txData = await prepareCeloDeployErc721SignedTransaction(testnet, body as CeloDeployErc721, provider);
break;
case Currency.EGLD:
txData = await prepareEgldDeployNftOrSftSignedTransaction(body as EgldEsdtTransaction, provider)
break;
case Currency.FLOW:
return await this.deployFlowNft(testnet, body as FlowDeployNft);
// case Currency.XDC:
// txData = await prepareXdcDeployErc721SignedTransaction(body as EthDeployErc721, (await this.getNodesUrl(chain, testnet))[0]);
// break;
default:
throw new NftError(`Unsupported chain ${chain}.`, 'unsupported.chain');
}
if (body.signatureId) {
return { signatureId: await this.storeKMSTransaction(txData, chain, [body.signatureId], body.index) };
} else {
return await this.broadcast(chain, txData);
}
}
private async GetNftDataForAddress(
chain: Currency, address: string, contractAddress: string, nonce: string | undefined, testnet: boolean
): Promise<any> {
const provider = (await this.getNodesUrl(chain, testnet))[0];
try {
const { tokenData } = (await axios.get(`${provider}/address/${address}/nft/${contractAddress}/nonce/${nonce}`,
{ headers: { 'Content-Type': 'application/json' } })).data.data;
return { data: tokenData };
} catch (e) {
this.logger.error(e);
throw new NftError('Get NFT data for an address not found.', 'GetNftDataForAddress.not.found');
}
}
private async getClient(chain: Currency, testnet: boolean): Promise<any> {
const url = (await this.getNodesUrl(chain, testnet))[0];
if (chain === Currency.FLOW) {
fcl.config().put('accessNode.api', url);
return;
} else if (chain === Currency.TRON) {
return this.getTronClient(testnet);
}
return new Web3(url);
}
} | the_stack |
import { DataAccessTypes } from '@requestnetwork/types';
import RequestDataAccessBlock from '../src/block';
const CURRENT_VERSION = '0.1.0';
const transactionDataMock1String = JSON.stringify({
attribut1: 'plop',
attribut2: 'value',
});
const transactionDataMock2String = JSON.stringify({
attribut1: 'foo',
attribut2: 'bar',
});
const transactionMock: DataAccessTypes.ITransaction = {
data: transactionDataMock1String,
};
const transactionMock2: DataAccessTypes.ITransaction = {
data: transactionDataMock2String,
};
const arbitraryId1 = '011111111111111111111111111111111111111111111111111111111111111111';
const arbitraryId2 = '012222222222222222222222222222222222222222222222222222222222222222';
const arbitraryTopic1 = '01aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
const arbitraryTopic2 = '01cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc';
const emptyblock = RequestDataAccessBlock.createEmptyBlock();
const blockWith1tx = RequestDataAccessBlock.pushTransaction(
emptyblock,
transactionMock,
arbitraryId1,
[arbitraryTopic1, arbitraryTopic2],
);
const blockWith2tx = RequestDataAccessBlock.pushTransaction(
blockWith1tx,
transactionMock2,
arbitraryId2,
[arbitraryTopic2],
);
/* eslint-disable @typescript-eslint/no-unused-expressions */
describe('block', () => {
describe('createEmptyBlock', () => {
it('can create an empty block', () => {
const emptyblock1 = RequestDataAccessBlock.createEmptyBlock();
// 'header is wrong'
expect(emptyblock1.header).toEqual({
channelIds: {},
topics: {},
version: CURRENT_VERSION,
});
// 'transactions are wrong'
expect(emptyblock1.transactions).toEqual([]);
});
});
describe('pushTransaction', () => {
it('can pushTransaction with topics an empty block', () => {
const newBlock = RequestDataAccessBlock.pushTransaction(
emptyblock,
transactionMock,
arbitraryId1,
[arbitraryTopic1, arbitraryTopic2],
);
// empty block mush remain empty
// 'previous header must not change'
expect(emptyblock.header).toEqual({
channelIds: {},
topics: {},
version: CURRENT_VERSION,
});
// 'previous transactions must not change'
expect(emptyblock.transactions).toEqual([]);
// 'header is wrong'
expect(newBlock.header).toEqual({
channelIds: {
[arbitraryId1]: [0],
},
topics: {
[arbitraryId1]: [arbitraryTopic1, arbitraryTopic2],
},
version: CURRENT_VERSION,
});
// 'transactions are wrong'
expect(newBlock.transactions).toEqual([transactionMock]);
});
it('can pushTransaction with topics a NOT empty block', () => {
const previousBlock = RequestDataAccessBlock.pushTransaction(
emptyblock,
transactionMock,
arbitraryId1,
);
const newBlock = RequestDataAccessBlock.pushTransaction(
previousBlock,
transactionMock2,
arbitraryId2,
[arbitraryTopic1, arbitraryTopic2],
);
// 'previous header must not change'
expect(previousBlock.header).toEqual({
channelIds: {
[arbitraryId1]: [0],
},
topics: {},
version: CURRENT_VERSION,
});
// 'transactions are wrong'
expect(previousBlock.transactions).toEqual([transactionMock]);
// 'header is wrong'
expect(newBlock.header).toEqual({
channelIds: {
[arbitraryId1]: [0],
[arbitraryId2]: [1],
},
topics: {
[arbitraryId2]: [arbitraryTopic1, arbitraryTopic2],
},
version: CURRENT_VERSION,
});
// 'transactions are wrong'
expect(newBlock.transactions).toEqual([transactionMock, transactionMock2]);
});
it('can pushTransaction without topics on an empty block', () => {
const newBlock = RequestDataAccessBlock.pushTransaction(
emptyblock,
transactionMock,
arbitraryId1,
);
// empty block mush remain empty
// 'previous header must not change'
expect(emptyblock.header).toEqual({
channelIds: {},
topics: {},
version: CURRENT_VERSION,
});
// 'previous transactions must not change'
expect(emptyblock.transactions).toEqual([]);
// 'header is wrong'
expect(newBlock.header).toEqual({
channelIds: {
[arbitraryId1]: [0],
},
topics: {},
version: CURRENT_VERSION,
});
// 'transactions are wrong'
expect(newBlock.transactions).toEqual([transactionMock]);
});
it('can pushTransaction without topics on a NOT empty block', () => {
const previousBlock = RequestDataAccessBlock.pushTransaction(
emptyblock,
transactionMock,
arbitraryId1,
);
const newBlock = RequestDataAccessBlock.pushTransaction(
previousBlock,
transactionMock2,
arbitraryId2,
);
// 'previous header must not change'
expect(previousBlock.header).toEqual({
channelIds: {
[arbitraryId1]: [0],
},
topics: {},
version: CURRENT_VERSION,
});
// 'transactions are wrong'
expect(previousBlock.transactions).toEqual([transactionMock]);
// 'header is wrong'
expect(newBlock.header).toEqual({
channelIds: {
[arbitraryId1]: [0],
[arbitraryId2]: [1],
},
topics: {},
version: CURRENT_VERSION,
});
// 'transactions are wrong'
expect(newBlock.transactions).toEqual([transactionMock, transactionMock2]);
});
it('can pushTransaction with topics with topics already existing', () => {
const newBlock = RequestDataAccessBlock.pushTransaction(
blockWith1tx,
transactionMock2,
arbitraryId2,
[arbitraryTopic2],
);
// 'header is wrong'
expect(newBlock.header).toEqual({
channelIds: {
[arbitraryId1]: [0],
[arbitraryId2]: [1],
},
topics: {
[arbitraryId1]: [arbitraryTopic1, arbitraryTopic2],
[arbitraryId2]: [arbitraryTopic2],
},
version: CURRENT_VERSION,
});
// 'transactions are wrong'
expect(newBlock.transactions).toEqual([transactionMock, transactionMock2]);
});
it('cannot pushTransaction without property data', () => {
// 'must throw'
expect(() => {
RequestDataAccessBlock.pushTransaction(
emptyblock,
{ noData: 'here' } as any,
arbitraryId1,
[],
);
}).toThrowError('The transaction is missing the data property');
});
});
describe('getAllTransactions', () => {
it('can getAllTransactions on empty block', () => {
const allTxs = RequestDataAccessBlock.getAllTransactions(emptyblock);
// 'transactions must be empty'
expect(allTxs).toEqual([]);
});
it('can getAllTransactions on NOT empty block', () => {
let newBlock = RequestDataAccessBlock.pushTransaction(
emptyblock,
transactionMock,
arbitraryId1,
[arbitraryTopic1, arbitraryTopic2],
);
newBlock = RequestDataAccessBlock.pushTransaction(newBlock, transactionMock2, arbitraryId2);
const allTxs = RequestDataAccessBlock.getAllTransactions(newBlock);
// 'transactions must be empty'
expect(allTxs).toEqual([transactionMock, transactionMock2]);
});
});
describe('getAllTopic', () => {
it('can getAllTopic on empty block', () => {
const allTopices = RequestDataAccessBlock.getAllTopics(emptyblock);
// 'transactions must be empty'
expect(allTopices).toEqual({});
});
it('can getAllTopic on NOT empty block', () => {
const allTopices = RequestDataAccessBlock.getAllTopics(blockWith2tx);
// 'transactions must be empty'
expect(allTopices).toEqual({
[arbitraryId1]: [arbitraryTopic1, arbitraryTopic2],
[arbitraryId2]: [arbitraryTopic2],
});
});
});
describe('getAllChannelIds', () => {
it('can getAllChannelIds on empty block', () => {
const allIds = RequestDataAccessBlock.getAllChannelIds(emptyblock);
// 'transactions must be empty'
expect(allIds).toEqual({});
});
it('can getAllChannelIds on NOT empty block', () => {
const allIds = RequestDataAccessBlock.getAllChannelIds(blockWith2tx);
// 'transactions must be empty'
expect(allIds).toEqual({
[arbitraryId1]: [0],
[arbitraryId2]: [1],
});
});
});
describe('getTransactionFromPosition', () => {
it('can getTransactionFromPosition on an empty block', () => {
const tx = RequestDataAccessBlock.getTransactionFromPosition(emptyblock, 0);
// 'tx must be undefined'
expect(tx).toBeUndefined();
});
it('can getTransactionFromPosition with transaction existing', () => {
const tx = RequestDataAccessBlock.getTransactionFromPosition(blockWith1tx, 0);
// 'transactions is wrong'
expect(tx).toEqual(transactionMock);
});
});
describe('getTransactionPositionFromChannelId', () => {
it('can getTransactionPositionFromChannelId on an empty block', () => {
const txTopic = RequestDataAccessBlock.getTransactionPositionFromChannelId(
emptyblock,
arbitraryId1,
);
// 'txTopic is wrong'
expect(txTopic).toEqual([]);
});
it('can getTransactionPositionFromChannelId with topics existing', () => {
const txTopic = RequestDataAccessBlock.getTransactionPositionFromChannelId(
blockWith1tx,
arbitraryId1,
);
// 'txTopic is wrong'
expect(txTopic).toEqual([0]);
});
});
describe('getTransactionsByPositions', () => {
it('can getTransactionsByPositions on an empty block', () => {
const txs = RequestDataAccessBlock.getTransactionsByPositions(emptyblock, [0, 1]);
// 'txs must be empty'
expect(txs).toEqual([]);
});
it('can getTransactionsByPositions on missing transaction', () => {
const txs = RequestDataAccessBlock.getTransactionsByPositions(blockWith1tx, [0, 1]);
// 'txs is wrong'
expect(txs).toEqual([transactionMock]);
});
it('can getTransactionsByPositions on more than one transaction', () => {
const txs = RequestDataAccessBlock.getTransactionsByPositions(blockWith2tx, [0, 1]);
// 'txs is wrong'
expect(txs).toEqual([transactionMock, transactionMock2]);
});
it('can getTransactionsByPositions on more than one transaction with array not sorted', () => {
const txs = RequestDataAccessBlock.getTransactionsByPositions(blockWith2tx, [1, 0]);
// 'txs is wrong'
expect(txs).toEqual([transactionMock, transactionMock2]);
});
it('can getTransactionsByPositions on more than one transaction with array duplication', () => {
const txs = RequestDataAccessBlock.getTransactionsByPositions(
blockWith2tx,
[1, 1, 0, 1, 0, 0],
);
// 'txs is wrong'
expect(txs).toEqual([transactionMock, transactionMock2]);
});
});
describe('getTransactionPositionsByChannelIds', () => {
it('can getTransactionPositionsByChannelIds on an empty block', () => {
const txs = RequestDataAccessBlock.getTransactionPositionsByChannelIds(emptyblock, [
arbitraryId1,
arbitraryId2,
]);
// 'txs must be empty'
expect(txs).toEqual([]);
});
it('can getTransactionPositionsByChannelIds on missing transaction', () => {
const txs = RequestDataAccessBlock.getTransactionPositionsByChannelIds(blockWith1tx, [
arbitraryId1,
arbitraryId2,
]);
// 'txs is wrong'
expect(txs).toEqual([0]);
});
it('can getTransactionPositionsByChannelIds on more than one transaction', () => {
const txs = RequestDataAccessBlock.getTransactionPositionsByChannelIds(blockWith2tx, [
arbitraryId1,
arbitraryId2,
]);
// 'txs is wrong'
expect(txs).toEqual([0, 1]);
});
it('can getTransactionPositionsByChannelIds on more than one transaction with array not sorted', () => {
const txs = RequestDataAccessBlock.getTransactionPositionsByChannelIds(blockWith2tx, [
arbitraryId2,
arbitraryId1,
]);
// 'txs is wrong'
expect(txs).toEqual([0, 1]);
});
it('can getTransactionPositionsByChannelIds on more than one transaction with array duplication', () => {
const txs = RequestDataAccessBlock.getTransactionPositionsByChannelIds(blockWith2tx, [
arbitraryId2,
arbitraryId1,
arbitraryId2,
arbitraryId2,
arbitraryId1,
arbitraryId1,
arbitraryId1,
]);
// 'txs is wrong'
expect(txs).toEqual([0, 1]);
});
});
describe('parseBlock', () => {
it('can parse a data', async () => {
const block = RequestDataAccessBlock.parseBlock(JSON.stringify(blockWith2tx));
expect(block).toEqual(blockWith2tx);
});
it('cannot parse a data not following the block standard', async () => {
const blockNotJson = 'This is not JSON';
expect(() => RequestDataAccessBlock.parseBlock(blockNotJson)).toThrowError(
`Impossible to JSON parse the data: `,
);
const blockWithoutHeader = {
transactions: [{ data: 'any data' }],
};
expect(() =>
RequestDataAccessBlock.parseBlock(JSON.stringify(blockWithoutHeader)),
).toThrowError(`Data do not follow the block standard`);
const blockWithoutChannelIds = {
header: { topics: {}, version: '0.1.0' },
transactions: [{ data: 'any data' }],
};
expect(() =>
RequestDataAccessBlock.parseBlock(JSON.stringify(blockWithoutChannelIds)),
).toThrowError(`Header do not follow the block standard`);
const blockWithoutTopics = {
header: { channelIds: {}, version: '0.1.0' },
transactions: [{ data: 'any data' }],
};
expect(() =>
RequestDataAccessBlock.parseBlock(JSON.stringify(blockWithoutTopics)),
).toThrowError(`Header do not follow the block standard`);
const blockWithoutVersion = {
header: { channelIds: {}, topics: {} },
transactions: [{ data: 'any data' }],
};
expect(() =>
RequestDataAccessBlock.parseBlock(JSON.stringify(blockWithoutVersion)),
).toThrowError(`Header do not follow the block standard`);
const blockWithoutTransactions = {
header: { channelIds: {}, topics: {}, version: '0.1.0' },
};
expect(() =>
RequestDataAccessBlock.parseBlock(JSON.stringify(blockWithoutTransactions)),
).toThrowError(`Data do not follow the block standard`);
const blockWithoutTransactionData = {
header: { channelIds: {}, topics: {}, version: '0.1.0' },
transactions: [{}],
};
expect(() =>
RequestDataAccessBlock.parseBlock(JSON.stringify(blockWithoutTransactionData)),
).toThrowError(`Transactions do not follow the block standard`);
const blockWrongVersion = {
header: { channelIds: {}, topics: {}, version: '0.0.0' },
transactions: [{ data: 'any data' }],
};
expect(() =>
RequestDataAccessBlock.parseBlock(JSON.stringify(blockWrongVersion)),
).toThrowError(`Version not supported`);
const blockWithChannelIdNotHash = {
header: { channelIds: { ['0x111']: [0] }, topics: {}, version: '0.1.0' },
transactions: [{ data: 'any data' }],
};
expect(() =>
RequestDataAccessBlock.parseBlock(JSON.stringify(blockWithChannelIdNotHash)),
).toThrowError(`Channel ids in header.channelIds must be formatted keccak256 hashes`);
const blockWithTxPositionNotExisting = {
header: { channelIds: { [arbitraryId1]: [1] }, topics: {}, version: '0.1.0' },
transactions: [{ data: 'any data' }],
};
expect(() =>
RequestDataAccessBlock.parseBlock(JSON.stringify(blockWithTxPositionNotExisting)),
).toThrowError(`transactions in channel ids must refer to transaction in the blocks`);
const blockWithNegativePosition = {
header: { channelIds: { [arbitraryId1]: [-1] }, topics: {}, version: '0.1.0' },
transactions: [{ data: 'any data' }],
};
expect(() =>
RequestDataAccessBlock.parseBlock(JSON.stringify(blockWithNegativePosition)),
).toThrowError(`transactions in channel ids must refer to transaction in the blocks`);
const blockWithChannelIdInTopicsNotHash = {
header: { channelIds: {}, topics: { ['Ox111']: [arbitraryTopic1] }, version: '0.1.0' },
transactions: [{ data: 'any data' }],
};
expect(() =>
RequestDataAccessBlock.parseBlock(JSON.stringify(blockWithChannelIdInTopicsNotHash)),
).toThrowError(`Channel ids in header.topics must be formatted keccak256 hashes`);
const blockWithTopicsNotHash = {
header: { channelIds: {}, topics: { [arbitraryId1]: ['0x111'] }, version: '0.1.0' },
transactions: [{ data: 'any data' }],
};
expect(() =>
RequestDataAccessBlock.parseBlock(JSON.stringify(blockWithTopicsNotHash)),
).toThrowError(`topics in header.topics must be formatted keccak256 hashes`);
});
});
describe('can use JSON', () => {
it('can use JSON.stringify and JSON.parse', () => {
const block = RequestDataAccessBlock.pushTransaction(
blockWith1tx,
transactionMock2,
arbitraryId2,
[arbitraryTopic2],
);
/* eslint-disable */
/* eslint-disable quote-props */
const strExpected = JSON.stringify({
header: {
channelIds: {
[arbitraryId1]: [0],
[arbitraryId2]: [1],
},
topics: {
[arbitraryId1]: [arbitraryTopic1, arbitraryTopic2],
[arbitraryId2]: [arbitraryTopic2],
},
version: '0.1.0',
},
transactions: [
{
data: '{"attribut1":"plop","attribut2":"value"}',
},
{
data: '{"attribut1":"foo","attribut2":"bar"}',
},
],
});
// 'Error stringify-ing a block'
expect(JSON.stringify(block)).toBe(strExpected);
// 'Error parsing a block'
expect(JSON.parse(strExpected)).toEqual(block);
});
});
}); | the_stack |
import * as os from 'os';
import * as path from 'path';
import {
ACTIVE_BUILD_TOOL_STATE,
ClientStatus,
JDKInfo,
ServerMode,
getJavaFilePathOfTextDocument,
getJavaSDKInfo,
getJavaServerLaunchMode,
hasNoBuildToolConflicts,
isPrefix,
makeRandomHexString,
} from './stripeJavaLanguageClient/utils';
import {
CloseAction,
Emitter,
ErrorAction,
LanguageClient,
LanguageClientOptions,
ServerOptions,
Trace,
} from 'vscode-languageclient';
import {
ExtensionContext,
OutputChannel,
RelativePattern,
Uri,
commands,
window,
workspace,
} from 'vscode';
import {OSType, getOSType} from './utils';
import {Commands} from './stripeJavaLanguageClient/commands';
import {StandardLanguageClient} from './stripeJavaLanguageClient/standardLanguageClient';
import {SyntaxLanguageClient} from './stripeJavaLanguageClient/syntaxLanguageClient';
import {Telemetry} from './telemetry';
import {prepareExecutable} from './stripeJavaLanguageClient/javaServerStarter';
import {registerHoverProvider} from './stripeJavaLanguageClient/hoverProvider';
const REQUIRED_DOTNET_RUNTIME_VERSION = '5.0';
const REQUIRED_JDK_VERSION = 11;
const syntaxClient: SyntaxLanguageClient = new SyntaxLanguageClient();
const standardClient: StandardLanguageClient = new StandardLanguageClient();
const onDidServerModeChangeEmitter: Emitter<ServerMode> = new Emitter<ServerMode>();
export let javaServerMode: ServerMode;
export class StripeLanguageClient {
static async activate(
context: ExtensionContext,
serverOptions: ServerOptions,
telemetry: Telemetry,
) {
const outputChannel = window.createOutputChannel('Stripe Language Client');
// start the csharp server if this is a dotnet project
const dotnetProjectFile = await this.getDotnetProjectFiles();
if (dotnetProjectFile.length > 0) {
this.activateDotNetServer(context, outputChannel, dotnetProjectFile[0], telemetry);
return;
}
// start the java server if this is a java project
const javaFiles = await this.getJavaProjectFiles();
if (javaFiles.length > 0) {
const jdkInfo = await getJavaSDKInfo(context, outputChannel);
if (jdkInfo.javaVersion < REQUIRED_JDK_VERSION) {
outputChannel.appendLine(
`Minimum JDK version required is ${REQUIRED_JDK_VERSION}. Please update the java.home setup in VSCode user settings.`,
);
telemetry.sendEvent('doesNotMeetRequiredJdkVersion');
return;
}
this.activateJavaServer(context, jdkInfo, outputChannel, javaFiles, telemetry);
return;
}
// start the universal server for all other languages
this.activateUniversalServer(context, outputChannel, serverOptions, telemetry);
}
static activateUniversalServer(
context: ExtensionContext,
outputChannel: OutputChannel,
serverOptions: ServerOptions,
telemetry: Telemetry,
) {
outputChannel.appendLine('Starting universal language server');
const universalClientOptions: LanguageClientOptions = {
// Register the server for stripe-supported languages. dotnet is not yet supported.
documentSelector: [
{scheme: 'file', language: 'javascript'},
{scheme: 'file', language: 'typescript'},
{scheme: 'file', language: 'go'},
// {scheme: 'file', language: 'java'},
{scheme: 'file', language: 'php'},
{scheme: 'file', language: 'python'},
{scheme: 'file', language: 'ruby'},
],
synchronize: {
fileEvents: workspace.createFileSystemWatcher('**/.clientrc'),
},
};
const universalClient = new LanguageClient(
'stripeLanguageServer',
'Stripe Language Server',
serverOptions,
universalClientOptions,
);
universalClient.onTelemetry((data: any) => {
const eventData = data.data || null;
telemetry.sendEvent(data.name, eventData);
});
universalClient.start();
outputChannel.appendLine('Universal language server is running');
telemetry.sendEvent('universalLanguageServerStarted');
}
static async activateDotNetServer(
context: ExtensionContext,
outputChannel: OutputChannel,
projectFile: string,
telemetry: Telemetry,
) {
outputChannel.appendLine('Detected C# Project file: ' + projectFile);
// Applie Silicon is not supported for dotnet < 6.0:
// https://github.com/dotnet/core/issues/4879#issuecomment-729046912
if (getOSType() === OSType.macOSarm) {
outputChannel.appendLine(
`.NET runtime v${REQUIRED_DOTNET_RUNTIME_VERSION} is not supported for M1`,
);
telemetry.sendEvent('dotnetRuntimeAcquisitionSkippedForM1');
return;
}
const result = await commands.executeCommand<{dotnetPath: string}>('dotnet.acquire', {
version: REQUIRED_DOTNET_RUNTIME_VERSION,
requestingExtensionId: 'stripe.vscode-stripe',
});
if (!result) {
outputChannel.appendLine(
`Failed to install .NET runtime v${REQUIRED_DOTNET_RUNTIME_VERSION}. Unable to start language server`,
);
telemetry.sendEvent('dotnetRuntimeAcquisitionFailed');
return;
}
const dotNetExecutable = path.resolve(result.dotnetPath);
outputChannel.appendLine('dotnet runtime acquired: ' + dotNetExecutable);
const serverAssembly = context.asAbsolutePath(
'dist/stripeDotnetLanguageServer/stripe.LanguageServer.dll',
);
const serverOptions: ServerOptions = {
command: dotNetExecutable,
args: [serverAssembly, projectFile],
};
// Options to control the language client
const clientOptions: LanguageClientOptions = {
// Register the server for plain text documents
documentSelector: [{scheme: 'file', language: 'csharp'}],
synchronize: {
configurationSection: 'stripeCsharpLangaugeServer',
fileEvents: workspace.createFileSystemWatcher('**/*.cs'),
},
diagnosticCollectionName: 'Stripe C# language server',
errorHandler: {
error: (error, message, count) => {
console.log(message);
console.log(error);
return ErrorAction.Continue;
},
closed: () => CloseAction.DoNotRestart,
},
};
// Create the language client and start the client.
const dotnetClient = new LanguageClient(
'stripeCsharpLanguageServer',
'Stripe C# Server',
serverOptions,
clientOptions,
);
dotnetClient.trace = Trace.Verbose;
outputChannel.appendLine('Starting C# language service for ' + projectFile);
const disposable = dotnetClient.start();
// Push the disposable to the context's subscriptions so that the
// client can be deactivated on extension deactivation
context.subscriptions.push(disposable);
await dotnetClient.onReady();
outputChannel.appendLine('C# language service is running.');
telemetry.sendEvent('dotnetServerStarted');
}
static async activateJavaServer(
context: ExtensionContext,
jdkInfo: JDKInfo,
outputChannel: OutputChannel,
projectFiles: string[],
telemetry: Telemetry,
) {
outputChannel.appendLine('Detected Java Project file: ' + projectFiles[0]);
let storagePath = context.storagePath;
if (!storagePath) {
storagePath = path.resolve(os.tmpdir(), 'vscodesws_' + makeRandomHexString(5));
}
const workspacePath = path.resolve(storagePath + '/jdt_ws');
const syntaxServerWorkspacePath = path.resolve(storagePath + '/ss_ws');
javaServerMode = getJavaServerLaunchMode();
commands.executeCommand('setContext', 'java:serverMode', javaServerMode);
const requireSyntaxServer = javaServerMode !== ServerMode.STANDARD;
const requireStandardServer = javaServerMode !== ServerMode.LIGHTWEIGHT;
// Options to control the language client
const clientOptions: LanguageClientOptions = {
// Register the server for java
documentSelector: [{scheme: 'file', language: 'java'}],
synchronize: {
configurationSection: ['java', 'editor.insertSpaces', 'editor.tabSize'],
},
initializationOptions: {
extendedClientCapabilities: {
classFileContentsSupport: true,
clientHoverProvider: true,
clientDocumentSymbolProvider: true,
shouldLanguageServerExitOnShutdown: true,
},
projectFiles,
},
revealOutputChannelOn: 4, // never
errorHandler: {
error: (error, message, count) => {
console.log(message);
console.log(error);
return ErrorAction.Continue;
},
closed: () => CloseAction.DoNotRestart,
},
};
if (requireSyntaxServer) {
try {
await this.startSyntaxServer(
clientOptions,
prepareExecutable(jdkInfo, syntaxServerWorkspacePath, context, true, outputChannel, telemetry),
outputChannel,
telemetry,
);
} catch (e) {
outputChannel.appendLine(`${e}`);
telemetry.sendEvent('syntaxJavaServerFailedToStart');
}
}
// handle server mode changes from syntax to standard
this.registerSwitchJavaServerModeCommand(
context,
jdkInfo,
clientOptions,
workspacePath,
outputChannel,
telemetry
);
onDidServerModeChangeEmitter.event((event: ServerMode) => {
if (event === ServerMode.STANDARD) {
syntaxClient.stop();
}
commands.executeCommand('setContext', 'java:serverMode', event);
});
// register hover provider
registerHoverProvider(context);
if (requireStandardServer) {
try {
await this.startStandardServer(
context,
clientOptions,
prepareExecutable(jdkInfo, workspacePath, context, false, outputChannel, telemetry),
outputChannel,
telemetry,
);
} catch (e) {
outputChannel.appendLine(`${e}`);
telemetry.sendEvent('standardJavaServerFailedToStart');
}
}
}
/**
* Returns a solutions file or project file if it exists in the workspace.
*
* If the user is working with multiple workspaces that contain C# projects, we don't know which one to run the server on, so we'll return the first one we find.
* In the future, we may want to prompt the user to pick one, or expose a command that let's the user change the tracking project and restart.
*
* Returns [] if none of the workspaces are .NET projects.
*/
static async getDotnetProjectFiles(): Promise<string[]> {
const workspaceFolders = workspace.workspaceFolders;
if (!workspaceFolders) {
return [];
}
const projectFiles = await Promise.all(
workspaceFolders.map(async (w) => {
const workspacePath = w.uri.fsPath;
// First look for solutions files. We only expect one solutions file to be present in a workspace.
const pattern = new RelativePattern(workspacePath, '**/*.sln');
// Files and folders to exclude
// There may be more we want to exclude but starting with the same set omnisharp uses:
// https://github.com/OmniSharp/omnisharp-vscode/blob/master/src/omnisharp/launcher.ts#L66
const exclude = '{**/node_modules/**,**/.git/**,**/bower_components/**}';
const sln = await workspace.findFiles(pattern, exclude, 1);
if (sln && sln.length === 1) {
return sln[0].fsPath;
} else {
// If there was no solutions file, look for a csproj file.
const pattern = new RelativePattern(workspacePath, '**/*.csproj');
const csproj = await workspace.findFiles(pattern, exclude, 1);
if (csproj && csproj.length === 1) {
return csproj[0].fsPath;
}
}
}),
);
return projectFiles.filter((file): file is string => Boolean(file));
}
static async getJavaProjectFiles() {
const openedJavaFiles = [];
if (!window.activeTextEditor) {
return [];
}
const activeJavaFile = getJavaFilePathOfTextDocument(window.activeTextEditor.document);
if (activeJavaFile) {
openedJavaFiles.push(Uri.file(activeJavaFile).toString());
}
if (!workspace.workspaceFolders) {
return openedJavaFiles;
}
await Promise.all(
workspace.workspaceFolders.map(async (rootFolder) => {
if (rootFolder.uri.scheme !== 'file') {
return;
}
const rootPath = path.normalize(rootFolder.uri.fsPath);
if (activeJavaFile && isPrefix(rootPath, activeJavaFile)) {
return;
}
for (const textEditor of window.visibleTextEditors) {
const javaFileInTextEditor = getJavaFilePathOfTextDocument(textEditor.document);
if (javaFileInTextEditor && isPrefix(rootPath, javaFileInTextEditor)) {
openedJavaFiles.push(Uri.file(javaFileInTextEditor).toString());
return;
}
}
for (const textDocument of workspace.textDocuments) {
const javaFileInTextDocument = getJavaFilePathOfTextDocument(textDocument);
if (javaFileInTextDocument && isPrefix(rootPath, javaFileInTextDocument)) {
openedJavaFiles.push(Uri.file(javaFileInTextDocument).toString());
return;
}
}
const javaFilesUnderRoot: Uri[] = await workspace.findFiles(
new RelativePattern(rootFolder, '*.java'),
undefined,
1,
);
for (const javaFile of javaFilesUnderRoot) {
if (isPrefix(rootPath, javaFile.fsPath)) {
openedJavaFiles.push(javaFile.toString());
return;
}
}
const javaFilesInCommonPlaces: Uri[] = await workspace.findFiles(
new RelativePattern(rootFolder, '{src, test}/**/*.java'),
undefined,
1,
);
for (const javaFile of javaFilesInCommonPlaces) {
if (isPrefix(rootPath, javaFile.fsPath)) {
openedJavaFiles.push(javaFile.toString());
return;
}
}
}),
);
return openedJavaFiles;
}
static async startSyntaxServer(
clientOptions: LanguageClientOptions,
serverOptions: ServerOptions,
outputChannel: OutputChannel,
telemetry: Telemetry,
) {
await syntaxClient.initialize(clientOptions, serverOptions);
syntaxClient.start();
outputChannel.appendLine('Java language service (syntax) is running.');
telemetry.sendEvent('syntaxJavaServerStarted');
}
static async startStandardServer(
context: ExtensionContext,
clientOptions: LanguageClientOptions,
serverOptions: ServerOptions,
outputChannel: OutputChannel,
telemetry: Telemetry,
) {
if (standardClient.getClientStatus() !== ClientStatus.Uninitialized) {
return;
}
const checkConflicts: boolean = await hasNoBuildToolConflicts(context);
if (!checkConflicts) {
outputChannel.appendLine(`Build tool conflict detected in workspace. Please set '${ACTIVE_BUILD_TOOL_STATE}' to either maven or gradle.`);
telemetry.sendEvent('standardJavaServerHasBuildToolConflict');
return;
}
if (javaServerMode === ServerMode.LIGHTWEIGHT) {
// Before standard server is ready, we are in hybrid.
javaServerMode = ServerMode.HYBRID;
}
await standardClient.initialize(clientOptions, serverOptions);
standardClient.start();
outputChannel.appendLine('Java language service (standard) is running.');
telemetry.sendEvent('standardJavaServerStarted');
}
static async registerSwitchJavaServerModeCommand(
context: ExtensionContext,
jdkInfo: JDKInfo,
clientOptions: LanguageClientOptions,
workspacePath: string,
outputChannel: OutputChannel,
telemetry: Telemetry,
) {
if ((await commands.getCommands()).includes(Commands.SWITCH_SERVER_MODE)) {
return;
}
/**
* Command to switch the server mode. Currently it only supports switch from lightweight to standard.
* @param force force to switch server mode without asking
*/
commands.registerCommand(
Commands.SWITCH_SERVER_MODE,
async (switchTo: ServerMode, force: boolean = false) => {
const isWorkspaceTrusted = (workspace as any).isTrusted;
if (isWorkspaceTrusted !== undefined && !isWorkspaceTrusted) {
// keep compatibility for old engines < 1.56.0
const button = 'Manage Workspace Trust';
const choice = await window.showInformationMessage(
'For security concern, Java language server cannot be switched to Standard mode in untrusted workspaces.',
button,
);
if (choice === button) {
commands.executeCommand('workbench.action.manageTrust');
}
return;
}
const clientStatus: ClientStatus = standardClient.getClientStatus();
if (clientStatus === ClientStatus.Starting || clientStatus === ClientStatus.Started) {
return;
}
if (javaServerMode === switchTo || javaServerMode === ServerMode.STANDARD) {
return;
}
let choice: string;
if (force) {
choice = 'Yes';
} else {
choice = await window.showInformationMessage(
'Are you sure you want to switch the Java language server to Standard mode?',
'Yes',
'No',
) || 'No';
}
if (choice === 'Yes') {
telemetry.sendEvent('switchToStandardMode');
try {
this.startStandardServer(
context,
clientOptions,
prepareExecutable(jdkInfo, workspacePath, context, false, outputChannel, telemetry),
outputChannel,
telemetry,
);
} catch (e) {
outputChannel.appendLine(`${e}`);
telemetry.sendEvent('failedToSwitchToStandardMode');
}
}
},
);
}
}
export async function getActiveJavaLanguageClient(): Promise<LanguageClient | undefined> {
let languageClient: LanguageClient | undefined;
if (javaServerMode === ServerMode.STANDARD) {
languageClient = standardClient.getClient();
} else {
languageClient = syntaxClient.getClient();
}
if (!languageClient) {
return undefined;
}
await languageClient.onReady();
return languageClient;
}
export function updateServerMode(serverMode: ServerMode) {
javaServerMode = serverMode;
console.log('server mode changed to ' + serverMode);
} | the_stack |
import {AbstractComponent} from '@common/component/abstract.component';
import {Component, ElementRef, Injector, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {isNullOrUndefined, isUndefined} from 'util';
import {MetadataService} from './service/metadata.service';
import {Metadata, SourceType} from '@domain/meta-data-management/metadata';
import {DeleteModalComponent} from '@common/component/modal/delete/delete.component';
import {Modal} from '@common/domain/modal';
import {Alert} from '@common/util/alert.util';
import {CatalogService} from '../catalog/service/catalog.service';
import * as _ from 'lodash';
import {StorageService} from '../../data-storage/service/storage.service';
import {ActivatedRoute} from '@angular/router';
import {CreateMetadataMainComponent} from './create-metadata/create-metadata-main.component';
import {Subscription} from 'rxjs';
import {StringUtil} from '@common/util/string.util';
@Component({
selector: 'app-metadata',
styleUrls: ['./metadata.component.css'],
templateUrl: './metadata.component.html'
})
export class MetadataComponent extends AbstractComponent implements OnInit, OnDestroy {
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
@ViewChild(CreateMetadataMainComponent)
private _selectDatatypeComponent: CreateMetadataMainComponent;
// 검색 파라메터
private _searchParams: { [key: string]: string };
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
@ViewChild(DeleteModalComponent)
public deleteModalComponent: DeleteModalComponent;
// 리스트, 카달로그 검색어
public listSearchText: string;
public selectedMetadata: SelectedMetadata;
public metadatas: Metadata[];
public sourceTypeList: any = [];
public sourceType: string;
public tagsList: any = [];
public tag: string;
public selectedCatalogId: string;
public catalogs: any;
// Unclassified 선택 여부
public isUnclassifiedSelected: boolean = false;
public tagDefaultIndex: number;
public typeDefaultIndex: number;
/**
* Metadata SourceType Enum
*/
public readonly METADATA_SOURCE_TYPE = SourceType;
// sort
readonly sortList = [
{name: this.translateService.instant('msg.comm.ui.sort.name.asc'), value: 'name,asc'},
{name: this.translateService.instant('msg.comm.ui.sort.name.desc'), value: 'name,desc'},
{name: this.translateService.instant('msg.comm.ui.sort.updated.asc'), value: 'modifiedTime,asc'},
{name: this.translateService.instant('msg.comm.ui.sort.updated.desc'), value: 'modifiedTime,desc'},
];
selectedSort;
private _paginationSubscription$: Subscription;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Constructor
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// 생성자
constructor(
protected element: ElementRef,
protected injector: Injector,
protected metadataService: MetadataService,
protected catalogService: CatalogService,
private _activatedRoute: ActivatedRoute) {
super(element, injector);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Override Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// Init
public ngOnInit() {
this._initView();
// Get query param from url
this._paginationSubscription$ = this._activatedRoute.queryParams.subscribe((params) => {
if (!_.isEmpty(params)) {
if (!isNullOrUndefined(params['size'])) {
this.page.size = params['size'];
}
if (!isNullOrUndefined(params['page'])) {
this.page.page = params['page'];
}
if (!isNullOrUndefined(params['nameContains'])) {
this.listSearchText = params['nameContains'];
}
if (!isNullOrUndefined(params['sourceType'])) {
this.sourceType = params['sourceType'];
this.typeDefaultIndex = this.sourceTypeList.findIndex((item) => {
return item.value.toString() === this.sourceType;
});
}
if (!_.isNil(params['sort'])) {
this.selectedSort = this.sortList.find(sort => sort.value === params['sort']);
}
}
// first fetch metadata tag list
this.getMetadataTags()
.then((result) => {
this.tagsList = this.tagsList.concat(result);
if (!isNullOrUndefined(params['tag'])) {
this.tag = params['tag'];
this.tagDefaultIndex = this.tagsList.findIndex((item) => {
return item.name === this.tag;
});
} else {
this.tagDefaultIndex = 0;
}
this.getMetadataList();
})
.catch(error => {
console.error(error);
this.getMetadataList();
})
});
}
public ngOnDestroy() {
if (!_.isNil(this._paginationSubscription$)) {
this._paginationSubscription$.unsubscribe();
}
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* After metadata creation
*/
// Todo : doesn't refresh
public onCreateEmit() {
this.reloadPage();
}
/**
* When data type list is changed
* @param event
*/
public onSourceTypeListChange(event) {
this.sourceType = event.value;
this.reloadPage();
}
/**
* When tags list is changed
* @param event
*/
public onTagsListChange(event) {
'All' === event.name ? this.tag = '' : this.tag = event.name;
this.reloadPage();
}
/**
* Refresh filter
*/
public refreshFilter() {
this._initView();
this.reloadPage();
}
/**
* Open create meta data popup
*/
public createNewMetadata() {
this._selectDatatypeComponent.init();
}
getMetadataCreator(creator: string) {
if (this.isNotEmptySearchKeyword()) {
return creator.replace(this.listSearchText, `<span class="ddp-txt-search type-search">${this.listSearchText}</span>`);
} else {
return creator;
}
}
getMetadataDescription(description: string) {
if (this.isNotEmptySearchKeyword()) {
return '-' + description.replace(this.listSearchText, `<span class="ddp-txt-search type-search">${this.listSearchText}</span>`);
} else {
return '-' + description;
}
}
getMetadataName(name: string) {
if (this.isNotEmptySearchKeyword()) {
return name.replace(this.listSearchText, `<span class="ddp-txt-search type-search">${this.listSearchText}</span>`);
} else {
return name;
}
}
getMetadataType(metadata: Metadata): string {
switch (metadata.sourceType) {
case SourceType.ENGINE:
return this.translateService.instant('msg.comm.th.ds');
case SourceType.JDBC:
return this.translateService.instant('msg.storage.li.db');
case SourceType.STAGEDB:
return this.translateService.instant('msg.storage.li.hive');
case SourceType.ETC:
return this.translateService.instant('msg.storage.li.etc');
}
}
getMetadataTypeIcon(metadata: Metadata): string {
switch (metadata.sourceType) {
case SourceType.ENGINE:
return 'ddp-datasource';
case SourceType.JDBC:
return 'ddp-hive';
case SourceType.STAGEDB:
return 'ddp-stagingdb';
case SourceType.ETC:
return 'ddp-etc';
}
}
/**
* 컨텐츠 총 갯수
* @returns {number}
*/
public get getTotalContentsCount(): number {
return this.pageResult.totalElements;
}
/**
* 메타 데이터 리스트 조회
*/
public getMetadataList() {
this.loadingShow();
this.metadatas = [];
const params = this._getMetadataParams();
this.metadataService.getMetaDataList(params).then((result) => {
this._searchParams = params;
this.pageResult = result.page;
// 코드 테이블 리스트
this.metadatas = result['_embedded'] ? this.metadatas.concat(result['_embedded'].metadatas) : [];
// 로딩 hide
this.loadingHide();
}).catch((error) => {
this.commonExceptionHandler(error);
this.loadingHide();
});
}
/**
* 카달로그 리스트 조회 (처음 한번)
* 트리구조로 카달로그 목록을 불러온다.
*/
public getCatalogList() {
this.loadingShow();
this.catalogService.getTreeCatalogs('ROOT').then((result) => {
this.loadingHide();
if (result.length > 0) {
this.catalogs = result;
// if catalog exists, the first catalog on the list is selected and gets metadata in that catalog
this.selectedCatalogId = this.catalogs[0].id;
this.catalogs[0].selected = true;
this.getMetadataInCatalog();
} else {
// if no catalog exists, get unclassified metadata list
this.catalogs = [];
this.isUnclassifiedSelected = true;
this.selectedCatalogId = '__EMPTY';
this.getMetadataList();
}
}).catch((_error) => {
this.loadingHide();
});
}
isEnableTag(metadata: Metadata): boolean {
return !Metadata.isEmptyTags(metadata);
}
isExistMoreTags(metadata: Metadata): boolean {
return metadata.tags.length > 1;
}
isEnableDescription(metadata: Metadata): boolean {
return StringUtil.isNotEmpty(metadata.description);
}
isNotEmptySearchKeyword(): boolean {
return StringUtil.isNotEmpty(this.listSearchText);
}
/**
* 하위 데이터 불러오기
* @param catalog
*/
public showChildren(catalog) {
this.loadingShow();
this.catalogService.getTreeCatalogs(catalog.id).then((result) => {
this.loadingHide();
catalog.children = result;
}).catch((_error) => {
this.loadingHide();
});
}
/**
* 메타데이터 디테일 페이지로 점프
* @param metadata
*/
public onClickMetadataDetail(metadata) {
this.metadataService.metadataDetailSelectedTab = 'information';
this.router.navigate(['management/metadata/metadata', metadata.id]);
}
/**
* 삭제 팝업 오픈
* @param event
* @param metadata
*/
public confirmDelete(event, metadata) {
event.stopImmediatePropagation();
const modal = new Modal();
modal.name = this.translateService.instant('msg.metadata.md.ui.delete.header');
modal.description = metadata.name;
this.selectedMetadata = {id: metadata.id, name: metadata.name};
this.deleteModalComponent.init(modal);
}
/**
* 삭제 확인
*/
public deleteMetadata() {
this.metadataService.deleteMetaData(this.selectedMetadata.id).then((_result) => {
Alert.success(
this.translateService.instant('msg.metadata.alert.md-deleted', {value: this.selectedMetadata.name}));
if (this.page.page > 0 && this.metadatas.length === 1) {
this.page.page = this.page.page - 1;
}
this.reloadPage(false);
}).catch((_error) => {
Alert.fail(this.translateService.instant('msg.metadata.alert.md-delete.fail'));
});
// 다시 페이지 로드
}
/**
* 카달로그 내 메타데이터 불러오기
* @param catalog
*/
public setSelectedCatalog(catalog) {
this.isUnclassifiedSelected = false;
this._refreshSelectedCatalog();
// this.refreshFilter();
catalog.selected = true;
this.selectedCatalogId = catalog.id;
this.getMetadataInCatalog();
}
/**
* 선택된 카달로그에 포함된 메타데이터 불러오기
*/
public getMetadataInCatalog() {
this.loadingShow();
this.metadatas = [];
const params = this._getMetadataParams();
this.catalogService.getMetadataInCatalog(this.selectedCatalogId, params).then((result) => {
this._searchParams = params;
// page 객체
this.pageResult = result.page;
// 컬럼 사전 리스트
this.metadatas = result['_embedded'] ? this.metadatas.concat(result['_embedded']['metadatas']) : [];
// 로딩 hide
this.loadingHide();
}).catch((error) => {
this.commonExceptionHandler(error);
// 로딩 hide
this.loadingHide();
});
}
/**
* 코드 테이블 이름 검색
*/
public onSearchText(): void {
this._searchText(this.listSearchText);
}
/**
* 코드 테이블 이름 초기화 후 검색
*/
public onSearchTextInit(): void {
this._searchText('');
}
public getMetadataTags(): Promise<any> {
return new Promise((resolve, reject) => {
this.metadataService.getMetadataTags()
.then(resolve)
.catch(reject);
})
}
/**
* Get Name and description of metada
* @param metadata
* @returns {string}
*/
public getTooltipValue(metadata): string {
let result = metadata.name;
if (metadata.description) {
result += ` - ${metadata.description}`;
}
return result;
}
/**
* 페이지 변경
* @param data
*/
public changePage(data: { page: number, size: number }) {
if (data) {
this.page.page = data.page;
this.page.size = data.size;
// 워크스페이스 조회
this.reloadPage(false);
}
} // function - changePage
/**
* 페이지를 새로 불러온다.
* @param {boolean} isFirstPage
*/
public reloadPage(isFirstPage: boolean = true) {
(isFirstPage) && (this.page.page = 0);
this._searchParams = this._getMetadataParams();
this.router.navigate(
[this.router.url.replace(/\?.*/gi, '')],
{queryParams: this._searchParams, replaceUrl: true}
).then();
} // function - reloadPage
createdMetadata(metadataId?: string) {
if (_.isNil(metadataId)) {
this.reloadPage(true);
} else { // if exist metadataId, go to detail page
this.router.navigate(['management/metadata/metadata', metadataId]).then();
}
}
changeSort(sort) {
this.selectedSort = sort;
this.reloadPage();
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* ui init
* @private
*/
private _initView() {
this.sourceTypeList = StorageService.isEnableStageDB
? [
{label: 'All', value: ''},
{label: this.translateService.instant('msg.comm.th.ds'), value: SourceType.ENGINE},
{label: this.translateService.instant('msg.storage.li.db'), value: SourceType.JDBC},
{label: this.translateService.instant('msg.storage.li.hive'), value: SourceType.STAGING},
{label: this.translateService.instant('msg.storage.li.etc'), value: SourceType.ETC},
]
: [
{label: 'All', value: ''},
{label: this.translateService.instant('msg.comm.th.ds'), value: SourceType.ENGINE},
{label: this.translateService.instant('msg.storage.li.db'), value: SourceType.JDBC},
{label: this.translateService.instant('msg.storage.li.etc'), value: SourceType.ETC},
];
this.sourceType = '';
this.listSearchText = '';
this.tagsList = [{name: 'All', id: ''}];
this.tagDefaultIndex = 0;
this.typeDefaultIndex = 0;
this.tag = '';
// 카달로그를 다시 불러오기
// if (getCatalogList !== false) {
// this.getCatalogList();
// }
// 정렬 초기화
this.selectedSort = this.sortList[3];
}
/**
* 선택된 카달로그 모두 해제
*/
private _refreshSelectedCatalog() {
this.catalogs.forEach((catalog) => {
catalog.selected = false;
if (catalog.children) {
catalog.children.forEach((child) => {
child.selected = false;
if (child.children) {
child.children.forEach((last) => {
last.selected = false;
});
}
});
}
});
}
/**
* 검색어로 카달로그 이름 검색
* @param {string} keyword
* @private
*/
private _searchText(keyword: string): void {
// key word
this.listSearchText = keyword;
this.reloadPage();
}
/**
* get params for meta data list
* @returns object
* @private
*/
private _getMetadataParams(): any {
const params = {
page: this.page.page,
size: this.page.size,
sort: this.selectedSort.value,
pseudoParam: (new Date()).getTime()
};
// 검색어
if (!isUndefined(this.listSearchText) && this.listSearchText.trim() !== '') {
params['nameContains'] = this.listSearchText.trim();
}
// 데이터타입
if (!isUndefined(this.sourceType) && this.sourceType.trim() !== '') {
params['sourceType'] = this.sourceType.trim();
}
// 태그
if (!isUndefined(this.tag) && this.tag.trim() !== '') {
params['tag'] = this.tag.trim();
}
return params;
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Method - getter
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
}
class SelectedMetadata {
id: string;
name: string;
} | the_stack |
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { SearchFilterChipsComponent } from './search-filter-chips.component';
import { SearchFacetFiltersService } from '../../services/search-facet-filters.service';
import { SearchQueryBuilderService } from '../../services/search-query-builder.service';
import { ContentTestingModule } from '../../../testing/content.testing.module';
import { By } from '@angular/platform-browser';
import { SearchFacetFieldComponent } from '../search-facet-field/search-facet-field.component';
import { TranslateModule } from '@ngx-translate/core';
import { SearchFilterList } from '../../models/search-filter-list.model';
import {
disabledCategories,
filteredResult,
mockSearchResult,
searchFilter,
simpleCategories,
stepOne,
stepThree,
stepTwo
} from '../../../mock';
import { getAllMenus } from '../search-filter/search-filter.component.spec';
import { AppConfigService } from '@alfresco/adf-core';
describe('SearchFilterChipsComponent', () => {
let fixture: ComponentFixture<SearchFilterChipsComponent>;
let searchFacetFiltersService: SearchFacetFiltersService;
let queryBuilder: SearchQueryBuilderService;
let appConfigService: AppConfigService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
]
});
queryBuilder = TestBed.inject(SearchQueryBuilderService);
appConfigService = TestBed.inject(AppConfigService);
searchFacetFiltersService = TestBed.inject(SearchFacetFiltersService);
fixture = TestBed.createComponent(SearchFilterChipsComponent);
});
it('should fetch facet fields from response payload and show the already checked items', () => {
spyOn(queryBuilder, 'execute').and.stub();
queryBuilder.config = {
categories: [],
facetFields: { fields: [
{ label: 'f1', field: 'f1' },
{ label: 'f2', field: 'f2' }
]},
facetQueries: {
queries: []
}
};
searchFacetFiltersService.responseFacets = [
{ type: 'field', label: 'f1', field: 'f1', buckets: new SearchFilterList([
{ label: 'b1', count: 10, filterQuery: 'filter', checked: true },
{ label: 'b2', count: 1, filterQuery: 'filter2' }]) },
{ type: 'field', label: 'f2', field: 'f2', buckets: new SearchFilterList()}
];
searchFacetFiltersService.queryBuilder.addUserFacetBucket({ label: 'f1', field: 'f1' }, searchFacetFiltersService.responseFacets[0].buckets.items[0]);
const serverResponseFields: any = [
{ type: 'field', label: 'f1', field: 'f1', buckets: [
{ label: 'b1', metrics: [{value: {count: 6}}], filterQuery: 'filter' },
{ label: 'b2', metrics: [{value: {count: 1}}], filterQuery: 'filter2' }] },
{ type: 'field', label: 'f2', field: 'f2', buckets: [] }
];
const data = {
list: {
context: {
facets: serverResponseFields
}
}
};
fixture.detectChanges();
const facetChip = fixture.debugElement.query(By.css('[data-automation-id="search-fact-chip-f1"] mat-chip'));
facetChip.triggerEventHandler('click', { stopPropagation: () => null });
fixture.detectChanges();
const facetField: SearchFacetFieldComponent = fixture.debugElement.query(By.css('adf-search-facet-field')).componentInstance;
facetField.selectFacetBucket({ field: 'f1', label: 'f1' }, searchFacetFiltersService.responseFacets[0].buckets.items[1]);
searchFacetFiltersService.onDataLoaded(data);
expect(searchFacetFiltersService.responseFacets.length).toEqual(2);
expect(searchFacetFiltersService.responseFacets[0].buckets.items[0].checked).toEqual(true, 'should show the already checked item');
});
it('should fetch facet fields from response payload and show the newly checked items', () => {
spyOn(queryBuilder, 'execute').and.stub();
queryBuilder.config = {
categories: [],
facetFields: { fields: [
{ label: 'f1', field: 'f1' },
{ label: 'f2', field: 'f2' }
]},
facetQueries: {
queries: []
}
};
searchFacetFiltersService.responseFacets = <any> [
{ type: 'field', label: 'f1', field: 'f1', buckets: new SearchFilterList([
{ label: 'b1', count: 10, filterQuery: 'filter', checked: true },
{ label: 'b2', count: 1, filterQuery: 'filter2' }]) },
{ type: 'field', label: 'f2', field: 'f2', buckets: new SearchFilterList()}
];
queryBuilder.addUserFacetBucket({ label: 'f1', field: 'f1' }, searchFacetFiltersService.responseFacets[0].buckets.items[0]);
const serverResponseFields: any = [
{ type: 'field', label: 'f1', field: 'f1', buckets: [
{ label: 'b1', metrics: [{value: {count: 6}}], filterQuery: 'filter' },
{ label: 'b2', metrics: [{value: {count: 1}}], filterQuery: 'filter2' }] },
{ type: 'field', label: 'f2', field: 'f2', buckets: [] }
];
const data = {
list: {
context: {
facets: serverResponseFields
}
}
};
fixture.detectChanges();
const facetChip = fixture.debugElement.query(By.css('[data-automation-id="search-fact-chip-f1"] mat-chip'));
facetChip.triggerEventHandler('click', { stopPropagation: () => null });
fixture.detectChanges();
const facetField: SearchFacetFieldComponent = fixture.debugElement.query(By.css('adf-search-facet-field')).componentInstance;
facetField.selectFacetBucket({ field: 'f1', label: 'f1' }, searchFacetFiltersService.responseFacets[0].buckets.items[1]);
searchFacetFiltersService.onDataLoaded(data);
expect(searchFacetFiltersService.responseFacets.length).toEqual(2);
expect(searchFacetFiltersService.responseFacets[0].buckets.items[1].checked).toEqual(true, 'should show the newly checked item');
});
it('should show buckets with 0 values when there are no facet fields on the response payload', () => {
spyOn(queryBuilder, 'execute').and.stub();
queryBuilder.config = {
categories: [],
facetFields: { fields: [
{ label: 'f1', field: 'f1' },
{ label: 'f2', field: 'f2' }
]},
facetQueries: {
queries: []
}
};
searchFacetFiltersService.responseFacets = <any> [
{ type: 'field', label: 'f1', field: 'f1', buckets: new SearchFilterList( [
{ label: 'b1', count: 10, filterQuery: 'filter', checked: true },
{ label: 'b2', count: 1, filterQuery: 'filter2' }]) },
{ type: 'field', label: 'f2', field: 'f2', buckets: new SearchFilterList() }
];
queryBuilder.addUserFacetBucket({ label: 'f1', field: 'f1' }, searchFacetFiltersService.responseFacets[0].buckets.items[0]);
const data = {
list: {
context: {}
}
};
fixture.detectChanges();
const facetChip = fixture.debugElement.query(By.css('[data-automation-id="search-fact-chip-f1"] mat-chip'));
facetChip.triggerEventHandler('click', { stopPropagation: () => null });
fixture.detectChanges();
const facetField: SearchFacetFieldComponent = fixture.debugElement.query(By.css('adf-search-facet-field')).componentInstance;
facetField.selectFacetBucket({ field: 'f1', label: 'f1' }, searchFacetFiltersService.responseFacets[0].buckets.items[1]);
searchFacetFiltersService.onDataLoaded(data);
expect(searchFacetFiltersService.responseFacets[0].buckets.items[0].count).toEqual(0);
expect(searchFacetFiltersService.responseFacets[0].buckets.items[1].count).toEqual(0);
});
it('should update query builder upon resetting selected queries', () => {
spyOn(queryBuilder, 'update').and.stub();
spyOn(queryBuilder, 'removeUserFacetBucket').and.callThrough();
const queryResponse = {
field: 'query-response',
label: 'query response',
buckets: new SearchFilterList([
{ label: 'q1', query: 'q1', checked: true, metrics: [{value: {count: 1}}] },
{ label: 'q2', query: 'q2', checked: false, metrics: [{value: {count: 1}}] },
{ label: 'q3', query: 'q3', checked: true, metrics: [{value: {count: 1}}] }])
} as any;
searchFacetFiltersService.responseFacets = [queryResponse];
fixture.detectChanges();
const facetChip = fixture.debugElement.query(By.css(`[data-automation-id="search-fact-chip-query-response"] mat-chip`));
facetChip.triggerEventHandler('click', { stopPropagation: () => null });
fixture.detectChanges();
const facetField: SearchFacetFieldComponent = fixture.debugElement.query(By.css('adf-search-facet-field')).componentInstance;
facetField.resetSelectedBuckets(queryResponse);
expect(queryBuilder.removeUserFacetBucket).toHaveBeenCalledTimes(3);
expect(queryBuilder.update).toHaveBeenCalled();
for (const entry of searchFacetFiltersService.responseFacets[0].buckets.items) {
expect(entry.checked).toEqual(false);
}
});
describe('widgets', () => {
it('should not show the disabled widget', async () => {
appConfigService.config.search = { categories: disabledCategories };
queryBuilder.resetToDefaults();
fixture.detectChanges();
await fixture.whenStable();
const chips = fixture.debugElement.queryAll(By.css('mat-chip'));
expect(chips.length).toBe(0);
});
it('should show the widgets only if configured', async () => {
appConfigService.config.search = { categories: simpleCategories };
queryBuilder.resetToDefaults();
fixture.detectChanges();
await fixture.whenStable();
const chips = fixture.debugElement.queryAll(By.css('mat-chip'));
expect(chips.length).toBe(2);
const titleElements = fixture.debugElement.queryAll(By.css('.adf-search-filter-placeholder'));
expect(titleElements.map(title => title.nativeElement.innerText.trim())).toEqual(['Name', 'Type']);
});
it('should be update the search query when name changed', async () => {
spyOn(queryBuilder, 'update').and.stub();
appConfigService.config.search = searchFilter;
queryBuilder.resetToDefaults();
fixture.detectChanges();
await fixture.whenStable();
let chips = fixture.debugElement.queryAll(By.css('mat-chip'));
expect(chips.length).toBe(6);
fixture.detectChanges();
const searchChip = fixture.debugElement.query(By.css(`[data-automation-id="search-filter-chip-Name"]`));
searchChip.triggerEventHandler('click', { stopPropagation: () => null });
fixture.detectChanges();
const inputElement = fixture.debugElement.query(By.css('[data-automation-id="search-field-Name"] input'));
inputElement.triggerEventHandler('change', { target: { value: '*' } });
expect(queryBuilder.update).toHaveBeenCalled();
queryBuilder.executed.next(<any> mockSearchResult);
await fixture.whenStable();
fixture.detectChanges();
chips = fixture.debugElement.queryAll(By.css('mat-chip'));
expect(chips.length).toBe(8);
});
it('should show the long facet options list with pagination', () => {
const field = `[data-automation-id="search-field-Size facet queries"]`;
appConfigService.config.search = searchFilter;
queryBuilder.resetToDefaults();
fixture.detectChanges();
queryBuilder.executed.next(<any> mockSearchResult);
fixture.detectChanges();
fixture.detectChanges();
const searchChip = fixture.debugElement.query(By.css(`[data-automation-id="search-filter-chip-Size facet queries"]`));
searchChip.triggerEventHandler('click', { stopPropagation: () => null });
fixture.detectChanges();
let sizes = getAllMenus(`${field} mat-checkbox`, fixture);
expect(sizes).toEqual(stepOne);
let moreButton = fixture.debugElement.query(By.css(`${field} button[title="SEARCH.FILTER.ACTIONS.SHOW-MORE"]`));
let lessButton = fixture.debugElement.query(By.css(`${field} button[title="SEARCH.FILTER.ACTIONS.SHOW-LESS"]`));
expect(lessButton).toEqual(null);
expect(moreButton).toBeDefined();
moreButton.triggerEventHandler('click', {});
fixture.detectChanges();
sizes = getAllMenus(`${field} mat-checkbox`, fixture);
expect(sizes).toEqual(stepTwo);
moreButton = fixture.debugElement.query(By.css(`${field} button[title="SEARCH.FILTER.ACTIONS.SHOW-MORE"]`));
lessButton = fixture.debugElement.query(By.css(`${field} button[title="SEARCH.FILTER.ACTIONS.SHOW-LESS"]`));
expect(lessButton).toBeDefined();
expect(moreButton).toBeDefined();
moreButton.triggerEventHandler('click', {});
fixture.detectChanges();
sizes = getAllMenus(`${field} mat-checkbox`, fixture);
expect(sizes).toEqual(stepThree);
moreButton = fixture.debugElement.query(By.css(`${field} button[title="SEARCH.FILTER.ACTIONS.SHOW-MORE"]`));
lessButton = fixture.debugElement.query(By.css(`${field} button[title="SEARCH.FILTER.ACTIONS.SHOW-LESS"]`));
expect(lessButton).toBeDefined();
expect(moreButton).toEqual(null);
lessButton.triggerEventHandler('click', {});
fixture.detectChanges();
sizes = getAllMenus(`${field} mat-checkbox`, fixture);
expect(sizes).toEqual(stepTwo);
moreButton = fixture.debugElement.query(By.css(`${field} button[title="SEARCH.FILTER.ACTIONS.SHOW-MORE"]`));
lessButton = fixture.debugElement.query(By.css(`${field} button[title="SEARCH.FILTER.ACTIONS.SHOW-LESS"]`));
expect(lessButton).toBeDefined();
expect(moreButton).toBeDefined();
lessButton.triggerEventHandler('click', {});
fixture.detectChanges();
sizes = getAllMenus(`${field} mat-checkbox`, fixture);
expect(sizes).toEqual(stepOne);
moreButton = fixture.debugElement.query(By.css(`${field} button[title="SEARCH.FILTER.ACTIONS.SHOW-MORE"]`));
lessButton = fixture.debugElement.query(By.css(`${field} button[title="SEARCH.FILTER.ACTIONS.SHOW-LESS"]`));
expect(lessButton).toEqual(null);
expect(moreButton).toBeDefined();
});
it('should not show facets if filter is not available', () => {
const chip = '[data-automation-id="search-filter-chip-Size facet queries"]';
const filter = { ...searchFilter };
delete filter.facetQueries;
appConfigService.config.search = filter;
queryBuilder.resetToDefaults();
fixture.detectChanges();
queryBuilder.executed.next(<any> mockSearchResult);
fixture.detectChanges();
const facetElement = fixture.debugElement.query(By.css(chip));
expect(facetElement).toEqual(null);
});
it('should search the facets options and select it', () => {
const field = `[data-automation-id="search-field-Size facet queries"]`;
appConfigService.config.search = searchFilter;
queryBuilder.resetToDefaults();
fixture.detectChanges();
queryBuilder.executed.next(<any> mockSearchResult);
fixture.detectChanges();
spyOn(queryBuilder, 'update').and.stub();
const searchChip = fixture.debugElement.query(By.css(`[data-automation-id="search-filter-chip-Size facet queries"]`));
searchChip.triggerEventHandler('click', { stopPropagation: () => null });
fixture.detectChanges();
const inputElement = fixture.debugElement.query(By.css(`${field} input`));
inputElement.nativeElement.value = 'Extra';
inputElement.nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
let filteredMenu = getAllMenus(`${field} mat-checkbox`, fixture);
expect(filteredMenu).toEqual(['Extra Small (10239)']);
inputElement.nativeElement.value = 'my';
inputElement.nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
filteredMenu = getAllMenus(`${field} mat-checkbox`, fixture);
expect(filteredMenu).toEqual(filteredResult);
const clearButton = fixture.debugElement.query(By.css(`${field} mat-form-field button`));
clearButton.triggerEventHandler('click', {});
fixture.detectChanges();
filteredMenu = getAllMenus(`${field} mat-checkbox`, fixture);
expect(filteredMenu).toEqual(stepOne);
const firstOption = fixture.debugElement.query(By.css(`${field} mat-checkbox`));
firstOption.triggerEventHandler('change', { checked: true });
fixture.detectChanges();
const checkedOption = fixture.debugElement.query(By.css(`${field} mat-checkbox.mat-checkbox-checked`));
expect(checkedOption.nativeElement.innerText).toEqual('Extra Small (10239)');
expect(queryBuilder.update).toHaveBeenCalledTimes(1);
});
});
}); | the_stack |
import * as React from 'react';
import { Input } from 'antd';
import { Location, History as RouterHistory } from 'history';
import _clamp from 'lodash/clamp';
import _get from 'lodash/get';
import _mapValues from 'lodash/mapValues';
import _memoize from 'lodash/memoize';
import { connect, Dispatch } from 'react-redux';
import { match as Match } from 'react-router-dom';
import { bindActionCreators } from 'redux';
import ArchiveNotifier from './ArchiveNotifier';
import { actions as archiveActions } from './ArchiveNotifier/duck';
import { trackFilter, trackFocusMatches, trackNextMatch, trackPrevMatch, trackRange } from './index.track';
import {
CombokeysHandler,
merge as mergeShortcuts,
reset as resetShortcuts,
ShortcutCallbacks,
} from './keyboard-shortcuts';
import { cancel as cancelScroll, scrollBy, scrollTo } from './scroll-page';
import ScrollManager from './ScrollManager';
import calculateTraceDagEV from './TraceGraph/calculateTraceDagEV';
import TraceGraph from './TraceGraph/TraceGraph';
import { TEv } from './TraceGraph/types';
import { trackSlimHeaderToggle } from './TracePageHeader/TracePageHeader.track';
import TracePageHeader from './TracePageHeader';
import TraceTimelineViewer from './TraceTimelineViewer';
import { actions as timelineActions } from './TraceTimelineViewer/duck';
import { TUpdateViewRangeTimeFunction, IViewRange, ViewRangeTimeUpdate, ETraceViewType } from './types';
import { getLocation, getUrl } from './url';
import ErrorMessage from '../common/ErrorMessage';
import LoadingIndicator from '../common/LoadingIndicator';
import { extractUiFindFromState } from '../common/UiFindInput';
import * as jaegerApiActions from '../../actions/jaeger-api';
import { getUiFindVertexKeys } from '../TraceDiff/TraceDiffGraph/traceDiffGraphUtils';
import { fetchedState } from '../../constants';
import { FetchedTrace, ReduxState, TNil } from '../../types';
import { Trace } from '../../types/trace';
import { TraceArchive } from '../../types/archive';
import { EmbeddedState } from '../../types/embedded';
import filterSpans from '../../utils/filter-spans';
import updateUiFind from '../../utils/update-ui-find';
import TraceStatistics from './TraceStatistics/index';
import TraceSpanView from './TraceSpanView/index';
import './index.css';
type TDispatchProps = {
acknowledgeArchive: (id: string) => void;
archiveTrace: (id: string) => void;
fetchTrace: (id: string) => void;
focusUiFindMatches: (trace: Trace, uiFind: string | TNil) => void;
};
type TOwnProps = {
history: RouterHistory;
location: Location;
match: Match<{ id: string }>;
};
type TReduxProps = {
archiveEnabled: boolean;
archiveTraceState: TraceArchive | TNil;
embedded: null | EmbeddedState;
id: string;
searchUrl: null | string;
trace: FetchedTrace | TNil;
uiFind: string | TNil;
};
type TProps = TDispatchProps & TOwnProps & TReduxProps;
type TState = {
headerHeight: number | TNil;
slimView: boolean;
viewType: ETraceViewType;
viewRange: IViewRange;
};
// export for tests
export const VIEW_MIN_RANGE = 0.01;
const VIEW_CHANGE_BASE = 0.005;
const VIEW_CHANGE_FAST = 0.05;
// export for tests
export const shortcutConfig = {
panLeft: [-VIEW_CHANGE_BASE, -VIEW_CHANGE_BASE],
panLeftFast: [-VIEW_CHANGE_FAST, -VIEW_CHANGE_FAST],
panRight: [VIEW_CHANGE_BASE, VIEW_CHANGE_BASE],
panRightFast: [VIEW_CHANGE_FAST, VIEW_CHANGE_FAST],
zoomIn: [VIEW_CHANGE_BASE, -VIEW_CHANGE_BASE],
zoomInFast: [VIEW_CHANGE_FAST, -VIEW_CHANGE_FAST],
zoomOut: [-VIEW_CHANGE_BASE, VIEW_CHANGE_BASE],
zoomOutFast: [-VIEW_CHANGE_FAST, VIEW_CHANGE_FAST],
};
// export for tests
export function makeShortcutCallbacks(adjRange: (start: number, end: number) => void): ShortcutCallbacks {
function getHandler([startChange, endChange]: [number, number]): CombokeysHandler {
return function combokeyHandler(event: React.KeyboardEvent<HTMLElement>) {
event.preventDefault();
adjRange(startChange, endChange);
};
}
return _mapValues(shortcutConfig, getHandler);
}
// export for tests
export class TracePageImpl extends React.PureComponent<TProps, TState> {
state: TState;
_headerElm: HTMLElement | TNil;
_filterSpans: typeof filterSpans;
_searchBar: React.RefObject<Input>;
_scrollManager: ScrollManager;
traceDagEV: TEv | TNil;
constructor(props: TProps) {
super(props);
const { embedded, trace } = props;
this.state = {
headerHeight: null,
slimView: Boolean(embedded && embedded.timeline.collapseTitle),
viewType: ETraceViewType.TraceTimelineViewer,
viewRange: {
time: {
current: [0, 1],
},
},
};
this._headerElm = null;
this._filterSpans = _memoize(
filterSpans,
// Do not use the memo if the filter text or trace has changed.
// trace.data.spans is populated after the initial render via mutation.
textFilter =>
`${textFilter} ${_get(this.props.trace, 'traceID')} ${_get(this.props.trace, 'data.spans.length')}`
);
this._scrollManager = new ScrollManager(trace && trace.data, {
scrollBy,
scrollTo,
});
this._searchBar = React.createRef();
resetShortcuts();
}
componentDidMount() {
this.ensureTraceFetched();
this.updateViewRangeTime(0, 1);
/* istanbul ignore if */
if (!this._scrollManager) {
throw new Error('Invalid state - scrollManager is unset');
}
const {
scrollPageDown,
scrollPageUp,
scrollToNextVisibleSpan,
scrollToPrevVisibleSpan,
} = this._scrollManager;
const adjViewRange = (a: number, b: number) => this._adjustViewRange(a, b, 'kbd');
const shortcutCallbacks = makeShortcutCallbacks(adjViewRange);
shortcutCallbacks.scrollPageDown = scrollPageDown;
shortcutCallbacks.scrollPageUp = scrollPageUp;
shortcutCallbacks.scrollToNextVisibleSpan = scrollToNextVisibleSpan;
shortcutCallbacks.scrollToPrevVisibleSpan = scrollToPrevVisibleSpan;
shortcutCallbacks.clearSearch = this.clearSearch;
shortcutCallbacks.searchSpans = this.focusOnSearchBar;
mergeShortcuts(shortcutCallbacks);
}
componentDidUpdate({ id: prevID }: TProps) {
const { id, trace } = this.props;
this._scrollManager.setTrace(trace && trace.data);
this.setHeaderHeight(this._headerElm);
if (!trace) {
this.ensureTraceFetched();
return;
}
if (prevID !== id) {
this.updateViewRangeTime(0, 1);
this.clearSearch();
}
}
componentWillUnmount() {
resetShortcuts();
cancelScroll();
this._scrollManager.destroy();
this._scrollManager = new ScrollManager(undefined, {
scrollBy,
scrollTo,
});
}
_adjustViewRange(startChange: number, endChange: number, trackSrc: string) {
const [viewStart, viewEnd] = this.state.viewRange.time.current;
let start = _clamp(viewStart + startChange, 0, 0.99);
let end = _clamp(viewEnd + endChange, 0.01, 1);
if (end - start < VIEW_MIN_RANGE) {
if (startChange < 0 && endChange < 0) {
end = start + VIEW_MIN_RANGE;
} else if (startChange > 0 && endChange > 0) {
end = start + VIEW_MIN_RANGE;
} else {
const center = viewStart + (viewEnd - viewStart) / 2;
start = center - VIEW_MIN_RANGE / 2;
end = center + VIEW_MIN_RANGE / 2;
}
}
this.updateViewRangeTime(start, end, trackSrc);
}
setHeaderHeight = (elm: HTMLElement | TNil) => {
this._headerElm = elm;
if (elm) {
if (this.state.headerHeight !== elm.clientHeight) {
this.setState({ headerHeight: elm.clientHeight });
}
} else if (this.state.headerHeight) {
this.setState({ headerHeight: null });
}
};
clearSearch = () => {
const { history, location } = this.props;
updateUiFind({
history,
location,
trackFindFunction: trackFilter,
});
if (this._searchBar.current) this._searchBar.current.blur();
};
focusOnSearchBar = () => {
if (this._searchBar.current) this._searchBar.current.focus();
};
updateViewRangeTime: TUpdateViewRangeTimeFunction = (start: number, end: number, trackSrc?: string) => {
if (trackSrc) {
trackRange(trackSrc, [start, end], this.state.viewRange.time.current);
}
const current: [number, number] = [start, end];
const time = { current };
this.setState((state: TState) => ({ viewRange: { ...state.viewRange, time } }));
};
updateNextViewRangeTime = (update: ViewRangeTimeUpdate) => {
this.setState((state: TState) => {
const time = { ...state.viewRange.time, ...update };
return { viewRange: { ...state.viewRange, time } };
});
};
toggleSlimView = () => {
const { slimView } = this.state;
trackSlimHeaderToggle(!slimView);
this.setState({ slimView: !slimView });
};
setTraceView = (viewType: ETraceViewType) => {
if (this.props.trace && this.props.trace.data && viewType === ETraceViewType.TraceGraph) {
this.traceDagEV = calculateTraceDagEV(this.props.trace.data);
}
this.setState({ viewType });
};
archiveTrace = () => {
const { id, archiveTrace } = this.props;
archiveTrace(id);
};
acknowledgeArchive = () => {
const { id, acknowledgeArchive } = this.props;
acknowledgeArchive(id);
};
ensureTraceFetched() {
const { fetchTrace, location, trace, id } = this.props;
if (!trace) {
fetchTrace(id);
return;
}
const { history } = this.props;
if (id && id !== id.toLowerCase()) {
history.replace(getLocation(id.toLowerCase(), location.state));
}
}
focusUiFindMatches = () => {
const { trace, focusUiFindMatches, uiFind } = this.props;
if (trace && trace.data) {
trackFocusMatches();
focusUiFindMatches(trace.data, uiFind);
}
};
nextResult = () => {
trackNextMatch();
this._scrollManager.scrollToNextVisibleSpan();
};
prevResult = () => {
trackPrevMatch();
this._scrollManager.scrollToPrevVisibleSpan();
};
render() {
const {
archiveEnabled,
archiveTraceState,
embedded,
id,
uiFind,
trace,
location: { state: locationState },
} = this.props;
const { slimView, viewType, headerHeight, viewRange } = this.state;
if (!trace || trace.state === fetchedState.LOADING) {
return <LoadingIndicator className="u-mt-vast" centered />;
}
const { data } = trace;
if (trace.state === fetchedState.ERROR || !data) {
return <ErrorMessage className="ub-m3" error={trace.error || 'Unknown error'} />;
}
let findCount = 0;
let graphFindMatches: Set<string> | null | undefined;
let spanFindMatches: Set<string> | null | undefined;
if (uiFind) {
if (viewType === ETraceViewType.TraceGraph) {
graphFindMatches = getUiFindVertexKeys(uiFind, _get(this.traceDagEV, 'vertices', []));
findCount = graphFindMatches ? graphFindMatches.size : 0;
} else {
spanFindMatches = this._filterSpans(uiFind, _get(trace, 'data.spans'));
findCount = spanFindMatches ? spanFindMatches.size : 0;
}
}
const isEmbedded = Boolean(embedded);
const headerProps = {
focusUiFindMatches: this.focusUiFindMatches,
slimView,
textFilter: uiFind,
viewType,
viewRange,
canCollapse: !embedded || !embedded.timeline.hideSummary || !embedded.timeline.hideMinimap,
clearSearch: this.clearSearch,
hideMap: Boolean(
viewType !== ETraceViewType.TraceTimelineViewer || (embedded && embedded.timeline.hideMinimap)
),
hideSummary: Boolean(embedded && embedded.timeline.hideSummary),
linkToStandalone: getUrl(id),
nextResult: this.nextResult,
onArchiveClicked: this.archiveTrace,
onSlimViewClicked: this.toggleSlimView,
onTraceViewChange: this.setTraceView,
prevResult: this.prevResult,
ref: this._searchBar,
resultCount: findCount,
showArchiveButton: !isEmbedded && archiveEnabled,
showShortcutsHelp: !isEmbedded,
showStandaloneLink: isEmbedded,
showViewOptions: !isEmbedded,
toSearch: (locationState && locationState.fromSearch) || null,
trace: data,
updateNextViewRangeTime: this.updateNextViewRangeTime,
updateViewRangeTime: this.updateViewRangeTime,
};
let view;
if (ETraceViewType.TraceTimelineViewer === viewType && headerHeight) {
view = (
<TraceTimelineViewer
registerAccessors={this._scrollManager.setAccessors}
scrollToFirstVisibleSpan={this._scrollManager.scrollToFirstVisibleSpan}
findMatchesIDs={spanFindMatches}
trace={data}
updateNextViewRangeTime={this.updateNextViewRangeTime}
updateViewRangeTime={this.updateViewRangeTime}
viewRange={viewRange}
/>
);
} else if (ETraceViewType.TraceGraph === viewType && headerHeight) {
view = (
<TraceGraph
headerHeight={headerHeight}
ev={this.traceDagEV}
uiFind={uiFind}
uiFindVertexKeys={graphFindMatches}
/>
);
} else if (ETraceViewType.TraceStatistics === viewType && headerHeight) {
view = <TraceStatistics trace={data} uiFindVertexKeys={spanFindMatches} uiFind={uiFind} />;
} else if (ETraceViewType.TraceSpansView === viewType && headerHeight) {
view = <TraceSpanView trace={data} uiFindVertexKeys={spanFindMatches} uiFind={uiFind} />;
}
return (
<div>
{archiveEnabled && (
<ArchiveNotifier acknowledge={this.acknowledgeArchive} archivedState={archiveTraceState} />
)}
<div className="Tracepage--headerSection" ref={this.setHeaderHeight}>
<TracePageHeader {...headerProps} />
</div>
{headerHeight ? <section style={{ paddingTop: headerHeight }}>{view}</section> : null}
</div>
);
}
}
// export for tests
export function mapStateToProps(state: ReduxState, ownProps: TOwnProps): TReduxProps {
const { id } = ownProps.match.params;
const { archive, config, embedded, router } = state;
const { traces } = state.trace;
const trace = id ? traces[id] : null;
const archiveTraceState = id ? archive[id] : null;
const archiveEnabled = Boolean(config.archiveEnabled);
const { state: locationState } = router.location;
const searchUrl = (locationState && locationState.fromSearch) || null;
return {
...extractUiFindFromState(state),
archiveEnabled,
archiveTraceState,
embedded,
id,
searchUrl,
trace,
};
}
// export for tests
export function mapDispatchToProps(dispatch: Dispatch<ReduxState>): TDispatchProps {
const { fetchTrace } = bindActionCreators(jaegerApiActions, dispatch);
const { archiveTrace, acknowledge: acknowledgeArchive } = bindActionCreators(archiveActions, dispatch);
const { focusUiFindMatches } = bindActionCreators(timelineActions, dispatch);
return { acknowledgeArchive, archiveTrace, fetchTrace, focusUiFindMatches };
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(TracePageImpl); | the_stack |
import { Studio, StudioId, Studios } from '../../lib/collections/Studios'
import {
RundownPlaylists,
RundownPlaylistId,
DBRundownPlaylist,
RundownPlaylist,
} from '../../lib/collections/RundownPlaylists'
import { DBRundown, Rundown, RundownId, Rundowns } from '../../lib/collections/Rundowns'
import {
getHash,
protectString,
makePromise,
clone,
getCurrentTime,
unprotectObjectArray,
getRank,
unprotectString,
mongoFindOptions,
} from '../../lib/lib'
import * as _ from 'underscore'
import { AdLibActions } from '../../lib/collections/AdLibActions'
import { AdLibPieces } from '../../lib/collections/AdLibPieces'
import { ExpectedMediaItems } from '../../lib/collections/ExpectedMediaItems'
import { ExpectedPlayoutItems } from '../../lib/collections/ExpectedPlayoutItems'
import { IngestDataCache } from '../../lib/collections/IngestDataCache'
import { PartInstances } from '../../lib/collections/PartInstances'
import { Parts } from '../../lib/collections/Parts'
import { PieceInstances } from '../../lib/collections/PieceInstances'
import { Pieces } from '../../lib/collections/Pieces'
import { RundownBaselineAdLibActions } from '../../lib/collections/RundownBaselineAdLibActions'
import { RundownBaselineAdLibPieces } from '../../lib/collections/RundownBaselineAdLibPieces'
import { RundownBaselineObjs } from '../../lib/collections/RundownBaselineObjs'
import { Segments } from '../../lib/collections/Segments'
import {
runStudioOperationWithCache,
runStudioOperationWithLock,
StudioLockFunctionPriority,
} from './studio/lockFunction'
import {
PlayoutLockFunctionPriority,
runPlayoutOperationWithLock,
runPlayoutOperationWithLockFromStudioOperation,
} from './playout/lockFunction'
import { ReadonlyDeep } from 'type-fest'
import { WrappedStudioBlueprint } from './blueprints/cache'
import { StudioUserContext } from './blueprints/context'
import { allowedToMoveRundownOutOfPlaylist } from './rundown'
import { Meteor } from 'meteor/meteor'
import { BlueprintResultOrderedRundowns } from '@sofie-automation/blueprints-integration'
import { MethodContext } from '../../lib/api/methods'
import { RundownPlaylistContentWriteAccess } from '../security/rundownPlaylist'
import { regeneratePlaylistAndRundownOrder, updatePlayoutAfterChangingRundownInPlaylist } from './ingest/commit'
import { DbCacheWriteCollection } from '../cache/CacheCollection'
import { Random } from 'meteor/random'
import { asyncCollectionRemove, asyncCollectionFindOne } from '../lib/database'
import { ExpectedPackages } from '../../lib/collections/ExpectedPackages'
import { checkAccessToPlaylist } from './lib'
export function removeEmptyPlaylists(studioId: StudioId) {
runStudioOperationWithCache('removeEmptyPlaylists', studioId, StudioLockFunctionPriority.MISC, async (cache) => {
// Skip any playlists which are active
const playlists = cache.RundownPlaylists.findFetch({ activationId: { $exists: false } })
// We want to run them all in parallel fibers
await Promise.allSettled(
playlists.map(async (playlist) =>
makePromise(() => {
// Take the playlist lock, to ensure we don't fight something else
runPlayoutOperationWithLockFromStudioOperation(
'removeEmptyPlaylists',
cache,
playlist,
PlayoutLockFunctionPriority.MISC,
async () => {
const rundowns = Rundowns.find({ playlistId: playlist._id }).count()
if (rundowns === 0) {
await removeRundownPlaylistFromDb(playlist)
}
}
)
})
)
)
})
}
/**
* Convert the playlistExternalId into a playlistId.
* When we've received an externalId for a playlist, that can directly be used to reference a playlistId
*/
export function getPlaylistIdFromExternalId(studioId: StudioId, playlistExternalId: string): RundownPlaylistId {
return protectString(getHash(`${studioId}_${playlistExternalId}`))
}
export async function removeRundownPlaylistFromDb(playlist: ReadonlyDeep<RundownPlaylist>): Promise<void> {
if (playlist.activationId)
throw new Meteor.Error(500, `RundownPlaylist "${playlist._id}" is active and cannot be removed`)
// We assume we have the master lock at this point
const rundownIds = Rundowns.find({ playlistId: playlist._id }, { fields: { _id: 1 } }).map((r) => r._id)
await Promise.allSettled([
asyncCollectionRemove(RundownPlaylists, { _id: playlist._id }),
removeRundownsFromDb(rundownIds),
])
}
export async function removeRundownsFromDb(rundownIds: RundownId[]): Promise<void> {
// Note: playlists are not removed by this, one could be left behind empty
if (rundownIds.length > 0) {
await Promise.allSettled([
asyncCollectionRemove(Rundowns, { _id: { $in: rundownIds } }),
asyncCollectionRemove(AdLibActions, { rundownId: { $in: rundownIds } }),
asyncCollectionRemove(AdLibPieces, { rundownId: { $in: rundownIds } }),
asyncCollectionRemove(ExpectedMediaItems, { rundownId: { $in: rundownIds } }),
asyncCollectionRemove(ExpectedPlayoutItems, { rundownId: { $in: rundownIds } }),
asyncCollectionRemove(ExpectedPackages, { rundownId: { $in: rundownIds } }),
asyncCollectionRemove(IngestDataCache, { rundownId: { $in: rundownIds } }),
asyncCollectionRemove(RundownBaselineAdLibPieces, { rundownId: { $in: rundownIds } }),
asyncCollectionRemove(Segments, { rundownId: { $in: rundownIds } }),
asyncCollectionRemove(Parts, { rundownId: { $in: rundownIds } }),
asyncCollectionRemove(PartInstances, { rundownId: { $in: rundownIds } }),
asyncCollectionRemove(Pieces, { startRundownId: { $in: rundownIds } }),
asyncCollectionRemove(PieceInstances, { rundownId: { $in: rundownIds } }),
asyncCollectionRemove(RundownBaselineAdLibActions, { rundownId: { $in: rundownIds } }),
asyncCollectionRemove(RundownBaselineObjs, { rundownId: { $in: rundownIds } }),
])
}
}
export interface RundownPlaylistAndOrder {
rundownPlaylist: DBRundownPlaylist
order: BlueprintResultOrderedRundowns
}
export function produceRundownPlaylistInfoFromRundown(
studio: ReadonlyDeep<Studio>,
studioBlueprint: WrappedStudioBlueprint | undefined,
existingPlaylist: ReadonlyDeep<RundownPlaylist> | undefined,
playlistId: RundownPlaylistId,
playlistExternalId: string,
rundowns: ReadonlyDeep<Array<Rundown>>
): RundownPlaylistAndOrder {
const playlistInfo = studioBlueprint?.blueprint?.getRundownPlaylistInfo
? studioBlueprint.blueprint.getRundownPlaylistInfo(
new StudioUserContext(
{
name: 'produceRundownPlaylistInfoFromRundown',
identifier: `studioId=${studio._id},playlistId=${playlistId},rundownIds=${rundowns
.map((r) => r._id)
.join(',')}`,
tempSendUserNotesIntoBlackHole: true,
},
studio
),
unprotectObjectArray(clone<Array<Rundown>>(rundowns))
)
: null
const rundownsInDefaultOrder = sortDefaultRundownInPlaylistOrder(rundowns)
let newPlaylist: DBRundownPlaylist
if (playlistInfo) {
newPlaylist = {
created: getCurrentTime(),
currentPartInstanceId: null,
nextPartInstanceId: null,
previousPartInstanceId: null,
...clone<RundownPlaylist | undefined>(existingPlaylist),
_id: playlistId,
externalId: playlistExternalId,
organizationId: studio.organizationId,
studioId: studio._id,
name: playlistInfo.playlist.name,
expectedStart: playlistInfo.playlist.expectedStart,
expectedDuration: playlistInfo.playlist.expectedDuration,
loop: playlistInfo.playlist.loop,
outOfOrderTiming: playlistInfo.playlist.outOfOrderTiming,
timeOfDayCountdowns: playlistInfo.playlist.timeOfDayCountdowns,
modified: getCurrentTime(),
}
} else {
newPlaylist = {
...defaultPlaylistForRundown(rundownsInDefaultOrder[0], studio, existingPlaylist),
_id: playlistId,
externalId: playlistExternalId,
}
}
// If no order is provided, fall back to default sorting:
const order = playlistInfo?.order ?? _.object(rundownsInDefaultOrder.map((i, index) => [i._id, index + 1]))
return {
rundownPlaylist: newPlaylist,
order: order, // Note: if playlist.rundownRanksAreSetInSofie is set, this order should be ignored later
}
}
function defaultPlaylistForRundown(
rundown: ReadonlyDeep<DBRundown>,
studio: ReadonlyDeep<Studio>,
existingPlaylist?: ReadonlyDeep<RundownPlaylist>
): Omit<DBRundownPlaylist, '_id' | 'externalId'> {
return {
created: getCurrentTime(),
currentPartInstanceId: null,
nextPartInstanceId: null,
previousPartInstanceId: null,
...clone<RundownPlaylist | undefined>(existingPlaylist),
organizationId: studio.organizationId,
studioId: studio._id,
name: rundown.name,
expectedStart: rundown.expectedStart,
expectedDuration: rundown.expectedDuration,
modified: getCurrentTime(),
}
}
/** Set _rank and playlistId of rundowns in a playlist */
export function updateRundownsInPlaylist(
_playlist: DBRundownPlaylist,
rundownRanks: BlueprintResultOrderedRundowns,
rundownCollection: DbCacheWriteCollection<Rundown, DBRundown>
) {
let maxRank: number = Number.NEGATIVE_INFINITY
let unrankedRundowns: DBRundown[] = []
for (const rundown of rundownCollection.findFetch({})) {
const rundownRank = rundownRanks[unprotectString(rundown._id)]
if (rundownRank !== undefined) {
rundown._rank = rundownRank
rundownCollection.update(rundown._id, { $set: { _rank: rundownRank } })
} else {
unrankedRundowns.push(rundown)
}
if (!_.isNaN(Number(rundown._rank))) {
maxRank = Math.max(maxRank, rundown._rank)
} else {
unrankedRundowns.push(rundown)
}
}
// Place new/unknown rundowns at the end:
const orderedUnrankedRundowns = sortDefaultRundownInPlaylistOrder(unrankedRundowns)
orderedUnrankedRundowns.forEach((rundown) => {
rundownCollection.update(rundown._id, { $set: { _rank: ++maxRank } })
})
}
/** Move a rundown manually (by a user in Sofie) */
export function moveRundownIntoPlaylist(
context: MethodContext,
/** The rundown to be moved */
rundownId: RundownId,
/** Which playlist to move into. If null, move into a (new) separate playlist */
intoPlaylistId: RundownPlaylistId | null,
/** The new rundowns in the new playlist */
rundownsIdsInPlaylistInOrder: RundownId[]
): void {
const access = RundownPlaylistContentWriteAccess.rundown(context, rundownId)
const rundown: Rundown = access.rundown
const oldPlaylist: RundownPlaylist | null = access.playlist
if (!rundown) throw new Meteor.Error(404, `Rundown "${rundownId}" not found!`)
if (oldPlaylist && rundown.playlistId !== oldPlaylist._id)
throw new Meteor.Error(
500,
`moveRundown: rundown.playlistId "${rundown.playlistId}" is not equal to oldPlaylist._id "${oldPlaylist._id}"`
)
runStudioOperationWithLock('moveRundown', rundown.studioId, StudioLockFunctionPriority.MISC, (lock) => {
let intoPlaylist: RundownPlaylist | null = null
if (intoPlaylistId) {
const access2 = RundownPlaylistContentWriteAccess.anyContent(context, intoPlaylistId)
intoPlaylist = access2.playlist
if (!intoPlaylist) throw new Meteor.Error(404, `Playlist "${intoPlaylistId}" not found!`)
}
const studio = Studios.findOne(rundown.studioId)
if (!studio) throw new Meteor.Error(404, `Studio "${rundown.studioId}" of rundown "${rundown._id}" not found!`)
if (intoPlaylist && intoPlaylist.studioId !== rundown.studioId) {
throw new Meteor.Error(
404,
`Cannot move Rundown "${rundown._id}" into playlist "${intoPlaylist._id}" because they are in different studios ("${intoPlaylist.studioId}", "${rundown.studioId}")!`
)
}
// Do a check if we're allowed to move out of currently playing playlist:
if (oldPlaylist && oldPlaylist._id !== intoPlaylist?._id) {
runPlayoutOperationWithLockFromStudioOperation(
'moveRundown: remove from old playlist',
lock,
oldPlaylist,
PlayoutLockFunctionPriority.MISC,
async (oldPlaylistLock) => {
// Reload playlist to ensure it is up-to-date
const playlist = RundownPlaylists.findOne(oldPlaylist._id)
if (!playlist)
throw new Meteor.Error(
404,
`RundownPlaylists "${oldPlaylist._id}" for rundown "${rundown._id}" not found!`
)
if (!allowedToMoveRundownOutOfPlaylist(playlist, rundown)) {
throw new Meteor.Error(400, `Not allowed to move currently playing rundown!`)
}
// Quickly Remove it from the old playlist so that we can free the lock
Rundowns.update(rundown._id, {
$set: { playlistId: protectString('__TMP__'), playlistIdIsSetInSofie: true },
})
// Regenerate the playlist
const newPlaylist = await regeneratePlaylistAndRundownOrder(studio, playlist)
if (newPlaylist) {
// ensure the 'old' playout is updated to remove any references to the rundown
updatePlayoutAfterChangingRundownInPlaylist(newPlaylist, oldPlaylistLock, null)
}
}
)
}
if (intoPlaylist) {
// Move into an existing playlist:
runPlayoutOperationWithLockFromStudioOperation(
'moveRundown: add into existing playlist',
lock,
intoPlaylist,
PlayoutLockFunctionPriority.MISC,
async (intoPlaylistLock) => {
const rundownsCollection = new DbCacheWriteCollection(Rundowns)
const [playlist] = await Promise.all([
asyncCollectionFindOne(RundownPlaylists, intoPlaylistLock._playlistId),
rundownsCollection.prepareInit({ playlistId: intoPlaylistLock._playlistId }, true),
])
if (!playlist)
throw new Meteor.Error(
404,
`RundownPlaylists "${intoPlaylistLock._playlistId}" for rundown "${rundown._id}" not found!`
)
if (!playlist.rundownRanksAreSetInSofie) {
playlist.rundownRanksAreSetInSofie = true
RundownPlaylists.update(playlist._id, {
$set: {
rundownRanksAreSetInSofie: true,
},
})
}
if (playlist._id === oldPlaylist?._id) {
// Move the rundown within the playlist
const i = rundownsIdsInPlaylistInOrder.indexOf(rundownId)
if (i === -1)
throw new Meteor.Error(
500,
`RundownId "${rundownId}" not found in rundownsIdsInPlaylistInOrder`
)
const rundownIdBefore: RundownId | undefined = rundownsIdsInPlaylistInOrder[i - 1]
const rundownIdAfter: RundownId | undefined = rundownsIdsInPlaylistInOrder[i + 1]
const rundownBefore: Rundown | undefined =
rundownIdBefore && rundownsCollection.findOne(rundownIdBefore)
const rundownAfter: Rundown | undefined =
rundownIdAfter && rundownsCollection.findOne(rundownIdAfter)
let newRank: number | undefined = getRank(rundownBefore, rundownAfter)
if (newRank === undefined) throw new Meteor.Error(500, `newRank is undefined`)
rundownsCollection.update(rundown._id, {
$set: {
_rank: newRank,
},
})
} else {
// Moving from another playlist
rundownsCollection.replace(rundown)
// Note: When moving into another playlist, the rundown is placed last.
rundownsCollection.update(rundown._id, {
$set: {
playlistId: playlist._id,
playlistIdIsSetInSofie: true,
_rank: 99999, // The rank will be set later, in updateRundownsInPlaylist
},
})
rundown.playlistId = playlist._id
rundown.playlistIdIsSetInSofie = true
// When updating the rundowns in the playlist, the newly moved rundown will be given it's proper _rank:
updateRundownsInPlaylist(
playlist,
_.object(rundownsIdsInPlaylistInOrder.map((id, index) => [id, index + 1])),
rundownsCollection
)
}
// Update the playlist and the order of the contents
const newPlaylist = await regeneratePlaylistAndRundownOrder(studio, playlist, rundownsCollection)
if (!newPlaylist) {
throw new Meteor.Error(500, `RundownPlaylist must still be valid as it has some Rundowns`)
}
await rundownsCollection.updateDatabaseWithData()
// If the playlist is active this could have changed lookahead
updatePlayoutAfterChangingRundownInPlaylist(newPlaylist, intoPlaylistLock, rundown)
}
)
} else {
// Move into a new playlist:
// No point locking, as we are creating something fresh and unique here
const externalId = Random.id()
const playlist: DBRundownPlaylist = {
...defaultPlaylistForRundown(rundown, studio),
externalId: externalId,
_id: getPlaylistIdFromExternalId(studio._id, externalId),
}
RundownPlaylists.insert(playlist)
Rundowns.update(rundown._id, {
$set: {
playlistId: playlist._id,
playlistIdIsSetInSofie: true,
_rank: 1,
},
})
}
})
}
/** Restore the order of rundowns in a playlist, giving control over the ordering back to the NRCS */
export function restoreRundownsInPlaylistToDefaultOrder(context: MethodContext, playlistId: RundownPlaylistId) {
const access = checkAccessToPlaylist(context, playlistId)
runPlayoutOperationWithLock(
access,
'restoreRundownsInPlaylistToDefaultOrder',
playlistId,
PlayoutLockFunctionPriority.MISC,
async (playlistLock, tmpPlaylist) => {
const studio = await asyncCollectionFindOne(Studios, tmpPlaylist.studioId)
if (!studio)
throw new Meteor.Error(
404,
`Studio "${tmpPlaylist.studioId}" of playlist "${tmpPlaylist._id}" not found!`
)
// Update the playlist
RundownPlaylists.update(tmpPlaylist._id, {
$set: {
rundownRanksAreSetInSofie: false,
},
})
const newPlaylist = clone<RundownPlaylist>(tmpPlaylist)
newPlaylist.rundownRanksAreSetInSofie = false
// Update the _rank of the rundowns
const updatedPlaylist = await regeneratePlaylistAndRundownOrder(studio, newPlaylist)
if (updatedPlaylist) {
// If the playlist is active this could have changed lookahead
updatePlayoutAfterChangingRundownInPlaylist(updatedPlaylist, playlistLock, null)
}
}
)
}
function sortDefaultRundownInPlaylistOrder(rundowns: ReadonlyDeep<Array<DBRundown>>): ReadonlyDeep<Array<DBRundown>> {
return mongoFindOptions<ReadonlyDeep<DBRundown>, ReadonlyDeep<DBRundown>>(rundowns, {
sort: {
expectedStart: 1,
name: 1,
_id: 1,
},
})
} | the_stack |
import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams,
HttpResponse, HttpEvent, HttpParameterCodec } from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
import { ChangeUserPasswordInput } from '../model/models';
import { CustomUserFields } from '../model/models';
import { ErrorResponse } from '../model/models';
import { FinalizeRegistrationInput } from '../model/models';
import { RegisterUserInput } from '../model/models';
import { ResetUserPasswordInput } from '../model/models';
import { User } from '../model/models';
import { UsersResponse } from '../model/models';
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
export interface ChangeUserPasswordRequestParams {
/** Use to change a user\'s password. */
changeUserPasswordInput?: ChangeUserPasswordInput;
}
export interface FinalizeUserRegistrationRequestParams {
/** Used to finalize a user registration. */
finalizeRegistrationInput?: FinalizeRegistrationInput;
}
export interface GetUserAvatarRequestParams {
/** Id of a user */
userId: string;
}
export interface GetUsersRequestParams {
/** The page number for pagination. */
page?: number;
/** The number of items per page for pagination. If the size is 0, the response contains only metadata and returns the values as for a non-paged resource. If the size is -1, the response contains all datas. */
size?: number;
/** query string to be used in the search engine */
q?: string;
}
export interface RegisterNewUserRequestParams {
/** Used to register a new User. */
registerUserInput?: RegisterUserInput;
}
export interface ResetUserPasswordRequestParams {
/** Use to reset a user\'s password. */
resetUserPasswordInput?: ResetUserPasswordInput;
}
@Injectable({
providedIn: 'root'
})
export class UsersService {
protected basePath = 'http://localhost:8083/portal/environments/DEFAULT';
public defaultHeaders = new HttpHeaders();
public configuration = new Configuration();
public encoder: HttpParameterCodec;
constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) {
if (configuration) {
this.configuration = configuration;
}
if (typeof this.configuration.basePath !== 'string') {
if (typeof basePath !== 'string') {
basePath = this.basePath;
}
this.configuration.basePath = basePath;
}
this.encoder = this.configuration.encoder || new CustomHttpParameterCodec();
}
private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams {
if (typeof value === "object" && value instanceof Date === false) {
httpParams = this.addToHttpParamsRecursive(httpParams, value);
} else {
httpParams = this.addToHttpParamsRecursive(httpParams, value, key);
}
return httpParams;
}
private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams {
if (value == null) {
return httpParams;
}
if (typeof value === "object") {
if (Array.isArray(value)) {
(value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key));
} else if (value instanceof Date) {
if (key != null) {
httpParams = httpParams.append(key,
(value as Date).toISOString().substr(0, 10));
} else {
throw Error("key may not be null if value is Date");
}
} else {
Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive(
httpParams, value[k], key != null ? `${key}.${k}` : k));
}
} else if (key != null) {
httpParams = httpParams.append(key, value);
} else {
throw Error("key may not be null if value is not object or array");
}
return httpParams;
}
/**
* Change a user\'s password after a reset requests
* Perform the password update for a user
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public changeUserPassword(requestParameters: ChangeUserPasswordRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<User>;
public changeUserPassword(requestParameters: ChangeUserPasswordRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<User>>;
public changeUserPassword(requestParameters: ChangeUserPasswordRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<User>>;
public changeUserPassword(requestParameters: ChangeUserPasswordRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const changeUserPasswordInput = requestParameters.changeUserPasswordInput;
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
headers = headers.set('Content-Type', httpContentTypeSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.post<User>(`${this.configuration.basePath}/users/_change_password`,
changeUserPasswordInput,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Finalize user registration.
* Create a new user for the portal. User registration must be enabled.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public finalizeUserRegistration(requestParameters: FinalizeUserRegistrationRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<User>;
public finalizeUserRegistration(requestParameters: FinalizeUserRegistrationRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<User>>;
public finalizeUserRegistration(requestParameters: FinalizeUserRegistrationRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<User>>;
public finalizeUserRegistration(requestParameters: FinalizeUserRegistrationRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const finalizeRegistrationInput = requestParameters.finalizeRegistrationInput;
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
headers = headers.set('Content-Type', httpContentTypeSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.post<User>(`${this.configuration.basePath}/users/registration/_finalize`,
finalizeRegistrationInput,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Retrieve a user\'s avatar
* Retrieve a user\'s avatar.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getUserAvatar(requestParameters: GetUserAvatarRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'image/_*' | 'application/json'}): Observable<Blob>;
public getUserAvatar(requestParameters: GetUserAvatarRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'image/_*' | 'application/json'}): Observable<HttpResponse<Blob>>;
public getUserAvatar(requestParameters: GetUserAvatarRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'image/_*' | 'application/json'}): Observable<HttpEvent<Blob>>;
public getUserAvatar(requestParameters: GetUserAvatarRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'image/_*' | 'application/json'}): Observable<any> {
const userId = requestParameters.userId;
if (userId === null || userId === undefined) {
throw new Error('Required parameter userId was null or undefined when calling getUserAvatar.');
}
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'image/_*',
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
return this.httpClient.get(`${this.configuration.basePath}/users/${encodeURIComponent(String(userId))}/avatar`,
{
responseType: "blob",
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* List platform users.
* List platform users from identity providers. User must have the MANAGEMENT_USERS[READ] permission.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getUsers(requestParameters: GetUsersRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<UsersResponse>;
public getUsers(requestParameters: GetUsersRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<UsersResponse>>;
public getUsers(requestParameters: GetUsersRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<UsersResponse>>;
public getUsers(requestParameters: GetUsersRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const page = requestParameters.page;
const size = requestParameters.size;
const q = requestParameters.q;
let queryParameters = new HttpParams({encoder: this.encoder});
if (page !== undefined && page !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>page, 'page');
}
if (size !== undefined && size !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>size, 'size');
}
if (q !== undefined && q !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>q, 'q');
}
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.post<UsersResponse>(`${this.configuration.basePath}/users/_search`,
null,
{
params: queryParameters,
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* List all the Custom User Fields.
* Provide the list of custom user fields asked to the new users.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public listCustomUserFields(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<Array<CustomUserFields>>;
public listCustomUserFields(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<Array<CustomUserFields>>>;
public listCustomUserFields(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<Array<CustomUserFields>>>;
public listCustomUserFields(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.get<Array<CustomUserFields>>(`${this.configuration.basePath}/configuration/users/custom-fields`,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Register a new user.
* Register a new user for the portal. As a result, an email is sent with an activation link. User registration must be enabled.\\ A SMTP server must have been configured.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public registerNewUser(requestParameters: RegisterNewUserRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<User>;
public registerNewUser(requestParameters: RegisterNewUserRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<User>>;
public registerNewUser(requestParameters: RegisterNewUserRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<User>>;
public registerNewUser(requestParameters: RegisterNewUserRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const registerUserInput = requestParameters.registerUserInput;
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
headers = headers.set('Content-Type', httpContentTypeSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.post<User>(`${this.configuration.basePath}/users/registration`,
registerUserInput,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Reset a user\'s password
* Send an email with a link so the user with this email can provide a new password. The user must be internally managed and active.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public resetUserPassword(requestParameters: ResetUserPasswordRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<any>;
public resetUserPassword(requestParameters: ResetUserPasswordRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<any>>;
public resetUserPassword(requestParameters: ResetUserPasswordRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<any>>;
public resetUserPassword(requestParameters: ResetUserPasswordRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const resetUserPasswordInput = requestParameters.resetUserPasswordInput;
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
headers = headers.set('Content-Type', httpContentTypeSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.post<any>(`${this.configuration.basePath}/users/_reset_password`,
resetUserPasswordInput,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
} | the_stack |
import React, { useCallback, useEffect, useMemo, useRef } from "react";
import BaseTable, { Column } from "react-base-table";
import Measure, { ContentRect } from "react-measure";
import "./table_styles.css";
import { Box, Paper, Typography } from "@mui/material";
import AssignmentIcon from "@mui/icons-material/Assignment";
import { useLocation } from "react-router-dom";
import {
AdditionalColumnDelegate,
CMSType,
CollectionSize,
FilterCombination,
Entity,
FilterValues,
Property,
WhereFilterOp, FireCMSContext
} from "../../models";
import {
CMSColumn,
getCellAlignment,
getPropertyColumnWidth,
getRowHeight,
isPropertyFilterable,
Sort
} from "../internal/common";
import CollectionTableToolbar from "../internal/CollectionTableToolbar";
import PreviewComponent from "../../preview/PreviewComponent";
import SkeletonComponent from "../../preview/components/SkeletonComponent";
import ErrorBoundary from "../../core/internal/ErrorBoundary";
import TableCell from "../internal/TableCell";
import PopupFormField from "../internal/popup_field/PopupFormField";
import OutsideAlerter from "../../core/internal/OutsideAlerter";
import CollectionRowActions from "../internal/CollectionRowActions";
import { CollectionTableProps } from "./CollectionTableProps";
import { TableCellProps } from "../internal/TableCellProps";
import CircularProgressCenter
from "../../core/components/CircularProgressCenter";
import { useTableStyles } from "./styles";
import { getPreviewSizeFrom } from "../../preview/util";
import PropertyTableCell, { OnCellChangeParams } from "../internal/PropertyTableCell";
import { CustomFieldValidator, mapPropertyToYup } from "../../form/validation";
import { useCollectionFetch, useFireCMSContext } from "../../hooks";
import CollectionTableHeader from "../internal/CollectionTableHeader";
import { buildPropertyFrom } from "../../core/util/property_builder";
const DEFAULT_PAGE_SIZE = 50;
const PIXEL_NEXT_PAGE_OFFSET = 1200;
/**
* This component is in charge of rendering a collection table with a high
* degree of customization.
*
* Please note that you only need to use this component if you are building
* a custom view. If you just need to create a default view you can do it
* exclusively with config options.
*
* If you just want to bind a EntityCollection to a collection table you can
* check {@link EntityCollectionTable}
*
* @see CollectionTableProps
* @see EntityCollectionTable
* @category Core components
*/
export default function CollectionTable<M extends { [Key: string]: any },
AdditionalKey extends string = string>({
initialFilter,
initialSort,
path,
schema,
displayedProperties,
textSearchEnabled,
additionalColumns,
filterCombinations,
inlineEditing,
toolbarActionsBuilder,
title,
tableRowActionsBuilder,
defaultSize = "m",
frozenIdColumn,
uniqueFieldValidator,
entitiesDisplayedFirst,
paginationEnabled,
onEntityClick,
onCellValueChange,
pageSize = DEFAULT_PAGE_SIZE
}: CollectionTableProps<M, AdditionalKey>) {
const context: FireCMSContext = useFireCMSContext();
const [size, setSize] = React.useState<CollectionSize>(defaultSize);
const [itemCount, setItemCount] = React.useState<number | undefined>(paginationEnabled ? pageSize : undefined);
const [filterValues, setFilterValues] = React.useState<FilterValues<M>>(initialFilter || {});
const [sortByProperty, setSortProperty] = React.useState<Extract<keyof M, string> | undefined>(initialSort ? initialSort[0] : undefined);
const [currentSort, setCurrentSort] = React.useState<Sort>(initialSort ? initialSort[1] : undefined);
const [tableSize, setTableSize] = React.useState<ContentRect | undefined>();
const [tableKey] = React.useState<string>(Math.random().toString(36));
const tableRef = useRef<BaseTable>(null);
const classes = useTableStyles();
const [selectedCell, setSelectedCell] = React.useState<TableCellProps<M>>(undefined);
const [popupCell, setPopupCell] = React.useState<TableCellProps<M>>(undefined);
const [focused, setFocused] = React.useState<boolean>(false);
const [formPopupOpen, setFormPopupOpen] = React.useState<boolean>(false);
const [preventOutsideClick, setPreventOutsideClick] = React.useState<boolean>(false);
const [searchString, setSearchString] = React.useState<string | undefined>();
const filterIsSet = filterValues && Object.keys(filterValues).length > 0;
const {
data,
dataLoading,
noMoreToLoad,
dataLoadingError
} = useCollectionFetch({
entitiesDisplayedFirst,
path,
schema,
filterValues,
sortByProperty,
searchString,
currentSort,
itemCount
});
const textSearchInProgress = Boolean(searchString);
const actions = toolbarActionsBuilder && toolbarActionsBuilder({
size,
data
});
const updatePopup = (value: boolean) => {
setFocused(!value);
setFormPopupOpen(value);
};
const { pathname } = useLocation();
React.useEffect(() => {
setFormPopupOpen(false);
}, [pathname]);
const loadNextPage = () => {
if (!paginationEnabled || dataLoading || noMoreToLoad)
return;
if (itemCount !== undefined)
setItemCount(itemCount + pageSize);
};
const resetPagination = () => {
setItemCount(pageSize);
};
const select = (cell: TableCellProps<M>) => {
setSelectedCell(cell);
setFocused(true);
if (!formPopupOpen) {
setPopupCell(cell);
}
};
const unselect = useCallback(() => {
setSelectedCell(undefined);
setFocused(false);
setPreventOutsideClick(false);
}, []);
const additionalColumnsMap: Record<string, AdditionalColumnDelegate<M, string>> = useMemo(() => {
return additionalColumns ?
additionalColumns
.map((aC) => ({ [aC.id]: aC }))
.reduce((a, b) => ({ ...a, ...b }), [])
: {};
}, [additionalColumns]);
const scrollToTop = () => {
if (tableRef.current) {
tableRef.current.scrollToTop(0);
}
};
const handleClickOutside = () => {
unselect();
};
// on ESC key press
useEffect(() => {
const escFunction = (event: any) => {
if (event.keyCode === 27) {
unselect();
}
};
document.addEventListener("keydown", escFunction, false);
return () => {
document.removeEventListener("keydown", escFunction, false);
};
});
const columns = useMemo(() => {
const allColumns: CMSColumn[] = (Object.keys(schema.properties) as (keyof M)[])
.map((key) => {
const property: Property<any> = buildPropertyFrom<any, M>(schema.properties[key], schema.defaultValues ?? {}, path);
return ({
id: key as string,
type: "property",
property,
align: getCellAlignment(property),
label: property.title || key as string,
sortable: true,
filterable: isPropertyFilterable(property),
width: getPropertyColumnWidth(property, size)
});
});
if (additionalColumns) {
const items: CMSColumn[] = additionalColumns.map((additionalColumn) =>
({
id: additionalColumn.id,
type: "additional",
align: "left",
sortable: false,
filterable: false,
label: additionalColumn.title,
width: additionalColumn.width ?? 200
}));
allColumns.push(...items);
}
return displayedProperties
.map((p) => {
return allColumns.find(c => c.id === p);
}).filter(c => !!c) as CMSColumn[];
}, [displayedProperties]);
const onColumnSort = (key: Extract<keyof M, string>) => {
const isDesc = sortByProperty === key && currentSort === "desc";
const isAsc = sortByProperty === key && currentSort === "asc";
const newSort = isDesc ? "asc" : (isAsc ? undefined : "desc");
const newSortProperty: Extract<keyof M, string> | undefined = isAsc ? undefined : key;
if (filterValues) {
if (!isFilterCombinationValid(filterValues, filterCombinations, newSortProperty, newSort)) {
// reset filters
setFilterValues({});
}
}
resetPagination();
setCurrentSort(newSort);
setSortProperty(newSortProperty);
scrollToTop();
};
const resetSort = () => {
setCurrentSort(undefined);
setSortProperty(undefined);
};
const clearFilter = () => setFilterValues({});
const buildIdColumn = (props: {
entity: Entity<M>,
size: CollectionSize,
}) => {
if (tableRowActionsBuilder)
return tableRowActionsBuilder(props);
else
return <CollectionRowActions {...props}/>;
};
function checkInlineEditing<M>(entity: Entity<M>) {
if (typeof inlineEditing === "boolean") {
return inlineEditing;
} else if (typeof inlineEditing === "function") {
return inlineEditing(entity);
} else {
return true;
}
}
const onRowClick = ({ rowData }: any) => {
const entity = rowData as Entity<M>;
if (checkInlineEditing(entity))
return;
return onEntityClick && onEntityClick(entity);
};
const cellRenderer = ({
column,
columnIndex,
rowData,
rowIndex
}: any) => {
const entity: Entity<M> = rowData;
if (columnIndex === 0) {
return buildIdColumn({
size,
entity
});
}
if (column.type === "property") {
const name = column.dataKey as keyof M;
const propertyOrBuilder = schema.properties[name];
const property: Property<any> = buildPropertyFrom<CMSType, M>(propertyOrBuilder, entity.values, entity.id);
const usedPropertyBuilder = typeof propertyOrBuilder === "function";
const inlineEditingEnabled = checkInlineEditing(entity);
if (!inlineEditingEnabled) {
return (
<TableCell
key={`preview_cell_${name}_${rowIndex}_${columnIndex}`}
size={size}
align={column.align}
disabled={true}>
<PreviewComponent
width={column.width}
height={column.height}
name={`preview_${name}_${rowIndex}_${columnIndex}`}
property={property}
value={entity.values[name]}
size={getPreviewSizeFrom(size)}
/>
</TableCell>
);
} else {
const openPopup = (cellRect: DOMRect | undefined) => {
if (!cellRect) {
setPopupCell(undefined);
} else {
setPopupCell({
columnIndex,
// rowIndex,
width: column.width,
height: column.height,
entity,
cellRect,
name: name,
property,
usedPropertyBuilder
});
}
updatePopup(true);
};
const onSelect = (cellRect: DOMRect | undefined) => {
if (!cellRect) {
select(undefined);
} else {
const selectedConfig = {
columnIndex,
// rowIndex,
width: column.width,
height: column.height,
entity,
cellRect,
name: name,
property,
usedPropertyBuilder
};
select(selectedConfig);
}
};
const selected = selectedCell?.columnIndex === columnIndex
&& selectedCell?.entity.id === entity.id;
const isFocused = selected && focused;
const customFieldValidator: CustomFieldValidator | undefined = uniqueFieldValidator
? ({ name, value, property }) => uniqueFieldValidator({
name, value, property, entityId: entity.id
}) : undefined;
const validation = mapPropertyToYup({
property,
customFieldValidator,
name
});
const onValueChange = onCellValueChange
? (props: OnCellChangeParams<any>) => onCellValueChange({
...props,
entity
})
: undefined;
return entity ?
<PropertyTableCell
key={`table_cell_${name}_${rowIndex}_${columnIndex}`}
size={size}
align={column.align}
name={name as string}
validation={validation}
onValueChange={onValueChange}
selected={selected}
focused={isFocused}
setPreventOutsideClick={setPreventOutsideClick}
setFocused={setFocused}
value={entity?.values ? entity.values[name] : undefined}
property={property}
openPopup={openPopup}
select={onSelect}
width={column.width}
height={column.height}/>
:
<SkeletonComponent property={property}
size={getPreviewSizeFrom(size)}/>;
}
} else if (column.type === "additional") {
return (
<TableCell
focused={false}
selected={false}
disabled={true}
size={size}
align={"left"}
allowScroll={false}
showExpandIcon={false}
disabledTooltip={"Additional columns can't be edited directly"}
>
<ErrorBoundary>
{(additionalColumnsMap[column.dataKey as AdditionalKey]).builder({
entity,
context
})}
</ErrorBoundary>
</TableCell>
);
} else {
return <Box>Internal ERROR</Box>;
}
};
const headerRenderer = ({ columnIndex }: any) => {
const column = columns[columnIndex - 1];
const filterForThisProperty: [WhereFilterOp, any] | undefined =
column && column.type === "property" && filterValues && filterValues[column.id] ?
filterValues[column.id]
: undefined;
const onPropertyFilterUpdate = (filterForProperty?: [WhereFilterOp, any]) => {
let newFilterValue = filterValues ? { ...filterValues } : {};
if (!filterForProperty) {
delete newFilterValue[column.id];
} else {
newFilterValue[column.id] = filterForProperty;
}
const isNewFilterCombinationValid = isFilterCombinationValid(newFilterValue, filterCombinations, sortByProperty, currentSort);
if (!isNewFilterCombinationValid) {
newFilterValue = filterForProperty ? { [column.id]: filterForProperty } as FilterValues<M> : {};
}
setFilterValues(newFilterValue);
if (column.id !== sortByProperty) {
resetSort();
}
};
return (
<ErrorBoundary>
{columnIndex === 0 ?
<div className={classes.header}
style={{
display: "flex",
justifyContent: "center",
alignItems: "center"
}}>
Id
</div>
:
<CollectionTableHeader
onFilterUpdate={onPropertyFilterUpdate}
filter={filterForThisProperty}
sort={sortByProperty === column.id ? currentSort : undefined}
onColumnSort={onColumnSort}
column={column}/>
}
</ErrorBoundary>
);
};
function buildErrorView<M extends { [Key: string]: any }>() {
return (
<Paper className={classes.root}>
<Box display="flex"
flexDirection={"column"}
justifyContent="center"
margin={6}>
<Typography variant={"h6"}>
{"Error fetching data from the data source"}
</Typography>
{dataLoadingError?.name && <Typography>
{dataLoadingError?.name}
</Typography>}
{dataLoadingError?.message && <Typography>
{dataLoadingError?.message}
</Typography>}
</Box>
</Paper>
);
}
function buildEmptyView<M extends { [Key: string]: any }>() {
if (dataLoading)
return <CircularProgressCenter/>;
return (
<Box display="flex"
flexDirection={"column"}
alignItems="center"
justifyContent="center"
width={"100%"}
height={"100%"}
padding={2}>
<Box padding={1}>
<AssignmentIcon/>
</Box>
<Typography>
{textSearchInProgress ? "No results" : (filterIsSet ? "No data with the selected filters" : "This collection is empty")}
</Typography>
</Box>
);
}
const body =
(
<Measure
bounds
onResize={setTableSize}>
{({ measureRef }) => (
<div ref={measureRef}
className={classes.tableContainer}>
{tableSize?.bounds &&
<BaseTable
rowClassName={`${classes.tableRow} ${classes.tableRowClickable}`}
data={data}
width={tableSize.bounds.width}
height={tableSize.bounds.height}
emptyRenderer={dataLoadingError ? buildErrorView() : buildEmptyView()}
fixed
ignoreFunctionInColumnCompare={false}
rowHeight={getRowHeight(size)}
ref={tableRef}
overscanRowCount={2}
onEndReachedThreshold={PIXEL_NEXT_PAGE_OFFSET}
onEndReached={loadNextPage}
components={{
TableCell: Cell
}}
rowEventHandlers={
{ onClick: onRowClick }
}
>
<Column
headerRenderer={headerRenderer}
cellRenderer={cellRenderer}
align={"center"}
key={"header-id"}
dataKey={"id"}
flexShrink={0}
frozen={frozenIdColumn ? "left" : undefined}
width={160}/>
{columns.map((column) =>
<Column
key={column.id}
type={column.type}
title={column.label}
className={classes.column}
headerRenderer={headerRenderer}
cellRenderer={cellRenderer}
height={getRowHeight(size)}
align={column.align}
flexGrow={1}
flexShrink={0}
resizable={true}
size={size}
dataKey={column.id}
width={column.width}/>)
}
</BaseTable>}
</div>
)}
</Measure>
);
const customFieldValidator: CustomFieldValidator | undefined = uniqueFieldValidator
? ({ name, value, property }) => uniqueFieldValidator({
name,
value,
property,
entityId: selectedCell?.entity.id
})
: undefined;
return (
<>
<Paper className={classes.root}>
<CollectionTableToolbar schema={schema}
filterIsSet={filterIsSet}
onTextSearch={textSearchEnabled ? setSearchString : undefined}
clearFilter={clearFilter}
actions={actions}
size={size}
onSizeChanged={setSize}
title={title}
loading={dataLoading}/>
<PopupFormField
cellRect={popupCell?.cellRect}
columnIndex={popupCell?.columnIndex}
name={popupCell?.name}
property={popupCell?.property}
usedPropertyBuilder={popupCell?.usedPropertyBuilder ?? false}
entity={popupCell?.entity}
tableKey={tableKey}
customFieldValidator={customFieldValidator}
schema={schema}
path={path}
formPopupOpen={formPopupOpen}
onCellValueChange={onCellValueChange}
setPreventOutsideClick={setPreventOutsideClick}
setFormPopupOpen={updatePopup}
/>
<OutsideAlerter enabled={!preventOutsideClick}
onOutsideClick={handleClickOutside}>
{body}
</OutsideAlerter>
</Paper>
</>
);
}
function isFilterCombinationValid<M extends { [Key: string]: any }>(filterValues: FilterValues<M>, indexes?: FilterCombination<Extract<keyof M, string>>[], sortKey?: keyof M, sortDirection?: "asc" | "desc"): boolean {
// Order by clause cannot contain a field with an equality filter available
const values: [WhereFilterOp, any][] = Object.values(filterValues) as [WhereFilterOp, any][];
if (sortKey && values.map((v) => v[0]).includes("==")) {
return false;
}
const filterKeys = Object.keys(filterValues);
const filtersCount = filterKeys.length;
if (!indexes && filtersCount > 1)
return false;
// only one filter set, different to the sort key
if (sortKey && filtersCount === 1 && filterKeys[0] !== sortKey)
return false;
return !!indexes && indexes
.filter((compositeIndex) => !sortKey || sortKey in compositeIndex)
.find((compositeIndex) =>
Object.entries(filterValues).every(([key, value]) => compositeIndex[key] !== undefined && (!sortDirection || compositeIndex[key] === sortDirection))
) !== undefined;
}
const Cell = ({ className, cellData }: any) => {
console.log("Cell", className, cellData);
return <div className={className}>{cellData}</div>;
}; | the_stack |
import { HttpResponse } from "@azure-rest/core-client";
import {
AzureKeyVault,
ErrorResponseModel,
AzureKeyVaultList,
ClassificationRule,
ClassificationRuleList,
OperationResponse,
DataSource,
DataSourceList,
Filter,
Scan,
ScanList,
ScanHistoryList,
ScanRuleset,
ScanRulesetList,
SystemScanRulesetList,
SystemScanRuleset,
Trigger,
} from "./models";
/** Gets key vault information */
export interface KeyVaultConnectionsGet200Response extends HttpResponse {
status: "200";
body: AzureKeyVault;
}
/** Gets key vault information */
export interface KeyVaultConnectionsGetdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Creates an instance of a key vault connection */
export interface KeyVaultConnectionsCreate200Response extends HttpResponse {
status: "200";
body: AzureKeyVault;
}
/** Creates an instance of a key vault connection */
export interface KeyVaultConnectionsCreatedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Deletes the key vault connection associated with the account */
export interface KeyVaultConnectionsDelete200Response extends HttpResponse {
status: "200";
body: AzureKeyVault;
}
/** Deletes the key vault connection associated with the account */
export interface KeyVaultConnectionsDelete204Response extends HttpResponse {
status: "204";
body: Record<string, unknown>;
}
/** Deletes the key vault connection associated with the account */
export interface KeyVaultConnectionsDeletedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** List key vault connections in account */
export interface KeyVaultConnectionsListAll200Response extends HttpResponse {
status: "200";
body: AzureKeyVaultList;
}
/** List key vault connections in account */
export interface KeyVaultConnectionsListAlldefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Get a classification rule */
export interface ClassificationRulesGet200Response extends HttpResponse {
status: "200";
body: ClassificationRule;
}
/** Get a classification rule */
export interface ClassificationRulesGetdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Creates or Updates a classification rule */
export interface ClassificationRulesCreateOrUpdate200Response extends HttpResponse {
status: "200";
body: ClassificationRule;
}
/** Creates or Updates a classification rule */
export interface ClassificationRulesCreateOrUpdate201Response extends HttpResponse {
status: "201";
body: ClassificationRule;
}
/** Creates or Updates a classification rule */
export interface ClassificationRulesCreateOrUpdatedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Deletes a classification rule */
export interface ClassificationRulesDelete200Response extends HttpResponse {
status: "200";
body: ClassificationRule;
}
/** Deletes a classification rule */
export interface ClassificationRulesDelete204Response extends HttpResponse {
status: "204";
body: Record<string, unknown>;
}
/** Deletes a classification rule */
export interface ClassificationRulesDeletedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** List classification rules in Account */
export interface ClassificationRulesListAll200Response extends HttpResponse {
status: "200";
body: ClassificationRuleList;
}
/** List classification rules in Account */
export interface ClassificationRulesListAlldefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Lists the rule versions of a classification rule */
export interface ClassificationRulesListVersionsByClassificationRuleName200Response
extends HttpResponse {
status: "200";
body: ClassificationRuleList;
}
/** Lists the rule versions of a classification rule */
export interface ClassificationRulesListVersionsByClassificationRuleNamedefaultResponse
extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Sets Classification Action on a specific classification rule version. */
export interface ClassificationRulesTagClassificationVersion202Response extends HttpResponse {
status: "202";
body: OperationResponse;
}
/** Sets Classification Action on a specific classification rule version. */
export interface ClassificationRulesTagClassificationVersiondefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Creates or Updates a data source */
export interface DataSourcesCreateOrUpdate200Response extends HttpResponse {
status: "200";
body: DataSource;
}
/** Creates or Updates a data source */
export interface DataSourcesCreateOrUpdate201Response extends HttpResponse {
status: "201";
body: DataSource;
}
/** Creates or Updates a data source */
export interface DataSourcesCreateOrUpdatedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Get a data source */
export interface DataSourcesGet200Response extends HttpResponse {
status: "200";
body: DataSource;
}
/** Get a data source */
export interface DataSourcesGetdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Deletes a data source */
export interface DataSourcesDelete200Response extends HttpResponse {
status: "200";
body: DataSource;
}
/** Deletes a data source */
export interface DataSourcesDelete204Response extends HttpResponse {
status: "204";
body: Record<string, unknown>;
}
/** Deletes a data source */
export interface DataSourcesDeletedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** List data sources in Data catalog */
export interface DataSourcesListAll200Response extends HttpResponse {
status: "200";
body: DataSourceList;
}
/** List data sources in Data catalog */
export interface DataSourcesListAlldefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Get a filter */
export interface FiltersGet200Response extends HttpResponse {
status: "200";
body: Filter;
}
/** Get a filter */
export interface FiltersGetdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Creates or updates a filter */
export interface FiltersCreateOrUpdate200Response extends HttpResponse {
status: "200";
body: Filter;
}
/** Creates or updates a filter */
export interface FiltersCreateOrUpdate201Response extends HttpResponse {
status: "201";
body: Filter;
}
/** Creates or updates a filter */
export interface FiltersCreateOrUpdatedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Creates an instance of a scan */
export interface ScansCreateOrUpdate200Response extends HttpResponse {
status: "200";
body: Scan;
}
/** Creates an instance of a scan */
export interface ScansCreateOrUpdate201Response extends HttpResponse {
status: "201";
body: Scan;
}
/** Creates an instance of a scan */
export interface ScansCreateOrUpdatedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Gets a scan information */
export interface ScansGet200Response extends HttpResponse {
status: "200";
body: Scan;
}
/** Gets a scan information */
export interface ScansGetdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Deletes the scan associated with the data source */
export interface ScansDelete200Response extends HttpResponse {
status: "200";
body: Scan;
}
/** Deletes the scan associated with the data source */
export interface ScansDelete204Response extends HttpResponse {
status: "204";
body: Record<string, unknown>;
}
/** Deletes the scan associated with the data source */
export interface ScansDeletedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** List scans in data source */
export interface ScansListByDataSource200Response extends HttpResponse {
status: "200";
body: ScanList;
}
/** List scans in data source */
export interface ScansListByDataSourcedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Runs the scan */
export interface ScanResultRunScan202Response extends HttpResponse {
status: "202";
body: OperationResponse;
}
/** Runs the scan */
export interface ScanResultRunScandefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Cancels a scan */
export interface ScanResultCancelScan202Response extends HttpResponse {
status: "202";
body: OperationResponse;
}
/** Cancels a scan */
export interface ScanResultCancelScandefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Lists the scan history of a scan */
export interface ScanResultListScanHistory200Response extends HttpResponse {
status: "200";
body: ScanHistoryList;
}
/** Lists the scan history of a scan */
export interface ScanResultListScanHistorydefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Get a scan ruleset */
export interface ScanRulesetsGet200Response extends HttpResponse {
status: "200";
body: ScanRuleset;
}
/** Get a scan ruleset */
export interface ScanRulesetsGetdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Creates or Updates a scan ruleset */
export interface ScanRulesetsCreateOrUpdate200Response extends HttpResponse {
status: "200";
body: ScanRuleset;
}
/** Creates or Updates a scan ruleset */
export interface ScanRulesetsCreateOrUpdate201Response extends HttpResponse {
status: "201";
body: ScanRuleset;
}
/** Creates or Updates a scan ruleset */
export interface ScanRulesetsCreateOrUpdatedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Deletes a scan ruleset */
export interface ScanRulesetsDelete200Response extends HttpResponse {
status: "200";
body: ScanRuleset;
}
/** Deletes a scan ruleset */
export interface ScanRulesetsDelete204Response extends HttpResponse {
status: "204";
body: Record<string, unknown>;
}
/** Deletes a scan ruleset */
export interface ScanRulesetsDeletedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** List scan rulesets in Data catalog */
export interface ScanRulesetsListAll200Response extends HttpResponse {
status: "200";
body: ScanRulesetList;
}
/** List scan rulesets in Data catalog */
export interface ScanRulesetsListAlldefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** List all system scan rulesets for an account */
export interface SystemScanRulesetsListAll200Response extends HttpResponse {
status: "200";
body: SystemScanRulesetList;
}
/** List all system scan rulesets for an account */
export interface SystemScanRulesetsListAlldefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Get a system scan ruleset for a data source */
export interface SystemScanRulesetsGet200Response extends HttpResponse {
status: "200";
body: SystemScanRuleset;
}
/** Get a system scan ruleset for a data source */
export interface SystemScanRulesetsGetdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Get a scan ruleset by version */
export interface SystemScanRulesetsGetByVersion200Response extends HttpResponse {
status: "200";
body: SystemScanRuleset;
}
/** Get a scan ruleset by version */
export interface SystemScanRulesetsGetByVersiondefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Get the latest version of a system scan ruleset */
export interface SystemScanRulesetsGetLatest200Response extends HttpResponse {
status: "200";
body: SystemScanRuleset;
}
/** Get the latest version of a system scan ruleset */
export interface SystemScanRulesetsGetLatestdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** List system scan ruleset versions in Data catalog */
export interface SystemScanRulesetsListVersionsByDataSource200Response extends HttpResponse {
status: "200";
body: SystemScanRulesetList;
}
/** List system scan ruleset versions in Data catalog */
export interface SystemScanRulesetsListVersionsByDataSourcedefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Gets trigger information */
export interface TriggersGetTrigger200Response extends HttpResponse {
status: "200";
body: Trigger;
}
/** Gets trigger information */
export interface TriggersGetTriggerdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Creates an instance of a trigger */
export interface TriggersCreateTrigger200Response extends HttpResponse {
status: "200";
body: Trigger;
}
/** Creates an instance of a trigger */
export interface TriggersCreateTrigger201Response extends HttpResponse {
status: "201";
body: Trigger;
}
/** Creates an instance of a trigger */
export interface TriggersCreateTriggerdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
}
/** Deletes the trigger associated with the scan */
export interface TriggersDeleteTrigger200Response extends HttpResponse {
status: "200";
body: Trigger;
}
/** Deletes the trigger associated with the scan */
export interface TriggersDeleteTrigger204Response extends HttpResponse {
status: "204";
body: Record<string, unknown>;
}
/** Deletes the trigger associated with the scan */
export interface TriggersDeleteTriggerdefaultResponse extends HttpResponse {
status: "500";
body: ErrorResponseModel;
} | the_stack |
import {
useMyPresence,
useOthers,
useList,
RoomProvider,
useMap,
useHistory,
useBatch,
} from "@liveblocks/react";
import { LiveList, LiveMap, LiveObject } from "@liveblocks/client";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import {
Color,
Layer,
LayerType,
CanvasState,
CanvasMode,
Presence,
Camera,
Side,
XYWH,
Point,
} from "./types";
import styles from "./index.module.css";
import {
colorToCss,
connectionIdToColor,
findIntersectingLayersWithRectangle,
getSelectedLayers,
penPointsToPathLayer,
pointerEventToCanvasPoint,
resizeBounds,
} from "./utils";
import SelectionBox from "./SelectionBox";
import { nanoid } from "nanoid";
import LayerComponent from "./LayerComponent";
import SelectionTools from "./SelectionTools";
import LoadingIndicator from "../components/LoadingIndicator";
import useSelectionBounds from "./useSelectionBounds";
import useDisableScrollBounce from "./useDisableScrollBounce";
import MultiplayerGuides from "./MultiplayerGuides";
import Path from "./Path";
import ToolsBar from "./ToolsBar";
const MAX_LAYERS = 100;
export default function Room() {
return (
<RoomProvider
id={"multiplayer-canvas"}
defaultPresence={() => ({
selection: [],
penPoints: null,
penColor: null,
})}
>
<div className={styles.container}>
<WhiteboardTool />
</div>
</RoomProvider>
);
}
function WhiteboardTool() {
// layers is a LiveMap that contains all the shapes drawn on the canvas
const layers = useMap<string, LiveObject<Layer>>("layers");
// layerIds is LiveList of all the layer ids ordered by their z-index
const layerIds = useList<string>("layerIds");
if (layerIds == null || layers == null) {
return <LoadingIndicator />;
}
return <Canvas layers={layers} layerIds={layerIds} />;
}
function Canvas({
layerIds,
layers,
}: {
layerIds: LiveList<string>;
layers: LiveMap<string, LiveObject<Layer>>;
}) {
const [{ selection, pencilDraft }, setPresence] = useMyPresence<Presence>();
const [canvasState, setState] = useState<CanvasState>({
mode: CanvasMode.None,
});
const [camera, setCamera] = useState<Camera>({ x: 0, y: 0 });
const [lastUsedColor, setLastUsedColor] = useState<Color>({
r: 252,
g: 142,
b: 42,
});
const batch = useBatch();
const history = useHistory();
const selectionBounds = useSelectionBounds(layers, selection);
useDisableScrollBounce();
/**
* Delete all the selected layers.
*/
const deleteLayers = useCallback(() => {
batch(() => {
for (const id of selection) {
// Delete the layer from the layers LiveMap
layers.delete(id);
// Find the layer index in the z-index list and remove it
const index = layerIds.indexOf(id);
if (index !== -1) {
layerIds.delete(index);
}
}
});
}, [layerIds, layers, selection]);
/**
* Hook used to listen to Undo / Redo and delete selected layers
*/
useEffect(() => {
function onKeyDown(e: KeyboardEvent) {
switch (e.key) {
case "Backspace": {
deleteLayers();
break;
}
case "z": {
if (e.ctrlKey || e.metaKey) {
if (e.shiftKey) {
history.redo();
} else {
history.undo();
}
break;
}
}
}
}
document.addEventListener("keydown", onKeyDown);
return () => {
document.removeEventListener("keydown", onKeyDown);
};
}, [selection, deleteLayers, history]);
/**
* Change the color of all the selected layers
*/
const setFill = useCallback(
(fill: Color) => {
setLastUsedColor(fill);
const selectedLayers = getSelectedLayers(layers, selection);
batch(() => {
for (const layer of selectedLayers) {
layer.set("fill", fill);
}
});
},
[layers, selection, setLastUsedColor]
);
/**
* Select the layer if not already selected and start translating the selection
*/
const onLayerPointerDown = useCallback(
(e: React.PointerEvent, layerId: string) => {
if (
canvasState.mode === CanvasMode.Pencil ||
canvasState.mode === CanvasMode.Inserting
) {
return;
}
history.pause();
e.stopPropagation();
const point = pointerEventToCanvasPoint(e, camera);
if (!selection.includes(layerId)) {
setPresence({ selection: [layerId] }, { addToHistory: true });
}
setState({ mode: CanvasMode.Translating, current: point });
},
[setPresence, setState, selection, camera, history, canvasState.mode]
);
/**
* Move all the selected layers to the front
*/
const moveToFront = useCallback(() => {
batch(() => {
const indices: number[] = [];
const arr = layerIds.toArray();
for (let i = 0; i < arr.length; i++) {
if (selection.includes(arr[i])) {
indices.push(i);
}
}
for (let i = indices.length - 1; i >= 0; i--) {
layerIds.move(indices[i], arr.length - 1 - (indices.length - 1 - i));
}
});
}, [layerIds, selection]);
/**
* Move all the selected layers to the back
*/
const moveToBack = useCallback(() => {
batch(() => {
const indices: number[] = [];
const arr = layerIds.toArray();
for (let i = 0; i < arr.length; i++) {
if (selection.includes(arr[i])) {
indices.push(i);
}
}
for (let i = 0; i < indices.length; i++) {
layerIds.move(indices[i], i);
}
});
}, [layerIds, selection]);
/**
* Start resizing the layer
*/
const onResizeHandlePointerDown = useCallback(
(corner: Side, initialBounds: XYWH) => {
history.pause();
setState({
mode: CanvasMode.Resizing,
initialBounds,
corner,
});
},
[history]
);
/**
* Insert an ellipse or a rectangle at the given position and select it
*/
const insertLayer = useCallback(
(layerType: LayerType.Ellipse | LayerType.Rectangle, position: Point) => {
if (layers.size >= MAX_LAYERS) {
return;
}
batch(() => {
const layerId = nanoid();
const layer = new LiveObject({
type: layerType,
x: position.x,
y: position.y,
height: 100,
width: 100,
fill: lastUsedColor,
});
layerIds.push(layerId);
layers.set(layerId, layer);
setPresence({ selection: [layerId] }, { addToHistory: true });
setState({ mode: CanvasMode.None });
});
},
[batch, layerIds, layers, setPresence, lastUsedColor]
);
/**
* Transform the drawing of the current user in a layer and reset the presence to delete the draft.
*/
const insertPath = useCallback(() => {
if (
pencilDraft == null ||
pencilDraft.length < 2 ||
layers.size >= MAX_LAYERS
) {
setPresence({ pencilDraft: null });
return;
}
batch(() => {
const id = nanoid();
layers.set(
id,
new LiveObject(penPointsToPathLayer(pencilDraft, lastUsedColor))
);
layerIds.push(id);
setPresence({ pencilDraft: null });
setState({ mode: CanvasMode.Pencil });
});
}, [layers, setPresence, batch, layerIds, lastUsedColor, pencilDraft]);
/**
* Move selected layers on the canvas
*/
const translateSelectedLayers = useCallback(
(point: Point) => {
if (canvasState.mode !== CanvasMode.Translating) {
return;
}
batch(() => {
const offset = {
x: point.x - canvasState.current.x,
y: point.y - canvasState.current.y,
};
for (const id of selection) {
const layer = layers.get(id);
if (layer) {
layer.update({
x: layer.get("x") + offset.x,
y: layer.get("y") + offset.y,
});
}
}
setState({ mode: CanvasMode.Translating, current: point });
});
},
[layers, canvasState, selection, batch]
);
/**
* Resize selected layer. Only resizing a single layer is allowed.
*/
const resizeSelectedLayer = useCallback(
(point: Point) => {
if (canvasState.mode !== CanvasMode.Resizing) {
return;
}
const bounds = resizeBounds(
canvasState.initialBounds,
canvasState.corner,
point
);
const layer = layers.get(selection[0]);
if (layer) {
layer.update(bounds);
}
},
[canvasState, layers]
);
const unselectLayers = useCallback(() => {
setPresence({ selection: [] }, { addToHistory: true });
}, [setPresence]);
/**
* Insert the first path point and start drawing with the pencil
*/
const startDrawing = useCallback(
(point: Point, pressure: number) => {
setPresence({
pencilDraft: [[point.x, point.y, pressure]],
penColor: lastUsedColor,
});
},
[setPresence]
);
/**
* Continue the drawing and send the current draft to other users in the room
*/
const continueDrawing = useCallback(
(point: Point, e: React.PointerEvent) => {
if (
canvasState.mode !== CanvasMode.Pencil ||
e.buttons !== 1 ||
pencilDraft == null
) {
return;
}
setPresence({
cursor: point,
pencilDraft:
pencilDraft.length === 1 &&
pencilDraft[0][0] === point.x &&
pencilDraft[0][1] === point.y
? pencilDraft
: [...pencilDraft, [point.x, point.y, e.pressure]],
});
},
[canvasState.mode, setPresence, pencilDraft]
);
/**
* Start multiselection with the selection net if the pointer move enough since pressed
*/
const startMultiSelection = useCallback((current: Point, origin: Point) => {
// If the distance between the pointer position and the pointer position when it was pressed
if (Math.abs(current.x - origin.x) + Math.abs(current.y - origin.y) > 5) {
// Start multi selection
setState({
mode: CanvasMode.SelectionNet,
origin,
current,
});
}
}, []);
/**
* Update the position of the selection net and select the layers accordingly
*/
const updateSelectionNet = useCallback(
(current: Point, origin: Point) => {
setState({
mode: CanvasMode.SelectionNet,
origin: origin,
current,
});
const ids = findIntersectingLayersWithRectangle(
layerIds,
layers,
origin,
current
);
setPresence({ selection: ids });
},
[layers, layerIds, setPresence]
);
// TODO: Expose a hook to observe only one key of the others presence to improve performance
// For example, multiplayer selection should not be re-render if only a cursor move
const others = useOthers<Presence>();
/**
* Create a map layerId to color based on the selection of all the users in the room
*/
const layerIdsToColorSelection = useMemo(() => {
const layerIdsToColorSelection: Record<string, string> = {};
const users = others.toArray();
for (const user of users) {
const selection = user.presence?.selection;
if (selection == null || selection.length === 0) {
continue;
}
for (const id of selection) {
layerIdsToColorSelection[id] = connectionIdToColor(user.connectionId);
}
}
return layerIdsToColorSelection;
}, [others]);
return (
<>
<div className={styles.canvas}>
{selectionBounds && (
<SelectionTools
isAnimated={
canvasState.mode !== CanvasMode.Translating &&
canvasState.mode !== CanvasMode.Resizing
}
x={selectionBounds.width / 2 + selectionBounds.x + camera.x}
y={selectionBounds.y + camera.y}
setFill={setFill}
moveToFront={moveToFront}
moveToBack={moveToBack}
deleteItems={deleteLayers}
/>
)}
<svg
className={styles.renderer_svg}
onWheel={(e) => {
// Pan the camera based on the wheel delta
setCamera((camera) => ({
x: camera.x - e.deltaX,
y: camera.y - e.deltaY,
}));
}}
onPointerDown={(e) => {
const point = pointerEventToCanvasPoint(e, camera);
if (canvasState.mode === CanvasMode.Inserting) {
return;
}
if (canvasState.mode === CanvasMode.Pencil) {
startDrawing(point, e.pressure);
return;
}
setState({ origin: point, mode: CanvasMode.Pressing });
}}
onPointerLeave={(e) => {
setPresence({ cursor: null });
}}
onPointerMove={(e) => {
e.preventDefault();
const current = pointerEventToCanvasPoint(e, camera);
if (canvasState.mode === CanvasMode.Pressing) {
startMultiSelection(current, canvasState.origin);
} else if (canvasState.mode === CanvasMode.SelectionNet) {
updateSelectionNet(current, canvasState.origin);
} else if (canvasState.mode === CanvasMode.Translating) {
translateSelectedLayers(current);
} else if (canvasState.mode === CanvasMode.Resizing) {
resizeSelectedLayer(current);
} else if (canvasState.mode === CanvasMode.Pencil) {
continueDrawing(current, e);
}
setPresence({ cursor: current });
}}
onPointerUp={(e) => {
const point = pointerEventToCanvasPoint(e, camera);
if (
canvasState.mode === CanvasMode.None ||
canvasState.mode === CanvasMode.Pressing
) {
unselectLayers();
setState({
mode: CanvasMode.None,
});
} else if (canvasState.mode === CanvasMode.Pencil) {
insertPath();
} else if (canvasState.mode === CanvasMode.Inserting) {
insertLayer(canvasState.layerType, point);
} else {
setState({
mode: CanvasMode.None,
});
}
history.resume();
}}
>
<g
style={{
transform: `translate(${camera.x}px, ${camera.y}px)`,
}}
>
{layerIds.map((layerId) => {
const layer = layers.get(layerId);
if (layer == null) {
return null;
}
return (
<LayerComponent
key={layerId}
id={layerId}
mode={canvasState.mode}
onLayerPointerDown={onLayerPointerDown}
layer={layer}
selectionColor={layerIdsToColorSelection[layerId]}
/>
);
})}
{/* Blue square that show the selection of the current users. Also contains the resize handles. */}
{selectionBounds && (
<SelectionBox
selection={selection}
bounds={selectionBounds}
layers={layers}
onResizeHandlePointerDown={onResizeHandlePointerDown}
isAnimated={
canvasState.mode !== CanvasMode.Translating &&
canvasState.mode !== CanvasMode.Resizing
}
/>
)}
{/* Selection net that appears when the user is selecting multiple layers at once */}
{canvasState.mode === CanvasMode.SelectionNet &&
canvasState.current != null && (
<rect
className={styles.selection_net}
x={Math.min(canvasState.origin.x, canvasState.current.x)}
y={Math.min(canvasState.origin.y, canvasState.current.y)}
width={Math.abs(canvasState.origin.x - canvasState.current.x)}
height={Math.abs(
canvasState.origin.y - canvasState.current.y
)}
/>
)}
<MultiplayerGuides />
{/* Drawing in progress. Still not commited to the storage. */}
{pencilDraft != null && pencilDraft.length > 0 && (
<Path
points={pencilDraft}
fill={colorToCss(lastUsedColor)}
x={0}
y={0}
/>
)}
</g>
</svg>
</div>
<ToolsBar
canvasState={canvasState}
setCanvasState={setState}
undo={history.undo}
redo={history.redo}
/>
</>
);
} | the_stack |
import Crowi from 'server/crowi'
import { Types, Document, Model, Schema, model } from 'mongoose'
import Debug from 'debug'
import mongoosePaginate from 'mongoose-paginate'
import crypto from 'crypto'
import async from 'async'
import { googleLoginEnabled, githubLoginEnabled, isDisabledPasswordAuth } from 'server/models/config'
const STATUS_REGISTERED = 1
const STATUS_ACTIVE = 2
const STATUS_SUSPENDED = 3
const STATUS_DELETED = 4
const STATUS_INVITED = 5
const LANG_EN = 'en'
const LANG_EN_US = 'en-US'
const LANG_EN_GB = 'en-GB'
const LANG_JA = 'ja'
const PAGE_ITEMS = 50
export interface UserDocument extends Document {
_id: Types.ObjectId
userId: string
image: string | null
googleId: string | null
githubId: string | null
name: string
username: string
email: string
introduction: string
password: string
apiToken: string
lang: 'en' | 'en-US' | 'en-GB' | 'ja'
status: number
createdAt: Date
admin: boolean
isPasswordSet(): boolean
isPasswordValid(password: string): boolean
setPassword(password: string): this
isEmailSet(): boolean
updatePassword(password: string, callback: (err: Error, userData: UserDocument) => void): any
updateApiToken(): Promise<UserDocument>
updateImage(image, callback: (err: Error, userData: UserDocument) => void): any
updateEmail(email: string): any
updateNameAndEmail(name: string, email: string): any
deleteImage(callback): any
updateGoogleId(googleId): Promise<UserDocument>
deleteGoogleId(): Promise<UserDocument>
updateGitHubId(githubId): Promise<UserDocument>
deleteGitHubId(): Promise<UserDocument>
countValidThirdPartyIds(): number
hasValidThirdPartyId(): boolean
canDisconnectThirdPartyId(): boolean
activateInvitedUser(username, name, password, callback: (err: Error, userData: UserDocument) => void): any
removeFromAdmin(callback: (err: Error, userData: UserDocument) => void): any
makeAdmin(callback: (err: Error, userData: UserDocument) => void): any
statusActivate(callback: (err: Error, userData: UserDocument) => void): any
statusSuspend(callback: (err: Error, userData: UserDocument) => void): any
statusDelete(callback: (err: Error, userData: UserDocument) => void): any
populateSecrets(): Promise<any>
}
export interface UserModel extends Model<UserDocument> {
paginate: any
getLanguageLabels(): Record<string, string>
getUserStatusLabels(): any
isEmailValid(email): boolean
isGitHubAccountValid(organizations): boolean
findUsers(options, callback: (err: Error, userData: UserDocument[]) => void)
findAllUsers(options?): Promise<UserDocument[]>
findUsersByIds(ids, options?): Promise<UserDocument[]>
findAdmins(callback: (err: Error, admins: UserDocument[]) => void): void
findUsersWithPagination(options, query, callback): any
findUsersByPartOfEmail(emailPart, options): any
findUserByUsername(username): Promise<UserDocument | null>
findUserByApiToken(apiToken): Promise<UserDocument | null>
findUserByGoogleId(googleId): Promise<UserDocument | null>
findUserByGitHubId(githubId): Promise<UserDocument | null>
findUserByEmail(email): Promise<UserDocument | null>
findUserByEmailAndPassword(email: string, password: string): Promise<UserDocument | null>
isRegisterableUsername(username, callback: (registerable: boolean) => void): void
isRegisterable(email, username, callback: (registerable: boolean, detail: { email?: boolean; username?: boolean }) => void): void
removeCompletelyById(id, callback: (err: Error | null, userData: 1 | null) => void): any
resetPasswordByRandomString(id: Types.ObjectId): Promise<{ user: UserDocument; newPassword: string }>
createUsersByInvitation(emailList, toSendEmail, callback): any
createUserByEmailAndPassword(name, username, email, password, lang, callback): any
createUserPictureFilePath(user: UserDocument, ext: string): string
getUsernameByPath(path): string | null
STATUS_REGISTERED: number
STATUS_ACTIVE: number
STATUS_SUSPENDED: number
STATUS_DELETED: number
STATUS_INVITED: number
PAGE_ITEMS: number
LANG_EN: string
LANG_EN_US: string
LANG_EN_GB: string
LANG_JA: string
}
export default (crowi: Crowi) => {
const debug = Debug('crowi:models:user')
const userEvent = crowi.event('User')
const userSchema = new Schema<UserDocument, UserModel>({
userId: String,
image: String,
googleId: String,
githubId: String,
name: { type: String, index: true },
username: { type: String, index: true },
email: { type: String, required: true, index: true },
introduction: { type: String },
password: { type: String, select: false },
apiToken: { type: String, select: false },
lang: {
type: String,
enum: Object.values(getLanguageLabels()),
default: LANG_EN_US,
},
status: { type: Number, required: true, default: STATUS_ACTIVE, index: true },
createdAt: { type: Date, default: Date.now },
admin: { type: Boolean, default: 0, index: true },
})
userSchema.plugin(mongoosePaginate)
userEvent.on('activated', userEvent.onActivated)
function decideUserStatusOnRegistration() {
const Config = crowi.model('Config')
const config = crowi.getConfig()
if (!config.crowi) {
return STATUS_ACTIVE // is this ok?
}
// status decided depends on registrationMode
switch (config.crowi['security:registrationMode']) {
case Config.SECURITY_REGISTRATION_MODE_OPEN:
return STATUS_ACTIVE
case Config.SECURITY_REGISTRATION_MODE_RESTRICTED:
case Config.SECURITY_REGISTRATION_MODE_CLOSED: // 一応
return STATUS_REGISTERED
default:
return STATUS_ACTIVE // どっちにすんのがいいんだろうな
}
}
function generateRandomTempPassword() {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!=-_'
let password = ''
const len = 12
for (let i = 0; i < len; i++) {
const randomPoz = Math.floor(Math.random() * chars.length)
password += chars.substring(randomPoz, randomPoz + 1)
}
return password
}
function generatePassword(password) {
const hasher = crypto.createHash('sha256')
hasher.update(crowi.env.PASSWORD_SEED + password)
return hasher.digest('hex')
}
function generateApiToken(user) {
const hasher = crypto.createHash('sha256')
hasher.update(new Date().getTime() + user._id)
return hasher.digest('base64')
}
function getLanguageLabels() {
const lang = {
LANG_EN,
LANG_EN_US,
LANG_EN_GB,
LANG_JA,
}
return lang
}
userSchema.methods.isPasswordSet = function () {
if (this.password) {
return true
}
return false
}
userSchema.methods.isPasswordValid = function (password) {
return this.password == generatePassword(password)
}
userSchema.methods.setPassword = function (password) {
this.password = generatePassword(password)
return this
}
userSchema.methods.isEmailSet = function () {
if (this.email) {
return true
}
return false
}
userSchema.methods.updatePassword = function (password, callback) {
this.setPassword(password)
this.save(function (err, userData) {
return callback(err, userData)
})
}
userSchema.methods.updateApiToken = function () {
this.apiToken = generateApiToken(this)
return this.save()
}
userSchema.methods.updateImage = function (image, callback) {
this.image = image
this.save(function (err, userData) {
return callback(err, userData)
})
}
userSchema.methods.updateEmail = function (email) {
this.email = email
return this.save()
}
userSchema.methods.updateNameAndEmail = function (name, email) {
this.name = name
this.email = email
return this.save()
}
userSchema.methods.deleteImage = function (callback) {
return this.updateImage(null, callback)
}
userSchema.methods.updateGoogleId = function (googleId) {
this.googleId = googleId
return this.save()
}
userSchema.methods.deleteGoogleId = function () {
return this.updateGoogleId(null)
}
userSchema.methods.updateGitHubId = function (githubId) {
this.githubId = githubId
return this.save()
}
userSchema.methods.deleteGitHubId = function () {
return this.updateGitHubId(null)
}
userSchema.methods.countValidThirdPartyIds = function () {
const config = crowi.getConfig()
const googleId = googleLoginEnabled(config) && this.googleId
const githubId = githubLoginEnabled(config) && this.githubId
const validIds = [googleId, githubId].filter(Boolean)
return validIds.length
}
userSchema.methods.hasValidThirdPartyId = function () {
return this.countValidThirdPartyIds() > 0
}
userSchema.methods.canDisconnectThirdPartyId = function () {
const config = crowi.getConfig()
return !isDisabledPasswordAuth(config) || this.countValidThirdPartyIds() > 1
}
userSchema.methods.activateInvitedUser = function (username, name, password, callback) {
this.setPassword(password)
this.name = name
this.username = username
this.status = STATUS_ACTIVE
this.save(function (err, userData) {
userEvent.emit('activated', userData)
return callback(err, userData)
})
}
userSchema.methods.removeFromAdmin = function (callback) {
debug('Remove from admin', this)
this.admin = false
this.save(function (err, userData) {
return callback(err, userData)
})
}
userSchema.methods.makeAdmin = function (callback) {
debug('Admin', this)
this.admin = true
this.save(function (err, userData) {
return callback(err, userData)
})
}
userSchema.methods.statusActivate = function (callback) {
debug('Activate User', this)
this.status = STATUS_ACTIVE
this.save(function (err, userData) {
userEvent.emit('activated', userData)
return callback(err, userData)
})
}
userSchema.methods.statusSuspend = function (callback) {
debug('Suspend User', this)
this.status = STATUS_SUSPENDED
if (this.email === undefined || this.email === null) {
// migrate old data
this.email = '-'
}
if (this.name === undefined || this.name === null) {
// migrate old data
this.name = '-' + Date.now()
}
if (this.username === undefined || this.username === null) {
// migrate old data
this.username = '-'
}
this.save(function (err, userData) {
return callback(err, userData)
})
}
userSchema.methods.statusDelete = function (callback) {
debug('Delete User', this)
this.status = STATUS_DELETED
this.password = ''
this.email = 'deleted@deleted'
this.googleId = null
this.image = null
this.save(function (err, userData) {
return callback(err, userData)
})
}
userSchema.methods.populateSecrets = async function () {
return User.findById(this._id, '+password +apiToken').exec()
}
userSchema.statics.getLanguageLabels = getLanguageLabels
userSchema.statics.getUserStatusLabels = function () {
const userStatus = {}
userStatus[STATUS_REGISTERED] = '承認待ち'
userStatus[STATUS_ACTIVE] = 'Active'
userStatus[STATUS_SUSPENDED] = 'Suspended'
userStatus[STATUS_DELETED] = 'Deleted'
userStatus[STATUS_INVITED] = '招待済み'
return userStatus
}
userSchema.statics.isEmailValid = function (email) {
const config = crowi.getConfig()
const whitelist = config.crowi['security:registrationWhiteList']
if (Array.isArray(whitelist) && whitelist.length > 0) {
return config.crowi['security:registrationWhiteList'].some(function (allowedEmail) {
const re = new RegExp(allowedEmail + '$')
return re.test(email)
})
}
return true
}
userSchema.statics.isGitHubAccountValid = function (organizations) {
const config = crowi.getConfig()
const org = config.crowi['github:organization']
const orgs = organizations || []
return !org || orgs.includes(org)
}
userSchema.statics.findUsers = function (options, callback) {
const sort = options.sort || { status: 1, createdAt: 1 }
this.find()
.sort(sort)
.skip(options.skip || 0)
.limit(options.limit || 21)
.exec(function (err, userData) {
callback(err, userData)
})
}
userSchema.statics.findAllUsers = function (options = {}) {
const sort = options.sort || { createdAt: -1 }
let status = options.status || [STATUS_ACTIVE, STATUS_SUSPENDED]
const fields = options.fields
if (!Array.isArray(status)) {
status = [status]
}
return User.find()
.or(
status.map((s) => {
return { status: s }
}),
)
.select(fields)
.sort(sort)
.exec()
}
userSchema.statics.findUsersByIds = function (ids, options = {}) {
const sort = options.sort || { createdAt: -1 }
const status = options.status || STATUS_ACTIVE
const fields = options.fields
return User.find({ _id: { $in: ids }, status: status })
.select(fields)
.sort(sort)
.exec()
}
userSchema.statics.findAdmins = function (callback) {
this.find({ admin: true }).exec(function (err, admins) {
debug('Admins: ', admins)
callback(err, admins)
})
}
userSchema.statics.findUsersWithPagination = function (options, query, callback) {
const sort = options.sort || { status: 1, username: 1, createdAt: 1 }
this.paginate(
query,
{ page: options.page || 1, limit: options.limit || PAGE_ITEMS },
function (err, result) {
if (err) {
debug('Error on pagination:', err)
return callback(err, null)
}
return callback(err, result)
},
{ sortBy: sort },
)
}
userSchema.statics.findUsersByPartOfEmail = function (emailPart, options) {
const status = options.status || null
const emailPartRegExp = new RegExp(emailPart.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'))
const query = User.find({ email: emailPartRegExp })
if (status) {
query.and({ status } as any)
}
return query.limit(PAGE_ITEMS + 1).exec()
}
userSchema.statics.findUserByUsername = function (username) {
return User.findOne({ username }).exec()
}
userSchema.statics.findUserByApiToken = function (apiToken) {
return User.findOne({ apiToken }).exec()
}
userSchema.statics.findUserByGoogleId = function (googleId) {
return User.findOne({ googleId }).exec()
}
userSchema.statics.findUserByGitHubId = function (githubId) {
return User.findOne({ githubId }).exec()
}
userSchema.statics.findUserByEmail = function (email) {
return User.findOne({ email }).exec()
}
userSchema.statics.findUserByEmailAndPassword = function (email, password) {
const hashedPassword = generatePassword(password)
return User.findOne({ email, password: hashedPassword }).exec()
}
userSchema.statics.isRegisterableUsername = async function (username, callback) {
const userData = await User.findOne({ username })
if (userData) {
return callback(false)
}
return callback(true)
}
userSchema.statics.isRegisterable = async function (email, username, callback) {
let emailUsable = true
let usernameUsable = true
let userData: UserDocument | null = null
// username check
userData = await User.findOne({ username })
if (userData) {
usernameUsable = false
}
// email check
userData = await User.findOne({ email })
if (userData) {
emailUsable = false
}
if (!emailUsable || !usernameUsable) {
return callback(false, { email: emailUsable, username: usernameUsable })
}
return callback(true, {})
}
userSchema.statics.removeCompletelyById = function (id, callback) {
User.findById(id, function (err, userData) {
if (!userData) {
return callback(err, null)
}
debug('Removing user:', userData)
// 物理削除可能なのは、招待中ユーザーのみ
// 利用を一度開始したユーザーは論理削除のみ可能
if (userData.status !== STATUS_INVITED) {
return callback(new Error('Cannot remove completely the user whoes status is not INVITED'), null)
}
userData.remove(function (err) {
if (err) {
return callback(err, null)
}
return callback(null, 1)
})
})
}
userSchema.statics.resetPasswordByRandomString = async function (id) {
const userData = await User.findById(id)
if (!userData) {
throw new Error('User not found')
}
// is updatable check
// if (userData.isUp
const newPassword = generateRandomTempPassword()
userData.setPassword(newPassword)
const user = await userData.save()
return { user, newPassword }
}
userSchema.statics.createUsersByInvitation = function (emailList, toSendEmail, callback) {
const createdUserList: {
email: string
password: string | null
user: UserDocument | null
}[] = []
const config = crowi.getConfig()
const mailer = crowi.getMailer()
if (!Array.isArray(emailList)) {
debug('emailList is not array')
}
async.each(
emailList,
function (email, next) {
const newUser = new User()
let password
email = email.trim()
// email check
// TODO: 削除済みはチェック対象から外そう〜
User.findOne({ email }, function (err, user) {
// The user is exists
if (user) {
createdUserList.push({ email, password: null, user: null })
return next()
}
password = Math.random().toString(36).slice(-16)
newUser.email = email
newUser.setPassword(password)
newUser.createdAt = Date.now() as any
newUser.status = STATUS_INVITED
newUser.save(function (err, user) {
if (err) {
createdUserList.push({ email, password: null, user: null })
debug('save failed!! ', email)
} else {
createdUserList.push({ email, password, user })
debug('saved!', email)
}
next()
})
})
},
function (err) {
if (err) {
debug('error occured while iterate email list')
}
if (toSendEmail) {
// TODO: メール送信部分のロジックをサービス化する
async.each(
createdUserList,
function (user, next) {
if (user.password === null) {
return next()
}
mailer.send(
{
to: user.email,
subject: 'Invitation to ' + config.crowi['app:title'],
template: 'admin/userInvitation.txt',
vars: {
email: user.email,
password: user.password,
url: config.crowi['app:url'],
appTitle: config.crowi['app:title'],
},
},
function (err, s) {
debug('completed to send email: ', err, s)
next()
},
)
},
function (err) {
debug('Sending invitation email completed.', err)
},
)
}
debug('createdUserList!!! ', createdUserList)
return callback(null, createdUserList)
},
)
}
userSchema.statics.createUserByEmailAndPassword = function (name, username, email, password, lang, callback) {
const newUser = new User()
newUser.name = name
newUser.username = username
newUser.email = email
newUser.setPassword(password)
newUser.lang = lang
newUser.createdAt = Date.now() as any
newUser.status = decideUserStatusOnRegistration()
newUser.save(function (err, userData) {
if (userData.status == STATUS_ACTIVE) {
userEvent.emit('activated', userData)
}
return callback(err, userData)
})
}
userSchema.statics.createUserPictureFilePath = function (user, ext) {
ext = '.' + ext
return 'user/' + user._id + ext
}
userSchema.statics.getUsernameByPath = function (path) {
let username = null
let m
if ((m = path.match(/^\/user\/([^/]+)\/?/))) {
username = m[1]
}
return username
}
userSchema.statics.STATUS_REGISTERED = STATUS_REGISTERED
userSchema.statics.STATUS_ACTIVE = STATUS_ACTIVE
userSchema.statics.STATUS_SUSPENDED = STATUS_SUSPENDED
userSchema.statics.STATUS_DELETED = STATUS_DELETED
userSchema.statics.STATUS_INVITED = STATUS_INVITED
userSchema.statics.PAGE_ITEMS = PAGE_ITEMS
userSchema.statics.LANG_EN = LANG_EN
userSchema.statics.LANG_EN_US = LANG_EN_US
userSchema.statics.LANG_EN_GB = LANG_EN_US
userSchema.statics.LANG_JA = LANG_JA
const User = model<UserDocument, UserModel>('User', userSchema)
return User
} | the_stack |
import { satisfies } from 'satisfier'
import { assertType, T, Equal } from '..'
describe('undefined', () => {
test('satisfies only undefined', () => {
expect(T.satisfy(T.undefined, undefined)).toBe(true)
notSatisfyTypesOtherThan(T.undefined, undefined)
const value: unknown = undefined
if (T.satisfy(T.undefined, value)) {
assertType<undefined>(value)
}
})
})
describe('null', () => {
test('satisfies only null', () => {
expect(T.satisfy(T.null, null)).toBe(true)
notSatisfyTypesOtherThan(T.null, null)
const value: unknown = null
if (T.satisfy(T.null, value)) {
assertType<null>(value)
}
})
test('optional', () => {
const t = T.null.optional
expect(T.satisfy(t, undefined)).toBe(true)
const value: unknown = undefined
if (T.satisfy(t, value)) {
assertType<null | undefined>(value)
}
})
})
describe('boolean', () => {
test('base type satisfies both true and false', () => {
expect(T.satisfy(T.boolean, true)).toBe(true)
expect(T.satisfy(T.boolean, false)).toBe(true)
notSatisfyTypesOtherThan(T.boolean, true, false)
const value: unknown = undefined
if (T.satisfy(T.boolean, value)) {
assertType<boolean>(value)
}
})
test('true', () => {
expect(T.satisfy(T.boolean.true, true)).toBe(true)
notSatisfyTypesOtherThan(T.boolean.true, true)
const value: unknown = true
if (T.satisfy(T.boolean.true, value)) {
assertType<true>(value)
}
})
test('false', () => {
expect(T.satisfy(T.boolean.false, false)).toBe(true)
notSatisfyTypesOtherThan(T.boolean.false, false)
const value: unknown = false
if (T.satisfy(T.boolean.false, value)) {
assertType<false>(value)
}
})
test('true does not satisfy False', () => {
expect(T.satisfy(T.boolean.false, true)).toBe(false)
})
test('false does not satisfy True', () => {
expect(T.satisfy(T.boolean.true, false)).toBe(false)
})
test('optional', () => {
const t = T.boolean.optional
expect(T.satisfy(t, undefined)).toBe(true)
const value: unknown = undefined
if (T.satisfy(t, value)) {
assertType<boolean | undefined>(value)
}
})
test('optional create', () => {
const t = T.boolean.optional.create(true)
expect(T.satisfy(t, undefined)).toBe(true)
const value: unknown = undefined
if (T.satisfy(t, value)) {
assertType<true | undefined>(value)
}
})
})
describe('number', () => {
test('base type satisfy all numbers', () => {
expect(T.satisfy(T.number, 0)).toBe(true)
expect(T.satisfy(T.number, -1)).toBe(true)
expect(T.satisfy(T.number, 1)).toBe(true)
notSatisfyTypesOtherThan(T.number, -1, 0, 1)
const value: unknown = 0
if (T.satisfy(T.number, value)) {
assertType<number>(value)
assertType.isTrue(true as Equal<number, typeof value>)
assertType.isFalse(false as Equal<0, typeof value>)
}
})
test('0', () => {
expect(T.satisfy(T.number.create(0), 0)).toBe(true)
notSatisfyTypesOtherThan(T.number.create(0), 0)
const value: unknown = 0
if (T.satisfy(T.number.create(0), value)) {
assertType<0>(value)
}
})
test('1', () => {
expect(T.satisfy(T.number.create(1), 1)).toBe(true)
notSatisfyTypesOtherThan(T.number.create(1), 1)
const value: unknown = 1
if (T.satisfy(T.number.create(1), value)) {
assertType<1>(value)
}
})
test('0 does not satisfy 1', () => {
expect(T.satisfy(T.number.create(1), 0)).toBe(false)
})
test('1 does not satisfy 0', () => {
expect(T.satisfy(T.number.create(0), 1)).toBe(false)
})
test('optional', () => {
const t = T.number.optional
expect(T.satisfy(t, undefined)).toBe(true)
const value: unknown = undefined
if (T.satisfy(t, value)) {
assertType<number | undefined>(value)
}
})
test('optional const', () => {
const t = T.number.optional.create(1)
expect(T.satisfy(t, undefined)).toBe(true)
const value: unknown = undefined
if (T.satisfy(t, value)) {
assertType<1 | undefined>(value)
}
})
test('list: single', () => {
const t = T.number.list(0)
const value: unknown = 0
expect(T.satisfy(t, value)).toBe(true)
if (T.satisfy(t, value)) {
assertType<0>(value)
}
})
test('list: multiple', () => {
const t = T.number.list(1, 2, 3)
const value: unknown = 1
expect(T.satisfy(t, value)).toBe(true)
if (T.satisfy(t, value)) {
assertType<1 | 2 | 3>(value)
}
})
test('optional.list: multiple', () => {
const t = T.number.optional.list(1, 2, 3)
const value: unknown = 1
expect(T.satisfy(t, value)).toBe(true)
if (T.satisfy(t, value)) {
assertType<1 | 2 | 3 | undefined>(value)
}
})
})
describe('string', () => {
test('base type satisfies any string', () => {
expect(T.satisfy(T.string, '')).toBe(true)
expect(T.satisfy(T.string, 'a')).toBe(true)
notSatisfyTypesOtherThan(T.string, '', 'a')
const value: unknown = ''
if (T.satisfy(T.string, value)) {
assertType<string>(value)
assertType.isTrue(true as Equal<string, typeof value>)
assertType.isFalse(false as Equal<'', typeof value>)
}
})
test(`''`, () => {
expect(T.satisfy(T.string, '')).toBe(true)
notSatisfyTypesOtherThan(T.string, '')
const value: unknown = ''
if (T.satisfy(T.string.create(''), value)) {
assertType<''>(value)
}
})
test(`'a'`, () => {
expect(T.satisfy(T.string, 'a')).toBe(true)
notSatisfyTypesOtherThan(T.string, '', 'a')
const value: unknown = 'a'
if (T.satisfy(T.string.create('a'), value)) {
assertType<'a'>(value)
}
})
test(`'' does not satisfy 'a'`, () => {
expect(T.satisfy(T.string.create('a'), '')).toBe(false)
})
test(`'a' does not satisfy ''`, () => {
expect(T.satisfy(T.string.create(''), 'a')).toBe(false)
})
test('optional', () => {
const t = T.string.optional
expect(T.satisfy(t, undefined)).toBe(true)
const value: unknown = undefined
if (T.satisfy(t, value)) {
assertType<string | undefined>(value)
}
})
test('optional const', () => {
const t = T.string.optional.create('a')
expect(T.satisfy(t, undefined)).toBe(true)
const value: unknown = undefined
if (T.satisfy(t, value)) {
assertType<'a' | undefined>(value)
}
})
test('list: single', () => {
const t = T.string.list('a')
const value: unknown = 'a'
expect(T.satisfy(t, value)).toBe(true)
if (T.satisfy(t, value)) {
assertType<'a'>(value)
}
})
test('list: multiple', () => {
const t = T.string.list('1', '2', '3')
const value: unknown = '1'
expect(T.satisfy(t, value)).toBe(true)
if (T.satisfy(t, value)) {
assertType<'1' | '2' | '3'>(value)
}
})
test('optional list: multiple', () => {
const t = T.string.optional.list('1', '2', '3')
const value: unknown = '1'
expect(T.satisfy(t, value)).toBe(true)
if (T.satisfy(t, value)) {
assertType<'1' | '2' | '3' | undefined>(value)
}
})
})
describe('bigint', () => {
// test('bigint', () => {
// expect(T.satisfy(T.bigint, 0n)).toBe(true)
// notSatisfyTypesOtherThan(T.bigint, 0n, 1n)
// const value: unknown = 0n
// if (T.satisfy(T.bigint, value)) {
// assertType<bigint>(value)
// assertType.isFalse(assignability<0>()(value))
// }
// })
// test('bigint:0', () => {
// expect(T.satisfy(T.bigint.create(0n), 0n)).toBe(true)
// notSatisfyTypesOtherThan(T.bigint.create(0n), 0n)
// const value: unknown = 0n
// if (T.satisfy(T.bigint.create(0n), value)) {
// assertType<0n>(value)
// }
// })
// test('bigint:1', () => {
// expect(T.satisfy(T.bigint.create(1n), 1n)).toBe(true)
// notSatisfyTypesOtherThan(T.bigint.create(1n), 1n)
// const value: unknown = 1n
// if (T.satisfy(T.bigint.create(1n), value)) {
// assertType<1n>(value)
// }
// })
// test('0n not satisfy 1n', () => {
// expect(T.satisfy(T.bigint.create(1n), 0n)).toBe(false)
// })
// test('1n not satisfy 0n', () => {
// expect(T.satisfy(T.bigint.create(0n), 1n)).toBe(false)
// })
})
describe('symbol', () => {
test('base type satisfies any symbol', () => {
expect(T.satisfy(T.symbol, Symbol())).toBe(true)
notSatisfyTypesOtherThan(T.symbol, Symbol())
const value: unknown = Symbol()
if (T.satisfy(T.symbol, value)) {
assertType<symbol>(value)
}
})
test('optional', () => {
const t = T.symbol.optional
const value: unknown = Symbol()
expect(T.satisfy(t, value)).toBe(true)
if (T.satisfy(t, value)) {
assertType<symbol | undefined>(value)
}
})
})
describe('union', () => {
test('single type gets the type back', () => {
const t = T.union.create(T.boolean)
assertType<T.Boolean>(t)
})
test('on two types', () => {
const t = T.union.create(T.boolean, T.number)
expect(T.satisfy(t, 0)).toBe(true)
expect(T.satisfy(t, false)).toBe(true)
const value: unknown = 0
if (T.satisfy(t, value)) {
assertType<boolean | number>(value)
}
})
test('on multiple primitive types', () => {
const t = T.union.create(T.boolean, T.null, T.number)
expect(T.satisfy(t, false)).toBe(true)
const value: unknown = true
if (T.satisfy(t, value)) {
assertType<boolean | null | number>(value)
}
})
test('nested union is flatten', () => {
const t = T.union.create(T.union.create(T.boolean, T.null), T.string)
expect(T.satisfy(t, false)).toBe(true)
const value: unknown = true
if (T.satisfy(t, value)) {
assertType<boolean | string | null>(value)
}
})
test.todo('remove duplicates')
test('optional create', () => {
const t = T.union.optional.create(T.boolean)
expect(T.satisfy(t, undefined)).toBe(true)
const value: unknown = undefined
if (T.satisfy(t, value)) {
assertType<boolean | undefined>(value)
}
})
})
describe('array', () => {
test('base type satisfies any array and type guard it to any[]', () => {
expect(T.satisfy(T.array, [])).toBe(true)
expect(T.satisfy(T.array, ['a'])).toBe(true)
const value: unknown = []
if (T.satisfy(T.array, value)) {
// Note that this test is weak.
// I don't have a good way to nail it down as it is a top type.
assertType<any[]>(value)
}
})
test('base type does not satisfy non-array', () => {
notSatisfyTypesOtherThan(T.array, [], ['a'])
})
test('unknown type assert result to unknown[]', () => {
expect(T.satisfy(T.array.unknown, [])).toBe(true)
expect(T.satisfy(T.array.unknown, ['a'])).toBe(true)
const value: unknown = []
if (T.satisfy(T.array.unknown, value)) {
// Note that this test is weak.
// I don't have a good way to nail it down as it is a top type.
assertType<unknown[]>(value)
}
})
test('unknown type does not satisfy non-array', () => {
notSatisfyTypesOtherThan(T.array.unknown, [], ['a'])
})
test('specific type', () => {
const t = T.array.create(T.number)
expect(T.satisfy(t, [])).toBe(true)
expect(T.satisfy(t, [0])).toBe(true)
expect(T.satisfy(t, [1, 2])).toBe(true)
expect(T.satisfy(t, ['a'])).toBe(false)
expect(T.satisfy(t, [1, 'a'])).toBe(false)
expect(T.satisfy(t, ['a', 1])).toBe(false)
const value: unknown = ['a']
if (T.satisfy(t, value)) {
assertType<number[]>(value)
}
})
test(`array's value type can be union type`, () => {
const t = T.array.create(T.union.create(T.number, T.boolean))
expect(T.satisfy(t, [])).toBe(true)
expect(T.satisfy(t, [0])).toBe(true)
expect(T.satisfy(t, [false])).toBe(true)
expect(T.satisfy(t, [false, 0])).toBe(true)
expect(T.satisfy(t, [0, false, ''])).toBe(false)
const value: unknown = [0, false]
if (T.satisfy(t, value)) {
assertType<Array<number | boolean>>(value)
}
})
test('optional', () => {
const t = T.array.optional
expect(T.satisfy(t, undefined)).toBe(true)
const value: unknown = undefined
if (T.satisfy(t, value)) {
assertType<any[] | undefined>(value)
}
})
test('optional create', () => {
const t = T.array.optional.create(T.string)
expect(T.satisfy(t, undefined)).toBe(true)
const value: unknown = undefined
if (T.satisfy(t, value)) {
assertType<string[] | undefined>(value)
}
})
})
describe('tuple', () => {
test('single value', () => {
const t = T.tuple.create(T.number)
expect(T.satisfy(t, [0])).toBe(true)
expect(T.satisfy(t, [''])).toBe(false)
const value: unknown = [1]
if (T.satisfy(t, value)) {
assertType<[number]>(value)
}
})
test('two values', () => {
const t = T.tuple.create(T.number, T.string)
expect(T.satisfy(t, [0, ''])).toBe(true)
expect(T.satisfy(t, [0])).toBe(false)
const value: unknown = [1, 'a']
if (T.satisfy(t, value)) {
assertType<[number, string]>(value)
}
})
test('pass with more values than what specified in the type', () => {
expect(T.satisfy(T.tuple.create(T.number), [1, 'a'])).toBe(true)
})
test('optional', () => {
const t = T.tuple.optional.create(T.boolean)
expect(T.satisfy(t, undefined)).toBe(true)
const value: unknown = undefined
if (T.satisfy(t, value)) {
assertType<[boolean] | undefined>(value)
}
})
})
describe('object', () => {
test('base type satisfies any object', () => {
expect(T.satisfy(T.object, {})).toBe(true)
expect(T.satisfy(T.object, { a: 1 })).toBe(true)
expect(T.satisfy(T.object, { 0: 0 })).toBe(true)
const value: unknown = { a: 1 }
if (T.satisfy(T.object, value)) {
assertType<Record<string, any>>(value)
}
})
test('base type does not satisfy non-object including array and null', () => {
notSatisfyTypesOtherThan(T.object, {}, { a: 1 })
})
test('single prop', () => {
const t = T.object.create({ a: T.number })
expect(T.satisfy(t, { a: 0 })).toBe(true)
expect(T.satisfy(t, { a: 1 })).toBe(true)
const value: unknown = { a: 1 }
if (T.satisfy(t, value)) {
assertType<{ a: number }>(value)
}
})
test('two props', () => {
const t = T.object.create({
a: T.number.create(1),
b: T.string
})
expect(T.satisfy(t, { a: 1, b: '' })).toBe(true)
expect(T.satisfy(t, { a: 1, b: 'b' })).toBe(true)
const value: unknown = { a: 1, b: '' }
if (T.satisfy(t, value)) {
assertType<{ a: 1, b: string }>(value)
}
})
test('props with union', () => {
const t = T.object.create({
a: T.union.create(T.number.create(1), T.boolean.true),
b: T.string
})
expect(T.satisfy(t, { a: 1, b: '' })).toBe(true)
expect(T.satisfy(t, { a: true, b: '' })).toBe(true)
expect(T.satisfy(t, { a: false, b: '' })).toBe(false)
const value: unknown = { a: 1, b: '' }
if (T.satisfy(t, value)) {
assertType<{ a: true | 1, b: string }>(value)
}
})
test('nested object', () => {
const t = T.object.create({
a: T.object.create({
b: T.number
})
})
expect(T.satisfy(t, { a: { b: 0 } })).toBe(true)
const value: unknown = { a: { b: 0 } }
if (T.satisfy(t, value)) {
assertType<{ a: { b: number } }>(value)
}
})
test('keys is string + number + symbol', () => {
// technically empty string is not a valid key.
// maybe we can do a disjoint or something
expect(T.satisfy(T.keys, '')).toBe(true)
expect(T.satisfy(T.keys, 'a')).toBe(true)
expect(T.satisfy(T.keys, 0)).toBe(true)
expect(T.satisfy(T.keys, Symbol.for('abc'))).toBe(true)
})
test('optional', () => {
const t = T.object.optional
expect(T.satisfy(t, undefined)).toBe(true)
const value: unknown = undefined
if (T.satisfy(t, value)) {
assertType<Record<string, any> | undefined>(value)
}
})
test('optional create', () => {
const t = T.object.optional.create({
a: T.string
})
expect(T.satisfy(t, undefined)).toBe(true)
const value: unknown = undefined
if (T.satisfy(t, value)) {
assertType<{ a: string } | undefined>(value)
}
})
})
describe('record', () => {
test('base case', () => {
const t = T.record.create(T.number)
const value: any = { 'a': 1 }
expect(T.satisfy(t, value)).toBe(true)
if (T.satisfy(t, value)) {
assertType<Record<string, number>>(value)
}
})
test('base type does not satisfy non-object including array and null', () => {
notSatisfyTypesOtherThan(T.record.create(T.null), {}, { a: 1 })
})
})
// test('if condition', () => {
// T.If(T.boolean.false, {}, false as const)
// })
function notSatisfyTypesOtherThan(type: T.AllType, ...excepts: any[]) {
const values = [undefined, null, true, false, 0, 1, 0n, 1n, '', 'a', [], ['a'], {}, { a: 1 }, Symbol(), Symbol.for('a')]
values.forEach(v => {
if (!excepts.some(e => satisfies(v, e))) {
expect(T.satisfy(type, v))
}
})
} | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
class EmailApi {
/**
* DynamicsCrm.DevKit EmailApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** The Entity that Accepted the Email */
acceptingentityid_queue: DevKit.WebApi.LookupValue;
/** The Entity that Accepted the Email */
acceptingentityid_systemuser: DevKit.WebApi.LookupValue;
/** For internal use only. */
ActivityAdditionalParams: DevKit.WebApi.StringValue;
/** Unique identifier of the email activity. */
ActivityId: DevKit.WebApi.GuidValue;
/** Type the number of minutes spent creating and sending the email. The duration is used in reporting. */
ActualDurationMinutes: DevKit.WebApi.IntegerValue;
/** Enter the actual end date and time of the email. By default, it displays the date and time when the activity was completed or canceled, but can be edited to capture the actual time to create and send the email. */
ActualEnd_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the actual start date and time for the email. By default, it displays the date and time when the activity was created, but can be edited to capture the actual time to create and send the email. */
ActualStart_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Shows the umber of attachments of the email message. */
AttachmentCount: DevKit.WebApi.IntegerValueReadonly;
/** Shows the number of times an email attachment has been viewed. */
AttachmentOpenCount: DevKit.WebApi.IntegerValue;
/** Hash of base of conversation index. */
BaseConversationIndexHash: DevKit.WebApi.IntegerValue;
/** Type a category to identify the email type, such as lead outreach, customer follow-up, or service alert, to tie the email to a business group or function. */
Category: DevKit.WebApi.StringValue;
/** Indicates if the body is compressed. */
Compressed: DevKit.WebApi.BooleanValueReadonly;
/** Identifier for all the email responses for this conversation. */
ConversationIndex: DevKit.WebApi.StringValueReadonly;
/** Conversation Tracking Id. */
ConversationTrackingId: DevKit.WebApi.GuidValue;
/** Correlated Activity Id */
CorrelatedActivityId: DevKit.WebApi.LookupValue;
/** Shows how an email is matched to an existing email in Microsoft Dynamics 365. For system use only. */
CorrelationMethod: DevKit.WebApi.OptionSetValueReadonly;
/** Shows who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who created the record on behalf of another user. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Enter the expected date and time when email will be sent. */
DelayedEmailSendTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Shows the count of the number of attempts made to send the email. The count is used as an indicator of email routing issues. */
DeliveryAttempts: DevKit.WebApi.IntegerValue;
/** Select the priority of delivery of the email to the email server. */
DeliveryPriorityCode: DevKit.WebApi.OptionSetValue;
/** Select whether the sender should receive confirmation that the email was delivered. */
DeliveryReceiptRequested: DevKit.WebApi.BooleanValue;
/** Type the greeting and message text of the email. */
Description: DevKit.WebApi.StringValue;
/** Select the direction of the email as incoming or outbound. */
DirectionCode: DevKit.WebApi.BooleanValue;
/** Shows the date and time when an email reminder expires. */
EmailReminderExpiryTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Shows the status of the email reminder. */
EmailReminderStatus: DevKit.WebApi.OptionSetValueReadonly;
/** For internal use only. */
EmailReminderText: DevKit.WebApi.StringValue;
/** Shows the type of the email reminder. */
EmailReminderType: DevKit.WebApi.OptionSetValue;
/** Shows the sender of the email. */
emailsender_account: DevKit.WebApi.LookupValueReadonly;
/** Shows the sender of the email. */
emailsender_contact: DevKit.WebApi.LookupValueReadonly;
/** Shows the sender of the email. */
emailsender_equipment: DevKit.WebApi.LookupValueReadonly;
/** Shows the sender of the email. */
emailsender_lead: DevKit.WebApi.LookupValueReadonly;
/** Shows the sender of the email. */
emailsender_queue: DevKit.WebApi.LookupValueReadonly;
/** Shows the sender of the email. */
emailsender_systemuser: DevKit.WebApi.LookupValueReadonly;
/** Email Tracking Id. */
EmailTrackingId: DevKit.WebApi.GuidValue;
/** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */
ExchangeRate: DevKit.WebApi.DecimalValueReadonly;
/** Select whether the email allows following recipient activities sent from Microsoft Dynamics 365.This is user preference state which can be overridden by system evaluated state. */
FollowEmailUserPreference: DevKit.WebApi.BooleanValue;
/** Unique identifier of the data import or data migration that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Type the ID of the email message that this email activity is a response to. */
InReplyTo: DevKit.WebApi.StringValueReadonly;
/** Information regarding whether the email activity was billed as part of resolving a case. */
IsBilled: DevKit.WebApi.BooleanValue;
/** For internal use only. Shows whether this email is followed. This is evaluated state which overrides user selection of follow email. */
IsEmailFollowed: DevKit.WebApi.BooleanValueReadonly;
/** For internal use only. Shows whether this email Reminder is Set. */
IsEmailReminderSet: DevKit.WebApi.BooleanValueReadonly;
/** Information regarding whether the activity is a regular activity type or event type. */
IsRegularActivity: DevKit.WebApi.BooleanValueReadonly;
/** For internal use only. */
IsUnsafe: DevKit.WebApi.IntegerValueReadonly;
/** Indication if the email was created by a workflow rule. */
IsWorkflowCreated: DevKit.WebApi.BooleanValue;
/** Contains the date and time stamp of the last on hold time. */
LastOnHoldTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Shows the latest date and time when email was opened. */
LastOpenedTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Shows the number of times a link in an email has been clicked. */
LinksClickedCount: DevKit.WebApi.IntegerValue;
/** Unique identifier of the email message. Used only for email that is received. */
MessageId: DevKit.WebApi.StringValue;
/** MIME type of the email message data. */
MimeType: DevKit.WebApi.StringValue;
/** Shows who last updated the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who last updated the record on behalf of another user. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Select the notification code to identify issues with the email recipients or attachments, such as blocked attachments. */
Notifications: DevKit.WebApi.OptionSetValue;
/** Shows how long, in minutes, that the record was on hold. */
OnHoldTime: DevKit.WebApi.IntegerValueReadonly;
/** Shows the number of times an email has been opened. */
OpenCount: DevKit.WebApi.IntegerValue;
/** Date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Unique identifier of the business unit that owns the email activity. */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the team who owns the email activity. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the user who owns the email activity. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Select the activity that the email is associated with. */
ParentActivityId: DevKit.WebApi.LookupValue;
/** For internal use only. */
PostponeEmailProcessingUntil_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Select the priority so that preferred customers or critical issues are handled quickly. */
PriorityCode: DevKit.WebApi.OptionSetValue;
/** Shows the ID of the process. */
ProcessId: DevKit.WebApi.GuidValue;
/** Indicates that a read receipt is requested. */
ReadReceiptRequested: DevKit.WebApi.BooleanValue;
/** The Mailbox that Received the Email. */
ReceivingMailboxId: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_account_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_asyncoperation: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_bookableresourcebooking_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_bookableresourcebookingheader_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_bulkoperation_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_campaign_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_campaignactivity_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_contact_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_contract_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_entitlement_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_entitlementtemplate_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_incident_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_invoice_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_knowledgearticle_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_knowledgebaserecord_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_lead_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_agreement_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_agreementbookingdate_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_agreementbookingincident_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_agreementbookingproduct_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_agreementbookingservice_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_agreementbookingservicetask_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_agreementbookingsetup_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_agreementinvoicedate_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_agreementinvoiceproduct_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_agreementinvoicesetup_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_bookingalertstatus_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_bookingrule_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_bookingtimestamp_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_customerasset_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_fieldservicesetting_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_incidenttypecharacteristic_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_incidenttypeproduct_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_incidenttypeservice_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_inventoryadjustment_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_inventoryadjustmentproduct_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_inventoryjournal_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_inventorytransfer_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_payment_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_paymentdetail_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_paymentmethod_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_paymentterm_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_playbookinstance_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_postalbum_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_postalcode_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_processnotes_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_productinventory_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_projectteam_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_purchaseorder_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_purchaseorderbill_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_purchaseorderproduct_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_purchaseorderreceipt_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_purchaseorderreceiptproduct_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_purchaseordersubstatus_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_quotebookingincident_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_quotebookingproduct_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_quotebookingservice_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_quotebookingservicetask_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_resourceterritory_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_rma_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_rmaproduct_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_rmareceipt_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_rmareceiptproduct_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_rmasubstatus_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_rtv_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_rtvproduct_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_rtvsubstatus_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_shipvia_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_systemuserschedulersetting_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_timegroup_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_timegroupdetail_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_timeoffrequest_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_warehouse_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_workorder_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_workordercharacteristic_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_workorderincident_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_workorderproduct_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_workorderresourcerestriction_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_workorderservice_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_msdyn_workorderservicetask_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_opportunity_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_quote_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_salesorder_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_site_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_uii_action_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_uii_hostedapplication_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_uii_nonhostedapplication_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_uii_option_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_uii_savedsession_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_uii_workflow_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_uii_workflowstep_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the e-mail is associated. */
regardingobjectid_uii_workflow_workflowstep_mapping_email: DevKit.WebApi.LookupValue;
/** Reminder Action Card Id. */
ReminderActionCardId: DevKit.WebApi.GuidValue;
/** Shows the number of replies received for an email. */
ReplyCount: DevKit.WebApi.IntegerValueReadonly;
/** For internal use only */
ReservedForInternalUse: DevKit.WebApi.StringValue;
/** Safe body text of the e-mail. */
SafeDescription: DevKit.WebApi.StringValueReadonly;
/** Scheduled duration of the email activity, specified in minutes. */
ScheduledDurationMinutes: DevKit.WebApi.IntegerValueReadonly;
/** Enter the expected due date and time for the activity to be completed to provide details about when the email will be sent. */
ScheduledEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Enter the expected start date and time for the activity to provide details about the tentative time when the email activity must be initiated. */
ScheduledStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Sender of the email. */
Sender: DevKit.WebApi.StringValue;
/** Select the mailbox associated with the sender of the email message. */
SenderMailboxId: DevKit.WebApi.LookupValueReadonly;
/** Shows the parent account of the sender of the email. */
SendersAccount: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time that the email was sent. */
SentOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier for the associated service. */
ServiceId: DevKit.WebApi.LookupValue;
/** Choose the service level agreement (SLA) that you want to apply to the email record. */
SLAId: DevKit.WebApi.LookupValue;
/** Last SLA that was applied to this email. This field is for internal use only. */
SLAInvokedId: DevKit.WebApi.LookupValueReadonly;
SLAName: DevKit.WebApi.StringValueReadonly;
/** Shows the date and time by which the activities are sorted. */
SortDate_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Shows the ID of the stage. */
StageId: DevKit.WebApi.GuidValue;
/** Shows whether the email is open, completed, or canceled. Completed and canceled email is read-only and can't be edited. */
StateCode: DevKit.WebApi.OptionSetValue;
/** Select the email's status. */
StatusCode: DevKit.WebApi.OptionSetValue;
/** Type a subcategory to identify the email type and relate the activity to a specific product, sales region, business group, or other function. */
Subcategory: DevKit.WebApi.StringValue;
/** Type a short description about the objective or primary topic of the email. */
Subject: DevKit.WebApi.StringValue;
/** Shows the Microsoft Office Outlook account for the user who submitted the email to Microsoft Dynamics 365. */
SubmittedBy: DevKit.WebApi.StringValue;
/** For internal use only. ID for template used in email. */
TemplateId: DevKit.WebApi.LookupValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Shows the email addresses corresponding to the recipients. */
ToRecipients: DevKit.WebApi.StringValue;
/** Shows the tracking token assigned to the email to make sure responses are automatically tracked in Microsoft Dynamics 365. */
TrackingToken: DevKit.WebApi.StringValue;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.WebApi.LookupValue;
/** For internal use only. */
TraversedPath: DevKit.WebApi.StringValue;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version number of the email message. */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
/** The array of object that can cast object to ActivityPartyApi class */
ActivityParties: Array<any>;
}
}
declare namespace OptionSet {
namespace Email {
enum CorrelationMethod {
/** 0 */
None,
/** 1 */
Skipped,
/** 2 */
XHeader,
/** 3 */
InReplyTo,
/** 4 */
TrackingToken,
/** 5 */
ConversationIndex,
/** 6 */
SmartMatching,
/** 7 */
CustomCorrelation
}
enum DeliveryPriorityCode {
/** 0 */
Low,
/** 1 */
Normal,
/** 2 */
High
}
enum EmailReminderStatus {
/** 0 */
NotSet,
/** 1 */
ReminderSet,
/** 2 */
ReminderExpired,
/** 3 */
ReminderInvalid
}
enum EmailReminderType {
/** 0 */
If_I_do_not_receive_a_reply_by,
/** 1 */
If_the_email_is_not_opened_by,
/** 2 */
Remind_me_anyways_at
}
enum Notifications {
/** 0 */
None,
/** 1 */
The_message_was_saved_as_a_Microsoft_Dynamics_365_email_record_but_not_all_the_attachments_could_be_saved_with_it_An_attachment_cannot_be_saved_if_it_is_blocked_or_if_its_file_type_is_invalid,
/** 2 */
Truncated_body
}
enum PriorityCode {
/** 0 */
Low,
/** 1 */
Normal,
/** 2 */
High
}
enum StateCode {
/** 0 */
Open,
/** 1 */
Completed,
/** 2 */
Canceled
}
enum StatusCode {
/** 1 */
Draft,
/** 2 */
Completed,
/** 3 */
Sent,
/** 4 */
Received,
/** 5 */
Canceled,
/** 6 */
Pending_Send,
/** 7 */
Sending,
/** 8 */
Failed
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':[],'JsWebApi':true,'IsDebugForm':false,'IsDebugWebApi':true,'Version':'2.13.33','JsFormVersion':null} | the_stack |
import type { VFile, VFileCompatible } from 'vfile';
import type { Node } from 'unist';
import type {
Parent,
Heading,
Text,
Paragraph,
Link,
Code,
Root,
HTML,
Table,
TableRow,
TableCell,
AlignType,
InlineCode,
BlockContent,
PhrasingContent,
} from 'mdast';
import type { Options as PrettierOptions } from 'prettier';
import type {
CommandFlags,
GeneratorReadmeOptions,
ReadmeConfig,
PackgeJsonInfo,
ReactAPI,
ReactComponentProps,
ReactComponentPropType,
ReactComponentTSDescriptor,
} from './types';
import fs from 'fs';
import path from 'path';
// import shelljs from 'shelljs';
import Listr from 'listr';
// @ts-ignore
import ListrVerboseRenderer from 'listr-verbose-renderer';
import { getPackagesSync } from '@manypkg/get-packages';
import toVfile from 'to-vfile';
import vfile from 'vfile';
import unified from 'unified';
import parse from 'remark-parse';
import mdx from 'remark-mdx';
import gfm from 'remark-gfm';
import stringify from 'remark-stringify';
// @ts-ignore
import * as reactDocgen from 'react-docgen';
// @ts-ignore
import setParamsTypeDefinitionFromFunctionType from 'typescript-react-function-component-props-handler';
import rcfile from 'rcfile';
import prettier from 'prettier';
import camelcase from 'lodash/camelCase';
import upperFirst from 'lodash/upperFirst';
import stringifyOptions from './utils/stringify-options';
import gfmOptions from './utils/gfm-options';
const prettierConfig = rcfile<PrettierOptions>('prettier');
async function existPath(filePath: string) {
try {
await fs.promises.access(filePath);
return true;
} catch (error) {
return false;
}
}
const html = (value: string): HTML => ({
type: 'html',
value,
});
const text = (value: string): Text => ({
type: 'text',
value,
});
const paragraph = (value: string): Paragraph => ({
type: 'paragraph',
children: [text(value)],
});
const heading = (depth: Heading['depth'], value: string): Heading => ({
type: 'heading',
depth,
children: [text(value)],
});
const headingSignature = (
depth: Heading['depth'],
value: string,
propName: string
): Heading => ({
type: 'heading',
depth,
children: [text(value), text(' '), inlineCode(propName)],
});
const link = (url: Link['url'], value: string): Link => ({
type: 'link',
url,
children: [text(value)],
});
const code = (lang: string, value: string): Code => ({
type: 'code',
lang,
value,
});
const inlineCode = (value: string): InlineCode => ({
type: 'inlineCode',
value,
});
const table = (
tableHeader: TableRow,
tableBody: TableRow[],
align: AlignType[]
): Table => ({
type: 'table',
align,
children: [tableHeader, ...tableBody],
});
const tableRow = (tableCells: TableCell[]): TableRow => ({
type: 'tableRow',
children: tableCells,
});
const tableCell = (value: string | PhrasingContent): TableCell => ({
type: 'tableCell',
children: [typeof value === 'string' ? text(value) : value],
});
const tableCellMultiline = (children: PhrasingContent[]): TableCell => ({
type: 'tableCell',
children,
});
const parseMarkdownFragmentToAST = (fragmentContent: VFileCompatible) => {
const fragmentAST = unified()
.use(parse)
.use(gfm, gfmOptions)
.use(stringify, stringifyOptions)
.use(mdx)
.parse(fragmentContent) as Root;
return fragmentAST.children;
};
const embeddedDefaultValueRegex = /@@defaultValue@@:\s(.*)$/;
const parseEmbeddedDefaultValue = (
originalDescription: string,
nextPropInfo: ReactComponentProps
): ReactComponentProps => {
const hasEmbeddedDefaultValue = originalDescription.match(
embeddedDefaultValueRegex
);
if (hasEmbeddedDefaultValue) {
const [, value] = hasEmbeddedDefaultValue;
nextPropInfo.description = originalDescription.replace(
embeddedDefaultValueRegex,
''
);
nextPropInfo.defaultValue = {
value,
computed: false,
};
}
return nextPropInfo;
};
// Recursive function to normalize the nested prop types in a flat object shape.
// This is important to then render in the table each nested array/object element
// in a separate row.
const normalizeReactProps = (
normalizedPropName: string,
componentPropsInfo: ReactComponentProps,
options: { isTsx: boolean }
): ReactAPI['props'] => {
if (options.isTsx) {
// NOTE: we can't really normalize the nested TS types, as the AST structure is a bit weird.
// Instead, we print the signature below the table and simply link to that.
return { [normalizedPropName]: componentPropsInfo };
}
const propInfoType = componentPropsInfo.type as ReactComponentPropType;
switch (propInfoType.name) {
case 'arrayOf': {
const arrayValue = propInfoType.value as ReactComponentPropType;
switch (arrayValue.name) {
case 'shape': {
const arrayShapeValue = arrayValue.value as {
[name: string]: ReactComponentPropType;
};
const normalizedArrayShapeProps = Object.entries(
arrayShapeValue
).reduce((normalizedShapeValues, [shapePropName, shapePropInfo]) => {
const originalDescription = shapePropInfo.description ?? '';
const nextPropInfo: ReactComponentProps = parseEmbeddedDefaultValue(
originalDescription,
{
// Here use the nested prop type definition.
type: shapePropInfo,
required: shapePropInfo.required ?? false,
description: originalDescription,
}
);
return {
...normalizedShapeValues,
...normalizeReactProps(
// The name of the prop has the "array + dot" notation (`[].`),
// meaning that it's the property of an object of the array.
`${normalizedPropName}[].${shapePropName}`,
nextPropInfo,
options
),
};
}, {});
return {
// Include the main prop as well.
[normalizedPropName]: {
...componentPropsInfo,
type: {
name: 'array',
},
},
...normalizedArrayShapeProps,
};
}
case 'union': {
const arrayUnionValues = arrayValue.value as ReactComponentPropType[];
const normalizedArrayShapeProps = arrayUnionValues.reduce(
(normalizedShapeValues, shapePropInfo) => ({
...normalizedShapeValues,
...normalizeReactProps(
// The name of the prop has the "array + union" notation (`[]<>`),
// meaning that it's one of the supported shapes of the array.
`${normalizedPropName}[]<${shapePropInfo.name}>`,
{
// Here use the nested prop type definition.
type: shapePropInfo,
required: shapePropInfo.required ?? false,
description: shapePropInfo.description ?? '',
},
options
),
}),
{}
);
return {
// Include the main prop as well.
[normalizedPropName]: {
...componentPropsInfo,
type: {
name: 'array',
},
},
...normalizedArrayShapeProps,
};
}
default:
return { [normalizedPropName]: componentPropsInfo };
}
}
case 'shape': {
const shapeValue = propInfoType.value as {
[name: string]: ReactComponentPropType;
};
const normalizedShapeProps = Object.entries(shapeValue).reduce(
(normalizedShapeValues, [shapePropName, shapePropInfo]) => {
const originalDescription = shapePropInfo.description ?? '';
const nextPropInfo: ReactComponentProps = parseEmbeddedDefaultValue(
originalDescription,
{
// Here use the nested prop type definition.
type: shapePropInfo,
required: shapePropInfo.required ?? false,
description: originalDescription,
defaultValue: componentPropsInfo.defaultValue,
}
);
return {
...normalizedShapeValues,
...normalizeReactProps(
// The name of the prop has the "dot" notation (`.`),
// meaning that it's the property of an object.
`${normalizedPropName}.${shapePropName}`,
nextPropInfo,
options
),
};
},
{}
);
return {
// Include the main prop as well.
[normalizedPropName]: {
...componentPropsInfo,
type: {
name: 'object',
},
},
...normalizedShapeProps,
};
}
case 'union': {
const unionValues = propInfoType.value as ReactComponentPropType[];
const normalizedUnionProps = unionValues.reduce(
(normalizedUnionValues, shapePropInfo) => {
switch (shapePropInfo.name) {
case 'arrayOf':
case 'shape':
return {
...normalizedUnionValues,
...normalizeReactProps(
// The name of the prop has the "union" notation (`<>`),
// meaning that it's one of the supported shapes.
`${normalizedPropName}<${shapePropInfo.name}>`,
{
// Here use the nested prop type definition.
type: shapePropInfo,
required: shapePropInfo.required ?? false,
description: shapePropInfo.description ?? '',
},
options
),
};
}
return normalizedUnionValues;
},
{}
);
return {
// Include the main prop as well.
[normalizedPropName]: componentPropsInfo,
...normalizedUnionProps,
};
}
}
return { [normalizedPropName]: componentPropsInfo };
};
const parsePropTypesToMarkdown = (
componentPath: string,
options: { isTsx: boolean; hasManyComponents: boolean }
): (PhrasingContent | BlockContent)[] => {
const result = reactDocgen.parse(
fs.readFileSync(componentPath, { encoding: 'utf8' }),
reactDocgen.resolver.findExportedComponentDefinition,
[setParamsTypeDefinitionFromFunctionType, ...reactDocgen.defaultHandlers],
{
filename: componentPath,
}
);
const reactAPI: ReactAPI = result;
const tableHeaders = tableRow([
tableCell('Props'),
tableCell('Type'),
tableCell('Required'),
tableCell('Default'),
tableCell('Description'),
]);
const normalizedReactProps = Object.entries(reactAPI.props).reduce(
(normalizedProps, [propName, propInfo]) => ({
...normalizedProps,
...normalizeReactProps(propName, propInfo, options),
}),
{} as ReactAPI['props']
);
const signatures: (PhrasingContent | BlockContent)[] = [];
const tableBody = Object.entries(normalizedReactProps).map(
([propName, propInfo]) => {
let propTypeNode: PhrasingContent[];
if (options.isTsx) {
const propInfoType = propInfo.tsType as ReactComponentTSDescriptor;
switch (propInfoType.name) {
case 'signature': {
switch (propInfoType.type) {
case 'object': {
propTypeNode = [
inlineCode('Object'),
html('<br/>'),
link(`#signature-${propName}`, 'See signature.'),
];
signatures.push(
...[
headingSignature(
options.hasManyComponents ? 4 : 3,
'Signature',
propName
),
code('ts', propInfoType.raw),
]
);
break;
}
case 'function': {
propTypeNode = [
inlineCode('Function'),
html('<br/>'),
link(`#signature-${propName}`, 'See signature.'),
];
signatures.push(
...[
headingSignature(
options.hasManyComponents ? 4 : 3,
'Signature',
propName
),
code('ts', propInfoType.raw),
]
);
break;
}
default:
propTypeNode = [];
break;
}
break;
}
case 'Array': {
propTypeNode = [
inlineCode(`Array: ${propInfoType.raw.replace('\n', '')}`),
html('<br/>'),
link(`#signature-${propName}`, 'See signature.'),
];
signatures.push(
...[
headingSignature(
options.hasManyComponents ? 4 : 3,
'Signature',
propName
),
...propInfoType.elements
.map((elemNode) => {
switch (elemNode.name) {
case 'signature':
return elemNode.raw;
// TODO: add support for more cases?
default:
return undefined;
}
})
.filter(Boolean)
.map((value) => code('ts', value!)),
]
);
break;
}
case 'union': {
const possibleSignatures = propInfoType.elements
.map((elemNode) => {
switch (elemNode.name) {
case 'signature':
return elemNode.raw;
// TODO: add support for more cases?
default:
return undefined;
}
})
.filter(Boolean)
.map((value) => code('ts', value!));
propTypeNode = [
inlineCode(propInfoType.name),
html('<br/>'),
html('Possible values:'),
html('<br/>'),
inlineCode(
(propInfoType.raw || '').replace(/\n/g, '').replace(/\|/g, ',')
),
...(possibleSignatures.length > 0
? [
html('<br/>'),
link(`#signature-${propName}`, 'See signature.'),
]
: []),
];
if (possibleSignatures.length > 0) {
signatures.push(
...[
headingSignature(
options.hasManyComponents ? 4 : 3,
'Signature',
propName
),
...possibleSignatures,
]
);
}
break;
}
default:
propTypeNode = [inlineCode(propInfoType.name)];
}
} else {
const propInfoType = propInfo.type as ReactComponentPropType;
switch (propInfoType.name) {
// This case is only for arrays of scalar values, so we can render it as `Array of <scalar>`.
case 'arrayOf': {
const arrayValue = propInfoType.value as ReactComponentPropType;
propTypeNode = [text('Array of '), inlineCode(arrayValue.name)];
break;
}
// This case is for unions of scalar values, so we can render it as `Array of <scalar>`.
case 'union': {
let unionValues = (
propInfoType.value as ReactComponentPropType[]
).map((union) => union.name);
const combinedUnionValues = unionValues
// FIXME: it seems that there is a regression about escaping mulitple pipes.
// https://github.com/syntax-tree/mdast-util-gfm-table
// .join('\\|');
.join(', ');
propTypeNode = [inlineCode(`<${combinedUnionValues}>`)];
break;
}
case 'enum': {
propTypeNode = [
inlineCode(propInfoType.name),
html('<br/>'),
html('Possible values:'),
html('<br/>'),
inlineCode(
(propInfoType.value as { value: string }[])
.map((enumValue) => enumValue.value)
// FIXME: it seems that there is a regression about escaping mulitple pipes.
// https://github.com/syntax-tree/mdast-util-gfm-table
// .join(' \\| ');
.join(', ')
),
];
break;
}
case 'objectOf': {
propTypeNode = [
inlineCode(
`${propInfoType.name}(${
(propInfoType.value as ReactComponentPropType).name
})`
),
];
break;
}
default: {
propTypeNode = [
inlineCode(
propInfoType.value
? String(propInfoType.value)
: propInfoType.name
),
];
}
}
}
return tableRow([
tableCell(inlineCode(propName)),
tableCellMultiline(propTypeNode),
tableCell(propInfo.required ? '✅' : ''),
tableCell(
propInfo.defaultValue ? inlineCode(propInfo.defaultValue.value) : ''
),
tableCellMultiline(
parseMarkdownFragmentToAST(propInfo.description) as PhrasingContent[]
),
]);
}
);
return [
table(tableHeaders, tableBody, [null, null, 'center', null, null]),
...(signatures.length > 0
? [
heading(options.hasManyComponents ? 3 : 2, 'Signatures'),
...signatures,
]
: []),
];
};
function readmeTransformer(packageFolderPath: string) {
const packageJsonRaw = fs.readFileSync(
path.join(packageFolderPath, 'package.json'),
{ encoding: 'utf8' }
);
const parsedPackageJson = JSON.parse(packageJsonRaw);
const readmeConfig: ReadmeConfig = parsedPackageJson.readme ?? {};
const packageJsonInfo: PackgeJsonInfo = {
name: parsedPackageJson.name,
description: parsedPackageJson.description,
version: parsedPackageJson.version,
peerDependencies: parsedPackageJson.peerDependencies,
};
const isTsx = fs.existsSync(path.join(packageFolderPath, 'src/index.ts'));
const hasCustomComponentsPath = readmeConfig.componentPaths
? readmeConfig.componentPaths.length > 0
: false;
const defaultComponentPath = path.join(
packageFolderPath,
`src/${path.basename(packageFolderPath)}.${isTsx ? 'tsx' : 'js'}`
);
const paths = {
componentPaths:
readmeConfig.componentPaths?.map((componentPath) =>
path.join(packageFolderPath, componentPath)
) ?? [],
description: path.join(packageFolderPath, 'docs/description.md'),
usageExample: path.join(packageFolderPath, 'docs/usage-example.js'),
additionalInfo: path.join(packageFolderPath, 'docs/additional-info.md'),
};
return transformer;
async function transformer(tree: Node, _file: VFile) {
(tree as Parent).children = [
html(
[
'<!-- THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. -->',
'<!-- This file is created by the `yarn generate-readme` script. -->',
].join('\n')
),
// The main heading is derived by the name of the folder
heading(1, upperFirst(camelcase(path.basename(packageFolderPath)))),
// The description is what's defined in the package.json
heading(2, 'Description'),
...((await existPath(paths.description))
? parseMarkdownFragmentToAST(await toVfile.read(paths.description))
: // Fall back to the package.json description field.
[paragraph(packageJsonInfo.description)]),
// Describe the installation steps
heading(2, 'Installation'),
code('', `yarn add ${packageJsonInfo.name}`),
code('', `npm --save install ${packageJsonInfo.name}`),
packageJsonInfo.peerDependencies &&
paragraph(
'Additionally install the peer dependencies (if not present)'
),
packageJsonInfo.peerDependencies &&
code(
'',
`yarn add ${Object.keys(packageJsonInfo.peerDependencies).join(' ')}`
),
code(
'',
`npm --save install ${Object.keys(
packageJsonInfo.peerDependencies
).join(' ')}`
),
// Usage example
heading(2, 'Usage'),
code(
'jsx',
await fs.promises.readFile(paths.usageExample, { encoding: 'utf8' })
),
...(hasCustomComponentsPath
? // Render components in a group, otherwise omit the nested heading.
paths.componentPaths.flatMap((componentPath) => {
const [componentName] = path
.basename(componentPath)
.split(isTsx ? '.tsx' : '.js');
return [
heading(2, upperFirst(camelcase(componentName))),
// Describe the component's properties
heading(3, 'Properties'),
...parsePropTypesToMarkdown(componentPath, {
isTsx,
hasManyComponents: true,
}),
];
})
: [
// Describe the component's properties
heading(2, 'Properties'),
...parsePropTypesToMarkdown(defaultComponentPath, {
isTsx,
hasManyComponents: false,
}),
]),
// Additional information (can be anything, there is no pre-defined structure here)
...((await existPath(paths.additionalInfo))
? parseMarkdownFragmentToAST(await toVfile.read(paths.additionalInfo))
: []),
];
}
}
export async function transformDocument(
doc: VFileCompatible,
packageFolderPath: string
) {
return new Promise<VFile>((resolve, reject) => {
unified()
.use(parse)
.use(gfm, gfmOptions)
.use(stringify, stringifyOptions)
.use(mdx)
.use(readmeTransformer, packageFolderPath)
.process(doc, (err, file) => {
if (err) reject(err);
else resolve(file);
});
});
}
function writeFile(
filePath: string,
file: VFile,
options: GeneratorReadmeOptions
) {
// Assign the path where to write the file to.
file.path = filePath;
// Format file using prettier.
file.contents = prettier.format(file.contents.toString(), {
...prettierConfig,
parser: 'markdown',
});
if (options.dryRun) {
console.log(vfile(file).contents);
} else {
// Write the file to disk.
toVfile.writeSync(file);
}
}
export async function generate(
relativePackagePath: string,
flags: CommandFlags
) {
const options: GeneratorReadmeOptions = {
dryRun: flags.dryRun,
};
if (flags.allWorkspacePackages) {
const workspacePackages = getPackagesSync(process.cwd());
const taskList = new Listr(
workspacePackages.packages.map((packageInfo) => ({
title: `Processing ${packageInfo.packageJson.name}`,
task: async () => {
const readmePath = path.join(packageInfo.dir, 'README.md');
// Create an empty VFile.
const doc = vfile();
const content = await transformDocument(doc, packageInfo.dir);
await writeFile(readmePath, content, options);
},
skip: async () =>
!(await existPath(path.join(packageInfo.dir, 'docs'))),
})),
{
concurrent: 10,
exitOnError: false,
renderer:
// @ts-ignore
process.env.CI === true || process.env.CI === 'true'
? ListrVerboseRenderer
: 'default',
nonTTYRenderer: ListrVerboseRenderer,
}
);
await taskList.run();
} else {
const packageFolderPath = path.resolve(process.cwd(), relativePackagePath);
// Create an empty VFile.
const doc = vfile();
const content = await transformDocument(doc, packageFolderPath);
await writeFile(
path.join(packageFolderPath, 'README.md'),
content,
options
);
}
} | the_stack |
import * as path from "path";
import * as fs from "fs";
import { AddressSpace, IServerBase, ISessionBase, PseudoSession, SessionContext, WellKnownRoles, makeRoles, UAServer, UAServerConfiguration, ContinuationPointManager } from "node-opcua-address-space";
import { generateAddressSpace } from "node-opcua-address-space/nodeJS";
import { NodeClass } from "node-opcua-data-model";
import { nodesets } from "node-opcua-nodesets";
import { assert } from "node-opcua-assert";
import { CertificateManager, OPCUACertificateManager } from "node-opcua-certificate-manager";
import { NodeId } from "node-opcua-nodeid";
import { StatusCodes } from "node-opcua-status-code";
import { MessageSecurityMode, UserNameIdentityToken } from "node-opcua-types";
import { readCertificate } from "node-opcua-crypto";
import { SecurityPolicy } from "node-opcua-secure-channel";
import { ClientPushCertificateManagement, installPushCertificateManagement } from "..";
import { TrustListMasks } from "../source/server/trust_list_server";
import { initializeHelpers } from "./helpers/fake_certificate_authority";
const doDebug = false;
// make sure extra error checking is made on object constructions
// tslint:disable-next-line:no-var-requires
const describe = require("node-opcua-leak-detector").describeWithLeakDetector;
describe("ServerConfiguration", () => {
let addressSpace: AddressSpace;
const opcuaServer: IServerBase = {
userManager: {
getUserRoles(userName: string): NodeId[] {
return makeRoles([WellKnownRoles.AuthenticatedUser, WellKnownRoles.SecurityAdmin]);
}
}
};
const session: ISessionBase = {
userIdentityToken: new UserNameIdentityToken({
userName: "admin"
}),
channel: {
securityMode: MessageSecurityMode.SignAndEncrypt,
securityPolicy: SecurityPolicy.Basic256Sha256,
clientCertificate: Buffer.from("dummy", "ascii")
},
getSessionId() {
return NodeId.nullNodeId;
},
continuationPointManager: new ContinuationPointManager()
};
const _tempFolder = path.join(__dirname, "../temp");
let applicationGroup: CertificateManager;
let userTokenGroup: CertificateManager;
const xmlFiles = [nodesets.standard];
beforeEach(async () => {
try {
await initializeHelpers();
applicationGroup = new CertificateManager({
location: path.join(_tempFolder, "application")
});
userTokenGroup = new CertificateManager({
location: path.join(_tempFolder, "user")
});
await applicationGroup.initialize();
await userTokenGroup.initialize();
addressSpace = AddressSpace.create();
await generateAddressSpace(addressSpace, xmlFiles);
addressSpace.registerNamespace("Private");
} catch (err) {
console.log(err);
throw err;
}
});
afterEach(() => {
addressSpace.dispose();
applicationGroup.dispose();
userTokenGroup.dispose();
});
it("should expose a server configuration object", async () => {
const server = addressSpace.rootFolder.objects.server;
server.should.have.ownProperty("serverConfiguration");
});
interface UAServerWithConfiguration extends UAServer {
serverConfiguration: UAServerConfiguration;
}
it("should expose a server configuration object - Certificate Management", async () => {
const server = addressSpace.rootFolder.objects.server as UAServerWithConfiguration;
// folders
server.serverConfiguration.should.have.ownProperty("certificateGroups");
// properties
server.serverConfiguration.should.have.ownProperty("maxTrustListSize");
server.serverConfiguration.should.have.ownProperty("multicastDnsEnabled");
server.serverConfiguration.should.have.ownProperty("serverCapabilities");
server.serverConfiguration.should.have.ownProperty("supportedPrivateKeyFormats");
// methods
server.serverConfiguration.should.have.ownProperty("applyChanges");
server.serverConfiguration.should.have.ownProperty("createSigningRequest");
server.serverConfiguration.should.have.ownProperty("getRejectedList");
server.serverConfiguration.should.have.ownProperty("updateCertificate");
});
it("server configuration should make its first level object visible", () => {
// ServerConfiguration Object and its immediate children shall be visible (i.e. browse access is available) to
// users who can access the Server Object.
// todo
});
it("server configuration should hide children of certificate groups to non admin user", () => {
// The children of the CertificateGroups Object should
// only be visible to authorized administrators.
// todo
});
it("should expose a server configuration object - KeyCredential Management", async () => {
const server = addressSpace.rootFolder.objects.server as UAServerWithConfiguration;
server.serverConfiguration.should.have.ownProperty("keyCredentialConfiguration");
});
it("should expose a server configuration object - Authorization Management", async () => {
const server = addressSpace.rootFolder.objects.server as UAServerWithConfiguration;
server.serverConfiguration.should.have.ownProperty("authorizationServices");
});
describe("Push Certificate Management model", () => {
//
// from OpcUA Specification part#12 7.3:
// Push management is targeted at Server applications to
// get a Certificate Request which can be passed onto the CertificateManager.
// After the CertificateManager signs the Certificate the new Certificate
// is pushed to the Server with the UpdateCertificate Method
// The Administration Component may be part of the CertificateManager or a standalone utility
// that uses OPC UA to communicate with the CertificateManager.
// The Configuration Database is used by the Server to persist its configuration information.
// The RegisterApplication Method (or internal equivalent) is assumed to have been called
// before the sequence in the diagram starts.
// A similar process is used to renew certificates or to periodically update Trust List.
// Security when using the Push Management Model requires an encrypted channel and the use
// of Administrator credentials for the Server that ensure only authorized users can update
// Certificates or Trust Lists. In addition, separate Administrator credentials are required for the
// CertificateManager that ensure only authorized users can register new Servers and request
// new Certificates.
it("should implement createSigningRequest", async () => {
await installPushCertificateManagement(addressSpace, { applicationGroup, userTokenGroup, applicationUri: "SomeURI" });
const server = addressSpace.rootFolder.objects.server as UAServerWithConfiguration;
server.serverConfiguration.createSigningRequest.nodeClass.should.eql(NodeClass.Method);
const context = new SessionContext({ server: opcuaServer, session });
const pseudoSession = new PseudoSession(addressSpace, context);
const clientPullCertificateManager = new ClientPushCertificateManagement(pseudoSession);
const certificateGroupId = await clientPullCertificateManager.getCertificateGroupId("DefaultApplicationGroup");
const certificateTypeId = NodeId.nullNodeId;
const subjectName = "/O=NodeOPCUA/CN=urn:NodeOPCUA-Server";
const regeneratePrivateKey = false;
const nonce = Buffer.alloc(0);
const result = await clientPullCertificateManager.createSigningRequest(
certificateGroupId,
certificateTypeId,
subjectName,
regeneratePrivateKey,
nonce
);
result.statusCode.should.eql(StatusCodes.Good);
});
xit("should implement UpdateCertificate", async () => {
await installPushCertificateManagement(addressSpace, { applicationUri: "SomeUri" });
const context = new SessionContext({ server: opcuaServer, session });
const pseudoSession = new PseudoSession(addressSpace, context);
const clientPushCertificateManager = new ClientPushCertificateManagement(pseudoSession);
const certificateGroupId = NodeId.nullNodeId;
const certificateTypeId = NodeId.nullNodeId;
const certificate = Buffer.from("SomeCertificate");
const issuerCertificates = [Buffer.from("Issuer1"), Buffer.from("Issuer2")];
const privateKeyFormat = "PEM";
const privateKey = Buffer.from("1234");
const result = await clientPushCertificateManager.updateCertificate(
certificateGroupId,
certificateTypeId,
certificate,
issuerCertificates
);
result.statusCode.should.eql(StatusCodes.BadInvalidArgument);
// result.applyChangesRequired!.should.eql(true);
});
async function give_a_address_space_with_server_configuration_and_default_application_group() {
const rootFolder = path.join(__dirname, "../temp/pkipki");
const certificateManager = new OPCUACertificateManager({
rootFolder
});
await certificateManager.initialize();
const server = addressSpace.rootFolder.objects.server as UAServerWithConfiguration;
const defaultApplicationGroup = server .serverConfiguration.certificateGroups.defaultApplicationGroup;
(defaultApplicationGroup.trustList as any).$$certificateManager = certificateManager;
}
it("should provide trust list", async () => {
//------------------
await installPushCertificateManagement(
addressSpace, { applicationGroup, userTokenGroup, applicationUri: "SomeUri" });
const context = new SessionContext({ server: opcuaServer, session });
const pseudoSession = new PseudoSession(addressSpace, context);
const clientPushCertificateManager = new ClientPushCertificateManagement(pseudoSession);
const defaultApplicationGroup = await clientPushCertificateManager.getCertificateGroup("DefaultApplicationGroup");
const trustList = await defaultApplicationGroup.getTrustList();
let a = await trustList.readTrustedCertificateList();
console.log(a.toString());
// now add a certificate
const certificateFile = path.join(__dirname, "../../node-opcua-samples/certificates/client_cert_2048.pem");
assert(fs.existsSync(certificateFile));
const certificate = await readCertificate(certificateFile);
const sc = await trustList.addCertificate(certificate, true);
sc.should.eql(StatusCodes.Good);
a = await trustList.readTrustedCertificateList();
console.log(a.toString());
a.trustedCertificates!.length.should.eql(1);
a.issuerCertificates!.length.should.eql(1); // the issuer certificate in the chain
a.issuerCrls!.length.should.eql(0);
a.trustedCrls!.length.should.eql(0);
});
it("should provide trust list with masks - issuer certificates", async () => {
//------------------
await installPushCertificateManagement(
addressSpace, { applicationGroup, userTokenGroup, applicationUri: "SomeUri" });
const context = new SessionContext({ server: opcuaServer, session });
const pseudoSession = new PseudoSession(addressSpace, context);
const clientPushCertificateManager = new ClientPushCertificateManagement(pseudoSession);
const defaultApplicationGroup = await clientPushCertificateManager.getCertificateGroup("DefaultApplicationGroup");
const trustList = await defaultApplicationGroup.getTrustList();
let a = await trustList.readTrustedCertificateListWithMasks(TrustListMasks.IssuerCertificates);
doDebug && console.log(a.toString());
a.trustedCertificates!.length.should.eql(0);
a.issuerCertificates!.length.should.eql(0);
a.issuerCrls!.length.should.eql(0);
a.trustedCrls!.length.should.eql(0);
// now add a certificate
{
const certificateFile = path.join(__dirname, "../../node-opcua-samples/certificates/client_cert_2048.pem");
assert(fs.existsSync(certificateFile));
const certificate = await readCertificate(certificateFile);
const sc = await trustList.addCertificate(certificate, /*isTrustedCertificate =*/false);
sc.should.eql(StatusCodes.Good);
}
{
const selfSignedCertificateFile = path.join(__dirname, "../../node-opcua-samples/certificates/client_selfsigned_cert_2048.pem");
assert(fs.existsSync(selfSignedCertificateFile));
const certificate = await readCertificate(selfSignedCertificateFile);
const sc = await trustList.addCertificate(certificate, /*isTrustedCertificate =*/true);
sc.should.eql(StatusCodes.Good);
}
a = await trustList.readTrustedCertificateListWithMasks(TrustListMasks.IssuerCertificates);
doDebug && console.log(a.toString());
a.specifiedLists.should.eql(TrustListMasks.IssuerCertificates);
a.trustedCertificates!.length.should.eql(0);
a.issuerCertificates!.length.should.eql(2);
a.issuerCrls!.length.should.eql(0);
a.trustedCrls!.length.should.eql(0);
a = await trustList.readTrustedCertificateListWithMasks(TrustListMasks.TrustedCertificates);
doDebug && console.log(a.toString());
a.specifiedLists.should.eql(TrustListMasks.TrustedCertificates);
a.trustedCertificates!.length.should.eql(1);
a.issuerCertificates!.length.should.eql(0);
a.issuerCrls!.length.should.eql(0);
a.trustedCrls!.length.should.eql(0);
});
});
}); | the_stack |
import Cookies from 'js-cookie';
import {analyticsEvent} from '../util/analytics';
import {DataSource, DataSourceEnum, SourceSelection} from './data_source';
import {Date, DateOrRange, JsonFam, JsonIndi} from 'topola';
import {GedcomData, normalizeGedcom, TopolaData} from '../util/gedcom_util';
import {GedcomEntry} from 'parse-gedcom';
import {IntlShape} from 'react-intl';
import {TopolaError} from '../util/error';
/** Prefix for IDs of private individuals. */
export const PRIVATE_ID_PREFIX = '~Private';
/**
* Cookie where the logged in user name is stored. This cookie is shared
* between apps hosted on apps.wikitree.com.
*/
const USER_NAME_COOKIE = 'wikidb_wtb_UserName';
/** WikiTree API getAncestors request. */
interface GetAncestorsRequest {
action: 'getAncestors';
key: string;
fields: string;
}
/** WikiTree API getRelatives request. */
interface GetRelativesRequest {
action: 'getRelatives';
keys: string;
getChildren?: true;
getSpouses?: true;
}
/** WikiTree API clientLogin request. */
interface ClientLoginRequest {
action: 'clientLogin';
authcode: string;
}
/** WikiTree API clientLogin response. */
interface ClientLoginResponse {
result: string;
username: string;
}
type WikiTreeRequest =
| GetAncestorsRequest
| GetRelativesRequest
| ClientLoginRequest;
/** Person structure returned from WikiTree API. */
interface Person {
Id: number;
Name: string;
FirstName: string;
LastNameAtBirth: string;
RealName: string;
Spouses?: {[key: number]: Person};
Children: {[key: number]: Person};
Mother: number;
Father: number;
Gender: string;
BirthDate: string;
DeathDate: string;
BirthLocation: string;
DeathLocation: string;
BirthDateDecade: string;
DeathDateDecade: string;
marriage_location: string;
marriage_date: string;
DataStatus?: {
BirthDate: string;
DeathDate: string;
};
PhotoData?: {
path: string;
url: string;
};
}
/** Gets item from session storage. Logs exception if one is thrown. */
function getSessionStorageItem(key: string): string | null {
try {
return sessionStorage.getItem(key);
} catch (e) {
console.warn('Failed to load data from session storage: ' + e);
}
return null;
}
/** Sets item in session storage. Logs exception if one is thrown. */
function setSessionStorageItem(key: string, value: string) {
try {
sessionStorage.setItem(key, value);
} catch (e) {
console.warn('Failed to store data in session storage: ' + e);
}
}
/** Sends a request to the WikiTree API. Returns the parsed response JSON. */
async function wikiTreeGet(request: WikiTreeRequest, handleCors: boolean) {
const requestData = new FormData();
requestData.append('format', 'json');
for (const key in request) {
requestData.append(key, request[key]);
}
const apiUrl = handleCors
? 'https://topola-cors.herokuapp.com/https://api.wikitree.com/api.php'
: 'https://api.wikitree.com/api.php';
const response = await window.fetch(apiUrl, {
method: 'POST',
body: requestData,
credentials: handleCors ? undefined : 'include',
});
const responseBody = await response.text();
return JSON.parse(responseBody);
}
/**
* Retrieves ancestors from WikiTree for the given person ID.
* Uses sessionStorage for caching responses.
*/
async function getAncestors(
key: string,
handleCors: boolean,
): Promise<Person[]> {
const cacheKey = `wikitree:ancestors:${key}`;
const cachedData = getSessionStorageItem(cacheKey);
if (cachedData) {
return JSON.parse(cachedData);
}
const response = await wikiTreeGet(
{
action: 'getAncestors',
key: key,
fields: '*',
},
handleCors,
);
const result = response[0].ancestors as Person[];
setSessionStorageItem(cacheKey, JSON.stringify(result));
return result;
}
/**
* Retrieves relatives from WikiTree for the given array of person IDs.
* Uses sessionStorage for caching responses.
*/
async function getRelatives(
keys: string[],
handleCors: boolean,
): Promise<Person[]> {
const result: Person[] = [];
const keysToFetch: string[] = [];
keys.forEach((key) => {
const cachedData = getSessionStorageItem(`wikitree:relatives:${key}`);
if (cachedData) {
result.push(JSON.parse(cachedData));
} else {
keysToFetch.push(key);
}
});
if (keysToFetch.length === 0) {
return result;
}
const response = await wikiTreeGet(
{
action: 'getRelatives',
keys: keysToFetch.join(','),
getChildren: true,
getSpouses: true,
},
handleCors,
);
if (response[0].items === null) {
const id = keysToFetch[0];
throw new TopolaError(
'WIKITREE_PROFILE_NOT_FOUND',
`WikiTree profile ${id} not found`,
{id},
);
}
const fetchedResults = response[0].items.map(
(x: {person: Person}) => x.person,
) as Person[];
fetchedResults.forEach((person) => {
setSessionStorageItem(
`wikitree:relatives:${person.Name}`,
JSON.stringify(person),
);
});
return result.concat(fetchedResults);
}
export async function clientLogin(
authcode: string,
): Promise<ClientLoginResponse> {
const response = await wikiTreeGet(
{
action: 'clientLogin',
authcode,
},
false,
);
return response.clientLogin;
}
/**
* Returnes the logged in user name or undefined if not logged in.
*
* This is not an authoritative answer. The result of this function relies on
* the cookies set on the apps.wikitree.com domain under which this application
* is hosted. The authoritative source of login information is in cookies set on
* the api.wikitree.com domain.
*/
export function getLoggedInUserName(): string | undefined {
return Cookies.get(USER_NAME_COOKIE);
}
/**
* Loads data from WikiTree to populate an hourglass chart starting from the
* given person ID.
*/
export async function loadWikiTree(
key: string,
intl: IntlShape,
authcode?: string,
): Promise<TopolaData> {
// Work around CORS if not in apps.wikitree.com domain.
const handleCors = window.location.hostname !== 'apps.wikitree.com';
if (!handleCors && !getLoggedInUserName() && authcode) {
const loginResult = await clientLogin(authcode);
if (loginResult.result === 'Success') {
sessionStorage.clear();
Cookies.set(USER_NAME_COOKIE, loginResult.username);
}
}
const everyone: Person[] = [];
// Fetch the ancestors of the input person and ancestors of his/her spouses.
const firstPerson = await getRelatives([key], handleCors);
if (!firstPerson[0].Name) {
const id = key;
throw new TopolaError(
'WIKITREE_PROFILE_NOT_ACCESSIBLE',
`WikiTree profile ${id} is not accessible. Try logging in.`,
{id},
);
}
const spouseKeys = Object.values(firstPerson[0].Spouses || {}).map(
(s) => s.Name,
);
const ancestors = await Promise.all(
[key]
.concat(spouseKeys)
.map((personId) => getAncestors(personId, handleCors)),
);
const ancestorKeys = ancestors
.flat()
.map((person) => person.Name)
.filter((key) => !!key);
const ancestorDetails = await getRelatives(ancestorKeys, handleCors);
// Map from person id to father id if the father profile is private.
const privateFathers: Map<number, number> = new Map();
// Map from person id to mother id if the mother profile is private.
const privateMothers: Map<number, number> = new Map();
// Andujst private individual ids so that there are no collisions in the case
// that ancestors were collected for more than one person.
ancestors.forEach((ancestorList, index) => {
const offset = 1000 * index;
// Adjust ids by offset.
ancestorList.forEach((person) => {
if (person.Id < 0) {
person.Id -= offset;
person.Name = `${PRIVATE_ID_PREFIX}${person.Id}`;
}
if (person.Father < 0) {
person.Father -= offset;
privateFathers.set(person.Id, person.Father);
}
if (person.Mother < 0) {
person.Mother -= offset;
privateMothers.set(person.Id, person.Mother);
}
});
});
// Set the Father and Mother fields again because getRelatives doesn't return
// private parents.
ancestorDetails.forEach((person) => {
const privateFather = privateFathers.get(person.Id);
if (privateFather) {
person.Father = privateFather;
}
const privateMother = privateMothers.get(person.Id);
if (privateMother) {
person.Mother = privateMother;
}
});
everyone.push(...ancestorDetails);
// Collect private individuals.
const privateAncestors = ancestors.flat().filter((person) => person.Id < 0);
everyone.push(...privateAncestors);
// Limit the number of generations of descendants because there may be tens of
// generations for some profiles.
const descendantGenerationLimit = 5;
// Fetch descendants recursively.
let toFetch = [key];
let generation = 0;
while (toFetch.length > 0 && generation <= descendantGenerationLimit) {
const people = await getRelatives(toFetch, handleCors);
everyone.push(...people);
const allSpouses = people.flatMap((person) =>
Object.values(person.Spouses || {}),
);
everyone.push(...allSpouses);
// Fetch all children.
toFetch = people.flatMap((person) =>
Object.values(person.Children).map((c) => c.Name),
);
generation++;
}
// Map from person id to the set of families where they are a spouse.
const families = new Map<number, Set<string>>();
// Map from family id to the set of children.
const children = new Map<string, Set<number>>();
// Map from famliy id to the spouses.
const spouses = new Map<
string,
{wife?: number; husband?: number; spouse?: Person}
>();
// Map from numerical id to human-readable id.
const idToName = new Map<number, string>();
everyone.forEach((person) => {
idToName.set(person.Id, person.Name);
if (person.Mother || person.Father) {
const famId = getFamilyId(person.Mother, person.Father);
getSet(families, person.Mother).add(famId);
getSet(families, person.Father).add(famId);
getSet(children, famId).add(person.Id);
spouses.set(famId, {
wife: person.Mother || undefined,
husband: person.Father || undefined,
});
}
});
const indis: JsonIndi[] = [];
const converted = new Set<number>();
everyone.forEach((person) => {
if (converted.has(person.Id)) {
return;
}
converted.add(person.Id);
const indi = convertPerson(person, intl);
if (person.Spouses) {
Object.values(person.Spouses).forEach((spouse) => {
const famId = getFamilyId(person.Id, spouse.Id);
getSet(families, person.Id).add(famId);
getSet(families, spouse.Id).add(famId);
const familySpouses =
person.Gender === 'Male'
? {wife: spouse.Id, husband: person.Id, spouse}
: {wife: person.Id, husband: spouse.Id, spouse};
spouses.set(famId, familySpouses);
});
}
indi.fams = Array.from(getSet(families, person.Id));
indis.push(indi);
});
const fams = Array.from(spouses.entries()).map(([key, value]) => {
const fam: JsonFam = {
id: key,
};
const wife = value.wife && idToName.get(value.wife);
if (wife) {
fam.wife = wife;
}
const husband = value.husband && idToName.get(value.husband);
if (husband) {
fam.husb = husband;
}
fam.children = Array.from(getSet(children, key)).map(
(child) => idToName.get(child)!,
);
if (
value.spouse &&
((value.spouse.marriage_date &&
value.spouse.marriage_date !== '0000-00-00') ||
value.spouse.marriage_location)
) {
const parsedDate = parseDate(value.spouse.marriage_date);
fam.marriage = Object.assign({}, parsedDate, {
place: value.spouse.marriage_location,
});
}
return fam;
});
const chartData = normalizeGedcom({indis, fams});
const gedcom = buildGedcom(indis);
return {chartData, gedcom};
}
/** Creates a family identifier given 2 spouse identifiers. */
function getFamilyId(spouse1: number, spouse2: number) {
if (spouse2 > spouse1) {
return `${spouse1}_${spouse2}`;
}
return `${spouse2}_${spouse1}`;
}
function convertPerson(person: Person, intl: IntlShape): JsonIndi {
const indi: JsonIndi = {
id: person.Name,
};
if (person.Name.startsWith(PRIVATE_ID_PREFIX)) {
indi.hideId = true;
indi.firstName = intl.formatMessage({
id: 'wikitree.private',
defaultMessage: 'Private',
});
}
if (person.FirstName && person.FirstName !== 'Unknown') {
indi.firstName = person.FirstName;
} else if (person.RealName && person.RealName !== 'Unknown') {
indi.firstName = person.RealName;
}
if (person.LastNameAtBirth !== 'Unknown') {
indi.lastName = person.LastNameAtBirth;
}
if (person.Mother || person.Father) {
indi.famc = getFamilyId(person.Mother, person.Father);
}
if (person.Gender === 'Male') {
indi.sex = 'M';
} else if (person.Gender === 'Female') {
indi.sex = 'F';
}
if (
(person.BirthDate && person.BirthDate !== '0000-00-00') ||
person.BirthLocation ||
person.BirthDateDecade !== 'unknown'
) {
const parsedDate = parseDate(
person.BirthDate,
person.DataStatus && person.DataStatus.BirthDate,
);
const date = parsedDate || parseDecade(person.BirthDateDecade);
indi.birth = Object.assign({}, date, {place: person.BirthLocation});
}
if (
(person.DeathDate && person.DeathDate !== '0000-00-00') ||
person.DeathLocation ||
person.DeathDateDecade !== 'unknown'
) {
const parsedDate = parseDate(
person.DeathDate,
person.DataStatus && person.DataStatus.DeathDate,
);
const date = parsedDate || parseDecade(person.DeathDateDecade);
indi.death = Object.assign({}, date, {place: person.DeathLocation});
}
if (person.PhotoData) {
indi.images = [{url: `https://www.wikitree.com${person.PhotoData.url}`}];
}
return indi;
}
/**
* Parses a date in the format returned by WikiTree and converts in to
* the format defined by Topola.
*/
function parseDate(date: string, dataStatus?: string): DateOrRange | undefined {
if (!date) {
return undefined;
}
const matchedDate = date.match(/(\d\d\d\d)-(\d\d)-(\d\d)/);
if (!matchedDate) {
return {date: {text: date}};
}
const parsedDate: Date = {};
if (matchedDate[1] !== '0000') {
parsedDate.year = ~~matchedDate[1];
}
if (matchedDate[2] !== '00') {
parsedDate.month = ~~matchedDate[2];
}
if (matchedDate[3] !== '00') {
parsedDate.day = ~~matchedDate[3];
}
if (dataStatus === 'after') {
return {dateRange: {from: parsedDate}};
}
if (dataStatus === 'before') {
return {dateRange: {to: parsedDate}};
}
if (dataStatus === 'guess') {
parsedDate.qualifier = 'abt';
}
return {date: parsedDate};
}
function parseDecade(decade: string): DateOrRange | undefined {
return decade !== 'unknown' ? {date: {text: decade}} : undefined;
}
/**
* Creates a GEDCOM structure for the purpose of displaying the details
* panel.
*/
function buildGedcom(indis: JsonIndi[]): GedcomData {
const gedcomIndis: {[key: string]: GedcomEntry} = {};
indis.forEach((indi) => {
// WikiTree URLs replace spaces with underscores.
const escapedId = indi.id.replace(/ /g, '_');
gedcomIndis[indi.id] = {
level: 0,
pointer: `@${indi.id}@`,
tag: 'INDI',
data: '',
tree: [
{
level: 1,
pointer: '',
tag: 'NAME',
data: `${indi.firstName || ''} /${indi.lastName || ''}/`,
tree: [],
},
],
};
if (!indi.id.startsWith('~')) {
gedcomIndis[indi.id].tree.push({
level: 1,
pointer: '',
tag: 'WWW',
data: `https://www.wikitree.com/wiki/${escapedId}`,
tree: [],
});
}
});
return {
head: {level: 0, pointer: '', tag: 'HEAD', data: '', tree: []},
indis: gedcomIndis,
fams: {},
other: {},
};
}
/**
* Returns a set which is a value from a SetMultimap. If the key doesn't exist,
* an empty set is added to the map.
*/
function getSet<K, V>(map: Map<K, Set<V>>, key: K): Set<V> {
const set = map.get(key);
if (set) {
return set;
}
const newSet = new Set<V>();
map.set(key, newSet);
return newSet;
}
export interface WikiTreeSourceSpec {
source: DataSourceEnum.WIKITREE;
authcode?: string;
}
/** Loading data from the WikiTree API. */
export class WikiTreeDataSource implements DataSource<WikiTreeSourceSpec> {
constructor(private intl: IntlShape) {}
isNewData(
newSource: SourceSelection<WikiTreeSourceSpec>,
oldSource: SourceSelection<WikiTreeSourceSpec>,
data?: TopolaData,
): boolean {
if (!newSource.selection) {
return false;
}
if (oldSource.selection?.id === newSource.selection.id) {
// Selection unchanged -> don't reload.
return false;
}
if (
data &&
data.chartData.indis.some((indi) => indi.id === newSource.selection?.id)
) {
// New selection exists in current view -> animate instead of reloading.
return false;
}
return true;
}
async loadData(
source: SourceSelection<WikiTreeSourceSpec>,
): Promise<TopolaData> {
if (!source.selection) {
throw new TopolaError(
'WIKITREE_ID_NOT_PROVIDED',
'WikiTree id needs to be provided',
);
}
try {
const data = await loadWikiTree(
source.selection.id,
this.intl,
source.spec.authcode,
);
analyticsEvent('wikitree_loaded');
return data;
} catch (error) {
analyticsEvent('wikitree_error');
throw error;
}
}
} | the_stack |
import { TreeSelectProps, TreeNodeRender } from "./interface";
import React, {
useState,
useEffect,
useCallback,
useMemo,
useRef
} from "react";
import classnames from "classnames";
import * as R from "ramda";
import PropTypes from "prop-types";
import Tag from "../Tag";
import Ico from "../Ico";
import Trigger from "../Trigger";
import Checkbox from "../Checkbox";
type SublingCheckedType = "none" | "some" | "all";
type CheckedIdList = TreeSelectProps["value"];
type CheckedIds = Set<TreeNodeRender["id"]>;
const TreeSelect: React.FunctionComponent<TreeSelectProps> = (
props: TreeSelectProps
) => {
/** 变量 */
const {
data,
defaultValue,
value,
multiple = false,
treeDefaultExpandAll,
treeRenderPropReflect,
treeDefaultExpandedKeys,
treeNodeRender,
filterTreeNode,
tagTheme,
className,
style,
size,
allowClear,
onDropDownVisibleChange,
showCheckedStrategy,
disabled,
placeholder,
searchable,
switcherIcon,
autoClearSearchValue = true,
onChange,
onSearch,
onTreeExpand,
suffixIcon,
loadData,
stretch,
listHeight
} = props;
const SeacrhInputRef = useRef(null);
const CountWidth = useRef(null);
const ListPopupRef = useRef(null);
const [filterString, setFileterString] = useState("");
const [checkedIds, setCheckedIds] = useState<CheckedIds>(
value ? new Set(value) : defaultValue ? new Set(defaultValue) : new Set()
);
const [searchFocus, setSearchFocus] = useState(false); // 记录搜索框的 聚焦状态
const [expandIds, setExpandIds] = useState<CheckedIds>(new Set());
const [showOption, setShowOption] = useState(false); // 下拉的状态改变
const [indeterminateIds, setIndeterminateIds] = useState(new Set());
const [loadingNode, setLoadingNode] = useState(undefined);
/** 方法 */
const initTreeStruct = useCallback(
(treeNode: Array<TreeNodeRender>, renderList, level: number = 0) => {
// 全部节点展开铺平的列表
// 包含树简单的信息 确定之后不再改变
treeNode.forEach((item) => {
if (treeRenderPropReflect) {
const { id = "id", label = "label" } = treeRenderPropReflect;
item.id = item[id];
item.label = item[label];
}
renderList.push({
level,
id: item.id,
label: item.label,
disabled: item.disabled || false
});
if (treeRenderPropReflect) {
const { children = "children" } = treeRenderPropReflect;
if (item[children] && item[children].length)
initTreeStruct(item[children], renderList, level + 1);
} else {
if (item.children && item.children.length)
initTreeStruct(item.children, renderList, level + 1);
}
});
return renderList;
},
[treeRenderPropReflect]
);
const treeStruct = useMemo(
() => {
// 树的平铺结构
return initTreeStruct(data, []);
},
[initTreeStruct, data]
);
const diffAllParent = useCallback((treeNode: TreeNodeRender, newIds) => {
// 有不同类型的计算 展开 或者 半选 依据上下文
while (treeNode && treeNode.parent !== null) {
treeNode = treeNode.parent;
if (treeNode.disabled) treeNode = null;
else {
newIds.add(treeNode.id);
}
}
}, []);
const dimensionMinusTo1 = useCallback(
(
parentNode: TreeNodeRender,
treeNode: Array<TreeNodeRender>,
renderList: Array<TreeNodeRender> = [],
level: number = 0,
newExpandIds: Set<TreeNodeRender["id"]>
): Array<TreeNodeRender> => {
// 把树变成一个列表 带有树的详细信息 checked expand indeterminate 需要另外计算 默认 false
const defaultExpandKeys = new Set(treeDefaultExpandedKeys);
treeNode.forEach((item: TreeNodeRender) => {
if (treeRenderPropReflect) {
const {
id = "id",
label = "label",
children = "children"
} = treeRenderPropReflect;
item.id = item[id];
item.label = item[label];
item.children = item[children];
}
if (multiple && !item.hasOwnProperty("checkable")) {
// 在multiple开启下 优先取传进来的checkable 属性 没有 checkable的赋值ture
// 节点是否可选 要依据 multiple 和 checkable 两个属性
item.checkable = true;
}
// 三个默认值 默认会覆盖了
multiple && (item.checked = false);
multiple && (item.indeterminate = false);
item.expand = false;
// 如果有传key就用传进来的
item.key = item.key || `${item.id}-${level}`;
item.level = level;
item.parent = parentNode;
if (treeDefaultExpandAll || defaultExpandKeys.has(item.id)) {
item.expand = true;
newExpandIds.add(item.id);
}
if (defaultExpandKeys.has(item.id)) {
diffAllParent(item, newExpandIds);
}
renderList.push(item);
if (item.children && item.children.length) {
dimensionMinusTo1(
item,
item.children,
renderList,
level + 1,
newExpandIds
);
}
});
return renderList;
},
[treeRenderPropReflect, multiple, treeDefaultExpandedKeys, diffAllParent, treeDefaultExpandAll]
);
const nodeRenderList = useMemo(
() => {
// 添加深拷贝 防止 多个组件使用同一数据源而造成组件的状态同步
const newExpandIds: Set<TreeNodeRender["id"]> = new Set();
const preRenderList = dimensionMinusTo1(
null,
R.clone(data),
[],
0,
newExpandIds
);
// 添加树节点的位置信息
const treeDeepTrack = new Map();
let markedLevel = -1;
preRenderList.map(item => {
if (item.level < markedLevel) {
while (item.level < markedLevel) {
treeDeepTrack.delete(markedLevel);
markedLevel -= 1;
}
}
markedLevel = item.level;
const existIndex = treeDeepTrack.get(item.level) || 0;
treeDeepTrack.set(item.level, existIndex + 1);
const position = [];
treeDeepTrack.forEach(item => {
position.push(item);
});
item.position = position.join(",");
});
setExpandIds(newExpandIds);
return preRenderList;
},
[dimensionMinusTo1, data]
);
const diffSublingNode = useCallback(
(node: TreeNodeRender, newcheckedIds) => {
let { id: checkedId, level: checkedLevel } = node;
let { id: checkedParentId, level: checkedParentLevel } = node.parent; // 调用前已经确认了有父节点
let isFind = false;
let allChecked = true;
let checkedChildrenId = [];
let childrenId = [];
let checkedType: SublingCheckedType = "none"; // 兄弟节点被选的情况 none | some | all
for (let i in treeStruct) {
if (treeStruct[i].id === checkedParentId) {
// 先找到该节点(node)的父节点 标记
isFind = true;
continue;
}
if (isFind && treeStruct[i].level <= checkedParentLevel) {
// = 的情况是 父节点 后 还有同级的节点
// < 的情况是 父节点 后 没有同级的节点 是 父节点 的 父节点 级别的
// 退出循环
break;
}
if (isFind && checkedLevel === treeStruct[i].level) {
childrenId.push(treeStruct[i].id);
if (checkedId !== treeStruct[i].id) {
// 同 level 的 并 排除自身
if (
!newcheckedIds.has(treeStruct[i].id) &&
!treeStruct[i].disabled
) {
// 排除disabled 的节点
allChecked = false;
}
if (
newcheckedIds.has(treeStruct[i].id) ||
nodeRenderList[i].indeterminate
) {
// 半选状态也被记为 some的一种
checkedChildrenId.push(treeStruct[i].id);
}
}
}
}
if (checkedChildrenId.length) checkedType = "some";
if (allChecked) checkedType = "all";
return { checkedType, checkedChildrenId, childrenId };
},
[treeStruct, nodeRenderList]
);
const clearAllChildNodeId = useCallback(
(node, newcheckedIds, newIndeterminateIds) => {
if (node.children && node.children.length) {
// 删除已选节点下的所有的已选的子子孙孙节点
let isFind = false;
let isDisabled = false;
let disabledLevel = -1;
for (let i in treeStruct) {
if (treeStruct[i].id === node.id) {
isFind = true;
continue;
}
if (disabledLevel >= treeStruct[i].level) {
disabledLevel = -1;
}
if (isFind && treeStruct[i].level <= node.level) {
break;
}
if (isFind) {
if (treeStruct[i].disabled) {
// 删除下级节点的过程中碰到了disabled的节点,跳过该节点的所有下级节点
isDisabled = true;
disabledLevel = treeStruct[i].level;
}
if (isDisabled && disabledLevel !== -1) continue;
newcheckedIds.delete(treeStruct[i].id);
newIndeterminateIds.delete(treeStruct[i].id);
}
}
}
},
[treeStruct]
);
/**
* 变更
* @param {bool} value - true 选中 false 取消选中
*/
const caculateSelectedKey = useCallback(
(newcheckedIds, checkedItem: TreeNodeRender, value): CheckedIds => {
let { id: checkedId } = checkedItem;
let { id: checkedParentId } = checkedItem.parent || {};
const newIndeterminateIds = new Set(indeterminateIds);
if (value) {
// 删除下级节点
if (checkedItem.children && checkedItem.children.length)
clearAllChildNodeId(checkedItem, newcheckedIds, newIndeterminateIds);
// 向上遍历
if (checkedParentId) {
let sublingItemAllChecked = true;
let diffNode = checkedItem;
// 所有父级节点加为半选
diffAllParent(checkedItem, newIndeterminateIds);
// 检查 被选项 的兄弟 节点 是否已经被选择
// 如果已被选择 删掉 兄弟节点的数据 添加父节点 为 已选择节点
// 重复这个步骤直到 到 一级的节点
while (sublingItemAllChecked && diffNode.parent) {
// 获取兄弟节点的选中状态
const { checkedType, childrenId } = diffSublingNode(
diffNode,
newcheckedIds
);
// 父节点disabled的话要停止向上遍历
if (checkedType === "all" && !diffNode.parent.disabled) {
childrenId.forEach(item => {
newcheckedIds.delete(item);
});
// 准备下一次遍历 能循环就确定了有父节点
diffNode = diffNode.parent;
// 添加 父 节点 为 已选状态
newcheckedIds.add(diffNode.id);
// 删除父节点的半选状态
newIndeterminateIds.delete(diffNode.id);
} else {
// 结束遍历
sublingItemAllChecked = false;
// 添加该节点为已选节点
newcheckedIds.add(diffNode.id);
}
}
} else {
// 没有父节点 直接添加该节点为已选
newcheckedIds.add(checkedId);
}
} else {
let diffNode = checkedItem;
// 消除自身的选中状态
newIndeterminateIds.delete(diffNode.id);
newcheckedIds.delete(checkedId);
const checkedChildrenIds = []; // 记录向上遍历时选中的节点
while (diffNode.parent && !diffNode.parent.disabled) {
if (diffNode.parent.checked) {
diffNode.parent.children.forEach(item => {
if (item.id !== diffNode.id && !item.disabled)
newcheckedIds.add(item.id);
});
}
const { checkedType, checkedChildrenId } = diffSublingNode(
diffNode,
newcheckedIds
);
checkedChildrenIds.push(...checkedChildrenId);
if (checkedType === "all") {
if (checkedChildrenId.length) {
// 改为半选
newIndeterminateIds.add(diffNode.parent.id);
} else {
// 没有兄弟节点的情况
newIndeterminateIds.delete(diffNode.parent.id);
}
newcheckedIds.delete(diffNode.parent.id);
}
if (checkedType === "some") break;
if (checkedType === "none" && !checkedChildrenIds.length) {
// 有选中的子孙节点就不删除半选状态
// 遍历兄弟节点时排除了自身 所以在 none 时会存在问题 加上checkedChildrenIds的判断
newIndeterminateIds.delete(diffNode.parent.id);
}
diffNode = diffNode.parent;
}
}
setCheckedIds(new Set(newcheckedIds));
setIndeterminateIds(newIndeterminateIds);
// return 出去是为了 计算不同形式的checkedIds
return newcheckedIds;
},
[
clearAllChildNodeId,
diffSublingNode,
indeterminateIds,
diffAllParent
]
);
useEffect(
() => {
onDropDownVisibleChange && onDropDownVisibleChange(showOption);
},
[showOption, onDropDownVisibleChange]
);
useEffect(
() => {
// 主要监听的是 filterString 和 showOption的变化
if (searchable) setSearchFocus(showOption);
if (showOption && searchable) SeacrhInputRef.current.focus(); // 打开面板输入框自动聚焦
if (!showOption && filterString) setFileterString(""); // 关闭面板清除筛选信息
},
[showOption, searchable, SeacrhInputRef, filterString]
);
const CIATSCS = useCallback(
(
nextCheckedIds: CheckedIds
): [Array<TreeNodeRender["id"]>, Array<TreeNodeRender["label"]>] => {
const newCheckedIds: Set<TreeNodeRender["id"]> = new Set();
const newCheckedLabels: Map<
TreeNodeRender["id"],
TreeNodeRender["label"]
> = new Map();
let markedLevel = -1;
let disabledLevel = -1;
let markedLevelInDisabled = -1;
switch (showCheckedStrategy) {
// 默认模式 勾选下级节点 会 反选上级
case "SHOW_PARENT": {
treeStruct.forEach(treeNode => {
if (nextCheckedIds.has(treeNode.id)) {
newCheckedIds.add(treeNode.id);
newCheckedLabels.set(treeNode.id, treeNode.label);
}
});
break;
}
case "SHOW_ALL": {
// 要处理的情况是 父节点选中了但是checkedIds 中不含其子节点
treeStruct.forEach(treeNode => {
// 循环分两个阶段 正常的遍历 和 disabled 内的遍历 单独区分
if (disabledLevel >= treeNode.level) {
// 结束 disabled 节点内的遍历
// 重制 markedLevelInDisabled
disabledLevel = -1;
markedLevelInDisabled = -1;
}
if (treeNode.disabled && disabledLevel === -1) {
disabledLevel = treeNode.level;
}
if (disabledLevel !== -1) {
// disabled 节点内的遍历
if (
markedLevelInDisabled >= treeNode.level ||
treeNode.disabled
) {
markedLevelInDisabled = -1;
}
if (nextCheckedIds.has(treeNode.id)) {
markedLevelInDisabled = treeNode.level;
}
}
if (markedLevel >= treeNode.level) {
// 结束 markedLevel 下子节点的遍历
markedLevel = -1;
}
if (nextCheckedIds.has(treeNode.id) && disabledLevel === -1) {
// 正常遍历
// 加上 disabledLevel 的判断防止 markedLevel 被 disabledLevel 下的 已选节点改变
markedLevel = treeNode.level;
}
if (
(markedLevel !== -1 && disabledLevel === -1) ||
markedLevelInDisabled !== -1
) {
// markedLevel !== -1 的情况会包含 disabled 下的节点 所以要排除
newCheckedIds.add(treeNode.id);
newCheckedLabels.set(treeNode.id, treeNode.label);
}
});
break;
}
case "SHOW_CHILD": {
treeStruct.forEach((treeNode, index) => {
const nextNode = treeStruct[index + 1];
const ifLeafe =
(nextNode && nextNode.level <= treeNode.level) || !nextNode; // 是否是叶子节点
if (disabledLevel >= treeNode.level) {
disabledLevel = -1;
markedLevelInDisabled = -1;
}
if (treeNode.disabled && disabledLevel === -1) {
// 判断 disabled 是 为了防止 disabled 内 disabled 的 情况
disabledLevel = treeNode.level;
}
if (disabledLevel !== -1) {
// disabled 节点内的遍历
if (
markedLevelInDisabled >= treeNode.level ||
treeNode.disabled
) {
// disabled 内 遇到 disabled 的节点
markedLevelInDisabled = -1;
}
if (nextCheckedIds.has(treeNode.id)) {
markedLevelInDisabled = treeNode.level;
}
}
if (markedLevel >= treeNode.level) {
// 结束一个节点的计算
markedLevel = -1;
}
if (nextCheckedIds.has(treeNode.id) && disabledLevel === -1) {
// 已选中 并且 表示其含有子节点
// 开始一个节点的计算
markedLevel = treeNode.level;
}
if (
((markedLevel !== -1 && disabledLevel === -1) ||
markedLevelInDisabled !== -1) &&
ifLeafe
) {
newCheckedIds.add(treeNode.id);
newCheckedLabels.set(treeNode.id, treeNode.label);
}
});
break;
}
default:
break;
}
const nextCheckedLabelListStrategy: Array<TreeNodeRender["label"]> = [];
newCheckedLabels.forEach(item => {
nextCheckedLabelListStrategy.push(item);
});
return [Array.from(newCheckedIds), nextCheckedLabelListStrategy];
},
[treeStruct, showCheckedStrategy]
);
let filteredNodeRenderList = useMemo(
() => {
// 基于nodeRenderList计算渲染用的树 包含搜索的条件 没展开的就不参与渲染
// 树 的表现和 checked回调的策略无关 只有一种 方式 SHOW_PARENT
// 弹出的窗口当中的树 的checked 依照checkedIds
const filterNodeList = [];
let markedLevel = -1;
let existIds = new Set(); // 已被加入筛选节点列表的 节点,包含目标节点的 父级
nodeRenderList.forEach(item => {
// 计算节点 是否勾选 和 半选状态
if (
checkedIds.has(item.id) ||
(item.parent && item.parent.checked && !item.parent.disabled)
)
item.checked = true;
else item.checked = false;
if (indeterminateIds.has(item.id)) {
item.indeterminate = true;
} else item.indeterminate = false;
if (
!treeNodeRender &&
((filterTreeNode && filterTreeNode(filterString, item)) ||
(item.label as string).includes(filterString))
) {
if (item.level <= markedLevel) {
markedLevel = -1;
}
const originalLength = filterNodeList.length;
// filterString 可能为空字符串
if (filterString) {
// 过滤后的树 无法进行展开 操作
filterNodeList.push(item);
existIds.add(item.id);
while (item.parent) {
// 过滤后的树节点默认展开
item.parent.expand = true;
if (!existIds.has(item.parent.id)) {
filterNodeList.splice(originalLength, 0, item.parent);
existIds.add(item.parent.id);
}
item = item.parent;
}
} else if (markedLevel === -1) {
if (expandIds.has(item.id)) {
item.expand = true;
} else item.expand = false;
filterNodeList.push(item);
!item.expand &&
item.children &&
item.children.length &&
(markedLevel = item.level);
}
}
});
return filterNodeList;
},
[nodeRenderList, filterString, treeNodeRender, checkedIds, expandIds, value, indeterminateIds]
);
const checkedIdList = useMemo<CheckedIdList>(
() => {
return value
? multiple
? CIATSCS(new Set(value))[0]
: value
: CIATSCS(checkedIds)[0];
},
[checkedIds, CIATSCS, value]
);
const NewSwitcherIcon = useCallback(
props => {
const { id, ...otherProps } = props;
return (
<div {...otherProps}>
{loadingNode === id ? (
<Ico type="rotate-right spin" />
) : switcherIcon ? (
switcherIcon
) : (
<Ico type="angle-right" />
)}
</div>
);
},
[switcherIcon, loadingNode]
);
return (
<Trigger
showAction="none"
hideAction="none"
popupVisible={showOption}
onPopupVisibleChange={setShowOption}
stretch={stretch}
transitionName="scale"
popup={
<div
className="dada-tree-select-popup"
ref={ListPopupRef}
style={{
[listHeight ? "height" : ""]: [listHeight ? listHeight + "px" : ""],
}}
>
<div
className="dada-tree-select-popup-list"
>
{filteredNodeRenderList.map(item => {
return (
<div className="dada-tree-select-node" key={item.key}>
{new Array(item.level).fill(1).map((item, index) => {
return (
<span className="dada-tree-space-content" key={index} />
);
})}
<NewSwitcherIcon
className={classnames(
item.expand ? "dada-tree-node-expand" : "",
"dada-tree-node-ico"
)}
id={item.id}
onClick={() => {
// 筛选时 折叠无响应
if (!filterString) {
const newExpandIds = new Set(expandIds);
if (item.expand && newExpandIds.has(item.id)) {
newExpandIds.delete(item.id);
setExpandIds(newExpandIds);
} else {
if (
(!item.children || !item.children.length) &&
(loadData && !item.isLeaf)
) {
setLoadingNode(item.id);
loadData(item)
.then(() => {
newExpandIds.add(item.id);
setExpandIds(newExpandIds);
})
.catch(error => {
console.log(error);
})
.finally(() => {
setLoadingNode(undefined);
});
} else {
newExpandIds.add(item.id);
setExpandIds(newExpandIds);
}
}
onTreeExpand && onTreeExpand(item.id, item);
searchable && SeacrhInputRef.current.focus();
}
}}
style={{
visibility:
(item.children && item.children.length) ||
(loadData && !item.isLeaf)
? "visible"
: "hidden"
}}
/>
<span
onClick={e => {
e.preventDefault();
let nextCheckedIds: CheckedIds = new Set();
const {
checked,
expand,
level,
indeterminate,
...others
} = item;
if (item.disabled) return;
if (autoClearSearchValue) setFileterString("");
if (multiple) {
nextCheckedIds = caculateSelectedKey(
checkedIds,
item,
!item.checked
);
const [
nextCheckedIdListStrategy,
nextCheckedLabelListStrategy
] = CIATSCS(nextCheckedIds);
onChange &&
onChange(
nextCheckedIdListStrategy,
nextCheckedLabelListStrategy,
{
preValue: checkedIdList,
triggerNode: others
}
);
} else {
if (!checkedIds.has(item.id)) {
nextCheckedIds.add(item.id);
setCheckedIds(nextCheckedIds);
onChange &&
onChange([item.id], [item.label], {
preValue: checkedIdList,
triggerNode: others
});
}
}
searchable && SeacrhInputRef.current.focus();
}}
className={classnames(
"dada-tree-select-check",
checkedIdList.includes(item.id) && !multiple
? "dada-tree-select-checked"
: "",
item.disabled ? "dada-tree-select-node-disabled" : ""
)}
>
{multiple && item.checkable && (
<Checkbox
disabled={item.disabled}
checked={item.disabled ? false : item.checked}
indeterminate={
item.disabled
? false
: item.checked
? false
: item.indeterminate
}
/>
)}
{suffixIcon && suffixIcon(item)}
{treeNodeRender ? (
treeNodeRender(item)
) : (
<span key={item.key} title={item.label}>
{item.label}
</span>
)}
</span>
</div>
);
})}
</div>
</div>
}
>
<div
className={classnames(
className,
`dada-tree-select${size ? "-" + size : ""}`,
"dada-tree-select"
)}
onClick={() => {
if (disabled) return;
setShowOption(!showOption);
}}
style={{ borderColor: showOption ? "#008cf0" : "", ...style }}
>
{disabled && <div className="dada-tree-select-disabled" />}
<div className={classnames("dada-tree-select-checked-tags")}>
{multiple ? (
checkedIdList.map(item => {
const selectItem =
R.find(R.propEq("id", item), nodeRenderList) || {};
return (
<Tag
closable={!selectItem.disabled}
onClose={e => {
e.preventDefault();
e.stopPropagation();
const nextCheckedIds = caculateSelectedKey(
checkedIds,
selectItem,
false
);
const {
checked,
expand,
level,
indeterminate,
...others
} = selectItem;
const [
nextCheckedIdListStrategy,
nextCheckedLabelListStrategy
] = CIATSCS(nextCheckedIds);
onChange &&
onChange(
nextCheckedIdListStrategy,
nextCheckedLabelListStrategy,
{
preValue: checkedIdList,
triggerNode: others
}
);
}}
key={selectItem.key}
theme={tagTheme || "default"}
size={size !== "lg" ? size || "md" : "md"}
>
{selectItem.label || ""}
</Tag>
);
})
) : filterString ? (
""
) : (
<div
className="dada-tree-select-singal-value"
style={{
color: filterString ? "#bfbfbf" : ""
}}
>
{(R.find(R.propEq("id", checkedIdList[0]), nodeRenderList) || {})
.label || ""}
</div>
)}
{searchable && (
<div className={classnames("dada-tree-select-search-input")}>
<input
value={filterString}
ref={SeacrhInputRef}
onChange={e => {
setFileterString(e.target.value);
onSearch && onSearch(e.target.value);
}}
style={{
width:
CountWidth.current && showOption
? CountWidth.current.clientWidth + 10 + "px"
: "4px"
}}
/>
<div className="dada-tree-select-count-width" ref={CountWidth}>
{filterString}
</div>
</div>
)}
{!checkedIdList.length && (!searchFocus || !filterString) && (
<span className="dada-tree-select-placeholder">{placeholder}</span>
)}
</div>
<div className="dada-tree-select-icons">
{allowClear && (
<Ico
type="times-circle"
onClick={e => {
e.stopPropagation();
setCheckedIds(new Set());
setShowOption(false);
setIndeterminateIds(new Set());
onChange && onChange([], [], { preValue: checkedIdList });
}}
className={classnames(
checkedIdList.length ? "dada-tree-select-allow-clear" : ""
)}
/>
)}
<Ico
type="angle-down"
className={classnames(
showOption ? "showoption" : "",
checkedIdList.length && allowClear
? "dada-tree-select-angle-hide"
: ""
)}
/>
</div>
</div>
</Trigger>
);
};
TreeSelect.propTypes = {
/**
* Input 框显示清除按钮
*/
allowClear: PropTypes.bool,
/**
* 树每个选项前是否有 checkbox
*/
multiple: PropTypes.bool,
/**
* 默认选中的数据
*/
defaultValue: PropTypes.array,
/**
* 用于渲染的数据
*/
data: PropTypes.array.isRequired,
/**
* 整体禁用
*/
disabled: PropTypes.bool,
/**
* 当多选模式下值被选择,自动清空搜索框
*/
autoClearSearchValue: PropTypes.bool,
/**
* 用作树的calssName
*/
dropdownClassName: PropTypes.string,
/**
* 自定义过滤方法
*/
filterTreeNode: PropTypes.func,
onChange: PropTypes.func,
/**
* 弹窗 显示状态改变的回调
*/
onDropDownVisibleChange: PropTypes.func,
/**
* 设置弹窗的高度
*/
listHeight: PropTypes.number,
/**
* 按节点加载数据 默认每个节点都能展开 除非单独设置isLeaf或有子节点
*/
loadData: PropTypes.func,
placeholder: PropTypes.string,
/**
* 选中时回调值的策略
*/
showCheckedStrategy: PropTypes.oneOf([
"SHOW_ALL",
"SHOW_PARENT",
"SHOW_CHILD"
]),
/**
* 是否支持 搜索
*/
searchable: PropTypes.bool,
/**
* 开关切换的icon
*/
switcherIcon: PropTypes.node,
/**
* data 属性默认支持的结构 是 id,label和children。当传入的data为其他结构时 可以使用treeRenderPropReflect指定他们的别名。
*/
treeRenderPropReflect: PropTypes.object,
/**
* 树 默认展开所有节点
*/
treeDefaultExpandAll: PropTypes.bool,
/**
* 默认 展开的树的id 列表
*/
treeDefaultExpandedKeys: PropTypes.array,
/**
* 搜索时的回调
*/
onSearch: PropTypes.func,
/**
* 展开节点时回调
*/
onTreeExpand: PropTypes.func,
/**
* 弹窗的最大高度,涉及虚拟滚动的最大可见区域高度
*/
treeNodeRender: PropTypes.func,
value: PropTypes.array,
/**
* 选中的标签的主题颜色
*/
tagTheme: PropTypes.string,
className: PropTypes.string,
style: PropTypes.object,
/**
* 弹出层的宽度 默认 sameWidth
*/
stretch: PropTypes.oneOf(["sameWidth", "auto"]),
/**
* label 前置的icon
*/
suffixIcon: PropTypes.func,
size: PropTypes.oneOf(["md", "sm", "lg"])
};
TreeSelect.defaultProps = {
showCheckedStrategy: "SHOW_PARENT",
stretch: "sameWidth",
};
TreeSelect.SHOW_PARENT = "SHOW_PARENT";
TreeSelect.SHOW_ALL = "SHOW_ALL";
TreeSelect.SHOW_CHILD = "SHOW_CHILD";
export default TreeSelect; | the_stack |
import parseGLB from './Glb';
import Accessor from './Accessor';
import { Mesh, Primitive } from './Mesh';
import { Skin, SkinJoint } from './Skin';
import { Animation, Track, ETransform, ELerp } from './Animation';
import { Texture } from './Texture';
import { Pose } from './Pose';
//#endregion
class Gltf2{
//#region MAIN
json : any;
bin : ArrayBuffer;
constructor( json: any, bin ?: ArrayBuffer | null ){
this.json = json;
this.bin = bin || new ArrayBuffer(0); // TODO, Fix for base64 inline buffer
}
//#endregion ///////////////////////////////////////////////////////////////////////
//#region NODES
getNodeByName( n: string ) : [ any, number ] | null{
let o: any, i: number;
for( i=0; i < this.json.nodes.length; i++ ){
o = this.json.nodes[ i ];
if( o.name == n ) return [ o, i ];
}
return null;
}
//#endregion ///////////////////////////////////////////////////////////////////////
//#region MESHES
getMeshNames() : Array<string>{
const json = this.json,
rtn : Array<string> = [];
let i: any;
for( i of json.meshes ) rtn.push( i.name );
return rtn;
}
getMeshByName( n: string ) : [ any, number ] | null {
let o, i;
for( i=0; i < this.json.meshes.length; i++ ){
o = this.json.meshes[ i ];
if( o.name == n ) return [ o, i ];
}
return null;
}
getMeshNodes( idx: number ) : Array< any >{
const out : Array< any > = [];
let n;
for( n of this.json.nodes ){
if( n.mesh == idx ) out.push( n );
}
return out;
}
getMesh( id: string | number | undefined ) : Mesh | null {
if( !this.json.meshes ){ console.warn( "No Meshes in GLTF File" ); return null; }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const json = this.json;
let m : any | null = null;
let mIdx : number | null = null;
switch( typeof id ){
case "string" : {
const tup = this.getMeshByName( id );
if( tup !== null ){
m = tup[ 0 ];
mIdx = tup[ 1 ];
}
break; }
case "number" : if( id < json.meshes.length ){ m = json.meshes[ id ]; mIdx = id; } break;
default : m = json.meshes[ 0 ]; mIdx = 0; break;
}
if( m == null || mIdx == null ){ console.warn( "No Mesh Found", id ); return null; }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const mesh = new Mesh();
mesh.name = m.name;
mesh.index = mIdx;
let p: any, prim: any, attr: any;
for( p of m.primitives ){
attr = p.attributes;
prim = new Primitive();
//------------------------------------------------------
if( p.material != undefined && p.material != null ){
prim.materialIdx = p.material;
prim.materialName = json.materials[ p.material ].name;
}
//------------------------------------------------------
if( p.indices != undefined ) prim.indices = this.parseAccessor( p.indices );
if( attr.POSITION != undefined ) prim.position = this.parseAccessor( attr.POSITION );
if( attr.NORMAL != undefined ) prim.normal = this.parseAccessor( attr.NORMAL );
if( attr.TANGENT != undefined ) prim.tangent = this.parseAccessor( attr.TANGENT );
if( attr.TEXCOORD_0 != undefined ) prim.texcoord_0 = this.parseAccessor( attr.TEXCOORD_0 );
if( attr.TEXCOORD_1 != undefined ) prim.texcoord_1 = this.parseAccessor( attr.TEXCOORD_1 );
if( attr.JOINTS_0 != undefined ) prim.joints_0 = this.parseAccessor( attr.JOINTS_0 );
if( attr.WEIGHTS_0 != undefined ) prim.weights_0 = this.parseAccessor( attr.WEIGHTS_0 );
if( attr.COLOR_0 != undefined ) prim.color_0 = this.parseAccessor( attr.COLOR_0 );
//------------------------------------------------------
mesh.primitives.push( prim );
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const nodes = this.getMeshNodes( mIdx );
// Save Position, Rotation and Scale if Available.
if( nodes?.length ){
if( nodes[0].translation ) mesh.position = nodes[0].translation.slice( 0 );
if( nodes[0].rotation ) mesh.rotation = nodes[0].rotation.slice( 0 );
if( nodes[0].scale ) mesh.scale = nodes[0].scale.slice( 0 );
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
return mesh;
}
//#endregion ///////////////////////////////////////////////////////////////////////
//#region SKINS
getSkinNames() : Array<string> {
const json = this.json,
rtn: Array<string> = [];
let i: any;
for( i of json.skins ) rtn.push( i.name );
return rtn;
}
getSkinByName( n: string ) : [ any, number ] | null{
let o, i;
for( i=0; i < this.json.skins.length; i++ ){
o = this.json.skins[ i ];
if( o.name == n ) return [ o, i ];
}
return null;
}
getSkin( id: string | number | undefined ) : Skin | null{
if( !this.json.skins ){ console.warn( "No Skins in GLTF File" ); return null; }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const json = this.json;
let js : any | null = null;
let idx : number | null = null;
switch( typeof id ){
case "string" : {
const tup = this.getSkinByName( id );
if( tup !== null ){
js = tup[ 0 ];
idx = tup[ 1 ];
}
break; }
case "number" : if( id < json.skins.length ){ js = json.meshes[ id ]; idx = id; } break;
default : js = json.skins[ 0 ]; idx = 0; break;
}
if( js == null ){ console.warn( "No Skin Found", id ); return null; }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const bind : Accessor | null = this.parseAccessor( js.inverseBindMatrices );
if( bind && bind.elementCnt != js.joints.length ){
console.warn( "Strange Error. Joint Count & Bind Matrix Count dont match" );
return null;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
let i : number,
bi : number,
ni : number,
joint : SkinJoint,
node : Record<string,any>;
const jMap = new Map(); // Map Node Index to Joint Index;
const skin = new Skin();
skin.name = js.name;
skin.index = idx;
for( i=0; i < js.joints.length; i++ ){
//console.log( i, js.joints[ i ] );
ni = js.joints[ i ];
node = json.nodes[ ni ];
jMap.set( ni, i ); // Map Node Index to Joint Index
//-----------------------------------------
joint = new SkinJoint();
joint.index = i;
joint.name = ( node.name )? node.name : "bone_" + i;
// Get Local Space Transform if available on the Node
joint.rotation = node?.rotation?.slice( 0 ) ?? null;
joint.position = node?.translation?.slice( 0 ) ?? null;
joint.scale = node?.scale?.slice( 0 ) ?? null;
if( bind && bind.data ){
bi = i * 16;
joint.bindMatrix = Array.from( bind.data.slice( bi, bi+16 ) );
}
//-----------------------------------------
// Because of Rounding Errors, If Scale is VERY close to 1, Set it to 1.
// This helps when dealing with transform hierachy since small errors will
// compound and cause scaling in places that its not ment to.
if( joint.scale ){
if( Math.abs( 1 - joint.scale [0] ) <= 0.000001 ) joint.scale [0] = 1;
if( Math.abs( 1 - joint.scale [1] ) <= 0.000001 ) joint.scale [1] = 1;
if( Math.abs( 1 - joint.scale [2] ) <= 0.000001 ) joint.scale [2] = 1;
}
//-----------------------------------------
skin.joints.push( joint );
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Update Joints with the index to their parent. In GLTF we only know a joint's
// children. Using the Node-Joint Map, we can translate the node children to
// joints.
let j: number;
for( i=0; i < js.joints.length; i++ ){
ni = js.joints[ i ]; // Joint Points t a Node
node = json.nodes[ ni ]; // Get that Joint's Node
// If joint Node has children, Loop threw the list and
// update their parentIndex to match this current joint.
if( node?.children?.length ){
for( j=0; j < node.children.length; j++ ){
bi = jMap.get( node.children[ j ] ); // Joint Node Children Index, get their mapped joint index.
if( bi != undefined ) skin.joints[ bi ].parentIndex = i; // With Child Joint Index, Save this Index as its parent.
else console.log( 'BI', bi, node );
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Sometimes there is a Node Transform available for a Skin
if( skin.name ){
const snode = this.getNodeByName( skin.name );
if( snode ){
const n = snode[ 0 ];
skin.rotation = n?.rotation?.slice( 0 ) ?? null;
skin.position = n?.translation?.slice( 0 ) ?? null;
skin.scale = n?.scale?.slice( 0 ) ?? null;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
return skin;
}
//#endregion ///////////////////////////////////////////////////////////////////////
//#region MATERIALS
// https://github.com/KhronosGroup/glTF-Tutorials/blob/master/gltfTutorial/gltfTutorial_010_Materials.md
getMaterial( id: number | undefined ) : any{
if( !this.json.materials ){ console.warn( "No Materials in GLTF File" ); return null; }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const json = this.json;
let mat = null;
switch( typeof id ){
case "number" : if( id < json.materials.length ){ mat = json.materials[ id ].pbrMetallicRoughness; } break;
default : mat = json.materials[ 0 ].pbrMetallicRoughness; break;
}
return mat;
}
// https://www.khronos.org/registry/glTF/specs/2.0/glTF-2.0.html#texture-data
getTexture( id: number ): Texture | null{
const js = this.json;
const t = js.textures[ id ];
//const samp = js.samplers[ t.sampler ];
const img = js.images[ t.source ];
const bv = js.bufferViews[ img.bufferView ];
const bAry = new Uint8Array( this.bin, bv.byteOffset, bv.byteLength );
const tex = new Texture();
tex.index = id;
tex.name = img.name;
tex.mime = img.mimeType;
tex.blob = new Blob( [ bAry ], { type: img.mimeType } );
return tex;
}
//#endregion ///////////////////////////////////////////////////////////////////////
//#region ANIMATION
/*
https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#appendix-c-spline-interpolation (Has math for cubic spline)
https://www.khronos.org/registry/glTF/specs/2.0/glTF-2.0.html#reference-animation
animation = {
frame_cnt : int
time : float,
times : [ float32array, float32array, etc ],
tracks : [
{
type : "rot || pos || scl",
time_idx : 0,
joint_idx : 0,
lerp : "LINEAR || STEP || CUBICSPLINE",
data : float32array,
},
]
}
{
name: '',
channels: [ {
sampler: SAMPLER_INDEX,
target:{
node : NODE_INDEX, ( NEED TO TRANSLATE NODE INDEX TO JOINT INDEX )
path : 'translation' | 'rotation' | 'scale'
}
] ],
samplers: [ {
input: ACCESSOR_INDEX_FOR_KEYFRAME_TIMESTAMP,
interpolation: 'LINEAR' | 'STEP' | 'CUBICSPLINE',
output: ACCESSOR_INDEX_FOR_KEYFRAME_TRANFORM_VALUE,
} ],
}
*/
getAnimationNames() : Array<string> {
const json = this.json,
rtn: Array<string> = [];
let i: any;
for( i of json.animations ) rtn.push( i.name );
return rtn;
}
getAnimationByName( n: string ) : [ any, number ] | null{
let o: any, i: number;
for( i=0; i < this.json.animations.length; i++ ){
o = this.json.animations[ i ];
if( o.name == n ) return [ o, i ];
}
return null;
}
getAnimation( id: string | number | undefined ): any {
//this.getAnimationByName( 'Armature|mixamo.com|Layer0' );
if( !this.json.animations ){ console.warn( "No Animations in GLTF File" ); return null; }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const json = this.json;
let js : any | null = null;
let idx : number | null = null;
switch( typeof id ){
case "string" : {
const tup = this.getAnimationByName( id );
if( tup !== null ){
js = tup[ 0 ]; // Object Reference
idx = tup[ 1 ]; // Object Index
}
break; }
case "number" : if( id < json.animations.length ){ js = json.animations[ id ]; idx = id; } break;
default : js = json.animations[ 0 ]; idx = 0; break;
}
if( js == null ){ console.warn( "No Animation Found", id ); return null; }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const NJMap : Map< number, number > = new Map(); // Node to Joint Map;
const timeStamps : Array< Accessor > = [];
const tsMap : Map< number, number > = new Map(); // Timestamp Sample ID to Array Index
// Get the Joint Index from the Node Index
const fnGetJoint = ( nIdx: number ) : number=>{
let jIdx : number | undefined = NJMap.get( nIdx );
if( jIdx != undefined ) return jIdx;
// Search every skin's joints for the node index
// if found, the index is the joint index that
// can be used for skinning.
for( let skin of this.json.skins ){
jIdx = skin.joints.indexOf( nIdx );
if( jIdx != -1 && jIdx != undefined ){
NJMap.set( nIdx, jIdx ); // Map the indices
return jIdx;
}
}
return -1; // This should Never Happen
};
// Get the Timestamp index from the Accessor Sample Index.
// This will also cache a unique list of timestamps that
// can be references from multiple tracks.
const fnGetTimestamp = ( sIdx: number ) : number=>{
let aIdx : number | undefined = tsMap.get( sIdx );
if( aIdx != undefined ) return aIdx;
const acc = this.parseAccessor( sIdx );
if( acc ){
aIdx = timeStamps.length;
timeStamps.push( acc ); // Save Timestamp Data
tsMap.set( sIdx, aIdx ); // Map the Indices
return aIdx;
}
return -1; // This should Never Happen
};
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const anim = new Animation( js.name );
anim.timestamps = timeStamps;
let track : Track; // New Track Object
let ch : any; // Channel
let jointIdx : number; // Joint Index it Effects
let sampler : any; // Sampler Object ( Input:Timestamp Array, Output:Value Array )
let acc : Accessor | null; // Accessor tmp var
for( ch of js.channels ){
//---------------------------------
jointIdx = fnGetJoint( ch.target.node );
sampler = js.samplers[ ch.sampler ];
track = Track.fromGltf( jointIdx, ch.target.path, sampler.interpolation );
//---------------------------------
// Get the Keyframe Vaues for this Transform Track
acc = this.parseAccessor( sampler.output ); // ACCESSOR_INDEX_FOR_KEYFRAME_TRANFORM_VALUE,
if( acc ) track.keyframes = acc;
//---------------------------------
// Save Timestamp Data Since its shared amoung tracks.
// This creates a unique array of TimeStamps that we can
// reference by using the index value
track.timeStampIndex = fnGetTimestamp( sampler.input );
//---------------------------------
anim.tracks.push( track );
}
return anim;
}
//#endregion ///////////////////////////////////////////////////////////////////////
//#region POSES ( CUSTOM, NOT PART OF GLTF SPEC )
getPoseByName( n: string ) : [ any, number ] | null{
let o: any, i: number;
for( i=0; i < this.json.poses.length; i++ ){
o = this.json.poses[ i ];
if( o.name == n ) return [ o, i ];
}
return null;
}
getPose( id ?: string ): Pose | null{
if( !this.json.poses ){ console.warn( "No Poses in GLTF File" ); return null; }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const json = this.json;
let js : any | null = null;
let idx : number | null = null;
switch( typeof id ){
case "string" : {
const tup = this.getPoseByName( id );
if( tup !== null ){
js = tup[ 0 ]; // Object Reference
idx = tup[ 1 ]; // Object Index
}
break; }
default : js = json.poses[ 0 ]; idx = 0; break;
}
if( js == null ){ console.warn( "No Pose Found", id ); return null; }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const pose = new Pose( js.name );
let jnt: any;
for( jnt of js.joints ){
pose.add( jnt.idx, jnt.rot, jnt.pos, jnt.scl );
}
return pose;
}
//#endregion ///////////////////////////////////////////////////////////////////////
//#region SUPPORT
// https://github.com/KhronosGroup/glTF-Tutorials/blob/master/gltfTutorial/gltfTutorial_005_BuffersBufferViewsAccessors.md
parseAccessor( accID: number ) : Accessor | null {
const accessor = this.json.accessors[ accID ];
const bufView = this.json.bufferViews[ accessor.bufferView ];
if( bufView.byteStride ){ console.error( "UNSUPPORTED - Parsing Stride Buffer" ); return null; }
return new Accessor( accessor, bufView, this.bin );
}
//#endregion ///////////////////////////////////////////////////////////////////////
//#region STATIC
static async fetch( url: string ) : Promise< Gltf2 | null >{
const res = await fetch( url );
if( !res.ok ) return null;
switch( url.slice( -4 ).toLocaleLowerCase() ){
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'gltf':
let bin : ArrayBuffer | undefined;
const json = await res.json();
if( json.buffers && json.buffers.length > 0 ){
const path = url.substring( 0, url.lastIndexOf( '/') + 1 );
bin = await fetch( path + json.buffers[ 0 ].uri ).then( r=>r.arrayBuffer() );
}
return new Gltf2( json, bin );
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case '.glb':
const tuple = await parseGLB( res );
return ( tuple )? new Gltf2( tuple[0], tuple[1] ) : null;
}
return null;
}
//#endregion ///////////////////////////////////////////////////////////////////////
}
export default Gltf2;
export { Accessor }; | the_stack |
import { ChangeDetectorRef, Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ComponentFixture, inject, TestBed, waitForAsync, } from '@angular/core/testing';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {
DynamicFormArrayModel,
DynamicFormControlEvent,
DynamicFormControlModel,
DynamicFormValidationService,
DynamicInputModel
} from '@ng-dynamic-forms/core';
import { Store, StoreModule } from '@ngrx/store';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { TranslateModule } from '@ngx-translate/core';
import { FormComponent } from './form.component';
import { FormService } from './form.service';
import { FormBuilderService } from './builder/form-builder.service';
import { FormState } from './form.reducer';
import { FormChangeAction, FormStatusChangeAction } from './form.actions';
import { StoreMock } from '../testing/store.mock';
import { FormFieldMetadataValueObject } from './builder/models/form-field-metadata-value.model';
import { createTestComponent } from '../testing/utils.test';
import { BehaviorSubject } from 'rxjs';
import { storeModuleConfig } from '../../app.reducer';
let TEST_FORM_MODEL;
let TEST_FORM_MODEL_WITH_ARRAY;
let config;
let formState: FormState;
let html;
let store: StoreMock<FormState>;
function init() {
TEST_FORM_MODEL = [
new DynamicInputModel(
{
id: 'dc_title',
label: 'Title',
placeholder: 'Title',
validators: {
required: null
},
errorMessages: {
required: 'You must enter a main title for this item.'
}
}
),
new DynamicInputModel(
{
id: 'dc_title_alternative',
label: 'Other Titles',
placeholder: 'Other Titles',
}
),
new DynamicInputModel(
{
id: 'dc_publisher',
label: 'Publisher',
placeholder: 'Publisher',
}
),
new DynamicInputModel(
{
id: 'dc_identifier_citation',
label: 'Citation',
placeholder: 'Citation',
}
),
new DynamicInputModel(
{
id: 'dc_identifier_issn',
label: 'Identifiers',
placeholder: 'Identifiers',
}
),
];
TEST_FORM_MODEL_WITH_ARRAY = [
new DynamicFormArrayModel({
id: 'bootstrapFormArray',
initialCount: 1,
label: 'Form Array',
groupFactory: () => {
return [
new DynamicInputModel({
id: 'bootstrapArrayGroupInput',
placeholder: 'example array group input',
readOnly: false
})
];
}
})
];
config = {
form: {
validatorMap: {
required: 'required',
regex: 'pattern'
}
}
} as any;
formState = {
testForm: {
data: {
dc_title: null,
dc_title_alternative: null,
dc_publisher: null,
dc_identifier_citation: null,
dc_identifier_issn: null
},
valid: false,
errors: [],
touched: {}
}
};
}
describe('FormComponent test suite', () => {
let testComp: TestComponent;
let formComp: FormComponent;
let testFixture: ComponentFixture<TestComponent>;
let formFixture: ComponentFixture<FormComponent>;
// waitForAsync beforeEach
beforeEach(waitForAsync(() => {
init();
/* TODO make sure these files use mocks instead of real services/components https://github.com/DSpace/dspace-angular/issues/281 */
TestBed.configureTestingModule({
imports: [
BrowserModule,
CommonModule,
FormsModule,
ReactiveFormsModule,
NgbModule,
StoreModule.forRoot({}, storeModuleConfig),
TranslateModule.forRoot()
],
declarations: [
FormComponent,
TestComponent,
], // declare the test component
providers: [
ChangeDetectorRef,
DynamicFormValidationService,
FormBuilderService,
FormComponent,
FormService,
{ provide: Store, useClass: StoreMock }
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
});
}));
describe('', () => {
// synchronous beforeEach
beforeEach(() => {
html = `
<ds-form *ngIf="formModel" #formRef="formComponent"
[formId]="formId"
[formModel]="formModel"
[displaySubmit]="displaySubmit"
[displayCancel]="displayCancel"></ds-form>`;
testFixture = createTestComponent(html, TestComponent) as ComponentFixture<TestComponent>;
testComp = testFixture.componentInstance;
});
afterEach(() => {
testFixture.destroy();
testComp = null;
html = undefined;
});
it('should create FormComponent', inject([FormComponent], (app: FormComponent) => {
expect(app).toBeDefined();
}));
});
describe('', () => {
let form;
let valid;
beforeEach(() => {
formFixture = TestBed.createComponent(FormComponent);
store = TestBed.inject(Store as any);
formComp = formFixture.componentInstance; // FormComponent test instance
formComp.formId = 'testForm';
formComp.formModel = TEST_FORM_MODEL;
formComp.displaySubmit = false;
formComp.displayCancel = false;
form = new BehaviorSubject(formState);
valid = new BehaviorSubject(false);
spyOn((formComp as any).formService, 'getForm').and.returnValue(form);
spyOn((formComp as any).formService, 'isValid').and.returnValue(valid);
formFixture.detectChanges();
spyOn(store, 'dispatch');
});
afterEach(() => {
formFixture.destroy();
formComp = null;
});
it('should dispatch a FormStatusChangeAction when Form group status changes', () => {
const control = formComp.formGroup.get(['dc_title']);
control.setValue('Test Title');
expect(store.dispatch).toHaveBeenCalledWith(new FormStatusChangeAction('testForm', formComp.formGroup.valid));
});
it('should display form errors when errors are added to the state', () => {
const errors = [{
fieldId: 'dc_title',
fieldIndex: 0,
message: 'error.validation.required'
}];
formState.testForm.errors = errors;
form.next(formState.testForm);
formFixture.detectChanges();
expect((formComp as any).formErrors).toEqual(errors);
});
it('should remove form errors when errors are empty in the state', () => {
(formComp as any).formErrors = [{
fieldId: 'dc_title',
message: 'error.validation.required'
}];
const errors = [];
formState.testForm.errors = errors;
form.next(formState.testForm);
formFixture.detectChanges();
expect((formComp as any).formErrors).toEqual(errors);
});
it('should dispatch FormChangeAction on form change', inject([FormBuilderService], (service: FormBuilderService) => {
const event = {
$event: new FormFieldMetadataValueObject('Test Title'),
context: null,
control: formComp.formGroup.get('dc_title'),
group: formComp.formGroup,
model: formComp.formModel[0],
type: 'change'
} as DynamicFormControlEvent;
spyOn(formComp.change, 'emit');
formComp.onChange(event);
expect(store.dispatch).toHaveBeenCalledWith(new FormChangeAction('testForm', service.getValueFromModel(formComp.formModel)));
expect(formComp.change.emit).toHaveBeenCalled();
}));
it('should emit change on form change', inject([FormBuilderService], (service: FormBuilderService) => {
const event = {
$event: new FormFieldMetadataValueObject('Test Title'),
context: null,
control: formComp.formGroup.get('dc_title'),
group: formComp.formGroup,
model: formComp.formModel[0],
type: 'change'
} as DynamicFormControlEvent;
spyOn(formComp.change, 'emit');
formComp.onChange(event);
expect(formComp.change.emit).toHaveBeenCalled();
}));
it('should not emit change Event on form change when emitChange is false', inject([FormBuilderService], (service: FormBuilderService) => {
const event = {
$event: new FormFieldMetadataValueObject('Test Title'),
context: null,
control: formComp.formGroup.get('dc_title'),
group: formComp.formGroup,
model: formComp.formModel[0],
type: 'change'
} as DynamicFormControlEvent;
formComp.emitChange = false;
spyOn(formComp.change, 'emit');
formComp.onChange(event);
expect(formComp.change.emit).not.toHaveBeenCalled();
}));
it('should emit blur Event on blur', () => {
const event = {
$event: new FocusEvent('blur'),
context: null,
control: formComp.formGroup.get('dc_title'),
group: formComp.formGroup,
model: formComp.formModel[0],
type: 'blur'
} as DynamicFormControlEvent;
spyOn(formComp.blur, 'emit');
formComp.onBlur(event);
expect(formComp.blur.emit).toHaveBeenCalled();
});
it('should emit focus Event on focus', () => {
const event = {
$event: new FocusEvent('focus'),
context: null,
control: formComp.formGroup.get('dc_title'),
group: formComp.formGroup,
model: formComp.formModel[0],
type: 'focus'
} as DynamicFormControlEvent;
spyOn(formComp.focus, 'emit');
formComp.onFocus(event);
expect(formComp.focus.emit).toHaveBeenCalled();
});
it('should return Observable of form status', () => {
const control = formComp.formGroup.get(['dc_title']);
control.setValue('Test Title');
valid.next(true);
formFixture.detectChanges();
formComp.isValid().subscribe((v) => {
expect(v).toBe(true);
});
});
it('should emit submit Event on form submit whether the form is valid', () => {
const control = formComp.formGroup.get(['dc_title']);
control.setValue('Test Title');
formState.testForm.valid = true;
spyOn(formComp.submitForm, 'emit');
form.next(formState.testForm);
formFixture.detectChanges();
formComp.onSubmit();
expect(formComp.submitForm.emit).toHaveBeenCalled();
});
it('should not emit submit Event on form submit whether the form is not valid', () => {
spyOn((formComp as any).formService, 'validateAllFormFields');
form.next(formState.testForm);
formFixture.detectChanges();
formComp.onSubmit();
expect((formComp as any).formService.validateAllFormFields).toHaveBeenCalled();
});
it('should reset form group', () => {
spyOn(formComp.formGroup, 'reset');
formComp.reset();
expect(formComp.formGroup.reset).toHaveBeenCalled();
});
});
describe('', () => {
init();
beforeEach(() => {
formFixture = TestBed.createComponent(FormComponent);
store = TestBed.inject(Store as any);
formComp = formFixture.componentInstance; // FormComponent test instance
formComp.formId = 'testFormArray';
formComp.formModel = TEST_FORM_MODEL_WITH_ARRAY;
formComp.displaySubmit = false;
formComp.displayCancel = false;
formFixture.detectChanges();
spyOn(store, 'dispatch');
});
afterEach(() => {
formFixture.destroy();
formComp = null;
});
it('should return ReadOnly property from array item', inject([FormBuilderService], (service: FormBuilderService) => {
const readOnly = formComp.isItemReadOnly(formComp.formModel[0] as DynamicFormArrayModel, 0);
expect(readOnly).toBe(false);
}));
it('should dispatch FormChangeAction when an item has been added to an array', inject([FormBuilderService], (service: FormBuilderService) => {
formComp.insertItem(new Event('click'), formComp.formModel[0] as DynamicFormArrayModel, 0);
expect(store.dispatch).toHaveBeenCalledWith(new FormChangeAction('testFormArray', service.getValueFromModel(formComp.formModel)));
}));
it('should emit addArrayItem Event when an item has been added to an array', inject([FormBuilderService], (service: FormBuilderService) => {
spyOn(formComp.addArrayItem, 'emit');
formComp.insertItem(new Event('click'), formComp.formModel[0] as DynamicFormArrayModel, 0);
expect(formComp.addArrayItem.emit).toHaveBeenCalled();
}));
it('should dispatch FormChangeAction when an item has been removed from an array', inject([FormBuilderService], (service: FormBuilderService) => {
formComp.removeItem(new Event('click'), formComp.formModel[0] as DynamicFormArrayModel, 0);
expect(store.dispatch).toHaveBeenCalledWith(new FormChangeAction('testFormArray', service.getValueFromModel(formComp.formModel)));
}));
it('should emit removeArrayItem Event when an item has been removed from an array', inject([FormBuilderService], (service: FormBuilderService) => {
spyOn(formComp.removeArrayItem, 'emit');
formComp.removeItem(new Event('click'), formComp.formModel[0] as DynamicFormArrayModel, 0);
expect(formComp.removeArrayItem.emit).toHaveBeenCalled();
}));
});
});
// declare a test component
@Component({
selector: 'ds-test-cmp',
template: ``
})
class TestComponent {
public formId;
public formModel: DynamicFormControlModel[];
public displaySubmit = false;
public displayCancel = false;
constructor() {
this.formId = 'testForm';
this.formModel = TEST_FORM_MODEL;
}
} | the_stack |
import { FocusMonitor, FocusOrigin, isFakeMousedownFromScreenReader } from '@angular/cdk/a11y';
import { RIGHT_ARROW } from '@angular/cdk/keycodes';
import {
FlexibleConnectedPositionStrategy,
HorizontalConnectionPos,
Overlay,
OverlayConfig,
OverlayRef,
VerticalConnectionPos,
} from '@angular/cdk/overlay';
import { TemplatePortal } from '@angular/cdk/portal';
import {
AfterContentInit,
Directive,
ElementRef,
HostListener,
Input,
OnDestroy,
Optional,
Self,
ViewContainerRef,
} from '@angular/core';
import { asapScheduler, merge, of, Subscription } from 'rxjs';
import { delay, filter, take, takeUntil } from 'rxjs/operators';
import { MenuItemComponent } from './menu-item.component';
import { MenuPanel } from './menu-panel';
import { MenuPositionX, MenuPositionY } from './menu-positions';
import { MenuComponent } from './menu.component';
@Directive({
selector: '[gdMenuTrigger]',
host: {
'aria-haspopup': 'true',
'[attr.aria-expanded]': 'menuOpen || null',
},
exportAs: 'gdMenuTrigger',
})
export class MenuTriggerDirective implements AfterContentInit, OnDestroy {
// Tracking input type is necessary so it's possible to only auto-focus
// the first item of the list when the menu is opened via the keyboard
_openedBy: 'mouse' | 'touch' | null = null;
private _portal: TemplatePortal;
private _overlayRef: OverlayRef | null = null;
private _closeSubscription = Subscription.EMPTY;
private _hoverSubscription = Subscription.EMPTY;
private _menuCloseSubscription = Subscription.EMPTY;
constructor(
private _overlay: Overlay,
private _elementRef: ElementRef<HTMLElement>,
private _viewContainerRef: ViewContainerRef,
@Optional() private _parentMenu: MenuComponent,
@Optional() @Self() private _menuItem: MenuItemComponent,
private _focusMonitor: FocusMonitor,
) {
if (_menuItem) {
_menuItem._triggersSubmenu = this.triggersSubmenu();
}
}
private _menuOpen: boolean = false;
get menuOpen(): boolean {
return this._menuOpen;
}
private _menu: MenuPanel;
@Input('gdMenuTrigger')
get menu() {
return this._menu;
}
set menu(menu: MenuPanel) {
if (menu === this._menu) {
return;
}
this._menu = menu;
this._menuCloseSubscription.unsubscribe();
if (menu) {
this._menuCloseSubscription = menu.closed.asObservable().subscribe((reason) => {
this._destroyMenu();
// If a click closed the menu, we should close the entire chain of nested menus.
if ((reason === 'click' || reason === 'tab') && this._parentMenu) {
this._parentMenu.closed.emit(reason);
}
});
}
}
ngAfterContentInit(): void {
this._checkMenu();
this._handleHover();
}
ngOnDestroy(): void {
if (this._overlayRef) {
this._overlayRef.dispose();
this._overlayRef = null;
}
this._cleanUpSubscriptions();
}
/** Whether the menu triggers a sub-menu or a top-level one. */
triggersSubmenu(): boolean {
return !!(this._menuItem && this._parentMenu);
}
/** Toggles the menu between the open and closed states. */
toggleMenu(): void {
return this._menuOpen ? this.closeMenu() : this.openMenu();
}
openMenu(): void {
if (this._menuOpen) {
return;
}
this._checkMenu();
const overlayRef = this._createOverlay();
this._setPosition(overlayRef.getConfig().positionStrategy as FlexibleConnectedPositionStrategy);
overlayRef.attach(this._getPortal());
this._closeSubscription = this._menuClosingActions().subscribe(() => this.closeMenu());
this._initMenu();
if (this.menu instanceof MenuComponent) {
this.menu._startAnimation();
}
}
/** Closes the menu. */
closeMenu(): void {
this.menu.closed.emit();
}
/**
* Focuses the menu trigger.
* @param origin Source of the menu trigger's focus.
*/
focus(origin: FocusOrigin = 'program') {
this._focusMonitor.focusVia(this._elementRef.nativeElement, origin);
}
/** Handles mouse presses on the trigger. */
@HostListener('mousedown', ['$event'])
_handleMousedown(event: MouseEvent): void {
if (!isFakeMousedownFromScreenReader(event)) {
// Since right or middle button clicks won't trigger the `click` event,
// we shouldn't consider the menu as opened by mouse in those cases.
this._openedBy = event.button === 0 ? 'mouse' : null;
// Since clicking on the trigger won't close the menu if it opens a sub-menu,
// we should prevent focus from moving onto it via click to avoid the
// highlight from lingering on the menu item.
if (this.triggersSubmenu()) {
event.preventDefault();
}
}
}
/** Handles key presses on the trigger. */
@HostListener('keydown', ['$event'])
_handleKeydown(event: KeyboardEvent): void {
const keyCode = event.keyCode;
if (this.triggersSubmenu() && keyCode === RIGHT_ARROW) {
this.openMenu();
}
}
/** Handles click events on the trigger. */
@HostListener('click', ['$event'])
_handleClick(event: MouseEvent): void {
if (this.triggersSubmenu()) {
// Stop event propagation to avoid closing the parent menu.
event.stopPropagation();
this.openMenu();
} else {
this.toggleMenu();
}
}
private _initMenu(): void {
this.menu.parentMenu = this.triggersSubmenu() ? this._parentMenu : undefined;
this._setIsMenuOpen(true);
this.menu.focusFirstItem(this._openedBy || 'program');
}
/** Closes the menu and does the necessary cleanup. */
private _destroyMenu() {
if (!this._overlayRef || !this.menuOpen) {
return;
}
const menu = this.menu;
this._closeSubscription.unsubscribe();
this._overlayRef.detach();
if (menu instanceof MenuComponent) {
menu._resetAnimation();
}
this._resetMenu();
}
/**
* This method checks that a valid instance of MatMenu has been passed into
* matMenuTriggerFor. If not, an exception is thrown.
*/
private _checkMenu() {
if (!this.menu) {
throw new Error('Mush pass in an gd-menu instance.');
}
}
/**
* This method resets the menu when it's closed, most importantly restoring
* focus to the menu trigger if the menu was opened via the keyboard.
*/
private _resetMenu(): void {
this._setIsMenuOpen(false);
// We should reset focus if the user is navigating using a keyboard or
// if we have a top-level trigger which might cause focus to be lost
// when clicking on the backdrop.
if (!this._openedBy) {
// Note that the focus style will show up both for `program` and
// `keyboard` so we don't have to specify which one it is.
this.focus();
} else if (!this.triggersSubmenu()) {
this.focus(this._openedBy);
}
this._openedBy = null;
}
// set state rather than toggle to support triggers sharing a menu
private _setIsMenuOpen(isOpen: boolean): void {
this._menuOpen = isOpen;
if (this.triggersSubmenu()) {
this._menuItem._highlighted = isOpen;
}
}
/**
* This method creates the overlay from the provided menu's template and saves its
* OverlayRef so that it can be attached to the DOM when openMenu is called.
*/
private _createOverlay(): OverlayRef {
if (!this._overlayRef) {
const config = this._getOverlayConfig();
this._subscribeToPositions(config.positionStrategy as FlexibleConnectedPositionStrategy);
this._overlayRef = this._overlay.create(config);
// Consume the `keydownEvents` in order to prevent them from going to another overlay.
// Ideally we'd also have our keyboard event logic in here, however doing so will
// break anybody that may have implemented the `MatMenuPanel` themselves.
this._overlayRef.keydownEvents().subscribe();
}
return this._overlayRef;
}
/**
* This method builds the configuration object needed to create the overlay, the OverlayState.
* @returns OverlayConfig
*/
private _getOverlayConfig(): OverlayConfig {
return new OverlayConfig({
positionStrategy: this._overlay.position()
.flexibleConnectedTo(this._elementRef)
.withLockedPosition()
.withTransformOriginOn('.Menu'),
hasBackdrop: this.menu.hasBackdrop == null ? !this.triggersSubmenu() : this.menu.hasBackdrop,
backdropClass: this.menu.backdropClass || 'cdk-overlay-transparent-backdrop',
scrollStrategy: this._overlay.scrollStrategies.reposition(),
});
}
/**
* Listens to changes in the position of the overlay and sets the correct classes
* on the menu based on the new position. This ensures the animation origin is always
* correct, even if a fallback position is used for the overlay.
*/
private _subscribeToPositions(position: FlexibleConnectedPositionStrategy): void {
if (this.menu.setPositionClasses) {
position.positionChanges.subscribe(change => {
const posX: MenuPositionX = change.connectionPair.overlayX === 'start' ? 'after' : 'before';
const posY: MenuPositionY = change.connectionPair.overlayY === 'top' ? 'below' : 'above';
this.menu.setPositionClasses(posX, posY);
});
}
}
/**
* Sets the appropriate positions on a position strategy
* so the overlay connects with the trigger correctly.
* @param positionStrategy Strategy whose position to update.
*/
private _setPosition(positionStrategy: FlexibleConnectedPositionStrategy) {
let [originX, originFallbackX]: HorizontalConnectionPos[] =
this.menu.xPosition === 'before' ? ['end', 'start'] : ['start', 'end'];
const [overlayY, overlayFallbackY]: VerticalConnectionPos[] =
this.menu.yPosition === 'above' ? ['bottom', 'top'] : ['top', 'bottom'];
let [originY, originFallbackY] = [overlayY, overlayFallbackY];
let [overlayX, overlayFallbackX] = [originX, originFallbackX];
const offsetY = 0;
if (this.triggersSubmenu()) {
// When the menu is a sub-menu, it should always align itself
// to the edges of the trigger, instead of overlapping it.
overlayFallbackX = originX = this.menu.xPosition === 'before' ? 'start' : 'end';
originFallbackX = overlayX = originX === 'end' ? 'start' : 'end';
} else if (!this.menu.overlapTrigger) {
originY = overlayY === 'top' ? 'bottom' : 'top';
originFallbackY = overlayFallbackY === 'top' ? 'bottom' : 'top';
}
positionStrategy.withPositions([
{ originX, originY, overlayX, overlayY, offsetY },
{ originX: originFallbackX, originY, overlayX: overlayFallbackX, overlayY, offsetY },
{
originX,
originY: originFallbackY,
overlayX,
overlayY: overlayFallbackY,
offsetY: -offsetY,
},
{
originX: originFallbackX,
originY: originFallbackY,
overlayX: overlayFallbackX,
overlayY: overlayFallbackY,
offsetY: -offsetY,
},
]);
}
/** Cleans up the active subscriptions. */
private _cleanUpSubscriptions(): void {
this._closeSubscription.unsubscribe();
this._hoverSubscription.unsubscribe();
}
/** Returns a stream that emits whenever an action that should close the menu occurs. */
private _menuClosingActions() {
const backdrop = this._overlayRef.backdropClick();
const detachments = this._overlayRef.detachments();
const parentClose = this._parentMenu ? this._parentMenu.closed : of();
const hover = this._parentMenu ? this._parentMenu._hovered().pipe(
filter(active => active !== this._menuItem),
filter(() => this._menuOpen),
) : of();
return merge(backdrop, parentClose, hover, detachments);
}
/** Handles the cases where the user hovers over the trigger. */
private _handleHover(): void {
// Subscribe to changes in the hovered item in order to toggle the panel.
if (!this.triggersSubmenu()) {
return;
}
this._hoverSubscription = this._parentMenu._hovered()
// Since we might have multiple competing triggers for the same menu (e.g. a sub-menu
// with different data and triggers), we have to delay it by a tick to ensure that
// it won't be closed immediately after it is opened.
.pipe(
filter(active => active === this._menuItem && !active.disabled),
delay(0, asapScheduler),
)
.subscribe(() => {
this._openedBy = 'mouse';
// If the same menu is used between multiple triggers, it might still be animating
// while the new trigger tries to re-open it. Wait for the animation to finish
// before doing so. Also interrupt if the user moves to another item.
if (this.menu instanceof MenuComponent && this.menu._isAnimating) {
// We need the `delay(0)` here in order to avoid
// 'changed after checked' errors in some cases. See #12194.
this.menu._animationDone
.pipe(take(1), delay(0, asapScheduler), takeUntil(this._parentMenu._hovered()))
.subscribe(() => this.openMenu());
} else {
this.openMenu();
}
});
}
/** Gets the portal that should be attached to the overlay. */
private _getPortal(): TemplatePortal {
// Note that we can avoid this check by keeping the portal on the menu panel.
// While it would be cleaner, we'd have to introduce another required method on
// `MatMenuPanel`, making it harder to consume.
if (!this._portal || this._portal.templateRef !== this.menu.templateRef) {
this._portal = new TemplatePortal(this.menu.templateRef, this._viewContainerRef);
}
return this._portal;
}
} | the_stack |
import type {Framework} from '@roots/bud-framework'
import {pkgUp} from '@roots/bud-support'
import {posix} from 'path'
const {dirname} = posix
/**
* Filters framework values and returns a webpack configuration
*
* @param app - the Framework instance
*
* @public
*/
export async function config(app: Framework): Promise<void> {
app.hooks
.async<'build'>('build', async () => {
const entry = await app.hooks.filterAsync<'build.entry'>(
'build.entry',
)
const plugins =
await app.hooks.filterAsync<'build.plugins'>(
'build.plugins',
)
const resolve =
await app.hooks.filterAsync<'build.resolve'>(
'build.resolve',
)
return {
entry,
plugins,
resolve,
bail: app.hooks.filter<'build.bail'>('build.bail'),
cache: app.hooks.filter<'build.cache'>('build.cache'),
context:
app.hooks.filter<'build.context'>('build.context'),
devtool:
app.hooks.filter<'build.devtool'>('build.devtool'),
experiments: app.hooks.filter<'build.experiments'>(
'build.experiments',
),
externals: app.hooks.filter<'build.externals'>(
'build.externals',
),
infrastructureLogging:
app.hooks.filter<'build.infrastructureLogging'>(
'build.infrastructureLogging',
),
mode: app.hooks.filter<'build.mode'>('build.mode'),
module: app.hooks.filter<'build.module'>('build.module'),
name: app.hooks.filter<'build.name'>('build.name'),
node: app.hooks.filter<'build.node'>('build.node'),
output: app.hooks.filter<'build.output'>('build.output'),
optimization: app.hooks.filter<'build.optimization'>(
'build.optimization',
),
parallelism: app.hooks.filter<'build.parallelism'>(
'build.parallelism',
),
performance: app.hooks.filter<'build.performance'>(
'build.performance',
),
profile:
app.hooks.filter<'build.profile'>('build.profile'),
recordsPath: app.hooks.filter<'build.recordsPath'>(
'build.recordsPath',
),
stats: app.hooks.filter<'build.stats'>('build.stats'),
target: app.hooks.filter<'build.target'>('build.target'),
watch: app.hooks.filter<'build.watch'>('build.watch'),
watchOptions: app.hooks.filter<'build.watchOptions'>(
'build.watchOptions',
),
}
})
/**
* build.bail
*/
.hooks.on<'build.bail'>('build.bail', () =>
app.store.get('build.bail'),
)
/**
* build.context
*/
.hooks.on<'build.context'>('build.context', () =>
app.path('project'),
)
/**
* build.devtool
*/
.hooks.on<'build.devtool'>('build.devtool', () =>
app.store.get('build.devtool'),
)
/**
* build.infrastructureLogging
*/
.hooks.on<'build.infrastructureLogging'>(
'build.infrastructureLogging',
() => app.store.get('build.infrastructureLogging'),
)
/**
* build.mode
*/
.hooks.on<'build.mode'>('build.mode', () => app.mode)
/**
* build.module
*/
.hooks.on<'build.module'>('build.module', () => ({
rules: app.hooks.filter<'build.module.rules'>(
'build.module.rules',
),
}))
/**
* build.module.rules
*/
.hooks.on<'build.module.rules'>('build.module.rules', () => [
...app.hooks.filter<'build.module.rules.before'>(
'build.module.rules.before',
),
{
oneOf: app.hooks.filter<'build.module.rules.oneOf'>(
'build.module.rules.oneOf',
),
},
...app.hooks.filter<'build.module.rules.after'>(
'build.module.rules.after',
),
])
/**
* build.module.rules[1].oneOf
*/
.hooks.on<'build.module.rules.oneOf'>(
'build.module.rules.oneOf',
() =>
Object.values(app.build.rules).map(rule =>
rule.make(app),
),
)
/**
* build.module.rules[0]
*/
.hooks.on<'build.module.rules.before'>(
'build.module.rules.before',
() => [
{
test: /\.[cm]?(jsx?|tsx?)$/,
parser: {requireEnsure: false},
},
],
)
/**
* build.module.rules[2]
*/
.hooks.on<'build.module.rules.after'>(
'build.module.rules.after',
() => [],
)
/**
* build.name
*/
.hooks.on(<'build.name'>'build.name', () => app.name)
/**
* build.node
*/
.hooks.on<'build.node'>('build.node', () => false)
/**
* build.optimization
*/
.hooks.on<'build.optimization'>(
'build.optimization',
() => ({
emitOnErrors:
app.hooks.filter<'build.optimization.emitOnErrors'>(
'build.optimization.emitOnErrors',
),
minimize:
app.hooks.filter<'build.optimization.minimize'>(
'build.optimization.minimize',
),
minimizer:
app.hooks.filter<'build.optimization.minimizer'>(
'build.optimization.minimizer',
),
moduleIds:
app.hooks.filter<'build.optimization.moduleIds'>(
'build.optimization.moduleIds',
),
runtimeChunk:
app.hooks.filter<'build.optimization.runtimeChunk'>(
'build.optimization.runtimeChunk',
),
splitChunks:
app.hooks.filter<'build.optimization.splitChunks'>(
'build.optimization.splitChunks',
),
}),
)
/**
* build.optimization.emitOnErrors
*/
.hooks.on<'build.optimization.emitOnErrors'>(
'build.optimization.emitOnErrors',
() => app.store.get('build.optimization.emitOnErrors'),
)
/**
* build.optimization.minimize
*/
.hooks.on<'build.optimization.minimize'>(
'build.optimization.minimize',
() => app.store.is('features.minimize', true),
)
/**
* build.optimization.minimizer
*/
.hooks.on<'build.optimization.minimizer'>(
'build.optimization.minimizer',
() => ['...'],
)
/**
* build.optimization.moduleIds
*/
.hooks.on<'build.optimization.moduleIds'>(
'build.optimization.moduleIds',
() => app.store.get('build.optimization.moduleIds'),
)
/**
* build.optimization.removeEmptyChunks
*/
.hooks.on<'build.optimization.removeEmptyChunks'>(
'build.optimization.removeEmptyChunks',
() =>
app.store.get('build.optimization.removeEmptyChunks'),
)
/**
* build.optimization.runtimeChunk
*/
.hooks.on('build.optimization.runtimeChunk', () =>
app.store.is('features.runtimeChunk', true),
)
/**
* build.optimization.splitChunks
*/
.hooks.on(
'build.optimization.splitChunks',
() => app.store.is('features.splitChunks', true) as any,
)
/**
* build.output
*/
.hooks.on<'build.output'>('build.output', () => ({
assetModuleFilename:
app.hooks.filter<'build.output.assetModuleFilename'>(
'build.output.assetModuleFilename',
),
chunkFilename: app.hooks.filter(
'build.output.chunkFilename',
),
clean: app.hooks.filter<'build.output.clean'>(
'build.output.clean',
),
filename: app.hooks.filter<'build.output.filename'>(
'build.output.filename',
),
path: app.hooks.filter<'build.output.path'>(
'build.output.path',
),
pathinfo: app.hooks.filter<'build.output.pathinfo'>(
'build.output.pathinfo',
),
publicPath: app.hooks.filter<'build.output.publicPath'>(
'build.output.publicPath',
),
}))
/**
* build.output.assetModuleFilename
*/
.hooks.on('build.output.assetModuleFilename', () =>
app.isProduction && app.store.is('features.hash', true)
? `assets/${app.store.get('hashFormat')}[ext]`
: app.store.get('fileFormat'),
)
.hooks.on('build.output.clean', () =>
app.store.get('build.output.clean'),
)
/**
* build.output.filename
*/
.hooks.on(
'build.output.filename',
() =>
`${
app.store.is('features.hash', true) && app.isProduction
? app.store.get('hashFormat')
: app.store.get('fileFormat')
}.js`,
)
/**
* build.output.path
*/
.hooks.on('build.output.path', () => app.path('dist'))
/**
* build.output.pathinfo
*/
.hooks.on('build.output.pathinfo', () =>
app.store.get('build.output.pathinfo'),
)
/**
* build.output.publicPath
*/
.hooks.on('build.output.publicPath', () =>
app.store.get('location.publicPath'),
)
/**
* Parallelism
*/
.hooks.on('build.parallelism', () =>
app.store.get('build.parallelism'),
)
/**
* build.performance
*/
.hooks.on<'build.performance'>('build.performance', () =>
app.store.get('build.performance'),
)
.hooks.async<'build.plugins'>('build.plugins', async () => {
const newExtensions = await app.extensions.make()
return newExtensions
})
/**
* build.profile
*/
.hooks.on('build.profile', () =>
app.store.get('build.profile'),
)
/**
* build.recordsPath
*/
.hooks.on<'build.recordsPath'>('build.recordsPath', () =>
app.path('storage', app.name, `modules.json`),
)
.hooks.async<'build.resolve'>('build.resolve', async () => {
const modules =
await app.hooks.filterAsync<'build.resolve.modules'>(
'build.resolve.modules',
)
const alias =
await app.hooks.filter<'build.resolve.alias'>(
'build.resolve.alias',
)
const extensions =
app.hooks.filter<'build.resolve.extensions'>(
'build.resolve.extensions',
)
return {modules, alias, extensions}
})
/**
* build.resolve.alias
*/
.hooks.on<'build.resolve.alias'>(
'build.resolve.alias',
() => ({}),
)
/**
* build.resolve.modules
*/
.hooks.async<'build.resolve.modules'>(
'build.resolve.modules',
async (value?: any): Promise<any> => {
const budPkg = await pkgUp({
cwd: require.resolve('@roots/bud'),
})
const bud = dirname(budPkg)
const roots = bud
.split('/')
.splice(0, bud.split('/').length - 1)
.join('/')
const peers = roots
.split('/')
.splice(0, roots.split('/').length - 1)
.join('/')
return [
...new Set([
...(value ?? []),
app.hooks.filter('location.src'),
app.hooks.filter('location.modules'),
peers,
...(app.project?.get('resolve') ?? []),
...(app.root?.project.get('resolve') ?? []),
]),
]
},
)
/**
* build.resolve.extensions
*/
.hooks.on<'build.resolve.extensions'>(
'build.resolve.extensions',
() => app.store.get('build.resolve.extensions'),
)
/**
* build.stats
*/
.hooks.on<'build.stats'>('build.stats', () =>
app.store.get('build.stats'),
)
/**
* build.target
*/
.hooks.on<'build.target'>(
'build.target',
() =>
`browserslist:${app.path('project', 'package.json')}`,
)
/**
* build.watch
*/
.hooks.on<'build.watch'>('build.watch', () =>
app.store.get('build.watch'),
)
/**
* build.watchOptions
*/
.hooks.on<'build.watchOptions'>('build.watchOptions', () =>
app.store.get('build.watchOptions'),
)
} | the_stack |
import { PointModel } from './point-model';
/**
* Matrix module is used to transform points based on offsets, angle
*/
/** @private */
export enum MatrixTypes {
Identity = 0,
Translation = 1,
Scaling = 2,
Unknown = 4
}
/** @private */
export class Matrix {
/** @private */
public m11: number;
/** @private */
public m12: number;
/** @private */
public m21: number;
/** @private */
public m22: number;
/** @private */
public offsetX: number;
/** @private */
public offsetY: number;
/** @private */
public type: MatrixTypes;
constructor(m11: number, m12: number, m21: number, m22: number, offsetX: number, offsetY: number, type?: MatrixTypes) {
this.m11 = m11;
this.m12 = m12;
this.m21 = m21;
this.m22 = m22;
this.offsetX = offsetX;
this.offsetY = offsetY;
// if (type === undefined) {
// this.type = MatrixTypes.Unknown;
// } else {
// this.type = type;
// }
this.type = type;
}
}
/**
* Will identify the matrix .\
*
* @returns {Matrix} Will identify the matrix .
* @private
*/
export function identityMatrix(): Matrix {
return new Matrix(1, 0, 0, 1, 0, 0, MatrixTypes.Identity);
}
/**
* Will transform the points by matrix .\
*
* @returns {PointModel[]} Will transform the points by matrix .
*
* @param {Matrix} matrix - provide the matrix value .
* @param {number} point - provide the points value.
* @private
*/
export function transformPointByMatrix(matrix: Matrix, point: PointModel): PointModel {
const pt: PointModel = multiplyPoint(matrix, point.x, point.y);
return { x: Math.round(pt.x * 100) / 100, y: Math.round(pt.y * 100) / 100 };
}
/**
* Will transform the points by matrix .\
*
* @returns {PointModel[]} Will transform the points by matrix .
*
* @param {Matrix} matrix - provide the matrix value .
* @param {number} points - provide the points value.
* @private
*/
export function transformPointsByMatrix(matrix: Matrix, points: PointModel[]): PointModel[] {
const transformedPoints: PointModel[] = [];
for (const point of points) {
transformedPoints.push(transformPointByMatrix(matrix, point));
}
return transformedPoints;
}
/**
* Will rotate the matrix .\
*
* @returns {void} Will rotate the matrix .
*
* @param {Matrix} matrix - provide the matrix value .
* @param {number} angle - provide the angle value.
* @param {number} centerX - provide the centerX value .
* @param {number} centerY - provide the centerY value .
* @private
*/
export function rotateMatrix(matrix: Matrix, angle: number, centerX: number, centerY: number): void {
angle %= 360.0;
multiplyMatrix(matrix, createRotationRadians(angle * 0.017453292519943295, centerX ? centerX : 0, centerY ? centerY : 0));
}
/**
* Will scale the matrix .\
*
* @returns {void} Will scale the matrix .
*
* @param {Matrix} matrix - provide the matrix value .
* @param {number} scaleX - provide the scaleXvalue.
* @param {number} scaleY - provide the scaleY value .
* @param {number} centerX - provide the centerX value .
* @param {number} centerY - provide the centerY value .
* @private
*/
export function scaleMatrix(
matrix: Matrix, scaleX: number, scaleY: number, centerX: number = 0, centerY: number = 0): void {
multiplyMatrix(matrix, createScaling(scaleX, scaleY, centerX, centerY));
}
/**
* Will translate the matrix .\
*
* @returns {void} Will translate the matrix .
*
* @param {Matrix} matrix - provide the matrix value .
* @param {number} offsetX - provide the offset x value.
* @param {number} offsetY - provide the offset y value .
* @private
*/
export function translateMatrix(matrix: Matrix, offsetX: number, offsetY: number): void {
if (matrix.type & MatrixTypes.Identity) {
matrix.type = MatrixTypes.Translation;
setMatrix(matrix, 1.0, 0.0, 0.0, 1.0, offsetX, offsetY);
return;
}
if (matrix.type & MatrixTypes.Unknown) {
matrix.offsetX += offsetX;
matrix.offsetY += offsetY;
return;
}
matrix.offsetX += offsetX;
matrix.offsetY += offsetY;
matrix.type |= MatrixTypes.Translation;
}
/**
* Will create scaling value .\
*
* @returns {Matrix} Will create scaling value . .
*
* @param {Matrix} scaleX - provide the scale x value .
* @param {number} scaleY - provide the scale y value.
* @param {number} centerX - provide the centerX x value .
* @param {number} centerY - provide the centerX y value .
* @private
*/
function createScaling(scaleX: number, scaleY: number, centerX: number, centerY: number): Matrix {
const result: Matrix = identityMatrix();
result.type = !(centerX || centerY) ? MatrixTypes.Scaling : MatrixTypes.Scaling | MatrixTypes.Translation;
setMatrix(result, scaleX, 0.0, 0.0, scaleY, centerX - scaleX * centerX, centerY - scaleY * centerY);
return result;
}
/**
* Will create the rotation radians.\
*
* @returns {Matrix} Will create the rotation radians .
*
* @param {Matrix} angle - provide the angle .
* @param {number} centerX - provide the x value .
* @param {number} centerY - provide the y value .
* @private
*/
function createRotationRadians(angle: number, centerX: number, centerY: number): Matrix {
const result: Matrix = identityMatrix();
const num: number = Math.sin(angle);
const num2: number = Math.cos(angle);
const offsetX: number = centerX * (1.0 - num2) + centerY * num;
const offsetY: number = centerY * (1.0 - num2) - centerX * num;
result.type = MatrixTypes.Unknown;
setMatrix(result, num2, num, -num, num2, offsetX, offsetY);
return result;
}
/**
* Multiply the point .\
*
* @returns {void} Multiply the point .
*
* @param {Matrix} matrix - Provide the matrix .
* @param {number} x - provide the x value .
* @param {number} y - provide the y value .
* @private
*/
function multiplyPoint(matrix: Matrix, x: number, y: number): PointModel {
switch (matrix.type) {
case MatrixTypes.Identity: break;
case MatrixTypes.Translation:
x += matrix.offsetX;
y += matrix.offsetY;
break;
case MatrixTypes.Scaling:
x *= matrix.m11;
y *= matrix.m22;
break;
case MatrixTypes.Translation | MatrixTypes.Scaling:
x *= matrix.m11;
x += matrix.offsetX;
y *= matrix.m22;
y += matrix.offsetY;
break;
default:
// eslint-disable-next-line no-case-declarations
const num: number = y * matrix.m21 + matrix.offsetX;
// eslint-disable-next-line no-case-declarations
const num2: number = x * matrix.m12 + matrix.offsetY;
x *= matrix.m11;
x += num;
y *= matrix.m22;
y += num2;
break;
}
return { x: x, y: y };
}
/**
* Will multiply the matrix .\
*
* @returns {void} Will multiply the matrix .
*
* @param {Matrix} matrix1 - Provide the matrix 1 value .
* @param {Matrix} matrix2 - Provide the matrix 2 value .
* @private
*/
export function multiplyMatrix(matrix1: Matrix, matrix2: Matrix): void {
const type: MatrixTypes = matrix1.type;
const type2: MatrixTypes = matrix2.type;
if (type2 === MatrixTypes.Identity) {
return;
}
if (type === MatrixTypes.Identity) {
assignMatrix(matrix1, matrix2);
matrix1.type = matrix2.type;
return;
}
if (type2 === MatrixTypes.Translation) {
matrix1.offsetX += matrix2.offsetX;
matrix1.offsetY += matrix2.offsetY;
if (type !== MatrixTypes.Unknown) {
matrix1.type |= MatrixTypes.Translation;
}
return;
}
if (type !== MatrixTypes.Translation) {
const num: number = type << 4 | type2;
switch (num) {
case 34:
matrix1.m11 *= matrix2.m11;
matrix1.m22 *= matrix2.m22;
return;
case 35:
matrix1.m11 *= matrix2.m11;
matrix1.m22 *= matrix2.m22;
matrix1.offsetX = matrix2.offsetX;
matrix1.offsetY = matrix2.offsetY;
matrix1.type = (MatrixTypes.Translation | MatrixTypes.Scaling);
return;
case 36: break;
default:
{
switch (num) {
case 50:
matrix1.m11 *= matrix2.m11;
matrix1.m22 *= matrix2.m22;
matrix1.offsetX *= matrix2.m11;
matrix1.offsetY *= matrix2.m22;
return;
case 51:
matrix1.m11 *= matrix2.m11;
matrix1.m22 *= matrix2.m22;
matrix1.offsetX = matrix2.m11 * matrix1.offsetX + matrix2.offsetX;
matrix1.offsetY = matrix2.m22 * matrix1.offsetY + matrix2.offsetY;
return;
case 52: break;
default:
switch (num) {
case 66:
case 67:
case 68: break;
default: return;
}
break;
}
break;
}
}
const result: Matrix = identityMatrix();
const m11New: number = matrix1.m11 * matrix2.m11 + matrix1.m12 * matrix2.m21;
const m12New: number = matrix1.m11 * matrix2.m12 + matrix1.m12 * matrix2.m22;
const m21New: number = matrix1.m21 * matrix2.m11 + matrix1.m22 * matrix2.m21;
const m22New: number = matrix1.m21 * matrix2.m12 + matrix1.m22 * matrix2.m22;
const offsetX: number = matrix1.offsetX * matrix2.m11 + matrix1.offsetY * matrix2.m21 + matrix2.offsetX;
const offsetY: number = matrix1.offsetX * matrix2.m12 + matrix1.offsetY * matrix2.m22 + matrix2.offsetY;
setMatrix(result, m11New, m12New, m21New, m22New, offsetX, offsetY);
if (result.m21 || result.m12) {
result.type = MatrixTypes.Unknown;
} else {
if (result.m11 && result.m11 !== 1.0 || result.m22 && result.m22 !== 1.0) {
result.type = MatrixTypes.Scaling;
}
if (result.offsetX || result.offsetY) {
result.type |= MatrixTypes.Translation;
}
if ((result.type & (MatrixTypes.Translation | MatrixTypes.Scaling)) === MatrixTypes.Identity) {
result.type = MatrixTypes.Identity;
}
result.type = MatrixTypes.Scaling | MatrixTypes.Translation;
}
assignMatrix(matrix1, result);
matrix1.type = result.type;
return;
}
const offsetX: number = matrix1.offsetX;
const offsetY: number = matrix1.offsetY;
matrix1.offsetX = offsetX * matrix2.m11 + offsetY * matrix2.m21 + matrix2.offsetX;
matrix1.offsetY = offsetX * matrix2.m12 + offsetY * matrix2.m22 + matrix2.offsetY;
if (type2 === MatrixTypes.Unknown) {
matrix1.type = MatrixTypes.Unknown;
return;
}
matrix1.type = (MatrixTypes.Translation | MatrixTypes.Scaling);
}
/**
* set the matrix .\
*
* @returns {void} set the matrix .
*
* @param {Matrix} mat - Provide the matrix 1 value .
* @param {number} m11 - Provide the matrix m11 value .
* @param {number} m12 - Provide the matrix m11 value .
* @param {number} m21 - Provide the matrix m11 value .
* @param {number} m22 - Provide the matrix m11 value .
* @param {number} x - Provide the matrix m11 value .
* @param {number} y - Provide the matrix m11 value .
* @private
*/
function setMatrix(mat: Matrix, m11: number, m12: number, m21: number, m22: number, x: number, y: number): void {
mat.m11 = m11;
mat.m12 = m12;
mat.m21 = m21;
mat.m22 = m22;
mat.offsetX = x;
mat.offsetY = y;
}
/**
* Assign the matrix .\
*
* @returns {void} Assign the matrix .
*
* @param {Matrix} matrix1 - Provide the element type as string .
* @param {Matrix} matrix2 - Provide the element type as string .
* @private
*/
function assignMatrix(matrix1: Matrix, matrix2: Matrix): void {
matrix1.m11 = matrix2.m11;
matrix1.m12 = matrix2.m12;
matrix1.m21 = matrix2.m21;
matrix1.m22 = matrix2.m22;
matrix1.offsetX = matrix2.offsetX;
matrix1.offsetY = matrix2.offsetY;
matrix1.type = matrix2.type;
} | the_stack |
import {Class, Arrays, Creatable, ObserverType} from "@swim/util";
import {Affinity} from "@swim/component";
import {R2Box} from "@swim/math";
import {ThemeMatrix, Theme} from "@swim/theme";
import {ToAttributeString, ToStyleString, ToCssValue} from "@swim/style";
import {View, Viewport} from "@swim/view";
import type {StyleContext} from "../css/StyleContext";
import {
ViewNodeType,
AnyNodeView,
NodeViewInit,
NodeViewFactory,
NodeViewClass,
NodeViewConstructor,
NodeView,
} from "../node/NodeView";
import type {
ElementViewObserver,
ElementViewObserverCache,
ViewWillSetAttribute,
ViewDidSetAttribute,
ViewWillSetStyle,
ViewDidSetStyle,
} from "./ElementViewObserver";
import {DomService} from "../"; // forward import
import {HtmlView} from "../"; // forward import
import {SvgView} from "../"; // forward import
/** @public */
export interface ViewElement extends Element, ElementCSSInlineStyle {
view?: ElementView;
}
/** @public */
export type AnyElementView<V extends ElementView = ElementView> = AnyNodeView<V>;
/** @public */
export interface ElementViewInit extends NodeViewInit {
id?: string;
classList?: string[];
}
/** @public */
export interface ElementViewFactory<V extends ElementView = ElementView, U = AnyElementView<V>> extends NodeViewFactory<V, U> {
fromTag(tag: string): V;
}
/** @public */
export interface ElementViewClass<V extends ElementView = ElementView, U = AnyElementView<V>> extends NodeViewClass<V, U>, ElementViewFactory<V, U> {
readonly tag?: string;
readonly namespace?: string;
}
/** @public */
export interface ElementViewConstructor<V extends ElementView = ElementView, U = AnyElementView<V>> extends NodeViewConstructor<V, U>, ElementViewClass<V, U> {
}
/** @public */
export class ElementView extends NodeView implements StyleContext {
constructor(node: Element) {
super(node);
this.initElement(node);
}
override readonly observerType?: Class<ElementViewObserver>;
override readonly node!: Element & ElementCSSInlineStyle;
protected initElement(node: Element): void {
const themeName = node.getAttribute("swim-theme");
if (themeName !== null && themeName !== "") {
let theme: ThemeMatrix | undefined;
if (themeName === "auto") {
const viewport = Viewport.detect();
const colorScheme = viewport.colorScheme;
if (colorScheme === "dark") {
theme = Theme.dark;
} else {
theme = Theme.light;
}
} else if (themeName.indexOf('.') < 0) {
theme = (Theme as any)[themeName];
} else {
theme = DomService.eval(themeName) as ThemeMatrix | undefined;
}
if (theme instanceof ThemeMatrix) {
this.theme.setValue(theme, Affinity.Extrinsic);
} else {
throw new TypeError("unknown swim-theme: " + themeName);
}
}
}
/** @internal */
protected override mountTheme(): void {
super.mountTheme();
if (NodeView.isRootView(this.node)) {
const themeService = this.themeProvider.service;
if (themeService !== void 0 && themeService !== null) {
if (this.mood.hasAffinity(Affinity.Intrinsic) && this.mood.value === null) {
this.mood.setValue(themeService.mood, Affinity.Intrinsic);
}
if (this.theme.hasAffinity(Affinity.Intrinsic) && this.theme.value === null) {
this.theme.setValue(themeService.theme, Affinity.Intrinsic);
}
}
}
}
getAttribute(attributeName: string): string | null {
return this.node.getAttribute(attributeName);
}
setAttribute(attributeName: string, value: unknown): this {
this.willSetAttribute(attributeName, value);
if (value !== void 0 && value !== null) {
this.node.setAttribute(attributeName, ToAttributeString(value));
} else {
this.node.removeAttribute(attributeName);
}
this.onSetAttribute(attributeName, value);
this.didSetAttribute(attributeName, value);
return this;
}
protected willSetAttribute(attributeName: string, value: unknown): void {
const observers = this.observerCache.viewWillSetAttributeObservers;
if (observers !== void 0) {
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
observer.viewWillSetAttribute(attributeName, value, this);
}
}
}
protected onSetAttribute(attributeName: string, value: unknown): void {
// hook
}
protected didSetAttribute(attributeName: string, value: unknown): void {
const observers = this.observerCache.viewDidSetAttributeObservers;
if (observers !== void 0) {
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
observer.viewDidSetAttribute(attributeName, value, this);
}
}
}
getStyle(propertyNames: string | ReadonlyArray<string>): CSSStyleValue | string | undefined {
if (typeof CSSStyleValue !== "undefined") { // CSS Typed OM support
const style = this.node.attributeStyleMap;
if (typeof propertyNames === "string") {
try {
return style.get(propertyNames);
} catch (e) {
return void 0;
}
} else {
for (let i = 0, n = propertyNames.length; i < n; i += 1) {
const value = style.get(propertyNames[i]!);
if (value !== void 0) {
return value;
}
}
return "";
}
} else {
const style = this.node.style;
if (typeof propertyNames === "string") {
return style.getPropertyValue(propertyNames);
} else {
for (let i = 0, n = propertyNames.length; i < n; i += 1) {
const value = style.getPropertyValue(propertyNames[i]!);
if (value.length !== 0) {
return value;
}
}
return "";
}
}
}
setStyle(propertyName: string, value: unknown, priority?: string): this {
this.willSetStyle(propertyName, value, priority);
if (typeof CSSStyleValue !== "undefined") { // CSS Typed OM support
if (value !== void 0 && value !== null) {
const cssValue = ToCssValue(value);
if (cssValue !== null) {
try {
this.node.attributeStyleMap.set(propertyName, cssValue);
} catch (e) {
// swallow
}
} else {
this.node.style.setProperty(propertyName, ToStyleString(value), priority);
}
} else {
this.node.attributeStyleMap.delete(propertyName);
}
} else {
if (value !== void 0 && value !== null) {
this.node.style.setProperty(propertyName, ToStyleString(value), priority);
} else {
this.node.style.removeProperty(propertyName);
}
}
this.onSetStyle(propertyName, value, priority);
this.didSetStyle(propertyName, value, priority);
return this;
}
protected willSetStyle(propertyName: string, value: unknown, priority: string | undefined): void {
const observers = this.observerCache.viewWillSetStyleObservers;
if (observers !== void 0) {
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
observer.viewWillSetStyle(propertyName, value, priority, this);
}
}
}
protected onSetStyle(propertyName: string, value: unknown, priority: string | undefined): void {
// hook
}
protected didSetStyle(propertyName: string, value: unknown, priority: string | undefined): void {
const observers = this.observerCache.viewDidSetStyleObservers;
if (observers !== void 0) {
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
observer.viewDidSetStyle(propertyName, value, priority, this);
}
}
}
id(): string | undefined;
id(value: string | undefined): this;
id(value?: string | undefined): string | undefined | this {
if (arguments.length == 0) {
const id = this.getAttribute("id");
return id !== null ? id : void 0;
} else {
this.setAttribute("id", value);
return this;
}
}
className(): string | undefined;
className(value: string | undefined): this;
className(value?: string | undefined): string | undefined | this {
if (arguments.length === 0) {
const className = this.getAttribute("class");
return className !== null ? className : void 0;
} else {
this.setAttribute("class", value);
return this;
}
}
get classList(): DOMTokenList {
return this.node.classList;
}
hasClass(className: string): boolean {
return this.node.classList.contains(className);
}
addClass(...classNames: string[]): this {
const classList = this.node.classList;
for (let i = 0, n = classNames.length; i < n; i += 1) {
classList.add(classNames[i]!);
}
return this;
}
removeClass(...classNames: string[]): this {
const classList = this.node.classList;
for (let i = 0, n = classNames.length; i < n; i += 1) {
classList.remove(classNames[i]!);
}
return this;
}
toggleClass(className: string, state?: boolean): this {
const classList = this.node.classList;
if (state === void 0) {
classList.toggle(className);
} else if (state === true) {
classList.add(className);
} else if (state === false) {
classList.remove(className);
}
return this;
}
override get clientBounds(): R2Box {
const bounds = this.node.getBoundingClientRect();
return new R2Box(bounds.left, bounds.top, bounds.right, bounds.bottom);
}
override get pageBounds(): R2Box {
const bounds = this.node.getBoundingClientRect();
const scrollX = window.pageXOffset;
const scrollY = window.pageYOffset;
return new R2Box(bounds.left + scrollX, bounds.top + scrollY,
bounds.right + scrollX, bounds.bottom + scrollY);
}
override on<K extends keyof ElementEventMap>(type: K, listener: (this: Element, event: ElementEventMap[K]) => unknown,
options?: AddEventListenerOptions | boolean): this;
override on(type: string, listener: EventListenerOrEventListenerObject, options?: AddEventListenerOptions | boolean): this;
override on(type: string, listener: EventListenerOrEventListenerObject, options?: AddEventListenerOptions | boolean): this {
this.node.addEventListener(type, listener, options);
return this;
}
override off<K extends keyof ElementEventMap>(type: K, listener: (this: Element, event: ElementEventMap[K]) => unknown,
options?: EventListenerOptions | boolean): this;
override off(type: string, listener: EventListenerOrEventListenerObject, options?: EventListenerOptions | boolean): this;
override off(type: string, listener: EventListenerOrEventListenerObject, options?: EventListenerOptions | boolean): this {
this.node.removeEventListener(type, listener, options);
return this;
}
/** @internal */
override readonly observerCache!: ElementViewObserverCache<this>;
protected override onObserve(observer: ObserverType<this>): void {
super.onObserve(observer);
if (observer.viewWillSetAttribute !== void 0) {
this.observerCache.viewWillSetAttributeObservers = Arrays.inserted(observer as ViewWillSetAttribute, this.observerCache.viewWillSetAttributeObservers);
}
if (observer.viewDidSetAttribute !== void 0) {
this.observerCache.viewDidSetAttributeObservers = Arrays.inserted(observer as ViewDidSetAttribute, this.observerCache.viewDidSetAttributeObservers);
}
if (observer.viewWillSetStyle !== void 0) {
this.observerCache.viewWillSetStyleObservers = Arrays.inserted(observer as ViewWillSetStyle, this.observerCache.viewWillSetStyleObservers);
}
if (observer.viewDidSetStyle !== void 0) {
this.observerCache.viewDidSetStyleObservers = Arrays.inserted(observer as ViewDidSetStyle, this.observerCache.viewDidSetStyleObservers);
}
}
protected override onUnobserve(observer: ObserverType<this>): void {
super.onUnobserve(observer);
if (observer.viewWillSetAttribute !== void 0) {
this.observerCache.viewWillSetAttributeObservers = Arrays.removed(observer as ViewWillSetAttribute, this.observerCache.viewWillSetAttributeObservers);
}
if (observer.viewDidSetAttribute !== void 0) {
this.observerCache.viewDidSetAttributeObservers = Arrays.removed(observer as ViewDidSetAttribute, this.observerCache.viewDidSetAttributeObservers);
}
if (observer.viewWillSetStyle !== void 0) {
this.observerCache.viewWillSetStyleObservers = Arrays.removed(observer as ViewWillSetStyle, this.observerCache.viewWillSetStyleObservers);
}
if (observer.viewDidSetStyle !== void 0) {
this.observerCache.viewDidSetStyleObservers = Arrays.removed(observer as ViewDidSetStyle, this.observerCache.viewDidSetStyleObservers);
}
}
override init(init: ElementViewInit): void {
super.init(init);
if (init.id !== void 0) {
this.id(init.id);
}
if (init.classList !== void 0) {
this.addClass(...init.classList);
}
}
/** @internal */
static readonly tag?: string;
/** @internal */
static readonly namespace?: string;
static override create<S extends abstract new (...args: any) => InstanceType<S>>(this: S): InstanceType<S>;
static override create(): ElementView;
static override create(): ElementView {
let tag = this.tag;
if (tag === void 0) {
tag = "div";
}
return this.fromTag(tag);
}
static fromTag<S extends abstract new (...args: any) => InstanceType<S>>(this: S, tag: string, namespace?: string): InstanceType<S>;
static fromTag(tag: string, namespace?: string): ElementView;
static fromTag(tag: string, namespace?: string): ElementView {
if (namespace === void 0) {
if (tag === "svg") {
namespace = SvgView.namespace;
}
}
let node: Element;
if (namespace !== void 0) {
node = document.createElementNS(namespace, tag);
} else {
node = document.createElement(tag);
}
return this.fromNode(node);
}
static override fromNode<S extends new (node: Element) => InstanceType<S>>(this: S, node: ViewNodeType<InstanceType<S>>): InstanceType<S>;
static override fromNode(node: Element): ElementView;
static override fromNode(node: Element): ElementView {
let view = (node as ViewElement).view;
if (view === void 0) {
if (node instanceof HTMLElement) {
view = HtmlView.fromNode(node);
} else if (node instanceof SVGElement) {
view = SvgView.fromNode(node);
} else {
view = new this(node);
this.mount(view);
}
} else if (!(view instanceof this)) {
throw new TypeError(view + " not an instance of " + this);
}
return view;
}
static override fromAny<S extends abstract new (...args: any) => InstanceType<S>>(this: S, value: AnyElementView<InstanceType<S>>): InstanceType<S>;
static override fromAny(value: AnyElementView | string): ElementView;
static override fromAny(value: AnyElementView | string): ElementView {
if (value === void 0 || value === null) {
return value;
} else if (value instanceof View) {
if (value instanceof this) {
return value;
} else {
throw new TypeError(value + " not an instance of " + this);
}
} else if (value instanceof Node) {
return this.fromNode(value);
} else if (typeof value === "string") {
return this.fromTag(value);
} else if (Creatable.is(value)) {
return value.create();
} else {
return this.fromInit(value);
}
}
} | the_stack |
import {
Component,
Input,
Output,
EventEmitter,
OnInit,
ViewChild,
ElementRef,
forwardRef,
NgZone,
ChangeDetectorRef,
OnDestroy,
} from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
import { Observable, Subject } from 'rxjs';
import { fromEvent, merge, timer } from 'rxjs';
import { debounceTime, distinctUntilChanged, takeUntil } from 'rxjs/operators';
// Use esm version to support shipping subset of languages and features
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
const noop: any = () => {
// empty method
};
// counter for ids to allow for multiple editors on one page
let uniqueCounter: number = 0;
@Component({
selector: 'td-code-editor',
templateUrl: './code-editor.component.html',
styleUrls: ['./code-editor.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => TdCodeEditorComponent),
multi: true,
},
],
})
export class TdCodeEditorComponent implements OnInit, ControlValueAccessor, OnDestroy {
private _destroy: Subject<boolean> = new Subject<boolean>();
private _widthSubject: Subject<number> = new Subject<number>();
private _heightSubject: Subject<number> = new Subject<number>();
private _editorStyle: string = 'width:100%;height:100%;border:1px solid grey;';
private _value: string = '';
private _theme: string = 'vs';
private _language: string = 'javascript';
private _subject: Subject<string> = new Subject();
private _editorInnerContainer: string = 'editorInnerContainer' + uniqueCounter++;
private _editor: any;
private _fromEditor: boolean = false;
private _componentInitialized: boolean = false;
private _editorOptions: any = {};
private _isFullScreen: boolean = false;
private _keycode: any;
private _registeredLanguagesStyles: HTMLStyleElement[] = [];
@ViewChild('editorContainer', { static: true }) _editorContainer: ElementRef;
/**
* editorInitialized: function($event)
* Event emitted when editor is first initialized
*/
@Output() editorInitialized: EventEmitter<void> = new EventEmitter<void>();
/**
* editorConfigurationChanged: function($event)
* Event emitted when editor's configuration changes
*/
@Output() editorConfigurationChanged: EventEmitter<void> = new EventEmitter<void>();
/**
* editorLanguageChanged: function($event)
* Event emitted when editor's Language changes
*/
@Output() editorLanguageChanged: EventEmitter<void> = new EventEmitter<void>();
/**
* editorValueChange: function($event)
* Event emitted any time something changes the editor value
*/
@Output() editorValueChange: EventEmitter<void> = new EventEmitter<void>();
/**
* The change event notifies you about a change happening in an input field.
* Since the component is not a native Angular component have to specifiy the event emitter ourself
*/
@Output() change: EventEmitter<void> = new EventEmitter<void>();
/* tslint:disable-next-line */
propagateChange = (_: any) => {};
onTouched = () => noop;
/**
* value?: string
*/
@Input('value')
set value(value: string) {
if (value === this._value) {
return;
}
this._value = value;
if (this._componentInitialized) {
this.applyValue();
}
}
get value(): string {
return this._value;
}
applyValue(): void {
if (!this._fromEditor) {
this._editor.setValue(this._value);
}
this._fromEditor = false;
this.propagateChange(this._value);
this.change.emit();
this.editorValueChange.emit();
}
/**
* Implemented as part of ControlValueAccessor.
*/
writeValue(value: any): void {
// do not write if null or undefined
// tslint:disable-next-line
if (value != undefined) {
this.value = value;
}
}
registerOnChange(fn: any): void {
this.propagateChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
/**
* getEditorContent?: function
* Returns the content within the editor
*/
getValue(): Observable<string> {
if (this._componentInitialized) {
setTimeout(() => {
this._subject.next(this._value);
this._subject.complete();
this._subject = new Subject();
});
return this._subject.asObservable();
}
}
/**
* language?: string
* language used in editor
*/
@Input('language')
set language(language: string) {
this._language = language;
if (this._componentInitialized) {
this.applyLanguage();
}
}
get language(): string {
return this._language;
}
applyLanguage(): void {
if (this._language) {
monaco.editor.setModelLanguage(this._editor.getModel(), this._language);
this.editorLanguageChanged.emit();
}
}
/**
* registerLanguage?: function
* Registers a custom Language within the editor
*/
registerLanguage(language: any): void {
if (this._componentInitialized) {
for (const provider of language.completionItemProvider) {
/* tslint:disable-next-line */
provider.kind = eval(provider.kind);
}
for (const monarchTokens of language.monarchTokensProvider) {
/* tslint:disable-next-line */
monarchTokens[0] = eval(monarchTokens[0]);
}
monaco.languages.register({ id: language.id });
monaco.languages.setMonarchTokensProvider(language.id, {
tokenizer: {
root: language.monarchTokensProvider,
},
});
// Define a new theme that constains only rules that match this language
monaco.editor.defineTheme(language.customTheme.id, language.customTheme.theme);
this._theme = language.customTheme.id;
monaco.languages.registerCompletionItemProvider(language.id, {
provideCompletionItems: () => {
return language.completionItemProvider;
},
});
const css: HTMLStyleElement = document.createElement('style');
css.type = 'text/css';
css.innerHTML = language.monarchTokensProviderCSS;
document.body.appendChild(css);
this.editorConfigurationChanged.emit();
this._registeredLanguagesStyles = [...this._registeredLanguagesStyles, css];
}
}
/**
* style?: string
* css style of the editor on the page
*/
@Input('editorStyle')
set editorStyle(editorStyle: string) {
this._editorStyle = editorStyle;
if (this._componentInitialized) {
this.applyStyle();
}
}
get editorStyle(): string {
return this._editorStyle;
}
applyStyle(): void {
if (this._editorStyle) {
const containerDiv: HTMLDivElement = this._editorContainer.nativeElement;
containerDiv.setAttribute('style', this._editorStyle);
}
}
/**
* theme?: string
* Theme to be applied to editor
*/
@Input('theme')
set theme(theme: string) {
this._theme = theme;
if (this._componentInitialized) {
this._editor.updateOptions({ theme });
this.editorConfigurationChanged.emit();
}
}
get theme(): string {
return this._theme;
}
/**
* fullScreenKeyBinding?: number
* See here for key bindings https://microsoft.github.io/monaco-editor/api/enums/monaco.keycode.html
* Sets the KeyCode for shortcutting to Fullscreen mode
*/
@Input('fullScreenKeyBinding')
set fullScreenKeyBinding(keycode: number[]) {
this._keycode = keycode;
}
get fullScreenKeyBinding(): number[] {
return this._keycode;
}
/**
* editorOptions?: object
* Options used on editor instantiation. Available options listed here:
* https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.ieditoroptions.html
*/
@Input('editorOptions')
set editorOptions(editorOptions: any) {
this._editorOptions = editorOptions;
if (this._componentInitialized) {
this._editor.updateOptions(editorOptions);
this.editorConfigurationChanged.emit();
}
}
get editorOptions(): any {
return this._editorOptions;
}
/**
* layout method that calls layout method of editor and instructs the editor to remeasure its container
*/
layout(): void {
if (this._componentInitialized) {
this._editor.layout();
}
}
/**
* Returns if in Full Screen Mode or not
*/
get isFullScreen(): boolean {
return this._isFullScreen;
}
// tslint:disable-next-line:member-ordering
constructor(private zone: NgZone, private _changeDetectorRef: ChangeDetectorRef, private _elementRef: ElementRef) {}
ngOnInit(): void {
const containerDiv: HTMLDivElement = this._editorContainer.nativeElement;
containerDiv.id = this._editorInnerContainer;
this._editor = monaco.editor.create(
containerDiv,
Object.assign(
{
value: this._value,
language: this.language,
theme: this._theme,
},
this.editorOptions,
),
);
this._componentInitialized = true;
setTimeout(() => {
this.applyLanguage();
this._fromEditor = true;
this.applyValue();
this.applyStyle();
this.editorInitialized.emit(this._editor);
this.editorConfigurationChanged.emit();
});
this._editor.getModel().onDidChangeContent((e: any) => {
this._fromEditor = true;
this.writeValue(this._editor.getValue());
this.layout();
});
this.addFullScreenModeCommand();
merge(
fromEvent(window, 'resize').pipe(debounceTime(100)),
this._widthSubject.asObservable().pipe(distinctUntilChanged()),
this._heightSubject.asObservable().pipe(distinctUntilChanged()),
)
.pipe(takeUntil(this._destroy), debounceTime(100))
.subscribe(() => {
this.layout();
this._changeDetectorRef.markForCheck();
});
timer(500, 250)
.pipe(takeUntil(this._destroy))
.subscribe(() => {
if (this._elementRef && this._elementRef.nativeElement) {
this._widthSubject.next((<HTMLElement>this._elementRef.nativeElement).getBoundingClientRect().width);
this._heightSubject.next((<HTMLElement>this._elementRef.nativeElement).getBoundingClientRect().height);
}
});
}
ngOnDestroy(): void {
this._changeDetectorRef.detach();
this._registeredLanguagesStyles.forEach((style: HTMLStyleElement) => style.remove());
if (this._editor) {
this._editor.dispose();
}
this._destroy.next(true);
this._destroy.unsubscribe();
}
/**
* showFullScreenEditor request for full screen of Code Editor based on its browser type.
*/
public showFullScreenEditor(): void {
if (this._componentInitialized) {
const codeEditorElement: HTMLDivElement = this._editorContainer.nativeElement as HTMLDivElement;
const fullScreenMap: object = {
// Chrome
requestFullscreen: () => codeEditorElement.requestFullscreen(),
// Safari
webkitRequestFullscreen: () => (<any>codeEditorElement).webkitRequestFullscreen(),
// IE
msRequestFullscreen: () => (<any>codeEditorElement).msRequestFullscreen(),
// Firefox
mozRequestFullScreen: () => (<any>codeEditorElement).mozRequestFullScreen(),
};
for (const handler of Object.keys(fullScreenMap)) {
if (codeEditorElement[handler]) {
fullScreenMap[handler]();
}
}
}
this._isFullScreen = true;
}
/**
* exitFullScreenEditor request to exit full screen of Code Editor based on its browser type.
*/
public exitFullScreenEditor(): void {
if (this._componentInitialized) {
const exitFullScreenMap: object = {
// Chrome
exitFullscreen: () => document.exitFullscreen(),
// Safari
webkitExitFullscreen: () => (<any>document).webkitExitFullscreen(),
// Firefox
mozCancelFullScreen: () => (<any>document).mozCancelFullScreen(),
// IE
msExitFullscreen: () => (<any>document).msExitFullscreen(),
};
for (const handler of Object.keys(exitFullScreenMap)) {
if (document[handler]) {
exitFullScreenMap[handler]();
}
}
}
this._isFullScreen = false;
}
/**
* addFullScreenModeCommand used to add the fullscreen option to the context menu
*/
private addFullScreenModeCommand(): void {
this._editor.addAction({
// An unique identifier of the contributed action.
id: 'fullScreen',
// A label of the action that will be presented to the user.
label: 'Full Screen',
// An optional array of keybindings for the action.
contextMenuGroupId: 'navigation',
keybindings: this._keycode,
contextMenuOrder: 1.5,
// Method that will be executed when the action is triggered.
// @param editor The editor instance is passed in as a convinience
run: (ed: any) => {
this.showFullScreenEditor();
},
});
}
} | the_stack |
module WinJSTests {
"use strict";
var list,
proxy,
first,
second,
focused,
invoked,
currentMode,
layoutToDataIndex,
Key = WinJS.Utilities.Key;
var ListView = <typeof WinJS.UI.PrivateListView> WinJS.UI.ListView;
var callbacks = [];
var oldRequestAnimationFrame;
var oldHasWinRT;
var _oldMaxTimePerCreateContainers;
var defaultPrevented;
function mockRequestAnimationFrame() {
window.requestAnimationFrame = function (callback) {
callbacks.push(callback);
return 0;
};
}
function forceRequestAnimationFrames() {
while (callbacks.length) {
callbacks.shift()();
}
}
function createKeyEvent(element, key, preventDefaultHandler?, stopPropagationHandler?, altKey?, ctrlKey?, shiftKey?) {
return {
keyCode: key,
target: element,
altKey: altKey,
ctrlKey: ctrlKey,
shiftKey: shiftKey,
stopPropagation: function () {
if (stopPropagationHandler) {
stopPropagationHandler();
}
},
preventDefault: function () {
if (preventDefaultHandler) {
preventDefaultHandler();
}
}
};
}
function isEmptyArray(array) {
LiveUnit.Assert.areEqual(array.length, 0);
}
function eventOnElement(element) {
var rect = element.getBoundingClientRect();
// Simulate clicking the middle of the element
return {
target: element,
clientX: (rect.left + rect.right) / 2,
clientY: (rect.top + rect.bottom) / 2,
defaultPrevented: false,
preventDefault: function () {
this.defaultPrevented = true;
}
};
}
function createModeForTabTests(element) {
var mode = new WinJS.UI._SelectionMode({
_element: element,
_isZombie: function () { return true; },
_selection: {
_getFocused: function () {
return mode._focused;
}
},
_changeFocus: function (entity) {
mode._focused = entity;
if (entity.type === WinJS.UI.ObjectType.item) {
mode.site._groupFocusCache.updateCache("" + Math.floor(entity.index / 10), "" + entity.index, entity.index);
}
mode.site.focus();
},
_groups: {
groupFromItem: function (index) {
return Math.floor(index / 10);
},
group: function (index) {
return {
key: "" + index
};
},
fromKey: function (key) {
return {
group: {
startIndex: +key * 10
}
};
},
length: function () {
return 100;
},
},
_lastFocusedElementInGroupTrack: { type: WinJS.UI.ObjectType.item, index: -1 },
_rtl: function () {
return false;
},
_supportsGroupHeaderKeyboarding: true
});
mode.site._groupFocusCache = new WinJS.UI._GroupFocusCache(mode.site);
mode.site.focus = function () {
mode.site._hasKeyboardFocus = true;
};
mode.site.unfocus = function () {
mode.site._hasKeyboardFocus = false;
};
mode.site._changeFocus({ type: WinJS.UI.ObjectType.item, index: 0 });
return mode;
}
function createMode() {
var mode = new WinJS.UI._SelectionMode({
_groups: new WinJS.UI._NoGroups(this),
_versionManager: new WinJS.UI._VersionManager(),
_element: list,
_viewport: list,
_canvas: list,
_canvasProxy: proxy,
_cachedCount: 10,
_isZombie: function () { return true; },
_selection: {
focused: { type: WinJS.UI.ObjectType.item, index: 0 },
clear: function () {
},
set: function () {
},
_isIncluded: function () {
return false;
},
_getFocused: function () {
return focused;
},
_setFocused: function (f) {
focused = f;
},
getRanges: function () {
return [];
}
},
_options: {},
keyboardFocusedItem: { type: WinJS.UI.ObjectType.item, index: 0 },
_lastFocusedElementInGroupTrack: { type: WinJS.UI.ObjectType.item, index: -1 },
_unsetFocusOnItem: function () {
this.keyboardFocusedItem = -1;
},
_setFocusOnItem: function (item) {
this.keyboardFocusedItem = item;
},
scrollPosition: 0,
_getViewportLength: function () {
return 350;
},
_setupTabOrder: function () {
},
addEventListener: function () {
},
removeEventListener: function () {
},
ensureVisible: function () {
},
_rtl: function () {
return false;
},
_view: {
getAdjacent: function (oldFocus, direction) {
return mode.site._layout.getKeyboardNavigatedItem(oldFocus, null, direction);
},
items: {
_itemFrom: function (element) {
while (element && element !== first && element !== second) {
element = element.parentNode;
}
return element;
},
index: function (element) {
switch (this._itemFrom(element)) {
case first:
return 0;
case second:
return 1;
}
},
itemDataAt: function (index) {
var element = index ? second : first;
return {
element: element,
container: element,
itemBox: element
};
},
itemAt: function (index) {
return this.itemDataAt(index).element;
},
containerAt: function (index) {
return this.itemDataAt(index).container;
},
itemBoxAt: function (index) {
return this.itemDataAt(index).itemBox;
}
},
lastItemIndex: function () {
return 8;
}
},
_changeFocus: function (newFocus) {
focused = newFocus;
this.keyboardFocusedItem = newFocus;
},
_selectOnTap: function () {
return false;
},
_selectionAllowed: function () {
return false;
},
_selectFocused: function () {
return false;
},
_renderSelection: function () {
},
_getItemPosition: function (index) {
return {
then: function (callback) {
callback({
left: 0,
top: 0,
contentWidth: 100,
contentHeight: 100
});
}
};
},
_getItemOffset: function (index) {
return {
then: function (callback) {
callback({
begin: 0,
end: 100
});
}
};
},
_convertFromCanvasCoordinates: function (range) {
return range;
},
_batchViewUpdates: function (stage, priority, functor) {
functor();
},
_groupsEnabled: function () {
return false;
}
});
mode._fireInvokeEvent = function (entity) {
invoked = entity;
};
return mode;
}
// As a side effect, this will scroll the browser to make the element visible
function createPointerUpEvent(element) {
element.scrollIntoView(false);
var rect = element.getBoundingClientRect();
// Simulate clicking the middle of the element
return {
target: element,
clientX: (rect.left + rect.right) / 2,
clientY: (rect.top + rect.bottom) / 2,
defaultPrevented: false,
preventDefault: function () {
this.defaultPrevented = true;
},
button: undefined
};
}
export class BrowseModeTests {
// This is the setup function that will be called at the beginning of each test function.
setUp() {
LiveUnit.LoggingCore.logComment("In setup");
var newNode = document.createElement("div");
newNode.id = "BrowseModeTests";
newNode.innerHTML =
"<div id='list' style='width:350px; height:400px'></div>" +
"<div id='proxy'>" +
"<div id='first'>" +
"<div>Label</div>" +
"</div>" +
"<div id='second'>" +
"<div>Label</div>" +
"</div>" +
"</div>";
document.body.appendChild(newNode);
list = document.getElementById("list");
proxy = document.getElementById("proxy");
first = document.getElementById("first");
second = document.getElementById("second");
proxy.setPointerCapture = function () { };
proxy.releasePointerCapture = function () { };
list.setPointerCapture = function () { };
list.releasePointerCapture = function () { };
callbacks = [];
oldRequestAnimationFrame = window.requestAnimationFrame;
oldHasWinRT = WinJS.Utilities.hasWinRT;
WinJS.Utilities._setHasWinRT(false);
focused = { type: WinJS.UI.ObjectType.item, index: 0 };
invoked = { type: WinJS.UI.ObjectType.item, index: WinJS.UI._INVALID_INDEX };
currentMode = null;
layoutToDataIndex = [];
defaultPrevented = false;
//WinBlue: 298587
_oldMaxTimePerCreateContainers = WinJS.UI._VirtualizeContentsView._maxTimePerCreateContainers;
WinJS.UI._VirtualizeContentsView._maxTimePerCreateContainers = Number.MAX_VALUE;
}
tearDown() {
LiveUnit.LoggingCore.logComment("In tearDown");
WinJS.UI._VirtualizeContentsView._maxTimePerCreateContainers = _oldMaxTimePerCreateContainers;
window.requestAnimationFrame = oldRequestAnimationFrame;
WinJS.Utilities._setHasWinRT(oldHasWinRT);
var element = document.getElementById("BrowseModeTests");
document.body.removeChild(element);
}
// Test methods
// Any child objects that start with "test" are automatically test methods
testSimpleClick = function (complete) {
LiveUnit.LoggingCore.logComment("In testSimpleClick");
mockRequestAnimationFrame();
var browseMode = createMode();
invoked = { type: WinJS.UI.ObjectType.item, index: WinJS.UI._INVALID_INDEX };
LiveUnit.Assert.isTrue(!WinJS.Utilities.hasClass(first, WinJS.UI._pressedClass));
browseMode.onPointerDown({ target: first, button: WinJS.UI._LEFT_MSPOINTER_BUTTON, preventDefault: function () { } });
forceRequestAnimationFrames();
LiveUnit.Assert.isTrue(WinJS.Utilities.hasClass(first, WinJS.UI._pressedClass));
browseMode.onPointerUp(createPointerUpEvent(first));
browseMode.onclick();
WinJS.Utilities._setImmediate(function () {
LiveUnit.Assert.areEqual(0, invoked.index);
LiveUnit.Assert.isTrue(!WinJS.Utilities.hasClass(first, WinJS.UI._pressedClass));
complete();
});
};
testInvokeEvent = function (complete) {
var items = [];
for (var i = 0; i < 100; ++i) {
items[i] = { title: "Tile" + i };
}
var listView = new ListView(list, {
itemDataSource: new WinJS.Binding.List(items).dataSource
});
Helper.ListView.waitForReady(listView, -1)().then(function () {
var gotItemInvokedEvent = false;
listView.addEventListener("iteminvoked", function () {
gotItemInvokedEvent = true;
});
listView.tapBehavior = WinJS.UI.TapBehavior.none;
listView.selectionMode = WinJS.UI.SelectionMode.none;
var firstItem = listView.elementFromIndex(0);
listView._mode.onKeyDown(createKeyEvent(firstItem, Key.enter));
LiveUnit.Assert.isFalse(gotItemInvokedEvent);
listView.tapBehavior = WinJS.UI.TapBehavior.invokeOnly;
listView._mode.onKeyDown(createKeyEvent(firstItem, Key.enter));
LiveUnit.Assert.isTrue(gotItemInvokedEvent);
gotItemInvokedEvent = false;
listView.tapBehavior = WinJS.UI.TapBehavior.toggleSelect;
listView.selectionMode = WinJS.UI.SelectionMode.single;
listView._mode.onKeyDown(createKeyEvent(firstItem, Key.enter));
LiveUnit.Assert.isTrue(gotItemInvokedEvent);
gotItemInvokedEvent = false;
listView.selectionMode = WinJS.UI.SelectionMode.multi;
listView._mode.onKeyDown(createKeyEvent(firstItem, Key.enter));
LiveUnit.Assert.isFalse(gotItemInvokedEvent);
complete();
});
};
// Verify that right-click doesn't trigger the pressed visual when selection is disabled
testRightClickDisabled = function (complete) {
LiveUnit.LoggingCore.logComment("In testRightClickDisabled");
mockRequestAnimationFrame();
var browseMode = createMode();
browseMode.site._selectionMode = "none";
LiveUnit.Assert.isFalse(WinJS.Utilities.hasClass(first, WinJS.UI._pressedClass));
browseMode.onPointerDown({ target: first, button: WinJS.UI._RIGHT_MSPOINTER_BUTTON, preventDefault: function () { } });
forceRequestAnimationFrames();
LiveUnit.Assert.isFalse(WinJS.Utilities.hasClass(first, WinJS.UI._pressedClass));
browseMode.onPointerUp(createPointerUpEvent(first));
browseMode.onclick();
WinJS.Utilities._setImmediate(function () {
LiveUnit.Assert.isFalse(WinJS.Utilities.hasClass(first, WinJS.UI._pressedClass));
complete();
});
};
testDownMoveUp = function (complete) {
LiveUnit.LoggingCore.logComment("In testDownMoveUp");
mockRequestAnimationFrame();
var browseMode = createMode();
invoked = { type: WinJS.UI.ObjectType.item, index: WinJS.UI._INVALID_INDEX };
LiveUnit.Assert.isTrue(!WinJS.Utilities.hasClass(first, WinJS.UI._pressedClass));
LiveUnit.Assert.isTrue(!WinJS.Utilities.hasClass(second, WinJS.UI._pressedClass));
browseMode.onPointerDown({ target: first, button: WinJS.UI._LEFT_MSPOINTER_BUTTON, preventDefault: function () { } });
forceRequestAnimationFrames();
LiveUnit.Assert.isTrue(WinJS.Utilities.hasClass(first, WinJS.UI._pressedClass));
LiveUnit.Assert.areEqual(WinJS.UI._INVALID_INDEX, invoked.index);
browseMode.onPointerUp(createPointerUpEvent(second));
browseMode.onclick();
WinJS.Utilities._setImmediate(function () {
LiveUnit.Assert.isTrue(!WinJS.Utilities.hasClass(first, WinJS.UI._pressedClass));
LiveUnit.Assert.isTrue(!WinJS.Utilities.hasClass(second, WinJS.UI._pressedClass));
complete();
});
};
testMoveUp = function () {
LiveUnit.LoggingCore.logComment("In testMoveUp");
var browseMode = createMode();
invoked = { type: WinJS.UI.ObjectType.item, index: WinJS.UI._INVALID_INDEX };
LiveUnit.Assert.isTrue(!WinJS.Utilities.hasClass(first, WinJS.UI._pressedClass));
LiveUnit.Assert.isTrue(!WinJS.Utilities.hasClass(second, WinJS.UI._pressedClass));
LiveUnit.Assert.isTrue(!WinJS.Utilities.hasClass(first, WinJS.UI._pressedClass));
LiveUnit.Assert.isTrue(!WinJS.Utilities.hasClass(second, WinJS.UI._pressedClass));
LiveUnit.Assert.areEqual(WinJS.UI._INVALID_INDEX, invoked.index);
browseMode.onPointerUp(createPointerUpEvent(second));
browseMode.onclick();
LiveUnit.Assert.areEqual(WinJS.UI._INVALID_INDEX, invoked.index);
LiveUnit.Assert.isTrue(!WinJS.Utilities.hasClass(first, WinJS.UI._pressedClass));
LiveUnit.Assert.isTrue(!WinJS.Utilities.hasClass(second, WinJS.UI._pressedClass));
};
testDownMoveBackUp = function (complete) {
LiveUnit.LoggingCore.logComment("In testDownMoveBackUp");
mockRequestAnimationFrame();
var browseMode = createMode();
invoked = { type: WinJS.UI.ObjectType.item, index: WinJS.UI._INVALID_INDEX };
LiveUnit.Assert.isTrue(!WinJS.Utilities.hasClass(first, WinJS.UI._pressedClass));
LiveUnit.Assert.isTrue(!WinJS.Utilities.hasClass(second, WinJS.UI._pressedClass));
browseMode.onPointerDown({ target: first, button: WinJS.UI._LEFT_MSPOINTER_BUTTON, preventDefault: function () { } });
forceRequestAnimationFrames();
LiveUnit.Assert.isTrue(WinJS.Utilities.hasClass(first, WinJS.UI._pressedClass));
LiveUnit.Assert.areEqual(WinJS.UI._INVALID_INDEX, invoked.index);
LiveUnit.Assert.isTrue(WinJS.Utilities.hasClass(first, WinJS.UI._pressedClass));
LiveUnit.Assert.isTrue(!WinJS.Utilities.hasClass(second, WinJS.UI._pressedClass));
LiveUnit.Assert.areEqual(WinJS.UI._INVALID_INDEX, invoked.index);
browseMode.onPointerUp(createPointerUpEvent(first));
browseMode.onclick();
WinJS.Utilities._setImmediate(function () {
LiveUnit.Assert.areEqual(0, invoked.index);
LiveUnit.Assert.isTrue(!WinJS.Utilities.hasClass(first, WinJS.UI._pressedClass));
LiveUnit.Assert.isTrue(!WinJS.Utilities.hasClass(second, WinJS.UI._pressedClass));
complete();
});
};
testKeyboard = function () {
var Key = WinJS.Utilities.Key;
var browseMode = createMode();
// We're pretending to be a 3x3 horizontal grid here
browseMode.site._layout = {
getKeyboardNavigatedItem: function (entity, element, keyPressed) {
if (keyPressed === WinJS.Utilities.Key.upArrow) {
return WinJS.Promise.wrap({ type: WinJS.UI.ObjectType.item, index: entity.index - 1 });
} else if (keyPressed === WinJS.Utilities.Key.downArrow) {
return WinJS.Promise.wrap({ type: WinJS.UI.ObjectType.item, index: entity.index + 1 });
} else if (keyPressed === WinJS.Utilities.Key.leftArrow) {
return WinJS.Promise.wrap({ type: WinJS.UI.ObjectType.item, index: entity.index - 3 });
} else if (keyPressed === WinJS.Utilities.Key.rightArrow) {
return WinJS.Promise.wrap({ type: WinJS.UI.ObjectType.item, index: entity.index + 3 });
} else if (keyPressed === WinJS.Utilities.Key.pageUp) {
return WinJS.Promise.wrap({ type: WinJS.UI.ObjectType.item, index: 0 });
} else if (keyPressed === WinJS.Utilities.Key.pageDown) {
return WinJS.Promise.wrap({ type: WinJS.UI.ObjectType.item, index: 8 });
}
}
};
var ensureVisibleCalled = false;
browseMode.site.ensureVisible = function (index) {
ensureVisibleCalled = true;
}
function createKeyEvent(key) {
return {
keyCode: key,
target: first,
stopPropagation: function () { },
preventDefault: function () { }
};
}
browseMode.onKeyDown(createKeyEvent(Key.upArrow));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 0);
browseMode.onKeyDown(createKeyEvent(Key.downArrow));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 1);
browseMode.onKeyDown(createKeyEvent(Key.downArrow));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 2);
browseMode.onKeyDown(createKeyEvent(Key.upArrow));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 1);
browseMode.onKeyDown(createKeyEvent(Key.leftArrow));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 1);
browseMode.onKeyDown(createKeyEvent(Key.rightArrow));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 4);
browseMode.onKeyDown(createKeyEvent(Key.downArrow));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 5);
browseMode.onKeyDown(createKeyEvent(Key.downArrow));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 6);
browseMode.onKeyDown(createKeyEvent(Key.downArrow));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 7);
browseMode.onKeyDown(createKeyEvent(Key.downArrow));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 8);
ensureVisibleCalled = false;
browseMode.onKeyDown(createKeyEvent(Key.downArrow));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 8);
browseMode.onKeyDown(createKeyEvent(Key.rightArrow));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 8);
browseMode.onKeyDown(createKeyEvent(Key.rightArrow));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 8);
browseMode.onKeyDown(createKeyEvent(Key.home));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 0);
ensureVisibleCalled = false;
browseMode.onKeyDown(createKeyEvent(Key.home));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 0);
browseMode.onKeyDown(createKeyEvent(Key.end));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 8);
ensureVisibleCalled = false;
browseMode.onKeyDown(createKeyEvent(Key.end));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 8);
browseMode.onKeyDown(createKeyEvent(Key.pageDown));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 8);
ensureVisibleCalled = false;
browseMode.onKeyDown(createKeyEvent(Key.pageDown));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 8);
browseMode.onKeyDown(createKeyEvent(Key.leftArrow));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 5);
browseMode.onKeyDown(createKeyEvent(Key.pageDown));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 8);
browseMode.onKeyDown(createKeyEvent(Key.pageUp));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 0);
invoked = { type: WinJS.UI.ObjectType.item, index: WinJS.UI._INVALID_INDEX };
browseMode.onKeyDown(createKeyEvent(Key.end));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 8);
browseMode.onKeyDown(createKeyEvent(Key.enter));
LiveUnit.Assert.areEqual(invoked.index, 8);
browseMode.onKeyDown(createKeyEvent(Key.home));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 0);
function onKeyboardNavigating_handler(event) {
if (event.detail.newFocus > 4) {
event.preventDefault();
}
}
document.body.addEventListener("keyboardnavigating", onKeyboardNavigating_handler);
browseMode.onKeyDown(createKeyEvent(Key.end));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 0);
browseMode.onKeyDown(createKeyEvent(Key.rightArrow));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 3);
browseMode.onKeyDown(createKeyEvent(Key.rightArrow));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 3);
browseMode.onKeyDown(createKeyEvent(Key.downArrow));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 4);
browseMode.onKeyDown(createKeyEvent(Key.downArrow));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 4);
browseMode.onKeyDown(createKeyEvent(Key.pageDown));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 4);
browseMode.onKeyDown(createKeyEvent(Key.pageUp));
LiveUnit.Assert.areEqual(browseMode.site.keyboardFocusedItem.index, 0);
document.body.removeEventListener("keyboardnavigating", onKeyboardNavigating_handler);
}
testInvocableHeaders = function (complete) {
var host = <HTMLElement>document.querySelector("#list");
host.style.position = "absolute"; //this test requires the element not to scroll
host.style.top = "0";
var data = [];
for (var i = 0; i < 10; i++) {
data.push({ data: i + "" });
}
var list = new WinJS.Binding.List(data);
var glist = list.createGrouped(function (item) {
return Math.floor(item.data / 2) + "";
}, function (item) {
return { data: Math.floor(item.data / 2) + "" };
});
var lv = new ListView(host);
lv.itemTemplate = lv.groupHeaderTemplate = function (itemPromise) {
return itemPromise.then(function (item) {
var div = document.createElement("div");
div.textContent = item.data.data;
div.style.width = "50px";
div.style.height = "50px";
div.style.backgroundColor = "red";
return div;
});
};
lv.itemDataSource = glist.dataSource;
lv.groupDataSource = glist.groups.dataSource;
var numInvokes = 0;
var gotEventFromOnEvent = 0;
lv.ongroupheaderinvoked = function (e) {
LiveUnit.Assert.areEqual(e.detail.groupHeaderIndex, 2);
if (++gotEventFromOnEvent === 2 && numInvokes === 2) {
complete();
}
};
lv.addEventListener("groupheaderinvoked", function (e) {
LiveUnit.Assert.areEqual(e.detail.groupHeaderIndex, 2);
if (++numInvokes === 2 && gotEventFromOnEvent === 2) {
complete();
}
});
lv.indexOfFirstVisible = 4; //ensure group 2 is visible on the screen
Helper.ListView.waitForReady(lv, -1)().then(function () {
var header = lv.element.querySelectorAll(".win-groupheader")[2];
lv._changeFocus({ type: WinJS.UI.ObjectType.groupHeader, index: 2 }, true, false, false, true);
lv._mode.onKeyDown({ target: header, keyCode: 13, stopPropagation: function () { }, preventDefault: function () { } });
var e = createPointerUpEvent(header);
e.button = WinJS.UI._LEFT_MSPOINTER_BUTTON;
lv._mode.onPointerDown(e);
lv._mode.onPointerUp(e);
});
};
testTabbingToHeaderFromChildElementDrawsFocusRect = function (complete) {
var data = [];
for (var i = 0; i < 20; i++) {
data.push({ data: i });
}
var list = new WinJS.Binding.List(data);
var glist = list.createGrouped(function (item) {
return Math.floor(item.data / 2) + "";
}, function (item) {
return { data: Math.floor(item.data / 2) + "" };
});
var lv = new ListView();
lv.layout['groupHeaderPosition'] = "left";
lv.itemDataSource = glist.dataSource;
lv.groupDataSource = glist.groups.dataSource;
lv.groupHeaderTemplate = function (itemPromise) {
return itemPromise.then(function (item) {
var div = document.createElement("div");
div.style.width = "200px";
div.style.height = "200px";
var innerDiv = document.createElement("div");
innerDiv.innerHTML = item.data.data;
var button = document.createElement("input");
button.classList.add("testHeaderButtonClass");
button.type = "button";
button.value = "button";
div.appendChild(innerDiv);
div.appendChild(button);
return div;
});
};
document.body.appendChild(lv.element);
var headerButton;
Helper.ListView.waitForReady(lv, -1)().then(function () {
headerButton = document.querySelector(".testHeaderButtonClass");
headerButton.focus();
return Helper.ListView.waitForReady(lv, -1)();
}).then(function () {
lv._keyboardFocusInbound = true;
headerButton.parentNode.focus();
return Helper.ListView.waitForReady(lv, -1)();
}).done(function () {
LiveUnit.Assert.isTrue(headerButton.parentNode.classList.contains(WinJS.UI._itemFocusClass));
document.body.removeChild(lv.element);
complete();
});
};
testPointerDownOnHeaderAndUpOnItemShouldNotInvoke = function (complete) {
var host = <HTMLElement>document.querySelector("#list");
host.style.position = "absolute"; //this test requires the element not to scroll
host.style.top = "0";
var data = [];
for (var i = 0; i < 10; i++) {
data.push({ data: i + "" });
}
var list = new WinJS.Binding.List(data);
var glist = list.createGrouped(function (item) {
return Math.floor(item.data / 2) + "";
}, function (item) {
return { data: Math.floor(item.data / 2) + "" };
});
var lv = new ListView(host);
lv.itemTemplate = lv.groupHeaderTemplate = function (itemPromise) {
return itemPromise.then(function (item) {
var div = document.createElement("div");
div.textContent = item.data.data;
div.style.width = "50px";
div.style.height = "50px";
div.style.backgroundColor = "red";
return div;
});
};
lv.itemDataSource = glist.dataSource;
lv.groupDataSource = glist.groups.dataSource;
lv.addEventListener("groupheaderinvoked", function (e) {
LiveUnit.Assert.fail("group header should not be invoked");
});
lv.indexOfFirstVisible = 4; //ensure group 2 is visible on the screen
Helper.ListView.waitForReady(lv, -1)().then(function () {
var header = lv.element.querySelector(".win-groupheader");
var item = lv.element.querySelector(".win-item");
var e = createPointerUpEvent(header);
e.button = WinJS.UI._LEFT_MSPOINTER_BUTTON;
lv._mode.onPointerDown(e);
e = createPointerUpEvent(item);
e.button = WinJS.UI._LEFT_MSPOINTER_BUTTON;
lv._mode.onPointerUp(e);
return Helper.ListView.waitForReady(lv, -1)();
}).done(function () {
complete();
});
};
testOnTabExiting = function () {
// This test mode mimics a ListView with infinite number of groups,
// where each group has 10 items: group0 has items 0-9, group1 has items 10-19, etc
var prevent = false;
var element = document.createElement("div");
element.addEventListener("keyboardnavigating", function (e) {
if (prevent) {
e.preventDefault();
}
});
var mode = createModeForTabTests(element);
mode.site._changeFocus({ type: WinJS.UI.ObjectType.item, index: 11 });
// Tab forward from item11, but prevent navigation
prevent = true;
mode.onTabExiting({ detail: 1, preventDefault: function () { } });
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.item, mode.site._selection._getFocused().type);
LiveUnit.Assert.areEqual(11, mode.site._selection._getFocused().index);
prevent = false;
// Tab forward from item11, should go to group1
mode.onTabExiting({ detail: 1, preventDefault: function () { } });
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.groupHeader, mode.site._selection._getFocused().type);
LiveUnit.Assert.areEqual(1, mode.site._selection._getFocused().index);
// Tab backwards from group1, but prevent navigation
prevent = true;
mode.onTabExiting({ detail: 0, preventDefault: function () { } });
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.groupHeader, mode.site._selection._getFocused().type);
LiveUnit.Assert.areEqual(1, mode.site._selection._getFocused().index);
prevent = false;
// Tab backwards from group1, should go to item11
mode.onTabExiting({ detail: 0, preventDefault: function () { } });
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.item, mode.site._selection._getFocused().type);
LiveUnit.Assert.areEqual(11, mode.site._selection._getFocused().index);
// Tab backwards from item11, leaving listView, should not change our internal focus state
mode.onTabExiting({ detail: 0, preventDefault: function () { } });
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.item, mode.site._selection._getFocused().type);
LiveUnit.Assert.areEqual(11, mode.site._selection._getFocused().index);
// Tab forward from group1, leaving listView, should not change our internal focus state
mode.site._changeFocus({ type: WinJS.UI.ObjectType.groupHeader, index: 1 });
mode.onTabExiting({ detail: 1, preventDefault: function () { } });
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.groupHeader, mode.site._selection._getFocused().type);
LiveUnit.Assert.areEqual(1, mode.site._selection._getFocused().index);
};
testOnTabEntered = function () {
// This test mode mimics a ListView with infinite number of groups,
// where each group has 10 items: group0 has items 0-9, group1 has items 10-19, etc
var fireCount = 0;
var element = document.createElement("div");
element.addEventListener("keyboardnavigating", function (e) {
fireCount++;
});
var mode = createModeForTabTests(element);
mode.site._changeFocus({ type: WinJS.UI.ObjectType.item, index: 11 });
mode.site.unfocus();
// Tab forward into the listView, focus should go to item11
var curFireCount = fireCount;
mode.onTabEntered({ detail: 1, preventDefault: function () { } });
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.item, mode.site._selection._getFocused().type);
LiveUnit.Assert.areEqual(11, mode.site._selection._getFocused().index);
LiveUnit.Assert.areEqual(curFireCount, fireCount);
mode.site._changeFocus({ type: WinJS.UI.ObjectType.groupHeader, index: 1 });
mode.site.unfocus();
// Tab forward into the listView, focus should go to item11
// even though the last focused entity was a header
curFireCount = fireCount;
mode.onTabEntered({ detail: 1, preventDefault: function () { } });
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.item, mode.site._selection._getFocused().type);
LiveUnit.Assert.areEqual(11, mode.site._selection._getFocused().index);
LiveUnit.Assert.areEqual(curFireCount + 1, fireCount);
mode.site._changeFocus({ type: WinJS.UI.ObjectType.groupHeader, index: 1 });
mode.site.unfocus();
// Tab backwards into the listView, focus should go to header1
curFireCount = fireCount;
mode.onTabEntered({ detail: 0, preventDefault: function () { } });
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.groupHeader, mode.site._selection._getFocused().type);
LiveUnit.Assert.areEqual(1, mode.site._selection._getFocused().index);
LiveUnit.Assert.areEqual(curFireCount, fireCount);
mode.site._changeFocus({ type: WinJS.UI.ObjectType.item, index: 11 });
mode.site.unfocus();
// Tab backwards into the listView, focus should go to header1
// even though the last focused entity was an item
curFireCount = fireCount;
mode.onTabEntered({ detail: 0, preventDefault: function () { } });
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.groupHeader, mode.site._selection._getFocused().type);
LiveUnit.Assert.areEqual(1, mode.site._selection._getFocused().index);
LiveUnit.Assert.areEqual(curFireCount + 1, fireCount);
};
testResetPointerStateAfterPressingEnterOnHeader = function (complete) {
Helper.initUnhandledErrors();
var data = [];
for (var i = 0; i < 10; i++) {
data.push({ data: i + "" });
}
var list = new WinJS.Binding.List(data);
var glist = list.createGrouped(function (item) {
return Math.floor(item.data / 2) + "";
}, function (item) {
return { data: Math.floor(item.data / 2) + "" };
});
var lv = new ListView(<HTMLElement>document.querySelector("#list"));
lv.itemDataSource = glist.dataSource;
lv.groupDataSource = glist.groups.dataSource;
Helper.ListView.waitForReady(lv, -1)().
then(function () {
lv.currentItem = { type: WinJS.UI.ObjectType.groupHeader, index: 0 };
lv._mode.onKeyDown(createKeyEvent(document.querySelector(".win-groupheader"), Key.enter));
lv._mode._itemEventsHandler.resetPointerDownState();
return Helper.ListView.waitForReady(lv, -1)();
}).
then(Helper.validateUnhandledErrorsOnIdle).
done(complete);
};
testKeyboardingBeforeTreeCreated = function (complete) {
Helper.initUnhandledErrors();
var placeholder = document.createElement("div");
placeholder.style.width = "300px";
placeholder.style.height = "300px";
document.body.appendChild(placeholder);
var items = [];
for (var i = 0; i < 100; ++i) {
items[i] = { title: "Tile" + i };
}
var list = new WinJS.Binding.List(items);
var layout = {
initialize: function (site, groups) {
}
};
var layouSignal = new WinJS._Signal();
Object.defineProperty(layout, "numberOfItemsPerItemsBlock", {
get: function () {
return layouSignal.promise;
}
});
var listView = new ListView(placeholder, {
itemDataSource: list.dataSource,
layout: layout
});
listView._mode.onKeyDown(createKeyEvent(listView._canvas, Key.end));
listView._mode.onKeyDown(createKeyEvent(listView._canvas, Key.home));
listView._mode.onKeyDown(createKeyEvent(listView._canvas, Key.leftArrow));
listView._mode.onKeyDown(createKeyEvent(listView._canvas, Key.rightArrow));
listView._mode.onKeyDown(createKeyEvent(listView._canvas, Key.upArrow));
listView._mode.onKeyDown(createKeyEvent(listView._canvas, Key.downArrow));
listView._mode.onKeyDown(createKeyEvent(listView._canvas, Key.pageUp));
listView._mode.onKeyDown(createKeyEvent(listView._canvas, Key.pageDown));
listView._mode.onKeyDown(createKeyEvent(listView._canvas, Key.enter));
layouSignal.complete(10);
Helper.ListView.waitForReady(listView)().
then(Helper.validateUnhandledErrorsOnIdle).
done(function () {
document.body.removeChild(placeholder);
complete();
});
};
testKeyboardReorderStopsPropagationOnArrowKeyUp = function (complete) {
if (!WinJS.Utilities.isPhone) {
return complete();
}
var placeholder = document.createElement("div");
placeholder.style.width = "300px";
placeholder.style.height = "300px";
document.body.appendChild(placeholder);
var items = [];
for (var i = 0; i < 100; ++i) {
items[i] = { title: "Tile" + i };
}
var list = new WinJS.Binding.List(items);
var listView = new ListView(placeholder, {
itemDataSource: list.dataSource,
itemsReorderable: true
});
var count = 0;
function incCount() {
count++;
}
Helper.ListView.waitForReady(listView, -1)().done(function () {
listView._mode.onKeyDown(createKeyEvent(listView._canvas, Key.alt));
listView._mode.onKeyDown(createKeyEvent(listView._canvas, Key.shift, null, null, true));
listView._mode.onKeyDown(createKeyEvent(listView._canvas, Key.leftArrow, null, null, true, false, true));
listView._mode.onKeyUp(createKeyEvent(listView._canvas, Key.leftArrow, incCount, incCount, true, false, true));
LiveUnit.Assert.areEqual(2, count);
listView.dispose();
document.body.removeChild(placeholder);
complete();
});
};
testKeyboardReorderStopsPropagationOnShiftThenArrowKeyUp = function (complete) {
if (!WinJS.Utilities.isPhone) {
return complete();
}
var placeholder = document.createElement("div");
placeholder.style.width = "300px";
placeholder.style.height = "300px";
document.body.appendChild(placeholder);
var items = [];
for (var i = 0; i < 100; ++i) {
items[i] = { title: "Tile" + i };
}
var list = new WinJS.Binding.List(items);
var listView = new ListView(placeholder, {
itemDataSource: list.dataSource,
itemsReorderable: true
});
var count = 0;
function incCount() {
count++;
}
Helper.ListView.waitForReady(listView, -1)().done(function () {
listView._mode.onKeyDown(createKeyEvent(listView._canvas, Key.alt));
listView._mode.onKeyDown(createKeyEvent(listView._canvas, Key.shift, null, null, true));
listView._mode.onKeyDown(createKeyEvent(listView._canvas, Key.leftArrow, null, null, true, false, true));
listView._mode.onKeyUp(createKeyEvent(listView._canvas, Key.shift, null, null, true));
listView._mode.onKeyUp(createKeyEvent(listView._canvas, Key.leftArrow, incCount, incCount, true));
LiveUnit.Assert.areEqual(2, count);
listView.dispose();
document.body.removeChild(placeholder);
complete();
});
};
};
function generateChangeDataSourceInInvoke(layoutName) {
BrowseModeTests.prototype["testChangeDataSourceInInvoke" + layoutName] = function (complete) {
var bindingList1 = new WinJS.Binding.List(["a", "b", "c", "d"]);
var listView = new ListView(list, {
itemDataSource: bindingList1.dataSource,
layout: new WinJS.UI[layoutName](),
itemTemplate: function (itemPromise) {
var element = document.createElement("div");
element.style.width = "100";
element.style.height = "100";
element.style.backgroundColor = "#777";
return {
element: element,
renderComplete: itemPromise.then(function (item) {
element.textContent = '' + item.data;
})
};
}
});
listView._canvas.setPointerCapture = function () { };
var tests = [function () {
var elements = list.querySelectorAll('.win-container');
LiveUnit.Assert.areEqual(4, elements.length);
// Click on the 4th item and then switch to a data source with 3 items
listView._currentMode().onPointerDown({ target: elements[3], button: WinJS.UI._LEFT_MSPOINTER_BUTTON, preventDefault: function () { } });
listView._currentMode().onPointerUp(createPointerUpEvent(elements[3]));
listView._currentMode().onclick();
}, function () {
var elements = list.querySelectorAll('.win-container');
LiveUnit.Assert.areEqual(3, elements.length);
// Press enter on the 3rd item and then switch to a data source with 2 items
listView._selection._setFocused({ type: WinJS.UI.ObjectType.item, index: 2 }, true);
listView._currentMode().onKeyDown({
target: elements[2],
preventDefault: function () { },
stopPropagation: function () { },
keyCode: WinJS.Utilities.Key.enter
});
}, function () {
var elements = list.querySelectorAll('.win-container');
LiveUnit.Assert.areEqual(2, elements.length);
complete();
}];
var i = 0;
listView.addEventListener('iteminvoked', function () {
if (i === 0) {
var bindingList2 = new WinJS.Binding.List(["x", "y", "z"]);
listView.itemDataSource = bindingList2.dataSource;
i++;
} else {
var bindingList2 = new WinJS.Binding.List(["first", "second"]);
listView.itemDataSource = bindingList2.dataSource;
}
});
Helper.ListView.runTests(listView, tests);
};
};
generateChangeDataSourceInInvoke("GridLayout");
function generateInvokeOnUnrealizedItem(layoutName) {
BrowseModeTests.prototype["testInvokeOnUnrealizedItem" + layoutName] = function (complete) {
var data = [];
for (var i = 0; i < 1000; i++) {
data.push("Item" + i);
}
var bindingList = new WinJS.Binding.List(data);
var listView = new ListView(list, {
itemDataSource: bindingList.dataSource,
layout: new WinJS.UI[layoutName](),
itemTemplate: function (itemPromise) {
var element = document.createElement("div");
element.style.width = "100px";
element.style.height = "100px";
return {
element: element,
renderComplete: itemPromise.then(function (item) {
element.textContent = item.data;
})
};
},
currentItem: {
index: 4,
hasFocus: true
}
});
listView._canvas.setPointerCapture = function () { };
var expectingInvokeEvent = false,
gotInvokeEvent = false,
targetElement = null;
listView.addEventListener('iteminvoked', function (e) {
LiveUnit.Assert.isTrue(expectingInvokeEvent);
gotInvokeEvent = true;
if (expectingInvokeEvent) {
expectingInvokeEvent = false;
}
});
Helper.ListView.waitForDeferredAction(listView)().then(function () {
targetElement = listView._tabManager.childFocus;
expectingInvokeEvent = true;
LiveUnit.Assert.areEqual("Item4", targetElement.textContent);
listView._currentMode().onKeyDown({
target: targetElement,
preventDefault: function () { },
stopPropagation: function () { },
keyCode: WinJS.Utilities.Key.enter
});
return WinJS.Promise.timeout();
}).then(function () {
LiveUnit.Assert.isTrue(targetElement === listView._tabManager.childFocus);
LiveUnit.Assert.isTrue(gotInvokeEvent);
gotInvokeEvent = false;
var scrollPos = WinJS.Utilities.getScrollPosition(listView._viewport);
scrollPos.scrollLeft += 5000;
WinJS.Utilities.setScrollPosition(listView._viewport, scrollPos);
return Helper.ListView.waitForDeferredAction(listView)();
}).then(function () {
LiveUnit.Assert.isFalse(listView.element.contains(targetElement));
LiveUnit.Assert.isTrue(targetElement !== listView._tabManager.childFocus);
listView._currentMode().onKeyDown({
target: targetElement,
preventDefault: function () { },
stopPropagation: function () { },
keyCode: WinJS.Utilities.Key.enter
});
// Give the test some time to see if it fires an invoke event on enter. It shouldn't fire an invoke event here.
setTimeout(function () {
LiveUnit.Assert.isFalse(gotInvokeEvent);
complete();
}, 500);
});
};
};
generateInvokeOnUnrealizedItem("GridLayout");
function generateEnsureVisibleNegative(layoutName) {
BrowseModeTests.prototype["testEnsureVisibleNegative" + layoutName] = function (complete) {
var data = [];
for (var i = 0; i < 1000; i++) {
data.push("Item" + i);
}
var bindingList = new WinJS.Binding.List(data);
var listView = new WinJS.UI.ListView(list, {
itemDataSource: bindingList.dataSource,
layout: new WinJS.UI[layoutName](),
});
Helper.initUnhandledErrors();
var range;
var promiseErrorsTimeout = setTimeout(function () {
Helper.validateUnhandledErrors();
}, 9900);
var ensureVisibleIndices = [999, -1];
Helper.ListView.waitForReady(listView, -1)().
then(function () {
listView.ensureVisible(ensureVisibleIndices[0]);
return Helper.ListView.waitForReady(listView, -1)();
}).
then(function () {
range = {
indexOfFirstVisible: listView.indexOfFirstVisible,
indexOfLastVisible: listView.indexOfLastVisible
};
LiveUnit.Assert.isTrue(ensureVisibleIndices[0] >= range.indexOfFirstVisible && ensureVisibleIndices[0] <= range.indexOfLastVisible);
listView.ensureVisible(ensureVisibleIndices[1]);
return Helper.ListView.waitForReady(listView, -1)();
}).
then(function () {
LiveUnit.Assert.areEqual(range.indexOfFirstVisible, listView.indexOfFirstVisible);
clearTimeout(promiseErrorsTimeout);
}).
then(Helper.validateUnhandledErrorsOnIdle).
done(complete);
};
};
generateEnsureVisibleNegative("GridLayout");
function generateEnsureVisibleEmpty(layoutName) {
BrowseModeTests.prototype["testEnsureVisibleEmpty" + layoutName] = function (complete) {
var data = [];
var bindingList = new WinJS.Binding.List(data);
var listView = new WinJS.UI.ListView(list, {
itemDataSource: bindingList.dataSource,
layout: new WinJS.UI[layoutName](),
});
Helper.initUnhandledErrors();
var range;
var promiseErrorsTimeout = setTimeout(function () {
Helper.validateUnhandledErrors();
}, 9900);
var ensureVisibleIndices = [999, -1];
Helper.ListView.waitForReady(listView, -1)().
then(function () {
listView.ensureVisible(ensureVisibleIndices[0]);
return WinJS.Promise.timeout(500);
}).
then(function () {
LiveUnit.Assert.areEqual(-1, listView.indexOfFirstVisible);
listView.ensureVisible(ensureVisibleIndices[1]);
return WinJS.Promise.timeout(500);
}).
then(function () {
LiveUnit.Assert.areEqual(-1, listView.indexOfFirstVisible);
clearTimeout(promiseErrorsTimeout);
}).
then(Helper.validateUnhandledErrorsOnIdle).
done(complete);
}
};
generateEnsureVisibleEmpty("GridLayout");
function generateIndexOfFirstVisibleNegative(layoutName) {
BrowseModeTests.prototype["testIndexOfFirstVisibleNegative" + layoutName] = function (complete) {
var data = [];
for (var i = 0; i < 1000; i++) {
data.push("Item" + i);
}
var bindingList = new WinJS.Binding.List(data);
var listView = new WinJS.UI.ListView(list, {
itemDataSource: bindingList.dataSource,
layout: new WinJS.UI[layoutName](),
});
Helper.initUnhandledErrors();
var range;
var promiseErrorsTimeout = setTimeout(function () {
Helper.validateUnhandledErrors();
}, 9900);
var indexOfFirstVisibleIndices = [999, -1];
Helper.ListView.waitForReady(listView, -1)().
then(function () {
listView.indexOfFirstVisible = indexOfFirstVisibleIndices[0];
return Helper.ListView.waitForReady(listView, -1)();
}).
then(function () {
range = {
indexOfFirstVisible: listView.indexOfFirstVisible,
indexOfLastVisible: listView.indexOfLastVisible
};
LiveUnit.Assert.isTrue(indexOfFirstVisibleIndices[0] >= range.indexOfFirstVisible && indexOfFirstVisibleIndices[0] <= range.indexOfLastVisible);
listView.indexOfFirstVisible = indexOfFirstVisibleIndices[1];
return Helper.ListView.waitForReady(listView, -1)();
}).
then(function () {
LiveUnit.Assert.areEqual(range.indexOfFirstVisible, listView.indexOfFirstVisible);
clearTimeout(promiseErrorsTimeout);
}).
then(Helper.validateUnhandledErrorsOnIdle).
done(complete);
};
};
generateIndexOfFirstVisibleNegative("GridLayout");
function generateEnsureVisibleScroll(layoutName) {
BrowseModeTests.prototype["testEnsureVisibleScroll" + layoutName] = function (complete) {
var data = [];
for (var i = 0; i < 1000; i++) {
data.push("Item" + i);
}
var bindingList = new WinJS.Binding.List(data);
var listView = new WinJS.UI.ListView(list, {
layout: new WinJS.UI[layoutName](),
itemDataSource: bindingList.dataSource
});
var visibleAt900;
Helper.ListView.waitForReady(listView)().
then(function () {
listView.ensureVisible(900);
return Helper.ListView.waitForReady(listView)();
}).
then(function () {
visibleAt900 = listView.indexOfFirstVisible;
LiveUnit.Assert.isTrue(listView.indexOfFirstVisible > 10);
listView.ensureVisible(0);
return Helper.ListView.waitForReady(listView)();
}).
then(function () {
LiveUnit.Assert.areEqual(0, listView.indexOfFirstVisible);
listView.ensureVisible(900);
return Helper.ListView.waitForReady(listView)();
}).
then(function () {
LiveUnit.Assert.areEqual(visibleAt900, listView.indexOfFirstVisible);
listView.ensureVisible(-1);
return Helper.ListView.waitForReady(listView)();
}).
then(function () {
// invalid request should be ignored
LiveUnit.Assert.areEqual(visibleAt900, listView.indexOfFirstVisible);
return Helper.ListView.waitForReady(listView)();
}).
done(complete, function (e) {
throw "Unexpected exception: " + e;
});
};
};
generateEnsureVisibleScroll("GridLayout");
function generateHeaderKeyboardNavigationTest(layout) {
function groupKey(item) {
return item.groupKey;
}
function groupData(item) {
return { key: groupKey(item), title: groupKey(item) };
}
function createKeyEvent(element, key) {
return {
keyCode: key,
target: element,
stopPropagation: function () { },
preventDefault: function () { }
};
}
var a = "A".charCodeAt(0),
items = [];
for (var i = 0; i < 100; ++i) {
items[i] = {
title: "Item " + i,
groupKey: String.fromCharCode(a + Math.floor(i / 5))
};
}
var data = new WinJS.Binding.List(items).createGrouped(groupKey, groupData);
BrowseModeTests.prototype["testHeaderKeyboardNavigation" + layout] = function (complete) {
var lv = new ListView(list);
lv.layout = new WinJS.UI[layout];
lv.itemDataSource = data.dataSource;
lv.groupDataSource = data.groups.dataSource;
function setFocus(entity) {
function getEntity(entity) {
if (entity.type === "item") {
return lv.elementFromIndex(entity.index);
} else {
return lv.element.querySelectorAll(".win-groupheadercontainer")[entity.index];
}
}
function waitForFocus(element) {
return new WinJS.Promise(function (c) {
var token = setInterval(function () {
if (document.activeElement === element || element.contains(document.activeElement)) {
clearInterval(token);
c();
}
}, 100);
});
}
return WinJS.Promise.wrap().then(function () {
// Ensure that entity is visible so that we'll be able to give it focus
lv.ensureVisible(entity);
return Helper.ListView.waitForReady(lv)();
}).then(function () {
// Give entity focus and when it receives focus, the returned promise completes
lv.currentItem = {
type: entity.type, index: entity.index,
hasFocus: true, showFocus: true
};
// Sometimes setActive will throw so the item won't receive focus. To allow the
// test to continue when this happens, use a timeout as a fallback.
return WinJS.Promise.any([waitForFocus(getEntity(entity)), WinJS.Promise.timeout(500)]);
});
}
// Let's wait until the tree is fully created
Helper.ListView.waitForAllContainers(lv).then(function () {
// Navigating backwards
return setFocus({ type: WinJS.UI.ObjectType.groupHeader, index: 5 });
}).then(function () {
lv._mode.onKeyDown(createKeyEvent(document.querySelector(".win-groupheader"), (layout === "ListLayout" ? Key.upArrow : Key.leftArrow)));
return Helper.ListView.waitForReady(lv, -1)();
}).then(function () {
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.groupHeader, lv.currentItem.type);
LiveUnit.Assert.areEqual(4, lv.currentItem.index);
// Navigating forwards
return setFocus({ type: WinJS.UI.ObjectType.groupHeader, index: 5 });
}).then(function () {
lv._mode.onKeyDown(createKeyEvent(document.querySelector(".win-groupheader"), (layout === "ListLayout" ? Key.downArrow : Key.rightArrow)));
return Helper.ListView.waitForReady(lv, -1)();
}).then(function () {
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.groupHeader, lv.currentItem.type);
LiveUnit.Assert.areEqual(6, lv.currentItem.index);
// Lower bound check
return setFocus({ type: WinJS.UI.ObjectType.groupHeader, index: 0 });
}).then(function () {
lv._mode.onKeyDown(createKeyEvent(document.querySelector(".win-groupheader"), (layout === "ListLayout" ? Key.upArrow : Key.leftArrow)));
return Helper.ListView.waitForReady(lv, -1)();
}).then(function () {
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.groupHeader, lv.currentItem.type);
LiveUnit.Assert.areEqual(0, lv.currentItem.index);
// Upper bound check
return setFocus({ type: WinJS.UI.ObjectType.groupHeader, index: 19 });
}).then(function () {
lv._mode.onKeyDown(createKeyEvent(document.querySelector(".win-groupheader"), (layout === "ListLayout" ? Key.downArrow : Key.rightArrow)));
return Helper.ListView.waitForReady(lv, -1)();
}).then(function () {
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.groupHeader, lv.currentItem.type);
LiveUnit.Assert.areEqual(19, lv.currentItem.index);
// Home
return setFocus({ type: WinJS.UI.ObjectType.groupHeader, index: 5 });
}).then(function () {
lv._mode.onKeyDown(createKeyEvent(document.querySelector(".win-groupheader"), Key.home));
return Helper.ListView.waitForReady(lv, -1)();
}).then(function () {
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.groupHeader, lv.currentItem.type);
LiveUnit.Assert.areEqual(0, lv.currentItem.index);
// End
return setFocus({ type: WinJS.UI.ObjectType.groupHeader, index: 5 });
}).then(function () {
lv._mode.onKeyDown(createKeyEvent(document.querySelector(".win-groupheader"), Key.end));
return Helper.ListView.waitForReady(lv, -1)();
}).then(function () {
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.groupHeader, lv.currentItem.type);
LiveUnit.Assert.areEqual(19, lv.currentItem.index);
// Page up
return setFocus({ type: WinJS.UI.ObjectType.groupHeader, index: 5 });
}).then(function () {
lv._mode.onKeyDown(createKeyEvent(document.querySelector(".win-groupheader"), Key.pageUp));
return Helper.ListView.waitForReady(lv, -1)();
}).then(function () {
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.item, lv.currentItem.type);
// Page down
return setFocus({ type: WinJS.UI.ObjectType.groupHeader, index: 5 });
}).then(function () {
return Helper.ListView.waitForReady(lv, -1)();
}).then(function () {
lv._mode.onKeyDown(createKeyEvent(document.querySelector(".win-groupheader"), Key.pageDown));
return Helper.ListView.waitForReady(lv, -1)();
}).then(function () {
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.item, lv.currentItem.type);
lv.header = document.createElement("div");
lv.footer = document.createElement("div");
return setFocus({ type: WinJS.UI.ObjectType.groupHeader, index: 0 });
}).then(function () {
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.groupHeader, lv.currentItem.type);
lv._mode.onKeyDown(createKeyEvent(document.querySelector(".win-groupheader"), Key.leftArrow));
return Helper.ListView.waitForReady(lv, -1)();
}).then(function () {
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.header, lv.currentItem.type);
lv._mode.onKeyDown(createKeyEvent(document.querySelector(".win-groupheader"), Key.end));
return Helper.ListView.waitForReady(lv, -1)();
}).then(function () {
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.footer, lv.currentItem.type);
lv.header = null;
lv._mode.onKeyDown(createKeyEvent(document.querySelector(".win-groupheader"), Key.home));
return Helper.ListView.waitForReady(lv, -1)();
}).then(function () {
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.groupHeader, lv.currentItem.type);
lv.header = document.createElement("div");
lv._mode.onKeyDown(createKeyEvent(document.querySelector(".win-groupheader"), Key.leftArrow));
return Helper.ListView.waitForReady(lv, -1)();
}).then(function () {
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.header, lv.currentItem.type);
lv.footer = null;
lv._mode.onKeyDown(createKeyEvent(document.querySelector(".win-groupheader"), Key.end));
return Helper.ListView.waitForReady(lv, -1)();
}).done(function () {
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.groupHeader, lv.currentItem.type);
complete();
});
};
};
generateHeaderKeyboardNavigationTest("ListLayout");
generateHeaderKeyboardNavigationTest("GridLayout");
function generateLastFocusedItemIndexChangeForGroupHeaderTest(layout) {
function groupKey(item) {
return item.groupKey;
}
function groupData(item) {
return { key: groupKey(item), title: groupKey(item) };
}
function createKeyEvent(element, key) {
return {
keyCode: key,
target: element,
stopPropagation: function () { },
preventDefault: function () { }
};
}
var a = "A".charCodeAt(0),
items = [];
for (var i = 0; i < 100; ++i) {
items[i] = {
title: "Item " + i,
groupKey: String.fromCharCode(a + Math.floor(i / 5))
};
}
var data = new WinJS.Binding.List(items).createGrouped(groupKey, groupData);
BrowseModeTests.prototype["testLastFocusedItemIndexChangeForGroupHeader" + layout] = function (complete) {
var lv = new ListView(list);
lv.layout = new WinJS.UI[layout];
lv.itemDataSource = data.dataSource;
lv.groupDataSource = data.groups.dataSource;
Helper.ListView.waitForReady(lv)().then(function () {
// Focus item, go to group header, remove last focused item from the group and go to item track again, focus should go on first item of the group
lv.currentItem = { type: WinJS.UI.ObjectType.groupHeader, index: 4 };
lv.currentItem = { type: WinJS.UI.ObjectType.item, index: 22 };
lv._mode.onTabExiting({ detail: 1, preventDefault: function () { } });
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.groupHeader, lv.currentItem.type);
lv.itemDataSource.remove("22");
lv._mode.onTabExiting({ detail: 0, preventDefault: function () { } });
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.item, lv.currentItem.type);
LiveUnit.Assert.areEqual(20, lv.currentItem.index);
// Focus item, go to group header, insert item at the place of last focused item from the group and go to item track again
// Focus should go on last visited item not on new inserted item or not on first item of the group
lv.currentItem = { type: WinJS.UI.ObjectType.groupHeader, index: 18 };
lv.currentItem = { type: WinJS.UI.ObjectType.item, index: 93 };
var itemKey = lv.currentItem.key;
lv._mode.onTabExiting({ detail: 1, preventDefault: function () { } });
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.groupHeader, lv.currentItem.type);
LiveUnit.Assert.areEqual(18, lv.currentItem.index);
lv.itemDataSource.insertAfter("newItem92", { title: "S", groupKey: "S" }, "91");
lv.itemDataSource.insertAfter("newItem94", { title: "S", groupKey: "S" }, "93");
lv.itemDataSource.insertAfter("newItem93", { title: "S", groupKey: "S" }, "92");
lv.itemDataSource.insertAfter("newItem95", { title: "S", groupKey: "S" }, "94");
lv._mode.onTabExiting({ detail: 0, preventDefault: function () { } });
LiveUnit.Assert.areEqual(WinJS.UI.ObjectType.item, lv.currentItem.type);
LiveUnit.Assert.areEqual(itemKey, lv.currentItem.key);
complete();
});
};
}
generateLastFocusedItemIndexChangeForGroupHeaderTest("ListLayout");
generateLastFocusedItemIndexChangeForGroupHeaderTest("GridLayout");
function generateOffscreenPageKeysTest(layout) {
function groupKey(item) {
return item.groupKey;
}
function groupData(item) {
return { key: groupKey(item), title: groupKey(item) };
}
function createKeyEvent(element, key) {
return {
keyCode: key,
target: element,
stopPropagation: function () { },
preventDefault: function () { }
};
}
var a = "A".charCodeAt(0),
items = [];
for (var i = 0; i < 100; ++i) {
items[i] = {
title: "Item " + i,
groupKey: String.fromCharCode(a + Math.floor(i / 5))
};
}
var data = new WinJS.Binding.List(items).createGrouped(groupKey, groupData);
BrowseModeTests.prototype["testOffscreenPageKeys" + layout] = function (complete) {
var lv = new ListView(list);
lv.layout = new WinJS.UI[layout];
lv.itemDataSource = data.dataSource;
lv.groupDataSource = data.groups.dataSource;
lv.currentItem = { type: WinJS.UI.ObjectType.item, index: 1 };
var origScrollPos;
var indexOfFirstVisible;
Helper.ListView.waitForReady(lv)().then(function () {
origScrollPos = lv.scrollPosition;
lv.scrollPosition = 1000;
return Helper.ListView.waitForReady(lv, -1)();
}).then(function () {
indexOfFirstVisible = lv.indexOfFirstVisible;
lv._mode.onKeyDown(createKeyEvent(lv.element, Key.pageDown));
return Helper.ListView.waitForReady(lv, -1)();
}).then(function () {
LiveUnit.Assert.areNotEqual(indexOfFirstVisible, lv.indexOfFirstVisible);
complete();
});
};
};
generateOffscreenPageKeysTest("ListLayout");
generateOffscreenPageKeysTest("GridLayout");
}
// register the object as a test class by passing in the name
LiveUnit.registerTestClass("WinJSTests.BrowseModeTests"); | the_stack |
import mxClient from '../../../../mxClient';
import {
ABSOLUTE_LINE_HEIGHT,
ALIGN_BOTTOM,
ALIGN_CENTER,
ALIGN_MIDDLE,
ALIGN_RIGHT,
DEFAULT_FONTFAMILY,
DEFAULT_FONTSIZE,
DEFAULT_FONTSTYLE,
DEFAULT_TEXT_DIRECTION,
DIALECT_STRICTHTML,
FONT_BOLD,
FONT_ITALIC,
FONT_STRIKETHROUGH,
FONT_UNDERLINE,
LINE_HEIGHT,
NONE,
TEXT_DIRECTION_AUTO,
TEXT_DIRECTION_DEFAULT,
TEXT_DIRECTION_LTR,
TEXT_DIRECTION_RTL,
WORD_WRAP,
} from '../../../../util/Constants';
import { getAlignmentAsPoint, getBoundingBox } from '../../../../util/Utils';
import Point from '../../Point';
import AbstractCanvas2D from '../../../../util/canvas/AbstractCanvas2D';
import Shape from '../Shape';
import Rectangle from '../../Rectangle';
import CellState from '../../../cell/datatypes/CellState';
import {
htmlEntities,
replaceTrailingNewlines,
trim,
} from '../../../../util/StringUtils';
import { isNode } from '../../../../util/DomUtils';
import {
AlignValue,
ColorValue,
OverflowValue,
TextDirectionValue,
VAlignValue,
} from '../../../../types';
import SvgCanvas2D from '../../../../util/canvas/SvgCanvas2D';
/**
* Extends mxShape to implement a text shape.
* To change vertical text from bottom to top to top to bottom,
* the following code can be used:
* @example
* ```javascript
* mxText.prototype.verticalTextRotation = 90;
* ```
* @class TextShape
* @extends {Shape}
*/
class TextShape extends Shape {
constructor(
value: string | HTMLElement | SVGGElement,
bounds: Rectangle,
align: AlignValue = ALIGN_CENTER,
valign: VAlignValue = ALIGN_MIDDLE,
color = 'black',
family = DEFAULT_FONTFAMILY,
size = DEFAULT_FONTSIZE,
fontStyle = DEFAULT_FONTSTYLE,
spacing = 2,
spacingTop = 0,
spacingRight = 0,
spacingBottom = 0,
spacingLeft = 0,
horizontal = true,
background = NONE,
border = NONE,
wrap = false,
clipped = false,
overflow: OverflowValue = 'visible',
labelPadding = 0,
textDirection: TextDirectionValue = DEFAULT_TEXT_DIRECTION
) {
super();
this.value = value;
this.bounds = bounds;
this.color = color ?? 'black';
this.align = align ?? ALIGN_CENTER;
this.valign = valign ?? ALIGN_MIDDLE;
this.family = family ?? DEFAULT_FONTFAMILY;
this.size = size ?? DEFAULT_FONTSIZE;
this.fontStyle = fontStyle ?? DEFAULT_FONTSTYLE;
this.spacing = spacing ?? 2;
this.spacingTop = this.spacing + (spacingTop ?? 0);
this.spacingRight = this.spacing + (spacingRight ?? 0);
this.spacingBottom = this.spacing + (spacingBottom ?? 0);
this.spacingLeft = this.spacing + (spacingLeft ?? 0);
this.horizontal = horizontal ?? true;
this.background = background;
this.border = border;
this.wrap = wrap ?? false;
this.clipped = clipped ?? false;
this.overflow = overflow ?? 'visible';
this.labelPadding = labelPadding ?? 0;
this.textDirection = textDirection;
this.rotation = 0;
this.updateMargin();
}
value: string | HTMLElement | SVGGElement;
bounds: Rectangle;
align: AlignValue;
valign: VAlignValue;
color: ColorValue;
family: string;
size: number;
fontStyle: number;
spacing: number;
spacingTop: number;
spacingRight: number;
spacingBottom: number;
spacingLeft: number;
horizontal: boolean;
background: ColorValue;
border: ColorValue;
wrap: boolean;
clipped: boolean;
overflow: OverflowValue;
labelPadding: number;
textDirection: TextDirectionValue;
margin: Point | null = null;
unrotatedBoundingBox: Rectangle | null = null;
flipH = false;
flipV = false;
/**
* Variable: baseSpacingTop
*
* Specifies the spacing to be added to the top spacing. Default is 0. Use the
* value 5 here to get the same label positions as in mxGraph 1.x.
*/
baseSpacingTop = 0;
/**
* Variable: baseSpacingBottom
*
* Specifies the spacing to be added to the bottom spacing. Default is 0. Use the
* value 1 here to get the same label positions as in mxGraph 1.x.
*/
baseSpacingBottom = 0;
/**
* Variable: baseSpacingLeft
*
* Specifies the spacing to be added to the left spacing. Default is 0.
*/
baseSpacingLeft = 0;
/**
* Variable: baseSpacingRight
*
* Specifies the spacing to be added to the right spacing. Default is 0.
*/
baseSpacingRight = 0;
/**
* Variable: replaceLinefeeds
*
* Specifies if linefeeds in HTML labels should be replaced with BR tags.
* Default is true.
*/
replaceLinefeeds = true;
/**
* Variable: verticalTextRotation
*
* Rotation for vertical text. Default is -90 (bottom to top).
*/
verticalTextRotation = -90;
/**
* Variable: ignoreClippedStringSize
*
* Specifies if the string size should be measured in <updateBoundingBox> if
* the label is clipped and the label position is center and middle. If this is
* true, then the bounding box will be set to <bounds>. Default is true.
* <ignoreStringSize> has precedence over this switch.
*/
ignoreClippedStringSize = true;
/**
* Variable: ignoreStringSize
*
* Specifies if the actual string size should be measured. If disabled the
* boundingBox will not ignore the actual size of the string, otherwise
* <bounds> will be used instead. Default is false.
*/
ignoreStringSize = false;
/**
* Variable: lastValue
*
* Contains the last rendered text value. Used for caching.
*/
lastValue: string | HTMLElement | SVGGElement | null = null;
/**
* Variable: cacheEnabled
*
* Specifies if caching for HTML labels should be enabled. Default is true.
*/
cacheEnabled = true;
/**
* Function: getSvgScreenOffset
*
* Disables offset in IE9 for crisper image output.
*/
getSvgScreenOffset() {
return 0;
}
/**
* Function: checkBounds
*
* Returns true if the bounds are not null and all of its variables are numeric.
*/
checkBounds() {
return (
!isNaN(this.scale) &&
isFinite(this.scale) &&
this.scale > 0 &&
this.bounds &&
!isNaN(this.bounds.x) &&
!isNaN(this.bounds.y) &&
!isNaN(this.bounds.width) &&
!isNaN(this.bounds.height)
);
}
/**
* Function: paint
*
* Generic rendering code.
*/
paint(c: AbstractCanvas2D, update = false): void {
// Scale is passed-through to canvas
const s = this.scale;
const x = this.bounds.x / s;
const y = this.bounds.y / s;
const w = this.bounds.width / s;
const h = this.bounds.height / s;
this.updateTransform(c, x, y, w, h);
this.configureCanvas(c, x, y, w, h);
if (update) {
c.updateText(
x,
y,
w,
h,
this.align,
this.valign,
this.wrap,
this.overflow,
this.clipped,
this.getTextRotation(),
this.node
);
} else {
// Checks if text contains HTML markup
const realHtml = isNode(this.value) || this.dialect === DIALECT_STRICTHTML;
// Always renders labels as HTML in VML
const fmt = realHtml ? 'html' : '';
let val = this.value as string;
if (!realHtml && fmt === 'html') {
// @ts-ignore
val = htmlEntities(val, false);
}
if (fmt === 'html' && !isNode(this.value)) {
val = replaceTrailingNewlines(val, '<div><br></div>');
}
// Handles trailing newlines to make sure they are visible in rendering output
val =
!isNode(this.value) && this.replaceLinefeeds && fmt === 'html'
? (<string>val).replace(/\n/g, '<br/>')
: val;
let dir: TextDirectionValue = this.textDirection;
if (dir === TEXT_DIRECTION_AUTO && !realHtml) {
dir = this.getAutoDirection();
}
if (dir !== TEXT_DIRECTION_LTR && dir !== TEXT_DIRECTION_RTL) {
dir = TEXT_DIRECTION_DEFAULT;
}
c.text(
x,
y,
w,
h,
val,
this.align,
this.valign,
this.wrap,
fmt,
this.overflow,
this.clipped,
this.getTextRotation(),
dir
);
}
}
/**
* Function: redraw
*
* Renders the text using the given DOM nodes.
*/
redraw(): void {
if (
this.visible &&
this.checkBounds() &&
this.cacheEnabled &&
this.lastValue === this.value &&
(isNode(this.value) || this.dialect === DIALECT_STRICTHTML)
) {
if (this.node.nodeName === 'DIV') {
this.redrawHtmlShape();
this.updateBoundingBox();
} else {
const canvas = this.createCanvas();
if (canvas) {
// Specifies if events should be handled
canvas.pointerEvents = this.pointerEvents;
this.paint(canvas, true);
this.destroyCanvas(canvas);
this.updateBoundingBox();
}
}
} else {
super.redraw();
if (isNode(this.value) || this.dialect === DIALECT_STRICTHTML) {
this.lastValue = this.value;
} else {
this.lastValue = null;
}
}
}
/**
* Function: resetStyles
*
* Resets all styles.
*/
resetStyles(): void {
super.resetStyles();
this.color = 'black';
this.align = ALIGN_CENTER;
this.valign = ALIGN_MIDDLE;
this.family = DEFAULT_FONTFAMILY;
this.size = DEFAULT_FONTSIZE;
this.fontStyle = DEFAULT_FONTSTYLE;
this.spacing = 2;
this.spacingTop = 2;
this.spacingRight = 2;
this.spacingBottom = 2;
this.spacingLeft = 2;
this.horizontal = true;
this.background = NONE;
this.border = NONE;
this.textDirection = DEFAULT_TEXT_DIRECTION;
this.margin = null;
}
/**
* Function: apply
*
* Extends mxShape to update the text styles.
*
* Parameters:
*
* state - <mxCellState> of the corresponding cell.
*/
apply(state: CellState): void {
const old = this.spacing;
super.apply(state);
if (this.style) {
this.fontStyle = this.style.fontStyle ?? this.fontStyle;
this.family = this.style.fontFamily ?? this.family;
this.size = this.style.fontSize ?? this.size;
this.color = this.style.fontColor ?? this.color;
this.align = this.style.align ?? this.align;
this.valign = this.style.verticalAlign ?? this.valign;
this.spacing = this.style.spacing ?? this.spacing;
this.spacingTop = (this.style.spacingTop ?? this.spacingTop - old) + this.spacing;
this.spacingRight =
(this.style.spacingRight ?? this.spacingRight - old) + this.spacing;
this.spacingBottom =
(this.style.spacingBottom ?? this.spacingBottom - old) + this.spacing;
this.spacingLeft =
(this.style.spacingLeft ?? this.spacingLeft - old) + this.spacing;
this.horizontal = this.style.horizontal ?? this.horizontal;
this.background = this.style.backgroundColor ?? this.background;
this.border = this.style.labelBorderColor ?? this.border;
this.textDirection = this.style.textDirection ?? DEFAULT_TEXT_DIRECTION;
this.opacity = this.style.textOpacity ?? 100;
this.updateMargin();
}
this.flipV = false;
this.flipH = false;
}
/**
* Function: getAutoDirection
*
* Used to determine the automatic text direction. Returns
* <mxConstants.TEXT_DIRECTION_LTR> or <mxConstants.TEXT_DIRECTION_RTL>
* depending on the contents of <value>. This is not invoked for HTML, wrapped
* content or if <value> is a DOM node.
*/
getAutoDirection() {
// Looks for strong (directional) characters
const tmp = /[A-Za-z\u05d0-\u065f\u066a-\u06ef\u06fa-\u07ff\ufb1d-\ufdff\ufe70-\ufefc]/.exec(
String(this.value)
);
// Returns the direction defined by the character
return tmp && tmp.length > 0 && tmp[0] > 'z'
? TEXT_DIRECTION_RTL
: TEXT_DIRECTION_LTR;
}
/**
* Function: getContentNode
*
* Returns the node that contains the rendered input.
*/
getContentNode() {
let result = this.node;
if (result) {
// Rendered with no foreignObject
if (!result.ownerSVGElement) {
// @ts-ignore
result = this.node.firstChild.firstChild;
} else {
// Innermost DIV that contains the actual content
// @ts-ignore
result = result.firstChild.firstChild.firstChild.firstChild.firstChild;
}
}
return result;
}
/**
* Function: updateBoundingBox
*
* Updates the <boundingBox> for this shape using the given node and position.
*/
updateBoundingBox() {
let { node } = this;
this.boundingBox = this.bounds.clone();
const rot = this.getTextRotation();
const h = this.style?.labelPosition ?? ALIGN_CENTER;
const v = this.style?.verticalLabelPosition ?? ALIGN_MIDDLE;
if (
!this.ignoreStringSize &&
node &&
this.overflow !== 'fill' &&
(!this.clipped ||
!this.ignoreClippedStringSize ||
h !== ALIGN_CENTER ||
v !== ALIGN_MIDDLE)
) {
let ow = null;
let oh = null;
if (
node.firstChild &&
node.firstChild.firstChild &&
node.firstChild.firstChild.nodeName === 'foreignObject'
) {
// Uses second inner DIV for font metrics
// @ts-ignore
node = node.firstChild.firstChild.firstChild.firstChild;
// @ts-ignore
oh = node.offsetHeight * this.scale;
if (this.overflow === 'width') {
ow = this.boundingBox.width;
} else {
// @ts-ignore
ow = node.offsetWidth * this.scale;
}
} else {
try {
const b = node.getBBox();
// Workaround for bounding box of empty string
if (typeof this.value === 'string' && trim(this.value)?.length === 0) {
this.boundingBox = null;
} else if (b.width === 0 && b.height === 0) {
this.boundingBox = null;
} else {
this.boundingBox = new Rectangle(b.x, b.y, b.width, b.height);
}
return;
} catch (e) {
// Ignores NS_ERROR_FAILURE in FF if container display is none.
}
}
if (ow && oh) {
this.boundingBox = new Rectangle(this.bounds.x, this.bounds.y, ow, oh);
}
}
if (this.boundingBox) {
const margin = <Rectangle>this.margin;
if (rot !== 0) {
// Accounts for pre-rotated x and y
const bbox = <Rectangle>(
getBoundingBox(
new Rectangle(
margin.x * this.boundingBox.width,
margin.y * this.boundingBox.height,
this.boundingBox.width,
this.boundingBox.height
),
rot,
new Point(0, 0)
)
);
this.unrotatedBoundingBox = Rectangle.fromRectangle(this.boundingBox);
this.unrotatedBoundingBox.x += margin.x * this.unrotatedBoundingBox.width;
this.unrotatedBoundingBox.y += margin.y * this.unrotatedBoundingBox.height;
this.boundingBox.x += bbox.x;
this.boundingBox.y += bbox.y;
this.boundingBox.width = bbox.width;
this.boundingBox.height = bbox.height;
} else {
this.boundingBox.x += margin.x * this.boundingBox.width;
this.boundingBox.y += margin.y * this.boundingBox.height;
this.unrotatedBoundingBox = null;
}
}
}
/**
* Function: getShapeRotation
*
* Returns 0 to avoid using rotation in the canvas via updateTransform.
*/
getShapeRotation() {
return 0;
}
/**
* Function: getTextRotation
*
* Returns the rotation for the text label of the corresponding shape.
*/
getTextRotation() {
return this.state && this.state.shape ? this.state.shape.getTextRotation() : 0;
}
/**
* Function: isPaintBoundsInverted
*
* Inverts the bounds if <mxShape.isBoundsInverted> returns true or if the
* horizontal style is false.
*/
isPaintBoundsInverted() {
return !this.horizontal && !!this.state && this.state.cell.isVertex();
}
/**
* Function: configureCanvas
*
* Sets the state of the canvas for drawing the shape.
*/
configureCanvas(c: AbstractCanvas2D, x: number, y: number, w: number, h: number): void {
super.configureCanvas(c, x, y, w, h);
c.setFontColor(this.color);
c.setFontBackgroundColor(this.background);
c.setFontBorderColor(this.border);
c.setFontFamily(this.family);
c.setFontSize(this.size);
c.setFontStyle(this.fontStyle);
}
/**
* Function: getHtmlValue
*
* Private helper function to create SVG elements
*/
getHtmlValue() {
let val = this.value as string;
if (this.dialect !== DIALECT_STRICTHTML) {
// @ts-ignore
val = htmlEntities(val, false);
}
// Handles trailing newlines to make sure they are visible in rendering output
val = replaceTrailingNewlines(val, '<div><br></div>');
val = this.replaceLinefeeds ? val.replace(/\n/g, '<br/>') : val;
return val;
}
/**
* Function: getTextCss
*
* Private helper function to create SVG elements
*/
getTextCss() {
const lh = ABSOLUTE_LINE_HEIGHT ? `${this.size * LINE_HEIGHT}px` : LINE_HEIGHT;
let css =
`display: inline-block; font-size: ${this.size}px; ` +
`font-family: ${this.family}; color: ${
this.color
}; line-height: ${lh}; pointer-events: ${this.pointerEvents ? 'all' : 'none'}; `;
if ((this.fontStyle & FONT_BOLD) === FONT_BOLD) {
css += 'font-weight: bold; ';
}
if ((this.fontStyle & FONT_ITALIC) === FONT_ITALIC) {
css += 'font-style: italic; ';
}
const deco = [];
if ((this.fontStyle & FONT_UNDERLINE) === FONT_UNDERLINE) {
deco.push('underline');
}
if ((this.fontStyle & FONT_STRIKETHROUGH) === FONT_STRIKETHROUGH) {
deco.push('line-through');
}
if (deco.length > 0) {
css += `text-decoration: ${deco.join(' ')}; `;
}
return css;
}
/**
* Function: redrawHtmlShape
*
* Updates the HTML node(s) to reflect the latest bounds and scale.
*/
redrawHtmlShape() {
const w = Math.max(0, Math.round(this.bounds.width / this.scale));
const h = Math.max(0, Math.round(this.bounds.height / this.scale));
const flex =
`position: absolute; left: ${Math.round(this.bounds.x)}px; ` +
`top: ${Math.round(this.bounds.y)}px; pointer-events: none; `;
const block = this.getTextCss();
const margin = <Point>this.margin;
const node = this.node;
SvgCanvas2D.createCss(
w + 2,
h,
this.align,
this.valign,
this.wrap,
this.overflow,
this.clipped,
this.background !== NONE ? htmlEntities(this.background, true) : null,
this.border !== NONE ? htmlEntities(this.border, true) : null,
flex,
block,
this.scale,
(
dx: number,
dy: number,
flex: string,
item: string,
block: string,
ofl: string
) => {
const r = this.getTextRotation();
let tr =
(this.scale !== 1 ? `scale(${this.scale}) ` : '') +
(r !== 0 ? `rotate(${r}deg) ` : '') +
(margin.x !== 0 || margin.y !== 0
? `translate(${margin.x * 100}%,${margin.y * 100}%)`
: '');
if (tr !== '') {
tr = `transform-origin: 0 0; transform: ${tr}; `;
}
if (ofl === '') {
flex += item;
item = `display:inline-block; min-width: 100%; ${tr}`;
} else {
item += tr;
if (mxClient.IS_SF) {
item += '-webkit-clip-path: content-box;';
}
}
if (this.opacity < 100) {
block += `opacity: ${<number>this.opacity / 100}; `;
}
node.setAttribute('style', flex);
const html = isNode(this.value)
? // @ts-ignore
this.value.outerHTML
: this.getHtmlValue();
if (!node.firstChild) {
node.innerHTML = `<div><div>${html}</div></div>`;
}
// @ts-ignore
node.firstChild.firstChild.setAttribute('style', block);
// @ts-ignore
node.firstChild.setAttribute('style', item);
}
);
}
/**
* Function: setInnerHtml
*
* Sets the inner HTML of the given element to the <value>.
*/
updateInnerHtml(elt: HTMLElement) {
if (isNode(this.value)) {
// @ts-ignore
elt.innerHTML = this.value.outerHTML;
} else {
let val = this.value as string;
if (this.dialect !== DIALECT_STRICTHTML) {
// LATER: Can be cached in updateValue
val = htmlEntities(val, false);
}
// Handles trailing newlines to make sure they are visible in rendering output
val = replaceTrailingNewlines(val, '<div> </div>');
val = this.replaceLinefeeds ? val.replace(/\n/g, '<br/>') : val;
val = `<div style="display:inline-block;_display:inline;">${val}</div>`;
elt.innerHTML = val;
}
}
/**
* Function: updateValue
*
* Updates the HTML node(s) to reflect the latest bounds and scale.
*/
updateValue() {
const node = this.node;
if (isNode(this.value)) {
node.innerHTML = '';
node.appendChild(<HTMLElement | SVGGElement>this.value);
} else {
let val = this.value as string;
if (this.dialect !== DIALECT_STRICTHTML) {
val = htmlEntities(val, false);
}
// Handles trailing newlines to make sure they are visible in rendering output
val = replaceTrailingNewlines(val, '<div><br></div>');
val = this.replaceLinefeeds ? val.replace(/\n/g, '<br/>') : val;
const bg = this.background !== NONE ? this.background : null;
const bd = this.border !== NONE ? this.border : null;
if (this.overflow === 'fill' || this.overflow === 'width') {
if (bg) {
node.style.backgroundColor = bg;
}
if (bd) {
node.style.border = `1px solid ${bd}`;
}
} else {
let css = '';
if (bg) {
css += `background-color:${htmlEntities(bg, true)};`;
}
if (bd) {
css += `border:1px solid ${htmlEntities(bd, true)};`;
}
// Wrapper DIV for background, zoom needed for inline in quirks
// and to measure wrapped font sizes in all browsers
// FIXME: Background size in quirks mode for wrapped text
const lh = ABSOLUTE_LINE_HEIGHT ? `${this.size * LINE_HEIGHT}px` : LINE_HEIGHT;
val =
`<div style="zoom:1;${css}display:inline-block;_display:inline;text-decoration:inherit;` +
`padding-bottom:1px;padding-right:1px;line-height:${lh}">${val}</div>`;
}
node.innerHTML = val;
// Sets text direction
const divs = node.getElementsByTagName('div');
if (divs.length > 0) {
let dir = this.textDirection;
if (dir === TEXT_DIRECTION_AUTO && this.dialect !== DIALECT_STRICTHTML) {
dir = this.getAutoDirection();
}
if (dir === TEXT_DIRECTION_LTR || dir === TEXT_DIRECTION_RTL) {
divs[divs.length - 1].setAttribute('dir', dir);
} else {
divs[divs.length - 1].removeAttribute('dir');
}
}
}
}
/**
* Function: updateFont
*
* Updates the HTML node(s) to reflect the latest bounds and scale.
*/
updateFont(node: HTMLElement | SVGGElement) {
const { style } = node;
// @ts-ignore
style.lineHeight = ABSOLUTE_LINE_HEIGHT
? `${this.size * LINE_HEIGHT}px`
: LINE_HEIGHT;
style.fontSize = `${this.size}px`;
style.fontFamily = this.family;
style.verticalAlign = 'top';
style.color = this.color;
if ((this.fontStyle & FONT_BOLD) === FONT_BOLD) {
style.fontWeight = 'bold';
} else {
style.fontWeight = '';
}
if ((this.fontStyle & FONT_ITALIC) === FONT_ITALIC) {
style.fontStyle = 'italic';
} else {
style.fontStyle = '';
}
const txtDecor = [];
if ((this.fontStyle & FONT_UNDERLINE) === FONT_UNDERLINE) {
txtDecor.push('underline');
}
if ((this.fontStyle & FONT_STRIKETHROUGH) === FONT_STRIKETHROUGH) {
txtDecor.push('line-through');
}
style.textDecoration = txtDecor.join(' ');
if (this.align === ALIGN_CENTER) {
style.textAlign = 'center';
} else if (this.align === ALIGN_RIGHT) {
style.textAlign = 'right';
} else {
style.textAlign = 'left';
}
}
/**
* Function: updateSize
*
* Updates the HTML node(s) to reflect the latest bounds and scale.
*/
updateSize(node: HTMLElement, enableWrap = false) {
const w = Math.max(0, Math.round(this.bounds.width / this.scale));
const h = Math.max(0, Math.round(this.bounds.height / this.scale));
const { style } = node;
// NOTE: Do not use maxWidth here because wrapping will
// go wrong if the cell is outside of the viewable area
if (this.clipped) {
style.overflow = 'hidden';
style.maxHeight = `${h}px`;
style.maxWidth = `${w}px`;
} else if (this.overflow === 'fill') {
style.width = `${w + 1}px`;
style.height = `${h + 1}px`;
style.overflow = 'hidden';
} else if (this.overflow === 'width') {
style.width = `${w + 1}px`;
style.maxHeight = `${h + 1}px`;
style.overflow = 'hidden';
}
if (this.wrap && w > 0) {
style.wordWrap = WORD_WRAP;
style.whiteSpace = 'normal';
style.width = `${w}px`;
if (enableWrap && this.overflow !== 'fill' && this.overflow !== 'width') {
let sizeDiv = node;
if (sizeDiv.firstChild != null && sizeDiv.firstChild.nodeName === 'DIV') {
// @ts-ignore
sizeDiv = sizeDiv.firstChild;
if (node.style.wordWrap === 'break-word') {
sizeDiv.style.width = '100%';
}
}
let tmp = sizeDiv.offsetWidth;
// Workaround for text measuring in hidden containers
if (tmp === 0) {
const prev = <HTMLElement>node.parentNode;
node.style.visibility = 'hidden';
document.body.appendChild(node);
tmp = sizeDiv.offsetWidth;
node.style.visibility = '';
prev.appendChild(node);
}
tmp += 3;
if (this.clipped) {
tmp = Math.min(tmp, w);
}
style.width = `${tmp}px`;
}
} else {
style.whiteSpace = 'nowrap';
}
}
/**
* Function: getMargin
*
* Returns the spacing as an <mxPoint>.
*/
updateMargin() {
this.margin = getAlignmentAsPoint(this.align, this.valign);
}
/**
* Function: getSpacing
*
* Returns the spacing as an <mxPoint>.
*/
getSpacing() {
let dx = 0;
let dy = 0;
if (this.align === ALIGN_CENTER) {
dx = (this.spacingLeft - this.spacingRight) / 2;
} else if (this.align === ALIGN_RIGHT) {
dx = -this.spacingRight - this.baseSpacingRight;
} else {
dx = this.spacingLeft + this.baseSpacingLeft;
}
if (this.valign === ALIGN_MIDDLE) {
dy = (this.spacingTop - this.spacingBottom) / 2;
} else if (this.valign === ALIGN_BOTTOM) {
dy = -this.spacingBottom - this.baseSpacingBottom;
} else {
dy = this.spacingTop + this.baseSpacingTop;
}
return new Point(dx, dy);
}
}
export default TextShape; | the_stack |
import * as assert from "assert"
import * as http from "http"
import { testCli } from "."
import distbin from "../"
import * as activitypub from "../src/activitypub"
import { clientAddressedActivity, getASId, objectTargets, objectTargetsNoRecurse,
targetedAudience } from "../src/activitypub"
import { ASJsonLdProfileContentType } from "../src/activitystreams"
import { Activity, ASObject, LDValue } from "../src/types"
import { ensureArray, readableToString, sendRequest } from "../src/util"
import { first, isProbablyAbsoluteUrl } from "../src/util"
import { listen, requestForListener } from "./util"
const tests = module.exports
const setsAreEqual = (s1: Set<any>, s2: Set<any>) => (s1.size === s2.size) && Array.from(s1).every((i) => s2.has(i))
tests.objectTargets = async () => {
const activity: Activity = {
"@context": ["https://www.w3.org/ns/activitystreams",
{"@language": "en-GB"}],
"object": {
attributedTo: {
attributedTo: {
attributedTo: {
cc: [{
id: "https://rhiaro.co.uk/attributedTo/attributedTo/cc/0",
}],
id: "https://rhiaro.co.uk/attributedTo/attributedTo",
},
id: "https://rhario.co.uk/attributedTo",
},
id: "https://rhiaro.co.uk/#amy",
},
cc: "https://e14n.com/evan",
content: "Today I finished morph, a client for posting ActivityStreams2...",
id: "https://rhiaro.co.uk/2016/05/minimal-activitypub",
name: "Minimal ActivityPub update client",
to: "https://rhiaro.co.uk/followers/",
type: "Article",
},
"type": "Like",
}
const levels: Array<Set<string>> = [
["https://rhiaro.co.uk/#amy", "https://rhiaro.co.uk/followers/", "https://e14n.com/evan"],
["https://rhario.co.uk/attributedTo"],
["https://rhiaro.co.uk/attributedTo/attributedTo"],
["https://rhiaro.co.uk/attributedTo/attributedTo/cc/0"],
].map((a: string[]) => new Set(a))
const targetsShouldBeForLevel = (level: number) => {
const theseLevels = levels.slice(0, level + 1)
const targetsShouldBe = theseLevels.reduce(
(targets, levelTargetSet) => new Set([...levelTargetSet, ...targets]),
new Set(),
)
return new Set(targetsShouldBe)
}
for (const [index, level] of enumerate(levels)) {
const targets = (await objectTargets(activity, index, false, (u: string) => u)).map(getASId)
const targetsShouldBe = targetsShouldBeForLevel(index)
// console.log({ level: index, targets, targetsShouldBe })
assert(setsAreEqual(targetsShouldBe, new Set(targets)))
}
}
function* enumerate(iterable: Iterable<any>) {
let i = 0
for (const x of iterable) {
yield [i, x]
i++
}
}
tests.targetedAudience = async () => {
const asObject: ASObject = {
"@context": "https://www.w3.org/ns/activitystreams",
"attributedTo": "https://rhiaro.co.uk/#amy",
"cc": "https://e14n.com/evan",
"content": "Today I finished morph, a client for posting ActivityStreams2...",
"id": "https://rhiaro.co.uk/2016/05/minimal-activitypub",
"name": "Minimal ActivityPub update client",
"to": "https://rhiaro.co.uk/followers/",
"type": "Article",
}
const audience = targetedAudience(asObject)
// console.log('audience', audience)
assert.deepEqual(audience, ["https://rhiaro.co.uk/followers/", "https://e14n.com/evan"])
}
tests.clientAddressedActivity = async () => {
const attributedToId = "https://bengo.is/clientAddressedActivityTest"
const parentUrl = await listen(http.createServer((req, res) => {
res.writeHead(200, {"content-type": ASJsonLdProfileContentType})
res.end(JSON.stringify({
attributedTo: {
id: attributedToId,
},
type: "Note",
}, null, 2))
}))
const activityToAddress = {
object: {
content: "i reply to u ok",
inReplyTo: parentUrl,
type: "Note",
},
type: "Create",
}
const addressed = await clientAddressedActivity(activityToAddress, 0, true, (u: string) => u)
assert(ensureArray(addressed.cc).includes(attributedToId))
}
/*
Tests of ActivityPub functionality, including lots of text from the spec itself and #critiques
*/
/*
3.1 Object Identifiers - https://w3c.github.io/activitypub/#obj-id
All Objects in [ActivityStreams] should have unique global identifiers. ActivityPub extends this requirement;
all objects distributed by the ActivityPub protocol must have unique global identifiers; these identifiers must
fall into one of the following groups:
* Publicly dereferencable URIs, such as HTTPS URIs, with their authority belonging to that of their originating
server. (Publicly facing content should use HTTPS URIs.)
* An ID explicitly specified as the JSON null object, which implies an anonymous object (a part of its parent context)
#critique: There are no examples of this anywhere in the spec, and it's a weird deviation from AS2 which does not
require 'explicit' null (I think...).
Identifiers must be provided for activities posted in server to server communication.
However, for client to server communication, a server receiving an object with no specified id should allocate an
object ID in the user's namespace and attach it to the posted object.
All objects must have the following properties:
id
The object's unique global identifier
type
The type of the object
*/
// activitypub.objectHasRequiredProperties = (obj: {[key: string]: any}) => {
// const requiredProperties = ["id", "type"]
// const missingProperties = requiredProperties.filter((p: string) => obj[p])
// return Boolean(!missingProperties.length)
// }
// 3.2 Methods on Objects - https://w3c.github.io/activitypub/#obj-methods
// 4 Actors - https://w3c.github.io/activitypub/#actors
// #critique - This normalization algorithm isn't really normalizing if it leaves the default URI scheme up to
// each implementation to decide "preferably https"
// 5.4 Outbox - https://w3c.github.io/activitypub/#outbox
// The outbox is discovered through the outbox property of an actor's profile.
// #critique - Can only 'actors' have outboxes? Can a single distbin have one outbox?
// The outbox must be an OrderedCollection.
// #critique - another part of spec says "The outbox accepts HTTP POST requests". Does it also accept GET?
// If yet, clarify in other section; If not, what does it mean to 'be an OrderedCollection'
// (see isOrderedCollection function)
// #assumption - interpretation is that outbox MUST accept GET requests, so I'll test
tests["The outbox must be an OrderedCollection"] = async () => {
const res = await sendRequest(await requestForListener(distbin(), {
headers: activitypub.clientHeaders(),
path: "/activitypub/outbox",
}))
assert.equal(res.statusCode, 200)
const resBody = await readableToString(res)
assert(isOrderedCollection(resBody))
}
/*
#TODO
The outbox stream contains objects the user has published, subject to the ability of the requestor to retrieve
the object (that is, the contents of the outbox are filtered by the permissions of the person reading it).
#TODO assert that outbox collection object has '.items'
If a user submits a request without Authorization the server should respond with all of the Public posts.
This could potentially be all relevant objects published by the user, though the number of available items is
left to the discretion of those implementing and deploying the server.
#critique - "All of the public posts"? Or all of the public posts that have been sent through this outbox?
*/
// The outbox accepts HTTP POST requests, with behaviour described in Client to Server Interactions.
// see section 7
/*
5.6 Public Addressing - https://w3c.github.io/activitypub/#public-addressing
*/
tests["can request the public Collection"] = async () => {
const res = await sendRequest(await requestForListener(distbin(), "/activitypub/public"))
assert.equal(res.statusCode, 200)
}
// In addition to [ActivityStreams] collections and objects, Activities may additionally be addressed to the
// special "public" collection, with the identifier https://www.w3.org/ns/activitystreams#Public. For example:
// #critique: It would be helpful to show an example activity that is 'addressed to the public collection', as
// there aren't any currently in the spec
// Like... should the public collection id bein the 'to' or 'cc' or 'bcc' fields or does it matter?
tests["can address activities to the public Collection when sending to outbox, and they show up in the public" +
"Collection"] = async () => {
const distbinListener = distbin()
// post an activity addressed to public collection to outbox
const activityToPublic = {
"@context": "https://www.w3.org/ns/activitystreams",
"cc": ["https://www.w3.org/ns/activitystreams#Public"],
"object": "https://rhiaro.co.uk/2016/05/minimal-activitypub",
"type": "Like",
}
const postActivityRequest = await requestForListener(distbinListener, {
headers: activitypub.clientHeaders({
"content-type": ASJsonLdProfileContentType,
}),
method: "post",
path: "/activitypub/outbox",
})
postActivityRequest.write(JSON.stringify(activityToPublic))
const postActivityResponse = await sendRequest(postActivityRequest)
assert.equal(postActivityResponse.statusCode, 201)
// k it's been POSTed to outbox. Verify it's in the public collection
const publicCollectionResponse = await sendRequest(await requestForListener(distbinListener, "/activitypub/public"))
const publicCollection = JSON.parse(await readableToString(publicCollectionResponse))
// #critique ... ok so this is an example of where it's hard to know whether its in the Collection
// because of id generation and such
assert(publicCollection.totalItems > 0, "publicCollection has at least one item")
assert(
publicCollection.items.filter(
(a: Activity) => a.type === "Like" && a.object === "https://rhiaro.co.uk/2016/05/minimal-activitypub",
).length === 1,
"publicCollection contains the activity that targeted it")
}
/*
5.5 Inbox
The inbox is discovered through the inbox property of an actor's profile.
#TODO add .inbox with propert context to / JSON
*/
// The inbox must be an OrderedCollection.
tests["The inbox must be an OrderedCollection"] = async () => {
const res = await sendRequest(await requestForListener(distbin(), {
headers: activitypub.clientHeaders(),
path: "/activitypub/inbox",
}))
assert.equal(res.statusCode, 200)
const resBody = await readableToString(res)
assert(isOrderedCollection(resBody))
}
function isOrderedCollection(something: string|object) {
const obj = typeof something === "string" ? JSON.parse(something) : something
// #TODO: Assert that this is valid AS2. Ostensible 'must be an OrderedCollection' implies that
let type = obj.type
if (!Array.isArray(type)) { type = [type] }
assert(type.includes("OrderedCollection"))
return true
}
/*
The inbox stream contains all objects received by the user.
The server should filter content according to the requester's permission.
In general, the owner of an inbox is likely to be able to access all of their inbox contents.
Depending on access control, some other content may be public, whereas other content may require authentication
for non-owner users, if they can access the inbox at all.
The server must perform de-duplication of activities returned by the inbox.
Duplication can occur if an activity is addressed both to a user's followers, and a specific user who also follows
the recipient user, and the server has failed to de-duplicate the recipients list.
Such deduplication must be performed by comparing the id of the activities and dropping any activities already seen.
The inbox accepts HTTP POST requests, with behaviour described in Delivery.
*/
// 6 Binary Data - #TODO
// 7 Client to Server Interactions - https://w3c.github.io/activitypub/#client-to-server-interactions
// Example 6
// let article = {
// '@context': 'https://www.w3.org/ns/activitypub',
// 'id': 'https://rhiaro.co.uk/2016/05/minimal-activitypub',
// 'type': 'Article',
// 'name': 'Minimal ActivityPub update client',
// 'content': 'Today I finished morph, a client for posting ActivityStreams2...',
// 'attributedTo': 'https://rhiaro.co.uk/#amy',
// 'to': 'https://rhiaro.co.uk/followers/',
// 'cc': 'https://e14n.com/evan'
// }
// Example 7
// let likeOfArticle = {
// '@context': 'https://www.w3.org/ns/activitypub',
// 'type': 'Like',
// // #TODO: Fix bug where a comma was missing at end of here
// 'actor': 'https://dustycloud.org/chris/',
// 'name': "Chris liked 'Minimal ActivityPub update client'",
// 'object': 'https://rhiaro.co.uk/2016/05/minimal-activitypub',
// 'to': ['https://rhiaro.co.uk/#amy',
// 'https://dustycloud.org/followers',
// 'https://rhiaro.co.uk/followers/'],
// 'cc': 'https://e14n.com/evan'
// }
/*
To submit new Activities to a user's server, clients must discover the URL of the user's outbox from their profile
and then must make an HTTP POST request to to this URL with the Content-Type of
application/ld+json; profile="https://www.w3.org/ns/activitystreams".
#critique: no mention of application/activity+json even though it is the most correct mimetype of ActivityStreams
The request must be authenticated with the credentials of the user to whom the outbox belongs.
#critique - I think this is superfluous. Security could be out of band, e.g. through firewalls or other network
layers, or intentionally nonexistent. Instead of saying what the client MUST do, say that the server MAY require
authorization.
The body of the POST request must contain a single Activity (which may contain embedded objects), or a single
non-Activity object which will be wrapped in a Create activity by the server.
*/
// Example 8,9: Submitting an Activity to the Outbox
tests["can submit an Activity to the Outbox"] = async () => {
const distbinListener = distbin()
const req = await requestForListener(distbinListener, {
headers: activitypub.clientHeaders({
"content-type": ASJsonLdProfileContentType,
}),
method: "post",
path: "/activitypub/outbox",
})
req.write(JSON.stringify({
"@context": "https://www.w3.org/ns/activitypub",
"actor": "https://bengo.is/proxy/dustycloud.org/chris/", // #TODO fix that there was a missing comma here in spec
"name": "Chris liked 'Minimal ActivityPub update client'",
"object": "https://rhiaro.co.uk/2016/05/minimal-activitypub",
"type": "Like",
// 'to': ['https://dustycloud.org/followers', 'https://rhiaro.co.uk/followers/'],
// 'cc': 'https://e14n.com/evan'
}))
const postActivityRequest = await sendRequest(req)
// Servers MUST return a 201 Created HTTP code...
assert.equal(postActivityRequest.statusCode, 201)
// ...with the new URL in the Location header.
const location = first(postActivityRequest.headers.location)
assert(location, "Location header is present in response")
// #TODO assert its a URL
// #question - Does this imply any requirements about what happens when GET that URL?
// going to test that it's GETtable for now
const getActivityResponse = await sendRequest(await requestForListener(distbinListener, location))
assert.equal(getActivityResponse.statusCode, 200)
const newCreateActivity = JSON.parse(await readableToString(getActivityResponse))
assert.ok(newCreateActivity.id)
assert.ok(isProbablyAbsoluteUrl(newCreateActivity.id))
/*
If an Activity is submitted with a value in the id property, servers must ignore this and generate a new id for
the Activity.
#critique - noooo. It's better to block requests that already have IDs than ignore what the client sends. I
think a 409 Conflict or 400 Bad Request would be better.
#critique - If there *is not* an id, is the server supposed to generate one? Implied but not stated
Oh actually it is mentioned up on 3.1 "However, for client to server communication, a server receiving an
object with no specified id should allocate an object ID in the user's namespace and attach it to the posted
object.", but it's SHOULD not MUST. Regardless I think it would be easier for implementors if this were moved
from 3.1 to 7
#critique - ok last one. In 3.1 it says "Identifiers must be provided for activities posted in server to server
communication." How can a server tell if a request is coming from the server or the client? It's supposed to
always expect .ids from other servers, but it's supposed to ignore/rewrite all .ids from 'clients'.
In a federated thing like this every server is someone elses client, no? I think this is a blocking
inconsistency. Oh... maybe not. Is the heuristic here that 'servers' deliver to inboxes and 'clients' deliver
to outboxes?
#TODO - skipping for now. test later
*/
// The server adds this new Activity to the outbox collection. Depending on the type of Activity, servers may
// then be required to carry out further side effects.
// #TODO: Probably verify this by fetching the outbox collection. Keep in mind that tests all run in parallel
// right now so any assumption of isolation will be wrong.
// #critique - What's the best way to verify this, considering there is no requirement for the Activity POST
// response to include a representation, and another part of the spec currently says the server should ignore any
// .id provided by the client and set it's own. If the Client can provide its own ID, then it can instantly go in
// the outbox to verify something with that ID is there. If not, it first has to fetch the Location URL, see the
// ID, then look in the outbox and check for that ID. Eh. Ultimately not that crazy but I still feel strongly
// that bit about 'ignoring' the provided id and using a new one is really really bad.
}
// 7.1 Create Activity - https://w3c.github.io/activitypub/#create-activity-outbox
/*
The Create activity is used to when posting a new object. This has the side effect that the object embedded
within the Activity (in the object property) is created.
When a Create activity is posted, the actor of the activity should be copied onto the object's attributedTo field.
#critique like... at what stage of processing? And does .attributedTo always have to be included when the
activity is sent/retrieved later? And why is this so important? If it's required for logical consistency, maybe
the server should require the Client to submit activities that have attribution? It's odd for the server to
make tiny semantic adjustments to the representation provided by the client. Just be strict about what the
client must do.
A mismatch between addressing of the Create activity and its object is likely to lead to confusion. As such, a
server should copy any recipients of the Create activity to its object upon initial distribution, and likewise
with copying recipients from the object to the wrapping Create activity. Note that it is acceptable for the
object's addressing may be changed later without changing the Create's addressing (for example via an Update
activity).
# urgh, see #critique on previous line. Small little copying adjustments are weird and not-very REST because
they're changing what the client sent without telling it instead of just being strict about accepting what the
client sends. Can lead to ambiguity in client representation.
*/
tests["can submit a Create Activity to the Outbox"] = async () => {
const req = await requestForListener(distbin(), {
headers: activitypub.clientHeaders({
"content-type": ASJsonLdProfileContentType,
}),
method: "post",
path: "/activitypub/outbox",
})
req.write(JSON.stringify({
"@context": "https://www.w3.org/ns/activitypub",
"actor": "https://example.net/~mallory",
"id": "https://example.net/~mallory/87374", // #TODO: comma was missing here, fix in spec
"object": {
attributedTo: "https://example.net/~mallory",
content: "This is a note",
id: "https://example.com/~mallory/note/72",
published: "2015-02-10T15:04:55Z",
type: "Note",
// 'to': ['https://example.org/~john/'],
// 'cc': ['https://example.com/~erik/followers']
},
"published": "2015-02-10T15:04:55Z",
"type": "Create", // #TODO: comma was missing here, fix in spec
// 'to': ['https://example.org/~john/'],
// 'cc': ['https://example.com/~erik/followers']
}))
const res = await sendRequest(req)
// Servers MUST return a 201 Created HTTP code...
assert.equal(res.statusCode, 201)
}
// 7.1.1 Object creation without a Create Activity - https://w3c.github.io/activitypub/#object-without-create
/**
* For client to server posting, it is possible to create a new object without a surrounding activity.
* The server must accept a valid [ActivityStreams] object
* that isn't a subtype of Activity in the POST request to the outbox.
* #critique: Does this mean it should reject subtypes of Activities? No, right, because Activities are normal to
* send to outbox. Maybe then you're just saying that, if it's not an Activity subtype, initiate this
* 'Create-wrapping' algorithm.
*/
tests["can submit a non-Activity to the Outbox, and it is converted to a Create"] = async () => {
const distbinListener = distbin()
const req = await requestForListener(distbinListener, {
headers: activitypub.clientHeaders({
"content-type": ASJsonLdProfileContentType,
}),
method: "post",
path: "/activitypub/outbox",
})
// Example 10: Object with audience targeting
const example10 = {
"@context": "https://www.w3.org/ns/activitystreams",
"bcc": ["https://bengo.is/bcc"],
"cc": ["https://bengo.is/cc"],
"content": "This is a note",
"published": "2015-02-10T15:04:55Z",
"to": [activitypub.publicCollectionId],
"type": "Note",
}
req.write(JSON.stringify(example10))
const res = await sendRequest(req)
// Servers MUST return a 201 Created HTTP code...
assert.equal(res.statusCode, 201)
const newCreateActivityResponse = await sendRequest(
await requestForListener(distbinListener, first(res.headers.location)))
assert.equal(newCreateActivityResponse.statusCode, 200)
const newCreateActivity = JSON.parse(await readableToString(newCreateActivityResponse))
// The server then must attach this object as the object of a Create Activity.
assert.equal(newCreateActivity.type, "Create")
assert.ok("id" in newCreateActivity.object, "object.id was provisioned")
assert.notEqual(newCreateActivity.id, newCreateActivity.object.id)
const withoutProperties = (obj: object, withoutProps: string[]) => {
const lesserObj = Array.from(Object.entries(obj)).reduce((nextObj, [prop, val]) => {
if (!withoutProps.includes(prop)) { nextObj[prop] = val }
return nextObj
}, {} as {[key: string]: any})
return lesserObj
}
assert.deepEqual(withoutProperties(newCreateActivity.object, ["id"]), example10)
// The audience specified on the object must be copied over to the new Create activity by the server.
assert.deepEqual(newCreateActivity.to, example10.to)
assert.deepEqual(newCreateActivity.cc, example10.cc)
assert.deepEqual(newCreateActivity.bcc, example10.bcc)
}
/*
8.2 Delivery
An activity is delivered to its targets (which are actors) by first looking up the targets' inboxes and then posting
the activity to those inboxes.
The inbox property is determined by first retrieving the target actor's json-ld representation and then looking up
the inbox property.
An HTTP POST request (with authorization of the submitting user) is then made to to the inbox, with the Activity as
the body of the request.
This Activity is added by the receiver as an item in the inbox OrderedCollection.
For federated servers performing delivery to a 3rd party server, delivery should be performed asynchronously, and
should additionally retry delivery to recipients if it fails due to network error.
8.2.1 Outbox Delivery
When objects are received in the outbox, the server MUST target and deliver to:
The to, cc or bcc fields if their values are individuals, or Collections owned by the actor.
These fields will have been populated appropriately by the client which posted the Activity to the outbox.
*/
tests["targets and delivers targeted activities sent to Outbox"] = async () => {
// ok so we're going to make to distbins, A and B, and test that A delivers to B
const distbinA = distbin({ deliverToLocalhost: true })
const distbinB = distbin()
const distbinBUrl = await listen(http.createServer(distbinB))
// post an Activity to distbinA that has cc distbinB
const a = {
cc: distbinBUrl,
content: "Man, distbinB is really killing it today.",
type: "Note",
}
const postNoteRequest = await requestForListener(distbinA, {
headers: activitypub.clientHeaders({
"content-type": ASJsonLdProfileContentType,
}),
method: "post",
path: "/activitypub/outbox",
})
postNoteRequest.write(JSON.stringify(a))
const postNoteResponse = await sendRequest(postNoteRequest)
assert.equal(postNoteResponse.statusCode, 201)
// then verify that it is in distbinB's inbox
const distbinBInboxResponse = await sendRequest(http.get(distbinBUrl + "/activitypub/inbox"))
assert.equal(distbinBInboxResponse.statusCode, 200)
const distbinBInbox = JSON.parse(await readableToString(distbinBInboxResponse))
assert.equal(distbinBInbox.items.length, 1, "there is 1 item in distbin B inbox")
// Ensure that the activity has a URL that is absolute
// #todo this tests what comes out of the inbox but probably it's a more accurate test to verify what the /inbox
// *receives from distbinA (the receiver doesn't strictly need to be a distbinB, but any endpoint)
// #todo resolvable via @context.@base (https://www.w3.org/TR/json-ld/#base-iri) would also be fine, but not using
// right now. can check later.
assert(isProbablyAbsoluteUrl(distbinBInbox.items[0].url), ".url should be an absolute url")
}
tests["does not deliver to localhost"] = async () => {
// ok so we're going to make to distbins, A and B, and test that A delivers to B
const distbinA = distbin({ deliverToLocalhost: false })
const distbinB = distbin({ deliverToLocalhost: false })
const distbinBUrl = await listen(http.createServer(distbinB))
// post an Activity to distbinA that has cc distbinB
const a = {
cc: distbinBUrl,
content: "Man, distbinB is really killing it today.",
type: "Note",
}
const postNoteRequest = await requestForListener(distbinA, {
headers: activitypub.clientHeaders({
"content-type": ASJsonLdProfileContentType,
}),
method: "post",
path: "/activitypub/outbox",
})
postNoteRequest.write(JSON.stringify(a))
const postNoteResponse = await sendRequest(postNoteRequest)
assert.equal(postNoteResponse.statusCode, 201)
const noteResponse = await sendRequest(await requestForListener(distbinA, {
path: first(postNoteResponse.headers.location),
}))
const noteActivity = JSON.parse(await readableToString(noteResponse))
const inboxDeliveryFailures = noteActivity["distbin:activityPubDeliveryFailures"]
assert(inboxDeliveryFailures.length >= 1)
// 'distbin:activityPubDeliveryFailures': [ { name: 'Error', message: 'I will not deliver to localhost' } ],
assert(inboxDeliveryFailures.some((failure: { name: string, message: string }) =>
failure.message.includes("server:security-considerations:do-not-post-to-localhost")))
// then verify that it is in distbinB's inbox
const distbinBInboxResponse = await sendRequest(http.get(distbinBUrl + "/activitypub/inbox"))
assert.equal(distbinBInboxResponse.statusCode, 200)
const distbinBInbox = JSON.parse(await readableToString(distbinBInboxResponse))
assert.equal(distbinBInbox.items.length, 0, "there is 0 item in distbin B inbox")
}
/*
8.2.2 Inbox Delivery
When Activities are received in the inbox, the server needs to forward these to recipients that the origin was
unable to deliver them to.
To do this, the server must target and deliver to the values of to, cc and/or bcc if and only if all of the
following are true:
This is the first time the server has seen this Activity.
The values of to, cc and/or bcc contain a Collection owned by the server.
The values of inReplyTo, object, target and/or tag are objects owned by the server. The server should recurse
through these values to look for linked objects owned by the server, and should set a maximum limit for recursion
(ie. the point at which the thread is so deep the recipients followers may not mind if they are no longer getting
updates that don't directly involve the recipient). The server must only target the values of to, cc and/or bcc on
the original object being forwarded, and not pick up any new addressees whilst recursing through the linked objects
(in case these addressees were purposefully amended by or via the client).
The server may filter its delivery targets according to implementation-specific rules, for example, spam filtering.
*/
if (require.main === module) {
testCli(tests)
} | the_stack |
import { deployWalletContext } from './utils/deploy-wallet-context'
import { CallReceiverMock, HookCallerMock } from '@0xsequence/wallet-contracts'
import { Wallet } from '@0xsequence/wallet'
import { LocalRelayer } from '@0xsequence/relayer'
import { WalletContext, Networks, NetworkConfig } from '@0xsequence/network'
import { JsonRpcProvider } from '@ethersproject/providers'
import { ethers, Signer as AbstractSigner } from 'ethers'
import chaiAsPromised from 'chai-as-promised'
import * as chai from 'chai'
const CallReceiverMockArtifact = require('@0xsequence/wallet-contracts/artifacts/contracts/mocks/CallReceiverMock.sol/CallReceiverMock.json')
const HookCallerMockArtifact = require('@0xsequence/wallet-contracts/artifacts/contracts/mocks/HookCallerMock.sol/HookCallerMock.json')
const { expect } = chai.use(chaiAsPromised)
import { computeMetaTxnHash, encodeNonce } from '@0xsequence/transactions'
type EthereumInstance = {
chainId?: number
providerUrl?: string,
provider?: JsonRpcProvider
signer?: AbstractSigner
}
describe('Wallet integration', function () {
const ethnode: EthereumInstance = {}
let relayer: LocalRelayer
let callReceiver: CallReceiverMock
let hookCaller: HookCallerMock
let context: WalletContext
let networks: Networks
before(async () => {
// Provider from hardhat without a server instance
ethnode.providerUrl = `http://localhost:9547/`
ethnode.provider = new ethers.providers.JsonRpcProvider(ethnode.providerUrl)
ethnode.signer = ethnode.provider.getSigner()
ethnode.chainId = 31337
// Deploy local relayer
relayer = new LocalRelayer(ethnode.signer)
networks = [{
name: 'local',
chainId: ethnode.chainId,
provider: ethnode.provider,
isDefaultChain: true,
isAuthChain: true,
relayer: relayer
}] as NetworkConfig[]
// Deploy Sequence env
const [
factory,
mainModule,
mainModuleUpgradable,
guestModule,
sequenceUtils,
requireFreshSigner
] = await deployWalletContext(ethnode.provider)
// Create fixed context obj
context = {
factory: factory.address,
mainModule: mainModule.address,
mainModuleUpgradable: mainModuleUpgradable.address,
guestModule: guestModule.address,
sequenceUtils: sequenceUtils.address,
libs: {
requireFreshSigner: requireFreshSigner.address
}
}
// Deploy call receiver mock
callReceiver = (await new ethers.ContractFactory(
CallReceiverMockArtifact.abi,
CallReceiverMockArtifact.bytecode,
ethnode.signer
).deploy()) as CallReceiverMock
// Deploy hook caller mock
hookCaller = (await new ethers.ContractFactory(
HookCallerMockArtifact.abi,
HookCallerMockArtifact.bytecode,
ethnode.signer
).deploy()) as HookCallerMock
})
describe("Waiting for receipts", () => {
[{
name: "deployed",
deployed: true
}, {
name: "undeployed",
deployed: false
}].map((c) => {
var wallet: Wallet
beforeEach(async () => {
wallet = (await Wallet.singleOwner(ethers.Wallet.createRandom(), context)).connect(networks[0].provider, relayer)
if (c.deployed) await relayer.deployWallet(wallet.config, wallet.context)
expect(await wallet.isDeployed()).to.equal(c.deployed)
})
describe(`For ${c.name} wallet`, () => {
it("Should get receipt of success transaction", async () => {
const txn = {
to: ethers.Wallet.createRandom().address,
data: ethers.utils.randomBytes(43),
delegateCall: false,
revertOnError: false,
gasLimit: 140000,
value: 0,
nonce: 0
}
const id = computeMetaTxnHash(wallet.address, ethnode.chainId, txn)
const receiptPromise = relayer.wait(id, 10000)
await new Promise(r => setTimeout(r, 1000))
const ogtx = await wallet.sendTransaction(txn)
const receipt = await receiptPromise
expect(receipt).to.not.be.undefined
expect(receipt.hash).to.equal(ogtx.hash)
})
it("Should get receipt of success batch transaction", async () => {
const txns = [{
to: ethers.Wallet.createRandom().address,
data: ethers.utils.randomBytes(43),
delegateCall: false,
revertOnError: false,
gasLimit: 140000,
value: 0,
nonce: 0
}, {
to: ethers.Wallet.createRandom().address,
data: ethers.utils.randomBytes(43),
delegateCall: false,
revertOnError: false,
gasLimit: 140000,
value: 0,
nonce: 0
}]
const id = computeMetaTxnHash(wallet.address, ethnode.chainId, ...txns)
const receiptPromise = relayer.wait(id, 10000)
await new Promise(r => setTimeout(r, 1000))
const ogtx = await wallet.sendTransaction(txns)
const receipt = await receiptPromise
expect(receipt).to.not.be.undefined
expect(receipt.hash).to.equal(ogtx.hash)
})
it("Should get receipt of batch transaction with failed meta-txs", async () => {
const txns = [{
to: ethers.Wallet.createRandom().address,
data: ethers.utils.randomBytes(43),
delegateCall: false,
revertOnError: false,
gasLimit: 140000,
value: 0,
nonce: 0
}, {
to: context.factory,
// 0xff not a valid factory method
data: "0xffffffffffff",
delegateCall: false,
revertOnError: false,
gasLimit: 140000,
value: 0,
nonce: 0
}]
const id = computeMetaTxnHash(wallet.address, ethnode.chainId, ...txns)
const receiptPromise = relayer.wait(id, 10000)
await new Promise(r => setTimeout(r, 1000))
const ogtx = await wallet.sendTransaction(txns)
const receipt = await receiptPromise
expect(receipt).to.not.be.undefined
expect(receipt.hash).to.equal(ogtx.hash)
})
it("Should get receipt of failed transaction", async () => {
const txn = {
to: context.factory,
// 0xff not a valid factory method
data: "0xffffffffffff",
delegateCall: false,
revertOnError: false,
gasLimit: 140000,
value: 0,
nonce: 0
}
const id = computeMetaTxnHash(wallet.address, ethnode.chainId, txn)
const receiptPromise = relayer.wait(id, 10000)
await new Promise(r => setTimeout(r, 1000))
const ogtx = await wallet.sendTransaction(txn)
const receipt = await receiptPromise
expect(receipt).to.not.be.undefined
expect(receipt.hash).to.equal(ogtx.hash)
})
it("Find correct receipt between multiple other transactions", async () => {
// Pre-txs
const altWallet = (await Wallet.singleOwner(ethers.Wallet.createRandom(), context)).connect(networks[0].provider, relayer)
await relayer.deployWallet(altWallet.config, altWallet.context)
expect(await altWallet.isDeployed()).to.equal(true)
await Promise.all(new Array(8).fill(0).map(async (_, i) => {
await altWallet.sendTransaction({
to: ethers.Wallet.createRandom().address,
data: ethers.utils.randomBytes(43),
delegateCall: false,
revertOnError: false,
gasLimit: 140000,
value: 0,
nonce: encodeNonce(i, 0)
})
}))
const txn = {
to: ethers.Wallet.createRandom().address,
data: ethers.utils.randomBytes(43),
delegateCall: false,
revertOnError: false,
gasLimit: 140000,
value: 0,
nonce: 0
}
const id = computeMetaTxnHash(wallet.address, ethnode.chainId, txn)
const receiptPromise = relayer.wait(id, 10000)
await new Promise(r => setTimeout(r, 1000))
const ogtx = await wallet.sendTransaction(txn)
// Post-txs
await Promise.all(new Array(8).fill(0).map(async (_, i) => {
await altWallet.sendTransaction({
to: ethers.Wallet.createRandom().address,
data: ethers.utils.randomBytes(43),
delegateCall: false,
revertOnError: false,
gasLimit: 140000,
value: 0,
nonce: encodeNonce(i + 1000, 0)
})
}))
const receipt = await receiptPromise
expect(receipt).to.not.be.undefined
expect(receipt.hash).to.equal(ogtx.hash)
})
it("Find correct receipt between multiple other failed transactions", async () => {
// Pre-txs
const altWallet = (await Wallet.singleOwner(ethers.Wallet.createRandom(), context)).connect(networks[0].provider, relayer)
await relayer.deployWallet(altWallet.config, altWallet.context)
expect(await altWallet.isDeployed()).to.equal(true)
await Promise.all(new Array(8).fill(0).map(async (_, i) => {
await altWallet.sendTransaction({
to: ethers.Wallet.createRandom().address,
data: ethers.utils.randomBytes(43),
delegateCall: false,
revertOnError: false,
gasLimit: 140000,
value: 0,
nonce: encodeNonce(i, 0)
})
}))
await Promise.all(new Array(8).fill(0).map(async (_, i) => {
await altWallet.sendTransaction({
to: context.factory,
// 0xff not a valid factory method
data: "0xffffffffffff",
delegateCall: false,
revertOnError: false,
gasLimit: 140000,
value: 0,
nonce: encodeNonce(i + 1000, 0)
})
}))
const txn = {
to: ethers.Wallet.createRandom().address,
data: ethers.utils.randomBytes(43),
delegateCall: false,
revertOnError: false,
gasLimit: 140000,
value: 0,
nonce: 0
}
const id = computeMetaTxnHash(wallet.address, ethnode.chainId, txn)
const receiptPromise = relayer.wait(id, 10000)
await new Promise(r => setTimeout(r, 1000))
const ogtx = await wallet.sendTransaction(txn)
const receipt = await receiptPromise
expect(receipt).to.not.be.undefined
expect(receipt.hash).to.equal(ogtx.hash)
})
it("Find failed tx receipt between multiple other failed transactions", async () => {
// Pre-txs
const altWallet = (await Wallet.singleOwner(ethers.Wallet.createRandom(), context)).connect(networks[0].provider, relayer)
await relayer.deployWallet(altWallet.config, altWallet.context)
expect(await altWallet.isDeployed()).to.equal(true)
await Promise.all(new Array(8).fill(0).map(async (_, i) => {
await altWallet.sendTransaction({
to: ethers.Wallet.createRandom().address,
data: ethers.utils.randomBytes(43),
delegateCall: false,
revertOnError: false,
gasLimit: 140000,
value: 0,
nonce: encodeNonce(i, 0)
})
}))
await Promise.all(new Array(8).fill(0).map(async (_, i) => {
await altWallet.sendTransaction({
to: context.factory,
// 0xff not a valid factory method
data: "0xffffffffffff",
delegateCall: false,
revertOnError: false,
gasLimit: 140000,
value: 0,
nonce: encodeNonce(i + 1000, 0)
})
}))
const txn = {
to: context.factory,
// 0xff not a valid factory method
data: "0xffffffffffff",
delegateCall: false,
revertOnError: false,
gasLimit: 140000,
value: 0,
nonce: 0
}
const id = computeMetaTxnHash(wallet.address, ethnode.chainId, txn)
const receiptPromise = relayer.wait(id, 10000)
await new Promise(r => setTimeout(r, 1000))
const ogtx = await wallet.sendTransaction(txn)
const receipt = await receiptPromise
expect(receipt).to.not.be.undefined
expect(receipt.hash).to.equal(ogtx.hash)
})
it("Should timeout receipt if transaction is never sent", async () => {
const txn = {
to: ethers.Wallet.createRandom().address,
data: ethers.utils.randomBytes(43),
delegateCall: false,
revertOnError: false,
gasLimit: 140000,
value: 0,
nonce: 0
}
const id = computeMetaTxnHash(wallet.address, ethnode.chainId, txn)
const receiptPromise = relayer.wait(id, 2000)
await expect(receiptPromise).to.be.rejectedWith(`Timeout waiting for transaction receipt ${id}`)
})
if (c.deployed) {
it("Find correct receipt between multiple other failed transactions of the same wallet", async () => {
// Pre-txs
await Promise.all(new Array(8).fill(0).map(async (_, i) => {
await wallet.sendTransaction({
to: ethers.Wallet.createRandom().address,
data: ethers.utils.randomBytes(43),
delegateCall: false,
revertOnError: false,
gasLimit: 140000,
value: 0,
nonce: encodeNonce(i + 1000, 0)
})
}))
await Promise.all(new Array(8).fill(0).map(async (_, i) => {
await wallet.sendTransaction({
to: context.factory,
// 0xff not a valid factory method
data: "0xffffffffffff",
delegateCall: false,
revertOnError: false,
gasLimit: 140000,
value: 0,
nonce: encodeNonce(i + 2000, 0)
})
}))
const txn = {
to: ethers.Wallet.createRandom().address,
data: ethers.utils.randomBytes(43),
delegateCall: false,
revertOnError: false,
gasLimit: 140000,
value: 0,
nonce: 0
}
const id = computeMetaTxnHash(wallet.address, ethnode.chainId, txn)
const receiptPromise = relayer.wait(id, 10000)
await new Promise(r => setTimeout(r, 1000))
const ogtx = await wallet.sendTransaction(txn)
const receipt = await receiptPromise
expect(receipt).to.not.be.undefined
expect(receipt.hash).to.equal(ogtx.hash)
})
}
})
})
})
}) | the_stack |
import { useState, useEffect, useRef } from 'react'
import { useStore, Storage } from 'stook'
import gql from 'graphql-tag'
import compose from 'koa-compose'
import { produce } from 'immer'
import { GraphQLClient } from '@peajs/graphql-client'
import { SubscriptionClient } from 'subscriptions-transport-ws'
import isEqual from 'react-fast-compare'
import { fetcher } from './fetcher'
import {
Options,
RefetchOptions,
QueryResult,
FetcherItem,
Middleware,
GraphqlOptions,
MutateResult,
Variables,
SubscribeResult,
SubscriptionOption,
FromSubscriptionOption,
Observer,
Start,
} from './types'
import {
getDeps,
getVariables,
getDepsMaps,
useUnmounted,
useUnmount,
isResolve,
getOperationName,
} from './utils'
interface VarCurrent {
value: any
resolve: boolean
}
interface DepsCurrent {
value: any
resolve: boolean
}
const NULL_AS: any = null
export class Context {
headers: Record<string, string> = {}
body: any = undefined
valid: boolean = true
}
export class Client {
graphqlOptions: GraphqlOptions
middleware: Middleware[] = []
graphqlClient: GraphQLClient = NULL_AS
subscriptionClient: SubscriptionClient = NULL_AS
constructor(opt: GraphqlOptions = { endpoint: '/graphql', headers: {} }) {
const { endpoint, headers, subscriptionsEndpoint } = opt
this.graphqlOptions = opt
this.graphqlClient = new GraphQLClient(endpoint, {
headers,
} as any)
if (subscriptionsEndpoint) {
this.subscriptionClient = new SubscriptionClient(subscriptionsEndpoint, {
reconnect: true,
})
}
}
config = (opt: GraphqlOptions = { endpoint: '/graphql', headers: {} }) => {
this.graphqlOptions = { ...this.graphqlOptions, ...opt }
const { endpoint, headers, subscriptionsEndpoint } = opt
this.graphqlClient = new GraphQLClient(endpoint, { headers } as any)
if (subscriptionsEndpoint) {
this.subscriptionClient = new SubscriptionClient(subscriptionsEndpoint, {
reconnect: true,
})
}
}
applyMiddleware = (fn: Middleware) => {
this.middleware.push(fn)
}
query = async <T = any>(input: string, options: Options = {}): Promise<T> => {
const context = new Context()
const { variables = {}, endpoint } = options
const opt: any = {}
if (options.headers) {
opt.headers = options.headers
}
const action = async (ctx: Context) => {
const queryOpt = {
...opt,
headers: { ...(opt.headers || {}), ...(ctx.headers || {}) },
}
if (endpoint) queryOpt.endpoint = endpoint
try {
ctx.body = await this.graphqlClient.query<T>(input, variables, queryOpt)
} catch (error) {
ctx.body = error
ctx.valid = false
}
}
// TODO: get req headers
await compose([...this.middleware])(context)
// call requerst
await compose([...this.middleware, action])(context)
if (!context.valid) {
throw context.body
}
return context.body as T
}
useQuery = <T = any, V = Variables>(input: string, options: Options<T, V> = {}) => {
const isUnmouted = useUnmounted()
const { initialData: data, onUpdate, lazy = false, pollInterval } = options
const fetcherName = options.key || input
const initialState = { loading: true, data } as QueryResult<T>
const deps = getDeps(options)
const [result, setState] = useStore(fetcherName, initialState)
//是否应该立刻开始发送请求
const [shouldStart, setShouldStart] = useState(!lazy)
const update = (nextState: QueryResult<T>) => {
setState(nextState)
onUpdate && onUpdate(nextState)
}
const makeFetch = async (opt: RefetchOptions<T, V> = {}): Promise<any> => {
const key = opt.key ?? fetcherName
try {
if (fetcher.get(key)) fetcher.get(key).called = true
const resData = await this.query<T>(input, opt || {})
const nextState = produce(result, (draft: any) => {
draft.loading = false
if (opt.setData && typeof opt.setData === 'function') {
opt.setData(draft.data, resData)
} else {
draft.data = resData
}
})
update(nextState)
return resData
} catch (error) {
update({ loading: false, error } as QueryResult<T>)
// throw error
}
}
/**
*
* @param opt
* @return 返回类型为 data,也就是 T
*/
const refetch = async (opt: RefetchOptions<T, V> = {}): Promise<T> => {
const key = opt.key ?? fetcherName
let showLoading = true
if (typeof opt.showLoading === 'boolean' && opt.showLoading === false) {
showLoading = false
}
if (showLoading) {
update({ loading: true } as QueryResult<T>)
}
function getRefechVariables(opt: RefetchOptions<T, V> = {}): any {
const fetcherVariables: any = fetcher.get(key).variables
// TODO: handle any
const variables: any = opt.variables
if (!variables) {
return fetcherVariables || {}
}
if (typeof variables === 'function') {
return variables(fetcherVariables)
}
return opt.variables
}
opt.variables = getRefechVariables(opt)
// store variables to fetcher
fetcher.get(key).variables = opt.variables
const data: T = (await makeFetch(opt)) as any
return data
}
// TODO: 要确保 variable resolve
const start: Start = (): any => {
setShouldStart(true)
}
/**
* handle variable
*/
const variables = getVariables(options)
const varRef = useRef<VarCurrent>({
value: getVariables(options),
resolve: isResolve(options.variables),
})
if (!varRef.current.resolve && getVariables(options)) {
varRef.current = { value: variables, resolve: true }
}
// 轮询
const timerRef = useRef<any>()
useEffect(() => {
// store refetch fn to fetcher
if (!fetcher.get(fetcherName)) {
fetcher.set(fetcherName, { refetch, called: false } as FetcherItem<T>)
}
// if resolve, 说明已经拿到最终的 variables
const shouldFetch =
varRef.current.resolve && !fetcher.get(fetcherName).called && !isUnmouted() && shouldStart
if (shouldFetch) {
// store variables to fetcher
fetcher.get(fetcherName).variables = varRef.current.value
// make http request
makeFetch({ ...options, variables: varRef.current.value })
if (pollInterval && !fetcher.get(fetcherName).polled) {
fetcher.get(fetcherName).polled = true
/** pollInterval */
timerRef.current = setInterval(() => {
makeFetch({ ...options, variables: varRef.current.value })
}, pollInterval)
}
}
return () => {
if (timerRef.current) {
clearInterval(timerRef.current)
fetcher.get(fetcherName).polled = false
}
}
// eslint-disable-next-line
}, [varRef.current, shouldStart])
/**
* handle deps
*/
const depsMaps = getDepsMaps(deps)
const depsRef = useRef<DepsCurrent>({ value: depsMaps, resolve: false })
if (!isEqual(depsRef.current.value, depsMaps)) {
depsRef.current = { value: depsMaps, resolve: true }
}
useEffect(() => {
if (depsRef.current.resolve) {
update({ loading: true } as QueryResult<T>)
makeFetch({ ...options, variables: varRef.current.value })
}
// eslint-disable-next-line
}, [depsRef.current])
/** pollInterval */
useEffect(() => {
if (pollInterval && !fetcher.get(fetcherName).polled) {
fetcher.get(fetcherName).polled = true
const timer = setInterval(() => {
makeFetch({ ...options, variables: varRef.current.value })
}, pollInterval)
return () => {
clearInterval(timer)
}
}
return () => {}
}, [])
// when unmount
useUnmount(() => {
// 全部 unmount,设置 called false
const store = Storage.get(fetcherName)
// 对应的 hooks 全部都 unmount 了
if (store && store.setters.length === 0) {
// 重新设置为 false,以便后续调用刷新
fetcher.get(fetcherName).called = false
// TODO: 要为true ? 还是 undefined 好
update({ loading: true } as any)
}
})
const called = fetcher.get(fetcherName) && fetcher.get(fetcherName).called
return { ...result, refetch, start, called }
}
useMutation = <T = any, V = Variables>(input: string, options: Options = {}) => {
const { initialData: data, onUpdate } = options
const initialState = { data, called: false } as MutateResult<T>
const fetcherName = options.key || input
const [result, setState] = useStore<MutateResult<T>>(fetcherName, initialState)
const update = (nextState: MutateResult<T>) => {
setState(nextState)
onUpdate && onUpdate(nextState)
}
const makeFetch = async (opt: Options = {}): Promise<any> => {
try {
const data = await this.query<T>(input, { ...options, ...opt })
update({ loading: false, called: true, data } as MutateResult<T>)
return data
} catch (error) {
update({ loading: false, called: true, error } as MutateResult<T>)
// throw error
}
}
const mutate = async (variables: V, opt: Options = {}): Promise<T> => {
update({ loading: true } as MutateResult<T>)
return (await makeFetch({ ...opt, variables })) as T
}
return [mutate, result] as [(variables: V, opt?: Options) => Promise<T>, MutateResult<T>]
}
useSubscription = <T = any>(input: string, options: SubscriptionOption<T> = {}) => {
const { variables = {}, operationName = '', initialQuery = '', onUpdate } = options
const unmounted = useRef(false)
const initialState = { loading: true } as SubscribeResult<T>
const [result, setState] = useState(initialState)
const context = new Context()
let unsubscribe: SubscribeResult<any>['unsubscribe'] = () => {}
function update(nextState: SubscribeResult<T>) {
setState(nextState)
onUpdate && onUpdate(nextState)
}
function updateInitialQuery(nextState: SubscribeResult<T>) {
setState(nextState)
if (options.initialQuery && options.initialQuery.onUpdate) {
options.initialQuery.onUpdate(nextState)
}
}
const initQuery = async () => {
if (!initialQuery) return
if (unmounted.current) return
try {
let data = await this.query<T>(initialQuery.query, {
variables: initialQuery.variables || {},
})
updateInitialQuery({ loading: false, data } as SubscribeResult<T>)
return data
} catch (error) {
updateInitialQuery({ loading: false, error } as SubscribeResult<T>)
return error
}
}
const initSubscribe = async () => {
if (unmounted.current) return
const node = gql`
${input}
`
const subResult = this.subscriptionClient
.request({
query: node,
variables,
operationName: getOperationName(input) || operationName,
})
.subscribe({
next: ({ data }) => {
const action = async (ctx: Context) => {
ctx.body = data
}
compose([...this.middleware, action])(context).then(() => {
update({ loading: false, data: context.body } as SubscribeResult<T>)
})
},
error: (error) => {
const action = async (ctx: Context) => {
ctx.body = error
ctx.valid = false
}
compose([...this.middleware, action])(context).then(() => {
update({ loading: false, error: context.body } as SubscribeResult<T>)
})
},
complete() {
console.log('completed')
},
})
unsubscribe = subResult.unsubscribe
}
useEffect(() => {
if (initialQuery) initQuery()
// TODO: 参照小程序
initSubscribe()
return () => {
unmounted.current = true
}
// eslint-disable-next-line
}, [])
return { ...result, unsubscribe }
}
fromSubscription = <T = any>(input: string, options: FromSubscriptionOption = {}) => {
const { variables = {} } = options
if (!this.subscriptionClient) {
throw new Error('require subscriptionsEndpoint config')
}
return {
subscribe: (observer: Observer<T>) => {
const ob = {} as Observer<T>
if (observer.next) {
ob.next = (data: T) => {
if (observer.next) observer.next(data)
}
}
if (observer.error) ob.error = observer.error
if (observer.error) ob.complete = observer.complete
return this.subscriptionClient
.request({
query: gql`
${input}
`,
variables,
})
.subscribe(ob as any) // TODO:
},
}
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.