@pega/cosmos-react-core 7.0.0-build.22.6 → 7.0.0-build.22.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"Banner.d.ts","sourceRoot":"","sources":["../../../src/components/Banner/Banner.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAmB,GAAG,EAAE,iBAAiB,EAAa,MAAM,OAAO,CAAC;AAKhF,OAAO,KAAK,EACV,YAAY,EACZ,UAAU,EACV,cAAc,EAGd,UAAU,EACV,cAAc,EACf,MAAM,aAAa,CAAC;AA+BrB,MAAM,WAAW,iBAAiB;IAChC,kEAAkE;IAClE,KAAK,EAAE,MAAM,IAAI,CAAC;CACnB;AAED,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,CAAC,EAAE;QACP,IAAI,EAAE,MAAM,CAAC;QACb,OAAO,CAAC,EAAE,iBAAiB,CAAC,iBAAiB,GAAG,iBAAiB,CAAC,CAAC;QACnE,IAAI,CAAC,EAAE,MAAM,CAAC;KACf,CAAC;IACF,KAAK,CAAC,EAAE,CAAC,aAAa,GAAG,MAAM,CAAC,EAAE,CAAC;CACpC;AAED,MAAM,MAAM,WAAW,GAAG,cAAc,CACtC,KAAK,EACL,UAAU,GACR,cAAc,GAAG;IACf,0CAA0C,CAAC,OAAO,EAAE,QAAQ,GAAG,SAAS,GAAG,SAAS,GAAG,MAAM,CAAC;IAC9F;;;OAGG;IACH,UAAU,CAAC,EAAE,UAAU,CAAC;IACxB,gEAAgE;IAChE,QAAQ,EAAE,CAAC,MAAM,GAAG,aAAa,CAAC,EAAE,CAAC;IACrC,0DAA0D;IAC1D,SAAS,CAAC,EAAE,iBAAiB,CAAC;IAC9B,4DAA4D;IAC5D,MAAM,CAAC,EAAE,GAAG,CAAC,iBAAiB,CAAC,CAAC;CACjC,CACJ,CA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AAC,EAAE,CAAC;IACrC,0DAA0D;IAC1D,SAAS,CAAC,EAAE,iBAAiB,CAAC;IAC9B,4DAA4D;IAC5D,MAAM,CAAC,EAAE,GAAG,CAAC,iBAAiB,CAAC,CAAC;CACjC,CACJ,CAAC;AAEF,eAAO,MAAM,YAAY;gBAA4B,WAAW,CAAC,YAAY,CAAC;SAY7E,CAAC;AAIF,eAAO,MAAM,kBAAkB,mIAiB7B,CAAC;AAIH,eAAO,MAAM,kBAAkB,yGAoB7B,CAAC;AAIH,eAAO,MAAM,mBAAmB;;SAW9B,CAAC;AAIH,eAAO,MAAM,uBAAuB,2KAMnC,CAAC;AAIF,eAAO,MAAM,mBAAmB,0GAG/B,CAAC;;;;AAoEF,wBA4JE"}
@@ -168,6 +168,6 @@ export default withTestIds(forwardRef(function Banner({ testId, variant, heading
168
168
  }), []);
169
169
  return (_jsxs(Grid, { "data-testid": testIds.root, ...restProps, as: StyledBanner, container: { cols: '2rem minmax(0, 1fr)' }, role: role, "aria-live": ariaLive, headingTag: headingTag, ref: bannerRef, children: [_jsx(Flex, { as: StyledBannerStatus, container: { justify: 'center', alignItems: 'start', pad: [1.5, 0] }, variant: variant, children: _jsx(Icon, { name: icon }) }), count === 1 ? (_jsxs(Flex, { container: { alignItems: 'start' }, as: StyledBannerContent, children: [_jsx(VisuallyHiddenText, { as: headingTag, children: `${heading} ${count}` }), _jsx(Flex, { item: { alignSelf: 'center', grow: 1 }, as: 'ul', children: typeof messages[0] === 'string' ? (_jsx(BannerMessageItem, { testId: testId, label: messages[0], as: 'li' })) : (_jsx(BannerMessageItem, { ...messages[0], testId: testId, as: 'li' })) }), onDismiss && (_jsx(Button, { "data-testid": testIds.dismiss, onClick: onDismiss, label: t('dismiss'), "aria-label": t('banner_dismiss_button_label_a11y'), variant: 'simple', icon: true, children: _jsx(Icon, { name: 'times' }) }))] })) : (_jsxs(StyledBannerContent, { expandable: true, children: [_jsxs(Grid, { as: StyledBannerHeader, container: { cols: 'auto 1fr auto', areas: '"toggle heading dismiss"', gap: 0.5 }, children: [_jsxs(Grid, { "data-testid": testIds.heading, container: { cols: 'min-content min-content', gap: 0.5, alignItems: 'center' }, item: { area: 'heading', alignSelf: 'center' }, as: Text, forwardedAs: headingTag, variant: 'h2', children: [heading, " ", _jsx(Count, { children: count })] }), _jsx(Grid, { item: { area: 'toggle', alignSelf: 'center' }, children: _jsx(Button, { "data-testid": testIds.expandCollapse, onClick: () => {
170
170
  setCollapsed(cur => !cur);
171
- }, label: t(collapsed ? 'expand' : 'collapse'), "aria-expanded": collapsed ? 'false' : 'true', variant: 'simple', icon: true, children: _jsx(Icon, { name: 'caret-right' }) }) }), _jsx(Grid, { item: { area: 'dismiss', alignSelf: 'center' }, children: onDismiss && (_jsx(Button, { "data-testid": testIds.dismiss, onClick: onDismiss, label: t('dismiss'), "aria-label": t('banner_dismiss_button_label_a11y'), variant: 'simple', icon: true, children: _jsx(Icon, { name: 'times' }) })) })] }), _jsx(ExpandCollapse, { collapsed: collapsed, children: _jsx(StyledBannerMessageList, { items: messagesToRender }) })] }))] }));
171
+ }, label: t(collapsed ? 'expand' : 'collapse'), "aria-label": t(collapsed ? 'expand_noun' : 'collapse_noun', [heading]), "aria-expanded": collapsed ? 'false' : 'true', variant: 'simple', icon: true, children: _jsx(Icon, { name: 'caret-right' }) }) }), _jsx(Grid, { item: { area: 'dismiss', alignSelf: 'center' }, children: onDismiss && (_jsx(Button, { "data-testid": testIds.dismiss, onClick: onDismiss, label: t('dismiss'), "aria-label": t('banner_dismiss_button_label_a11y'), variant: 'simple', icon: true, children: _jsx(Icon, { name: 'times' }) })) })] }), _jsx(ExpandCollapse, { collapsed: collapsed, children: _jsx(StyledBannerMessageList, { items: messagesToRender }) })] }))] }));
172
172
  }), getBannerTestIds);
173
173
  //# sourceMappingURL=Banner.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Banner.js","sourceRoot":"","sources":["../../../src/components/Banner/Banner.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,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AuB,IAAC,KAAK,EAAE,gBAAgB,GAAI,GACrC,IACG,CACvB,IACI,CACR,CAAC;AACJ,CAAC,CAAC,EACF,gBAAgB,CACjB,CAAC","sourcesContent":["import { useState, forwardRef, useMemo, useImperativeHandle } from 'react';\nimport type { PropsWithoutRef, Ref, MouseEventHandler, ReactNode } from 'react';\nimport styled, { css } from 'styled-components';\nimport { getContrast } from 'polished';\n\nimport { defaultThemeProp } from '../../theme';\nimport type {\n ForwardProps,\n HeadingTag,\n NoChildrenProp,\n OmitStrict,\n RefElement,\n TestIdProp,\n WithAttributes\n} from '../../types';\nimport Button, { StyledButton } from '../Button';\nimport { focusHeadingOrContainer, tryCatch, withTestIds } from '../../utils';\nimport { useConsolidatedRef, useDirection, useI18n, useTestIds } from '../../hooks';\nimport Flex from '../Flex';\nimport Text from '../Text';\nimport Grid from '../Grid';\nimport ExpandCollapse from '../ExpandCollapse';\nimport { Count } from '../Badges';\nimport Icon, { StyledIcon, registerIcon } from '../Icon';\nimport * as timesIcon from '../Icon/icons/times.icon';\nimport * as caretRightIcon from '../Icon/icons/caret-right.icon';\nimport * as warnSolidIcon from '../Icon/icons/warn-solid.icon';\nimport * as flagWaveSolidIcon from '../Icon/icons/flag-wave-solid.icon';\nimport * as informationSolidIcon from '../Icon/icons/information-solid.icon';\nimport * as checkIcon from '../Icon/icons/check.icon';\nimport VisuallyHiddenText from '../VisuallyHiddenText';\nimport { UnorderedList } from '../List';\nimport { readableColor } from '../../styles';\n\nimport { getBannerTestIds } from './Banner.test-ids';\n\nregisterIcon(\n timesIcon,\n caretRightIcon,\n warnSolidIcon,\n flagWaveSolidIcon,\n informationSolidIcon,\n checkIcon\n);\n\nexport interface BannerHandleValue {\n /** Used to apply focus to the banner via an imperative handle. */\n focus: () => void;\n}\n\nexport interface BannerMessage {\n label: string;\n description?: string;\n action?: {\n text: string;\n onClick?: MouseEventHandler<HTMLButtonElement | HTMLAnchorElement>;\n href?: string;\n };\n items?: (BannerMessage | string)[];\n}\n\nexport type BannerProps = WithAttributes<\n 'div',\n TestIdProp &\n NoChildrenProp & {\n /** Controls the styling of the Banner. */ variant: 'urgent' | 'warning' | 'success' | 'info';\n /**\n * The heading tag to render the provided heading as. This is agnostic to the styling of the heading.\n * @default 'h2'\n */\n headingTag?: HeadingTag;\n /** Pass one or more descriptive messages to inform the user. */\n messages: (string | BannerMessage)[];\n /** Callback when user explicitly dismisses the Banner. */\n onDismiss?: MouseEventHandler;\n /** Ref that can be used to access the imperative handle. */\n handle?: Ref<BannerHandleValue>;\n }\n>;\n\nexport const StyledBanner = styled.div<{ headingTag: BannerProps['headingTag'] }>(\n ({ headingTag, theme }) => {\n return css`\n border-radius: ${theme.components.card['border-radius']};\n min-inline-size: 100%;\n inline-size: 0;\n\n &:has(${headingTag}:focus) {\n box-shadow: ${theme.base.shadow.focus};\n }\n `;\n }\n);\n\nStyledBanner.defaultProps = defaultThemeProp;\n\nexport const StyledBannerStatus = styled.div<Pick<BannerProps, 'variant'>>(({ variant, theme }) => {\n const { background } = theme.components.banner[variant];\n const color = tryCatch(() =>\n getContrast(background, theme.base.palette['primary-background']) >= 3\n ? theme.base.palette['primary-background']\n : readableColor(background)\n );\n\n return css`\n background-color: ${background};\n color: ${color};\n border-start-start-radius: inherit;\n border-end-start-radius: inherit;\n border: 0.0625rem solid ${theme.base.palette['border-line']};\n border-inline-end: none;\n font-size: 1.25rem;\n `;\n});\n\nStyledBannerStatus.defaultProps = defaultThemeProp;\n\nexport const StyledBannerHeader = styled.div(({ theme }) => {\n const { rtl } = useDirection();\n\n return css`\n min-height: 2.125rem;\n\n ${StyledButton}[aria-expanded] {\n ${StyledIcon} {\n transition: rotate ${theme.base.animation.speed} ${theme.base.animation.timing.ease};\n }\n\n &[aria-expanded='true'] ${StyledIcon} {\n rotate: 90deg;\n }\n\n &[aria-expanded='false'] ${StyledIcon} {\n rotate: ${rtl ? 180 : 0}deg;\n }\n }\n `;\n});\n\nStyledBannerHeader.defaultProps = defaultThemeProp;\n\nexport const StyledBannerContent = styled.div<{ expandable?: boolean }>(({ expandable, theme }) => {\n return css`\n background: ${theme.components.card.background};\n padding-block: calc(0.5 * ${theme.base.spacing});\n padding-inline-start: calc(${expandable ? 0.5 : 2} * ${theme.base.spacing});\n padding-inline-end: calc(0.5 * ${theme.base.spacing});\n border: 0.0625rem solid ${theme.base.palette['border-line']};\n border-inline-start: none;\n border-start-end-radius: inherit;\n border-end-end-radius: inherit;\n `;\n});\n\nStyledBannerContent.defaultProps = defaultThemeProp;\n\nexport const StyledBannerMessageList = styled(UnorderedList)(\n ({ theme }) => css`\n padding-block-end: calc(0.5 * ${theme.base.spacing});\n padding-inline-start: calc(5 * ${theme.base.spacing});\n padding-inline-end: calc(2 * ${theme.base.spacing});\n `\n);\n\nStyledBannerMessageList.defaultProps = defaultThemeProp;\n\nexport const StyledBannerMessage = styled.span`\n overflow-wrap: break-word;\n list-style: none;\n`;\n\nStyledBannerMessage.defaultProps = defaultThemeProp;\n\nconst BannerMessageItem = forwardRef<\n HTMLLIElement,\n TestIdProp & OmitStrict<BannerMessage, 'items'> & ForwardProps\n>(function BannerMessageItem({ testId, label, description, action, ...restProps }, ref) {\n const testIds = useTestIds(testId, getBannerTestIds);\n\n return (\n <StyledBannerMessage {...restProps} ref={ref}>\n <span data-testid={testIds.messageLabel}>{label}</span>\n {description && (\n <>\n {' '}\n <Text data-testid={testIds.messageDescription} variant='secondary'>\n {description}\n </Text>\n </>\n )}\n {action && (\n <>\n {' '}\n <Text variant='secondary'>\n <Button\n data-testid={testIds.messageAction}\n variant='link'\n href={action.href}\n onClick={action.onClick}\n {...action}\n >\n {action.text}\n </Button>\n </Text>\n </>\n )}\n </StyledBannerMessage>\n );\n});\n\nconst prepareMessages = (\n messages: (string | BannerMessage)[],\n testId: TestIdProp['testId']\n): [messages: ReactNode[], count: number] => {\n let count = 0;\n\n return [\n messages.flatMap(msg => {\n count += 1;\n\n if (typeof msg === 'string') {\n return [<BannerMessageItem label={msg} />];\n }\n\n if (msg.items) {\n const { items, ...restMsg } = msg;\n const [subMessages, subCount] = prepareMessages(items, testId);\n count += subCount;\n return [<BannerMessageItem {...restMsg} testId={testId} />, subMessages];\n }\n\n return [<BannerMessageItem {...msg} testId={testId} />];\n }),\n count\n ];\n};\n\nexport default withTestIds(\n forwardRef<RefElement<BannerProps>, PropsWithoutRef<BannerProps>>(function Banner(\n { testId, variant, headingTag = 'h2', messages, onDismiss, handle, ...restProps },\n ref\n ) {\n const testIds = useTestIds(testId, getBannerTestIds);\n const [messagesToRender, count] = useMemo(() => prepareMessages(messages, testId), [messages]);\n const t = useI18n();\n const [collapsed, setCollapsed] = useState(count > 2);\n\n const bannerRef = useConsolidatedRef(ref);\n\n let role: string;\n let icon: string;\n let heading: string;\n let ariaLive: string;\n\n switch (variant) {\n case 'urgent':\n heading = t('error');\n icon = 'warn-solid';\n role = 'alert';\n ariaLive = 'assertive';\n break;\n case 'warning':\n heading = t('warning');\n icon = 'flag-wave-solid';\n role = 'alert';\n ariaLive = 'assertive';\n break;\n case 'success':\n heading = t('success');\n icon = 'check';\n role = 'none';\n ariaLive = 'polite';\n break;\n case 'info':\n default:\n heading = t('information');\n icon = 'information-solid';\n role = 'none';\n ariaLive = 'polite';\n break;\n }\n\n useImperativeHandle(\n handle,\n () => ({\n focus: () => {\n // Empty timeout ensures that the banner will take focus after any other programmatic focus events\n setTimeout(() => {\n if (bannerRef.current) {\n focusHeadingOrContainer(bannerRef.current, heading);\n }\n });\n }\n }),\n []\n );\n\n return (\n <Grid\n data-testid={testIds.root}\n {...restProps}\n as={StyledBanner}\n container={{ cols: '2rem minmax(0, 1fr)' }}\n role={role}\n aria-live={ariaLive}\n headingTag={headingTag}\n ref={bannerRef}\n >\n <Flex\n as={StyledBannerStatus}\n container={{ justify: 'center', alignItems: 'start', pad: [1.5, 0] }}\n variant={variant}\n >\n <Icon name={icon} />\n </Flex>\n {count === 1 ? (\n <Flex container={{ alignItems: 'start' }} as={StyledBannerContent}>\n <VisuallyHiddenText as={headingTag}>{`${heading} ${count}`}</VisuallyHiddenText>\n <Flex item={{ alignSelf: 'center', grow: 1 }} as='ul'>\n {typeof messages[0] === 'string' ? (\n <BannerMessageItem testId={testId} label={messages[0]} as='li' />\n ) : (\n <BannerMessageItem {...messages[0]} testId={testId} as='li' />\n )}\n </Flex>\n {onDismiss && (\n <Button\n data-testid={testIds.dismiss}\n onClick={onDismiss}\n label={t('dismiss')}\n aria-label={t('banner_dismiss_button_label_a11y')}\n variant='simple'\n icon\n >\n <Icon name='times' />\n </Button>\n )}\n </Flex>\n ) : (\n <StyledBannerContent expandable>\n <Grid\n as={StyledBannerHeader}\n container={{ cols: 'auto 1fr auto', areas: '\"toggle heading dismiss\"', gap: 0.5 }}\n >\n <Grid\n data-testid={testIds.heading}\n container={{ cols: 'min-content min-content', gap: 0.5, alignItems: 'center' }}\n item={{ area: 'heading', alignSelf: 'center' }}\n as={Text}\n forwardedAs={headingTag}\n variant='h2'\n >\n {heading} <Count>{count}</Count>\n </Grid>\n <Grid item={{ area: 'toggle', alignSelf: 'center' }}>\n <Button\n data-testid={testIds.expandCollapse}\n onClick={() => {\n setCollapsed(cur => !cur);\n }}\n label={t(collapsed ? 'expand' : 'collapse')}\n aria-expanded={collapsed ? 'false' : 'true'}\n variant='simple'\n icon\n >\n <Icon name='caret-right' />\n </Button>\n </Grid>\n <Grid item={{ area: 'dismiss', alignSelf: 'center' }}>\n {onDismiss && (\n <Button\n data-testid={testIds.dismiss}\n onClick={onDismiss}\n label={t('dismiss')}\n aria-label={t('banner_dismiss_button_label_a11y')}\n variant='simple'\n icon\n >\n <Icon name='times' />\n </Button>\n )}\n </Grid>\n </Grid>\n <ExpandCollapse collapsed={collapsed}>\n <StyledBannerMessageList items={messagesToRender} />\n </ExpandCollapse>\n </StyledBannerContent>\n )}\n </Grid>\n );\n }),\n getBannerTestIds\n);\n"]}
