text
stringlengths
9
39.2M
dir
stringlengths
25
226
lang
stringclasses
163 values
created_date
timestamp[s]
updated_date
timestamp[s]
repo_name
stringclasses
751 values
repo_full_name
stringclasses
752 values
star
int64
1.01k
183k
len_tokens
int64
1
18.5M
```unknown /* @flow * @generated by TsFlower */ import type { TypedNavigator as $tsflower_import_type$_$_40_react_2d_navigation_2f_native$TypedNavigator } from '@react-navigation/native'; import type { JSX$Element as $tsflower_subst$React$JSX$Element } from 'tsflower/subst/react'; import { type DefaultNavigatorOptions, type TabRouterOptions, type TabNavigationState, } from '@react-navigation/native'; import { type MaterialTopTabNavigationConfig, type MaterialTopTabNavigationOptions, type MaterialTopTabNavigationEventMap, } from '../types'; type Props = TabRouterOptions & MaterialTopTabNavigationConfig; declare function MaterialTopTabNavigator(Props): $tsflower_subst$React$JSX$Element; declare var _default: < ParamList: { +[key: string]: { ... } | void }, >() => $tsflower_import_type$_$_40_react_2d_navigation_2f_native$TypedNavigator< ParamList, TabNavigationState<ParamList>, MaterialTopTabNavigationOptions, MaterialTopTabNavigationEventMap, typeof MaterialTopTabNavigator, >; export default _default; ```
/content/code_sandbox/types/@react-navigation/material-top-tabs/lib/typescript/src/navigators/createMaterialTopTabNavigator.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
257
```unknown /* @flow * @generated by TsFlower */ import type { JSX$Element as $tsflower_subst$React$JSX$Element } from 'tsflower/subst/react'; import { type TabNavigationState, type ParamListBase } from '@react-navigation/native'; import { type MaterialTopTabDescriptorMap, type MaterialTopTabNavigationConfig, type MaterialTopTabNavigationHelpers, } from '../types'; type Props = MaterialTopTabNavigationConfig & { state: TabNavigationState<ParamListBase>, navigation: MaterialTopTabNavigationHelpers, descriptors: MaterialTopTabDescriptorMap, tabBarPosition?: 'top' | 'bottom', ... }; declare export default function MaterialTopTabView(Props): $tsflower_subst$React$JSX$Element; export {}; ```
/content/code_sandbox/types/@react-navigation/material-top-tabs/lib/typescript/src/views/MaterialTopTabView.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
170
```unknown /* @flow * @generated by TsFlower */ import type { JSX$Element as $tsflower_subst$React$JSX$Element } from 'tsflower/subst/react'; import { type MaterialTopTabBarProps } from '../types'; declare export default function TabBarTop( props: MaterialTopTabBarProps, ): $tsflower_subst$React$JSX$Element; ```
/content/code_sandbox/types/@react-navigation/material-top-tabs/lib/typescript/src/views/MaterialTopTabBar.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
86
```unknown /* @flow * @generated */ export * from './lib/typescript/src/index.js.flow'; ```
/content/code_sandbox/types/@react-navigation/native/index.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
22
```unknown /* @flow * @generated by TsFlower */ declare export default function useLinkTo(): (path: string) => void; ```
/content/code_sandbox/types/@react-navigation/native/lib/typescript/src/useLinkTo.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
30
```unknown /* @flow * @generated by TsFlower */ import type { Partial } from 'tsflower/subst/lib'; import type { ReactNode, ComponentProps } from 'tsflower/subst/react'; import type { StyleProp as $tsflower_subst$RN$StyleProp, ViewStyle as $tsflower_subst$RN$ViewStyle, TextStyle as $tsflower_subst$RN$TextStyle, } from 'tsflower/subst/react-native'; import 'react-native'; import { TabBar, type SceneRendererProps, TabView } from 'react-native-tab-view'; import { type ParamListBase, type Descriptor, type NavigationHelpers, type Route, type NavigationProp, type TabNavigationState, type TabActionHelpers, type RouteProp, } from '@react-navigation/native'; export type MaterialTopTabNavigationEventMap = {| tabPress: {| data: void, canPreventDefault: true, |}, tabLongPress: {| data: void |}, swipeStart: {| data: void |}, swipeEnd: {| data: void |}, |}; export type MaterialTopTabNavigationHelpers = NavigationHelpers< ParamListBase, MaterialTopTabNavigationEventMap, > & TabActionHelpers<ParamListBase>; export type MaterialTopTabNavigationProp< ParamList: ParamListBase, +RouteName: $Keys<ParamList> = string, > = NavigationProp< ParamList, RouteName, TabNavigationState<ParamList>, MaterialTopTabNavigationOptions, MaterialTopTabNavigationEventMap, > & TabActionHelpers<ParamList>; export type MaterialTopTabScreenProps< ParamList: ParamListBase, RouteName: $Keys<ParamList> = string, > = { navigation: MaterialTopTabNavigationProp<ParamList, RouteName>, route: RouteProp<ParamList, RouteName>, ... }; export type MaterialTopTabNavigationOptions = { title?: string, tabBarLabel?: | string | ((props: { focused: boolean, color: string, ... }) => ReactNode), tabBarIcon?: (props: { focused: boolean, color: string, ... }) => ReactNode, tabBarAccessibilityLabel?: string, tabBarTestID?: string, ... }; export type MaterialTopTabDescriptor = Descriptor< ParamListBase, string, TabNavigationState<ParamListBase>, MaterialTopTabNavigationOptions, >; export type MaterialTopTabDescriptorMap = { [key: string]: MaterialTopTabDescriptor, ... }; export type MaterialTopTabNavigationConfig = Partial< $Diff< ComponentProps<typeof TabView>, {| navigationState: mixed, onIndexChange: mixed, onSwipeStart: mixed, onSwipeEnd: mixed, renderScene: mixed, renderTabBar: mixed, renderPager: mixed, renderLazyPlaceholder: mixed, |}, >, > & { pager?: $ElementType<ComponentProps<typeof TabView>, 'renderPager'>, lazyPlaceholder?: (props: { route: Route<string>, ... }) => ReactNode, tabBar?: (props: MaterialTopTabBarProps) => ReactNode, tabBarOptions?: MaterialTopTabBarOptions, tabBarPosition?: 'top' | 'bottom', ... }; export type MaterialTopTabBarOptions = Partial< $Diff< ComponentProps<typeof TabBar>, {| [key: | 'navigationState' | 'activeColor' | 'inactiveColor' | 'renderLabel' | 'renderIcon' | 'getLabelText' | 'getAccessibilityLabel' | 'getTestID' | 'onTabPress' | 'onTabLongPress' | $Keys<SceneRendererProps>]: mixed, |}, >, > & { activeTintColor?: string, inactiveTintColor?: string, iconStyle?: $tsflower_subst$RN$StyleProp<$tsflower_subst$RN$ViewStyle>, labelStyle?: $tsflower_subst$RN$StyleProp<$tsflower_subst$RN$TextStyle>, showLabel?: boolean, showIcon?: boolean, allowFontScaling?: boolean, ... }; export type MaterialTopTabBarProps = MaterialTopTabBarOptions & SceneRendererProps & { state: TabNavigationState<ParamListBase>, navigation: NavigationHelpers<ParamListBase, MaterialTopTabNavigationEventMap>, descriptors: MaterialTopTabDescriptorMap, ... }; ```
/content/code_sandbox/types/@react-navigation/material-top-tabs/lib/typescript/src/types.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
978
```unknown /* @flow * @generated by TsFlower */ import type { ReactNode as $tsflower_subst$React$ReactNode, RefAttributes as $tsflower_subst$React$RefAttributes, } from 'tsflower/subst/react'; import * as TsReact from 'tsflower/subst/react'; import * as React from 'react'; import { type NavigationContainerProps, type NavigationContainerRef } from '@react-navigation/core'; import { type Theme, type LinkingOptions, type DocumentTitleOptions } from './types'; type ForwardRefExoticComponent<P> = React.AbstractComponent< $Rest<P, {| ref: mixed |}>, $Call<<T>(?TsReact.Ref<T>) => T, $ElementType<P, 'ref'>>, >; declare var NavigationContainer: ForwardRefExoticComponent< NavigationContainerProps & { theme?: Theme | void, linking?: LinkingOptions | void, fallback?: $tsflower_subst$React$ReactNode, documentTitle?: DocumentTitleOptions | void, onReady?: () => void | void, ... } & $tsflower_subst$React$RefAttributes<NavigationContainerRef>, >; export default NavigationContainer; ```
/content/code_sandbox/types/@react-navigation/native/lib/typescript/src/NavigationContainer.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
256
```unknown /* @flow * @generated by TsFlower */ import type { Context as $tsflower_subst$React$Context } from 'tsflower/subst/react'; import * as React from 'react'; import { type LinkingOptions } from './types'; declare var LinkingContext: $tsflower_subst$React$Context<{ options: LinkingOptions | void, ... }>; export default LinkingContext; ```
/content/code_sandbox/types/@react-navigation/native/lib/typescript/src/LinkingContext.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
89
```unknown /* @flow * @generated by TsFlower */ import type { RefObject as $tsflower_subst$React$RefObject } from 'tsflower/subst/react'; import * as React from 'react'; import { type NavigationContainerRef } from '@react-navigation/core'; declare export default function useBackButton( ref: $tsflower_subst$React$RefObject<NavigationContainerRef>, ): void; ```
/content/code_sandbox/types/@react-navigation/native/lib/typescript/src/useBackButton.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
89
```unknown /* @flow * @generated by TsFlower */ import type { Context as $tsflower_subst$React$Context } from 'tsflower/subst/react'; import * as React from 'react'; export type ServerContextType = { location?: { pathname: string, search: string, ... }, ... }; declare var ServerContext: $tsflower_subst$React$Context<ServerContextType | void>; export default ServerContext; ```
/content/code_sandbox/types/@react-navigation/native/lib/typescript/src/ServerContext.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
99
```unknown /* @flow * @generated by TsFlower */ import type { MouseEvent as $tsflower_subst$React$MouseEvent } from 'tsflower/subst/react'; import type { GestureResponderEvent as $tsflower_subst$RN$GestureResponderEvent } from 'tsflower/subst/react-native'; import * as React from 'react'; import 'react-native'; import { type NavigationAction } from '@react-navigation/core'; type Props = { to: string, action?: NavigationAction, ... }; declare export default function useLinkProps(Props): { href: string, accessibilityRole: 'link', onPress: ( e?: | $tsflower_subst$React$MouseEvent<HTMLAnchorElement, MouseEvent> | $tsflower_subst$RN$GestureResponderEvent | void, ) => void, ... }; export {}; ```
/content/code_sandbox/types/@react-navigation/native/lib/typescript/src/useLinkProps.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
184
```unknown /* @flow * @generated by TsFlower */ declare export default function useLinkBuilder(): ( name: string, params?: { ... } | void, ) => string | void; ```
/content/code_sandbox/types/@react-navigation/native/lib/typescript/src/useLinkBuilder.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
43
```unknown /* @flow * @generated by TsFlower */ export * from '@react-navigation/core'; export { default as NavigationContainer } from './NavigationContainer'; export { default as useBackButton } from './useBackButton'; export { default as useScrollToTop } from './useScrollToTop'; export { default as DefaultTheme } from './theming/DefaultTheme'; export { default as DarkTheme } from './theming/DarkTheme'; export { default as ThemeProvider } from './theming/ThemeProvider'; export { default as useTheme } from './theming/useTheme'; export { default as Link } from './Link'; export { default as useLinking } from './useLinking'; export { default as useLinkTo } from './useLinkTo'; export { default as useLinkProps } from './useLinkProps'; export { default as useLinkBuilder } from './useLinkBuilder'; export { default as ServerContainer } from './ServerContainer'; export * from './types'; ```
/content/code_sandbox/types/@react-navigation/native/lib/typescript/src/index.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
206
```unknown /* @flow * @generated by TsFlower */ import type { PromiseLike } from 'tsflower/subst/lib'; declare export default function useThenable<T>(create: () => PromiseLike<T>): [boolean, T | void]; ```
/content/code_sandbox/types/@react-navigation/native/lib/typescript/src/useThenable.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
52
```unknown /* @flow * @generated by TsFlower */ import type { RefObject as $tsflower_subst$React$RefObject } from 'tsflower/subst/react'; import * as React from 'react'; import { type NavigationContainerRef } from '@react-navigation/core'; import { type DocumentTitleOptions } from './types'; declare export default function useDocumentTitle( ref: $tsflower_subst$React$RefObject<NavigationContainerRef>, ?DocumentTitleOptions, ): void; ```
/content/code_sandbox/types/@react-navigation/native/lib/typescript/src/useDocumentTitle.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
106
```unknown /* @flow * @generated by TsFlower */ import type { PartialState as $tsflower_import_type$_$_40_react_2d_navigation_2f_core$PartialState } from '@react-navigation/core'; import type { PartialRoute as $tsflower_import_type$_$_40_react_2d_navigation_2f_core$PartialRoute } from '@react-navigation/core'; import type { Route as $tsflower_import_type$_$_40_react_2d_navigation_2f_core$Route } from '@react-navigation/core'; import type { RefObject as $tsflower_subst$React$RefObject } from 'tsflower/subst/react'; import type { PromiseLike, Partial, Readonly } from 'tsflower/subst/lib'; import * as React from 'react'; import { type NavigationContainerRef } from '@react-navigation/core'; import { type LinkingOptions } from './types'; declare export default function useLinking( ref: $tsflower_subst$React$RefObject<NavigationContainerRef>, LinkingOptions, ): { getInitialState: () => PromiseLike< | (Partial< Readonly<{ key: string, index: number, routeNames: string[], history?: mixed[] | void, type: string, ... }>, > & Readonly<{ stale?: true | void, routes: $tsflower_import_type$_$_40_react_2d_navigation_2f_core$PartialRoute< $tsflower_import_type$_$_40_react_2d_navigation_2f_core$Route<string, { ... } | void>, >[], ... }> & { state?: | (Partial< Readonly<{ key: string, index: number, routeNames: string[], history?: mixed[] | void, type: string, ... }>, > & Readonly<{ stale?: true | void, routes: $tsflower_import_type$_$_40_react_2d_navigation_2f_core$PartialRoute< $tsflower_import_type$_$_40_react_2d_navigation_2f_core$Route< string, { ... } | void, >, >[], ... }> & any) | void, ... }) | void, >, ... }; ```
/content/code_sandbox/types/@react-navigation/native/lib/typescript/src/useLinking.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
497
```unknown /* @flow * @generated by TsFlower */ import type { ForwardRefExoticComponent as $tsflower_subst$React$ForwardRefExoticComponent, ReactNode as $tsflower_subst$React$ReactNode, RefAttributes as $tsflower_subst$React$RefAttributes, } from 'tsflower/subst/react'; import * as React from 'react'; import { type ServerContextType } from './ServerContext'; import { type ServerContainerRef } from './types'; declare var _default: $tsflower_subst$React$ForwardRefExoticComponent< ServerContextType & { children: $tsflower_subst$React$ReactNode, ... } & $tsflower_subst$React$RefAttributes<ServerContainerRef>, >; export default _default; ```
/content/code_sandbox/types/@react-navigation/native/lib/typescript/src/ServerContainer.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
173
```unknown /* @flow * @generated by TsFlower */ import type { ReactNode as $tsflower_subst$React$ReactNode, RefObject as $tsflower_subst$React$RefObject, } from 'tsflower/subst/react'; import * as React from 'react'; type ScrollOptions = { y?: number, animated?: boolean, ... }; type ScrollableView = | { scrollToTop(): void, ... } | { scrollTo(options: ScrollOptions): void, ... } | { scrollToOffset(options: { offset?: number, animated?: boolean, ... }): void, ... } | { scrollResponderScrollTo(options: ScrollOptions): void, ... }; type ScrollableWrapper = | { getScrollResponder(): $tsflower_subst$React$ReactNode, ... } | { getNode(): ScrollableView, ... } | ScrollableView; declare export default function useScrollToTop( ref: $tsflower_subst$React$RefObject<ScrollableWrapper>, ): void; export {}; ```
/content/code_sandbox/types/@react-navigation/native/lib/typescript/src/useScrollToTop.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
226
```unknown /* @flow * @generated by TsFlower */ import type { MouseEvent as $tsflower_subst$React$MouseEvent, ReactNode as $tsflower_subst$React$ReactNode, CElement as $tsflower_subst$React$CElement, } from 'tsflower/subst/react'; import type { GestureResponderEvent as $tsflower_subst$RN$GestureResponderEvent, TextProps as $tsflower_subst$RN$TextProps, Text as $tsflower_subst$RN$Text, } from 'tsflower/subst/react-native'; import * as React from 'react'; import { Text } from 'react-native'; import { type NavigationAction } from '@react-navigation/core'; type Props = { to: string, action?: NavigationAction, target?: string, onPress?: ( e: | $tsflower_subst$React$MouseEvent<HTMLAnchorElement, MouseEvent> | $tsflower_subst$RN$GestureResponderEvent, ) => void, ... } & $tsflower_subst$RN$TextProps & { children: $tsflower_subst$React$ReactNode, ... }; declare export default function Link( Props, ): $tsflower_subst$React$CElement<$tsflower_subst$RN$TextProps, $tsflower_subst$RN$Text>; export {}; ```
/content/code_sandbox/types/@react-navigation/native/lib/typescript/src/Link.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
293
```unknown /* @flow * @generated by TsFlower */ declare export default function extractPathFromURL(prefixes: string[], url: string): string | void; ```
/content/code_sandbox/types/@react-navigation/native/lib/typescript/src/extractPathFromURL.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
35
```unknown /* @flow * @generated by TsFlower */ declare export default function useDocumentTitle(): void; ```
/content/code_sandbox/types/@react-navigation/native/lib/typescript/src/useDocumentTitle.native.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
24
```unknown /* @flow * @generated by TsFlower */ import type { PartialState as $tsflower_import_type$_$_40_react_2d_navigation_2f_core$PartialState } from '@react-navigation/core'; import type { PartialRoute as $tsflower_import_type$_$_40_react_2d_navigation_2f_core$PartialRoute } from '@react-navigation/core'; import type { Route as $tsflower_import_type$_$_40_react_2d_navigation_2f_core$Route } from '@react-navigation/core'; import type { RefObject as $tsflower_subst$React$RefObject } from 'tsflower/subst/react'; import type { PromiseLike, Partial, Readonly } from 'tsflower/subst/lib'; import * as React from 'react'; import { type NavigationContainerRef } from '@react-navigation/core'; import { type LinkingOptions } from './types'; declare export default function useLinking( ref: $tsflower_subst$React$RefObject<NavigationContainerRef>, LinkingOptions, ): { getInitialState: () => PromiseLike< | (Partial< Readonly<{ key: string, index: number, routeNames: string[], history?: mixed[] | void, type: string, ... }>, > & Readonly<{ stale?: true | void, routes: $tsflower_import_type$_$_40_react_2d_navigation_2f_core$PartialRoute< $tsflower_import_type$_$_40_react_2d_navigation_2f_core$Route<string, { ... } | void>, >[], ... }> & { state?: | (Partial< Readonly<{ key: string, index: number, routeNames: string[], history?: mixed[] | void, type: string, ... }>, > & Readonly<{ stale?: true | void, routes: $tsflower_import_type$_$_40_react_2d_navigation_2f_core$PartialRoute< $tsflower_import_type$_$_40_react_2d_navigation_2f_core$Route< string, { ... } | void, >, >[], ... }> & any) | void, ... }) | void, >, ... }; ```
/content/code_sandbox/types/@react-navigation/native/lib/typescript/src/useLinking.native.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
497
```unknown /* @flow * @generated by TsFlower */ import { type Theme } from '../types'; declare var DarkTheme: Theme; export default DarkTheme; ```
/content/code_sandbox/types/@react-navigation/native/lib/typescript/src/theming/DarkTheme.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
35
```unknown /* @flow * @generated by TsFlower */ import { typeof getStateFromPath as getStateFromPathDefault, typeof getPathFromState as getPathFromStateDefault, typeof getActionFromState as getActionFromStateDefault, type PathConfigMap, type Route, } from '@react-navigation/core'; export type Theme = { dark: boolean, colors: { primary: string, background: string, card: string, text: string, border: string, notification: string, ... }, ... }; export type LinkingOptions = { enabled?: boolean, prefixes: string[], config?: { initialRouteName?: string, screens: PathConfigMap, ... }, getInitialURL?: () => string | null | void | Promise<string | null | void>, subscribe?: (listener: (url: string) => void) => void | void | (() => void), getStateFromPath?: getStateFromPathDefault, getActionFromState?: getActionFromStateDefault, getPathFromState?: getPathFromStateDefault, ... }; export type DocumentTitleOptions = { enabled?: boolean, formatter?: (options: { [key: string]: any } | void, route: Route<string> | void) => string, ... }; export type ServerContainerRef = { getCurrentOptions(): { [key: string]: any } | void, ... }; ```
/content/code_sandbox/types/@react-navigation/native/lib/typescript/src/types.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
302
```unknown /* @flow * @generated by TsFlower */ import { type Theme } from '../types'; declare var DefaultTheme: Theme; export default DefaultTheme; ```
/content/code_sandbox/types/@react-navigation/native/lib/typescript/src/theming/DefaultTheme.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
35
```unknown /* @flow * @generated by TsFlower */ import type { ReactNode as $tsflower_subst$React$ReactNode, JSX$Element as $tsflower_subst$React$JSX$Element, } from 'tsflower/subst/react'; import * as React from 'react'; import { type Theme } from '../types'; type Props = { value: Theme, children: $tsflower_subst$React$ReactNode, ... }; declare export default function ThemeProvider(Props): $tsflower_subst$React$JSX$Element; export {}; ```
/content/code_sandbox/types/@react-navigation/native/lib/typescript/src/theming/ThemeProvider.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
126
```unknown /* @flow * @generated by TsFlower */ import type { Context as $tsflower_subst$React$Context } from 'tsflower/subst/react'; import * as React from 'react'; import { type Theme } from '../types'; declare var ThemeContext: $tsflower_subst$React$Context<Theme>; export default ThemeContext; ```
/content/code_sandbox/types/@react-navigation/native/lib/typescript/src/theming/ThemeContext.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
76
```unknown /* @flow * @generated by TsFlower */ import type { Theme as $tsflower_import_type$_$_2e__2e_$Theme } from '..'; declare export default function useTheme(): $tsflower_import_type$_$_2e__2e_$Theme; ```
/content/code_sandbox/types/@react-navigation/native/lib/typescript/src/theming/useTheme.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
59
```unknown /* @flow * @generated */ export * from './build/WebBrowser.js.flow'; ```
/content/code_sandbox/types/expo-web-browser/index.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
20
```unknown /* @flow * @generated by TsFlower */ declare var _default: { document: { title: string, ... }, location: URL, history: { +state: any, pushState(state: any, _: string, path: string): void, replaceState(state: any, _: string, path: string): void, go(n: number): void, back(): void, forward(): void, ... }, addEventListener: (type: 'popstate', listener: () => void) => void, removeEventListener: (type: 'popstate', listener: () => void) => void, ... }; export default _default; ```
/content/code_sandbox/types/@react-navigation/native/lib/typescript/src/__mocks__/window.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
147
```unknown /* @flow * @generated by TsFlower */ export type RedirectEvent = { url: string, ... }; export type WebBrowserWindowFeatures = { [key: string]: number | boolean | string }; export type WebBrowserOpenOptions = { toolbarColor?: string, browserPackage?: string, enableBarCollapsing?: boolean, secondaryToolbarColor?: string, showTitle?: boolean, enableDefaultShareMenuItem?: boolean, showInRecents?: boolean, createTask?: boolean, controlsColor?: string, dismissButtonStyle?: "done" | "close" | "cancel", readerMode?: boolean, presentationStyle?: WebBrowserPresentationStyleT, windowName?: string, windowFeatures?: string | WebBrowserWindowFeatures, ... }; export type AuthSessionOpenOptions = WebBrowserOpenOptions & { preferEphemeralSession?: boolean, ... }; export type WebBrowserAuthSessionResult = WebBrowserRedirectResult | WebBrowserResult; export type WebBrowserCustomTabsResults = { defaultBrowserPackage?: string, preferredBrowserPackage?: string, browserPackages: string[], servicePackages: string[], ... }; declare export var WebBrowserResultType: {| /** * @platform ios */ +CANCEL: 'cancel', /** * @platform ios */ +DISMISS: 'dismiss', /** * @platform android */ +OPENED: 'opened', +LOCKED: 'locked', |} export type WebBrowserResultTypeT = $Values<typeof WebBrowserResultType>; /** * A browser presentation style. Its values are directly mapped to the [`UIModalPresentationStyle`](path_to_url * * @platform ios */ declare export var WebBrowserPresentationStyle: {| /** * A presentation style in which the presented browser covers the screen. */ +FULL_SCREEN: "fullScreen", /** * A presentation style that partially covers the underlying content. */ +PAGE_SHEET: "pageSheet", /** * A presentation style that displays the browser centered in the screen. */ +FORM_SHEET: "formSheet", /** * A presentation style where the browser is displayed over the app's content. */ +CURRENT_CONTEXT: "currentContext", /** * A presentation style in which the browser view covers the screen. */ +OVER_FULL_SCREEN: "overFullScreen", /** * A presentation style where the browser is displayed over the app's content. */ +OVER_CURRENT_CONTEXT: "overCurrentContext", /** * A presentation style where the browser is displayed in a popover view. */ +POPOVER: "popover", /** * The default presentation style chosen by the system. * On older iOS versions, falls back to `WebBrowserPresentationStyle.FullScreen`. * * @platform ios 13+ */ +AUTOMATIC: "automatic" |} export type WebBrowserPresentationStyleT = $Values<typeof WebBrowserPresentationStyle>; export type WebBrowserResult = { type: WebBrowserResultTypeT, ... }; export type WebBrowserRedirectResult = { type: "success", url: string, ... }; export type ServiceActionResult = { servicePackage?: string, ... }; export type WebBrowserMayInitWithUrlResult = ServiceActionResult; export type WebBrowserWarmUpResult = ServiceActionResult; export type WebBrowserCoolDownResult = ServiceActionResult; export type WebBrowserCompleteAuthSessionOptions = { skipRedirectCheck?: boolean, ... }; export type WebBrowserCompleteAuthSessionResult = { type: "success" | "failed", message: string, ... }; ```
/content/code_sandbox/types/expo-web-browser/build/WebBrowser.types.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
773
```unknown /* @flow * @generated by TsFlower */ import { type WebBrowserAuthSessionResult as WebBrowserAuthSessionResult_, type WebBrowserCompleteAuthSessionOptions as WebBrowserCompleteAuthSessionOptions_, type WebBrowserCompleteAuthSessionResult as WebBrowserCompleteAuthSessionResult_, type WebBrowserCoolDownResult as WebBrowserCoolDownResult_, type WebBrowserCustomTabsResults as WebBrowserCustomTabsResults_, type WebBrowserMayInitWithUrlResult as WebBrowserMayInitWithUrlResult_, type WebBrowserOpenOptions as WebBrowserOpenOptions_, type WebBrowserRedirectResult as WebBrowserRedirectResult_, type WebBrowserResult as WebBrowserResult_, WebBrowserResultType, type WebBrowserResultTypeT as WebBrowserResultTypeT_, type WebBrowserWarmUpResult as WebBrowserWarmUpResult_, type WebBrowserWindowFeatures as WebBrowserWindowFeatures_, WebBrowserPresentationStyle, type WebBrowserPresentationStyleT as WebBrowserPresentationStyleT_, type AuthSessionOpenOptions as AuthSessionOpenOptions_, } from "./WebBrowser.types"; export { WebBrowserResultType, WebBrowserPresentationStyle }; export type WebBrowserAuthSessionResult = WebBrowserAuthSessionResult_; export type WebBrowserCompleteAuthSessionOptions = WebBrowserCompleteAuthSessionOptions_; export type WebBrowserCompleteAuthSessionResult = WebBrowserCompleteAuthSessionResult_; export type WebBrowserCoolDownResult = WebBrowserCoolDownResult_; export type WebBrowserCustomTabsResults = WebBrowserCustomTabsResults_; export type WebBrowserMayInitWithUrlResult = WebBrowserMayInitWithUrlResult_; export type WebBrowserOpenOptions = WebBrowserOpenOptions_; export type WebBrowserRedirectResult = WebBrowserRedirectResult_; export type WebBrowserResult = WebBrowserResult_; export type WebBrowserResultTypeT = WebBrowserResultTypeT_; export type WebBrowserWarmUpResult = WebBrowserWarmUpResult_; export type WebBrowserWindowFeatures = WebBrowserWindowFeatures_; export type WebBrowserPresentationStyleT = WebBrowserPresentationStyleT_; export type AuthSessionOpenOptions = AuthSessionOpenOptions_; declare export function getCustomTabsSupportingBrowsersAsync(): Promise<WebBrowserCustomTabsResults>; declare export function warmUpAsync(browserPackage?: string): Promise<WebBrowserWarmUpResult>; declare export function mayInitWithUrlAsync(url: string, browserPackage?: string): Promise<WebBrowserMayInitWithUrlResult>; declare export function coolDownAsync(browserPackage?: string): Promise<WebBrowserCoolDownResult>; declare export function openBrowserAsync(url: string, browserParams?: WebBrowserOpenOptions): Promise<WebBrowserResult>; declare export function dismissBrowser(): void; declare export function openAuthSessionAsync(url: string, redirectUrl: string, options?: AuthSessionOpenOptions): Promise<WebBrowserAuthSessionResult>; declare export function dismissAuthSession(): void; declare export function maybeCompleteAuthSession(options?: WebBrowserCompleteAuthSessionOptions): WebBrowserCompleteAuthSessionResult; ```
/content/code_sandbox/types/expo-web-browser/build/WebBrowser.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
611
```unknown /* @flow * @generated by TsFlower */ import type { ProxyNativeModule as $tsflower_import_type$_$expo_2d_modules_2d_core$ProxyNativeModule, } from "expo-modules-core"; declare var _default: $tsflower_import_type$_$expo_2d_modules_2d_core$ProxyNativeModule; export default _default; ```
/content/code_sandbox/types/expo-web-browser/build/ExpoWebBrowser.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
81
```unknown /* @flow * @generated */ export * from './lib/typescript/index.js.flow'; ```
/content/code_sandbox/types/react-native-image-picker/index.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
21
```unknown /* @flow * @generated by TsFlower */ import type { ImagePickerResponse as $tsflower_import_type$_$_2e__2f_types$ImagePickerResponse } from './types'; import { type CameraOptions, type ImageLibraryOptions, type Callback } from './types'; export * from './types'; declare export function launchCamera( options: CameraOptions, callback?: Callback, ): Promise<$tsflower_import_type$_$_2e__2f_types$ImagePickerResponse>; declare export function launchImageLibrary( options: ImageLibraryOptions, callback?: Callback, ): Promise<$tsflower_import_type$_$_2e__2f_types$ImagePickerResponse>; ```
/content/code_sandbox/types/react-native-image-picker/lib/typescript/index.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
143
```unknown /* @flow * @generated by TsFlower */ import { type TurboModule } from 'react-native/Libraries/TurboModule/RCTExport'; export interface Spec extends TurboModule { launchCamera(options: Object, callback: () => void): void; launchImageLibrary(options: Object, callback: () => void): void; } declare var _default: Spec | null; export default _default; ```
/content/code_sandbox/types/react-native-image-picker/lib/typescript/platforms/NativeImagePicker.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
87
```unknown /* @flow * @generated by TsFlower */ import { type CameraOptions, type ImageLibraryOptions, type Callback, type ImagePickerResponse, } from '../types'; declare export function camera( options: CameraOptions, callback?: Callback, ): Promise<ImagePickerResponse>; declare export function imageLibrary( options: ImageLibraryOptions, callback?: Callback, ): Promise<ImagePickerResponse>; ```
/content/code_sandbox/types/react-native-image-picker/lib/typescript/platforms/native.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
88
```unknown /* @flow * @generated by TsFlower */ export type Callback = (response: ImagePickerResponse) => any; export interface OptionsCommon { mediaType: MediaType; maxWidth?: number; maxHeight?: number; quality?: PhotoQuality; videoQuality?: AndroidVideoOptions | iOSVideoOptions; includeBase64?: boolean; includeExtra?: boolean; formatAsMp4?: boolean; presentationStyle?: | 'currentContext' | 'fullScreen' | 'pageSheet' | 'formSheet' | 'popover' | 'overFullScreen' | 'overCurrentContext'; assetRepresentationMode?: 'auto' | 'current' | 'compatible'; } export interface ImageLibraryOptions extends OptionsCommon { selectionLimit?: number; } export interface CameraOptions extends OptionsCommon { durationLimit?: number; saveToPhotos?: boolean; cameraType?: CameraType; } export interface Asset { base64?: string; uri?: string; width?: number; height?: number; fileSize?: number; type?: string; fileName?: string; duration?: number; bitrate?: number; timestamp?: string; id?: string; } export interface ImagePickerResponse { didCancel?: boolean; errorCode?: ErrorCode; errorMessage?: string; assets?: Asset[]; } export type PhotoQuality = 0 | 0.1 | 0.2 | 0.3 | 0.4 | 0.5 | 0.6 | 0.7 | 0.8 | 0.9 | 1; export type CameraType = 'back' | 'front'; export type MediaType = 'photo' | 'video' | 'mixed'; export type AndroidVideoOptions = 'low' | 'high'; export type iOSVideoOptions = 'low' | 'medium' | 'high'; export type ErrorCode = 'camera_unavailable' | 'permission' | 'others'; ```
/content/code_sandbox/types/react-native-image-picker/lib/typescript/types.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
416
```unknown /* @flow * @generated by TsFlower */ import { type ImageLibraryOptions, type Callback, type ImagePickerResponse } from '../types'; declare export function camera( options?: ImageLibraryOptions, callback?: Callback, ): Promise<ImagePickerResponse>; declare export function imageLibrary( options?: ImageLibraryOptions, callback?: Callback, ): Promise<ImagePickerResponse>; ```
/content/code_sandbox/types/react-native-image-picker/lib/typescript/platforms/web.js.flow
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
80
```batchfile @rem @rem @rem @rem path_to_url @rem @rem Unless required by applicable law or agreed to in writing, software @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Resolve any "." and ".." in APP_HOME to make it shorter. for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ```
/content/code_sandbox/android/gradlew.bat
batchfile
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
590
```ini # Project-wide Gradle settings. # IDE (e.g. Android Studio) users: # Gradle settings configured through the IDE *will override* # any settings specified in this file. # For more details on how to configure your build environment visit # path_to_url # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. # Default value (empirically, with Gradle 6.0.1): # -XX:MaxMetaspaceSize=256m -XX:+HeapDumpOnOutOfMemoryError -Xms256m -Xmx512m # We allow more space (no MaxMetaspaceSize; bigger -Xmx), # and don't litter heap dumps if that still proves insufficient. org.gradle.jvmargs=-Xms256m -Xmx1280m # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # path_to_url#sec:decoupled_projects # org.gradle.parallel=true # AndroidX package structure to make it clearer which packages are bundled with the # Android operating system, and which are packaged with your app's APK # path_to_url android.useAndroidX=true # Automatically convert third-party libraries to use AndroidX android.enableJetifier=true # Version of flipper SDK to use with React Native FLIPPER_VERSION=0.125.0 # Use this property to specify which architecture you want to build. # You can also override it from the CLI using # tools/gradle <task> -PreactNativeArchitectures=x86_64 reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64 ```
/content/code_sandbox/android/gradle.properties
ini
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
378
```ini # How to upgrade Gradle: # $ tools/gradle wrapper --distribution-type=all --gradle-version=NEW_VERSION # $ tools/gradle wrapper --distribution-type=all --gradle-version=NEW_VERSION # (Yep, run the same command twice. The first updates this file so we use # the new Gradle; the second updates the wrapper's jar and scripts, so that # the wrapper is the one from the new Gradle too.) distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-all.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists ```
/content/code_sandbox/android/gradle/wrapper/gradle-wrapper.properties
ini
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
158
```qmake # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # path_to_url # Add any project specific keep options here: # Disabling obfuscation is useful if you collect stack traces from production crashes # (unless you are using a system that supports de-obfuscate the stack traces). -dontobfuscate # React Native # Keep our interfaces so they can be used by other ProGuard rules. # See path_to_url -keep,allowobfuscation @interface com.facebook.proguard.annotations.DoNotStrip -keep,allowobfuscation @interface com.facebook.proguard.annotations.KeepGettersAndSetters -keep,allowobfuscation @interface com.facebook.common.internal.DoNotStrip # Do not strip any method/class that is annotated with @DoNotStrip -keep @com.facebook.proguard.annotations.DoNotStrip class * -keep @com.facebook.common.internal.DoNotStrip class * -keepclassmembers class * { @com.facebook.proguard.annotations.DoNotStrip *; @com.facebook.common.internal.DoNotStrip *; } -keepclassmembers @com.facebook.proguard.annotations.KeepGettersAndSetters class * { void set*(***); *** get*(); } -keep class * extends com.facebook.react.bridge.JavaScriptModule { *; } -keep class * extends com.facebook.react.bridge.NativeModule { *; } -keepclassmembers,includedescriptorclasses class * { native <methods>; } -keepclassmembers class * { @com.facebook.react.uimanager.UIProp <fields>; } -keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactProp <methods>; } -keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactPropGroup <methods>; } -dontwarn com.facebook.react.** # TextLayoutBuilder uses a non-public Android constructor within StaticLayout. # See libs/proxy/src/main/java/com/facebook/fbui/textlayoutbuilder/proxy for details. -dontwarn android.text.StaticLayout # okhttp -keepattributes Signature -keepattributes *Annotation* -keep class okhttp3.** { *; } -keep interface okhttp3.** { *; } -dontwarn okhttp3.** # okio -keep class sun.misc.Unsafe { *; } -dontwarn java.nio.file.* -dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement -dontwarn okio.** ```
/content/code_sandbox/android/app/proguard-rules.pro
qmake
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
576
```unknown #!/bin/sh # # # # path_to_url # # Unless required by applicable law or agreed to in writing, software # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # ############################################################################## # # Gradle start up script for POSIX generated by Gradle. # # Important for running: # # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is # noncompliant, but you have some other compliant shell such as ksh or # bash, then to run this script, type that shell name before the whole # command line, like: # # ksh Gradle # # Busybox and similar reduced shells will NOT work, because this script # requires all of these POSIX shell features: # * functions; # * expansions $var, ${var}, ${var:-default}, ${var+SET}, # ${var#prefix}, ${var%suffix}, and $( cmd ); # * compound commands having a testable exit status, especially case; # * various built-in commands including command, set, and ulimit. # # Important for patching: # # (2) This script targets any POSIX shell, so it avoids extensions provided # by Bash, Ksh, etc; in particular arrays are avoided. # # The "traditional" practice of packing multiple parameters into a # space-separated string is a well documented source of bugs and security # problems, so this is (mostly) avoided, by progressively accumulating # options in "$@", and eventually passing that to Java. # # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; # see the in-line comments for details. # # There are tweaks for specific operating systems such as AIX, CygWin, # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template # path_to_url # within the Gradle project. # # You can find Gradle at path_to_url # ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link app_path=$0 # Need this for daisy-chained symlinks. while APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path [ -h "$app_path" ] do ls=$( ls -ld "$app_path" ) link=${ls#*' -> '} case $link in #( /*) app_path=$link ;; #( *) app_path=$APP_HOME$link ;; esac done APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit APP_NAME="Gradle" APP_BASE_NAME=${0##*/} # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum warn () { echo "$*" } >&2 die () { echo echo "$*" echo exit 1 } >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "$( uname )" in #( CYGWIN* ) cygwin=true ;; #( Darwin* ) darwin=true ;; #( MSYS* | MINGW* ) msys=true ;; #( NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD=$JAVA_HOME/jre/sh/java else JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD=java which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac case $MAX_FD in #( '' | soft) :;; #( *) ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac fi # Collect all arguments for the java command, stacking in reverse order: # * args from the command line # * the main class name # * -classpath # * -D...appname settings # * --module-path (only if needed) # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java if "$cygwin" || "$msys" ; then APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) JAVACMD=$( cygpath --unix "$JAVACMD" ) # Now convert the arguments - kludge to limit ourselves to /bin/sh for arg do if case $arg in #( -*) false ;; # don't mess with options #( /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath [ -e "$t" ] ;; #( *) false ;; esac then arg=$( cygpath --path --ignore --mixed "$arg" ) fi # Roll the args list around exactly as many times as the number of # args, so each arg winds up back in the position where it started, but # possibly modified. # # NB: a `for` loop captures its iteration list before it begins, so # changing the positional parameters here affects neither the number of # iterations, nor the values presented in `arg`. shift # remove old arg set -- "$@" "$arg" # push replacement arg done fi # Collect all arguments for the java command; # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of # shell script including quotes and variable substitutions, so put them in # double quotes to make sure that they get re-expanded; and # * put everything else in single quotes, so that it's not re-expanded. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ -classpath "$CLASSPATH" \ org.gradle.wrapper.GradleWrapperMain \ "$@" # Use "xargs" to parse quoted args. # # With -n1 it outputs one arg per line, with the quotes and backslashes removed. # # In Bash we could simply go: # # readarray ARGS < <( xargs -n1 <<<"$var" ) && # set -- "${ARGS[@]}" "$@" # # but POSIX shell has neither arrays nor command substitution, so instead we # post-process each arg (as a line of input to sed) to backslash-escape any # character that might be a shell metacharacter, then use eval to reverse # that process (while maintaining the separation between arguments), and wrap # the whole thing up as a single "set" statement. # # This will of course break if any of these variables contains a newline or # an unmatched quote. # eval "set -- $( printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | xargs -n1 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | tr '\n' ' ' )" '"$@"' exec "$JAVACMD" "$@" ```
/content/code_sandbox/android/gradlew
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,929
```gradle import org.apache.tools.ant.taskdefs.condition.Os import java.nio.file.Paths /** * Build and merge static webview assets. * * This is largely the job of `$ROOT/tools/build-webview`, a script external to * Gradle, as there is significant overlap between the iOS and Android build * processes. See comments therein (or $ROOT/src/webview/static/README.md) for * more information. */ /* * Windows support functions. * * On Windows, we have three different possible setups: * 1. Windows Gradle + Git Bash. * 2. Windows Gradle + WSL's bash. * 3. WSL Gradle + WSL's bash. * * Case 3, fortunately, should behave exactly like Linux. * * In cases 1 and 2, however, all paths Gradle provides are backslash-separated. * This is problematic on its own, as the script we're invoking doesn't grok * backslashes, so we normalize those on Windows. That's enough for case 1. * * Case 2 is worse, though. The `bash` of Git Bash groks both "C:/" and "C:\"; * more generally, it operates on the Windows filesystem with Windows path * names. The WSL `bash` _doesn't_ -- it's a standard Linux `bash` (or close * enough), and it only sees the Windows disks as ordinary mounts under the lone * root path '/'. Paths beginning with either "C:/" or "C:\" will confuse it * terribly. * * And, of course, Gradle has no good way of distinguishing between cases 1 and * 2. As far as it's concerned, `bash.exe` is `bash.exe`. * * Since we can't predict the environment of our callee, we can't use absolute * paths. Fortunately, with only a little extra work within the script itself, * we _can_ use relative paths; the script must derelativize them appropriately. */ /** Normalize the path-separators of `path` to be forward slashes. */ def normalizePath(String path) { if (Os.isFamily(Os.FAMILY_WINDOWS)) { return path.replace('\\', '/') } else { return path } } /** Return `path`, made relative to `basePath`. */ def relativizePath(String path, String basePath) { return Paths.get(basePath).relativize(Paths.get(path)).toString(); } gradle.projectsEvaluated { // The root of our git repository. def repoDir = project.file('../..').absolutePath // The intermediate assets directory which we'll be writing files to. // // This directory: // * should not be under source control, and // * should not collide with any autogenerated directory. // // (In particular, we should _not_ build directly to an assets-merge task's // output directory: we run before it does, and it will generally clear that // directory out before merging.) // // At present, as there is no difference between debug and release, this // directory is the same for all build variants. If the former fact changes, // the latter should as well. def assetsDir = "${buildDir}/_zulip_webview_staging/out" // Declare ${assetsDir} to be an asset source directory associated with all // build variants. (See the documentation on build variants and source sets, // linked below, for more information.) // // path_to_url#sourceset-build android.sourceSets.main.assets.srcDirs += assetsDir; // The immediate destination directory for `tools/build-webview`. This // directory will itself be copied into the APK, and so must be named // `webview`, as MessageList expects. // // (Additionally, see above note on Windows compatibility.) def destDir = normalizePath(relativizePath("${assetsDir}/webview", repoDir)) // The actual task to be executed. def webviewTask = tasks.create( name: "buildStaticWebviewAssets", type: Exec ) { // All arguments to our script must be relative to `workingDir`. workingDir repoDir executable "bash" args "./tools/build-webview", "android", "--check-path-name", "--destination", destDir } // Ensure that the webview-build task is executed before each variant's // assets-merge task. android.applicationVariants.all { variant -> variant.mergeAssetsProvider.configure { dependsOn webviewTask } } } ```
/content/code_sandbox/android/app/webviewAssets.gradle
gradle
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
991
```xml <manifest xmlns:android="path_to_url" xmlns:tools="path_to_url" package="com.zulipmobile"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" tools:node="remove" /> <!-- CAMERA has an unexpected wrinkle, and we want to avoid having any dependency requesting it. See path_to_url#narrow/stream/243-mobile-team/topic/react-native-image-picker.20upgrade/near/1267245, path_to_url and path_to_url --> <uses-permission android:name="android.permission.CAMERA" tools:node="remove" /> <!-- We shouldn't need these two elements in our merged manifest when we stop supporting Android 9 (SDK version 28); see path_to_url#storage-permission. At that time, check that none of our dependencies (such as expo-file-system) are trying to request these permissions; if they are, use tools:node="remove" (path_to_url#node_markers). If this reasoning changes, adjust `androidEnsureStoragePermission` in src/lightbox/download.js accordingly. --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="28" /> <uses-feature android:name="android.hardware.touchscreen" android:required="false" /> <!-- We use certain modules that adds the permission requirement for `ACCESS_WIFI_STATE` in the final AndroidManifest of the app, which makes wifi hardware a compulsary requirement to install the app. The following statement makes the hardware requirement optional. --> <uses-feature android:name="android.hardware.wifi" android:required="false" /> <queries> <intent> <!-- Find Chrome Custom Tabs, with this query and a "com.android.chrome" package check, so we can use it to open external links. --> <action android:name="android.support.customtabs.action.CustomTabsService" /> </intent> <intent> <!-- Find other apps that can open URLs, in case Chrome Custom Tabs is unavailable, so we can open external links. --> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.BROWSABLE" /> </intent> </queries> <application android:name=".MainApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" android:networkSecurityConfig="@xml/network_security_config" > <activity android:name=".MainActivity" android:exported="true" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode" android:label="@string/app_name" android:launchMode="singleTask" android:windowSoftInputMode="adjustResize"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:host="login" android:scheme="zulip" /> </intent-filter> </activity> <activity android:name=".ShareToZulipActivity" android:exported="true" android:label="@string/app_name" android:launchMode="standard" > <intent-filter> <action android:name="android.intent.action.SEND" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="*/*" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.SEND_MULTIPLE" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="*/*" /> </intent-filter> </activity> <service android:name=".notifications.FcmListenerService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service> <!-- To make a build that reports errors to Sentry, fill in the Sentry DSN below and uncomment. See src/sentryConfig.js for another site and more discussion. --> <!-- <meta-data android:name="io.sentry.auto-init" android:value="true" tools:node="replace" /> <meta-data android:name="io.sentry.dsn" android:value="path_to_url" /> --> </application> </manifest> ```
/content/code_sandbox/android/app/src/main/AndroidManifest.xml
xml
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,121
```xml <?xml version="1.0" encoding="utf-8"?> <resources> <!-- These are used for receiving notifications through the Zulip notification bouncer service: path_to_url They represent public identifiers for that service as an application registered with the relevant Google service. They're derived from a `google-services.json` file. For details, see: path_to_url#processing_the_json_file --> <string name="google_app_id" translatable="false">1:835904834568:android:19a01c6476449260</string> <string name="gcm_defaultSenderId" translatable="false">835904834568</string> </resources> ```
/content/code_sandbox/android/app/src/main/res/values/firebase.xml
xml
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
157
```xml <resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/primaryColor</item> <item name="colorPrimaryDark">@color/primaryColorDark</item> </style> </resources> ```
/content/code_sandbox/android/app/src/main/res/values/styles.xml
xml
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
76
```xml <?xml version="1.0" encoding="utf-8"?> <resources> <color name="primaryColor">#ffffff</color> <color name="primaryColorDark">#d7ccc8</color> <!-- This should agree with `BRAND_COLOR` in the JS code. --> <color name="brandColor">#6492fe</color> </resources> ```
/content/code_sandbox/android/app/src/main/res/values/color.xml
xml
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
82
```xml <resources> <string name="app_name">Zulip</string> <string name="notification_channel_name">Messages</string> <string name="no_browser_found">No Browser Found</string> <plurals name="numConversations"> <item quantity="one">%d conversation</item> <item quantity="other">%d conversations</item> </plurals> <string name="send_to">Share To</string> <plurals name="group_pm"> <item quantity="one">%1$s to you and %2$s other</item> <item quantity="other">%1$s to you and %2$s others</item> </plurals> <string name="selfUser">You</string> </resources> ```
/content/code_sandbox/android/app/src/main/res/values/strings.xml
xml
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
169
```kotlin package com.zulipmobile.notifications import com.google.common.truth.Expect import org.junit.Rule import org.junit.Test import org.junit.jupiter.api.assertThrows import java.net.URL open class FcmMessageTestBase { // This lets a single test method report multiple failures. // See upstream docs: // path_to_url // path_to_url @get:Rule val expect: Expect = Expect.create() // I'm pretty sure there are cleaner ways to do this -- ideally it would be // invoked more like // expect.that(mapOf()).parseFailure() // I think that means something like making a custom `Subject`, and adding // a `that` overload with a type like `Map<String, String> -> FcmMessageSubject`. // // But this is what I've figured out enough of the API so far to do, // and it'll be good enough for now. protected fun assertParseFails(data: Map<String, String>): FcmMessageParseException? { val f = assertThrows { FcmMessage.fromFcmData(data) } as Throwable expect.that(f).isInstanceOf(FcmMessageParseException::class.java) return f as? FcmMessageParseException } object Example { val base = mapOf( "server" to "zulip.example.cloud", // corresponds to EXTERNAL_HOST "realm_id" to "4", "realm_uri" to "path_to_url", // corresponds to realm.uri "user_id" to "234" ) internal val identity = Identity( serverHost = base["server"]!!, realmId = 4, realmUri = URL(base["realm_uri"]!!), userId = 234 ) } } class FcmMessageTest : FcmMessageTestBase() { @Test fun `parse failures on missing or bad event type`() { assertParseFails(mapOf()) assertParseFails(mapOf("event" to "nonsense")) } } class RecipientTest : FcmMessageTestBase() { @Test fun `GroupPm#getPmUsersString gives the correct string`() { expect.that(Recipient.GroupPm(pmUsers = setOf(123, 234, 345)).getPmUsersString()) .isEqualTo("123,234,345") } @Test fun `GroupPm#getPmUsersString correctly reorders user ids`() { expect.that(Recipient.GroupPm(pmUsers = setOf(234, 123, 23, 345)).getPmUsersString()) .isEqualTo("23,123,234,345") } } class MessageFcmMessageTest : FcmMessageTestBase() { object Example { val base = FcmMessageTestBase.Example.base.plus(sequenceOf( "event" to "message", "zulip_message_id" to "12345", "sender_id" to "123", "sender_email" to "sender@example.com", "sender_avatar_url" to "path_to_url", "sender_full_name" to "A Sender", "time" to "1546300800", // a Unix seconds-since-epoch "content" to "This is a message", // rendered_content, reduced to plain text "content_truncated" to "This is a m" )) val stream = base.plus(sequenceOf( "recipient_type" to "stream", "stream_id" to "42", "stream" to "denmark", "topic" to "play", "alert" to "New stream message from A Sender in denmark" )) val groupPm = base.plus(sequenceOf( "recipient_type" to "private", "pm_users" to "123,234,345", "alert" to "New private group message from A Sender" )) val pm = base.plus(sequenceOf( "recipient_type" to "private", "alert" to "New private message from A Sender" )) } @Test fun `'message' messages parse as MessageFcmMessage`() { val message = FcmMessage.fromFcmData(Example.stream) expect.that(message).isInstanceOf(MessageFcmMessage::class.java) } private fun parse(data: Map<String, String>) = FcmMessage.fromFcmData(data) as MessageFcmMessage private fun dataForOpen(data: Map<String, String>) = mapOf(*parse(data).dataForOpen()) @Test fun `fields get parsed right in 'message' happy path`() { expect.that(parse(Example.stream)).isEqualTo( MessageFcmMessage( identity = FcmMessageTestBase.Example.identity, sender = Sender( id = 123, email = Example.stream["sender_email"]!!, avatarURL = URL(Example.stream["sender_avatar_url"]!!), fullName = Example.stream["sender_full_name"]!! ), zulipMessageId = 12345, recipient = Recipient.Stream( streamId = Example.stream["stream_id"]!!.toInt(), streamName = Example.stream["stream"]!!, topic = Example.stream["topic"]!! ), content = Example.stream["content"]!!, timeMs = Example.stream["time"]!!.toLong() * 1000 ) ) expect.that(parse(Example.groupPm).recipient).isEqualTo( Recipient.GroupPm(pmUsers = setOf(123, 234, 345)) ) expect.that(parse(Example.pm).recipient).isEqualTo( Recipient.Pm ) } @Test fun `dataForOpen works right in happy path`() { expect.that(dataForOpen(Example.stream)).isEqualTo(mapOf( "realm_uri" to Example.stream["realm_uri"]!!, "user_id" to Example.stream["user_id"]!!.toInt(), "recipient_type" to "stream", "stream_id" to Example.stream["stream_id"]!!.toInt(), "stream_name" to Example.stream["stream"]!!, "topic" to Example.stream["topic"]!!, )) expect.that(dataForOpen(Example.groupPm)).isEqualTo(mapOf( "realm_uri" to Example.groupPm["realm_uri"]!!, "user_id" to Example.groupPm["user_id"]!!.toInt(), "recipient_type" to "private", "pm_users" to "123,234,345", )) expect.that(dataForOpen(Example.pm)).isEqualTo(mapOf( "realm_uri" to Example.pm["realm_uri"]!!, "user_id" to Example.pm["user_id"]!!.toInt(), "recipient_type" to "private", "sender_email" to Example.pm["sender_email"]!!, )) } @Test fun `optional fields missing cause no error`() { expect.that(parse(Example.stream.minus("stream_id")).recipient).isEqualTo(Recipient.Stream( streamId = null, streamName = Example.stream["stream"]!!, topic = Example.stream["topic"]!! )) expect.that(parse(Example.pm.minus("user_id")).identity.userId).isNull() } @Test fun `dataForOpen leaves out optional fields missing in input`() { val baseExpected = mapOf( "realm_uri" to Example.stream["realm_uri"]!!, "user_id" to Example.stream["user_id"]!!.toInt(), "recipient_type" to "stream", "stream_id" to Example.stream["stream_id"]!!.toInt(), "stream_name" to Example.stream["stream"]!!, "topic" to Example.stream["topic"]!!, ) expect.that(dataForOpen(Example.stream.minus("user_id"))) .isEqualTo(baseExpected.minus("user_id")) expect.that(dataForOpen(Example.stream.minus("stream_id"))) .isEqualTo(baseExpected.minus("stream_id")) } @Test fun `obsolete or novel fields have no effect`() { expect.that(parse(Example.pm.plus("user" to "client@example.com"))) .isEqualTo(parse(Example.pm)) expect.that(parse(Example.pm.plus("awesome_feature" to "behold!"))) .isEqualTo(parse(Example.pm)) } @Test fun `parse failures on malformed 'message'`() { assertParseFails(Example.pm.minus("server")) assertParseFails(Example.pm.minus("realm_id")) assertParseFails(Example.pm.plus("realm_id" to "12,34")) assertParseFails(Example.pm.plus("realm_id" to "abc")) assertParseFails(Example.pm.minus("realm_uri")) assertParseFails(Example.pm.plus("realm_uri" to "zulip.example.com")) assertParseFails(Example.pm.plus("realm_uri" to "/examplecorp")) assertParseFails(Example.stream.minus("recipient_type")) assertParseFails(Example.stream.plus("stream_id" to "12,34")) assertParseFails(Example.stream.plus("stream_id" to "abc")) assertParseFails(Example.stream.minus("stream")) assertParseFails(Example.stream.minus("topic")) assertParseFails(Example.groupPm.minus("recipient_type")) assertParseFails(Example.groupPm.plus("pm_users" to "abc,34")) assertParseFails(Example.groupPm.plus("pm_users" to "12,abc")) assertParseFails(Example.groupPm.plus("pm_users" to "12,")) assertParseFails(Example.pm.minus("recipient_type")) assertParseFails(Example.pm.plus("recipient_type" to "nonsense")) assertParseFails(Example.pm.minus("sender_avatar_url")) assertParseFails(Example.pm.plus("sender_avatar_url" to "/avatar/123.jpeg")) assertParseFails(Example.pm.plus("sender_avatar_url" to "")) assertParseFails(Example.pm.minus("sender_id")) assertParseFails(Example.pm.minus("sender_email")) assertParseFails(Example.pm.minus("sender_full_name")) assertParseFails(Example.pm.minus("zulip_message_id")) assertParseFails(Example.pm.plus("zulip_message_id" to "12,34")) assertParseFails(Example.pm.plus("zulip_message_id" to "abc")) assertParseFails(Example.pm.minus("content")) assertParseFails(Example.pm.minus("time")) assertParseFails(Example.pm.plus("time" to "12:34")) } } class RemoveFcmMessageTest : FcmMessageTestBase() { object Example { val base = FcmMessageTestBase.Example.base.plus(sequenceOf( "event" to "remove" )) /// The Zulip server before v2.0 sends this form (plus some irrelevant fields). // TODO(server-2.0): Drop this, and the logic it tests. val singular = base.plus(sequenceOf( "zulip_message_id" to "123" )) /// Zulip servers starting at v2.0 (released 2019-02-28; commit 9869153ae) /// send a hybrid form. (In practice the singular field has one of the /// same IDs found in the batch.) /// /// We started consuming the batch field in 23.2.111 (released 2019-02-28; /// commit 4acd07376). val hybrid = base.plus(sequenceOf( "zulip_message_ids" to "234,345", "zulip_message_id" to "123" )) /// Some future Zulip server (at least v2.1; after clients older than /// v23.2.111 are rare) may drop the singular field. val batched = base.plus(sequenceOf( "zulip_message_ids" to "123,234,345" )) internal val identity = FcmMessageTestBase.Example.identity } @Test fun `'remove' messages parse as RemoveFcmMessage`() { val message = FcmMessage.fromFcmData(Example.batched) expect.that(message).isInstanceOf(RemoveFcmMessage::class.java) } private fun parse(data: Map<String, String>) = FcmMessage.fromFcmData(data) as RemoveFcmMessage @Test fun `fields get parsed right in happy path`() { expect.that(parse(Example.hybrid)).isEqualTo( RemoveFcmMessage(Example.identity, setOf(123, 234, 345)) ) expect.that(parse(Example.batched)).isEqualTo( RemoveFcmMessage(Example.identity, setOf(123, 234, 345)) ) expect.that(parse(Example.singular)).isEqualTo( RemoveFcmMessage(Example.identity, setOf(123)) ) expect.that(parse(Example.singular.minus("zulip_message_id"))).isEqualTo( // This doesn't seem very useful to send, but harmless. RemoveFcmMessage(Example.identity, setOf()) ) } @Test fun `optional fields missing cause no error`() { expect.that(parse(Example.hybrid.minus("user_id")).identity.userId).isNull() } @Test fun `parse failures on malformed data`() { assertParseFails(Example.hybrid.minus("server")) assertParseFails(Example.hybrid.minus("realm_id")) assertParseFails(Example.hybrid.plus("realm_id" to "abc")) assertParseFails(Example.hybrid.plus("realm_id" to "12,34")) assertParseFails(Example.hybrid.minus("realm_uri")) assertParseFails(Example.hybrid.plus("realm_uri" to "zulip.example.com")) assertParseFails(Example.hybrid.plus("realm_uri" to "/examplecorp")) for (badInt in sequenceOf( "12,34", "abc", "" )) { assertParseFails(Example.singular.plus("zulip_message_id" to badInt)) assertParseFails(Example.hybrid.plus("zulip_message_id" to badInt)) } for (badIntList in sequenceOf( "abc,34", "12,abc", "12,", "" )) { assertParseFails(Example.hybrid.plus("zulip_message_ids" to badIntList)) assertParseFails(Example.batched.plus("zulip_message_ids" to badIntList)) } } } class TestFcmMessageTest : FcmMessageTestBase() { object Example { val base = FcmMessageTestBase.Example.base.plus(sequenceOf( "event" to "test", "realm_name" to "Zulip Community", )) val legacy = base .plus("event" to "test-by-device-token") .minus("realm_name") internal val identity = FcmMessageTestBase.Example.identity } @Test fun `'test' messages parse as TestFcmMessage`() { val message = FcmMessage.fromFcmData(Example.base) expect.that(message).isInstanceOf(TestFcmMessage::class.java) } @Test fun `legacy test messages parse as TestFcmMessage`() { val message = FcmMessage.fromFcmData(Example.legacy) expect.that(message).isInstanceOf(TestFcmMessage::class.java) } @Test fun `parse failures on malformed data`() { assertParseFails(Example.base.minus("server")) assertParseFails(Example.base.minus("realm_id")) assertParseFails(Example.base.plus("realm_id" to "abc")) assertParseFails(Example.base.plus("realm_id" to "12,34")) assertParseFails(Example.base.minus("realm_uri")) assertParseFails(Example.base.plus("realm_uri" to "zulip.example.com")) assertParseFails(Example.base.plus("realm_uri" to "/examplecorp")) } } ```
/content/code_sandbox/android/app/src/test/java/com/zulipmobile/notifications/FcmMessageTest.kt
kotlin
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
3,550
```xml <?xml version="1.0" encoding="utf-8"?> <network-security-config> <!-- For reference on this file's semantics: path_to_url#FileFormat --> <base-config> <!-- If the user has configured additional CAs on the device, trust those too. This can be useful for an internal Zulip server in a corporate or institutional environment, and was a recurring user request: path_to_url --> <trust-anchors> <certificates src="system" /> <certificates src="user" /> </trust-anchors> </base-config> <domain-config> <!-- But revert to the default, stricter behavior trusting only the system CA list where we know we can, which means for domains where we know a legitimate cert will always come from a widely-trusted CA. Specifically, we know this is the case for Zulip Cloud and other domains operated by the core Zulip developers at Kandra Labs. --> <domain includeSubdomains="true">zulipchat.com</domain> <domain includeSubdomains="true">zulip.com</domain> <domain includeSubdomains="true">zulip.org</domain> <trust-anchors> <certificates src="system" /> </trust-anchors> </domain-config> </network-security-config> ```
/content/code_sandbox/android/app/src/main/res/xml/network_security_config.xml
xml
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
297
```xml <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="path_to_url"> <translate android:fromXDelta="0" android:toXDelta="100%p" android:duration="@android:integer/config_mediumAnimTime"/> </set> ```
/content/code_sandbox/android/app/src/main/res/anim/slide_out_right.xml
xml
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
66
```xml <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="path_to_url"> <translate android:fromXDelta="0" android:toXDelta="-100%p" android:duration="@android:integer/config_mediumAnimTime"/> </set> ```
/content/code_sandbox/android/app/src/main/res/anim/slide_out_left.xml
xml
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
66
```xml <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="path_to_url"> <translate android:fromXDelta="100%p" android:toXDelta="0" android:duration="@android:integer/config_mediumAnimTime"/> </set> ```
/content/code_sandbox/android/app/src/main/res/anim/slide_in_right.xml
xml
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
66
```xml <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="path_to_url"> <translate android:fromXDelta="-100%p" android:toXDelta="0" android:duration="@android:integer/config_mediumAnimTime"/> </set> ```
/content/code_sandbox/android/app/src/main/res/anim/slide_in_left.xml
xml
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
66
```java package com.zulipmobile; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.ArrayList; import java.util.List; class ZulipNativePackage implements ReactPackage { @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { List<ViewManager> managers = new ArrayList<>(); return managers; } @Override public List<NativeModule> createNativeModules( ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>(); modules.add(new CustomTabsAndroid(reactContext)); modules.add(new RNSecureRandom(reactContext)); modules.add(new CloseAllCustomTabsAndroid(reactContext)); modules.add(new ShareFileAndroid(reactContext)); modules.add(new TextCompressionModule(reactContext)); return modules; } } ```
/content/code_sandbox/android/app/src/main/java/com/zulipmobile/ZulipNativePackage.java
java
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
196
```kotlin package com.zulipmobile import android.util.Log import io.sentry.Sentry import io.sentry.SentryLevel /** * Zulip-specific logging helpers. * * These mirror part of the interface of `android.util.Log`, but they log * to Sentry as well as to the device console. * * We basically always want to use these instead of plain `Log.e` or `Log.w`. */ class ZLog { companion object { /** Log an error to both Sentry and the device log. */ public fun e(tag: String, e: Throwable) { // Oddly there is no `Log.e` taking just a throwable, like there is for `Log.w`. // Have a message that just repeats the first line of how the throwable prints. val msg = "${e.javaClass.name}: ${e.message}" Log.e(tag, msg, e) Sentry.captureException(e) } /** Log a warning to both Sentry and the device log. */ public fun w(tag: String, e: Throwable) { Log.w(tag, e) SentryX.warnException(e) } /** Log a warning to both Sentry and the device log. */ public fun w(tag: String, msg: String) { Log.w(tag, msg) Sentry.captureMessage(msg, SentryLevel.WARNING) } } } ```
/content/code_sandbox/android/app/src/main/java/com/zulipmobile/ZLog.kt
kotlin
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
287
```kotlin package com.zulipmobile import android.util.Base64 import com.facebook.react.bridge.Promise import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactContextBaseJavaModule import com.facebook.react.bridge.ReactMethod import java.io.ByteArrayOutputStream import java.io.IOException import java.io.UnsupportedEncodingException import java.util.zip.DataFormatException import java.util.zip.Deflater import java.util.zip.Inflater // TODO: Write unit tests; see // path_to_url#unit-tests-android. // TODO: Experiment what value gives the best performance. private const val bufferSize = 8192 private const val header = "z|zlib base64|" internal fun compress(input: String): String { val outputStream = ByteArrayOutputStream() val deflater = Deflater() deflater.setInput(input.toByteArray(charset("UTF-8"))) deflater.finish() val buffer = ByteArray(bufferSize) while (!deflater.finished()) { val byteCount = deflater.deflate(buffer) outputStream.write(buffer, 0, byteCount) } deflater.end() outputStream.close() // The RN bridge currently doesn't support sending byte strings, so we // have to encode the compressed output as a `String`. To avoid any // trouble, we use base64 to keep things inside ASCII. // // Ultimately our ASCII data seems to end up going to SQLite with size // no more than about 1 byte/char (presumably the string gets encoded // as UTF-8 and it's exactly 1 byte/char), so this is pretty OK. return header + Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT) } internal fun decompress(input: String): String { val inflater = Inflater() val inputBytes = input.toByteArray(charset("ISO-8859-1")) inflater.setInput(Base64.decode(inputBytes, header.length, inputBytes.size - header.length, Base64.DEFAULT)) val outputStream = ByteArrayOutputStream() val buffer = ByteArray(bufferSize) while (inflater.remaining != 0) { val byteCount = inflater.inflate(buffer) outputStream.write(buffer, 0, byteCount) } inflater.end() outputStream.close() return outputStream.toString("UTF-8") } internal class TextCompressionModule(reactContext: ReactApplicationContext?) : ReactContextBaseJavaModule(reactContext) { override fun getName(): String = "TextCompressionModule" override fun getConstants(): Map<String, Any> = hashMapOf("header" to header) @ReactMethod fun compress(input: String, promise: Promise) { try { promise.resolve(compress(input)) } catch (e: UnsupportedEncodingException) { promise.reject("UNSUPPORTED_ENCODING_EXCEPTION", e) } catch (e: IOException) { promise.reject("IO_EXCEPTION", e) } } @ReactMethod fun decompress(input: String, promise: Promise) { try { promise.resolve(decompress(input)) } catch (e: UnsupportedEncodingException) { promise.reject("UNSUPPORTED_ENCODING_EXCEPTION", e) } catch (e: IOException) { promise.reject("IO_EXCEPTION", e) } catch (e: DataFormatException) { promise.reject("DATA_FORMAT_EXCEPTION", e) } } } ```
/content/code_sandbox/android/app/src/main/java/com/zulipmobile/TextCompression.kt
kotlin
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
697
```kotlin package com.zulipmobile; import android.content.ComponentName import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity /// The activity for when a user shares to Zulip from another app. /// /// This is a tiny shim activity, which forwards the user on to our /// [MainActivity] to get the actual UI for sharing to Zulip. class ShareToZulipActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) intent.component = ComponentName(applicationContext.packageName, "com.zulipmobile.MainActivity") intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(intent) finish() } } ```
/content/code_sandbox/android/app/src/main/java/com/zulipmobile/ShareToZulipActivity.kt
kotlin
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
144
```java package com.zulipmobile; import android.content.Context; import android.content.Intent; import android.content.pm.ResolveInfo; import androidx.annotation.NonNull; import java.util.List; /** * Contains helper methods for custom tabs. */ class CustomTabsHelper { private static final String SERVICE_ACTION = "android.support.customtabs.action.CustomTabsService"; private static final String CHROME_PACKAGE = "com.android.chrome"; public static boolean isChromeCustomTabsSupported(@NonNull final Context context) { Intent serviceIntent = new Intent(SERVICE_ACTION); serviceIntent.setPackage(CHROME_PACKAGE); List<ResolveInfo> resolveInfos = context.getPackageManager().queryIntentServices(serviceIntent, 0); return !(resolveInfos == null || resolveInfos.isEmpty()); } } ```
/content/code_sandbox/android/app/src/main/java/com/zulipmobile/CustomTabsHelper.java
java
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
155
```kotlin package com.zulipmobile import io.sentry.Sentry import io.sentry.SentryLevel /** * A home for things that ought to be static extensions of `Sentry`. * * Extending Java classes with static members isn't currently a feature * available in Kotlin: * path_to_url * so this is our substitute. */ class SentryX { companion object { /** * Like `Sentry.captureException`, but at level `SentryLevel.WARNING`. */ public fun warnException(e: Throwable) { Sentry.withScope { scope -> scope.level = SentryLevel.WARNING Sentry.captureException(e) } } } } ```
/content/code_sandbox/android/app/src/main/java/com/zulipmobile/SentryUtils.kt
kotlin
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
142
```kotlin package com.zulipmobile import android.content.Intent import android.net.Uri import androidx.core.content.FileProvider import com.facebook.react.bridge.Promise import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactContextBaseJavaModule import com.facebook.react.bridge.ReactMethod import java.io.File /** * Allows Sending Files from Zulip to other apps. */ class ShareFileAndroid(reactContext: ReactApplicationContext?) : ReactContextBaseJavaModule(reactContext) { override fun getName(): String { return "ShareFileAndroid" } @ReactMethod fun shareFile(path: String, promise: Promise) = try { // Using `FileProvider` here requires setup in AndroidManifest.xml: // path_to_url // Currently we don't do this explicitly in our AndroidManifest.xml // source file; instead we rely implicitly on a manifest snippet // added by `rn-fetch-blob`. This authority string needs to match // the `android:authorities` value from there. val fileProviderAuthority = reactApplicationContext.packageName + ".provider" val sharedFileUri: Uri = FileProvider.getUriForFile( reactApplicationContext, fileProviderAuthority, File(path)) val shareIntent = Intent() shareIntent.action = Intent.ACTION_SEND shareIntent.type = reactApplicationContext.contentResolver.getType(sharedFileUri) shareIntent.putExtra(Intent.EXTRA_STREAM, sharedFileUri) val chooserIntent = Intent.createChooser(shareIntent, reactApplicationContext.resources.getText(R.string.send_to)) chooserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) reactApplicationContext.startActivity(chooserIntent) promise.resolve(null) } catch (e: Exception) { promise.reject(e) } } ```
/content/code_sandbox/android/app/src/main/java/com/zulipmobile/ShareFileAndroid.kt
kotlin
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
363
```java package com.zulipmobile; import android.content.Intent; import android.content.pm.ResolveInfo; import android.net.Uri; import android.widget.Toast; import androidx.browser.customtabs.CustomTabsIntent; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import java.util.List; /** * Launches custom tabs. */ class CustomTabsAndroid extends ReactContextBaseJavaModule { private final ReactApplicationContext context; CustomTabsAndroid(ReactApplicationContext reactContext) { super(reactContext); this.context = reactContext; } @Override public String getName() { return "CustomTabsAndroid"; } @ReactMethod public void openURL(String url) throws NullPointerException { CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(); builder.setStartAnimations(context, R.anim.slide_in_right, R.anim.slide_out_left); builder.setExitAnimations(context, R.anim.slide_in_left, R.anim.slide_out_right); CustomTabsIntent customTabsIntent = builder.build(); if (CustomTabsHelper.isChromeCustomTabsSupported(context)) { customTabsIntent.launchUrl(context.getCurrentActivity(), Uri.parse(url)); } else { //open in browser Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); //ensure browser is present final List<ResolveInfo> customTabsApps = context.getPackageManager().queryIntentActivities(i, 0); if (customTabsApps.size() > 0) { i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); } else { // no browser Toast.makeText(getReactApplicationContext(), R.string.no_browser_found, Toast.LENGTH_SHORT).show(); } } } } ```
/content/code_sandbox/android/app/src/main/java/com/zulipmobile/CustomTabsAndroid.java
java
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
368
```java package com.zulipmobile; import android.util.Base64; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import java.security.SecureRandom; import java.util.HashMap; import java.util.Map; class RNSecureRandom extends ReactContextBaseJavaModule { private static final String SEED_KEY = "seed"; public RNSecureRandom(ReactApplicationContext reactContext) { super(reactContext); } @Override public String getName() { return "RNSecureRandom"; } @ReactMethod public void randomBase64(int size, Callback success) { success.invoke(null, getRandomBytes(size)); } @Override public Map<String, Object> getConstants() { final Map<String, Object> constants = new HashMap<>(); constants.put(SEED_KEY, getRandomBytes(4096)); return constants; } @ReactMethod private String getRandomBytes(int size) { SecureRandom sr = new SecureRandom(); byte[] values = new byte[size]; sr.nextBytes(values); return Base64.encodeToString(values, Base64.DEFAULT); } } ```
/content/code_sandbox/android/app/src/main/java/com/zulipmobile/RNSecureRandom.java
java
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
258
```kotlin package com.zulipmobile import com.facebook.react.ReactActivity import com.facebook.react.ReactApplication import com.facebook.react.ReactInstanceManager import com.facebook.react.ReactNativeHost import com.facebook.react.bridge.ReactContext import com.facebook.react.common.LifecycleState import com.facebook.react.modules.core.DeviceEventManagerModule /** * A distillation of ReactContext.getLifecycleState() and related information. * * See ReactContext.getAppStatus(). */ enum class ReactAppStatus { /** * The main activity has either never yet been in the foreground, * or never will again. There might not be an active JS instance. */ NOT_RUNNING, /** * The main activity has been in the foreground, is out of foreground * now, but might come back. There must be an active JS instance. */ BACKGROUND, /** * The main activity is in the foreground. * There must be an active JS instance. */ FOREGROUND } val ReactContext.appStatus: ReactAppStatus get() { if (!hasActiveCatalystInstance()) return ReactAppStatus.NOT_RUNNING // The RN lifecycleState: // * starts as BEFORE_CREATE // * responds to onResume, onPause, and onDestroy on the host Activity // * Android upstream docs on those: // path_to_url // * RN wires those through ReactActivity -> ReactActivityDelegate -> // ReactInstanceManager (as onHost{Resume,Pause,Destroy}) -> ReactContext // * notably goes straight BEFORE_CREATE -> RESUMED when first starting // (at least as of RN v0.59) return when (lifecycleState!!) { LifecycleState.BEFORE_CREATE -> ReactAppStatus.NOT_RUNNING LifecycleState.BEFORE_RESUME -> ReactAppStatus.BACKGROUND LifecycleState.RESUMED -> ReactAppStatus.FOREGROUND } } // A convenience shortcut. fun ReactContext.emitEvent(eventName: String, data: Any?) { getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java) .emit(eventName, data) } /** * Like getReactInstanceManager, but just return what exists; avoid trying to create. * * When there isn't already an instance manager, if we call * getReactInstanceManager it'll try to create one... which asserts we're * on the UI thread, which isn't true if e.g. we got here from a Service. */ fun ReactNativeHost.tryGetReactInstanceManager(): ReactInstanceManager? = if (this.hasInstance()) this.reactInstanceManager else null // A convenience shortcut. fun ReactApplication.tryGetReactContext(): ReactContext? = this.reactNativeHost.tryGetReactInstanceManager()?.currentReactContext /** * Like `.application`, but with a more specific type. * * This expresses the invariant that a ReactActivity's application * should always be a ReactApplication. */ val ReactActivity.reactApplication: ReactApplication get() = application as ReactApplication ```
/content/code_sandbox/android/app/src/main/java/com/zulipmobile/ReactExtensions.kt
kotlin
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
641
```java package com.zulipmobile; import android.content.Intent; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; /** * Close all custom tabs. */ public class CloseAllCustomTabsAndroid extends ReactContextBaseJavaModule { public CloseAllCustomTabsAndroid(ReactApplicationContext reactContext) { super(reactContext); } @Override public String getName() { return "CloseAllCustomTabsAndroid"; } @ReactMethod public void closeAll() throws NullPointerException { Intent intent = new Intent(getReactApplicationContext().getCurrentActivity(), MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getReactApplicationContext().getCurrentActivity().startActivity(intent); } } ```
/content/code_sandbox/android/app/src/main/java/com/zulipmobile/CloseAllCustomTabsAndroid.java
java
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
170
```java package com.zulipmobile; import android.app.Application; import android.content.Context; import android.content.res.Configuration; import androidx.annotation.NonNull; import com.facebook.react.PackageList; import com.facebook.react.ReactApplication; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.soloader.SoLoader; import expo.modules.ApplicationLifecycleDispatcher; import expo.modules.ReactNativeHostWrapper; import java.lang.reflect.InvocationTargetException; import java.util.List; import com.zulipmobile.notifications.NotificationChannelManager; import com.zulipmobile.notifications.NotificationsPackage; import com.zulipmobile.sharing.SharingPackage; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHostWrapper( this, new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { // Autolinked packages. // // To check what's included, see the // `getPackages` implementation, which is auto-generated // (android/app/build/generated/rncli/src/main/java/com/facebook/react/PackageList.java): @SuppressWarnings("UnnecessaryLocalVariable") List<ReactPackage> packages = new PackageList(this).getPackages(); // Packages that should be linked, but can't be with // autolinking: packages.add(new ZulipNativePackage()); packages.add(new NotificationsPackage()); packages.add(new SharingPackage()); return packages; } @Override protected String getJSMainModuleName() { return "index"; } }); @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); NotificationChannelManager.createNotificationChannel(this); SoLoader.init(this, /* native exopackage */ false); initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); ApplicationLifecycleDispatcher.onApplicationCreate(this); } @Override public void onConfigurationChanged(@NonNull Configuration newConfig) { super.onConfigurationChanged(newConfig); ApplicationLifecycleDispatcher.onConfigurationChanged(this, newConfig); } /** * Loads Flipper in React Native templates. Call this in the onCreate method with something like * initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); * * @param context * @param reactInstanceManager */ private static void initializeFlipper( Context context, ReactInstanceManager reactInstanceManager) { if (BuildConfig.DEBUG) { try { /* We use reflection here to pick up the class that initializes Flipper, since Flipper library is not available in release mode */ Class<?> aClass = Class.forName("com.zulipmobile.ReactNativeFlipper"); aClass .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class) .invoke(null, context, reactInstanceManager); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } } ```
/content/code_sandbox/android/app/src/main/java/com/zulipmobile/MainApplication.java
java
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
717
```kotlin package com.zulipmobile import android.content.Intent import android.os.Build import android.os.Bundle import android.webkit.WebView import com.facebook.react.ReactActivity import com.facebook.react.ReactActivityDelegate import com.zulipmobile.notifications.maybeHandleViewNotif import com.zulipmobile.sharing.handleSend import expo.modules.ReactActivityDelegateWrapper open class MainActivity : ReactActivity() { /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */ override fun getMainComponentName(): String { return "ZulipMobile" } override fun createReactActivityDelegate(): ReactActivityDelegate { return ReactActivityDelegateWrapper( this, ReactActivityDelegate(this, mainComponentName) ) } /* Returns true just if we did handle the intent. */ private fun maybeHandleIntent(intent: Intent?): Boolean { intent ?: return false when (intent.action) { // Share-to-Zulip Intent.ACTION_SEND, Intent.ACTION_SEND_MULTIPLE -> { handleSend(intent, reactApplication.tryGetReactContext(), contentResolver) return true } Intent.ACTION_VIEW -> { if (maybeHandleViewNotif(intent, reactApplication.tryGetReactContext())) { // Notification tapped return true } // Let RN handle other intents. In particular web-auth intents (parsed in // src/start/webAuth.js) have ACTION_VIEW, scheme "zulip", and authority "login". return false } // For other intents, let RN handle it. else -> return false } } override fun onCreate(savedInstanceState: Bundle?) { // Discard savedInstanceState. This is required by react-native-screens: // path_to_url#android super.onCreate(null) WebView.setWebContentsDebuggingEnabled(true) // Intent is reused after quitting, skip it. if ((intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) { return; } maybeHandleIntent(intent) } override fun onNewIntent(intent: Intent?) { if (maybeHandleIntent(intent)) { return } super.onNewIntent(intent) } /** * Align the back button behavior with Android S * where moving root activities to background instead of finishing activities. * @see <a href="path_to_url#onBackPressed()">onBackPressed</a> */ override fun invokeDefaultOnBackPressed() { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) { if (!moveTaskToBack(false)) { // For non-root activities, use the default implementation to finish them. super.invokeDefaultOnBackPressed() } return } // Use the default back button implementation on Android S // because it's doing more than {@link Activity#moveTaskToBack} in fact. super.invokeDefaultOnBackPressed() } } ```
/content/code_sandbox/android/app/src/main/java/com/zulipmobile/MainActivity.kt
kotlin
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
631
```kotlin package com.zulipmobile.sharing import com.facebook.react.bridge.* internal class SharingModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) { override fun getName(): String { return "Sharing" } @ReactMethod fun readInitialSharedContent(promise: Promise) { promise.resolve(initialSharedData) initialSharedData = null } companion object { var initialSharedData: WritableMap? = null } } ```
/content/code_sandbox/android/app/src/main/java/com/zulipmobile/sharing/SharingModule.kt
kotlin
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
106
```kotlin package com.zulipmobile.sharing import com.facebook.react.ReactPackage import com.facebook.react.bridge.NativeModule import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.uimanager.ViewManager class SharingPackage : ReactPackage { override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> { return emptyList() } override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> { return arrayListOf(SharingModule(reactContext)) } } ```
/content/code_sandbox/android/app/src/main/java/com/zulipmobile/sharing/SharingPackage.kt
kotlin
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
112
```kotlin package com.zulipmobile.notifications import com.facebook.react.ReactApplication import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage class FcmListenerService : FirebaseMessagingService() { override fun onMessageReceived(message: RemoteMessage) { onReceived(this, message.data) } override fun onNewToken(token: String) { super.onNewToken(token) val reactContext = (application as ReactApplication) .reactNativeHost .reactInstanceManager .currentReactContext NotificationsModule.emitToken(reactContext, token) } } ```
/content/code_sandbox/android/app/src/main/java/com/zulipmobile/notifications/FcmListenerService.kt
kotlin
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
127
```kotlin @file:JvmName("SharingHelper") package com.zulipmobile.sharing import android.content.ContentResolver import android.content.Intent import android.net.Uri import android.provider.OpenableColumns import android.util.Log import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.ReactContext import com.facebook.react.bridge.WritableMap import com.zulipmobile.ReactAppStatus import com.zulipmobile.ZLog import com.zulipmobile.appStatus import com.zulipmobile.emitEvent @JvmField val TAG = "ShareToZulip" internal fun handleSend( intent: Intent, reactContext: ReactContext?, contentResolver: ContentResolver, ) { val params: WritableMap = try { getParamsFromIntent(intent, contentResolver) } catch (e: ShareParamsParseException) { ZLog.w(TAG, e) return } // TODO deduplicate this with notifyReact; see // path_to_url#discussion_r764437055 // Until then, keep in sync when changing. val appStatus = reactContext?.appStatus Log.d(TAG, "app status is $appStatus") when (appStatus) { null, ReactAppStatus.NOT_RUNNING -> // Either there's no JS environment running, or we haven't yet reached // foreground. Expect the app to check initialSharedData on launch. SharingModule.initialSharedData = params ReactAppStatus.BACKGROUND, ReactAppStatus.FOREGROUND -> // JS is running and has already reached foreground. It won't check // initialSharedData again, but it will see a shareReceived event. reactContext.emitEvent("shareReceived", params) } } private fun urlToSharedFile(url: Uri, contentResolver: ContentResolver): WritableMap { val file = Arguments.createMap() file.putString("name", getFileName(url, contentResolver)) file.putString("mimeType", contentResolver.getType(url) ?: "application/octet-stream") file.putString("url", url.toString()) return file } private fun getParamsFromIntent(intent: Intent, contentResolver: ContentResolver): WritableMap { // For documentation of what fields to expect in the Intent, see: // path_to_url#ACTION_SEND // // params is constructed to be sent over to React/JS, and must contain data in // sync with the code over there. // // To Ensure this make sure to keep the construction logic in sync with what is // expected there. // // it corresponds with `src/types.js#SharedData`. val params = Arguments.createMap() if ("text/plain" == intent.type) { val sharedText = intent.getStringExtra(Intent.EXTRA_TEXT) params.putString("type", "text") params.putString("sharedText", sharedText) } else { val files = Arguments.createArray() when (intent.action) { Intent.ACTION_SEND -> { val url = intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM) ?: throw ShareParamsParseException("Could not extract URL from File Intent") val file = urlToSharedFile(url, contentResolver) files.pushMap(file) } Intent.ACTION_SEND_MULTIPLE -> { val urls = intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM) ?: throw ShareParamsParseException("Could not extract URLs from File Intent") for (url in urls) { files.pushMap(urlToSharedFile(url, contentResolver)) } } } params.putString("type", "file") params.putArray("files", files) } return params } fun getFileName(uri: Uri, contentResolver: ContentResolver): String { return contentResolver.query(uri, null, null, null, null)?.use { cursor -> cursor.moveToFirst() val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME) cursor.getString(nameIndex) } ?: "unknown." + (contentResolver.getType(uri)?.split('/')?.last() ?: "bin") } class ShareParamsParseException(errorMessage: String) : RuntimeException(errorMessage) ```
/content/code_sandbox/android/app/src/main/java/com/zulipmobile/sharing/SharingHelper.kt
kotlin
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
868
```kotlin @file:JvmName("NotifyReact") package com.zulipmobile.notifications import android.content.Intent import android.os.Bundle import android.util.Log import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.ReactContext import com.zulipmobile.* /** * Methods for telling React about a notification. * * This logic was largely inherited from the wix library. * TODO: Replace this with a fresh implementation based on RN upstream docs. */ /** * Recognize if an ACTION_VIEW intent came from tapping a notification; handle it if so * * Just if the intent is recognized, * sends a 'notificationOpened' event to the JavaScript layer * and returns true. * Else does nothing and returns false. * * Do not call if `intent.action` is not ACTION_VIEW. */ internal fun maybeHandleViewNotif(intent: Intent, maybeReactContext: ReactContext?): Boolean { assert(intent.action == Intent.ACTION_VIEW) val url = intent.data // Launch MainActivity on tapping a notification if (url?.scheme == "zulip" && url.authority == NOTIFICATION_URL_AUTHORITY) { val data = intent.getBundleExtra(EXTRA_NOTIFICATION_DATA) ?: return false logNotificationData("notif opened", data) notifyReact(maybeReactContext, data) return true } return false } internal fun notifyReact(reactContext: ReactContext?, data: Bundle) { // TODO deduplicate this with handleSend in SharingHelper.kt; see // path_to_url#discussion_r764437055 // Until then, keep in sync when changing. val appStatus = reactContext?.appStatus Log.d(TAG, "notifyReact: app status is $appStatus") when (appStatus) { null, ReactAppStatus.NOT_RUNNING -> // Either there's no JS environment running, or we haven't yet reached // foreground. Expect the app to check initialNotification on launch. NotificationsModule.initialNotification = data ReactAppStatus.BACKGROUND, ReactAppStatus.FOREGROUND -> // JS is running and has already reached foreground. It won't check // initialNotification again, but it will see a notificationOpened event. reactContext.emitEvent("notificationOpened", Arguments.fromBundle(data)) } } ```
/content/code_sandbox/android/app/src/main/java/com/zulipmobile/notifications/NotifyReact.kt
kotlin
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
484
```kotlin package com.zulipmobile.notifications import com.google.firebase.iid.FirebaseInstanceId import com.google.firebase.iid.InstanceIdResult import android.os.Bundle import android.util.Log import androidx.core.app.NotificationManagerCompat import com.facebook.react.bridge.* import com.google.android.gms.common.ConnectionResult import com.google.android.gms.common.GoogleApiAvailability import com.zulipmobile.emitEvent import java.lang.Exception internal class NotificationsModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) { override fun getName(): String { return "Notifications" } /** * Grab the token and return it to the JavaScript caller. */ @ReactMethod fun getToken(promise: Promise) { FirebaseInstanceId.getInstance().instanceId .addOnSuccessListener { instanceId: InstanceIdResult -> promise.resolve(instanceId.token) } .addOnFailureListener { e: Exception? -> promise.reject(e) } } @ReactMethod fun readInitialNotification(promise: Promise) { if (null == initialNotification) { promise.resolve(null) } else { promise.resolve(Arguments.fromBundle(initialNotification)) initialNotification = null } } /** * Tell the JavaScript caller about the availability of Google Play Services. */ // Ideally we wouldn't depend on Google Play Services for notifications; // that's #3838. @ReactMethod fun googlePlayServicesAvailability(promise: Promise) { val googleApiAvailability = GoogleApiAvailability.getInstance() // path_to_url#isGooglePlayServicesAvailable(android.content.Context) val connectionResult = ConnectionResult( googleApiAvailability.isGooglePlayServicesAvailable(reactApplicationContext)) promise.resolve(Arguments.createMap().apply { // Keep return value in sync with the Flow type on the JS side. putInt("errorCode", connectionResult.errorCode) putString("errorMessage", connectionResult.errorMessage) putBoolean("hasResolution", connectionResult.hasResolution()) putBoolean("isSuccess", connectionResult.isSuccess) }) } /** * Tell the JavaScript caller whether notifications are not blocked. */ // Ideally we could subscribe to changes in this value, but there // doesn't seem to be an API for that. The caller can poll, e.g., by // re-checking when the user has returned to the app, which they might // do after changing the notification settings. @ReactMethod fun areNotificationsEnabled(promise: Promise) { val notificationManagerCompat = NotificationManagerCompat .from(reactApplicationContext) // path_to_url#areNotificationsEnabled() promise.resolve(notificationManagerCompat.areNotificationsEnabled()) } companion object { var initialNotification: Bundle? = null fun emitToken(reactContext: ReactContext?, token: String) { if (reactContext == null) { // Perhaps this is possible if InstanceIDListenerService gets invoked? return } Log.i(TAG, "Got token; emitting event") reactContext.emitEvent("remoteNotificationsRegistered", token) } } } ```
/content/code_sandbox/android/app/src/main/java/com/zulipmobile/notifications/NotificationsModule.kt
kotlin
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
652
```kotlin package com.zulipmobile.notifications import com.facebook.react.ReactPackage import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.NativeModule import com.facebook.react.uimanager.ViewManager import java.util.ArrayList class NotificationsPackage : ReactPackage { override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> { return emptyList() } override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> { return listOf(NotificationsModule(reactContext)) } } ```
/content/code_sandbox/android/app/src/main/java/com/zulipmobile/notifications/NotificationsPackage.kt
kotlin
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
115
```kotlin package com.zulipmobile.notifications import java.net.MalformedURLException import java.net.URL import java.util.* /** * An identity belonging to this user in some Zulip org/realm. */ data class Identity( /// The server's `EXTERNAL_HOST` setting. This is a hostname, /// or a colon-separated hostname-plus-port. For documentation, /// see zulip-server:zproject/prod_settings_template.py . val serverHost: String, /// The realm's ID within the server. val realmId: Int, /// The realm's own URL/URI. This is a real, absolute URL which is /// the base for all URLs a client uses with this realm. It corresponds /// to `realm_uri` in the `server_settings` API response: /// path_to_url val realmUri: URL, /// This user's ID within the server. Useful mainly in the case where /// the user has multiple accounts in the same org. val userId: Int?, ) /** * Data about the Zulip user that sent a message. */ data class Sender( val id: Int, val email: String, val avatarURL: URL, val fullName: String, ) /** * Data identifying where a Zulip message was sent. */ sealed class Recipient { /** A 1:1 private message. Must have been sent to this user, so nothing more to say. */ object Pm : Recipient() /** * A group PM. * * pmUsers: the user IDs of all users in the conversation. */ data class GroupPm(val pmUsers: Set<Int>) : Recipient() { fun getPmUsersString() = pmUsers.sorted().joinToString(separator = ",") { it.toString() } } /** A stream message. */ // TODO(server-5.0): Require the stream ID (#3918). data class Stream(val streamId: Int?, val streamName: String, val topic: String) : Recipient() } /** * Parsed version of an FCM message, of any type. * * The word "message" can be confusing in this context: * * * FCM docs say "message" to refer to one of the blobs we receive over FCM, * aka a "data notification". One of these might correspond to zero, one, * or more actual notifications we show in the UI. * * * Around Zulip we of course say "message" all the time to mean the * central item in the app model. * * In our notification code we often say "FCM message" or "Zulip message" * to disambiguate between these two. */ sealed class FcmMessage { companion object { fun fromFcmData(data: Map<String, String>): FcmMessage = when (val eventType = data["event"]) { "message" -> MessageFcmMessage.fromFcmData(data) "remove" -> RemoveFcmMessage.fromFcmData(data) // The latter, longer name is deprecated: // path_to_url#narrow/stream/378-api-design/topic/.2323997.20Endpoint.20for.20test.20notification/near/1690777 "test", "test-by-device-token" -> TestFcmMessage.fromFcmData(data) null -> throw FcmMessageParseException("missing event type") else -> throw FcmMessageParseException("unknown event type: $eventType") } } } // This exists mainly to give a properly-typed wrapper around ArrayList#toArray. inline fun <reified T> buildArray(block: (ArrayList<T>) -> Unit): Array<T> { val result = arrayListOf<T>() block(result) return result.toArray(arrayOf<T>()) } /** * Parsed version of an FCM message of type `message`. * * This corresponds to a Zulip message for which the user wants to * see a notification. * * The word "message" can be confusing in this context. * See `FcmMessage` for discussion. */ data class MessageFcmMessage( val identity: Identity, val sender: Sender, val zulipMessageId: Int, val recipient: Recipient, val content: String, val timeMs: Long, ) : FcmMessage() { /** * All the data our React code needs on opening the notification. * * For the corresponding type definition on the JS side, see `Notification` * in `src/notification/types.js`. */ fun dataForOpen(): Array<Pair<String, Any?>> = // NOTE: Keep the JS-side type definition in sync with this code. buildArray { list -> list.add("realm_uri" to identity.realmUri.toString()) identity.userId?.let { list.add("user_id" to it) } when (recipient) { is Recipient.Stream -> { list.add("recipient_type" to "stream") recipient.streamId?.let { list.add("stream_id" to it) } list.add("stream_name" to recipient.streamName) list.add("topic" to recipient.topic) } is Recipient.GroupPm -> { list.add("recipient_type" to "private") list.add("pm_users" to recipient.getPmUsersString()) } is Recipient.Pm -> { list.add("recipient_type" to "private") list.add("sender_email" to sender.email) } } } companion object { fun fromFcmData(data: Map<String, String>): MessageFcmMessage { val recipientType = data.require("recipient_type") val recipient = when (recipientType) { "stream" -> Recipient.Stream( data["stream_id"]?.parseInt("stream_id"), data.require("stream"), data.require("topic") ) "private" -> data["pm_users"]?.parseCommaSeparatedInts("pm_users")?.let { Recipient.GroupPm(it.toSet()) } ?: Recipient.Pm else -> throw FcmMessageParseException("unexpected recipient_type: $recipientType") } val avatarURL = data.require("sender_avatar_url").parseUrl("sender_avatar_url") return MessageFcmMessage( identity = extractIdentity(data), sender = Sender( id = data.require("sender_id").parseInt("sender_id"), email = data.require("sender_email"), avatarURL = avatarURL, fullName = data.require("sender_full_name") ), zulipMessageId = data.require("zulip_message_id").parseInt("zulip_message_id"), recipient = recipient, content = data.require("content"), timeMs = data.require("time").parseLong("time") * 1000 ) } } } data class RemoveFcmMessage( val identity: Identity, val messageIds: Set<Int>, ) : FcmMessage() { companion object { fun fromFcmData(data: Map<String, String>): RemoveFcmMessage { val messageIds = HashSet<Int>() data["zulip_message_id"]?.parseInt("zulip_message_id")?.let { messageIds.add(it) } data["zulip_message_ids"]?.parseCommaSeparatedInts("zulip_message_ids")?.let { messageIds.addAll(it) } return RemoveFcmMessage( identity = extractIdentity(data), messageIds = messageIds ) } } } data class TestFcmMessage( val identity: Identity, // Hopefully to be added before 8.0 release; discussion: // path_to_url#narrow/stream/378-api-design/topic/.2323997.20Endpoint.20for.20test.20notification/near/1691552 val realmName: String?, ) : FcmMessage() { companion object { fun fromFcmData(data: Map<String, String>): TestFcmMessage { return TestFcmMessage( identity = extractIdentity(data), realmName = data["realm_name"], ) } } } private fun extractIdentity(data: Map<String, String>): Identity = Identity( serverHost = data.require("server"), realmId = data.require("realm_id").parseInt("realm_id"), // `realm_uri` was added in server version 1.9.0 realmUri = data.require("realm_uri").parseUrl("realm_uri"), // Server versions from 1.6.0 through 2.0.0 (and possibly earlier // and later) send the user's email address, as `user`. We *could* // use this as a substitute for `user_id` when that's missing... // but it'd be inherently buggy, and the bug it'd introduce seems // likely to affect more users than the bug it'd fix. So just ignore. // TODO(server-2.0): Delete this comment. // (data["user"] ignored) // `user_id` was added in server version 2.1.0 (released 2019-12-12; // commit 447a517e6, PR #12172.) // TODO(server-2.1): Require this. userId = data["user_id"]?.parseInt("user_id") ) private fun Map<String, String>.require(key: String): String = this[key] ?: throw FcmMessageParseException("missing expected field: $key") private fun String.parseInt(loc: String): Int = try { Integer.parseInt(this) } catch (e: NumberFormatException) { throw FcmMessageParseException("invalid int at $loc: $this") } private fun String.parseLong(loc: String): Long = try { toLong() } catch (e: NumberFormatException) { throw FcmMessageParseException("invalid long at $loc: $this") } private fun String.parseUrl(loc: String): URL = try { URL(this) } catch (e: MalformedURLException) { throw FcmMessageParseException("invalid URL at $loc: $this") } private fun String.parseCommaSeparatedInts(loc: String): Sequence<Int> = splitToSequence(",").map { it.parseInt(loc) } class FcmMessageParseException(errorMessage: String) : RuntimeException(errorMessage) ```
/content/code_sandbox/android/app/src/main/java/com/zulipmobile/notifications/FcmMessage.kt
kotlin
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
2,214
```kotlin @file:JvmName("NotificationUiManager") package com.zulipmobile.notifications import android.app.Notification import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.os.Bundle import android.util.Log import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.app.Person import androidx.core.graphics.drawable.IconCompat import androidx.core.os.bundleOf import com.zulipmobile.BuildConfig import com.zulipmobile.MainActivity import com.zulipmobile.R import com.zulipmobile.ZLog import java.io.IOException import java.io.InputStream import java.net.URL // This file maintains the notifications in the UI, using data from FCM messages. // // We map Zulip conversations to the Android notifications model like so: // * Each Zulip account/identity that has notifications gets a separate // notification group: // path_to_url // * Each Zulip conversation (a PM thread, or a stream + topic) goes to // one notification, a "messaging-style" notification: // path_to_url#message-style // * Each Zulip message that causes a notification (so by default, each PM // or @-mention; but the user's preferences live on the server, so as far // as we're concerned here, it's whatever the server sends us) becomes a // message in its conversation's notification. // // Further, the Android framework identifies each notification by both a // string "tag" and a numeric "ID", both of which we choose. We construct // the tags to be unique, and use an arbitrary constant for the IDs. // // The main entry point is `onReceived`, which is called when we receive // an FCM message. /** An Android logging tag for our notifications code. */ // (This doesn't particularly belong in this file, but it belongs somewhere // in the notifications package.) @JvmField val TAG = "ZulipNotif" /** * The constant numeric "ID" we use for all non-test notifications, * along with unique tags. * * Because we construct a unique string "tag" for each distinct notification, * and Android notifications are identified by the pair (tag, ID), it's simplest * to leave these numeric IDs all the same. */ private val NOTIFICATION_ID = 435 /** * The constant numeric "ID" we use for test notifications. */ private val TEST_NOTIFICATION_ID = 234 /** The authority in the `zulip:` URL for opening a notification. */ @JvmField val NOTIFICATION_URL_AUTHORITY = "notification" @JvmField val EXTRA_NOTIFICATION_DATA = "data" val Context.notificationManager: NotificationManager // This `getSystemService` method can return null if the class is not a supported // system service. But NotificationManager was added in API 1, long before the // oldest Android version we support, so just assert here that it's non-null. get() = this.getSystemService(NotificationManager::class.java)!! /** Write the given data to the device log, for debugging. */ fun logNotificationData(msg: String, data: Bundle) { data.keySet() // Has the side effect of making `data.toString` more informative. Log.v(TAG, "$msg: $data") } /** Handle an FCM message, updating the set of notifications in the UI. */ internal fun onReceived(context: Context, mapData: Map<String, String>) { // TODO refactor to not need this; reflects a juxtaposition of FCM with old GCM interfaces. val data = Bundle() for ((key, value) in mapData) { data.putString(key, value) } logNotificationData("notif received", data) val fcmMessage: FcmMessage try { fcmMessage = FcmMessage.fromFcmData(mapData) } catch (e: FcmMessageParseException) { ZLog.w(TAG, e) return } if (fcmMessage is MessageFcmMessage) { updateNotification(context, fcmMessage) } else if (fcmMessage is RemoveFcmMessage) { removeNotification(context, fcmMessage) } else if (fcmMessage is TestFcmMessage) { showTestNotification(context, fcmMessage) } } /** Handle a RemoveFcmMessage, removing notifications from the UI as appropriate. */ private fun removeNotification(context: Context, fcmMessage: RemoveFcmMessage) { // We have an FCM message telling us that some Zulip messages were read // and should no longer appear as notifications. We'll remove their // conversations' notifications, if appropriate, and then the whole // notification group if it's now empty. // There may be a lot of messages mentioned here, across a lot of // conversations. But they'll all be for one identity, so they'll // fall under one notification group. val groupKey = extractGroupKey(fcmMessage.identity) // Find any conversations we can cancel the notification for. // The API doesn't lend itself to removing individual messages as // they're read, so we wait until we're ready to remove the whole // conversation's notification. // See: path_to_url#pullrequestreview-725817909 var haveRemaining = false for (statusBarNotification in context.notificationManager.activeNotifications) { // The StatusBarNotification object describes an active notification in the UI. // Its relationship to the Notification and to our metadata is a bit confusing: // * The `.tag`, `.id`, and `.notification` are the same values as we passed to // `NotificationManager#notify`. So these are good to match on and inspect. // * The `.groupKey` and `.key` sound tempting. But while the `.groupKey` contains // the `.notification.group`, and the `.key` contains the `.id` and `.tag`, they // also have more stuff added on (and their structure doesn't seem to be documented.) // So don't try to match those. val notification = statusBarNotification.notification // Don't act on notifications that are for other Zulip accounts/identities. if (notification.group != groupKey) continue; // Don't act on the summary notification for the group. if (statusBarNotification.tag == groupKey) continue; val lastMessageId = notification.extras.getInt("lastZulipMessageId") if (fcmMessage.messageIds.contains(lastMessageId)) { // The latest Zulip message in this conversation was read. // That's our cue to cancel the notification for the conversation. NotificationManagerCompat.from(context) .cancel(statusBarNotification.tag, statusBarNotification.id) } else { // This notification is for another conversation that's still unread. // We won't cancel the summary notification. haveRemaining = true } } if (!haveRemaining) { // The notification group is now empty; it had no notifications we didn't // just cancel, except the summary notification. Cancel that one too. NotificationManagerCompat.from(context).cancel(groupKey, NOTIFICATION_ID) } } /** * Get the active notification with this tag, if any. * * In general Android allows multiple notifications with the same tag, * only requiring the (tag, id) pair to be unique. We use the fact that * our notifications have unique tags. */ private fun getActiveNotificationByTag(context: Context, notificationTag: String): Notification? { val activeStatusBarNotifications = context.notificationManager.activeNotifications for (statusBarNotification in activeStatusBarNotifications) { if (statusBarNotification.tag == notificationTag) { return statusBarNotification.notification } } return null } /** The unique tag we use for the group of notifications addressed to this Zulip account. */ private fun extractGroupKey(identity: Identity): String { // The realm URL can't contain a `|`, because `|` is not a URL code point: // path_to_url#url-code-points return "${identity.realmUri.toString()}|${identity.userId}" } /** * The unique tag we use for the notification for this Zulip message's conversation. * * This will match between different messages in the same conversation, but will * otherwise be distinct, even across other Zulip accounts. It also won't collide * with any `extractGroupKey` result. */ private fun extractConversationKey(fcmMessage: MessageFcmMessage): String { val groupKey = extractGroupKey(fcmMessage.identity) val conversation = when (fcmMessage.recipient) { // TODO(server-5.0): Rely on the stream ID (#3918). is Recipient.Stream -> when (fcmMessage.recipient.streamId) { // When using the stream name, we use `\u0000` as the delimiter because // it's the one character not allowed in Zulip stream names. // (See `check_stream_name` in zulip.git:zerver/lib/streams.py.) null -> "stream:${fcmMessage.recipient.streamName}\u0000${fcmMessage.recipient.topic}" // The conditional use of streamId means a slight glitch: when upgrading either the // client or server (whichever comes later) so that we start using stream IDs, any // existing notifications from before the upgrade won't get threaded together with new // ones. That seems OK; after all it's inherently transient. else -> "stream:${fcmMessage.recipient.streamId}:${fcmMessage.recipient.topic}" } is Recipient.GroupPm -> "groupPM:${fcmMessage.recipient.pmUsers.toString()}" is Recipient.Pm -> "private:${fcmMessage.sender.id}" } return "$groupKey|$conversation" } /** A unique tag for this Zulip message. */ private fun extractMessageKey(fcmMessage: MessageFcmMessage): String { val messageKey = "${extractGroupKey(fcmMessage.identity)}|${fcmMessage.zulipMessageId}" return messageKey } /** Fetch an image from the given URL. (We use this for sender avatars.) */ fun fetchBitmap(url: URL): Bitmap? { return try { val connection = url.openConnection() connection.useCaches = true (connection.content as? InputStream) ?.let { BitmapFactory.decodeStream(it) } } catch (e: IOException) { ZLog.e(TAG, e) null } } /** Handle a MessageFcmMessage, adding or extending notifications in the UI. */ private fun updateNotification( context: Context, fcmMessage: MessageFcmMessage, ) { // We have an FCM message telling us about a Zulip message. We'll add // a message (in the Android NotificationCompat.MessagingStyle.Message sense) // to the notification for that Zulip message's conversation. We create // the notification, and its notification group, if they don't already exist. val groupKey = extractGroupKey(fcmMessage.identity) val conversationKey = extractConversationKey(fcmMessage) val oldNotification = getActiveNotificationByTag(context, conversationKey) // The MessagingStyle contains details including the list of shown // messages in the conversation. val messagingStyle = if (oldNotification != null) { // If there's already a notification for this conversation, we get its // MessagingStyle so we can extend it. (This won't be null, because we // always use a MessagingStyle.) NotificationCompat.MessagingStyle.extractMessagingStyleFromNotification(oldNotification)!! } else { // If not, make a fresh one. val selfUser = Person.Builder().setName(context.getString(R.string.selfUser)).build() NotificationCompat.MessagingStyle(selfUser) .setGroupConversation(when (fcmMessage.recipient) { is Recipient.Stream, is Recipient.GroupPm -> true is Recipient.Pm -> false }) } // The title typically won't change between messages in a conversation, but we // update it anyway. This means a PM sender's display name gets updated if it's // changed, which is a rare edge case but probably good. The main effect is that // group-PM threads (pending #5116) get titled with the latest sender, rather than // the first. messagingStyle.setConversationTitle(when (fcmMessage.recipient) { is Recipient.Stream -> "#${fcmMessage.recipient.streamName} > ${fcmMessage.recipient.topic}" // TODO(#5116): use proper title for GroupPM, for which we will need // to have a way to get names of PM users here. is Recipient.GroupPm -> context.resources.getQuantityString( R.plurals.group_pm, fcmMessage.recipient.pmUsers.size - 2, fcmMessage.sender.fullName, fcmMessage.recipient.pmUsers.size - 2 ) is Recipient.Pm -> fcmMessage.sender.fullName }) val sender = Person.Builder().apply { setName(fcmMessage.sender.fullName) fetchBitmap(fcmMessage.sender.avatarURL)?.let { setIcon(IconCompat.createWithBitmap(it)) } }.build() messagingStyle.addMessage(fcmMessage.content, fcmMessage.timeMs, sender) val notification = NotificationCompat.Builder(context, CHANNEL_ID).apply { setGroup(groupKey) setZulipChannelLikeSettings(context) // TODO Perhaps set color and icon based on conversation? // E.g., stream-subscription color, and hash icon or lock icon. color = context.getColor(R.color.brandColor) setSmallIcon(if (BuildConfig.DEBUG) R.mipmap.ic_launcher else R.drawable.zulip_notification) setStyle(messagingStyle) setNumber(messagingStyle.messages.size) setExtras(bundleOf( // We use this for deciding when a RemoveFcmMessage should clear this notification. "lastZulipMessageId" to fcmMessage.zulipMessageId )) // Our own code doesn't look at the message details in this URL, // the "data URL" we put on the intent. Instead, we get data from // the "extra" we put on the intent. // // But the URL needs to be distinct each time; if it were the same // for two notifications, then we'd get the same PendingIntent twice. // That's because PendingIntents get reused when the Intents are // equal, and for that purpose extras don't count. See doc: // path_to_url // and in particular the discussion of Intent.filterEquals. val intentUrl = Uri.Builder().scheme("zulip") .authority(NOTIFICATION_URL_AUTHORITY).path(extractMessageKey(fcmMessage)).build() setContentIntent( PendingIntent.getActivity(context, 0, Intent(Intent.ACTION_VIEW, intentUrl, context, MainActivity::class.java) .setFlags( // See these sections in the Android docs: // path_to_url#TaskLaunchModes // path_to_url#FLAG_ACTIVITY_CLEAR_TOP // // * From the doc on `PendingIntent.getActivity` at // path_to_url#getActivity(android.content.Context,%20int,%20android.content.Intent,%20int) // > Note that the activity will be started outside of the context of an // > existing activity, so you must use the Intent.FLAG_ACTIVITY_NEW_TASK // > launch flag in the Intent. // // * The flag FLAG_ACTIVITY_CLEAR_TOP is mentioned as being what the // notification manager does; so use that. It has no effect as long // as we only have one activity; but if we add more, it will destroy // all the activities on top of the target one. Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP ) .putExtra(EXTRA_NOTIFICATION_DATA, bundleOf(*fcmMessage.dataForOpen())), PendingIntent.FLAG_IMMUTABLE)) setAutoCancel(true) }.build() val summaryNotification = NotificationCompat.Builder(context, CHANNEL_ID).apply { setGroup(groupKey) setGroupSummary(true) color = context.getColor(R.color.brandColor) setSmallIcon(if (BuildConfig.DEBUG) R.mipmap.ic_launcher else R.drawable.zulip_notification) // For the summary we use an "inbox-style" notification, as recommended here: // path_to_url#set_a_group_summary setStyle(NotificationCompat.InboxStyle() // TODO(#5115): Use the org's friendly name instead of its URL. .setSummaryText(fcmMessage.identity.realmUri.toString()) // TODO: Use addLine and setBigContentTitle to add some summary info when collapsed? // (See example in the linked doc.) ) // TODO Does this do something useful? There isn't a way to open these summary notifs. setAutoCancel(true) }.build() NotificationManagerCompat.from(context).apply { // This posts the notifications. If there is an existing notification // with the same tag and ID as one of these calls to `notify`, this will // replace it with the updated notification we've just constructed. notify(groupKey, NOTIFICATION_ID, summaryNotification) notify(conversationKey, NOTIFICATION_ID, notification) } } /** Handle a TestFcmMessage, showing the test notification. */ private fun showTestNotification(context: Context, fcmMessage: TestFcmMessage) { val groupKey = extractGroupKey(fcmMessage.identity) val notification = NotificationCompat.Builder(context, CHANNEL_ID).apply { setZulipChannelLikeSettings(context) // TODO(i18n) setContentTitle("Test notification") val realmUrl = fcmMessage.identity.realmUri.toString() val realmName = fcmMessage.realmName setContentText( if (realmName != null) "This is a test notification from ${realmName} (${realmUrl})." else "This is a test notification from ${realmUrl} ." ) color = context.getColor(R.color.brandColor) setSmallIcon(if (BuildConfig.DEBUG) R.mipmap.ic_launcher else R.drawable.zulip_notification) }.build() NotificationManagerCompat.from(context).apply { notify(groupKey, TEST_NOTIFICATION_ID, notification) } } ```
/content/code_sandbox/android/app/src/main/java/com/zulipmobile/notifications/NotificationUiManager.kt
kotlin
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
4,014
```xml <manifest xmlns:android="path_to_url" xmlns:tools="path_to_url"> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> <application android:usesCleartextTraffic="true" tools:remove="android:networkSecurityConfig" tools:ignore="GoogleAppIndexingWarning" tools:targetApi="28"> <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" android:exported="false" /> </application> </manifest> ```
/content/code_sandbox/android/app/src/debug/AndroidManifest.xml
xml
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
115
```xml <resources> <string name="app_name">Zulip (debug)</string> </resources> ```
/content/code_sandbox/android/app/src/debug/res/values/strings.xml
xml
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
23
```java /** * * <p>This source code is licensed under the MIT license found in the LICENSE file in the root * directory of this source tree. */ package com.zulipmobile; import android.content.Context; import com.facebook.flipper.android.AndroidFlipperClient; import com.facebook.flipper.android.utils.FlipperUtils; import com.facebook.flipper.core.FlipperClient; import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin; import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin; import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin; import com.facebook.flipper.plugins.inspector.DescriptorMapping; import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin; import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor; import com.facebook.flipper.plugins.network.NetworkFlipperPlugin; import com.facebook.flipper.plugins.react.ReactFlipperPlugin; import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin; import com.facebook.react.ReactInstanceEventListener; import com.facebook.react.ReactInstanceManager; import com.facebook.react.bridge.ReactContext; import com.facebook.react.modules.network.NetworkingModule; import okhttp3.OkHttpClient; public class ReactNativeFlipper { public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) { if (FlipperUtils.shouldEnableFlipper(context)) { final FlipperClient client = AndroidFlipperClient.getInstance(context); client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults())); client.addPlugin(new ReactFlipperPlugin()); client.addPlugin(new DatabasesFlipperPlugin(context)); client.addPlugin(new SharedPreferencesFlipperPlugin(context)); client.addPlugin(CrashReporterPlugin.getInstance()); NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin(); NetworkingModule.setCustomClientBuilder( new NetworkingModule.CustomClientBuilder() { @Override public void apply(OkHttpClient.Builder builder) { builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin)); } }); client.addPlugin(networkFlipperPlugin); client.start(); // Fresco Plugin needs to ensure that ImagePipelineFactory is initialized // Hence we run if after all native modules have been initialized ReactContext reactContext = reactInstanceManager.getCurrentReactContext(); if (reactContext == null) { reactInstanceManager.addReactInstanceEventListener( new ReactInstanceEventListener() { @Override public void onReactContextInitialized(ReactContext reactContext) { reactInstanceManager.removeReactInstanceEventListener(this); reactContext.runOnNativeModulesQueueThread( new Runnable() { @Override public void run() { client.addPlugin(new FrescoFlipperPlugin()); } }); } }); } else { client.addPlugin(new FrescoFlipperPlugin()); } } } } ```
/content/code_sandbox/android/app/src/debug/java/com/zulipmobile/ReactNativeFlipper.java
java
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
593
```unknown Format: path_to_url Upstream-Name: Zulip Upstream-Contact: Zulip Development Discussion <zulip-devel@googlegroups.com> Source: path_to_url Comment: Unless otherwise noted, the Zulip software is distributed under the Apache parties under other free and open source licenses. Those works are redistributed under the license terms under which the works were received. . While Kandra Labs has sought to provide complete and accurate licensing information for each FOSS package, neither Kandra Labs nor the Zulip contributors represent or warrant that the licensing information provided herein is correct or error-free. Recipients of the Zulip software should investigate the identified FOSS packages to confirm the accuracy of the licensing information provided. Recipients are also encouraged to notify Kandra Labs of any inaccurate information or errors found in these notices. Files: * Files: src/redux-persist-migrate/index.js and contributors Comment: Upstream is licensed as MIT. Files: src/third/react-native/* Comment: Changes we make here are designed to be sent upstream. So even when making changes, we keep our versions on the MIT license, the same as upstream. Files: src/third/redux-persist/* Comment: Upstream is licensed as MIT. Forked from v4.10.2, at path_to_url . Files: static/img/app-store-badge.* Non-free. Provided by Apple for use in connection with applications available for download on the App Store. Requirements include: . path_to_url path_to_url . Apple is a trademark, and App Store is a service mark, of Apple Inc. Files: static/img/google-play-badge.png Non-free. Provided by Google to promote content available on Google Play. Downloaded from, and see guidelines at: . path_to_url . Google Play and the Google Play logo are trademarks of Google LLC. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: . The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. . THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ```
/content/code_sandbox/docs/THIRDPARTY
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
605
```kotlin @file:JvmName("NotificationChannelManager") package com.zulipmobile.notifications import android.app.NotificationChannel import android.app.NotificationManager import android.content.ContentResolver import android.content.ContentUris import android.content.ContentValues import android.content.Context import android.media.AudioAttributes import android.net.Uri import android.os.Build import android.os.Environment import android.provider.MediaStore import androidx.core.app.NotificationCompat import com.zulipmobile.R import com.zulipmobile.ZLog import java.io.IOException import android.provider.MediaStore.Audio.Media as AudioStore /** The channel ID we use for our one notification channel, which we use for all notifications. */ // Previous values: "default", "messages-1", (alpha-only: "messages-2") val CHANNEL_ID = "messages-3" /** The vibration pattern we set. */ // We try to set a vibration pattern that, with the phone in one's pocket, // is both distinctly present and distinctly different from the default. // Discussion: path_to_url#narrow/stream/48-mobile/topic/notification.20vibration.20pattern/near/1284530 val kVibrationPattern = longArrayOf(0, 125, 100, 450); /** The Android resource URL for the given resource. */ // Based on: path_to_url fun Context.resourceUrl(resourceId: Int): Uri = with(resources) { Uri.Builder() .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) .authority(getResourcePackageName(resourceId)) .appendPath(getResourceTypeName(resourceId)) .appendPath(getResourceEntryName(resourceId)) .build() } private enum class NotificationSound constructor( val resourceId: Int, val fileDisplayName: String, ) { chime2(R.raw.chime2, "Zulip - Low Chime.m4a"), chime3(R.raw.chime3, "Zulip - Chime.m4a"), chime4(R.raw.chime4, "Zulip - High Chime.m4a"), } private val kDefaultNotificationSound = NotificationSound.chime3 /** * Prepare our notification sounds; return a URL for our default sound. * * Where possible, this copies each of our notification sounds into shared storage * so that the user can choose between them in the system notification settings. * * Returns a URL for our default notification sound: either in shared storage * if we successfully copied it there, or else as our internal resource file. */ private fun ensureInitNotificationSounds(context: Context): Uri { // The URL we'll return. // Typically this gets set in one of the loops below, but in case of error // or on old Android versions, we fall back to the internal resource. var defaultSoundUrl: Uri = context.resourceUrl(kDefaultNotificationSound.resourceId) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { // Before Android 10 Q, we don't attempt to put the sounds in shared media storage. // Just use the resource file directly. return defaultSoundUrl } val resolver = context.contentResolver val collection = AudioStore.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY) // The directory we store our notification sounds into, // expressed as a relative path suitable for: // path_to_url#RELATIVE_PATH:kotlin.String val soundsDirectoryPath = "${Environment.DIRECTORY_NOTIFICATIONS}/Zulip/" // First, look to see what notification sounds we've already stored, // and check against our list of sounds we have. val soundsTodo = NotificationSound.values().map { it.fileDisplayName to it }.toMap().toMutableMap() // Query and cursor-loop based on: path_to_url#query-collection val cursor = resolver.query( collection, kotlin.arrayOf(AudioStore._ID, AudioStore.DISPLAY_NAME, AudioStore.OWNER_PACKAGE_NAME), "${AudioStore.RELATIVE_PATH}=?", arrayOf(soundsDirectoryPath), "${AudioStore._ID} ASC" ) ?: run { ZLog.w(TAG, "ensureInitNotificationSounds: query failed") return defaultSoundUrl } val idColumn = cursor.getColumnIndexOrThrow(AudioStore._ID) val nameColumn = cursor.getColumnIndexOrThrow(AudioStore.DISPLAY_NAME) val ownerColumn = cursor.getColumnIndexOrThrow(AudioStore.OWNER_PACKAGE_NAME) while (cursor.moveToNext()) { val name = cursor.getString(nameColumn) // If the file is one we put there, and has the name we give to our // default sound, then use it as the default sound. val ownerPackageName = cursor.getString(ownerColumn) if (name == kDefaultNotificationSound.fileDisplayName && ownerPackageName == context.packageName ) { val id = cursor.getLong(idColumn) defaultSoundUrl = ContentUris.withAppendedId(collection, id) } // If it has the name of any of our sounds, then don't try to add // that sound. This applies even if we didn't put it there: the // name is taken, so if we tried adding it anyway it'd get some // other name (like "Zulip - Chime (1).m4a", with " (1)" added). // Which means the *next* launch would try to add it again ad infinitum. // We could avoid this given some other way to uniquely identify the // file, but haven't found an obvious one. // // This does mean it's possible the file isn't the one we would have // put there... but it probably is, just from a debug vs. release build // of the app (because those have different package names). And anyway, // this is a file we're supplying for the user in case they want it, not // something where the app depends on it having specific content. soundsTodo.remove(name) } // If that leaves any sounds we haven't yet put into shared storage // (e.g., because this is the first run after install, or after an // upgrade that added a sound), then store those. for (sound in soundsTodo.values) { class ResolverFailedException(msg: String) : RuntimeException(msg) try { // Based on: path_to_url#add-item val url = resolver.insert(collection, ContentValues().apply { put(AudioStore.DISPLAY_NAME, sound.fileDisplayName) put(AudioStore.RELATIVE_PATH, soundsDirectoryPath) put(AudioStore.IS_NOTIFICATION, 1) put(AudioStore.IS_PENDING, 1) }) ?: throw ResolverFailedException("resolver.insert failed") (resolver.openOutputStream(url, "wt") ?: throw ResolverFailedException("resolver.open failed")) .use { outputStream -> context.resources.openRawResource(sound.resourceId) .use { it.copyTo(outputStream) } } resolver.update( url, ContentValues().apply { put(AudioStore.IS_PENDING, 0) }, null, null) if (sound == kDefaultNotificationSound) { defaultSoundUrl = url } } catch (e: ResolverFailedException) { ZLog.w(TAG, e) } catch (e: IllegalStateException) { // If we already had "Zulip - Chime.m4a" through "Zulip - Chime (31).m4a", it gives up // with this exception rather than make a 33rd version "Zulip - Chime (32).m4a". ZLog.w(TAG, e) } catch (e: IOException) { ZLog.w(TAG, e) } } return defaultSoundUrl } /** * Apply our choices for settings that in modern Android go on the channel. * * On newer Android versions where notification channels exist, this has * no effect. * */ // TODO(Build.VERSION.SDK_INT>=26): Delete this, as it's a no-op. fun NotificationCompat.Builder.setZulipChannelLikeSettings(context: Context) { setVibrate(kVibrationPattern) // This whole function only does anything before SDK 26 / O, in which case // we're definitely before Q and don't have shared storage. setSound(context.resourceUrl(kDefaultNotificationSound.resourceId)) } fun createNotificationChannel(context: Context) { if (Build.VERSION.SDK_INT < 26) { // Notification channels don't exist before SDK 26, aka Android 8 Oreo. return } val manager = context.notificationManager // See if our current-version channel already exists; delete any obsolete previous channels. var found = false for (channel in manager.notificationChannels) { if (channel.id == CHANNEL_ID) { found = true } else { manager.deleteNotificationChannel(channel.id) } } if (found) { // The channel already exists; nothing to do. return } // The channel doesn't exist. Create it. val notificationSoundUrl = ensureInitNotificationSounds(context) // TODO: It'd be nice to use NotificationChannelCompat here: we get a nice builder class, // plus should then be able to drop the Build.VERSION condition. // Needs upgrading androidx.core to 1.5.0: // path_to_url#1.5.0-alpha02 // NOTE when changing anything here: the changes will not take effect // for existing installs of the app! That's because we'll have already // created the channel with the old settings, and they're in the user's // hands from there. (In fact we don't even reach this point; but if we did, // the `createNotificationChannel` would have no effect.) Our choices are: // // * Leave the old settings in place for existing installs, so the // changes only apply to new installs. // // * Change `CHANNEL_ID`, so that we abandon the old channel and use // a new one. Existing installs will get the new settings. // // This also means that if the user has changed any of the notification // settings for the channel -- like "override Do Not Disturb", or "use // a different sound", or "don't pop on screen" -- their changes get // reset. So this has to be done sparingly. manager.createNotificationChannel(NotificationChannel( CHANNEL_ID, context.getString(R.string.notification_channel_name), NotificationManager.IMPORTANCE_HIGH ).apply { // TODO: Is this the default value anyway for IMPORTANCE_HIGH? // If so, perhaps just take it out. enableLights(true) vibrationPattern = kVibrationPattern setSound(notificationSoundUrl, AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION).build()) }) } ```
/content/code_sandbox/android/app/src/main/java/com/zulipmobile/notifications/NotificationChannelManager.kt
kotlin
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
2,322
```javascript import resolve from "@rollup/plugin-node-resolve"; import commonjs from "@rollup/plugin-commonjs"; import babel from "rollup-plugin-babel"; import { terser } from "rollup-plugin-terser"; import sass from "rollup-plugin-sass"; import serve from "rollup-plugin-serve"; import livereload from "rollup-plugin-livereload"; import pkg from "./package.json"; import { writeFileSync } from "fs"; const production = !process.env.ROLLUP_WATCH; export default [ // browser-friendly UMD build { input: "src/index.js", output: [ { name: "Tribute", file: pkg.main, format: "umd" }, { name: "Tribute", file: pkg.browser, format: "umd", sourcemap: true, plugins: [terser()] }, { name: "Tribute", file: "example/tribute.js", format: "umd" } ], plugins: [ sass({ output(styles) { writeFileSync("dist/tribute.css", styles); writeFileSync("example/tribute.css", styles); } }), resolve(), commonjs(), babel({ exclude: ["node_modules/**"] }), !production && serve({ openPage: "/", contentBase: ["example"] }), !production && livereload({ watch: ["dist", "example/*.html"] }) ] }, // CommonJS (for Node) and ES module (for bundlers) build. // (We could have three entries in the configuration array // instead of two, but it's quicker to generate multiple // builds from a single configuration where possible, using // an array for the `output` option, where we can specify // `file` and `format` for each target) { input: "src/index.js", output: [{ file: pkg.module, format: "es" }], plugins: [sass({ output: "tribute.css" })] } ]; ```
/content/code_sandbox/rollup.config.js
javascript
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
450
```yaml exclude: - README.md ```
/content/code_sandbox/_config.yml
yaml
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
8
```css .tribute-container { position: absolute; top: 0; left: 0; height: auto; overflow: auto; display: block; z-index: 999999; } .tribute-container ul { margin: 0; margin-top: 2px; padding: 0; list-style: none; background: #efefef; } .tribute-container li { padding: 5px 5px; cursor: pointer; } .tribute-container li.highlight { background: #ddd; } .tribute-container li span { font-weight: bold; } .tribute-container li.no-match { cursor: default; } .tribute-container .menu-highlighted { font-weight: bold; } ```
/content/code_sandbox/tribute.css
css
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
161
```xml // Type definitions for TributeJS v5.1.3 // Project: path_to_url // Definitions by: Jordan Humphreys <path_to_url export type TributeItem<T extends {}> = { index: number; original: T; score: number; string: string; }; export type TributeSearchOpts = { pre: string; post: string; skip: boolean; }; export type TributeCollection<T extends {}> = { // symbol that starts the lookup trigger?: string; // element to target for @mentions iframe?: any; // class added in the flyout menu for active item selectClass?: string; // class added in the flyout menu for active item containerClass?: string; itemClass?: string; // function called on select that returns the content to insert selectTemplate?: (item: TributeItem<T>|undefined) => string; // template for displaying item in menu menuItemTemplate?: (item: TributeItem<T>) => string; // template for when no match is found (optional), // If no template is provided, menu is hidden. noMatchTemplate?: () => string; // specify an alternative parent container for the menu menuContainer?: Element; // column to search against in the object (accepts function or string) lookup?: string | ((item: T, mentionText: string) => string); // column that contains the content to insert by default fillAttr?: string; // array of objects to match values: Array<T> | ((text: string, cb: (result: Array<T>) => void) => void); // When your values function is async, an optional loading template to show loadingItemTemplate?: string; // specify whether a space is required before the trigger character requireLeadingSpace?: boolean; // specify whether a space is allowed in the middle of mentions allowSpaces?: boolean; // optionally specify a custom suffix for the replace text // (defaults to empty space if undefined) replaceTextSuffix?: string; //specify whether the menu should be positioned positionMenu?: boolean; //specify whether to put Tribute in autocomplete mode autocompleteMode?: boolean; // specify a regex to define after which characters the autocomplete option should open autocompleteSeparator?: RegExp; // Customize the elements used to wrap matched strings within the results list searchOpts?: TributeSearchOpts; // Limits the number of items in the menu menuItemLimit?: number; // require X number of characters to be entered before menu shows menuShowMinLength?: number; // specify if the current match should be selected when the spacebar is hit spaceSelectsMatch?: boolean; }; export type TributeOptions<T> = | TributeCollection<T> | { // pass an array of config objects collection: Array<TributeCollection<{ [key: string]: any }>>; }; type TributeElement = Element | NodeList | HTMLCollection | Array<Element>; export default class Tribute<T extends {}> { constructor(options: TributeOptions<T>); isActive: boolean; append(index: number, values: Array<T>, replace?: boolean): void; appendCurrent(values: Array<T>, replace?: boolean): void; attach(to: TributeElement): void; detach(to: TributeElement): void; showMenuForCollection(input: Element, collectionIndex?: number): void; } ```
/content/code_sandbox/tributejs.d.ts
xml
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
741
```javascript // Karma configuration // path_to_url // Generated on 2016-02-05 using // generator-karma 1.0.1 process.env.CHROME_BIN = require("puppeteer").executablePath(); module.exports = function(config) { "use strict"; config.set({ // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // base path, that will be used to resolve files and exclude basePath: "", // testing framework to use (jasmine/mocha/qunit/...) // as well as any additional frameworks (requirejs/chai/sinon/...) frameworks: ["jasmine", "browserify"], // list of files / patterns to load in the browser files: [ "../dist/tribute.js", "../dist/tribute.css", "../test/spec/*.js", "../test/libs/*.js" ], // add preprocessor to the files that should be processed via browserify preprocessors: { "../test/spec/*.js": ["browserify"], "../dist/tribute.js": ["coverage"] }, reporters: ["kjhtml", "spec", "coverage"], specReporter: { maxLogLines: 5, // limit number of lines logged per test suppressErrorSummary: false, // do not print error summary suppressFailed: false, // do not print information about failed tests suppressPassed: false, // do not print information about passed tests suppressSkipped: true, // do not print information about skipped tests showSpecTiming: false // print the time elapsed for each spec }, browserify: { debug: true, transform: [["babelify"]] }, // list of files / patterns to exclude exclude: [], // web server port port: 8080, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: ["Chrome"], // Which plugins to enable plugins: [ "karma-chrome-launcher", "karma-jasmine", "karma-browserify", "karma-jasmine-html-reporter", "karma-spec-reporter", "karma-coverage" ], coverageReporter: { type: "html", dir: "coverage/" }, // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false, colors: true, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: config.LOG_INFO // Uncomment the following lines if you are using grunt's server to run the tests // proxies: { // '/': 'path_to_url // }, // URL root prevent conflicts with the site root // urlRoot: '_karma_' }); }; ```
/content/code_sandbox/test/karma.conf.js
javascript
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
666
```javascript export const attachTribute = function(collectionObject, inputElementId) { let tribute = new Tribute(collectionObject); tribute.attach(document.getElementById(inputElementId)); return tribute; } export const detachTribute = function(tribute, inputElementId) { tribute.detach(document.getElementById(inputElementId)); } ```
/content/code_sandbox/test/spec/utils/tribute-helpers.js
javascript
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
66
```javascript export const createDomElement = function(element = 'text') { let elementToCreate = 'input'; if (element === 'contenteditable') { elementToCreate = 'div'; } let wrapperDiv = document.createElement('div'); wrapperDiv.id = 'tribute-wrapper-div'; let input = document.createElement(elementToCreate); input.id = `tribute-${element}`; wrapperDiv.appendChild(input); document.body.appendChild(wrapperDiv); return input; } export const clearDom = function() { let wrapperDiv = document.querySelector('#tribute-wrapper-div'); if (wrapperDiv) { wrapperDiv.parentNode.removeChild(wrapperDiv); } let tributeContainer = document.querySelector('.tribute-container'); if (tributeContainer) { tributeContainer.parentNode.removeChild(tributeContainer); } } export const fillIn = function(input, text) { input.focus(); $(input).sendkeys(text); input.dispatchEvent(new KeyboardEvent('keydown')); input.dispatchEvent(new KeyboardEvent('keyup')); } export const simulateMouseClick = function(targetNode) { function triggerMouseEvent(targetNode, eventType) { let clickEvent = document.createEvent('MouseEvents'); clickEvent.initEvent(eventType, true, true); targetNode.dispatchEvent(clickEvent); } ["mouseover", "mousedown", "mouseup", "click"].forEach(function (eventType) { triggerMouseEvent(targetNode, eventType); }); } ```
/content/code_sandbox/test/spec/utils/dom-helpers.js
javascript
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
293
```javascript // insert characters in a textarea or text input field // special characters are enclosed in {}; use {{} for the { character itself // documentation: path_to_url // Version: 4 // MIT license: // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. (function($){ $.fn.sendkeys = function (x){ x = x.replace(/([^{])\n/g, '$1{enter}'); // turn line feeds into explicit break insertions, but not if escaped return this.each( function(){ bililiteRange(this).bounds('selection').sendkeys(x).select(); this.focus(); }); }; // sendkeys // add a default handler for keydowns so that we can send keystrokes, even though code-generated events // are untrusted (path_to_url#trusted-events) // documentation of special event handlers is at path_to_url $.event.special.keydown = $.event.special.keydown || {}; $.event.special.keydown._default = function (evt){ if (evt.isTrusted) return false; if (evt.ctrlKey || evt.altKey || evt.metaKey) return false; // only deal with printable characters. This may be a false assumption if (evt.key == null) return false; // nothing to print. Use the keymap plugin to set this var target = evt.target; if (target.isContentEditable || target.nodeName == 'INPUT' || target.nodeName == 'TEXTAREA') { // only insert into editable elements var key = evt.key; if (key.length > 1 && key.charAt(0) != '{') key = '{'+key+'}'; // sendkeys notation $(target).sendkeys(key); return true; } return false; } })(jQuery) ```
/content/code_sandbox/test/libs/jquery.sendkeys.js
javascript
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
580
```javascript "use strict"; import bigList from "./utils/bigList.json"; import { clearDom, createDomElement, fillIn, simulateMouseClick } from "./utils/dom-helpers"; import { attachTribute, detachTribute } from "./utils/tribute-helpers"; describe("Tribute instantiation", function() { it("should not error in the base case from the README", () => { const options = [ { key: "Phil Heartman", value: "pheartman" }, { key: "Gordon Ramsey", value: "gramsey" } ]; const tribute = new Tribute({ values: options }); expect(tribute.collection[0].values).toEqual(options); }); }); describe("Tribute @mentions cases", function() { afterEach(function() { clearDom(); }); ["text", "contenteditable"].forEach(elementType => { ["@", "$("].forEach(trigger => { it(`when values key is predefined array. For : ${elementType} / ${trigger}`, () => { let input = createDomElement(elementType); let collectionObject = { trigger: trigger, selectTemplate: function(item) { if (typeof item === "undefined") return null; if (this.range.isContentEditable(this.current.element)) { return ( '<span contenteditable="false"><a href="path_to_url" target="_blank" title="' + item.original.email + '">' + item.original.value + "</a></span>" ); } return trigger + item.original.value; }, values: [ { key: "Jordan Humphreys", value: "Jordan Humphreys", email: "getstarted@zurb.com" }, { key: "Sir Walter Riley", value: "Sir Walter Riley", email: "getstarted+riley@zurb.com" } ] }; let tribute = attachTribute(collectionObject, input.id); fillIn(input, " " + trigger); let popupList = document.querySelectorAll( ".tribute-container > ul > li" ); expect(popupList.length).toBe(2); simulateMouseClick(popupList[0]); // click on Jordan Humphreys if (elementType === "text") { expect(input.value).toBe(" " + trigger + "Jordan Humphreys "); } else if (elementType === "contenteditable") { expect(input.innerHTML).toBe( ' <span contenteditable="false"><a href="path_to_url" target="_blank" title="getstarted@zurb.com">Jordan Humphreys</a></span>&nbsp;' ); } fillIn(input, " " + trigger + "sir"); popupList = document.querySelectorAll(".tribute-container > ul > li"); expect(popupList.length).toBe(1); detachTribute(tribute, input.id); }); it(`when values array is large and menuItemLimit is set. For : ${elementType} / ${trigger}`, () => { let input = createDomElement(elementType); let collectionObject = { trigger: trigger, menuItemLimit: 25, selectTemplate: function(item) { if (typeof item === "undefined") return null; if (this.range.isContentEditable(this.current.element)) { return ( '<span contenteditable="false"><a href="path_to_url" target="_blank" title="' + item.original.email + '">' + item.original.value + "</a></span>" ); } return trigger + item.original.value; }, values: bigList }; let tribute = attachTribute(collectionObject, input.id); fillIn(input, " " + trigger); let popupList = document.querySelectorAll( ".tribute-container > ul > li" ); expect(popupList.length).toBe(25); fillIn(input, " " + trigger + "an"); popupList = document.querySelectorAll(".tribute-container > ul > li"); expect(popupList.length).toBe(25); detachTribute(tribute, input.id); }); it("should add itemClass to list items when set it config", () => { let input = createDomElement(elementType); let collectionObject = { trigger: trigger, itemClass: "mention-list-item", selectClass: "mention-selected", values: [ { key: "Jordan Humphreys", value: "Jordan Humphreys", email: "getstarted@zurb.com" }, { key: "Sir Walter Riley", value: "Sir Walter Riley", email: "getstarted+riley@zurb.com" } ] }; let tribute = attachTribute(collectionObject, input.id); fillIn(input, " " + trigger); let popupList = document.querySelectorAll( ".tribute-container > ul > li" ); expect(popupList.length).toBe(2); expect(popupList[0].className).toBe( "mention-list-item mention-selected" ); expect(popupList[1].className).toBe("mention-list-item"); detachTribute(tribute, input.id); }); }); }); }); describe("Tribute autocomplete mode cases", function() { afterEach(function() { clearDom(); }); ['text', 'contenteditable'].forEach(elementType => { it(`when values key with autocompleteSeparator option. For : ${elementType}`, () => { let input = createDomElement(elementType); let collectionObject = { selectTemplate: function (item) { return item.original.value; }, autocompleteMode: true, autocompleteSeparator: new RegExp(/\-|\+/), values: [ { key: 'Jordan Humphreys', value: 'Jordan Humphreys', email: 'getstarted@zurb.com' }, { key: 'Sir Walter Riley', value: 'Sir Walter Riley', email: 'getstarted+riley@zurb.com' } ], } let tribute = attachTribute(collectionObject, input.id); fillIn(input, '+J'); let popupList = document.querySelectorAll('.tribute-container > ul > li'); expect(popupList.length).toBe(1); simulateMouseClick(popupList[0]); // click on Jordan Humphreys if (elementType === 'text') { expect(input.value).toBe('+Jordan Humphreys '); } else if (elementType === 'contenteditable') { expect(input.innerText).toBe('+Jordan Humphreys'); } fillIn(input, ' Si'); popupList = document.querySelectorAll('.tribute-container > ul > li'); expect(popupList.length).toBe(1); detachTribute(tribute, input.id); }); }); ["text", "contenteditable"].forEach(elementType => { it(`when values key is predefined array. For : ${elementType}`, () => { let input = createDomElement(elementType); let collectionObject = { selectTemplate: function(item) { return item.original.value; }, autocompleteMode: true, values: [ { key: "Jordan Humphreys", value: "Jordan Humphreys", email: "getstarted@zurb.com" }, { key: "Sir Walter Riley", value: "Sir Walter Riley", email: "getstarted+riley@zurb.com" } ] }; let tribute = attachTribute(collectionObject, input.id); fillIn(input, " J"); let popupList = document.querySelectorAll(".tribute-container > ul > li"); expect(popupList.length).toBe(1); simulateMouseClick(popupList[0]); // click on Jordan Humphreys if (elementType === "text") { expect(input.value).toBe(" Jordan Humphreys "); } else if (elementType === "contenteditable") { expect(input.innerText).toBe("Jordan Humphreys"); } fillIn(input, " Si"); popupList = document.querySelectorAll(".tribute-container > ul > li"); expect(popupList.length).toBe(1); detachTribute(tribute, input.id); }); }); ["text", "contenteditable"].forEach(elementType => { it(`when values key is a function. For : ${elementType}`, () => { let input = createDomElement(elementType); let collectionObject = { autocompleteMode: true, selectClass: "sample-highlight", noMatchTemplate: function() { this.hideMenu(); }, selectTemplate: function(item) { if (typeof item === "undefined") return null; if (this.range.isContentEditable(this.current.element)) { return `&nbsp;<a contenteditable=false>${item.original.value}</a>`; } return item.original.value; }, values: function(text, cb) { searchFn(text, users => cb(users)); } }; function searchFn(text, cb) { if (text === "a") { cb([ { key: "Alabama", value: "Alabama" }, { key: "Alaska", value: "Alaska" }, { key: "Arizona", value: "Arizona" }, { key: "Arkansas", value: "Arkansas" } ]); } else if (text === "c") { cb([ { key: "California", value: "California" }, { key: "Colorado", value: "Colorado" } ]); } else { cb([]); } } let tribute = attachTribute(collectionObject, input.id); fillIn(input, " a"); let popupList = document.querySelectorAll(".tribute-container > ul > li"); expect(popupList.length).toBe(4); simulateMouseClick(popupList[0]); if (elementType === "text") { expect(input.value).toBe(" Alabama "); } else if (elementType === "contenteditable") { expect(input.innerText).toBe("Alabama"); } fillIn(input, " c"); popupList = document.querySelectorAll(".tribute-container > ul > li"); expect(popupList.length).toBe(2); simulateMouseClick(popupList[1]); if (elementType === "text") { expect(input.value).toBe(" Alabama Colorado "); } else if (elementType === "contenteditable") { expect(input.innerText).toBe("Alabama Colorado"); } fillIn(input, " none"); let popupListWrapper = document.querySelector(".tribute-container"); expect(popupListWrapper.style.display).toBe("none"); detachTribute(tribute, input.id); }); }); ["contenteditable"].forEach(elementType => { it(`should work with newlines`, () => { let input = createDomElement(elementType); let collectionObject = { selectTemplate: function(item) { return item.original.value; }, autocompleteMode: true, values: [ { key: "Jordan Humphreys", value: "Jordan Humphreys", email: "getstarted@zurb.com" }, { key: "Sir Walter Riley", value: "Sir Walter Riley", email: "getstarted+riley@zurb.com" } ] }; let tribute = attachTribute(collectionObject, input.id); fillIn(input, "random{newline}J"); let popupList = document.querySelectorAll(".tribute-container > ul > li"); expect(popupList.length).toBe(1); detachTribute(tribute, input.id); }); }); }); describe("When Tribute searchOpts.skip", function() { afterEach(function() { clearDom(); }); it("should skip local filtering and display all items", () => { let input = createDomElement(); let collectionObject = { searchOpts: { skip: true }, noMatchTemplate: function() { this.hideMenu(); }, selectTemplate: function(item) { return item.original.value; }, values: [ { key: "Tributao e Divisas", value: "Tributao e Divisas" }, { key: "Tributao e Impostos", value: "Tributao e Impostos" }, { key: "Tributao e Taxas", value: "Tributao e Taxas" } ] }; let tribute = attachTribute(collectionObject, input.id); fillIn(input, "@random-text"); let popupList = document.querySelectorAll(".tribute-container > ul > li"); expect(popupList.length).toBe(3); detachTribute(tribute, input.id); }); }); describe("Tribute NoMatchTemplate cases", function() { afterEach(function() { clearDom(); }); it("should display template when specified as text", () => { let input = createDomElement(); let collectionObject = { noMatchTemplate: "testcase", selectTemplate: function(item) { return item.original.value; }, values: [ { key: "Jordan Humphreys", value: "Jordan Humphreys", email: "getstarted@zurb.com" }, { key: "Sir Walter Riley", value: "Sir Walter Riley", email: "getstarted+riley@zurb.com" } ] }; let tribute = attachTribute(collectionObject, input.id); fillIn(input, "@random-text"); let containerDiv = document.getElementsByClassName("tribute-container")[0]; expect(containerDiv.innerText).toBe("testcase"); detachTribute(tribute, input.id); }); it("should display template when specified as function", () => { let input = createDomElement(); let collectionObject = { noMatchTemplate: function() { return "testcase"; }, selectTemplate: function(item) { return item.original.value; }, values: [ { key: "Jordan Humphreys", value: "Jordan Humphreys", email: "getstarted@zurb.com" }, { key: "Sir Walter Riley", value: "Sir Walter Riley", email: "getstarted+riley@zurb.com" } ] }; let tribute = attachTribute(collectionObject, input.id); fillIn(input, "@random-text"); let containerDiv = document.getElementsByClassName("tribute-container")[0]; expect(containerDiv.innerText).toBe("testcase"); detachTribute(tribute, input.id); }); it("should display no menu container when text is empty", () => { let input = createDomElement(); let collectionObject = { noMatchTemplate: "", selectTemplate: function(item) { return item.original.value; }, values: [ { key: "Jordan Humphreys", value: "Jordan Humphreys", email: "getstarted@zurb.com" }, { key: "Sir Walter Riley", value: "Sir Walter Riley", email: "getstarted+riley@zurb.com" } ] }; let tribute = attachTribute(collectionObject, input.id); fillIn(input, "@random-text"); let popupListWrapper = document.querySelector(".tribute-container"); expect(popupListWrapper.style.display).toBe("none"); detachTribute(tribute, input.id); }); it("should display no menu when function returns empty string", () => { let input = createDomElement(); let collectionObject = { noMatchTemplate: function() { return ""; }, selectTemplate: function(item) { return item.original.value; }, values: [ { key: "Jordan Humphreys", value: "Jordan Humphreys", email: "getstarted@zurb.com" }, { key: "Sir Walter Riley", value: "Sir Walter Riley", email: "getstarted+riley@zurb.com" } ] }; let tribute = attachTribute(collectionObject, input.id); fillIn(input, "@random-text"); let popupListWrapper = document.querySelector(".tribute-container"); expect(popupListWrapper.style.display).toBe("none"); detachTribute(tribute, input.id); }); }); describe("Tribute menu positioning", function() { afterEach(function() { clearDom(); }); function checkPosition(collectionObject, input) { let bottomContent = document.createElement("div"); bottomContent.style = "background: blue; height: 400px; width: 10px;"; document.body.appendChild(bottomContent); let inputRect = input.getBoundingClientRect(); let inputX = inputRect.x; let inputY = inputRect.y; let tribute = attachTribute(collectionObject, input.id); fillIn(input, "@"); let popupListWrapper = document.querySelector(".tribute-container"); let menuRect = popupListWrapper.getBoundingClientRect(); let menuX = menuRect.x; let menuY = menuRect.y; detachTribute(tribute, input.id); bottomContent.remove(); clearDom(); return { x: menuX, y: menuY }; } it("should display a container menu in the same position when menuContainer is specified on an input as when the menuContainer is the body", () => { let input = createDomElement(); let container = input.parentElement; container.style = "position: relative;"; let { x: specifiedX, y: specifiedY } = checkPosition( { menuContainer: container, values: [ { key: "Jordan Humphreys", value: "Jordan Humphreys", email: "getstarted@zurb.com" }, { key: "Sir Walter Riley", value: "Sir Walter Riley", email: "getstarted+riley@zurb.com" } ] }, input ); input = createDomElement(); let { x: unspecifiedX, y: unspecifiedY } = checkPosition( { values: [ { key: "Jordan Humphreys", value: "Jordan Humphreys", email: "getstarted@zurb.com" }, { key: "Sir Walter Riley", value: "Sir Walter Riley", email: "getstarted+riley@zurb.com" } ] }, input ); expect(unspecifiedY).toEqual(specifiedY); expect(unspecifiedX).toEqual(specifiedX); }); it("should display a container menu in the same position when menuContainer is specified on an contenteditable as when the menuContainer is the body", () => { let input = createDomElement("contenteditable"); let container = input.parentElement; container.style = "position: relative;"; let { x: specifiedX, y: specifiedY } = checkPosition( { menuContainer: container, values: [ { key: "Jordan Humphreys", value: "Jordan Humphreys", email: "getstarted@zurb.com" }, { key: "Sir Walter Riley", value: "Sir Walter Riley", email: "getstarted+riley@zurb.com" } ] }, input ); input = createDomElement("contenteditable"); let { x: unspecifiedX, y: unspecifiedY } = checkPosition( { values: [ { key: "Jordan Humphreys", value: "Jordan Humphreys", email: "getstarted@zurb.com" }, { key: "Sir Walter Riley", value: "Sir Walter Riley", email: "getstarted+riley@zurb.com" } ] }, input ); expect(unspecifiedY).toEqual(specifiedY); expect(unspecifiedX).toEqual(specifiedX); }); }); describe("Multi-char tests", function() { afterEach(function() { clearDom(); }); it("should display no menu when only first char of multi-char trigger is used", () => { let input = createDomElement(); let collectionObject = { trigger: "$(", selectTemplate: function(item) { return item.original.value; }, values: [ { key: "Jordan Humphreys", value: "Jordan Humphreys", email: "getstarted@zurb.com" }, { key: "Sir Walter Riley", value: "Sir Walter Riley", email: "getstarted+riley@zurb.com" } ] }; let tribute = attachTribute(collectionObject, input.id); fillIn(input, " $"); let popupListWrapper = document.querySelector(".tribute-container"); expect(popupListWrapper).toBe(null); detachTribute(tribute, input.id); }); describe("Tribute events", function() { afterEach(function() { clearDom(); }); it("should raise tribute-active-true", () => { let input = createDomElement(); var eventSpy = jasmine.createSpy(); input.addEventListener("tribute-active-true", eventSpy); let collectionObject = { noMatchTemplate: function() { this.hideMenu(); }, selectTemplate: function(item) { return item.original.value; }, values: [ { key: "Tributao e Divisas", value: "Tributao e Divisas" }, { key: "Tributao e Impostos", value: "Tributao e Impostos" }, { key: "Tributao e Taxas", value: "Tributao e Taxas" } ] }; let tribute = attachTribute(collectionObject, input.id); fillIn(input, "@random-text"); let popupList = document.querySelectorAll(".tribute-container > ul > li"); expect(eventSpy).toHaveBeenCalled(); detachTribute(tribute, input.id); }); }); describe("Tribute events", function() { afterEach(function() { clearDom(); }); it("should raise tribute-active-false", () => { let input = createDomElement(); var eventSpy = jasmine.createSpy(); input.addEventListener("tribute-active-false", eventSpy); let collectionObject = { noMatchTemplate: function() { return ""; }, selectTemplate: function(item) { return item.original.value; }, values: [ { key: "Tributao e Divisas", value: "Tributao e Divisas" }, { key: "Tributao e Impostos", value: "Tributao e Impostos" }, { key: "Tributao e Taxas", value: "Tributao e Taxas" } ] }; let tribute = attachTribute(collectionObject, input.id); fillIn(input, "@random-text"); let popupList = document.querySelectorAll(".tribute-container > ul > li"); expect(eventSpy).toHaveBeenCalled(); detachTribute(tribute, input.id); }); }); }); describe("Tribute loadingItemTemplate", function() { afterEach(function() { clearDom(); }); ["text", "contenteditable"].forEach(elementType => { it(`Shows loading item template. For : ${elementType}`, (done) => { let input = createDomElement(elementType); let collectionObject = { loadingItemTemplate: '<div class="loading">Loading</div>', values: function(_, cb) { setTimeout(() => cb([ { key: "Jordan Humphreys", value: "Jordan Humphreys", email: "getstarted@zurb.com" }, { key: "Sir Walter Riley", value: "Sir Walter Riley", email: "getstarted+riley@zurb.com" } ]), 500) }, }; let tribute = attachTribute(collectionObject, input.id); fillIn(input, "@J"); const loadingItemTemplate = document.querySelectorAll(".loading"); expect(loadingItemTemplate.length).toBe(1); setTimeout(() => { const popupList = document.querySelectorAll(".tribute-container > ul > li"); expect(popupList.length).toBe(1); detachTribute(tribute, input.id); done(); }, 1000); }); }); }); ```
/content/code_sandbox/test/spec/test.js
javascript
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
5,267
```javascript // Cross-broswer implementation of text ranges and selections // documentation: path_to_url // Version: 2.6 // MIT license: // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. (function(){ // a bit of weirdness with IE11: using 'focus' is flaky, even if I'm not bubbling, as far as I can tell. var focusEvent = 'onfocusin' in document.createElement('input') ? 'focusin' : 'focus'; // IE11 normalize is buggy (path_to_url var n = document.createElement('div'); n.appendChild(document.createTextNode('x-')); n.appendChild(document.createTextNode('x')); n.normalize(); var canNormalize = n.firstChild.length == 3; bililiteRange = function(el, debug){ var ret; if (debug){ ret = new NothingRange(); // Easier to force it to use the no-selection type than to try to find an old browser }else if (window.getSelection && el.setSelectionRange){ // Standards. Element is an input or textarea // note that some input elements do not allow selections try{ el.selectionStart; // even getting the selection in such an element will throw ret = new InputRange(); }catch(e){ ret = new NothingRange(); } }else if (window.getSelection){ // Standards, with any other kind of element ret = new W3CRange(); }else if (document.selection){ // Internet Explorer ret = new IERange(); }else{ // doesn't support selection ret = new NothingRange(); } ret._el = el; // determine parent document, as implemented by John McLear <john@mclear.co.uk> ret._doc = el.ownerDocument; ret._win = 'defaultView' in ret._doc ? ret._doc.defaultView : ret._doc.parentWindow; ret._textProp = textProp(el); ret._bounds = [0, ret.length()]; // There's no way to detect whether a focus event happened as a result of a click (which should change the selection) // or as a result of a keyboard event (a tab in) or a script action (el.focus()). So we track it globally, which is a hack, and is likely to fail // in edge cases (right-clicks, drag-n-drop), and is vulnerable to a lower-down handler preventing bubbling. // I just don't know a better way. // I'll hack my event-listening code below, rather than create an entire new bilililiteRange, potentially before the DOM has loaded if (!('bililiteRangeMouseDown' in ret._doc)){ var _doc = {_el: ret._doc}; ret._doc.bililiteRangeMouseDown = false; bililiteRange.fn.listen.call(_doc, 'mousedown', function() { ret._doc.bililiteRangeMouseDown = true; }); bililiteRange.fn.listen.call(_doc, 'mouseup', function() { ret._doc.bililiteRangeMouseDown = false; }); } // note that bililiteRangeSelection is an array, which means that copying it only copies the address, which points to the original. // make sure that we never let it (always do return [bililiteRangeSelection[0], bililiteRangeSelection[1]]), which means never returning // this._bounds directly if (!('bililiteRangeSelection' in el)){ // start tracking the selection function trackSelection(evt){ if (evt && evt.which == 9){ // do tabs my way, by restoring the selection // there's a flash of the browser's selection, but I don't see a way of avoiding that ret._nativeSelect(ret._nativeRange(el.bililiteRangeSelection)); }else{ el.bililiteRangeSelection = ret._nativeSelection(); } } trackSelection(); // only IE does this right and allows us to grab the selection before blurring if ('onbeforedeactivate' in el){ ret.listen('beforedeactivate', trackSelection); }else{ // with standards-based browsers, have to listen for every user interaction ret.listen('mouseup', trackSelection).listen('keyup', trackSelection); } ret.listen(focusEvent, function(){ // restore the correct selection when the element comes into focus (mouse clicks change the position of the selection) // Note that Firefox will not fire the focus event until the window/tab is active even if el.focus() is called // path_to_url if (!ret._doc.bililiteRangeMouseDown){ ret._nativeSelect(ret._nativeRange(el.bililiteRangeSelection)); } }); } if (!('oninput' in el)){ // give IE8 a chance. Note that this still fails in IE11, which has has oninput on contenteditable elements but does not // dispatch input events. See path_to_url // TODO: revisit this when I have IE11 running on my development machine // TODO: FIXED var inputhack = function() {ret.dispatch({type: 'input', bubbles: true}) }; if(typeof window.setTimeout == 'object'){ /* IE 8 sees `setTimeout` as an `object` and not a `function` */ ret.listen('keyup', inputhack); ret.listen('cut', inputhack); ret.listen('paste', inputhack); ret.listen('drop', inputhack); el.oninput = 'patched'; } }else{ /* IE9/IE11 supports the `textinput` event (even on contenteditable elements) See path_to_url */ /* Detect IE 9/11, See: path_to_url */ if((!(window.FileReader) || !!window.MSInputMethodContext) && !!document.documentMode){ ret.listen('textinput', function(){ ret.dispatch({type: 'input', bubbles: true}); }); } } return ret; } function textProp(el){ // returns the property that contains the text of the element // note that for <body> elements the text attribute represents the obsolete text color, not the textContent. // we document that these routines do not work for <body> elements so that should not be relevant // Bugfix for path_to_url // Adding typeof check of string for el.value in case for li elements if (typeof el.value === 'string') return 'value'; if (typeof el.text != 'undefined') return 'text'; if (typeof el.textContent != 'undefined') return 'textContent'; return 'innerText'; } // base class function Range(){} Range.prototype = { length: function() { return this._el[this._textProp].replace(/\r/g, '').length; // need to correct for IE's CrLf weirdness }, bounds: function(s){ if (bililiteRange.bounds[s]){ this._bounds = bililiteRange.bounds[s].apply(this); }else if (s){ this._bounds = s; // don't do error checking now; things may change at a moment's notice }else{ var b = [ Math.max(0, Math.min (this.length(), this._bounds[0])), Math.max(0, Math.min (this.length(), this._bounds[1])) ]; b[1] = Math.max(b[0], b[1]); return b; // need to constrain it to fit } return this; // allow for chaining }, select: function(){ var b = this._el.bililiteRangeSelection = this.bounds(); if (this._el === this._doc.activeElement){ // only actually select if this element is active! this._nativeSelect(this._nativeRange(b)); } this.dispatch({type: 'select', bubbles: true}); return this; // allow for chaining }, text: function(text, select){ if (arguments.length){ var bounds = this.bounds(), el = this._el; // signal the input per DOM 3 input events, path_to_url#h4_events-inputevents // we add another field, bounds, which are the bounds of the original text before being changed. this.dispatch({type: 'beforeinput', bubbles: true, data: text, bounds: bounds}); this._nativeSetText(text, this._nativeRange(bounds)); if (select == 'start'){ this.bounds ([bounds[0], bounds[0]]); }else if (select == 'end'){ this.bounds ([bounds[0]+text.length, bounds[0]+text.length]); }else if (select == 'all'){ this.bounds ([bounds[0], bounds[0]+text.length]); } this.dispatch({type: 'input', bubbles: true, data: text, bounds: bounds}); return this; // allow for chaining }else{ return this._nativeGetText(this._nativeRange(this.bounds())).replace(/\r/g, ''); // need to correct for IE's CrLf weirdness } }, insertEOL: function (){ this._nativeEOL(); this._bounds = [this._bounds[0]+1, this._bounds[0]+1]; // move past the EOL marker return this; }, sendkeys: function (text){ var self = this; this.data().sendkeysOriginalText = this.text(); this.data().sendkeysBounds = undefined; function simplechar (rng, c){ if (/^{[^}]*}$/.test(c)) c = c.slice(1,-1); // deal with unknown {key}s for (var i =0; i < c.length; ++i){ var x = c.charCodeAt(i); rng.dispatch({type: 'keypress', bubbles: true, keyCode: x, which: x, charCode: x}); } rng.text(c, 'end'); } text.replace(/{[^}]*}|[^{]+|{/g, function(part){ (bililiteRange.sendkeys[part] || simplechar)(self, part, simplechar); }); this.bounds(this.data().sendkeysBounds); this.dispatch({type: 'sendkeys', which: text}); return this; }, top: function(){ return this._nativeTop(this._nativeRange(this.bounds())); }, scrollIntoView: function(scroller){ var top = this.top(); // scroll into position if necessary if (this._el.scrollTop > top || this._el.scrollTop+this._el.clientHeight < top){ if (scroller){ scroller.call(this._el, top); }else{ this._el.scrollTop = top; } } return this; }, wrap: function (n){ this._nativeWrap(n, this._nativeRange(this.bounds())); return this; }, selection: function(text){ if (arguments.length){ return this.bounds('selection').text(text, 'end').select(); }else{ return this.bounds('selection').text(); } }, clone: function(){ return bililiteRange(this._el).bounds(this.bounds()); }, all: function(text){ if (arguments.length){ this.dispatch ({type: 'beforeinput', bubbles: true, data: text}); this._el[this._textProp] = text; this.dispatch ({type: 'input', bubbles: true, data: text}); return this; }else{ return this._el[this._textProp].replace(/\r/g, ''); // need to correct for IE's CrLf weirdness } }, element: function() { return this._el }, // includes a quickie polyfill for CustomEvent for IE that isn't perfect but works for me // IE10 allows custom events but not "new CustomEvent"; have to do it the old-fashioned way dispatch: function(opts){ opts = opts || {}; var event = document.createEvent ? document.createEvent('CustomEvent') : this._doc.createEventObject(); event.initCustomEvent && event.initCustomEvent(opts.type, !!opts.bubbles, !!opts.cancelable, opts.detail); for (var key in opts) event[key] = opts[key]; // dispatch event asynchronously (in the sense of on the next turn of the event loop; still should be fired in order of dispatch var el = this._el; setTimeout(function(){ try { el.dispatchEvent ? el.dispatchEvent(event) : el.fireEvent("on" + opts.type, document.createEventObject()); }catch(e){ // IE8 will not let me fire custom events at all. Call them directly var listeners = el['listen'+opts.type]; if (listeners) for (var i = 0; i < listeners.length; ++i){ listeners[i].call(el, event); } } }, 0); return this; }, listen: function (type, func){ var el = this._el; if (el.addEventListener){ el.addEventListener(type, func); }else{ el.attachEvent("on" + type, func); // IE8 can't even handle custom events created with createEventObject (though it permits attachEvent), so we have to make our own var listeners = el['listen'+type] = el['listen'+type] || []; listeners.push(func); } return this; }, dontlisten: function (type, func){ var el = this._el; if (el.removeEventListener){ el.removeEventListener(type, func); }else try{ el.detachEvent("on" + type, func); }catch(e){ var listeners = el['listen'+type]; if (listeners) for (var i = 0; i < listeners.length; ++i){ if (listeners[i] === func) listeners[i] = function(){}; // replace with a noop } } return this; } }; // allow extensions ala jQuery bililiteRange.fn = Range.prototype; // to allow monkey patching bililiteRange.extend = function(fns){ for (fn in fns) Range.prototype[fn] = fns[fn]; }; //bounds functions bililiteRange.bounds = { all: function() { return [0, this.length()] }, start: function () { return [0,0] }, end: function () { return [this.length(), this.length()] }, selection: function(){ if (this._el === this._doc.activeElement){ this.bounds ('all'); // first select the whole thing for constraining return this._nativeSelection(); }else{ return this._el.bililiteRangeSelection; } } }; // sendkeys functions bililiteRange.sendkeys = { '{enter}': function (rng){ rng.dispatch({type: 'keypress', bubbles: true, keyCode: '\n', which: '\n', charCode: '\n'}); rng.insertEOL(); }, '{tab}': function (rng, c, simplechar){ simplechar(rng, '\t'); // useful for inserting what would be whitespace }, '{newline}': function (rng, c, simplechar){ simplechar(rng, '\n'); // useful for inserting what would be whitespace (and if I don't want to use insertEOL, which does some fancy things) }, '{backspace}': function (rng){ var b = rng.bounds(); if (b[0] == b[1]) rng.bounds([b[0]-1, b[0]]); // no characters selected; it's just an insertion point. Remove the previous character rng.text('', 'end'); // delete the characters and update the selection }, '{del}': function (rng){ var b = rng.bounds(); if (b[0] == b[1]) rng.bounds([b[0], b[0]+1]); // no characters selected; it's just an insertion point. Remove the next character rng.text('', 'end'); // delete the characters and update the selection }, '{rightarrow}': function (rng){ var b = rng.bounds(); if (b[0] == b[1]) ++b[1]; // no characters selected; it's just an insertion point. Move to the right rng.bounds([b[1], b[1]]); }, '{leftarrow}': function (rng){ var b = rng.bounds(); if (b[0] == b[1]) --b[0]; // no characters selected; it's just an insertion point. Move to the left rng.bounds([b[0], b[0]]); }, '{selectall}' : function (rng){ rng.bounds('all'); }, '{selection}': function (rng){ // insert the characters without the sendkeys processing var s = rng.data().sendkeysOriginalText; for (var i =0; i < s.length; ++i){ var x = s.charCodeAt(i); rng.dispatch({type: 'keypress', bubbles: true, keyCode: x, which: x, charCode: x}); } rng.text(s, 'end'); }, '{mark}' : function (rng){ rng.data().sendkeysBounds = rng.bounds(); } }; // Synonyms from the proposed DOM standard (path_to_url bililiteRange.sendkeys['{Enter}'] = bililiteRange.sendkeys['{enter}']; bililiteRange.sendkeys['{Backspace}'] = bililiteRange.sendkeys['{backspace}']; bililiteRange.sendkeys['{Delete}'] = bililiteRange.sendkeys['{del}']; bililiteRange.sendkeys['{ArrowRight}'] = bililiteRange.sendkeys['{rightarrow}']; bililiteRange.sendkeys['{ArrowLeft}'] = bililiteRange.sendkeys['{leftarrow}']; function IERange(){} IERange.prototype = new Range(); IERange.prototype._nativeRange = function (bounds){ var rng; if (this._el.tagName == 'INPUT'){ // IE 8 is very inconsistent; textareas have createTextRange but it doesn't work rng = this._el.createTextRange(); }else{ rng = this._doc.body.createTextRange (); rng.moveToElementText(this._el); } if (bounds){ if (bounds[1] < 0) bounds[1] = 0; // IE tends to run elements out of bounds if (bounds[0] > this.length()) bounds[0] = this.length(); if (bounds[1] < rng.text.replace(/\r/g, '').length){ // correct for IE's CrLf weirdness // block-display elements have an invisible, uncounted end of element marker, so we move an extra one and use the current length of the range rng.moveEnd ('character', -1); rng.moveEnd ('character', bounds[1]-rng.text.replace(/\r/g, '').length); } if (bounds[0] > 0) rng.moveStart('character', bounds[0]); } return rng; }; IERange.prototype._nativeSelect = function (rng){ rng.select(); }; IERange.prototype._nativeSelection = function (){ // returns [start, end] for the selection constrained to be in element var rng = this._nativeRange(); // range of the element to constrain to var len = this.length(); var sel = this._doc.selection.createRange(); try{ return [ iestart(sel, rng), ieend (sel, rng) ]; }catch (e){ // TODO: determine if this is still necessary, since we only call _nativeSelection if _el is active // IE gets upset sometimes about comparing text to input elements, but the selections cannot overlap, so make a best guess return (sel.parentElement().sourceIndex < this._el.sourceIndex) ? [0,0] : [len, len]; } }; IERange.prototype._nativeGetText = function (rng){ return rng.text; }; IERange.prototype._nativeSetText = function (text, rng){ rng.text = text; }; IERange.prototype._nativeEOL = function(){ if ('value' in this._el){ this.text('\n'); // for input and textarea, insert it straight }else{ this._nativeRange(this.bounds()).pasteHTML('\n<br/>'); } }; IERange.prototype._nativeTop = function(rng){ var startrng = this._nativeRange([0,0]); return rng.boundingTop - startrng.boundingTop; } IERange.prototype._nativeWrap = function(n, rng) { // hacky to use string manipulation but I don't see another way to do it. var div = document.createElement('div'); div.appendChild(n); // insert the existing range HTML after the first tag var html = div.innerHTML.replace('><', '>'+rng.htmlText+'<'); rng.pasteHTML(html); }; // IE internals function iestart(rng, constraint){ // returns the position (in character) of the start of rng within constraint. If it's not in constraint, returns 0 if it's before, length if it's after var len = constraint.text.replace(/\r/g, '').length; // correct for IE's CrLf weirdness if (rng.compareEndPoints ('StartToStart', constraint) <= 0) return 0; // at or before the beginning if (rng.compareEndPoints ('StartToEnd', constraint) >= 0) return len; for (var i = 0; rng.compareEndPoints ('StartToStart', constraint) > 0; ++i, rng.moveStart('character', -1)); return i; } function ieend (rng, constraint){ // returns the position (in character) of the end of rng within constraint. If it's not in constraint, returns 0 if it's before, length if it's after var len = constraint.text.replace(/\r/g, '').length; // correct for IE's CrLf weirdness if (rng.compareEndPoints ('EndToEnd', constraint) >= 0) return len; // at or after the end if (rng.compareEndPoints ('EndToStart', constraint) <= 0) return 0; for (var i = 0; rng.compareEndPoints ('EndToStart', constraint) > 0; ++i, rng.moveEnd('character', -1)); return i; } // an input element in a standards document. "Native Range" is just the bounds array function InputRange(){} InputRange.prototype = new Range(); InputRange.prototype._nativeRange = function(bounds) { return bounds || [0, this.length()]; }; InputRange.prototype._nativeSelect = function (rng){ this._el.setSelectionRange(rng[0], rng[1]); }; InputRange.prototype._nativeSelection = function(){ return [this._el.selectionStart, this._el.selectionEnd]; }; InputRange.prototype._nativeGetText = function(rng){ return this._el.value.substring(rng[0], rng[1]); }; InputRange.prototype._nativeSetText = function(text, rng){ var val = this._el.value; this._el.value = val.substring(0, rng[0]) + text + val.substring(rng[1]); }; InputRange.prototype._nativeEOL = function(){ this.text('\n'); }; InputRange.prototype._nativeTop = function(rng){ // I can't remember where I found this clever hack to find the location of text in a text area var clone = this._el.cloneNode(true); clone.style.visibility = 'hidden'; clone.style.position = 'absolute'; this._el.parentNode.insertBefore(clone, this._el); clone.style.height = '1px'; clone.value = this._el.value.slice(0, rng[0]); var top = clone.scrollHeight; // this gives the bottom of the text, so we have to subtract the height of a single line clone.value = 'X'; top -= clone.scrollHeight; clone.parentNode.removeChild(clone); return top; } InputRange.prototype._nativeWrap = function() {throw new Error("Cannot wrap in a text element")}; function W3CRange(){} W3CRange.prototype = new Range(); W3CRange.prototype._nativeRange = function (bounds){ var rng = this._doc.createRange(); rng.selectNodeContents(this._el); if (bounds){ w3cmoveBoundary (rng, bounds[0], true, this._el); rng.collapse (true); w3cmoveBoundary (rng, bounds[1]-bounds[0], false, this._el); } return rng; }; W3CRange.prototype._nativeSelect = function (rng){ this._win.getSelection().removeAllRanges(); this._win.getSelection().addRange (rng); }; W3CRange.prototype._nativeSelection = function (){ // returns [start, end] for the selection constrained to be in element var rng = this._nativeRange(); // range of the element to constrain to if (this._win.getSelection().rangeCount == 0) return [this.length(), this.length()]; // append to the end var sel = this._win.getSelection().getRangeAt(0); return [ w3cstart(sel, rng), w3cend (sel, rng) ]; } W3CRange.prototype._nativeGetText = function (rng){ return String.prototype.slice.apply(this._el.textContent, this.bounds()); // return rng.toString(); // this fails in IE11 since it insists on inserting \r's before \n's in Ranges. node.textContent works as expected }; W3CRange.prototype._nativeSetText = function (text, rng){ rng.deleteContents(); rng.insertNode (this._doc.createTextNode(text)); if (canNormalize) this._el.normalize(); // merge the text with the surrounding text }; W3CRange.prototype._nativeEOL = function(){ var rng = this._nativeRange(this.bounds()); rng.deleteContents(); var br = this._doc.createElement('br'); br.setAttribute ('_moz_dirty', ''); // for Firefox rng.insertNode (br); rng.insertNode (this._doc.createTextNode('\n')); rng.collapse (false); }; W3CRange.prototype._nativeTop = function(rng){ if (this.length == 0) return 0; // no text, no scrolling if (rng.toString() == ''){ var textnode = this._doc.createTextNode('X'); rng.insertNode (textnode); } var startrng = this._nativeRange([0,1]); var top = rng.getBoundingClientRect().top - startrng.getBoundingClientRect().top; if (textnode) textnode.parentNode.removeChild(textnode); return top; } W3CRange.prototype._nativeWrap = function(n, rng) { rng.surroundContents(n); }; // W3C internals function nextnode (node, root){ // in-order traversal // we've already visited node, so get kids then siblings if (node.firstChild) return node.firstChild; if (node.nextSibling) return node.nextSibling; if (node===root) return null; while (node.parentNode){ // get uncles node = node.parentNode; if (node == root) return null; if (node.nextSibling) return node.nextSibling; } return null; } function w3cmoveBoundary (rng, n, bStart, el){ // move the boundary (bStart == true ? start : end) n characters forward, up to the end of element el. Forward only! // if the start is moved after the end, then an exception is raised if (n <= 0) return; var node = rng[bStart ? 'startContainer' : 'endContainer']; if (node.nodeType == 3){ // we may be starting somewhere into the text n += rng[bStart ? 'startOffset' : 'endOffset']; } while (node){ if (node.nodeType == 3){ var length = node.nodeValue.length; if (n <= length){ rng[bStart ? 'setStart' : 'setEnd'](node, n); // special case: if we end next to a <br>, include that node. if (n == length){ // skip past zero-length text nodes for (var next = nextnode (node, el); next && next.nodeType==3 && next.nodeValue.length == 0; next = nextnode(next, el)){ rng[bStart ? 'setStartAfter' : 'setEndAfter'](next); } if (next && next.nodeType == 1 && next.nodeName == "BR") rng[bStart ? 'setStartAfter' : 'setEndAfter'](next); } return; }else{ rng[bStart ? 'setStartAfter' : 'setEndAfter'](node); // skip past this one n -= length; // and eat these characters } } node = nextnode (node, el); } } var START_TO_START = 0; // from the w3c definitions var START_TO_END = 1; var END_TO_END = 2; var END_TO_START = 3; // from the Mozilla documentation, for range.compareBoundaryPoints(how, sourceRange) // -1, 0, or 1, indicating whether the corresponding boundary-point of range is respectively before, equal to, or after the corresponding boundary-point of sourceRange. // * Range.END_TO_END compares the end boundary-point of sourceRange to the end boundary-point of range. // * Range.END_TO_START compares the end boundary-point of sourceRange to the start boundary-point of range. // * Range.START_TO_END compares the start boundary-point of sourceRange to the end boundary-point of range. // * Range.START_TO_START compares the start boundary-point of sourceRange to the start boundary-point of range. function w3cstart(rng, constraint){ if (rng.compareBoundaryPoints (START_TO_START, constraint) <= 0) return 0; // at or before the beginning if (rng.compareBoundaryPoints (END_TO_START, constraint) >= 0) return constraint.toString().length; rng = rng.cloneRange(); // don't change the original rng.setEnd (constraint.endContainer, constraint.endOffset); // they now end at the same place return constraint.toString().replace(/\r/g, '').length - rng.toString().replace(/\r/g, '').length; } function w3cend (rng, constraint){ if (rng.compareBoundaryPoints (END_TO_END, constraint) >= 0) return constraint.toString().length; // at or after the end if (rng.compareBoundaryPoints (START_TO_END, constraint) <= 0) return 0; rng = rng.cloneRange(); // don't change the original rng.setStart (constraint.startContainer, constraint.startOffset); // they now start at the same place return rng.toString().replace(/\r/g, '').length; } function NothingRange(){} NothingRange.prototype = new Range(); NothingRange.prototype._nativeRange = function(bounds) { return bounds || [0,this.length()]; }; NothingRange.prototype._nativeSelect = function (rng){ // do nothing }; NothingRange.prototype._nativeSelection = function(){ return [0,0]; }; NothingRange.prototype._nativeGetText = function (rng){ return this._el[this._textProp].substring(rng[0], rng[1]); }; NothingRange.prototype._nativeSetText = function (text, rng){ var val = this._el[this._textProp]; this._el[this._textProp] = val.substring(0, rng[0]) + text + val.substring(rng[1]); }; NothingRange.prototype._nativeEOL = function(){ this.text('\n'); }; NothingRange.prototype._nativeTop = function(){ return 0; }; NothingRange.prototype._nativeWrap = function() {throw new Error("Wrapping not implemented")}; // data for elements, similar to jQuery data, but allows for monitoring with custom events var data = []; // to avoid attaching javascript objects to DOM elements, to avoid memory leaks bililiteRange.fn.data = function(){ var index = this.element().bililiteRangeData; if (index == undefined){ index = this.element().bililiteRangeData = data.length; data[index] = new Data(this); } return data[index]; } try { Object.defineProperty({},'foo',{}); // IE8 will throw an error var Data = function(rng) { // we use JSON.stringify to display the data values. To make some of those non-enumerable, we have to use properties Object.defineProperty(this, 'values', { value: {} }); Object.defineProperty(this, 'sourceRange', { value: rng }); Object.defineProperty(this, 'toJSON', { value: function(){ var ret = {}; for (var i in Data.prototype) if (i in this.values) ret[i] = this.values[i]; return ret; } }); // to display all the properties (not just those changed), use JSON.stringify(state.all) Object.defineProperty(this, 'all', { get: function(){ var ret = {}; for (var i in Data.prototype) ret[i] = this[i]; return ret; } }); } Data.prototype = {}; Object.defineProperty(Data.prototype, 'values', { value: {} }); Object.defineProperty(Data.prototype, 'monitored', { value: {} }); bililiteRange.data = function (name, newdesc){ newdesc = newdesc || {}; var desc = Object.getOwnPropertyDescriptor(Data.prototype, name) || {}; if ('enumerable' in newdesc) desc.enumerable = !!newdesc.enumerable; if (!('enumerable' in desc)) desc.enumerable = true; // default if ('value' in newdesc) Data.prototype.values[name] = newdesc.value; if ('monitored' in newdesc) Data.prototype.monitored[name] = newdesc.monitored; desc.configurable = true; desc.get = function (){ if (name in this.values) return this.values[name]; return Data.prototype.values[name]; }; desc.set = function (value){ this.values[name] = value; if (Data.prototype.monitored[name]) this.sourceRange.dispatch({ type: 'bililiteRangeData', bubbles: true, detail: {name: name, value: value} }); } Object.defineProperty(Data.prototype, name, desc); } }catch(err){ // if we can't set object property properties, just use old-fashioned properties Data = function(rng){ this.sourceRange = rng }; Data.prototype = {}; bililiteRange.data = function(name, newdesc){ if ('value' in newdesc) Data.prototype[name] = newdesc.value; } } })(); // Polyfill for forEach, per Mozilla documentation. path_to_url#Polyfill if (!Array.prototype.forEach) { Array.prototype.forEach = function(fun /*, thisArg */) { "use strict"; if (this === void 0 || this === null) throw new TypeError(); var t = Object(this); var len = t.length >>> 0; if (typeof fun !== "function") throw new TypeError(); var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) fun.call(thisArg, t[i], i, t); } }; } ```
/content/code_sandbox/test/libs/bililiteRange.js
javascript
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
7,962
```css .tribute-container { position: absolute; top: 0; left: 0; height: auto; overflow: auto; display: block; z-index: 999999; } .tribute-container ul { margin: 0; margin-top: 2px; padding: 0; list-style: none; background: #efefef; } .tribute-container li { padding: 5px 5px; cursor: pointer; } .tribute-container li.highlight { background: #ddd; } .tribute-container li span { font-weight: bold; } .tribute-container li.no-match { cursor: default; } .tribute-container .menu-highlighted { font-weight: bold; } ```
/content/code_sandbox/example/tribute.css
css
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
161
```html <!DOCTYPE html> <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="x-ua-compatible" content="ie=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>ZURB Tribute | Demo</title> <link rel="stylesheet" href="css/foundation.min.css" /> <link rel="stylesheet" href="tribute.css" /> <style> body { position: relative; } .tribute-demo-input { outline: none; border: 1px solid #eee; padding: 3px 5px; border-radius: 2px; font-size: 15px; min-height: 32px; cursor: text; } .tribute-demo-input:focus { border-color: #d1d1d1; background-color: #fbfbfb; } [contenteditable="true"]:empty:before { content: attr(placeholder); display: block; color: #ccc; } #test-autocomplete-container { position: relative; } #test-autocomplete-textarea-container { position: relative; } .float-right { float: right; } </style> </head> <body> <div class="row text-center"> <div class="large-12 columns"> <h1>Tribute Demo</h1> </div> </div> <div class="row"> <div class="large-8 small-centered columns"> <div class="callout large"> <h5>Tribute on <code>contenteditable</code> element:</h5> <a id="activateInput">@mention</a> <p id="test" class="tribute-demo-input" placeholder="Enter some text here" ></p> <h5> Tribute with a local collection (on <code>@</code>) and a remote one (on <code>#</code>): </h5> <p id="testMultiple" class="tribute-demo-input" placeholder="Enter some text here" ></p> </div> </div> </div> <br /><br /> <div class="row"> <div class="large-8 small-centered columns"> <div class="callout large"> <h5> Tribute with <code>autocompleteMode:true</code> on <code>contenteditable</code> element: </h5> <!-- <a id="activateInput">@mention</a> --> <div id="test-autocomplete-container"> <p id="test-autocomplete" class="tribute-demo-input" placeholder="States of USA" ></p> </div> </div> </div> </div> <div class="row"> <div class="large-8 small-centered columns"> <div class="callout large"> <h5> Tribute with <code>autocompleteMode:true</code> on <code>textarea</code> element: </h5> <div id="test-autocomplete-textarea-container"> <textarea id="test-autocomplete-textarea" cols="40" rows="10" placeholder="States of USA" ></textarea> </div> </div> </div> </div> <div class="row" id="content"> <div class="large-8 medium-8 small-centered columns"> <h5>Tribute on traditional form elements!</h5> <form> <div class="row"> <div class="large-12 columns"> <label>Input Label</label> <input id="testInput" type="text" placeholder="Enter some text here" /> </div> </div> <div class="row"> <div class="large-12 columns"> <label>Textarea Label</label> <textarea id="testarea" placeholder="Enter some text here" ></textarea> </div> </div> </form> <hr /> <p> Brought to you by <a href="path_to_url">ZURB</a>, the creators of <a href="path_to_url">Helio</a> </p> <p> Design successful products by rapidly revealing key user behaviors. <a href="path_to_url">Helio</a> makes it easy to get reactions on your designs quickly so your team can focus on solving the right problems, right now. </p> <p> The code is available under the <a href="path_to_url" >. </p> </div> </div> <script src="tribute.js"></script> <script> // example of alternative callback var tribute = new Tribute({ // menuContainer: document.getElementById('content'), values: [ { key: "Jordan Humphreys", value: "Jordan Humphreys", email: "getstarted@zurb.com" }, { key: "Sir Walter Riley", value: "Sir Walter Riley", email: "getstarted+riley@zurb.com" }, { key: "Joachim", value: "Joachim", email: "getstarted+joachim@zurb.com" } ], selectTemplate: function(item) { if (typeof item === "undefined") return null; if (this.range.isContentEditable(this.current.element)) { return ( '<span contenteditable="false"><a href="path_to_url" target="_blank" title="' + item.original.email + '">' + item.original.value + "</a></span>" ); } return "@" + item.original.value; }, requireLeadingSpace: false }); tribute.attach(document.getElementById("test")); tribute.attach(document.getElementById("testInput")); tribute.attach(document.getElementById("testarea")); var tributeMultipleTriggers = new Tribute({ collection: [ { // The function that gets call on select that retuns the content to insert selectTemplate: function(item) { if (this.range.isContentEditable(this.current.element)) { return ( '<a href="path_to_url" title="' + item.original.email + '">@' + item.original.value + "</a>" ); } return "@" + item.original.value; }, // the array of objects values: [ { key: "Jordan Humphreys", value: "Jordan Humphreys", email: "jordan@zurb.com" }, { key: "Sir Walter Riley", value: "Sir Walter Riley", email: "jordan+riley@zurb.com" } ] }, { // The symbol that starts the lookup trigger: "#", loadingItemTemplate: '<div style="padding: 16px">Loading</div>', // The function that gets call on select that retuns the content to insert selectTemplate: function(item) { if (this.range.isContentEditable(this.current.element)) { return ( '<a href="mailto:' + item.original.email + '">#' + item.original.name.replace() + "</a>" ); } return "#" + item.original.name; }, // function retrieving an array of objects values: function(_, cb) { setTimeout(() => cb([ { name: "Bob Bill", email: "bobbill@example.com" }, { name: "Steve Stevenston", email: "steve@example.com" } ]), 1000) }, lookup: "name", fillAttr: "name" } ] }); tributeMultipleTriggers.attach(document.getElementById("testMultiple")); document .getElementById("test") .addEventListener("tribute-replaced", function(e) { console.log("Original Event:", e.detail.event); console.log("Matched item:", e.detail.item); }); var noMatchRunOnce = false; document .getElementById("test") .addEventListener("tribute-no-match", function(e) { if (noMatchRunOnce) return; var values = [ { key: "Cheese Tacos", value: "Cheese Tacos", email: "cheesetacos@zurb.com" } ]; tribute.appendCurrent(values); noMatchRunOnce = true; }); var activateLink = document.getElementById("activateInput"); if (activateLink) { activateLink.addEventListener("mousedown", function(e) { e.preventDefault(); var input = document.getElementById("test"); tribute.showMenuForCollection(input); }); } // example of Tribute in autocomplete mode var tributeAttributes = { autocompleteMode: true, noMatchTemplate: "", values: [ { key: "Alabama", value: "Alabama" }, { key: "Alaska", value: "Alaska" }, { key: "Arizona", value: "Arizona" }, { key: "Arkansas", value: "Arkansas" }, { key: "California", value: "California" }, { key: "Colorado", value: "Colorado" }, { key: "Connecticut", value: "Connecticut" }, { key: "Delaware", value: "Delaware" }, { key: "Florida", value: "Florida" }, { key: "Georgia", value: "Georgia" }, { key: "Hawaii", value: "Hawaii" }, { key: "Idaho", value: "Idaho" }, { key: "Illinois", value: "Illinois" }, { key: "Indiana", value: "Indiana" }, { key: "Iowa", value: "Iowa" }, { key: "Kansas", value: "Kansas" }, { key: "Kentucky", value: "Kentucky" }, { key: "Louisiana", value: "Louisiana" }, { key: "Maine", value: "Maine" }, { key: "Maryland", value: "Maryland" }, { key: "Massachusetts", value: "Massachusetts" }, { key: "Michigan", value: "Michigan" }, { key: "Minnesota", value: "Minnesota" }, { key: "Mississippi", value: "Mississippi" }, { key: "Missouri", value: "Missouri" }, { key: "Montana", value: "Montana" }, { key: "Nebraska", value: "Nebraska" }, { key: "Nevada", value: "Nevada" }, { key: "New Hampshire", value: "New Hampshire" }, { key: "New Jersey", value: "New Jersey" }, { key: "New Mexico", value: "New Mexico" }, { key: "New York", value: "New York" }, { key: "North Carolina", value: "North Carolina" }, { key: "North Dakota", value: "North Dakota" }, { key: "Ohio", value: "Ohio" }, { key: "Oklahoma", value: "Oklahoma" }, { key: "Oregon", value: "Oregon" }, { key: "Pennsylvania", value: "Pennsylvania" }, { key: "Rhode Island", value: "Rhode Island" }, { key: "South Carolina", value: "South Carolina" }, { key: "South Dakota", value: "South Dakota" }, { key: "Tennessee", value: "Tennessee" }, { key: "Texas", value: "Texas" }, { key: "Utah", value: "Utah" }, { key: "Vermont", value: "Vermont" }, { key: "Virginia", value: "Virginia" }, { key: "Washington", value: "Washington" }, { key: "West Virginia", value: "West Virginia" }, { key: "Wisconsin", value: "Wisconsin" }, { key: "Wyoming", value: "Wyoming" } ], selectTemplate: function(item) { if (typeof item === "undefined") return null; if (this.range.isContentEditable(this.current.element)) { return ( '<span contenteditable="false"><a>' + item.original.key + "</a></span>" ); } return item.original.value; }, menuItemTemplate: function(item) { return item.string; } }; var tributeAutocompleteTest = new Tribute( Object.assign( { menuContainer: document.getElementById( "test-autocomplete-container" ) }, tributeAttributes ) ); tributeAutocompleteTest.attach( document.getElementById("test-autocomplete") ); var tributeAutocompleteTestArea = new Tribute( Object.assign( { menuContainer: document.getElementById( "test-autocomplete-textarea-container" ) }, tributeAttributes ) ); tributeAutocompleteTestArea.attach( document.getElementById("test-autocomplete-textarea") ); </script> </body> </html> ```
/content/code_sandbox/example/index.html
html
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
2,934
```javascript (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = global || self, global.Tribute = factory()); }(this, (function () { 'use strict'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(n); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } if (!Array.prototype.find) { Array.prototype.find = function (predicate) { if (this === null) { throw new TypeError('Array.prototype.find called on null or undefined'); } if (typeof predicate !== 'function') { throw new TypeError('predicate must be a function'); } var list = Object(this); var length = list.length >>> 0; var thisArg = arguments[1]; var value; for (var i = 0; i < length; i++) { value = list[i]; if (predicate.call(thisArg, value, i, list)) { return value; } } return undefined; }; } if (window && typeof window.CustomEvent !== "function") { var CustomEvent$1 = function CustomEvent(event, params) { params = params || { bubbles: false, cancelable: false, detail: undefined }; var evt = document.createEvent('CustomEvent'); evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail); return evt; }; if (typeof window.Event !== 'undefined') { CustomEvent$1.prototype = window.Event.prototype; } window.CustomEvent = CustomEvent$1; } var TributeEvents = /*#__PURE__*/function () { function TributeEvents(tribute) { _classCallCheck(this, TributeEvents); this.tribute = tribute; this.tribute.events = this; } _createClass(TributeEvents, [{ key: "bind", value: function bind(element) { element.boundKeydown = this.keydown.bind(element, this); element.boundKeyup = this.keyup.bind(element, this); element.boundInput = this.input.bind(element, this); element.addEventListener("keydown", element.boundKeydown, false); element.addEventListener("keyup", element.boundKeyup, false); element.addEventListener("input", element.boundInput, false); } }, { key: "unbind", value: function unbind(element) { element.removeEventListener("keydown", element.boundKeydown, false); element.removeEventListener("keyup", element.boundKeyup, false); element.removeEventListener("input", element.boundInput, false); delete element.boundKeydown; delete element.boundKeyup; delete element.boundInput; } }, { key: "keydown", value: function keydown(instance, event) { if (instance.shouldDeactivate(event)) { instance.tribute.isActive = false; instance.tribute.hideMenu(); } var element = this; instance.commandEvent = false; TributeEvents.keys().forEach(function (o) { if (o.key === event.keyCode) { instance.commandEvent = true; instance.callbacks()[o.value.toLowerCase()](event, element); } }); } }, { key: "input", value: function input(instance, event) { instance.inputEvent = true; instance.keyup.call(this, instance, event); } }, { key: "click", value: function click(instance, event) { var tribute = instance.tribute; if (tribute.menu && tribute.menu.contains(event.target)) { var li = event.target; event.preventDefault(); event.stopPropagation(); while (li.nodeName.toLowerCase() !== "li") { li = li.parentNode; if (!li || li === tribute.menu) { throw new Error("cannot find the <li> container for the click"); } } tribute.selectItemAtIndex(li.getAttribute("data-index"), event); tribute.hideMenu(); // TODO: should fire with externalTrigger and target is outside of menu } else if (tribute.current.element && !tribute.current.externalTrigger) { tribute.current.externalTrigger = false; setTimeout(function () { return tribute.hideMenu(); }); } } }, { key: "keyup", value: function keyup(instance, event) { if (instance.inputEvent) { instance.inputEvent = false; } instance.updateSelection(this); if (event.keyCode === 27) return; if (!instance.tribute.allowSpaces && instance.tribute.hasTrailingSpace) { instance.tribute.hasTrailingSpace = false; instance.commandEvent = true; instance.callbacks()["space"](event, this); return; } if (!instance.tribute.isActive) { if (instance.tribute.autocompleteMode) { instance.callbacks().triggerChar(event, this, ""); } else { var keyCode = instance.getKeyCode(instance, this, event); if (isNaN(keyCode) || !keyCode) return; var trigger = instance.tribute.triggers().find(function (trigger) { return trigger.charCodeAt(0) === keyCode; }); if (typeof trigger !== "undefined") { instance.callbacks().triggerChar(event, this, trigger); } } } if (instance.tribute.current.mentionText.length < instance.tribute.current.collection.menuShowMinLength) { return; } if ((instance.tribute.current.trigger || instance.tribute.autocompleteMode) && instance.commandEvent === false || instance.tribute.isActive && event.keyCode === 8) { instance.tribute.showMenuFor(this, true); } } }, { key: "shouldDeactivate", value: function shouldDeactivate(event) { if (!this.tribute.isActive) return false; if (this.tribute.current.mentionText.length === 0) { var eventKeyPressed = false; TributeEvents.keys().forEach(function (o) { if (event.keyCode === o.key) eventKeyPressed = true; }); return !eventKeyPressed; } return false; } }, { key: "getKeyCode", value: function getKeyCode(instance, el, event) { var tribute = instance.tribute; var info = tribute.range.getTriggerInfo(false, tribute.hasTrailingSpace, true, tribute.allowSpaces, tribute.autocompleteMode); if (info) { return info.mentionTriggerChar.charCodeAt(0); } else { return false; } } }, { key: "updateSelection", value: function updateSelection(el) { this.tribute.current.element = el; var info = this.tribute.range.getTriggerInfo(false, this.tribute.hasTrailingSpace, true, this.tribute.allowSpaces, this.tribute.autocompleteMode); if (info) { this.tribute.current.selectedPath = info.mentionSelectedPath; this.tribute.current.mentionText = info.mentionText; this.tribute.current.selectedOffset = info.mentionSelectedOffset; } } }, { key: "callbacks", value: function callbacks() { var _this = this; return { triggerChar: function triggerChar(e, el, trigger) { var tribute = _this.tribute; tribute.current.trigger = trigger; var collectionItem = tribute.collection.find(function (item) { return item.trigger === trigger; }); tribute.current.collection = collectionItem; if (tribute.current.mentionText.length >= tribute.current.collection.menuShowMinLength && tribute.inputEvent) { tribute.showMenuFor(el, true); } }, enter: function enter(e, el) { // choose selection if (_this.tribute.isActive && _this.tribute.current.filteredItems) { e.preventDefault(); e.stopPropagation(); setTimeout(function () { _this.tribute.selectItemAtIndex(_this.tribute.menuSelected, e); _this.tribute.hideMenu(); }, 0); } }, escape: function escape(e, el) { if (_this.tribute.isActive) { e.preventDefault(); e.stopPropagation(); _this.tribute.isActive = false; _this.tribute.hideMenu(); } }, tab: function tab(e, el) { // choose first match _this.callbacks().enter(e, el); }, space: function space(e, el) { if (_this.tribute.isActive) { if (_this.tribute.spaceSelectsMatch) { _this.callbacks().enter(e, el); } else if (!_this.tribute.allowSpaces) { e.stopPropagation(); setTimeout(function () { _this.tribute.hideMenu(); _this.tribute.isActive = false; }, 0); } } }, up: function up(e, el) { // navigate up ul if (_this.tribute.isActive && _this.tribute.current.filteredItems) { e.preventDefault(); e.stopPropagation(); var count = _this.tribute.current.filteredItems.length, selected = _this.tribute.menuSelected; if (count > selected && selected > 0) { _this.tribute.menuSelected--; _this.setActiveLi(); } else if (selected === 0) { _this.tribute.menuSelected = count - 1; _this.setActiveLi(); _this.tribute.menu.scrollTop = _this.tribute.menu.scrollHeight; } } }, down: function down(e, el) { // navigate down ul if (_this.tribute.isActive && _this.tribute.current.filteredItems) { e.preventDefault(); e.stopPropagation(); var count = _this.tribute.current.filteredItems.length - 1, selected = _this.tribute.menuSelected; if (count > selected) { _this.tribute.menuSelected++; _this.setActiveLi(); } else if (count === selected) { _this.tribute.menuSelected = 0; _this.setActiveLi(); _this.tribute.menu.scrollTop = 0; } } }, "delete": function _delete(e, el) { if (_this.tribute.isActive && _this.tribute.current.mentionText.length < 1) { _this.tribute.hideMenu(); } else if (_this.tribute.isActive) { _this.tribute.showMenuFor(el); } } }; } }, { key: "setActiveLi", value: function setActiveLi(index) { var lis = this.tribute.menu.querySelectorAll("li"), length = lis.length >>> 0; if (index) this.tribute.menuSelected = parseInt(index); for (var i = 0; i < length; i++) { var li = lis[i]; if (i === this.tribute.menuSelected) { li.classList.add(this.tribute.current.collection.selectClass); var liClientRect = li.getBoundingClientRect(); var menuClientRect = this.tribute.menu.getBoundingClientRect(); if (liClientRect.bottom > menuClientRect.bottom) { var scrollDistance = liClientRect.bottom - menuClientRect.bottom; this.tribute.menu.scrollTop += scrollDistance; } else if (liClientRect.top < menuClientRect.top) { var _scrollDistance = menuClientRect.top - liClientRect.top; this.tribute.menu.scrollTop -= _scrollDistance; } } else { li.classList.remove(this.tribute.current.collection.selectClass); } } } }, { key: "getFullHeight", value: function getFullHeight(elem, includeMargin) { var height = elem.getBoundingClientRect().height; if (includeMargin) { var style = elem.currentStyle || window.getComputedStyle(elem); return height + parseFloat(style.marginTop) + parseFloat(style.marginBottom); } return height; } }], [{ key: "keys", value: function keys() { return [{ key: 9, value: "TAB" }, { key: 8, value: "DELETE" }, { key: 13, value: "ENTER" }, { key: 27, value: "ESCAPE" }, { key: 32, value: "SPACE" }, { key: 38, value: "UP" }, { key: 40, value: "DOWN" }]; } }]); return TributeEvents; }(); var TributeMenuEvents = /*#__PURE__*/function () { function TributeMenuEvents(tribute) { _classCallCheck(this, TributeMenuEvents); this.tribute = tribute; this.tribute.menuEvents = this; this.menu = this.tribute.menu; } _createClass(TributeMenuEvents, [{ key: "bind", value: function bind(menu) { var _this = this; this.menuClickEvent = this.tribute.events.click.bind(null, this); this.menuContainerScrollEvent = this.debounce(function () { if (_this.tribute.isActive) { _this.tribute.hideMenu(); } }, 10, false); this.windowResizeEvent = this.debounce(function () { if (_this.tribute.isActive) { _this.tribute.hideMenu(); } }, 10, false); // fixes IE11 issues with mousedown this.tribute.range.getDocument().addEventListener("MSPointerDown", this.menuClickEvent, false); this.tribute.range.getDocument().addEventListener("mousedown", this.menuClickEvent, false); window.addEventListener("resize", this.windowResizeEvent); if (this.menuContainer) { this.menuContainer.addEventListener("scroll", this.menuContainerScrollEvent, false); } else { window.addEventListener("scroll", this.menuContainerScrollEvent); } } }, { key: "unbind", value: function unbind(menu) { this.tribute.range.getDocument().removeEventListener("mousedown", this.menuClickEvent, false); this.tribute.range.getDocument().removeEventListener("MSPointerDown", this.menuClickEvent, false); window.removeEventListener("resize", this.windowResizeEvent); if (this.menuContainer) { this.menuContainer.removeEventListener("scroll", this.menuContainerScrollEvent, false); } else { window.removeEventListener("scroll", this.menuContainerScrollEvent); } } }, { key: "debounce", value: function debounce(func, wait, immediate) { var _arguments = arguments, _this2 = this; var timeout; return function () { var context = _this2, args = _arguments; var later = function later() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; } }]); return TributeMenuEvents; }(); var TributeRange = /*#__PURE__*/function () { function TributeRange(tribute) { _classCallCheck(this, TributeRange); this.tribute = tribute; this.tribute.range = this; } _createClass(TributeRange, [{ key: "getDocument", value: function getDocument() { var iframe; if (this.tribute.current.collection) { iframe = this.tribute.current.collection.iframe; } if (!iframe) { return document; } return iframe.contentWindow.document; } }, { key: "positionMenuAtCaret", value: function positionMenuAtCaret(scrollTo) { var context = this.tribute.current, coordinates; var info = this.getTriggerInfo(false, this.tribute.hasTrailingSpace, true, this.tribute.allowSpaces, this.tribute.autocompleteMode); if (typeof info !== 'undefined') { if (!this.tribute.positionMenu) { this.tribute.menu.style.cssText = "display: block;"; return; } if (!this.isContentEditable(context.element)) { coordinates = this.getTextAreaOrInputUnderlinePosition(this.tribute.current.element, info.mentionPosition); } else { coordinates = this.getContentEditableCaretPosition(info.mentionPosition); } this.tribute.menu.style.cssText = "top: ".concat(coordinates.top, "px;\n left: ").concat(coordinates.left, "px;\n right: ").concat(coordinates.right, "px;\n bottom: ").concat(coordinates.bottom, "px;\n max-height: ").concat(coordinates.maxHeight || 500, "px;\n max-width: ").concat(coordinates.maxWidth || 300, "px;\n position: ").concat(coordinates.position || 'absolute', ";\n display: block;"); if (coordinates.left === 'auto') { this.tribute.menu.style.left = 'auto'; } if (coordinates.top === 'auto') { this.tribute.menu.style.top = 'auto'; } if (scrollTo) this.scrollIntoView(); } else { this.tribute.menu.style.cssText = 'display: none'; } } }, { key: "selectElement", value: function selectElement(targetElement, path, offset) { var range; var elem = targetElement; if (path) { for (var i = 0; i < path.length; i++) { elem = elem.childNodes[path[i]]; if (elem === undefined) { return; } while (elem.length < offset) { offset -= elem.length; elem = elem.nextSibling; } if (elem.childNodes.length === 0 && !elem.length) { elem = elem.previousSibling; } } } var sel = this.getWindowSelection(); range = this.getDocument().createRange(); range.setStart(elem, offset); range.setEnd(elem, offset); range.collapse(true); try { sel.removeAllRanges(); } catch (error) {} sel.addRange(range); targetElement.focus(); } }, { key: "replaceTriggerText", value: function replaceTriggerText(text, requireLeadingSpace, hasTrailingSpace, originalEvent, item) { var info = this.getTriggerInfo(true, hasTrailingSpace, requireLeadingSpace, this.tribute.allowSpaces, this.tribute.autocompleteMode); if (info !== undefined) { var context = this.tribute.current; var replaceEvent = new CustomEvent('tribute-replaced', { detail: { item: item, instance: context, context: info, event: originalEvent } }); if (!this.isContentEditable(context.element)) { var myField = this.tribute.current.element; var textSuffix = typeof this.tribute.replaceTextSuffix == 'string' ? this.tribute.replaceTextSuffix : ' '; text += textSuffix; var startPos = info.mentionPosition; var endPos = info.mentionPosition + info.mentionText.length + textSuffix.length; if (!this.tribute.autocompleteMode) { endPos += info.mentionTriggerChar.length - 1; } myField.value = myField.value.substring(0, startPos) + text + myField.value.substring(endPos, myField.value.length); myField.selectionStart = startPos + text.length; myField.selectionEnd = startPos + text.length; } else { // add a space to the end of the pasted text var _textSuffix = typeof this.tribute.replaceTextSuffix == 'string' ? this.tribute.replaceTextSuffix : '\xA0'; text += _textSuffix; var _endPos = info.mentionPosition + info.mentionText.length; if (!this.tribute.autocompleteMode) { _endPos += info.mentionTriggerChar.length; } this.pasteHtml(text, info.mentionPosition, _endPos); } context.element.dispatchEvent(new CustomEvent('input', { bubbles: true })); context.element.dispatchEvent(replaceEvent); } } }, { key: "pasteHtml", value: function pasteHtml(html, startPos, endPos) { var range, sel; sel = this.getWindowSelection(); range = this.getDocument().createRange(); range.setStart(sel.anchorNode, startPos); range.setEnd(sel.anchorNode, endPos); range.deleteContents(); var el = this.getDocument().createElement('div'); el.innerHTML = html; var frag = this.getDocument().createDocumentFragment(), node, lastNode; while (node = el.firstChild) { lastNode = frag.appendChild(node); } range.insertNode(frag); // Preserve the selection if (lastNode) { range = range.cloneRange(); range.setStartAfter(lastNode); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } } }, { key: "getWindowSelection", value: function getWindowSelection() { if (this.tribute.collection.iframe) { return this.tribute.collection.iframe.contentWindow.getSelection(); } return window.getSelection(); } }, { key: "getNodePositionInParent", value: function getNodePositionInParent(element) { if (element.parentNode === null) { return 0; } for (var i = 0; i < element.parentNode.childNodes.length; i++) { var node = element.parentNode.childNodes[i]; if (node === element) { return i; } } } }, { key: "getContentEditableSelectedPath", value: function getContentEditableSelectedPath(ctx) { var sel = this.getWindowSelection(); var selected = sel.anchorNode; var path = []; var offset; if (selected != null) { var i; var ce = selected.contentEditable; while (selected !== null && ce !== 'true') { i = this.getNodePositionInParent(selected); path.push(i); selected = selected.parentNode; if (selected !== null) { ce = selected.contentEditable; } } path.reverse(); // getRangeAt may not exist, need alternative offset = sel.getRangeAt(0).startOffset; return { selected: selected, path: path, offset: offset }; } } }, { key: "getTextPrecedingCurrentSelection", value: function getTextPrecedingCurrentSelection() { var context = this.tribute.current, text = ''; if (!this.isContentEditable(context.element)) { var textComponent = this.tribute.current.element; if (textComponent) { var startPos = textComponent.selectionStart; if (textComponent.value && startPos >= 0) { text = textComponent.value.substring(0, startPos); } } } else { var selectedElem = this.getWindowSelection().anchorNode; if (selectedElem != null) { var workingNodeContent = selectedElem.textContent; var selectStartOffset = this.getWindowSelection().getRangeAt(0).startOffset; if (workingNodeContent && selectStartOffset >= 0) { text = workingNodeContent.substring(0, selectStartOffset); } } } return text; } }, { key: "getLastWordInText", value: function getLastWordInText(text) { text = text.replace(/\u00A0/g, ' '); // path_to_url var wordsArray; if (this.tribute.autocompleteSeparator) { wordsArray = text.split(this.tribute.autocompleteSeparator); } else { wordsArray = text.split(/\s+/); } var worldsCount = wordsArray.length - 1; return wordsArray[worldsCount].trim(); } }, { key: "getTriggerInfo", value: function getTriggerInfo(menuAlreadyActive, hasTrailingSpace, requireLeadingSpace, allowSpaces, isAutocomplete) { var _this = this; var ctx = this.tribute.current; var selected, path, offset; if (!this.isContentEditable(ctx.element)) { selected = this.tribute.current.element; } else { var selectionInfo = this.getContentEditableSelectedPath(ctx); if (selectionInfo) { selected = selectionInfo.selected; path = selectionInfo.path; offset = selectionInfo.offset; } } var effectiveRange = this.getTextPrecedingCurrentSelection(); var lastWordOfEffectiveRange = this.getLastWordInText(effectiveRange); if (isAutocomplete) { return { mentionPosition: effectiveRange.length - lastWordOfEffectiveRange.length, mentionText: lastWordOfEffectiveRange, mentionSelectedElement: selected, mentionSelectedPath: path, mentionSelectedOffset: offset }; } if (effectiveRange !== undefined && effectiveRange !== null) { var mostRecentTriggerCharPos = -1; var triggerChar; this.tribute.collection.forEach(function (config) { var c = config.trigger; var idx = config.requireLeadingSpace ? _this.lastIndexWithLeadingSpace(effectiveRange, c) : effectiveRange.lastIndexOf(c); if (idx > mostRecentTriggerCharPos) { mostRecentTriggerCharPos = idx; triggerChar = c; requireLeadingSpace = config.requireLeadingSpace; } }); if (mostRecentTriggerCharPos >= 0 && (mostRecentTriggerCharPos === 0 || !requireLeadingSpace || /[\xA0\s]/g.test(effectiveRange.substring(mostRecentTriggerCharPos - 1, mostRecentTriggerCharPos)))) { var currentTriggerSnippet = effectiveRange.substring(mostRecentTriggerCharPos + triggerChar.length, effectiveRange.length); triggerChar = effectiveRange.substring(mostRecentTriggerCharPos, mostRecentTriggerCharPos + triggerChar.length); var firstSnippetChar = currentTriggerSnippet.substring(0, 1); var leadingSpace = currentTriggerSnippet.length > 0 && (firstSnippetChar === ' ' || firstSnippetChar === '\xA0'); if (hasTrailingSpace) { currentTriggerSnippet = currentTriggerSnippet.trim(); } var regex = allowSpaces ? /[^\S ]/g : /[\xA0\s]/g; this.tribute.hasTrailingSpace = regex.test(currentTriggerSnippet); if (!leadingSpace && (menuAlreadyActive || !regex.test(currentTriggerSnippet))) { return { mentionPosition: mostRecentTriggerCharPos, mentionText: currentTriggerSnippet, mentionSelectedElement: selected, mentionSelectedPath: path, mentionSelectedOffset: offset, mentionTriggerChar: triggerChar }; } } } } }, { key: "lastIndexWithLeadingSpace", value: function lastIndexWithLeadingSpace(str, trigger) { var reversedStr = str.split('').reverse().join(''); var index = -1; for (var cidx = 0, len = str.length; cidx < len; cidx++) { var firstChar = cidx === str.length - 1; var leadingSpace = /\s/.test(reversedStr[cidx + 1]); var match = true; for (var triggerIdx = trigger.length - 1; triggerIdx >= 0; triggerIdx--) { if (trigger[triggerIdx] !== reversedStr[cidx - triggerIdx]) { match = false; break; } } if (match && (firstChar || leadingSpace)) { index = str.length - 1 - cidx; break; } } return index; } }, { key: "isContentEditable", value: function isContentEditable(element) { return element.nodeName !== 'INPUT' && element.nodeName !== 'TEXTAREA'; } }, { key: "isMenuOffScreen", value: function isMenuOffScreen(coordinates, menuDimensions) { var windowWidth = window.innerWidth; var windowHeight = window.innerHeight; var doc = document.documentElement; var windowLeft = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0); var windowTop = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0); var menuTop = typeof coordinates.top === 'number' ? coordinates.top : windowTop + windowHeight - coordinates.bottom - menuDimensions.height; var menuRight = typeof coordinates.right === 'number' ? coordinates.right : coordinates.left + menuDimensions.width; var menuBottom = typeof coordinates.bottom === 'number' ? coordinates.bottom : coordinates.top + menuDimensions.height; var menuLeft = typeof coordinates.left === 'number' ? coordinates.left : windowLeft + windowWidth - coordinates.right - menuDimensions.width; return { top: menuTop < Math.floor(windowTop), right: menuRight > Math.ceil(windowLeft + windowWidth), bottom: menuBottom > Math.ceil(windowTop + windowHeight), left: menuLeft < Math.floor(windowLeft) }; } }, { key: "getMenuDimensions", value: function getMenuDimensions() { // Width of the menu depends of its contents and position // We must check what its width would be without any obstruction // This way, we can achieve good positioning for flipping the menu var dimensions = { width: null, height: null }; this.tribute.menu.style.cssText = "top: 0px;\n left: 0px;\n position: fixed;\n display: block;\n visibility; hidden;\n max-height:500px;"; dimensions.width = this.tribute.menu.offsetWidth; dimensions.height = this.tribute.menu.offsetHeight; this.tribute.menu.style.cssText = "display: none;"; return dimensions; } }, { key: "getTextAreaOrInputUnderlinePosition", value: function getTextAreaOrInputUnderlinePosition(element, position, flipped) { var properties = ['direction', 'boxSizing', 'width', 'height', 'overflowX', 'overflowY', 'borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth', 'borderStyle', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'fontStyle', 'fontVariant', 'fontWeight', 'fontStretch', 'fontSize', 'fontSizeAdjust', 'lineHeight', 'fontFamily', 'textAlign', 'textTransform', 'textIndent', 'textDecoration', 'letterSpacing', 'wordSpacing']; var div = this.getDocument().createElement('div'); div.id = 'input-textarea-caret-position-mirror-div'; this.getDocument().body.appendChild(div); var style = div.style; var computed = window.getComputedStyle ? getComputedStyle(element) : element.currentStyle; style.whiteSpace = 'pre-wrap'; if (element.nodeName !== 'INPUT') { style.wordWrap = 'break-word'; } style.position = 'absolute'; style.visibility = 'hidden'; // transfer the element's properties to the div properties.forEach(function (prop) { style[prop] = computed[prop]; }); //NOT SURE WHY THIS IS HERE AND IT DOESNT SEEM HELPFUL // if (isFirefox) { // style.width = `${(parseInt(computed.width) - 2)}px` // if (element.scrollHeight > parseInt(computed.height)) // style.overflowY = 'scroll' // } else { // style.overflow = 'hidden' // } var span0 = document.createElement('span'); span0.textContent = element.value.substring(0, position); div.appendChild(span0); if (element.nodeName === 'INPUT') { div.textContent = div.textContent.replace(/\s/g, ''); } //Create a span in the div that represents where the cursor //should be var span = this.getDocument().createElement('span'); //we give it no content as this represents the cursor span.textContent = '&#x200B;'; div.appendChild(span); var span2 = this.getDocument().createElement('span'); span2.textContent = element.value.substring(position); div.appendChild(span2); var rect = element.getBoundingClientRect(); //position the div exactly over the element //so we can get the bounding client rect for the span and //it should represent exactly where the cursor is div.style.position = 'fixed'; div.style.left = rect.left + 'px'; div.style.top = rect.top + 'px'; div.style.width = rect.width + 'px'; div.style.height = rect.height + 'px'; div.scrollTop = element.scrollTop; var spanRect = span.getBoundingClientRect(); this.getDocument().body.removeChild(div); return this.getFixedCoordinatesRelativeToRect(spanRect); } }, { key: "getContentEditableCaretPosition", value: function getContentEditableCaretPosition(selectedNodePosition) { var range; var sel = this.getWindowSelection(); range = this.getDocument().createRange(); range.setStart(sel.anchorNode, selectedNodePosition); range.setEnd(sel.anchorNode, selectedNodePosition); range.collapse(false); var rect = range.getBoundingClientRect(); return this.getFixedCoordinatesRelativeToRect(rect); } }, { key: "getFixedCoordinatesRelativeToRect", value: function getFixedCoordinatesRelativeToRect(rect) { var coordinates = { position: 'fixed', left: rect.left, top: rect.top + rect.height }; var menuDimensions = this.getMenuDimensions(); var availableSpaceOnTop = rect.top; var availableSpaceOnBottom = window.innerHeight - (rect.top + rect.height); //check to see where's the right place to put the menu vertically if (availableSpaceOnBottom < menuDimensions.height) { if (availableSpaceOnTop >= menuDimensions.height || availableSpaceOnTop > availableSpaceOnBottom) { coordinates.top = 'auto'; coordinates.bottom = window.innerHeight - rect.top; if (availableSpaceOnBottom < menuDimensions.height) { coordinates.maxHeight = availableSpaceOnTop; } } else { if (availableSpaceOnTop < menuDimensions.height) { coordinates.maxHeight = availableSpaceOnBottom; } } } var availableSpaceOnLeft = rect.left; var availableSpaceOnRight = window.innerWidth - rect.left; //check to see where's the right place to put the menu horizontally if (availableSpaceOnRight < menuDimensions.width) { if (availableSpaceOnLeft >= menuDimensions.width || availableSpaceOnLeft > availableSpaceOnRight) { coordinates.left = 'auto'; coordinates.right = window.innerWidth - rect.left; if (availableSpaceOnRight < menuDimensions.width) { coordinates.maxWidth = availableSpaceOnLeft; } } else { if (availableSpaceOnLeft < menuDimensions.width) { coordinates.maxWidth = availableSpaceOnRight; } } } return coordinates; } }, { key: "scrollIntoView", value: function scrollIntoView(elem) { var reasonableBuffer = 20, clientRect; var maxScrollDisplacement = 100; var e = this.menu; if (typeof e === 'undefined') return; while (clientRect === undefined || clientRect.height === 0) { clientRect = e.getBoundingClientRect(); if (clientRect.height === 0) { e = e.childNodes[0]; if (e === undefined || !e.getBoundingClientRect) { return; } } } var elemTop = clientRect.top; var elemBottom = elemTop + clientRect.height; if (elemTop < 0) { window.scrollTo(0, window.pageYOffset + clientRect.top - reasonableBuffer); } else if (elemBottom > window.innerHeight) { var maxY = window.pageYOffset + clientRect.top - reasonableBuffer; if (maxY - window.pageYOffset > maxScrollDisplacement) { maxY = window.pageYOffset + maxScrollDisplacement; } var targetY = window.pageYOffset - (window.innerHeight - elemBottom); if (targetY > maxY) { targetY = maxY; } window.scrollTo(0, targetY); } } }, { key: "menuContainerIsBody", get: function get() { return this.tribute.menuContainer === document.body || !this.tribute.menuContainer; } }]); return TributeRange; }(); // Thanks to path_to_url var TributeSearch = /*#__PURE__*/function () { function TributeSearch(tribute) { _classCallCheck(this, TributeSearch); this.tribute = tribute; this.tribute.search = this; } _createClass(TributeSearch, [{ key: "simpleFilter", value: function simpleFilter(pattern, array) { var _this = this; return array.filter(function (string) { return _this.test(pattern, string); }); } }, { key: "test", value: function test(pattern, string) { return this.match(pattern, string) !== null; } }, { key: "match", value: function match(pattern, string, opts) { opts = opts || {}; var len = string.length, pre = opts.pre || '', post = opts.post || '', compareString = opts.caseSensitive && string || string.toLowerCase(); if (opts.skip) { return { rendered: string, score: 0 }; } pattern = opts.caseSensitive && pattern || pattern.toLowerCase(); var patternCache = this.traverse(compareString, pattern, 0, 0, []); if (!patternCache) { return null; } return { rendered: this.render(string, patternCache.cache, pre, post), score: patternCache.score }; } }, { key: "traverse", value: function traverse(string, pattern, stringIndex, patternIndex, patternCache) { if (this.tribute.autocompleteSeparator) { // if the pattern search at end pattern = pattern.split(this.tribute.autocompleteSeparator).splice(-1)[0]; } if (pattern.length === patternIndex) { // calculate score and copy the cache containing the indices where it's found return { score: this.calculateScore(patternCache), cache: patternCache.slice() }; } // if string at end or remaining pattern > remaining string if (string.length === stringIndex || pattern.length - patternIndex > string.length - stringIndex) { return undefined; } var c = pattern[patternIndex]; var index = string.indexOf(c, stringIndex); var best, temp; while (index > -1) { patternCache.push(index); temp = this.traverse(string, pattern, index + 1, patternIndex + 1, patternCache); patternCache.pop(); // if downstream traversal failed, return best answer so far if (!temp) { return best; } if (!best || best.score < temp.score) { best = temp; } index = string.indexOf(c, index + 1); } return best; } }, { key: "calculateScore", value: function calculateScore(patternCache) { var score = 0; var temp = 1; patternCache.forEach(function (index, i) { if (i > 0) { if (patternCache[i - 1] + 1 === index) { temp += temp + 1; } else { temp = 1; } } score += temp; }); return score; } }, { key: "render", value: function render(string, indices, pre, post) { var rendered = string.substring(0, indices[0]); indices.forEach(function (index, i) { rendered += pre + string[index] + post + string.substring(index + 1, indices[i + 1] ? indices[i + 1] : string.length); }); return rendered; } }, { key: "filter", value: function filter(pattern, arr, opts) { var _this2 = this; opts = opts || {}; return arr.reduce(function (prev, element, idx, arr) { var str = element; if (opts.extract) { str = opts.extract(element); if (!str) { // take care of undefineds / nulls / etc. str = ''; } } var rendered = _this2.match(pattern, str, opts); if (rendered != null) { prev[prev.length] = { string: rendered.rendered, score: rendered.score, index: idx, original: element }; } return prev; }, []).sort(function (a, b) { var compare = b.score - a.score; if (compare) return compare; return a.index - b.index; }); } }]); return TributeSearch; }(); var Tribute = /*#__PURE__*/function () { function Tribute(_ref) { var _this = this; var _ref$values = _ref.values, values = _ref$values === void 0 ? null : _ref$values, _ref$loadingItemTempl = _ref.loadingItemTemplate, loadingItemTemplate = _ref$loadingItemTempl === void 0 ? null : _ref$loadingItemTempl, _ref$iframe = _ref.iframe, iframe = _ref$iframe === void 0 ? null : _ref$iframe, _ref$selectClass = _ref.selectClass, selectClass = _ref$selectClass === void 0 ? "highlight" : _ref$selectClass, _ref$containerClass = _ref.containerClass, containerClass = _ref$containerClass === void 0 ? "tribute-container" : _ref$containerClass, _ref$itemClass = _ref.itemClass, itemClass = _ref$itemClass === void 0 ? "" : _ref$itemClass, _ref$trigger = _ref.trigger, trigger = _ref$trigger === void 0 ? "@" : _ref$trigger, _ref$autocompleteMode = _ref.autocompleteMode, autocompleteMode = _ref$autocompleteMode === void 0 ? false : _ref$autocompleteMode, _ref$autocompleteSepa = _ref.autocompleteSeparator, autocompleteSeparator = _ref$autocompleteSepa === void 0 ? null : _ref$autocompleteSepa, _ref$selectTemplate = _ref.selectTemplate, selectTemplate = _ref$selectTemplate === void 0 ? null : _ref$selectTemplate, _ref$menuItemTemplate = _ref.menuItemTemplate, menuItemTemplate = _ref$menuItemTemplate === void 0 ? null : _ref$menuItemTemplate, _ref$lookup = _ref.lookup, lookup = _ref$lookup === void 0 ? "key" : _ref$lookup, _ref$fillAttr = _ref.fillAttr, fillAttr = _ref$fillAttr === void 0 ? "value" : _ref$fillAttr, _ref$collection = _ref.collection, collection = _ref$collection === void 0 ? null : _ref$collection, _ref$menuContainer = _ref.menuContainer, menuContainer = _ref$menuContainer === void 0 ? null : _ref$menuContainer, _ref$noMatchTemplate = _ref.noMatchTemplate, noMatchTemplate = _ref$noMatchTemplate === void 0 ? null : _ref$noMatchTemplate, _ref$requireLeadingSp = _ref.requireLeadingSpace, requireLeadingSpace = _ref$requireLeadingSp === void 0 ? true : _ref$requireLeadingSp, _ref$allowSpaces = _ref.allowSpaces, allowSpaces = _ref$allowSpaces === void 0 ? false : _ref$allowSpaces, _ref$replaceTextSuffi = _ref.replaceTextSuffix, replaceTextSuffix = _ref$replaceTextSuffi === void 0 ? null : _ref$replaceTextSuffi, _ref$positionMenu = _ref.positionMenu, positionMenu = _ref$positionMenu === void 0 ? true : _ref$positionMenu, _ref$spaceSelectsMatc = _ref.spaceSelectsMatch, spaceSelectsMatch = _ref$spaceSelectsMatc === void 0 ? false : _ref$spaceSelectsMatc, _ref$searchOpts = _ref.searchOpts, searchOpts = _ref$searchOpts === void 0 ? {} : _ref$searchOpts, _ref$menuItemLimit = _ref.menuItemLimit, menuItemLimit = _ref$menuItemLimit === void 0 ? null : _ref$menuItemLimit, _ref$menuShowMinLengt = _ref.menuShowMinLength, menuShowMinLength = _ref$menuShowMinLengt === void 0 ? 0 : _ref$menuShowMinLengt; _classCallCheck(this, Tribute); this.autocompleteMode = autocompleteMode; this.autocompleteSeparator = autocompleteSeparator; this.menuSelected = 0; this.current = {}; this.inputEvent = false; this.isActive = false; this.menuContainer = menuContainer; this.allowSpaces = allowSpaces; this.replaceTextSuffix = replaceTextSuffix; this.positionMenu = positionMenu; this.hasTrailingSpace = false; this.spaceSelectsMatch = spaceSelectsMatch; if (this.autocompleteMode) { trigger = ""; allowSpaces = false; } if (values) { this.collection = [{ // symbol that starts the lookup trigger: trigger, // is it wrapped in an iframe iframe: iframe, // class applied to selected item selectClass: selectClass, // class applied to the Container containerClass: containerClass, // class applied to each item itemClass: itemClass, // function called on select that retuns the content to insert selectTemplate: (selectTemplate || Tribute.defaultSelectTemplate).bind(this), // function called that returns content for an item menuItemTemplate: (menuItemTemplate || Tribute.defaultMenuItemTemplate).bind(this), // function called when menu is empty, disables hiding of menu. noMatchTemplate: function (t) { if (typeof t === "string") { if (t.trim() === "") return null; return t; } if (typeof t === "function") { return t.bind(_this); } return noMatchTemplate || function () { return "<li>No Match Found!</li>"; }.bind(_this); }(noMatchTemplate), // column to search against in the object lookup: lookup, // column that contains the content to insert by default fillAttr: fillAttr, // array of objects or a function returning an array of objects values: values, // useful for when values is an async function loadingItemTemplate: loadingItemTemplate, requireLeadingSpace: requireLeadingSpace, searchOpts: searchOpts, menuItemLimit: menuItemLimit, menuShowMinLength: menuShowMinLength }]; } else if (collection) { if (this.autocompleteMode) console.warn("Tribute in autocomplete mode does not work for collections"); this.collection = collection.map(function (item) { return { trigger: item.trigger || trigger, iframe: item.iframe || iframe, selectClass: item.selectClass || selectClass, containerClass: item.containerClass || containerClass, itemClass: item.itemClass || itemClass, selectTemplate: (item.selectTemplate || Tribute.defaultSelectTemplate).bind(_this), menuItemTemplate: (item.menuItemTemplate || Tribute.defaultMenuItemTemplate).bind(_this), // function called when menu is empty, disables hiding of menu. noMatchTemplate: function (t) { if (typeof t === "string") { if (t.trim() === "") return null; return t; } if (typeof t === "function") { return t.bind(_this); } return noMatchTemplate || function () { return "<li>No Match Found!</li>"; }.bind(_this); }(noMatchTemplate), lookup: item.lookup || lookup, fillAttr: item.fillAttr || fillAttr, values: item.values, loadingItemTemplate: item.loadingItemTemplate, requireLeadingSpace: item.requireLeadingSpace, searchOpts: item.searchOpts || searchOpts, menuItemLimit: item.menuItemLimit || menuItemLimit, menuShowMinLength: item.menuShowMinLength || menuShowMinLength }; }); } else { throw new Error("[Tribute] No collection specified."); } new TributeRange(this); new TributeEvents(this); new TributeMenuEvents(this); new TributeSearch(this); } _createClass(Tribute, [{ key: "triggers", value: function triggers() { return this.collection.map(function (config) { return config.trigger; }); } }, { key: "attach", value: function attach(el) { if (!el) { throw new Error("[Tribute] Must pass in a DOM node or NodeList."); } // Check if it is a jQuery collection if (typeof jQuery !== "undefined" && el instanceof jQuery) { el = el.get(); } // Is el an Array/Array-like object? if (el.constructor === NodeList || el.constructor === HTMLCollection || el.constructor === Array) { var length = el.length; for (var i = 0; i < length; ++i) { this._attach(el[i]); } } else { this._attach(el); } } }, { key: "_attach", value: function _attach(el) { if (el.hasAttribute("data-tribute")) { console.warn("Tribute was already bound to " + el.nodeName); } this.ensureEditable(el); this.events.bind(el); el.setAttribute("data-tribute", true); } }, { key: "ensureEditable", value: function ensureEditable(element) { if (Tribute.inputTypes().indexOf(element.nodeName) === -1) { if (element.contentEditable) { element.contentEditable = true; } else { throw new Error("[Tribute] Cannot bind to " + element.nodeName); } } } }, { key: "createMenu", value: function createMenu(containerClass) { var wrapper = this.range.getDocument().createElement("div"), ul = this.range.getDocument().createElement("ul"); wrapper.className = containerClass; wrapper.appendChild(ul); if (this.menuContainer) { return this.menuContainer.appendChild(wrapper); } return this.range.getDocument().body.appendChild(wrapper); } }, { key: "showMenuFor", value: function showMenuFor(element, scrollTo) { var _this2 = this; // Only proceed if menu isn't already shown for the current element & mentionText if (this.isActive && this.current.element === element && this.current.mentionText === this.currentMentionTextSnapshot) { return; } this.currentMentionTextSnapshot = this.current.mentionText; // create the menu if it doesn't exist. if (!this.menu) { this.menu = this.createMenu(this.current.collection.containerClass); element.tributeMenu = this.menu; this.menuEvents.bind(this.menu); } this.isActive = true; this.menuSelected = 0; if (!this.current.mentionText) { this.current.mentionText = ""; } var processValues = function processValues(values) { // Tribute may not be active any more by the time the value callback returns if (!_this2.isActive) { return; } var items = _this2.search.filter(_this2.current.mentionText, values, { pre: _this2.current.collection.searchOpts.pre || "<span>", post: _this2.current.collection.searchOpts.post || "</span>", skip: _this2.current.collection.searchOpts.skip, extract: function extract(el) { if (typeof _this2.current.collection.lookup === "string") { return el[_this2.current.collection.lookup]; } else if (typeof _this2.current.collection.lookup === "function") { return _this2.current.collection.lookup(el, _this2.current.mentionText); } else { throw new Error("Invalid lookup attribute, lookup must be string or function."); } } }); if (_this2.current.collection.menuItemLimit) { items = items.slice(0, _this2.current.collection.menuItemLimit); } _this2.current.filteredItems = items; var ul = _this2.menu.querySelector("ul"); if (!items.length) { var noMatchEvent = new CustomEvent("tribute-no-match", { detail: _this2.menu }); _this2.current.element.dispatchEvent(noMatchEvent); if (typeof _this2.current.collection.noMatchTemplate === "function" && !_this2.current.collection.noMatchTemplate() || !_this2.current.collection.noMatchTemplate) { _this2.hideMenu(); } else { typeof _this2.current.collection.noMatchTemplate === "function" ? ul.innerHTML = _this2.current.collection.noMatchTemplate() : ul.innerHTML = _this2.current.collection.noMatchTemplate; _this2.range.positionMenuAtCaret(scrollTo); } return; } ul.innerHTML = ""; var fragment = _this2.range.getDocument().createDocumentFragment(); items.forEach(function (item, index) { var li = _this2.range.getDocument().createElement("li"); li.setAttribute("data-index", index); li.className = _this2.current.collection.itemClass; li.addEventListener("mousemove", function (e) { var _this2$_findLiTarget = _this2._findLiTarget(e.target), _this2$_findLiTarget2 = _slicedToArray(_this2$_findLiTarget, 2), li = _this2$_findLiTarget2[0], index = _this2$_findLiTarget2[1]; if (e.movementY !== 0) { _this2.events.setActiveLi(index); } }); if (_this2.menuSelected === index) { li.classList.add(_this2.current.collection.selectClass); } li.innerHTML = _this2.current.collection.menuItemTemplate(item); fragment.appendChild(li); }); ul.appendChild(fragment); _this2.range.positionMenuAtCaret(scrollTo); }; if (typeof this.current.collection.values === "function") { if (this.current.collection.loadingItemTemplate) { this.menu.querySelector("ul").innerHTML = this.current.collection.loadingItemTemplate; this.range.positionMenuAtCaret(scrollTo); } this.current.collection.values(this.current.mentionText, processValues); } else { processValues(this.current.collection.values); } } }, { key: "_findLiTarget", value: function _findLiTarget(el) { if (!el) return []; var index = el.getAttribute("data-index"); return !index ? this._findLiTarget(el.parentNode) : [el, index]; } }, { key: "showMenuForCollection", value: function showMenuForCollection(element, collectionIndex) { if (element !== document.activeElement) { this.placeCaretAtEnd(element); } this.current.collection = this.collection[collectionIndex || 0]; this.current.externalTrigger = true; this.current.element = element; if (element.isContentEditable) this.insertTextAtCursor(this.current.collection.trigger);else this.insertAtCaret(element, this.current.collection.trigger); this.showMenuFor(element); } // TODO: make sure this works for inputs/textareas }, { key: "placeCaretAtEnd", value: function placeCaretAtEnd(el) { el.focus(); if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") { var range = document.createRange(); range.selectNodeContents(el); range.collapse(false); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } else if (typeof document.body.createTextRange != "undefined") { var textRange = document.body.createTextRange(); textRange.moveToElementText(el); textRange.collapse(false); textRange.select(); } } // for contenteditable }, { key: "insertTextAtCursor", value: function insertTextAtCursor(text) { var sel, range; sel = window.getSelection(); range = sel.getRangeAt(0); range.deleteContents(); var textNode = document.createTextNode(text); range.insertNode(textNode); range.selectNodeContents(textNode); range.collapse(false); sel.removeAllRanges(); sel.addRange(range); } // for regular inputs }, { key: "insertAtCaret", value: function insertAtCaret(textarea, text) { var scrollPos = textarea.scrollTop; var caretPos = textarea.selectionStart; var front = textarea.value.substring(0, caretPos); var back = textarea.value.substring(textarea.selectionEnd, textarea.value.length); textarea.value = front + text + back; caretPos = caretPos + text.length; textarea.selectionStart = caretPos; textarea.selectionEnd = caretPos; textarea.focus(); textarea.scrollTop = scrollPos; } }, { key: "hideMenu", value: function hideMenu() { if (this.menu) { this.menu.style.cssText = "display: none;"; this.isActive = false; this.menuSelected = 0; this.current = {}; } } }, { key: "selectItemAtIndex", value: function selectItemAtIndex(index, originalEvent) { index = parseInt(index); if (typeof index !== "number" || isNaN(index)) return; var item = this.current.filteredItems[index]; var content = this.current.collection.selectTemplate(item); if (content !== null) this.replaceText(content, originalEvent, item); } }, { key: "replaceText", value: function replaceText(content, originalEvent, item) { this.range.replaceTriggerText(content, true, true, originalEvent, item); } }, { key: "_append", value: function _append(collection, newValues, replace) { if (typeof collection.values === "function") { throw new Error("Unable to append to values, as it is a function."); } else if (!replace) { collection.values = collection.values.concat(newValues); } else { collection.values = newValues; } } }, { key: "append", value: function append(collectionIndex, newValues, replace) { var index = parseInt(collectionIndex); if (typeof index !== "number") throw new Error("please provide an index for the collection to update."); var collection = this.collection[index]; this._append(collection, newValues, replace); } }, { key: "appendCurrent", value: function appendCurrent(newValues, replace) { if (this.isActive) { this._append(this.current.collection, newValues, replace); } else { throw new Error("No active state. Please use append instead and pass an index."); } } }, { key: "detach", value: function detach(el) { if (!el) { throw new Error("[Tribute] Must pass in a DOM node or NodeList."); } // Check if it is a jQuery collection if (typeof jQuery !== "undefined" && el instanceof jQuery) { el = el.get(); } // Is el an Array/Array-like object? if (el.constructor === NodeList || el.constructor === HTMLCollection || el.constructor === Array) { var length = el.length; for (var i = 0; i < length; ++i) { this._detach(el[i]); } } else { this._detach(el); } } }, { key: "_detach", value: function _detach(el) { var _this3 = this; this.events.unbind(el); if (el.tributeMenu) { this.menuEvents.unbind(el.tributeMenu); } setTimeout(function () { el.removeAttribute("data-tribute"); _this3.isActive = false; if (el.tributeMenu) { el.tributeMenu.remove(); } }); } }, { key: "isActive", get: function get() { return this._isActive; }, set: function set(val) { if (this._isActive != val) { this._isActive = val; if (this.current.element) { var noMatchEvent = new CustomEvent("tribute-active-".concat(val)); this.current.element.dispatchEvent(noMatchEvent); } } } }], [{ key: "defaultSelectTemplate", value: function defaultSelectTemplate(item) { if (typeof item === "undefined") return "".concat(this.current.collection.trigger).concat(this.current.mentionText); if (this.range.isContentEditable(this.current.element)) { return '<span class="tribute-mention">' + (this.current.collection.trigger + item.original[this.current.collection.fillAttr]) + "</span>"; } return this.current.collection.trigger + item.original[this.current.collection.fillAttr]; } }, { key: "defaultMenuItemTemplate", value: function defaultMenuItemTemplate(matchItem) { return matchItem.string; } }, { key: "inputTypes", value: function inputTypes() { return ["TEXTAREA", "INPUT"]; } }]); return Tribute; }(); /** * Tribute.js * Native ES6 JavaScript @mention Plugin **/ return Tribute; }))); ```
/content/code_sandbox/example/tribute.js
javascript
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
14,008
```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <link rel="shortcut icon" type="image/x-icon" href="path_to_url" /> <link rel="mask-icon" type="" href="path_to_url" color="#111" /> <title>CodePen - Tribute Debug Template</title> <link rel="stylesheet prefetch" href="path_to_url" /> <link rel="stylesheet" href="tribute.css" /> <style> .tribute-demo-input { outline: none; border: 1px solid #eee; padding: 3px 5px; border-radius: 2px; font-size: 15px; min-height: 32px; cursor: text; } .tribute-demo-input:focus { border-color: #d1d1d1; background-color: #fbfbfb; } [contenteditable="true"]:empty:before { content: attr(placeholder); display: block; color: #ccc; } </style> </head> <body translate="no"> <div class="container-fluid"> <div class="row"> <div class="col-lg-8"> <div class="row"> <div class="col-lg-12"></div> </div> </div> <div class="col-lg-4"> <div class="tab-content"> <div role="tabpanel" class="tab-pane active"> <div class="panel panel-info"> <div class="panel-body"> <div class="form-group"> <textarea id="editComment" name="comment" class="form-control" maxlength="20000" style="resize:vertical;max-height:200px;" data-tribute="true" > Testing123</textarea > </div> </div> </div> </div> </div> </div> </div> </div> <script src="tribute.js"></script> <script> // example of alternative callback var tribute = new Tribute({ values: [ { key: "Jordan Humphreys", value: "Jordan Humphreys", email: "getstarted@zurb.com" }, { key: "Sir Walter Riley", value: "Sir Walter Riley", email: "getstarted+riley@zurb.com" } ], selectTemplate: function(item) { if (typeof item === "undefined") return null; if (this.range.isContentEditable(this.current.element)) { return ( '<span contenteditable="false"><a href="path_to_url" target="_blank" title="' + item.original.email + '">' + item.original.value + "</a></span>" ); } return "@" + item.original.value; } }); tribute.attach(document.getElementById("editComment")); </script> </body> </html> ```
/content/code_sandbox/example/bootstrap.html
html
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
669
```css ```
/content/code_sandbox/example/css/foundation.min.css
css
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
1
```scss .tribute-container { position: absolute; top: 0; left: 0; height: auto; overflow: auto; display: block; z-index: 999999; ul { margin: 0; margin-top: 2px; padding: 0; list-style: none; background: #efefef; } li { padding: 5px 5px; cursor: pointer; &.highlight { background: #ddd; } span { font-weight: bold; } &.no-match { cursor: default; } } .menu-highlighted { font-weight: bold; } } ```
/content/code_sandbox/src/tribute.scss
scss
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
156
```javascript if (!Array.prototype.find) { Object.defineProperty(Array.prototype, 'find', { value: function(predicate) { // 1. Let O be ? ToObject(this value). if (this == null) { throw TypeError('"this" is null or not defined'); } var o = Object(this); // 2. Let len be ? ToLength(? Get(O, "length")). var len = o.length >>> 0; // 3. If IsCallable(predicate) is false, throw a TypeError exception. if (typeof predicate !== 'function') { throw TypeError('predicate must be a function'); } // 4. If thisArg was supplied, let T be thisArg; else let T be undefined. var thisArg = arguments[1]; // 5. Let k be 0. var k = 0; // 6. Repeat, while k < len while (k < len) { // a. Let Pk be ! ToString(k). // b. Let kValue be ? Get(O, Pk). // c. Let testResult be ToBoolean(? Call(predicate, T, kValue, k, O )). // d. If testResult is true, return kValue. var kValue = o[k]; if (predicate.call(thisArg, kValue, k, o)) { return kValue; } // e. Increase k by 1. k++; } // 7. Return undefined. return undefined; }, configurable: true, writable: true }); } if (typeof window !== 'undefined' && typeof window.CustomEvent !== "function") { function CustomEvent(event, params) { params = params || { bubbles: false, cancelable: false, detail: undefined } var evt = document.createEvent('CustomEvent') evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail) return evt } if (typeof window.Event !== 'undefined') { CustomEvent.prototype = window.Event.prototype } window.CustomEvent = CustomEvent } ```
/content/code_sandbox/src/utils.js
javascript
2016-01-19T00:54:39
2024-08-14T11:30:58
tribute
zurb/tribute
2,017
461