1
+ {"version":3,"file":"Banner.js","sourceRoot":"","sources":["../../../src/components/Banner/Banner.tsx"],"names":[],"mappings":";AAA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KAAC,IAAI,IAAC,IAAI,EAAC,OAAO,GAAG,GACd,CACV,GACI,IACF,EACP,KAAC,cAAc,IAAC,SAAS,EAAE,SAAS,YAClC,KAAC,uBAAuB,IAAC,KAAK,EAAE,gBAAgB,GAAI,GACrC,IACG,CACvB,IACI,CACR,CAAC;AACJ,CAAC,CAAC,EACF,gBAAgB,CACjB,CAAC","sourcesContent":["import { useState, forwardRef, useMemo, useImperativeHandle } from 'react';\nimport type { PropsWithoutRef, Ref, MouseEventHandler, ReactNode } from 'react';\nimport styled, { css } from 'styled-components';\nimport { getContrast } from 'polished';\n\nimport { defaultThemeProp } from '../../theme';\nimport type {\n ForwardProps,\n HeadingTag,\n NoChildrenProp,\n OmitStrict,\n RefElement,\n TestIdProp,\n WithAttributes\n} from '../../types';\nimport Button, { StyledButton } from '../Button';\nimport { focusHeadingOrContainer, tryCatch, withTestIds } from '../../utils';\nimport { useConsolidatedRef, useDirection, useI18n, useTestIds } from '../../hooks';\nimport Flex from '../Flex';\nimport Text from '../Text';\nimport Grid from '../Grid';\nimport ExpandCollapse from '../ExpandCollapse';\nimport { Count } from '../Badges';\nimport Icon, { StyledIcon, registerIcon } from '../Icon';\nimport * as timesIcon from '../Icon/icons/times.icon';\nimport * as caretRightIcon from '../Icon/icons/caret-right.icon';\nimport * as warnSolidIcon from '../Icon/icons/warn-solid.icon';\nimport * as flagWaveSolidIcon from '../Icon/icons/flag-wave-solid.icon';\nimport * as informationSolidIcon from '../Icon/icons/information-solid.icon';\nimport * as checkIcon from '../Icon/icons/check.icon';\nimport VisuallyHiddenText from '../VisuallyHiddenText';\nimport { UnorderedList } from '../List';\nimport { readableColor } from '../../styles';\n\nimport { getBannerTestIds } from './Banner.test-ids';\n\nregisterIcon(\n timesIcon,\n caretRightIcon,\n warnSolidIcon,\n flagWaveSolidIcon,\n informationSolidIcon,\n checkIcon\n);\n\nexport interface BannerHandleValue {\n /** Used to apply focus to the banner via an imperative handle. */\n focus: () => void;\n}\n\nexport interface BannerMessage {\n label: string;\n description?: string;\n action?: {\n text: string;\n onClick?: MouseEventHandler<HTMLButtonElement | HTMLAnchorElement>;\n href?: string;\n };\n items?: (BannerMessage | string)[];\n}\n\nexport type BannerProps = WithAttributes<\n 'div',\n TestIdProp &\n NoChildrenProp & {\n /** Controls the styling of the Banner. */ variant: 'urgent' | 'warning' | 'success' | 'info';\n /**\n * The heading tag to render the provided heading as. This is agnostic to the styling of the heading.\n * @default 'h2'\n */\n headingTag?: HeadingTag;\n /** Pass one or more descriptive messages to inform the user. */\n messages: (string | BannerMessage)[];\n /** Callback when user explicitly dismisses the Banner. */\n onDismiss?: MouseEventHandler;\n /** Ref that can be used to access the imperative handle. */\n handle?: Ref<BannerHandleValue>;\n }\n>;\n\nexport const StyledBanner = styled.div<{ headingTag: BannerProps['headingTag'] }>(\n ({ headingTag, theme }) => {\n return css`\n border-radius: ${theme.components.card['border-radius']};\n min-inline-size: 100%;\n inline-size: 0;\n\n &:has(${headingTag}:focus) {\n box-shadow: ${theme.base.shadow.focus};\n }\n `;\n }\n);\n\nStyledBanner.defaultProps = defaultThemeProp;\n\nexport const StyledBannerStatus = styled.div<Pick<BannerProps, 'variant'>>(({ variant, theme }) => {\n const { background } = theme.components.banner[variant];\n const color = tryCatch(() =>\n getContrast(background, theme.base.palette['primary-background']) >= 3\n ? theme.base.palette['primary-background']\n : readableColor(background)\n );\n\n return css`\n background-color: ${background};\n color: ${color};\n border-start-start-radius: inherit;\n border-end-start-radius: inherit;\n border: 0.0625rem solid ${theme.base.palette['border-line']};\n border-inline-end: none;\n font-size: 1.25rem;\n `;\n});\n\nStyledBannerStatus.defaultProps = defaultThemeProp;\n\nexport const StyledBannerHeader = styled.div(({ theme }) => {\n const { rtl } = useDirection();\n\n return css`\n min-height: 2.125rem;\n\n ${StyledButton}[aria-expanded] {\n ${StyledIcon} {\n transition: rotate ${theme.base.animation.speed} ${theme.base.animation.timing.ease};\n }\n\n &[aria-expanded='true'] ${StyledIcon} {\n rotate: 90deg;\n }\n\n &[aria-expanded='false'] ${StyledIcon} {\n rotate: ${rtl ? 180 : 0}deg;\n }\n }\n `;\n});\n\nStyledBannerHeader.defaultProps = defaultThemeProp;\n\nexport const StyledBannerContent = styled.div<{ expandable?: boolean }>(({ expandable, theme }) => {\n return css`\n background: ${theme.components.card.background};\n padding-block: calc(0.5 * ${theme.base.spacing});\n padding-inline-start: calc(${expandable ? 0.5 : 2} * ${theme.base.spacing});\n padding-inline-end: calc(0.5 * ${theme.base.spacing});\n border: 0.0625rem solid ${theme.base.palette['border-line']};\n border-inline-start: none;\n border-start-end-radius: inherit;\n border-end-end-radius: inherit;\n `;\n});\n\nStyledBannerContent.defaultProps = defaultThemeProp;\n\nexport const StyledBannerMessageList = styled(UnorderedList)(\n ({ theme }) => css`\n padding-block-end: calc(0.5 * ${theme.base.spacing});\n padding-inline-start: calc(5 * ${theme.base.spacing});\n padding-inline-end: calc(2 * ${theme.base.spacing});\n `\n);\n\nStyledBannerMessageList.defaultProps = defaultThemeProp;\n\nexport const StyledBannerMessage = styled.span`\n overflow-wrap: break-word;\n list-style: none;\n`;\n\nStyledBannerMessage.defaultProps = defaultThemeProp;\n\nconst BannerMessageItem = forwardRef<\n HTMLLIElement,\n TestIdProp & OmitStrict<BannerMessage, 'items'> & ForwardProps\n>(function BannerMessageItem({ testId, label, description, action, ...restProps }, ref) {\n const testIds = useTestIds(testId, getBannerTestIds);\n\n return (\n <StyledBannerMessage {...restProps} ref={ref}>\n <span data-testid={testIds.messageLabel}>{label}</span>\n {description && (\n <>\n {' '}\n <Text data-testid={testIds.messageDescription} variant='secondary'>\n {description}\n </Text>\n </>\n )}\n {action && (\n <>\n {' '}\n <Text variant='secondary'>\n <Button\n data-testid={testIds.messageAction}\n variant='link'\n href={action.href}\n onClick={action.onClick}\n {...action}\n >\n {action.text}\n </Button>\n </Text>\n </>\n )}\n </StyledBannerMessage>\n );\n});\n\nconst prepareMessages = (\n messages: (string | BannerMessage)[],\n testId: TestIdProp['testId']\n): [messages: ReactNode[], count: number] => {\n let count = 0;\n\n return [\n messages.flatMap(msg => {\n count += 1;\n\n if (typeof msg === 'string') {\n return [<BannerMessageItem label={msg} />];\n }\n\n if (msg.items) {\n const { items, ...restMsg } = msg;\n const [subMessages, subCount] = prepareMessages(items, testId);\n count += subCount;\n return [<BannerMessageItem {...restMsg} testId={testId} />, subMessages];\n }\n\n return [<BannerMessageItem {...msg} testId={testId} />];\n }),\n count\n ];\n};\n\nexport default withTestIds(\n forwardRef<RefElement<BannerProps>, PropsWithoutRef<BannerProps>>(function Banner(\n { testId, variant, headingTag = 'h2', messages, onDismiss, handle, ...restProps },\n ref\n ) {\n const testIds = useTestIds(testId, getBannerTestIds);\n const [messagesToRender, count] = useMemo(() => prepareMessages(messages, testId), [messages]);\n const t = useI18n();\n const [collapsed, setCollapsed] = useState(count > 2);\n\n const bannerRef = useConsolidatedRef(ref);\n\n let role: string;\n let icon: string;\n let heading: string;\n let ariaLive: string;\n\n switch (variant) {\n case 'urgent':\n heading = t('error');\n icon = 'warn-solid';\n role = 'alert';\n ariaLive = 'assertive';\n break;\n case 'warning':\n heading = t('warning');\n icon = 'flag-wave-solid';\n role = 'alert';\n ariaLive = 'assertive';\n break;\n case 'success':\n heading = t('success');\n icon = 'check';\n role = 'none';\n ariaLive = 'polite';\n break;\n case 'info':\n default:\n heading = t('information');\n icon = 'information-solid';\n role = 'none';\n ariaLive = 'polite';\n break;\n }\n\n useImperativeHandle(\n handle,\n () => ({\n focus: () => {\n // Empty timeout ensures that the banner will take focus after any other programmatic focus events\n setTimeout(() => {\n if (bannerRef.current) {\n focusHeadingOrContainer(bannerRef.current, heading);\n }\n });\n }\n }),\n []\n );\n\n return (\n <Grid\n data-testid={testIds.root}\n {...restProps}\n as={StyledBanner}\n container={{ cols: '2rem minmax(0, 1fr)' }}\n role={role}\n aria-live={ariaLive}\n headingTag={headingTag}\n ref={bannerRef}\n >\n <Flex\n as={StyledBannerStatus}\n container={{ justify: 'center', alignItems: 'start', pad: [1.5, 0] }}\n variant={variant}\n >\n <Icon name={icon} />\n </Flex>\n {count === 1 ? (\n <Flex container={{ alignItems: 'start' }} as={StyledBannerContent}>\n <VisuallyHiddenText as={headingTag}>{`${heading} ${count}`}</VisuallyHiddenText>\n <Flex item={{ alignSelf: 'center', grow: 1 }} as='ul'>\n {typeof messages[0] === 'string' ? (\n <BannerMessageItem testId={testId} label={messages[0]} as='li' />\n ) : (\n <BannerMessageItem {...messages[0]} testId={testId} as='li' />\n )}\n </Flex>\n {onDismiss && (\n <Button\n data-testid={testIds.dismiss}\n onClick={onDismiss}\n label={t('dismiss')}\n aria-label={t('banner_dismiss_button_label_a11y')}\n variant='simple'\n icon\n >\n <Icon name='times' />\n </Button>\n )}\n </Flex>\n ) : (\n <StyledBannerContent expandable>\n <Grid\n as={StyledBannerHeader}\n container={{ cols: 'auto 1fr auto', areas: '\"toggle heading dismiss\"', gap: 0.5 }}\n >\n <Grid\n data-testid={testIds.heading}\n container={{ cols: 'min-content min-content', gap: 0.5, alignItems: 'center' }}\n item={{ area: 'heading', alignSelf: 'center' }}\n as={Text}\n forwardedAs={headingTag}\n variant='h2'\n >\n {heading} <Count>{count}</Count>\n </Grid>\n <Grid item={{ area: 'toggle', alignSelf: 'center' }}>\n <Button\n data-testid={testIds.expandCollapse}\n onClick={() => {\n setCollapsed(cur => !cur);\n }}\n label={t(collapsed ? 'expand' : 'collapse')}\n aria-label={t(collapsed ? 'expand_noun' : 'collapse_noun', [heading])}\n aria-expanded={collapsed ? 'false' : 'true'}\n variant='simple'\n icon\n >\n <Icon name='caret-right' />\n </Button>\n </Grid>\n <Grid item={{ area: 'dismiss', alignSelf: 'center' }}>\n {onDismiss && (\n <Button\n data-testid={testIds.dismiss}\n onClick={onDismiss}\n label={t('dismiss')}\n aria-label={t('banner_dismiss_button_label_a11y')}\n variant='simple'\n icon\n >\n <Icon name='times' />\n </Button>\n )}\n </Grid>\n </Grid>\n <ExpandCollapse collapsed={collapsed}>\n <StyledBannerMessageList items={messagesToRender} />\n </ExpandCollapse>\n </StyledBannerContent>\n )}\n </Grid>\n );\n }),\n getBannerTestIds\n);\n"]}
@@ -46,5 +46,6 @@ export interface Location {
46
46
  export interface Pin extends LatLng {
47
47
  title?: string;
48
48
  additionalInfo?: FieldValueListItem[];
49
+ selected?: boolean;
49
50
  }
50
51
  //# sourceMappingURL=Location.types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Location.types.d.ts","sourceRoot":"","sources":["../../../src/components/Location/Location.types.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,MAAM,CAAC,OAAO,MAAM,MAAM,GAAG;IAC3B,mCAAmC;IACnC,QAAQ,EAAE,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IAChD,oCAAoC;IACpC,SAAS,EAAE,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;CAClD,CAAC;AAEF,MAAM,CAAC,OAAO,MAAM,IAAI,GAAG;IACzB;uGACmG;IACnG,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC1B,wEAAwE;IACxE,QAAQ,CAAC,EAAE;QACT,8CAA8C;QAC9C,oEAAoE;QACpE,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;QAC3B,yCAAyC;QACzC,MAAM,EAAE,MAAM,CAAC;KAChB,CAAC;CACH,CAAC;AAEF,MAAM,CAAC,OAAO,MAAM,YAAY,GAAG;IACjC,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACpB,CAAC;AAEF,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,CAAC,OAAO,EAAE,YAAY,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAClD,aAAa,EAAE,OAAO,CAAC,IAAI,CAAC,GAAG,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9C,OAAO,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,mBAAmB,CAAC,CAAC;IAC9D,QAAQ,CAAC,EAAE,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACjD,SAAS,CAAC,EAAE,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;CACnD;AAED,MAAM,WAAW,GAAI,SAAQ,MAAM;IACjC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,cAAc,CAAC,EAAE,kBAAkB,EAAE,CAAC;IACtC,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB"}
@@ -1 +1 @@
1
- {"version":3,"file":"Location.types.js","sourceRoot":"","sources":["../../../src/components/Location/Location.types.ts"],"names":[],"mappings":"AAkCA,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,MAAM,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,UAAU,CAAC,CAAC;AAC3F,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,eAAe,EAAE,SAAS,CAAC,CAAC;AAExD,MAAM,CAAC,MAAM,qBAAqB,GAAG,oBAAoB,CAAC;AAC1D,MAAM,CAAC,MAAM,2BAA2B,GAAG,yBAAyB,CAAC;AACrE,MAAM,CAAC,MAAM,0BAA0B,GAAG,6BAA6B,CAAC;AACxE,MAAM,CAAC,MAAM,kBAAkB,GAAG,sCAAsC,CAAC;AACzE,MAAM,CAAC,MAAM,yBAAyB,GAAG,mCAAmC,CAAC;AAC7E,MAAM,CAAC,MAAM,yBAAyB,GAAG,0BAA0B,CAAC;AACpE,MAAM,CAAC,MAAM,mBAAmB,GAAG,wBAAwB,CAAC","sourcesContent":["import type { FieldValueListItem } from '../FieldValueList';\n\nexport declare type LatLng = {\n /** The latitude representation. */\n latitude: ReturnType<google.maps.LatLng['lat']>;\n /** The longitude representation. */\n longitude: ReturnType<google.maps.LatLng['lng']>;\n};\n\nexport declare type Bias = {\n /** Predictions will be biased towards, but not restricted to, the given bounds. Both location and radius will be ignored if bounds is set.\n * Array stores south-west coordinate of bounding box and north-east coordinate of bounding box. */\n bounds?: [LatLng, LatLng];\n /** Predictions will be biased towards the given location and radius. */\n location?: {\n /** Must to provide both center and radius. */\n /** Location coordinate or current (means user current location). */\n center: LatLng | 'current';\n /** The radius is specified in meters. */\n radius: number;\n };\n};\n\nexport declare type ProviderOpts = {\n [key: string]: any;\n};\n\nexport interface MapsProvider {\n name: string;\n loadAPI: (options: ProviderOpts) => Promise<void>;\n loadedPromise: Promise<void> | null;\n loadedApiKey: string;\n}\n\nexport const QUERY_FIELDS = ['name', 'formatted_address', 'geometry.location', 'place_id'];\nexport const QUERY_TYPES = ['establishment', 'geocode'];\n\nexport const LocationNotFoundError = 'Location not found';\nexport const GeolocationUnsupportedError = 'Geolocation unsupported';\nexport const GoogleMapsAPINotFoundError = 'Cannot load Google Maps API';\nexport const IsNotAnObjectError = 'Provider data given is not an object';\nexport const ProviderNotSupportedError = 'Not supported maps provider given';\nexport const CoordsCannotBeParsedError = 'Coords cannot be parsed!';\nexport const GeocoderFailedError = 'Geocoder failed due to';\n\nexport interface Location {\n name?: google.maps.places.PlaceResult['name'];\n address?: google.maps.places.PlaceResult['formatted_address'];\n latitude?: ReturnType<google.maps.LatLng['lat']>;\n longitude?: ReturnType<google.maps.LatLng['lng']>;\n}\n\nexport interface Pin extends LatLng {\n title?: string;\n additionalInfo?: FieldValueListItem[];\n}\n"]}
1
+ {"version":3,"file":"Location.types.js","sourceRoot":"","sources":["../../../src/components/Location/Location.types.ts"],"names":[],"mappings":"AAkCA,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,MAAM,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,UAAU,CAAC,CAAC;AAC3F,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,eAAe,EAAE,SAAS,CAAC,CAAC;AAExD,MAAM,CAAC,MAAM,qBAAqB,GAAG,oBAAoB,CAAC;AAC1D,MAAM,CAAC,MAAM,2BAA2B,GAAG,yBAAyB,CAAC;AACrE,MAAM,CAAC,MAAM,0BAA0B,GAAG,6BAA6B,CAAC;AACxE,MAAM,CAAC,MAAM,kBAAkB,GAAG,sCAAsC,CAAC;AACzE,MAAM,CAAC,MAAM,yBAAyB,GAAG,mCAAmC,CAAC;AAC7E,MAAM,CAAC,MAAM,yBAAyB,GAAG,0BAA0B,CAAC;AACpE,MAAM,CAAC,MAAM,mBAAmB,GAAG,wBAAwB,CAAC","sourcesContent":["import type { FieldValueListItem } from '../FieldValueList';\n\nexport declare type LatLng = {\n /** The latitude representation. */\n latitude: ReturnType<google.maps.LatLng['lat']>;\n /** The longitude representation. */\n longitude: ReturnType<google.maps.LatLng['lng']>;\n};\n\nexport declare type Bias = {\n /** Predictions will be biased towards, but not restricted to, the given bounds. Both location and radius will be ignored if bounds is set.\n * Array stores south-west coordinate of bounding box and north-east coordinate of bounding box. */\n bounds?: [LatLng, LatLng];\n /** Predictions will be biased towards the given location and radius. */\n location?: {\n /** Must to provide both center and radius. */\n /** Location coordinate or current (means user current location). */\n center: LatLng | 'current';\n /** The radius is specified in meters. */\n radius: number;\n };\n};\n\nexport declare type ProviderOpts = {\n [key: string]: any;\n};\n\nexport interface MapsProvider {\n name: string;\n loadAPI: (options: ProviderOpts) => Promise<void>;\n loadedPromise: Promise<void> | null;\n loadedApiKey: string;\n}\n\nexport const QUERY_FIELDS = ['name', 'formatted_address', 'geometry.location', 'place_id'];\nexport const QUERY_TYPES = ['establishment', 'geocode'];\n\nexport const LocationNotFoundError = 'Location not found';\nexport const GeolocationUnsupportedError = 'Geolocation unsupported';\nexport const GoogleMapsAPINotFoundError = 'Cannot load Google Maps API';\nexport const IsNotAnObjectError = 'Provider data given is not an object';\nexport const ProviderNotSupportedError = 'Not supported maps provider given';\nexport const CoordsCannotBeParsedError = 'Coords cannot be parsed!';\nexport const GeocoderFailedError = 'Geocoder failed due to';\n\nexport interface Location {\n name?: google.maps.places.PlaceResult['name'];\n address?: google.maps.places.PlaceResult['formatted_address'];\n latitude?: ReturnType<google.maps.LatLng['lat']>;\n longitude?: ReturnType<google.maps.LatLng['lng']>;\n}\n\nexport interface Pin extends LatLng {\n title?: string;\n additionalInfo?: FieldValueListItem[];\n selected?: boolean;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"LocationView.d.ts","sourceRoot":"","sources":["../../../src/components/Location/LocationView.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,EAAE,EAAO,MAAM,OAAO,CAAC;AAGrC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAK7C,OAAO,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAC;AAIpD,eAAO,MAAM,mBAAmB;;uDAK/B,CAAC;AAIF,eAAO,MAAM,kBAAkB;;SAW7B,CAAC;AAiCH,MAAM,WAAW,iBAAkB,SAAQ,SAAS;IAClD;;;OAGG;IACH,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;IACb;;;OAGG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,+IAA+I;IAC/I,OAAO,CAAC,EAAE,CACR,YAAY,EAAE,MAAM,GAAG;QACrB,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,OAAO,CAAC,EAAE,MAAM,CAAC;KAClB,KACE,IAAI,CAAC;IACV;;OAEG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB;;;OAGG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB,sGAAsG;IACtG,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;CAClC;AAeD,QAAA,MAAM,YAAY,EAAE,EAAE,CAAC,iBAAiB,CA4JvC,CAAC;AAEF,eAAe,YAAY,CAAC"}
1
+ {"version":3,"file":"LocationView.d.ts","sourceRoot":"","sources":["../../../src/components/Location/LocationView.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,EAAE,EAAO,MAAM,OAAO,CAAC;AAGrC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAO7C,OAAO,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAC;AAIpD,eAAO,MAAM,mBAAmB;;uDAK/B,CAAC;AAIF,eAAO,MAAM,kBAAkB;;SAW7B,CAAC;AAiCH,MAAM,WAAW,iBAAkB,SAAQ,SAAS;IAClD;;;OAGG;IACH,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;IACb;;;OAGG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,+IAA+I;IAC/I,OAAO,CAAC,EAAE,CACR,YAAY,EAAE,MAAM,GAAG;QACrB,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,OAAO,CAAC,EAAE,MAAM,CAAC;KAClB,KACE,IAAI,CAAC;IACV;;OAEG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB;;;OAGG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB,sGAAsG;IACtG,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;CAClC;AAeD,QAAA,MAAM,YAAY,EAAE,EAAE,CAAC,iBAAiB,CAmLvC,CAAC;AAEF,eAAe,YAAY,CAAC"}
@@ -4,6 +4,8 @@ import styled, { css } from 'styled-components';
4
4
  import { defaultThemeProp } from '../../theme';
5
5
  import Progress from '../Progress';
6
6
  import { Status } from '../Badges';
7
+ import { createUID } from '../../utils';
8
+ import useTheme from '../../hooks/useTheme';
7
9
  import { loadMapsAPI, toGoogleLatLng, getPlaceById, isLatLngObject, getAddress } from './utils';
8
10
  import MapsContext from './MapsContext';
9
11
  export const StyledLocationError = styled(Status) `
@@ -60,6 +62,7 @@ const LocationView = (props) => {
60
62
  const markers = useRef([]);
61
63
  const ds = useRef();
62
64
  const dr = useRef();
65
+ const theme = useTheme();
63
66
  const onMapClick = (e) => {
64
67
  if (!isLatLngObject(e.latLng))
65
68
  return;
@@ -85,6 +88,7 @@ const LocationView = (props) => {
85
88
  if (mapElemRef.current) {
86
89
  const position = toGoogleLatLng({ latitude: 0, longitude: 0 });
87
90
  map.current = new google.maps.Map(mapElemRef.current, {
91
+ mapId: createUID(),
88
92
  center: position,
89
93
  zoom: 2,
90
94
  draggable: !disabled,
@@ -92,7 +96,7 @@ const LocationView = (props) => {
92
96
  draggingCursor: 'move'
93
97
  });
94
98
  ds.current = new google.maps.DirectionsService();
95
- dr.current = new google.maps.DirectionsRenderer();
99
+ dr.current = new google.maps.DirectionsRenderer({ suppressMarkers: true });
96
100
  }
97
101
  };
98
102
  useEffect(() => {
@@ -144,16 +148,31 @@ const LocationView = (props) => {
144
148
  travelMode: google.maps.TravelMode.DRIVING
145
149
  };
146
150
  ds.current.route(request).then(dr.current.setDirections.bind(dr.current), onError);
147
- return () => dr.current.setMap(null);
148
151
  }
149
152
  const bounds = new google.maps.LatLngBounds();
150
- markers.current = pins.map(({ latitude, longitude, title }, index) => {
153
+ markers.current = pins.map(({ latitude, longitude, title, selected }, index) => {
151
154
  const gCoords = toGoogleLatLng({ latitude, longitude });
152
- const marker = new google.maps.Marker({
155
+ const contentConfig = {
156
+ glyphColor: theme.base.colors.white
157
+ };
158
+ if (pins.length > 1) {
159
+ const glyphWrapper = document.createElement('span');
160
+ glyphWrapper.style.fontSize = '0.9rem';
161
+ glyphWrapper.style.paddingTop = '0.1rem';
162
+ glyphWrapper.innerHTML = markerLabels[index % markerLabels.length];
163
+ contentConfig.glyph = glyphWrapper;
164
+ }
165
+ if (selected) {
166
+ contentConfig.background = theme.base.colors.red.dark;
167
+ contentConfig.borderColor = theme.base.colors.red.dark;
168
+ contentConfig.scale = 1.15;
169
+ }
170
+ const content = new google.maps.marker.PinElement(contentConfig);
171
+ const marker = new google.maps.marker.AdvancedMarkerElement({
153
172
  map: map.current,
154
173
  position: gCoords,
155
- label: pins.length > 1 ? markerLabels[index % markerLabels.length] : undefined,
156
- title
174
+ title,
175
+ content: content.element
157
176
  });
158
177
  bounds.extend(gCoords);
159
178
  return marker;
@@ -167,7 +186,12 @@ const LocationView = (props) => {
167
186
  map.current.fitBounds(bounds);
168
187
  }
169
188
  }
170
- return () => markers.current.forEach(m => m.setMap(null));
189
+ return () => {
190
+ markers.current.forEach(m => {
191
+ m.map = null;
192
+ });
193
+ dr.current?.setMap(null);
194
+ };
171
195
  }, [JSON.stringify(pins), status, zoomLevel, disabled, drawRoute, centerMapOnChange, onError]);
172
196
  return (_jsxs(StyledLocationView, { height: height, children: [_jsx(StyledMap, { ref: mapElemRef, height: height, disabled: disabled, status: status, ...restProps }), (status === LoadStatus.Init || loading) && _jsx(Progress, { placement: 'local' }), status === LoadStatus.Error && eMessage && (_jsx(StyledLocationError, { "aria-label": eMessage, variant: 'info', children: eMessage }))] }));
173
197
  };
@@ -1 +1 @@
1
- {"version":3,"file":"LocationView.js","sourceRoot":"","sources":["../../../src/components/Location/LocationView.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAEhE,OAAO,MAAM,EAAE,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AAGhD,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,QAAQ,MAAM,aAAa,CAAC;AACnC,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CA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AAM,KAAK,UAAU,CAAC,IAAI,IAAI,OAAO,CAAC,IAAI,KAAC,QAAQ,IAAC,SAAS,EAAC,OAAO,GAAG,EACzE,MAAM,KAAK,UAAU,CAAC,KAAK,IAAI,QAAQ,IAAI,CAC1C,KAAC,mBAAmB,kBAAa,QAAQ,EAAE,OAAO,EAAC,MAAM,YACtD,QAAQ,GACW,CACvB,IACkB,CACtB,CAAC;AACJ,CAAC,CAAC;AAEF,eAAe,YAAY,CAAC","sourcesContent":["import { useContext, useRef, useState, useEffect } from 'react';\nimport type { FC, Ref } from 'react';\nimport styled, { css } from 'styled-components';\n\nimport type { BaseProps } from '../../types';\nimport { defaultThemeProp } from '../../theme';\nimport Progress from '../Progress';\nimport { Status } from '../Badges';\n\nimport type { LatLng, Pin } from './Location.types';\nimport { loadMapsAPI, toGoogleLatLng, getPlaceById, isLatLngObject, getAddress } from './utils';\nimport MapsContext from './MapsContext';\n\nexport const StyledLocationError = styled(Status)`\n position: absolute;\n top: 40%;\n left: 50%;\n transform: translate(-50%, -50%);\n`;\n\nStyledLocationError.defaultProps = defaultThemeProp;\n\nexport const StyledLocationView = styled.div<{ height?: string }>(props => {\n const { height, theme } = props;\n\n return css`\n height: ${height};\n position: relative;\n flex: auto;\n border-radius: ${theme.base['border-radius']};\n mask-image: radial-gradient(white, black);\n -webkit-mask-image: radial-gradient(white, black);\n `;\n});\n\nStyledLocationView.defaultProps = defaultThemeProp;\n\nconst StyledMap = styled.div<{\n height?: string;\n status: string;\n disabled: boolean;\n}>(\n ({\n height,\n disabled,\n status,\n theme: {\n base: { 'disabled-opacity': disabledOpacity }\n }\n }) => {\n return css`\n height: ${height};\n ${disabled &&\n css`\n opacity: ${disabledOpacity};\n `}\n ${status === 'error' &&\n css`\n opacity: ${disabledOpacity};\n `}\n `;\n }\n);\n\nStyledMap.defaultProps = defaultThemeProp;\n\nexport interface LocationViewProps extends BaseProps {\n /**\n * Array of location objects.\n * @default []\n */\n pins?: Pin[];\n /**\n * Set to true to always center the map when the selected location changes. Toggling this from false to true will re-center map on the last pinned location.\n * @default false\n */\n centerMapOnChange?: boolean;\n /**\n * Height of the map container.\n * @default '25rem'\n */\n height?: string;\n /**\n * How much the map should zoom.\n * @default 13\n */\n zoomLevel?: number;\n /** Callback fired when user clicks on a location on the map. This function will be passed the coordinates of the location that was clicked. */\n onClick?: (\n locationData: LatLng & {\n name?: string;\n address?: string;\n }\n ) => void;\n /**\n * Renders loading indicator when true. Informs the user location resolution is in progress.\n */\n loading?: boolean;\n /**\n * Disables dragging and clicking when true.\n * @default false\n */\n disabled?: boolean;\n /**\n * Indicates if route between pins should be rendered.\n * @default false\n */\n drawRoute?: boolean;\n\n /** Callback fired when an error occurs. This function gets called with one argument of type Error. */\n onError?: (error: Error) => void;\n}\n\nenum LoadStatus {\n Init = 'init',\n Ready = 'ready',\n Error = 'error'\n}\n\nconst hasPlaceId = (obj: any): obj is google.maps.IconMouseEvent & { placeId: string } => {\n return typeof obj === 'object' && obj.placeId && typeof obj.placeId === 'string';\n};\n\n/* cSpell:ignore 'ABCDEFGHIJKLMNOPQRSTUVWYZ' */\nconst markerLabels = 'ABCDEFGHIJKLMNOPQRSTUVWYZ';\n\nconst LocationView: FC<LocationViewProps> = (props: LocationViewProps) => {\n const {\n pins = [],\n zoomLevel = 13,\n height = '25rem',\n centerMapOnChange = false,\n onClick,\n onError,\n disabled = false,\n loading = false,\n drawRoute = false,\n ...restProps\n } = props;\n const { name, ...providerOpts } = useContext(MapsContext);\n const [status, setStatus] = useState<LoadStatus>(LoadStatus.Init);\n const [eMessage, setEMessage] = useState('');\n const mapElemRef = useRef<HTMLDivElement>();\n const map = useRef<google.maps.Map>();\n const markers = useRef<google.maps.Marker[]>([]);\n const ds = useRef<google.maps.DirectionsService>();\n const dr = useRef<google.maps.DirectionsRenderer>();\n\n const onMapClick = (e: google.maps.MapMouseEvent) => {\n if (!isLatLngObject(e.latLng)) return;\n\n if (hasPlaceId(e)) {\n getPlaceById(e.placeId).then(placeInfo => {\n onClick?.({\n ...placeInfo,\n latitude: e.latLng!.lat(),\n longitude: e.latLng!.lng()\n });\n });\n } else {\n getAddress({\n latitude: e.latLng.lat(),\n longitude: e.latLng.lng()\n })\n .then(onClick)\n .catch(err => onError?.(err));\n }\n };\n\n const initialize = () => {\n if (mapElemRef.current) {\n const position = toGoogleLatLng({ latitude: 0, longitude: 0 });\n map.current = new google.maps.Map(mapElemRef.current, {\n center: position,\n zoom: 2,\n draggable: !disabled,\n draggableCursor: 'auto',\n draggingCursor: 'move'\n });\n ds.current = new google.maps.DirectionsService();\n dr.current = new google.maps.DirectionsRenderer();\n }\n };\n\n useEffect(() => {\n if (!onClick || !map.current) return;\n\n const l = map.current.addListener('click', onMapClick);\n return () => google.maps.event.removeListener(l);\n }, [onClick, map.current]);\n\n useEffect(() => {\n let mounted = true;\n loadMapsAPI(name, providerOpts)\n .then(() => {\n if (mounted) {\n initialize();\n setStatus(LoadStatus.Ready);\n }\n })\n .catch((error: Error) => {\n setStatus(LoadStatus.Error);\n setEMessage(error.message);\n onError?.(error);\n });\n\n return () => {\n mounted = false;\n if (map.current) google.maps.event.clearInstanceListeners(map.current);\n };\n }, []);\n\n useEffect(() => {\n if (status !== LoadStatus.Ready || !map.current || !dr.current || !ds.current) return;\n\n if (drawRoute && pins.length > 1) {\n dr.current.setMap(map.current);\n const request: google.maps.DirectionsRequest = {\n origin: toGoogleLatLng({ latitude: pins[0].latitude, longitude: pins[0].longitude }),\n destination: toGoogleLatLng({\n latitude: pins[pins.length - 1].latitude,\n longitude: pins[pins.length - 1].longitude\n }),\n waypoints: pins.slice(1, pins.length - 1).map(l => {\n return {\n stopover: true,\n location: toGoogleLatLng({\n latitude: l.latitude,\n longitude: l.longitude\n })\n };\n }),\n travelMode: google.maps.TravelMode.DRIVING\n };\n\n ds.current.route(request).then(dr.current.setDirections.bind(dr.current), onError);\n\n return () => dr.current!.setMap(null);\n }\n\n const bounds = new google.maps.LatLngBounds();\n markers.current = pins.map(({ latitude, longitude, title }, index) => {\n const gCoords = toGoogleLatLng({ latitude, longitude });\n const marker = new google.maps.Marker({\n map: map.current,\n position: gCoords,\n label: pins.length > 1 ? markerLabels[index % markerLabels.length] : undefined,\n title\n });\n bounds.extend(gCoords);\n return marker;\n });\n\n if (centerMapOnChange) {\n if (pins.length === 1) {\n map.current.setCenter(toGoogleLatLng(pins[0]));\n map.current.setZoom(zoomLevel);\n } else if (pins.length > 1) {\n map.current.fitBounds(bounds);\n }\n }\n\n return () => markers.current.forEach(m => m.setMap(null));\n }, [JSON.stringify(pins), status, zoomLevel, disabled, drawRoute, centerMapOnChange, onError]);\n\n return (\n <StyledLocationView height={height}>\n <StyledMap\n ref={mapElemRef as Ref<HTMLDivElement>}\n height={height}\n disabled={disabled}\n status={status}\n {...restProps}\n />\n {(status === LoadStatus.Init || loading) && <Progress placement='local' />}\n {status === LoadStatus.Error && eMessage && (\n <StyledLocationError aria-label={eMessage} variant='info'>\n {eMessage}\n </StyledLocationError>\n )}\n </StyledLocationView>\n );\n};\n\nexport default LocationView;\n"]}
1
+ {"version":3,"file":"LocationView.js","sourceRoot":"","sources":["../../../src/components/Location/LocationView.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAEhE,OAAO,MAAM,EAAE,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AAGhD,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,QAAQ,MAAM,aAAa,CAAC;AACnC,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,QAAQ,MAAM,sBAAsB,CAAC;AAG5C,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,YAAY,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAChG,OAAO,WAAW,MAAM,eAAe,C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S,CAAC,CAAC;aAChC;iBAAM,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE;gBAC1B,GAAG,CAAC,OAAO,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;aAC/B;SACF;QAED,OAAO,GAAG,EAAE;YACV,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE;gBAC1B,CAAC,CAAC,GAAG,GAAG,IAAI,CAAC;YACf,CAAC,CAAC,CAAC;YACH,EAAE,CAAC,OAAO,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;QAC3B,CAAC,CAAC;IACJ,CAAC,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,EAAE,iBAAiB,EAAE,OAAO,CAAC,CAAC,CAAC;IAE/F,OAAO,CACL,MAAC,kBAAkB,IAAC,MAAM,EAAE,MAAM,aAChC,KAAC,SAAS,IACR,GAAG,EAAE,UAAiC,EACtC,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,QAAQ,EAClB,MAAM,EAAE,MAAM,KACV,SAAS,GACb,EACD,CAAC,MAAM,KAAK,UAAU,CAAC,IAAI,IAAI,OAAO,CAAC,IAAI,KAAC,QAAQ,IAAC,SAAS,EAAC,OAAO,GAAG,EACzE,MAAM,KAAK,UAAU,CAAC,KAAK,IAAI,QAAQ,IAAI,CAC1C,KAAC,mBAAmB,kBAAa,QAAQ,EAAE,OAAO,EAAC,MAAM,YACtD,QAAQ,GACW,CACvB,IACkB,CACtB,CAAC;AACJ,CAAC,CAAC;AAEF,eAAe,YAAY,CAAC","sourcesContent":["import { useContext, useRef, useState, useEffect } from 'react';\nimport type { FC, Ref } from 'react';\nimport styled, { css } from 'styled-components';\n\nimport type { BaseProps } from '../../types';\nimport { defaultThemeProp } from '../../theme';\nimport Progress from '../Progress';\nimport { Status } from '../Badges';\nimport { createUID } from '../../utils';\nimport useTheme from '../../hooks/useTheme';\n\nimport type { LatLng, Pin } from './Location.types';\nimport { loadMapsAPI, toGoogleLatLng, getPlaceById, isLatLngObject, getAddress } from './utils';\nimport MapsContext from './MapsContext';\n\nexport const StyledLocationError = styled(Status)`\n position: absolute;\n top: 40%;\n left: 50%;\n transform: translate(-50%, -50%);\n`;\n\nStyledLocationError.defaultProps = defaultThemeProp;\n\nexport const StyledLocationView = styled.div<{ height?: string }>(props => {\n const { height, theme } = props;\n\n return css`\n height: ${height};\n position: relative;\n flex: auto;\n border-radius: ${theme.base['border-radius']};\n mask-image: radial-gradient(white, black);\n -webkit-mask-image: radial-gradient(white, black);\n `;\n});\n\nStyledLocationView.defaultProps = defaultThemeProp;\n\nconst StyledMap = styled.div<{\n height?: string;\n status: string;\n disabled: boolean;\n}>(\n ({\n height,\n disabled,\n status,\n theme: {\n base: { 'disabled-opacity': disabledOpacity }\n }\n }) => {\n return css`\n height: ${height};\n ${disabled &&\n css`\n opacity: ${disabledOpacity};\n `}\n ${status === 'error' &&\n css`\n opacity: ${disabledOpacity};\n `}\n `;\n }\n);\n\nStyledMap.defaultProps = defaultThemeProp;\n\nexport interface LocationViewProps extends BaseProps {\n /**\n * Array of location objects.\n * @default []\n */\n pins?: Pin[];\n /**\n * Set to true to always center the map when the selected location changes. Toggling this from false to true will re-center map on the last pinned location.\n * @default false\n */\n centerMapOnChange?: boolean;\n /**\n * Height of the map container.\n * @default '25rem'\n */\n height?: string;\n /**\n * How much the map should zoom.\n * @default 13\n */\n zoomLevel?: number;\n /** Callback fired when user clicks on a location on the map. This function will be passed the coordinates of the location that was clicked. */\n onClick?: (\n locationData: LatLng & {\n name?: string;\n address?: string;\n }\n ) => void;\n /**\n * Renders loading indicator when true. Informs the user location resolution is in progress.\n */\n loading?: boolean;\n /**\n * Disables dragging and clicking when true.\n * @default false\n */\n disabled?: boolean;\n /**\n * Indicates if route between pins should be rendered.\n * @default false\n */\n drawRoute?: boolean;\n\n /** Callback fired when an error occurs. This function gets called with one argument of type Error. */\n onError?: (error: Error) => void;\n}\n\nenum LoadStatus {\n Init = 'init',\n Ready = 'ready',\n Error = 'error'\n}\n\nconst hasPlaceId = (obj: any): obj is google.maps.IconMouseEvent & { placeId: string } => {\n return typeof obj === 'object' && obj.placeId && typeof obj.placeId === 'string';\n};\n\n/* cSpell:ignore 'ABCDEFGHIJKLMNOPQRSTUVWYZ' */\nconst markerLabels = 'ABCDEFGHIJKLMNOPQRSTUVWYZ';\n\nconst LocationView: FC<LocationViewProps> = (props: LocationViewProps) => {\n const {\n pins = [],\n zoomLevel = 13,\n height = '25rem',\n centerMapOnChange = false,\n onClick,\n onError,\n disabled = false,\n loading = false,\n drawRoute = false,\n ...restProps\n } = props;\n const { name, ...providerOpts } = useContext(MapsContext);\n const [status, setStatus] = useState<LoadStatus>(LoadStatus.Init);\n const [eMessage, setEMessage] = useState('');\n const mapElemRef = useRef<HTMLDivElement>();\n const map = useRef<google.maps.Map>();\n const markers = useRef<google.maps.marker.AdvancedMarkerElement[]>([]);\n const ds = useRef<google.maps.DirectionsService>();\n const dr = useRef<google.maps.DirectionsRenderer>();\n const theme = useTheme();\n\n const onMapClick = (e: google.maps.MapMouseEvent) => {\n if (!isLatLngObject(e.latLng)) return;\n\n if (hasPlaceId(e)) {\n getPlaceById(e.placeId).then(placeInfo => {\n onClick?.({\n ...placeInfo,\n latitude: e.latLng!.lat(),\n longitude: e.latLng!.lng()\n });\n });\n } else {\n getAddress({\n latitude: e.latLng.lat(),\n longitude: e.latLng.lng()\n })\n .then(onClick)\n .catch(err => onError?.(err));\n }\n };\n\n const initialize = () => {\n if (mapElemRef.current) {\n const position = toGoogleLatLng({ latitude: 0, longitude: 0 });\n map.current = new google.maps.Map(mapElemRef.current, {\n mapId: createUID(),\n center: position,\n zoom: 2,\n draggable: !disabled,\n draggableCursor: 'auto',\n draggingCursor: 'move'\n });\n ds.current = new google.maps.DirectionsService();\n dr.current = new google.maps.DirectionsRenderer({ suppressMarkers: true });\n }\n };\n\n useEffect(() => {\n if (!onClick || !map.current) return;\n\n const l = map.current.addListener('click', onMapClick);\n return () => google.maps.event.removeListener(l);\n }, [onClick, map.current]);\n\n useEffect(() => {\n let mounted = true;\n loadMapsAPI(name, providerOpts)\n .then(() => {\n if (mounted) {\n initialize();\n setStatus(LoadStatus.Ready);\n }\n })\n .catch((error: Error) => {\n setStatus(LoadStatus.Error);\n setEMessage(error.message);\n onError?.(error);\n });\n\n return () => {\n mounted = false;\n if (map.current) google.maps.event.clearInstanceListeners(map.current);\n };\n }, []);\n\n useEffect(() => {\n if (status !== LoadStatus.Ready || !map.current || !dr.current || !ds.current) return;\n\n if (drawRoute && pins.length > 1) {\n dr.current.setMap(map.current);\n const request: google.maps.DirectionsRequest = {\n origin: toGoogleLatLng({ latitude: pins[0].latitude, longitude: pins[0].longitude }),\n destination: toGoogleLatLng({\n latitude: pins[pins.length - 1].latitude,\n longitude: pins[pins.length - 1].longitude\n }),\n waypoints: pins.slice(1, pins.length - 1).map(l => {\n return {\n stopover: true,\n location: toGoogleLatLng({\n latitude: l.latitude,\n longitude: l.longitude\n })\n };\n }),\n travelMode: google.maps.TravelMode.DRIVING\n };\n\n ds.current.route(request).then(dr.current.setDirections.bind(dr.current), onError);\n }\n\n const bounds = new google.maps.LatLngBounds();\n\n markers.current = pins.map(({ latitude, longitude, title, selected }, index) => {\n const gCoords = toGoogleLatLng({ latitude, longitude });\n\n const contentConfig: google.maps.marker.PinElementOptions = {\n glyphColor: theme.base.colors.white\n };\n if (pins.length > 1) {\n const glyphWrapper = document.createElement('span');\n glyphWrapper.style.fontSize = '0.9rem';\n glyphWrapper.style.paddingTop = '0.1rem';\n glyphWrapper.innerHTML = markerLabels[index % markerLabels.length];\n contentConfig.glyph = glyphWrapper;\n }\n if (selected) {\n contentConfig.background = theme.base.colors.red.dark;\n contentConfig.borderColor = theme.base.colors.red.dark;\n contentConfig.scale = 1.15;\n }\n const content = new google.maps.marker.PinElement(contentConfig);\n const marker = new google.maps.marker.AdvancedMarkerElement({\n map: map.current,\n position: gCoords,\n title,\n content: content.element\n });\n bounds.extend(gCoords);\n return marker;\n });\n\n if (centerMapOnChange) {\n if (pins.length === 1) {\n map.current.setCenter(toGoogleLatLng(pins[0]));\n map.current.setZoom(zoomLevel);\n } else if (pins.length > 1) {\n map.current.fitBounds(bounds);\n }\n }\n\n return () => {\n markers.current.forEach(m => {\n m.map = null;\n });\n dr.current?.setMap(null);\n };\n }, [JSON.stringify(pins), status, zoomLevel, disabled, drawRoute, centerMapOnChange, onError]);\n\n return (\n <StyledLocationView height={height}>\n <StyledMap\n ref={mapElemRef as Ref<HTMLDivElement>}\n height={height}\n disabled={disabled}\n status={status}\n {...restProps}\n />\n {(status === LoadStatus.Init || loading) && <Progress placement='local' />}\n {status === LoadStatus.Error && eMessage && (\n <StyledLocationError aria-label={eMessage} variant='info'>\n {eMessage}\n </StyledLocationError>\n )}\n </StyledLocationView>\n );\n};\n\nexport default LocationView;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/components/Location/utils.ts"],"names":[],"mappings":";AAaA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,EAAgB,YAAY,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAuI3F,wBAAsB,WAAW,CAAC,IAAI,GAAE,MAAW,EAAE,IAAI,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAYvF;AAED;;;GAGG;AACH,wBAAgB,6BAA6B,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAEpE;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAE1D;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAE3D;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAOzD;AA6BD;;GAEG;AACH,wBAAgB,QAAQ,CAAC,KAA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AU,GAAE,cAA8C,GACzD,OAAO,CAAC,QAAQ,CAAC,CAgBnB;AAED,yFAAyF;AACzF,wBAAsB,SAAS,CAC7B,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,EACnC,UAAU,CAAC,EAAE,cAAc,GAC1B,OAAO,CAAC,MAAM,CAAC,CAuCjB;AAED,wBAAsB,UAAU,CAC9B,MAAM,EAAE,MAAM,GACb,OAAO,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,CAAC,CAkClF;AAED,eAAO,MAAM,cAAc,QAAS,GAAG,8BAStC,CAAC"}
@@ -1,6 +1,6 @@
1
- import { hasProp, loadScript } from '../../utils';
1
+ import { Loader } from '@googlemaps/js-api-loader';
2
+ import { hasProp } from '../../utils';
2
3
  import { CoordsCannotBeParsedError, GeocoderFailedError, GeolocationUnsupportedError, GoogleMapsAPINotFoundError, IsNotAnObjectError, LocationNotFoundError, ProviderNotSupportedError, QUERY_FIELDS, QUERY_TYPES } from './Location.types';
3
- const GOOGLE_MAPS_SCRIPT_ID = 'google-map';
4
4
  const DegreeRegexChunks = [
5
5
  /^[-+]?/,
6
6
  // latitude degrees
@@ -86,23 +86,19 @@ const providers = {
86
86
  loadedPromise: null,
87
87
  loadedApiKey: '',
88
88
  loadAPI(opts) {
89
- const params = new URLSearchParams(Object.entries({
90
- key: opts.apiKey,
89
+ const loader = new Loader({
90
+ version: '3.55',
91
+ apiKey: opts.apiKey,
91
92
  region: opts.region,
92
- language: opts.language,
93
- libraries: 'places'
94
- }).filter(([, value]) => value !== undefined)).toString();
95
- const loadedScript = document.getElementById(GOOGLE_MAPS_SCRIPT_ID);
96
- if (loadedScript) {
97
- loadedScript.remove();
98
- // https://stackoverflow.com/questions/29930274/fixing-you-have-included-the-google-maps-api-multiple-times-on-this-page-this
99
- delete window.google;
100
- }
101
- return new Promise((resolve, reject) => {
102
- loadScript(`https://maps.googleapis.com/maps/api/js?${params}`, function onLoad() {
103
- this.id = GOOGLE_MAPS_SCRIPT_ID;
104
- return resolve();
105
- }, () => reject(new Error(GoogleMapsAPINotFoundError)));
93
+ language: opts.language
94
+ });
95
+ return Promise.all([
96
+ loader.importLibrary('core'),
97
+ loader.importLibrary('maps'),
98
+ loader.importLibrary('places'),
99
+ loader.importLibrary('marker')
100
+ ]).then(() => { }, () => {
101
+ throw new Error(GoogleMapsAPINotFoundError);
106
102
  });
107
103
  }
108
104
  },
@@ -118,9 +114,15 @@ export async function loadMapsAPI(name = '', opts) {
118
114
  throw new Error(IsNotAnObjectError);
119
115
  }
120
116
  const provider = providers[name] ?? providers.undefined;
121
- if (!provider.loadedPromise || provider.loadedApiKey !== opts?.apiKey) {
122
- provider.loadedApiKey = opts?.apiKey;
123
- provider.loadedPromise = provider.loadAPI(opts);
117
+ if (!provider.loadedPromise) {
118
+ provider.loadedPromise = provider
119
+ .loadAPI(opts)
120
+ .then(() => {
121
+ provider.loadedApiKey = opts?.apiKey;
122
+ })
123
+ .catch(() => {
124
+ provider.loadedPromise = null;
125
+ });
124
126
  }
125
127
  return provider.loadedPromise;
126
128
  }
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/components/Location/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAElD,OAAO,EACL,yBAAyB,EACzB,mBAAmB,EACnB,2BAA2B,EAC3B,0BAA0B,EAC1B,kBAAkB,EAClB,qBAAqB,EACrB,yBAAyB,EACzB,YAAY,EACZ,WAAW,EACZ,MAAM,kBAAkB,CAAC;AAG1B,MAAM,qBAAqB,GAAG,YAAY,CAAC;AAC3C,MAAM,iBAAiB,GAAG;IACxB,QAAQ;IACR,mBAAmB;IACnB,gCAAgC;IAChC,KAAK;IACL,qBAAqB;IACrB,QAAQ;IACR,2CAA2C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,CAAC,GAAG,EAAE,KAAK,CAAC;QACnB,OAAO,GAAG,CAAC,GAAG,KAAK,UAAU;QAC7B,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC;QACnB,OAAO,GAAG,CAAC,GAAG,KAAK,UAAU,CAC9B,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import { hasProp, loadScript } from '../../utils';\n\nimport {\n CoordsCannotBeParsedError,\n GeocoderFailedError,\n GeolocationUnsupportedError,\n GoogleMapsAPINotFoundError,\n IsNotAnObjectError,\n LocationNotFoundError,\n ProviderNotSupportedError,\n QUERY_FIELDS,\n QUERY_TYPES\n} from './Location.types';\nimport type { Bias, LatLng, MapsProvider, ProviderOpts, Location } from './Location.types';\n\nconst GOOGLE_MAPS_SCRIPT_ID = 'google-map';\nconst DegreeRegexChunks = [\n /^[-+]?/,\n // latitude degrees\n /([0-9]|[1-8][0-9]|90)(\\.\\d+)?°/,\n /\\s?/,\n // latitude direction\n /(N|S)?/,\n // sepeartor between latitude and longitude\n /(,|,\\s|\\s)/,\n /[-+]?/,\n // longitude degrees\n /([0-9]|[1-9][0-9]|1[0-7][0-9]|180)(\\.\\d+)?°/,\n /\\s?/,\n // longitude direction\n /(W|E)?$/\n];\n\nconst DegreeRegularExpression = new RegExp(DegreeRegexChunks.map(c => c.source).join(''));\n\nconst DMRegexChunks = [\n /^[-+]?/,\n // latitude degrees\n /([0-9]|[1-8][0-9]|90)°/,\n /\\s?/,\n // latitude minutes\n /([0-9]|[0-5][0-9])(\\.\\d+)?('|’)/,\n /\\s?/,\n // latitude direction\n /(N|S)?/,\n // sepeartor between latitude and longitude\n /(,|,\\s|\\s)/,\n /[-+]?/,\n // longitude degrees\n /([0-9]|[1-9][0-9]|1[0-7][0-9]|180)°/,\n /\\s?/,\n // longitude minutes\n /([0-9]|[0-5][0-9])(\\.\\d+)?('|’)/,\n /\\s?/,\n // longitude direction\n /(W|E)?$/\n];\n\nconst DMRegularExpression = new RegExp(DMRegexChunks.map(c => c.source).join(''));\nconst DMSRegexChunks = [\n /^[-+]?/,\n // latitude degrees\n /([0-9]|[1-8][0-9]|90)°/,\n /\\s?/,\n // latitude minutes\n /([0-9]|[0-5][0-9])('|’)/,\n /\\s?/,\n // latitude seconds\n /([0-9]|[0-5][0-9])(\\.\\d+)?(\"|″)/,\n /\\s?/,\n // latitude direction\n /(N|S)?/,\n // sepeartor between latitude and longitude\n /(,|,\\s|\\s)/,\n /[-+]?/,\n // longitude degrees\n /([0-9]|[1-9][0-9]|1[0-7][0-9]|180)°/,\n /\\s?/,\n // longitude minutes\n /([0-9]|[0-5][0-9])('|’)/,\n /\\s?/,\n // longitude seconds\n /([0-9]|[0-5][0-9])(\\.\\d+)?(\"|″)/,\n /\\s?/,\n // longitude direction\n /(W|E)?$/\n];\n\nconst DMSRegularExpression = new RegExp(DMSRegexChunks.map(c => c.source).join(''));\n\nconst decimalRegexChunks = [\n /^[-+]?/,\n /([0-9]|[1-8][0-9]|90)/,\n /(\\.\\d+)?/,\n /(,|\\s|,\\s)/,\n /[-+]?/,\n /([0-9]|[1-9][0-9]|1[0-7][0-9]|180)/,\n /(\\.\\d+)?$/\n];\n\nconst decimalFormatCoordinatesRegularExpression = new RegExp(\n decimalRegexChunks.map(c => c.source).join('')\n);\n\nconst providers: {\n [key: string]: MapsProvider;\n} = {\n google: {\n name: 'Google',\n loadedPromise: null,\n loadedApiKey: '',\n loadAPI(opts) {\n const params = new URLSearchParams(\n Object.entries({\n key: opts.apiKey,\n region: opts.region,\n language: opts.language,\n libraries: 'places'\n }).filter(([, value]) => value !== undefined)\n ).toString();\n\n const loadedScript = document.getElementById(GOOGLE_MAPS_SCRIPT_ID);\n if (loadedScript) {\n loadedScript.remove();\n // https://stackoverflow.com/questions/29930274/fixing-you-have-included-the-google-maps-api-multiple-times-on-this-page-this\n delete (window as any).google;\n }\n\n return new Promise((resolve, reject) => {\n loadScript(\n `https://maps.googleapis.com/maps/api/js?${params}`,\n function onLoad(this: HTMLScriptElement) {\n this.id = GOOGLE_MAPS_SCRIPT_ID;\n return resolve();\n },\n () => reject(new Error(GoogleMapsAPINotFoundError))\n );\n });\n }\n },\n undefined: {\n name: 'undefined',\n loadedPromise: null,\n loadedApiKey: '',\n loadAPI: data => Promise.reject(new Error(`${ProviderNotSupportedError}: ${data.name}`))\n }\n};\n\nexport async function loadMapsAPI(name: string = '', opts?: ProviderOpts): Promise<void> {\n if (typeof opts !== 'object' || !opts) {\n throw new Error(IsNotAnObjectError);\n }\n\n const provider = providers[name] ?? providers.undefined;\n\n if (!provider.loadedPromise || provider.loadedApiKey !== opts?.apiKey) {\n provider.loadedApiKey = opts?.apiKey;\n provider.loadedPromise = provider.loadAPI(opts);\n }\n return provider.loadedPromise;\n}\n\n/**\n * Identifies coordinates in degree format\n * eg. 45.78°N 9.11°E\n */\nexport function isValueDegreeFormatCoordinate(value: string): boolean {\n return DegreeRegularExpression.test(value);\n}\n\n/**\n * Identifies coordinates in degree, minute format\n * eg. 45°45.4’N 9°23’E\n */\nexport function isValueDMCoordinate(value: string): boolean {\n return DMRegularExpression.test(value);\n}\n\n/**\n * Identifies coordinates in degree, minute, second format\n * eg. 45°45’32.4″N 9°23’39.9″E\n */\nexport function isValueDMSCoordinate(value: string): boolean {\n return DMSRegularExpression.test(value);\n}\n\n/**\n * Identifies coordinates in decimal format\n * eg. 14.678, -38.765\n */\nexport function isValueACoordinate(value: string): boolean {\n return (\n decimalFormatCoordinatesRegularExpression.test(value) ||\n isValueDMSCoordinate(value) ||\n isValueDMCoordinate(value) ||\n isValueDegreeFormatCoordinate(value)\n );\n}\n\ninterface DMSParts {\n degrees: number;\n minutes?: number;\n seconds?: number;\n}\n\n/**\n * Converts DMS (degree, minute, second) format latitude/longitude into decimal format.\n */\nfunction convertDMSToDD({ degrees, minutes, seconds }: DMSParts, direction?: string): number {\n let dd = degrees;\n if (minutes) {\n if (degrees > 0) dd += minutes / 60;\n if (degrees < 0) dd -= minutes / 60;\n }\n if (seconds) {\n if (degrees > 0) dd += seconds / (60 * 60);\n if (degrees < 0) dd -= seconds / (60 * 60);\n }\n\n if (degrees > 0 && (direction === 'S' || direction === 'W')) {\n dd *= -1;\n }\n\n return dd;\n}\n\n/**\n * Parses DMS (degree, minute, second) format string into decimal format coordinates.\n */\nexport function parseDMS(input: string): number[] {\n if (isValueDMSCoordinate(input)) {\n const parts = input.split(/'|’|\"\\s?|″\\s?|°|,?\\s|,\\s?/);\n\n const lat = convertDMSToDD(\n { degrees: Number(parts[0]), minutes: Number(parts[1]), seconds: Number(parts[2]) },\n parts[3]\n );\n const lng = convertDMSToDD(\n { degrees: Number(parts[4]), minutes: Number(parts[5]), seconds: Number(parts[6]) },\n parts[7]\n );\n return [lat, lng];\n }\n if (isValueDMCoordinate(input)) {\n const parts = input.split(/'\\s?|’\\s?|°|,?\\s|,\\s?/);\n\n const lat = convertDMSToDD({ degrees: Number(parts[0]), minutes: Number(parts[1]) }, parts[2]);\n const lng = convertDMSToDD({ degrees: Number(parts[3]), minutes: Number(parts[4]) }, parts[5]);\n return [lat, lng];\n }\n\n const parts = input.split(/°\\s?|,?\\s|,\\s?/);\n\n const lat = convertDMSToDD({ degrees: Number(parts[0]) }, parts[1]);\n const lng = convertDMSToDD({ degrees: Number(parts[2]) }, parts[3]);\n return [lat, lng];\n}\n\nexport async function getNavigatorPosition(): Promise<LatLng> {\n if (!navigator.geolocation) throw new Error(GeolocationUnsupportedError);\n\n return new Promise((resolve, reject) => {\n navigator.geolocation.getCurrentPosition(\n currentLocation => {\n resolve({\n latitude: currentLocation.coords.latitude,\n longitude: currentLocation.coords.longitude\n });\n },\n error => reject(new Error(error.message))\n );\n });\n}\n\nexport function toGoogleLatLng(coords: LatLng): google.maps.LatLng {\n return new google.maps.LatLng(coords.latitude, coords.longitude);\n}\n\n/** Returns an array of place prediction objects ('place' can be an establishment, geographic location, or prominent point of interest)\n * and session token (valid for multiple queries, followed by one place selection).\n */\nexport async function getPlacePredictions(\n location: string,\n bias: Bias = {}\n): Promise<{\n placePredictions: google.maps.places.AutocompletePrediction[];\n token: google.maps.places.AutocompleteSessionToken;\n}> {\n const autocompleteService = new google.maps.places.AutocompleteService();\n const optionalParams: Partial<google.maps.places.AutocompletionRequest> = {};\n if (bias?.location) {\n if (bias?.location.center === 'current') {\n await getNavigatorPosition()\n .then(coords => {\n optionalParams.location = toGoogleLatLng(coords);\n optionalParams.radius = bias.location!.radius;\n })\n // no-op user didn't allow location\n .catch(() => {});\n } else {\n optionalParams.location = toGoogleLatLng(bias.location.center);\n optionalParams.radius = bias.location.radius;\n }\n }\n\n if (bias?.bounds) {\n const [sw, ne] = bias.bounds;\n optionalParams.bounds = new google.maps.LatLngBounds(toGoogleLatLng(sw), toGoogleLatLng(ne));\n }\n return new Promise((resolve, reject) => {\n const token = new google.maps.places.AutocompleteSessionToken();\n autocompleteService.getPlacePredictions(\n {\n input: location,\n types: QUERY_TYPES,\n sessionToken: token,\n ...optionalParams\n },\n (placePredictions, status) => {\n if (status === google.maps.places.PlacesServiceStatus.OK) {\n resolve({ placePredictions: placePredictions ?? [], token });\n } else {\n reject(new Error(LocationNotFoundError));\n }\n }\n );\n });\n}\n\nexport async function getPlace(\n location: string,\n mapElement: HTMLDivElement = document.createElement('div')\n): Promise<LatLng> {\n const placesService = new google.maps.places.PlacesService(mapElement);\n const { placePredictions, token } = await getPlacePredictions(location);\n return new Promise((resolve, reject) => {\n placesService.getDetails(\n { placeId: placePredictions[0]?.place_id, fields: QUERY_FIELDS, sessionToken: token },\n (place, pStatus) => {\n if (pStatus === google.maps.places.PlacesServiceStatus.OK) {\n resolve({\n latitude: place?.geometry?.location?.lat() || NaN,\n longitude: place?.geometry?.location?.lng() || NaN\n });\n } else {\n reject(new Error(LocationNotFoundError));\n }\n }\n );\n });\n}\n\nexport async function getPlaceById(\n placeId: string,\n sessionToken: google.maps.places.AutocompleteSessionToken = new google.maps.places.AutocompleteSessionToken(),\n mapElement: HTMLDivElement = document.createElement('div')\n): Promise<Location> {\n const placesService = new google.maps.places.PlacesService(mapElement);\n return new Promise((resolve, reject) => {\n placesService.getDetails({ placeId, fields: QUERY_FIELDS, sessionToken }, (place, pStatus) => {\n if (pStatus === google.maps.places.PlacesServiceStatus.OK) {\n resolve({\n name: place?.name,\n address: place?.formatted_address,\n latitude: place?.geometry?.location?.lat() || NaN,\n longitude: place?.geometry?.location?.lng() || NaN\n });\n } else {\n reject(new Error(LocationNotFoundError));\n }\n });\n });\n}\n\n/** Returns coordinations for given input: either coords, address or current position. */\nexport async function getCoords(\n coords: string | 'current' | LatLng,\n mapElement?: HTMLDivElement\n): Promise<LatLng> {\n if (coords === '' || coords === undefined) throw new Error();\n if (coords === 'current') return getNavigatorPosition();\n\n let location: LatLng;\n if (typeof coords === 'string') {\n let latLng: number[] = [];\n if (\n isValueDMSCoordinate(coords) ||\n isValueDMCoordinate(coords) ||\n isValueDegreeFormatCoordinate(coords)\n ) {\n latLng = parseDMS(coords);\n } else {\n let splitter;\n if (coords.includes(', ')) {\n splitter = ', ';\n } else if (coords.includes(',')) {\n splitter = ',';\n } else if (coords.includes(' ')) {\n splitter = ' ';\n } else {\n splitter = ', ';\n }\n\n latLng = coords.split(splitter).map(Number);\n }\n\n const [lat, lng] = latLng;\n if (Number.isNaN(lat) || Number.isNaN(lng) || lat === undefined || lng === undefined)\n return getPlace(coords, mapElement);\n location = { latitude: lat, longitude: lng };\n } else {\n location = coords;\n }\n\n if (Number.isFinite(location.latitude) && Number.isFinite(location.longitude)) return location;\n\n throw new Error(CoordsCannotBeParsedError);\n}\n\nexport async function getAddress(\n coords: LatLng\n): Promise<{ name: string; address?: string; latitude: number; longitude: number }> {\n const location = {\n lat: coords.latitude,\n lng: coords.longitude\n };\n const geocoder = new google.maps.Geocoder();\n return new Promise((resolve, reject) => {\n geocoder.geocode(\n { location },\n (results: google.maps.GeocoderResult[] | null, status: google.maps.GeocoderStatus) => {\n if (status === 'OK') {\n const [result] = results ?? [];\n if (result) {\n resolve({\n name: result.formatted_address,\n address: result.formatted_address,\n ...(result.geometry && {\n latitude: result.geometry.location.lat(),\n longitude: result.geometry.location.lng()\n })\n });\n } else {\n resolve({\n name: `${coords.latitude}, ${coords.longitude}`,\n latitude: coords.latitude,\n longitude: coords.longitude\n });\n }\n } else {\n reject(new Error(`${GeocoderFailedError}: ${status}`));\n }\n }\n );\n });\n}\n\nexport const isLatLngObject = (obj: any): obj is google.maps.LatLng => {\n return (\n !!obj &&\n typeof obj === 'object' &&\n hasProp(obj, 'lat') &&\n typeof obj.lat === 'function' &&\n hasProp(obj, 'lng') &&\n typeof obj.lng === 'function'\n );\n};\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/components/Location/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,2BAA2B,CAAC;AAEnD,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAEtC,OAAO,EACL,yBAAyB,EACzB,mBAAmB,EACnB,2BAA2B,EAC3B,0BAA0B,EAC1B,kBAAkB,EAClB,qBAAqB,EACrB,yBAAyB,EACzB,YAAY,EACZ,WAAW,EACZ,MAAM,kBAAkB,CAAC;AAG1B,MAAM,iBAAiB,GAAG;IACxB,QAAQ;IACR,mBAAmB;IACnB,gCAAgC;IAChC,KAAK;IACL,qBAAqB;IACrB,QAAQ;IACR,2CAA2C;IAC3C,YAAY;IACZ,OAAO;IACP,oBAAoB;IACpB,6CAA6C;IAC7C,KAAK;IACL,sBAAsB;IACtB,SAAS;CACV,CAAC;AAEF,MAAM,uBAAuB,GAAG,IAAI,MAAM,CAAC,iBAAiB,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;AAE1F,MAAM,aAAa,GAAG;IACpB,QAAQ;IACR,mBAAmB;IACnB,wBAAwB;IACxB,KAAK;IACL,mBAAmB;IACnB,iCAAiC;IACjC,KAAK;IACL,qBAAqB;IACrB,QAAQ;IACR,2CAA2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SAAS,EAAE,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,EAAE;yBAC1C,CAAC;qBACH,CAAC,CAAC;iBACJ;qBAAM;oBACL,OAAO,CAAC;wBACN,IAAI,EAAE,GAAG,MAAM,CAAC,QAAQ,KAAK,MAAM,CAAC,SAAS,EAAE;wBAC/C,QAAQ,EAAE,MAAM,CAAC,QAAQ;wBACzB,SAAS,EAAE,MAAM,CAAC,SAAS;qBAC5B,CAAC,CAAC;iBACJ;aACF;iBAAM;gBACL,MAAM,CAAC,IAAI,KAAK,CAAC,GAAG,mBAAmB,KAAK,MAAM,EAAE,CAAC,CAAC,CAAC;aACxD;QACH,CAAC,CACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,GAAQ,EAA6B,EAAE;IACpE,OAAO,CACL,CAAC,CAAC,GAAG;QACL,OAAO,GAAG,KAAK,QAAQ;QACvB,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC;QACnB,OAAO,GAAG,CAAC,GAAG,KAAK,UAAU;QAC7B,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC;QACnB,OAAO,GAAG,CAAC,GAAG,KAAK,UAAU,CAC9B,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import { Loader } from '@googlemaps/js-api-loader';\n\nimport { hasProp } from '../../utils';\n\nimport {\n CoordsCannotBeParsedError,\n GeocoderFailedError,\n GeolocationUnsupportedError,\n GoogleMapsAPINotFoundError,\n IsNotAnObjectError,\n LocationNotFoundError,\n ProviderNotSupportedError,\n QUERY_FIELDS,\n QUERY_TYPES\n} from './Location.types';\nimport type { Bias, LatLng, MapsProvider, ProviderOpts, Location } from './Location.types';\n\nconst DegreeRegexChunks = [\n /^[-+]?/,\n // latitude degrees\n /([0-9]|[1-8][0-9]|90)(\\.\\d+)?°/,\n /\\s?/,\n // latitude direction\n /(N|S)?/,\n // sepeartor between latitude and longitude\n /(,|,\\s|\\s)/,\n /[-+]?/,\n // longitude degrees\n /([0-9]|[1-9][0-9]|1[0-7][0-9]|180)(\\.\\d+)?°/,\n /\\s?/,\n // longitude direction\n /(W|E)?$/\n];\n\nconst DegreeRegularExpression = new RegExp(DegreeRegexChunks.map(c => c.source).join(''));\n\nconst DMRegexChunks = [\n /^[-+]?/,\n // latitude degrees\n /([0-9]|[1-8][0-9]|90)°/,\n /\\s?/,\n // latitude minutes\n /([0-9]|[0-5][0-9])(\\.\\d+)?('|’)/,\n /\\s?/,\n // latitude direction\n /(N|S)?/,\n // sepeartor between latitude and longitude\n /(,|,\\s|\\s)/,\n /[-+]?/,\n // longitude degrees\n /([0-9]|[1-9][0-9]|1[0-7][0-9]|180)°/,\n /\\s?/,\n // longitude minutes\n /([0-9]|[0-5][0-9])(\\.\\d+)?('|’)/,\n /\\s?/,\n // longitude direction\n /(W|E)?$/\n];\n\nconst DMRegularExpression = new RegExp(DMRegexChunks.map(c => c.source).join(''));\nconst DMSRegexChunks = [\n /^[-+]?/,\n // latitude degrees\n /([0-9]|[1-8][0-9]|90)°/,\n /\\s?/,\n // latitude minutes\n /([0-9]|[0-5][0-9])('|’)/,\n /\\s?/,\n // latitude seconds\n /([0-9]|[0-5][0-9])(\\.\\d+)?(\"|″)/,\n /\\s?/,\n // latitude direction\n /(N|S)?/,\n // sepeartor between latitude and longitude\n /(,|,\\s|\\s)/,\n /[-+]?/,\n // longitude degrees\n /([0-9]|[1-9][0-9]|1[0-7][0-9]|180)°/,\n /\\s?/,\n // longitude minutes\n /([0-9]|[0-5][0-9])('|’)/,\n /\\s?/,\n // longitude seconds\n /([0-9]|[0-5][0-9])(\\.\\d+)?(\"|″)/,\n /\\s?/,\n // longitude direction\n /(W|E)?$/\n];\n\nconst DMSRegularExpression = new RegExp(DMSRegexChunks.map(c => c.source).join(''));\n\nconst decimalRegexChunks = [\n /^[-+]?/,\n /([0-9]|[1-8][0-9]|90)/,\n /(\\.\\d+)?/,\n /(,|\\s|,\\s)/,\n /[-+]?/,\n /([0-9]|[1-9][0-9]|1[0-7][0-9]|180)/,\n /(\\.\\d+)?$/\n];\n\nconst decimalFormatCoordinatesRegularExpression = new RegExp(\n decimalRegexChunks.map(c => c.source).join('')\n);\n\nconst providers: {\n [key: string]: MapsProvider;\n} = {\n google: {\n name: 'Google',\n loadedPromise: null,\n loadedApiKey: '',\n loadAPI(opts) {\n const loader = new Loader({\n version: '3.55',\n apiKey: opts.apiKey,\n region: opts.region,\n language: opts.language\n });\n\n return Promise.all([\n loader.importLibrary('core'),\n loader.importLibrary('maps'),\n loader.importLibrary('places'),\n loader.importLibrary('marker')\n ]).then(\n () => {},\n () => {\n throw new Error(GoogleMapsAPINotFoundError);\n }\n );\n }\n },\n undefined: {\n name: 'undefined',\n loadedPromise: null,\n loadedApiKey: '',\n loadAPI: data => Promise.reject(new Error(`${ProviderNotSupportedError}: ${data.name}`))\n }\n};\n\nexport async function loadMapsAPI(name: string = '', opts?: ProviderOpts): Promise<void> {\n if (typeof opts !== 'object' || !opts) {\n throw new Error(IsNotAnObjectError);\n }\n\n const provider = providers[name] ?? providers.undefined;\n\n if (!provider.loadedPromise) {\n provider.loadedPromise = provider\n .loadAPI(opts)\n .then(() => {\n provider.loadedApiKey = opts?.apiKey;\n })\n .catch(() => {\n provider.loadedPromise = null;\n });\n }\n return provider.loadedPromise;\n}\n\n/**\n * Identifies coordinates in degree format\n * eg. 45.78°N 9.11°E\n */\nexport function isValueDegreeFormatCoordinate(value: string): boolean {\n return DegreeRegularExpression.test(value);\n}\n\n/**\n * Identifies coordinates in degree, minute format\n * eg. 45°45.4’N 9°23’E\n */\nexport function isValueDMCoordinate(value: string): boolean {\n return DMRegularExpression.test(value);\n}\n\n/**\n * Identifies coordinates in degree, minute, second format\n * eg. 45°45’32.4″N 9°23’39.9″E\n */\nexport function isValueDMSCoordinate(value: string): boolean {\n return DMSRegularExpression.test(value);\n}\n\n/**\n * Identifies coordinates in decimal format\n * eg. 14.678, -38.765\n */\nexport function isValueACoordinate(value: string): boolean {\n return (\n decimalFormatCoordinatesRegularExpression.test(value) ||\n isValueDMSCoordinate(value) ||\n isValueDMCoordinate(value) ||\n isValueDegreeFormatCoordinate(value)\n );\n}\n\ninterface DMSParts {\n degrees: number;\n minutes?: number;\n seconds?: number;\n}\n\n/**\n * Converts DMS (degree, minute, second) format latitude/longitude into decimal format.\n */\nfunction convertDMSToDD({ degrees, minutes, seconds }: DMSParts, direction?: string): number {\n let dd = degrees;\n if (minutes) {\n if (degrees > 0) dd += minutes / 60;\n if (degrees < 0) dd -= minutes / 60;\n }\n if (seconds) {\n if (degrees > 0) dd += seconds / (60 * 60);\n if (degrees < 0) dd -= seconds / (60 * 60);\n }\n\n if (degrees > 0 && (direction === 'S' || direction === 'W')) {\n dd *= -1;\n }\n\n return dd;\n}\n\n/**\n * Parses DMS (degree, minute, second) format string into decimal format coordinates.\n */\nexport function parseDMS(input: string): number[] {\n if (isValueDMSCoordinate(input)) {\n const parts = input.split(/'|’|\"\\s?|″\\s?|°|,?\\s|,\\s?/);\n\n const lat = convertDMSToDD(\n { degrees: Number(parts[0]), minutes: Number(parts[1]), seconds: Number(parts[2]) },\n parts[3]\n );\n const lng = convertDMSToDD(\n { degrees: Number(parts[4]), minutes: Number(parts[5]), seconds: Number(parts[6]) },\n parts[7]\n );\n return [lat, lng];\n }\n if (isValueDMCoordinate(input)) {\n const parts = input.split(/'\\s?|’\\s?|°|,?\\s|,\\s?/);\n\n const lat = convertDMSToDD({ degrees: Number(parts[0]), minutes: Number(parts[1]) }, parts[2]);\n const lng = convertDMSToDD({ degrees: Number(parts[3]), minutes: Number(parts[4]) }, parts[5]);\n return [lat, lng];\n }\n\n const parts = input.split(/°\\s?|,?\\s|,\\s?/);\n\n const lat = convertDMSToDD({ degrees: Number(parts[0]) }, parts[1]);\n const lng = convertDMSToDD({ degrees: Number(parts[2]) }, parts[3]);\n return [lat, lng];\n}\n\nexport async function getNavigatorPosition(): Promise<LatLng> {\n if (!navigator.geolocation) throw new Error(GeolocationUnsupportedError);\n\n return new Promise((resolve, reject) => {\n navigator.geolocation.getCurrentPosition(\n currentLocation => {\n resolve({\n latitude: currentLocation.coords.latitude,\n longitude: currentLocation.coords.longitude\n });\n },\n error => reject(new Error(error.message))\n );\n });\n}\n\nexport function toGoogleLatLng(coords: LatLng): google.maps.LatLng {\n return new google.maps.LatLng(coords.latitude, coords.longitude);\n}\n\n/** Returns an array of place prediction objects ('place' can be an establishment, geographic location, or prominent point of interest)\n * and session token (valid for multiple queries, followed by one place selection).\n */\nexport async function getPlacePredictions(\n location: string,\n bias: Bias = {}\n): Promise<{\n placePredictions: google.maps.places.AutocompletePrediction[];\n token: google.maps.places.AutocompleteSessionToken;\n}> {\n const autocompleteService = new google.maps.places.AutocompleteService();\n const optionalParams: Partial<google.maps.places.AutocompletionRequest> = {};\n if (bias?.location) {\n if (bias?.location.center === 'current') {\n await getNavigatorPosition()\n .then(coords => {\n optionalParams.location = toGoogleLatLng(coords);\n optionalParams.radius = bias.location!.radius;\n })\n // no-op user didn't allow location\n .catch(() => {});\n } else {\n optionalParams.location = toGoogleLatLng(bias.location.center);\n optionalParams.radius = bias.location.radius;\n }\n }\n\n if (bias?.bounds) {\n const [sw, ne] = bias.bounds;\n optionalParams.bounds = new google.maps.LatLngBounds(toGoogleLatLng(sw), toGoogleLatLng(ne));\n }\n return new Promise((resolve, reject) => {\n const token = new google.maps.places.AutocompleteSessionToken();\n autocompleteService.getPlacePredictions(\n {\n input: location,\n types: QUERY_TYPES,\n sessionToken: token,\n ...optionalParams\n },\n (placePredictions, status) => {\n if (status === google.maps.places.PlacesServiceStatus.OK) {\n resolve({ placePredictions: placePredictions ?? [], token });\n } else {\n reject(new Error(LocationNotFoundError));\n }\n }\n );\n });\n}\n\nexport async function getPlace(\n location: string,\n mapElement: HTMLDivElement = document.createElement('div')\n): Promise<LatLng> {\n const placesService = new google.maps.places.PlacesService(mapElement);\n const { placePredictions, token } = await getPlacePredictions(location);\n return new Promise((resolve, reject) => {\n placesService.getDetails(\n { placeId: placePredictions[0]?.place_id, fields: QUERY_FIELDS, sessionToken: token },\n (place, pStatus) => {\n if (pStatus === google.maps.places.PlacesServiceStatus.OK) {\n resolve({\n latitude: place?.geometry?.location?.lat() || NaN,\n longitude: place?.geometry?.location?.lng() || NaN\n });\n } else {\n reject(new Error(LocationNotFoundError));\n }\n }\n );\n });\n}\n\nexport async function getPlaceById(\n placeId: string,\n sessionToken: google.maps.places.AutocompleteSessionToken = new google.maps.places.AutocompleteSessionToken(),\n mapElement: HTMLDivElement = document.createElement('div')\n): Promise<Location> {\n const placesService = new google.maps.places.PlacesService(mapElement);\n return new Promise((resolve, reject) => {\n placesService.getDetails({ placeId, fields: QUERY_FIELDS, sessionToken }, (place, pStatus) => {\n if (pStatus === google.maps.places.PlacesServiceStatus.OK) {\n resolve({\n name: place?.name,\n address: place?.formatted_address,\n latitude: place?.geometry?.location?.lat() || NaN,\n longitude: place?.geometry?.location?.lng() || NaN\n });\n } else {\n reject(new Error(LocationNotFoundError));\n }\n });\n });\n}\n\n/** Returns coordinations for given input: either coords, address or current position. */\nexport async function getCoords(\n coords: string | 'current' | LatLng,\n mapElement?: HTMLDivElement\n): Promise<LatLng> {\n if (coords === '' || coords === undefined) throw new Error();\n if (coords === 'current') return getNavigatorPosition();\n\n let location: LatLng;\n if (typeof coords === 'string') {\n let latLng: number[] = [];\n if (\n isValueDMSCoordinate(coords) ||\n isValueDMCoordinate(coords) ||\n isValueDegreeFormatCoordinate(coords)\n ) {\n latLng = parseDMS(coords);\n } else {\n let splitter;\n if (coords.includes(', ')) {\n splitter = ', ';\n } else if (coords.includes(',')) {\n splitter = ',';\n } else if (coords.includes(' ')) {\n splitter = ' ';\n } else {\n splitter = ', ';\n }\n\n latLng = coords.split(splitter).map(Number);\n }\n\n const [lat, lng] = latLng;\n if (Number.isNaN(lat) || Number.isNaN(lng) || lat === undefined || lng === undefined)\n return getPlace(coords, mapElement);\n location = { latitude: lat, longitude: lng };\n } else {\n location = coords;\n }\n\n if (Number.isFinite(location.latitude) && Number.isFinite(location.longitude)) return location;\n\n throw new Error(CoordsCannotBeParsedError);\n}\n\nexport async function getAddress(\n coords: LatLng\n): Promise<{ name: string; address?: string; latitude: number; longitude: number }> {\n const location = {\n lat: coords.latitude,\n lng: coords.longitude\n };\n const geocoder = new google.maps.Geocoder();\n return new Promise((resolve, reject) => {\n geocoder.geocode(\n { location },\n (results: google.maps.GeocoderResult[] | null, status: google.maps.GeocoderStatus) => {\n if (status === 'OK') {\n const [result] = results ?? [];\n if (result) {\n resolve({\n name: result.formatted_address,\n address: result.formatted_address,\n ...(result.geometry && {\n latitude: result.geometry.location.lat(),\n longitude: result.geometry.location.lng()\n })\n });\n } else {\n resolve({\n name: `${coords.latitude}, ${coords.longitude}`,\n latitude: coords.latitude,\n longitude: coords.longitude\n });\n }\n } else {\n reject(new Error(`${GeocoderFailedError}: ${status}`));\n }\n }\n );\n });\n}\n\nexport const isLatLngObject = (obj: any): obj is google.maps.LatLng => {\n return (\n !!obj &&\n typeof obj === 'object' &&\n hasProp(obj, 'lat') &&\n typeof obj.lat === 'function' &&\n hasProp(obj, 'lng') &&\n typeof obj.lng === 'function'\n );\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"ModalManager.d.ts","sourceRoot":"","sources":["../../../src/components/Modal/ModalManager.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAA2B,OAAO,EAAE,MAAM,OAAO,CAAC;AAMjF,OAAO,YAAY,CAAC;AAGpB,OAAO,KAAK,EAIV,iBAAiB,EAEjB,wBAAwB,EACzB,MAAM,eAAe,CAAC;AAGvB,OAAO,QAAQ,YAAY,CAAC;IAC1B,UAAiB,aAAa;QAC5B,mBAAmB,CAAC,EAAE,OAAO,CAAC,wBAAwB,CAAC,CAAC;KACzD;CACF;AAgKD,QAAA,MAAM,YAAY,EAAE,iBAAiB,CAAC,iBAAiB,CAsHtD,CAAC;AAEF,eAAe,YAAY,CAAC"}
1
+ {"version":3,"file":"ModalManager.d.ts","sourceRoot":"","sources":["../../../src/components/Modal/ModalManager.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAA2B,OAAO,EAAE,MAAM,OAAO,CAAC;AAMjF,OAAO,YAAY,CAAC;AAGpB,OAAO,KAAK,EAIV,iBAAiB,EAEjB,wBAAwB,EACzB,MAAM,eAAe,CAAC;AAGvB,OAAO,QAAQ,YAAY,CAAC;IAC1B,UAAiB,aAAa;QAC5B,mBAAmB,CAAC,EAAE,OAAO,CAAC,wBAAwB,CAAC,CAAC;KACzD;CACF;AAgKD,QAAA,MAAM,YAAY,EAAE,iBAAiB,CAAC,iBAAiB,CA0HtD,CAAC;AAEF,eAAe,YAAY,CAAC"}
@@ -98,8 +98,12 @@ const ModalManager = ({ children }) => {
98
98
  dispatch({ action: 'dismiss', modal: { id } });
99
99
  options?.onDismiss?.(id);
100
100
  const initiator = initiatorRef?.deref();
101
+ const currentActiveElement = getActiveElement();
101
102
  if (initiator?.isConnected &&
102
- (initiator instanceof HTMLElement || initiator instanceof SVGElement)) {
103
+ (initiator instanceof HTMLElement || initiator instanceof SVGElement) &&
104
+ currentActiveElement !== null &&
105
+ (currentActiveElement.closest('[aria-modal="true"]') !== null ||
106
+ currentActiveElement === document.body)) {
103
107
  initiator.focus();
104
108
  }
105
109
  },
@@ -1 +1 @@
1
- {"version":3,"file":"ModalManager.js","sourceRoot":"","sources":["../../../src/components/Modal/ModalManager.tsx"],"names":[],"mappings":";;AAAA,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,OAAO,CAAC;AAEzE,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAC7E,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEhE,OAAO,YAA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,CAAC;IAEF,SAAS,CAAC,GAAG,EAAE;QACb,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,KAAK,KAAK,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE;YAC3E,aAAa,EAAE,CAAC;SACjB;aAAM;YACL,YAAY,EAAE,CAAC;SAChB;IACH,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;IAEb,MAAM,EAAE,YAAY,EAAE,GAAG,gBAAgB,EAAE,CAAC;IAE5C,MAAM,OAAO,GAAG,iBAAiB;QAC/B,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,mBAAmB,IAAI,mBAAmB;QAC1D,CAAC,CAAC,mBAAmB,CAAC;IACxB,MAAM,QAAQ,GAAG,UAAU,CAAC,OAAO,CAAC,CAAC;IAErC,yCAAyC;IACzC,IAAI,QAAQ,CAAC,WAAW;QAAE,OAAO,KAAC,OAAO,CAAC,QAAQ,IAAC,KAAK,EAAE,QAAQ,YAAG,QAAQ,GAAoB,CAAC;IAElG,OAAO,CACL,MAAC,OAAO,CAAC,QAAQ,IAAC,KAAK,EAAE,aAAa,aACnC,QAAQ,EACR,MAAM,CAAC,MAAM,GAAG,CAAC;gBAChB,YAAY;gBACZ,YAAY,CAAC,KAAC,YAAY,IAAC,MAAM,EAAE,MAAM,GAAI,EAAE,YAAY,CAAC,IAC7C,CACpB,CAAC;AACJ,CAAC,CAAC;AAEF,eAAe,YAAY,CAAC","sourcesContent":["import { useReducer, useMemo, useEffect, useContext, memo } from 'react';\nimport type { FunctionComponent, ComponentType, Dispatch, Context } from 'react';\nimport { createPortal } from 'react-dom';\n\nimport { createUID, getActiveElement, windowIsAvailable } from '../../utils';\nimport { useConfiguration, useScrollToggle } from '../../hooks';\nimport type { ExcludeStrict, OmitStrict } from '../../types';\nimport '../../init';\n\nimport DockedModals from './DockedModals';\nimport type {\n ModalMethods,\n ModalOptions,\n ModalObject,\n ModalManagerProps,\n ModalState,\n ModalManagerContextValue\n} from './Modal.types';\nimport { ModalContext, ModalManagerContext } from './Contexts';\n\ndeclare module '../../init' {\n export interface CosmosGlobals {\n modalManagerContext?: Context<ModalManagerContextValue>;\n }\n}\n\ntype ModalAction =\n | 'create'\n | 'update'\n | 'minimize'\n | 'maximize'\n | 'dock'\n | 'activate'\n | 'dismiss'\n | 'unmount';\n\ntype ModalReducerPayload<P extends object> =\n | { action: 'create'; modal: ModalObject<P> }\n | {\n action: 'update';\n modal: Partial<OmitStrict<ModalObject<P>, 'props'>> &\n Pick<ModalObject, 'id'> & { props: Partial<ModalObject<P>['props']> };\n }\n | {\n action: ExcludeStrict<ModalAction, 'create' | 'update'>;\n modal: Pick<ModalObject, 'id'>;\n };\n\nconst reducer = <P extends object>(\n modals: ModalObject[],\n payload: ModalReducerPayload<P>\n): ModalObject<any>[] => {\n switch (payload.action) {\n case 'create':\n return [...modals, payload.modal];\n\n case 'unmount':\n return modals.filter(modal => modal.id !== payload.modal.id);\n\n case 'dismiss':\n return modals.map(modal => {\n modal.state = modal.id === payload.modal.id ? 'closed' : modal.state;\n return modal;\n });\n\n case 'update':\n return modals.map(modal => {\n modal.props =\n modal.id === payload.modal.id ? { ...modal.props, ...payload.modal.props } : modal.props;\n return modal;\n });\n\n case 'activate': {\n const newModals = modals.map(modal => {\n modal.state = modal.id === payload.modal.id ? 'open' : modal.state;\n return modal;\n });\n\n // Move the newly activated modal to the end of the list\n // to ensure it is shown on top of other active modals.\n const activatedModal = newModals.splice(\n newModals.findIndex(modal => modal.id === payload.modal.id),\n 1\n );\n\n return [...newModals, ...activatedModal];\n }\n\n case 'minimize':\n return modals.map(modal => {\n modal.state =\n modal.id === payload.modal.id && modal.options.minimizable ? 'minimized' : modal.state;\n return modal;\n });\n\n case 'maximize':\n return modals.map(modal => {\n modal.state =\n modal.id === payload.modal.id && modal.options.maximizable ? 'maximized' : modal.state;\n return modal;\n });\n\n case 'dock':\n return modals.map(modal => {\n modal.state =\n modal.id === payload.modal.id && modal.options.dockable ? 'docked' : 'minimized';\n return modal;\n });\n\n default:\n return modals;\n }\n};\n\nconst WrappedModal = memo(\n ({\n Component,\n id,\n options: { alert, dismissible, dockable, minimizable, maximizable },\n state,\n methods,\n props,\n top\n }: ModalObject & { top: boolean }) => (\n <ModalContext.Provider\n // eslint-disable-next-line react/jsx-no-constructed-context-values\n value={{\n id,\n alert,\n dismissible,\n minimizable,\n maximizable,\n dockable,\n state,\n top,\n initialized: true,\n ...methods\n }}\n >\n <Component {...props} />\n </ModalContext.Provider>\n )\n);\n\nconst RenderModals = ({ modals }: { modals: ModalObject[] }) => {\n const { open, minimized, alerts } = modals.reduce<{\n open: ModalObject[];\n minimized: ModalObject[];\n alerts: ModalObject[];\n }>(\n (obj, modal) => {\n if (modal.options.alert) obj.alerts.push(modal);\n else if (modal.state === 'minimized' || modal.state === 'docked') {\n obj.minimized.push(modal);\n } else obj.open.push(modal);\n\n return obj;\n },\n { open: [], minimized: [], alerts: [] }\n );\n\n return (\n <>\n {open.map((modal, i) => (\n <WrappedModal\n {...modal}\n top={alerts.length === 0 && i === open.length - 1}\n key={modal.id}\n />\n ))}\n {minimized.length > 0 && (\n <DockedModals>\n {minimized.map(modal => (\n <WrappedModal {...modal} top={false} key={modal.id} />\n ))}\n </DockedModals>\n )}\n {alerts.map((modal, i) => (\n <WrappedModal {...modal} top={i === open.length - 1} key={modal.id} />\n ))}\n </>\n );\n};\n\nconst ModalManager: FunctionComponent<ModalManagerProps> = ({ children }) => {\n const [modals, dispatch] = useReducer(reducer, []);\n const { disableScroll, enableScroll } = useScrollToggle();\n\n const providerValue = useMemo(\n () => ({\n create: <P extends object>(\n Component: ComponentType<P>,\n props?: P,\n options?: ModalOptions\n ) => {\n const id = options?.id || createUID();\n const activeElement = getActiveElement();\n const initiatorRef = activeElement ? new WeakRef(activeElement) : null;\n\n const methods: ModalMethods<P> = {\n dismiss: () => {\n dispatch({ action: 'dismiss', modal: { id } });\n options?.onDismiss?.(id);\n const initiator = initiatorRef?.deref();\n if (\n initiator?.isConnected &&\n (initiator instanceof HTMLElement || initiator instanceof SVGElement)\n ) {\n initiator.focus();\n }\n },\n update: updateProps => {\n (dispatch as Dispatch<ModalReducerPayload<P>>)({\n action: 'update',\n modal: { id, props: updateProps }\n });\n },\n minimize: () => {\n dispatch({ action: 'minimize', modal: { id } });\n options?.onMinimize?.(id);\n },\n maximize: () => {\n dispatch({ action: 'maximize', modal: { id } });\n options?.onMaximize?.(id);\n },\n dock: () => {\n dispatch({ action: 'dock', modal: { id } });\n options?.onDock?.(id);\n },\n activate: () => {\n dispatch({ action: 'activate', modal: { id } });\n options?.onActivate?.(id);\n },\n unmount: () => {\n dispatch({ action: 'unmount', modal: { id } });\n }\n };\n\n let defaultState: ModalState;\n if (options?.defaultMinimized) {\n defaultState = 'minimized';\n } else if (options?.dockable) {\n defaultState = 'docked';\n } else {\n defaultState = 'open';\n }\n\n (dispatch as Dispatch<ModalReducerPayload<P>>)({\n action: 'create',\n modal: {\n id,\n methods,\n Component,\n props,\n state: defaultState,\n options: {\n alert: false,\n minimizable: false,\n maximizable: false,\n dockable: false,\n defaultMinimized: false,\n unmountWhenMinimized: true,\n ...options,\n dismissible: !!(options?.alert ? false : options?.dismissible ?? true)\n }\n }\n });\n\n return methods;\n },\n ModalContext,\n initialized: true\n }),\n []\n );\n\n useEffect(() => {\n if (modals.some(modal => modal.state === 'open' && !modal.options.dockable)) {\n disableScroll();\n } else {\n enableScroll();\n }\n }, [modals]);\n\n const { portalTarget } = useConfiguration();\n\n const context = windowIsAvailable\n ? window.cosmos.modalManagerContext ?? ModalManagerContext\n : ModalManagerContext;\n const priorCtx = useContext(context);\n\n // Don't create additional Modal portals.\n if (priorCtx.initialized) return <context.Provider value={priorCtx}>{children}</context.Provider>;\n\n return (\n <context.Provider value={providerValue}>\n {children}\n {modals.length > 0 &&\n portalTarget &&\n createPortal(<RenderModals modals={modals} />, portalTarget)}\n </context.Provider>\n );\n};\n\n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EAAE,QAAQ,YAAG,QAAQ,GAAoB,CAAC;IAElG,OAAO,CACL,MAAC,OAAO,CAAC,QAAQ,IAAC,KAAK,EAAE,aAAa,aACnC,QAAQ,EACR,MAAM,CAAC,MAAM,GAAG,CAAC;gBAChB,YAAY;gBACZ,YAAY,CAAC,KAAC,YAAY,IAAC,MAAM,EAAE,MAAM,GAAI,EAAE,YAAY,CAAC,IAC7C,CACpB,CAAC;AACJ,CAAC,CAAC;AAEF,eAAe,YAAY,CAAC","sourcesContent":["import { useReducer, useMemo, useEffect, useContext, memo } from 'react';\nimport type { FunctionComponent, ComponentType, Dispatch, Context } from 'react';\nimport { createPortal } from 'react-dom';\n\nimport { createUID, getActiveElement, windowIsAvailable } from '../../utils';\nimport { useConfiguration, useScrollToggle } from '../../hooks';\nimport type { ExcludeStrict, OmitStrict } from '../../types';\nimport '../../init';\n\nimport DockedModals from './DockedModals';\nimport type {\n ModalMethods,\n ModalOptions,\n ModalObject,\n ModalManagerProps,\n ModalState,\n ModalManagerContextValue\n} from './Modal.types';\nimport { ModalContext, ModalManagerContext } from './Contexts';\n\ndeclare module '../../init' {\n export interface CosmosGlobals {\n modalManagerContext?: Context<ModalManagerContextValue>;\n }\n}\n\ntype ModalAction =\n | 'create'\n | 'update'\n | 'minimize'\n | 'maximize'\n | 'dock'\n | 'activate'\n | 'dismiss'\n | 'unmount';\n\ntype ModalReducerPayload<P extends object> =\n | { action: 'create'; modal: ModalObject<P> }\n | {\n action: 'update';\n modal: Partial<OmitStrict<ModalObject<P>, 'props'>> &\n Pick<ModalObject, 'id'> & { props: Partial<ModalObject<P>['props']> };\n }\n | {\n action: ExcludeStrict<ModalAction, 'create' | 'update'>;\n modal: Pick<ModalObject, 'id'>;\n };\n\nconst reducer = <P extends object>(\n modals: ModalObject[],\n payload: ModalReducerPayload<P>\n): ModalObject<any>[] => {\n switch (payload.action) {\n case 'create':\n return [...modals, payload.modal];\n\n case 'unmount':\n return modals.filter(modal => modal.id !== payload.modal.id);\n\n case 'dismiss':\n return modals.map(modal => {\n modal.state = modal.id === payload.modal.id ? 'closed' : modal.state;\n return modal;\n });\n\n case 'update':\n return modals.map(modal => {\n modal.props =\n modal.id === payload.modal.id ? { ...modal.props, ...payload.modal.props } : modal.props;\n return modal;\n });\n\n case 'activate': {\n const newModals = modals.map(modal => {\n modal.state = modal.id === payload.modal.id ? 'open' : modal.state;\n return modal;\n });\n\n // Move the newly activated modal to the end of the list\n // to ensure it is shown on top of other active modals.\n const activatedModal = newModals.splice(\n newModals.findIndex(modal => modal.id === payload.modal.id),\n 1\n );\n\n return [...newModals, ...activatedModal];\n }\n\n case 'minimize':\n return modals.map(modal => {\n modal.state =\n modal.id === payload.modal.id && modal.options.minimizable ? 'minimized' : modal.state;\n return modal;\n });\n\n case 'maximize':\n return modals.map(modal => {\n modal.state =\n modal.id === payload.modal.id && modal.options.maximizable ? 'maximized' : modal.state;\n return modal;\n });\n\n case 'dock':\n return modals.map(modal => {\n modal.state =\n modal.id === payload.modal.id && modal.options.dockable ? 'docked' : 'minimized';\n return modal;\n });\n\n default:\n return modals;\n }\n};\n\nconst WrappedModal = memo(\n ({\n Component,\n id,\n options: { alert, dismissible, dockable, minimizable, maximizable },\n state,\n methods,\n props,\n top\n }: ModalObject & { top: boolean }) => (\n <ModalContext.Provider\n // eslint-disable-next-line react/jsx-no-constructed-context-values\n value={{\n id,\n alert,\n dismissible,\n minimizable,\n maximizable,\n dockable,\n state,\n top,\n initialized: true,\n ...methods\n }}\n >\n <Component {...props} />\n </ModalContext.Provider>\n )\n);\n\nconst RenderModals = ({ modals }: { modals: ModalObject[] }) => {\n const { open, minimized, alerts } = modals.reduce<{\n open: ModalObject[];\n minimized: ModalObject[];\n alerts: ModalObject[];\n }>(\n (obj, modal) => {\n if (modal.options.alert) obj.alerts.push(modal);\n else if (modal.state === 'minimized' || modal.state === 'docked') {\n obj.minimized.push(modal);\n } else obj.open.push(modal);\n\n return obj;\n },\n { open: [], minimized: [], alerts: [] }\n );\n\n return (\n <>\n {open.map((modal, i) => (\n <WrappedModal\n {...modal}\n top={alerts.length === 0 && i === open.length - 1}\n key={modal.id}\n />\n ))}\n {minimized.length > 0 && (\n <DockedModals>\n {minimized.map(modal => (\n <WrappedModal {...modal} top={false} key={modal.id} />\n ))}\n </DockedModals>\n )}\n {alerts.map((modal, i) => (\n <WrappedModal {...modal} top={i === open.length - 1} key={modal.id} />\n ))}\n </>\n );\n};\n\nconst ModalManager: FunctionComponent<ModalManagerProps> = ({ children }) => {\n const [modals, dispatch] = useReducer(reducer, []);\n const { disableScroll, enableScroll } = useScrollToggle();\n\n const providerValue = useMemo(\n () => ({\n create: <P extends object>(\n Component: ComponentType<P>,\n props?: P,\n options?: ModalOptions\n ) => {\n const id = options?.id || createUID();\n const activeElement = getActiveElement();\n const initiatorRef = activeElement ? new WeakRef(activeElement) : null;\n\n const methods: ModalMethods<P> = {\n dismiss: () => {\n dispatch({ action: 'dismiss', modal: { id } });\n options?.onDismiss?.(id);\n const initiator = initiatorRef?.deref();\n const currentActiveElement = getActiveElement();\n if (\n initiator?.isConnected &&\n (initiator instanceof HTMLElement || initiator instanceof SVGElement) &&\n currentActiveElement !== null &&\n (currentActiveElement.closest('[aria-modal=\"true\"]') !== null ||\n currentActiveElement === document.body)\n ) {\n initiator.focus();\n }\n },\n update: updateProps => {\n (dispatch as Dispatch<ModalReducerPayload<P>>)({\n action: 'update',\n modal: { id, props: updateProps }\n });\n },\n minimize: () => {\n dispatch({ action: 'minimize', modal: { id } });\n options?.onMinimize?.(id);\n },\n maximize: () => {\n dispatch({ action: 'maximize', modal: { id } });\n options?.onMaximize?.(id);\n },\n dock: () => {\n dispatch({ action: 'dock', modal: { id } });\n options?.onDock?.(id);\n },\n activate: () => {\n dispatch({ action: 'activate', modal: { id } });\n options?.onActivate?.(id);\n },\n unmount: () => {\n dispatch({ action: 'unmount', modal: { id } });\n }\n };\n\n let defaultState: ModalState;\n if (options?.defaultMinimized) {\n defaultState = 'minimized';\n } else if (options?.dockable) {\n defaultState = 'docked';\n } else {\n defaultState = 'open';\n }\n\n (dispatch as Dispatch<ModalReducerPayload<P>>)({\n action: 'create',\n modal: {\n id,\n methods,\n Component,\n props,\n state: defaultState,\n options: {\n alert: false,\n minimizable: false,\n maximizable: false,\n dockable: false,\n defaultMinimized: false,\n unmountWhenMinimized: true,\n ...options,\n dismissible: !!(options?.alert ? false : options?.dismissible ?? true)\n }\n }\n });\n\n return methods;\n },\n ModalContext,\n initialized: true\n }),\n []\n );\n\n useEffect(() => {\n if (modals.some(modal => modal.state === 'open' && !modal.options.dockable)) {\n disableScroll();\n } else {\n enableScroll();\n }\n }, [modals]);\n\n const { portalTarget } = useConfiguration();\n\n const context = windowIsAvailable\n ? window.cosmos.modalManagerContext ?? ModalManagerContext\n : ModalManagerContext;\n const priorCtx = useContext(context);\n\n // Don't create additional Modal portals.\n if (priorCtx.initialized) return <context.Provider value={priorCtx}>{children}</context.Provider>;\n\n return (\n <context.Provider value={providerValue}>\n {children}\n {modals.length > 0 &&\n portalTarget &&\n createPortal(<RenderModals modals={modals} />, portalTarget)}\n </context.Provider>\n );\n};\n\nexport default ModalManager;\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pega/cosmos-react-core",
3
- "version": "7.0.0-build.22.6",
3
+ "version": "7.0.0-build.22.7",
4
4
  "description": "Cosmos is a visual design system and UI component collection. Its goal is to empower application developers in their pursuit to create engaging and rewarding user experiences.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -25,11 +25,12 @@
25
25
  "build": "tsc -b tsconfig.build.json"
26
26
  },
27
27
  "dependencies": {
28
+ "@googlemaps/js-api-loader": "^1.16.6",
28
29
  "@popperjs/core": "^2.11.6",
29
30
  "@types/dompurify": "^3.0.5",
30
31
  "@types/emoji-mart": "^3.0.4",
31
32
  "@types/emoji-regex": "^8.0.0",
32
- "@types/google.maps": "^3.49.2",
33
+ "@types/google.maps": "^3.55.8",
33
34
  "@types/qrcode": "^1.5.0",
34
35
  "@types/react": "^17.0.62",
35
36
  "@types/react-dom": "^17.0.20",