text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```xml describe('App component', () => { it('first test', () => { expect(1).toEqual(1); }); }); ```
/content/code_sandbox/src/app/app.component.spec.ts
xml
2016-09-23T20:44:28
2024-08-15T12:52:51
ngx-mask
JsDaddy/ngx-mask
1,150
30
```xml import { userRoutes } from '~modules/user/shared/user-routes'; import { inject } from '@angular/core'; import { Router } from '@angular/router'; import { AuthRepository } from '~modules/auth/store/auth.repository'; export const noAuthenticationGuard = () => { const authRepository: AuthRepository = inject(AuthRepository); if (!authRepository.isLoggedInValue()) { return true; } else { const router: Router = inject(Router); router.navigate([userRoutes.dashboard]); return false; } }; ```
/content/code_sandbox/src/app/modules/shared/guards/no-authentication.guard.ts
xml
2016-11-22T17:10:18
2024-08-14T21:36:59
angular-example-app
Ismaestro/angular-example-app
2,150
109
```xml import React from 'react'; import { WorkspaceStore, ComponentRegistry } from 'mailspring-exports'; import { QuickEventButton } from './quick-event-button'; import { MailspringCalendar } from './core/mailspring-calendar'; const Notice = () => AppEnv.inDevMode() ? ( <span /> ) : ( <div className="preview-notice"> Calendar is launching later this year! This preview is read-only and only supports Google calendar. </div> ); Notice.displayName = 'Notice'; export function activate() { ComponentRegistry.register(MailspringCalendar, { location: WorkspaceStore.Location.Center, }); ComponentRegistry.register(Notice, { location: WorkspaceStore.Sheet.Main.Header, }); ComponentRegistry.register(QuickEventButton, { location: WorkspaceStore.Location.Center.Toolbar, }); } export function deactivate() { ComponentRegistry.unregister(MailspringCalendar); ComponentRegistry.unregister(QuickEventButton); } ```
/content/code_sandbox/app/internal_packages/main-calendar/lib/main.tsx
xml
2016-10-13T06:45:50
2024-08-16T18:14:37
Mailspring
Foundry376/Mailspring
15,331
204
```xml /** * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import type {Dag, DagCommitInfo} from './dag/dag'; import type {ExtendedGraphRow} from './dag/render'; import type {HashSet} from './dag/set'; import type {ReactNode} from 'react'; import {AnimatedReorderGroup} from './AnimatedReorderGroup'; import {AvatarPattern} from './Avatar'; import {YouAreHereLabel} from './YouAreHereLabel'; import {LinkLine, NodeLine, PadLine} from './dag/render'; import React from 'react'; import './RenderDag.css'; /* eslint no-bitwise: 0 */ export type RenderDagProps = { /** The dag to use */ dag: Dag; /** If set, render a subset. Otherwise, all commits are rendered. */ subset?: HashSet; /** Should "anonymous" parents (rendered as "~" in CLI) be ignored? */ ignoreAnonymousParents?: boolean; } & React.HTMLAttributes<HTMLDivElement> & RenderFunctionProps; type RenderFunctionProps = { /** * How to render a commit. * * To avoid re-rendering, pass a "static" (ex. not a closure) function, * then use hooks (ex. recoil selector) to trigger re-rendering inside * the static function. */ renderCommit?: (info: DagCommitInfo) => JSX.Element; /** * How to render extra stuff below a commit. Default: nothing. * * To avoid re-rendering, pass a "static" (ex. not a closure) function, * then use hooks (ex. recoil selector) to trigger re-rendering inside * the static function. */ renderCommitExtras?: (info: DagCommitInfo, row: ExtendedGraphRow) => null | JSX.Element; /** * How to render a "glyph" (ex. "o", "x", "@"). * This should return an SVG element. * The SVG viewbox is (-10,-10) to (10,10) (20px * 20px). * Default: defaultRenderGlyphSvg, draw a circle. * * To avoid re-rendering, pass a "static" (ex. not a closure) function, * then use hooks (ex. recoil selector) to trigger re-rendering inside * the static function. */ renderGlyph?: (info: DagCommitInfo) => RenderGlyphResult; /** * Get extra props for the DivRow for the given commit. * This can be used to tweak styles like selection background, border. * This should be a static-ish function to avoid re-rendering. Inside the function, * it can use hooks to fetch extra state. */ useExtraCommitRowProps?: (info: DagCommitInfo) => React.HTMLAttributes<HTMLDivElement> | void; }; /** * - 'inside-tile': Inside a <Tile />. Must be a svg element. Size decided by <Tile />. * - 'replace-tile': Replace the <Tile /> with the rendered result. Size decided by the * rendered result. Can be other elements not just svg. Useful for "You are here". */ export type RenderGlyphResult = ['inside-tile', JSX.Element] | ['replace-tile', JSX.Element]; /** * Renders a dag. Calculate and render the edges, aka. the left side: * * o +--------+ * | | commit | * | +--------+ * | * | o +--------+ * |/ | commit | * o +--------+ * :\ * : o +--------+ * : | commit | * : +--------+ * : * o +--------+ * | commit | * +--------+ * * The callsite can customize: * - What "dag" and what subset of commits to render. * - How to render each "commit" (the boxes above). * - How to render the glyph (the "o"). * * For a commit with `info.isYouAreHere` set, the "commit" body * will be positioned at the right of the "pad" line, not the * "node" line, and the default "o" rendering logic will render * a blue badge instead. * * See `DagListProps` for customization options. * * This component is intended to be used in multiple places, * ex. the main dag, "mutation dag", context-menu sub-dag, etc. * So it should avoid depending on Recoil states. */ export function RenderDag(props: RenderDagProps) { const { dag, subset, renderCommit, renderCommitExtras, renderGlyph = defaultRenderGlyph, useExtraCommitRowProps, className, ...restProps } = props; const rows = dag.renderToRows(subset); const authors = new Set<string>( rows.flatMap(([info]) => (info.phase === 'draft' && info.author.length > 0 ? info.author : [])), ); const renderedRows: Array<JSX.Element> = rows.map(([info, row]) => { return ( <DagRow key={info.hash} row={row} info={info} renderCommit={renderCommit} renderCommitExtras={renderCommitExtras} renderGlyph={renderGlyph} useExtraCommitRowProps={useExtraCommitRowProps} /> ); }); const fullClassName = ((className ?? '') + ' render-dag').trimStart(); return ( <div className={fullClassName} {...restProps}> <SvgPattenList authors={authors} /> <AnimatedReorderGroup animationDuration={100}>{renderedRows}</AnimatedReorderGroup> </div> ); } function DivRow( props: { left?: JSX.Element | null; right?: JSX.Element | null; } & React.HTMLAttributes<HTMLDivElement> & {['data-commit-hash']?: string}, ) { const {className, left, right, ...restProps} = props ?? {}; const fullClassName = `render-dag-row ${className ?? ''}`; return ( <div {...restProps} className={fullClassName}> <div className="render-dag-row-left-side">{left}</div> <div className="render-dag-row-right-side">{right}</div> </div> ); } function DagRowInner(props: {row: ExtendedGraphRow; info: DagCommitInfo} & RenderFunctionProps) { const { row, info, renderGlyph = defaultRenderGlyph, renderCommit, renderCommitExtras, useExtraCommitRowProps, } = props; const {className = '', ...commitRowProps} = useExtraCommitRowProps?.(info) ?? {}; // Layout per commit: // // Each (regular) commit is rendered in 2 rows: // // Row1 // LeftRight // PreNode* // | | (commit body) // Node // o | // PostNode* // | | // // // // // Row2 // LeftRight // PostNode* // | | // Term // | | (extras) // | ~ // Padding // | // Link // |\ // | | // Ancestry // : | // // // // Note: // - Row1 is used to highlight selection. The "node" line should be // at the center once selected. // - The "*" lines (PreNode, PostNode, PostAncestry) have a stretch // height based on the right-side content. // - Row2 can be hidden if there is no link line, no ":" ancestry, // and no "extras". // // Example of "You Are here" special case. "Row1" is split to two // rows: "Row0" and "Row1": // // Row0 // Left // Node // | (YouAreHere) // // // // Row1 // LeftRight // PostNode* // | | (commit body) // // // // // Note: // - Row0's "left" side can have a larger width, to fit the // "irregular" "(YouAreHere)" element. // - Row2 is the same in this special case. // // Also check fbcode/eden/website/src/components/RenderDag.js const {linkLine, termLine, nodeLine, ancestryLine, isHead, isRoot, hasIndirectAncestor} = row; // By default, the glyph "o" is rendered in a fixed size "Tile". // With 'replace-tile' the glyph can define its own rendered element // (of dynamic size). // // 'replace-tile' also moves the "commit" element to the right of // pad line, not node line. const [glyphPosition, glyph] = renderGlyph(info); const isIrregular = glyphPosition === 'replace-tile'; // isYouAreHere practically matches isIrregular but we treat them as // separate concepts. isYouAreHere affects colors, and isIrregular // affects layout. const color = info.isYouAreHere ? YOU_ARE_HERE_COLOR : undefined; const nodeLinePart = ( <div className="render-dag-row-left-side-line node-line"> {nodeLine.map((l, i) => { if (isIrregular && l === NodeLine.Node) { return <React.Fragment key={i}>{glyph}</React.Fragment>; } // Need stretchY if "glyph" is not "Tile" and has a dynamic height. return ( <NodeTile key={i} line={l} isHead={isHead} isRoot={isRoot} aboveNodeColor={info.isDot ? YOU_ARE_HERE_COLOR : undefined} stretchY={isIrregular && l != NodeLine.Node} scaleY={isIrregular ? 0.5 : 1} glyph={glyph} /> ); })} </div> ); const preNodeLinePart = ( <div className="render-dag-row-left-side-line pre-node-line grow" data-nodecolumn={row.nodeColumn}> {row.preNodeLine.map((l, i) => { const c = i === row.nodeColumn ? (info.isDot ? YOU_ARE_HERE_COLOR : color) : undefined; return <PadTile key={i} line={l} scaleY={0.1} stretchY={true} color={c} />; })} </div> ); const postNodeLinePart = ( <div className="render-dag-row-left-side-line post-node-line grow"> {row.postNodeLine.map((l, i) => { const c = i === row.nodeColumn ? color : undefined; return <PadTile key={i} line={l} scaleY={0.1} stretchY={true} color={c} />; })} </div> ); const linkLinePart = linkLine && ( <div className="render-dag-row-left-side-line link-line"> {linkLine.map((l, i) => ( <LinkTile key={i} line={l} color={color} colorLine={row.linkLineFromNode?.[i]} /> ))} </div> ); const stackPaddingPart = linkLine && linkLine.length <= 2 && ( <div className="render-dag-row-left-side-line stack-padding"> {linkLine // one less than the extra indent added by the link line normally .slice(0, -1) .map((l, i) => ( <PadTile key={i} scaleY={0.3} line={PadLine.Parent} /> ))} </div> ); const termLinePart = termLine && ( <> <div className="render-dag-row-left-side-line term-line-pad"> {termLine.map((isTerm, i) => { const line = isTerm ? PadLine.Ancestor : ancestryLine.at(i) ?? PadLine.Blank; return <PadTile key={i} scaleY={0.25} line={line} />; })} </div> <div className="render-dag-row-left-side-line term-line-term"> {termLine.map((isTerm, i) => { const line = ancestryLine.at(i) ?? PadLine.Blank; return isTerm ? <TermTile key={i} /> : <PadTile key={i} line={line} />; })} </div> </> ); const commitPart = renderCommit?.(info); const commitExtrasPart = renderCommitExtras?.(info, row); const ancestryLinePart = hasIndirectAncestor ? ( <div className="render-dag-row-left-side-line ancestry-line"> {ancestryLine.map((l, i) => ( <PadTile key={i} scaleY={0.6} strokeDashArray="0,2,3,0" line={l} color={row.parentColumns.includes(i) ? color : undefined} /> ))} </div> ) : null; // Put parts together. let row0: JSX.Element | null = null; let row1: JSX.Element | null = null; let row2: JSX.Element | null = null; if (isIrregular) { row0 = <DivRow className={className} {...commitRowProps} left={nodeLinePart} />; row1 = <DivRow left={postNodeLinePart} right={commitPart} />; } else { const left = ( <> {preNodeLinePart} {nodeLinePart} {postNodeLinePart} </> ); row1 = ( <DivRow className={`render-dag-row-commit ${className ?? ''}`} {...commitRowProps} left={left} right={commitPart} data-commit-hash={info.hash} /> ); } if ( linkLinePart != null || termLinePart != null || ancestryLinePart != null || postNodeLinePart != null || commitExtrasPart != null ) { const left = ( <> {commitExtrasPart && postNodeLinePart} {linkLinePart} {termLinePart} {stackPaddingPart} {ancestryLinePart} </> ); row2 = <DivRow left={left} right={commitExtrasPart} />; } return ( <div className="render-dag-row-group" data-reorder-id={info.hash} data-testid={`dag-row-group-${info.hash}`}> {row0} {row1} {row2} </div> ); } const DagRow = React.memo(DagRowInner, (prevProps, nextProps) => { return ( nextProps.info.equals(prevProps.info) && prevProps.row.valueOf() === nextProps.row.valueOf() && prevProps.renderCommit === nextProps.renderCommit && prevProps.renderCommitExtras === nextProps.renderCommitExtras && prevProps.renderGlyph === nextProps.renderGlyph && prevProps.useExtraCommitRowProps == nextProps.useExtraCommitRowProps ); }); export type TileProps = { /** Width. Default: defaultTileWidth. */ width?: number; /** Y scale. Default: 1. Decides height. */ scaleY?: number; /** * If true, set: * - CSS: height: 100% - take up the height of the (flexbox) parent. * - CSS: min-height: width * scaleY, i.e. scaleY affects min-height. * - SVG: preserveAspectRatio: 'none'. * Intended to be only used by PadLine. */ stretchY?: boolean; edges?: Edge[]; /** SVG children. */ children?: React.ReactNode; /** Line width. Default: strokeWidth. */ strokeWidth?: number; /** Dash array. Default: '3,2'. */ strokeDashArray?: string; }; /** * Represent a line within a box (-1,-1) to (1,1). * For example, x1=0, y1=-1, x2=0, y2=1 draws a vertical line in the middle. * Default x y values are 0. * Flag can be used to draw special lines. */ export type Edge = { x1?: number; y1?: number; x2?: number; y2?: number; flag?: number; color?: string; }; export enum EdgeFlag { Dash = 1, IntersectGap = 2, } const defaultTileWidth = 20; const defaultStrokeWidth = 2; /** * A tile is a rectangle with edges in it. * Children are in SVG. */ // eslint-disable-next-line prefer-arrow-callback function TileInner(props: TileProps) { const { scaleY = 1, width = defaultTileWidth, edges = [], strokeWidth = defaultStrokeWidth, strokeDashArray = '3,2', stretchY = false, } = props; const preserveAspectRatio = stretchY || scaleY < 1 ? 'none' : undefined; const height = width * scaleY; const style = stretchY ? {height: '100%', minHeight: height} : {}; // Fill the small caused by scaling, non-integer rounding. // When 'x' is at the border (abs >= 10) and 'y' is at the center, use the "gap fix". const getGapFix = (x: number, y: number) => y === 0 && Math.abs(x) >= 10 ? 0.5 * Math.sign(x) : 0; const paths = edges.map(({x1 = 0, y1 = 0, x2 = 0, y2 = 0, flag = 0, color}, i): JSX.Element => { // see getGapFix above. const fx1 = getGapFix(x1, y1); const fx2 = getGapFix(x2, y2); const fy1 = getGapFix(y1, x1); const fy2 = getGapFix(y2, x2); const sY = scaleY; const dashArray = flag & EdgeFlag.Dash ? strokeDashArray : undefined; let d; if (flag & EdgeFlag.IntersectGap) { // This vertical line intercects with a horizonal line visually but it does not mean // they connect. Leave a small gap in the middle. d = `M ${x1 + fx1} ${y1 * sY + fy1} L 0 -2 M 0 2 L ${x2 + fx2} ${y2 * sY + fy2}`; } else if (y1 === y2 || x1 === x2) { // Straight line (-----). d = `M ${x1 + fx1} ${y1 * sY + fy1} L ${x2 + fx2} ${y2 * sY + fy2}`; } else { // Curved line (towards center). d = `M ${x1 + fx1} ${y1 * sY + fy1} L ${x1} ${y1 * sY} Q 0 0 ${x2} ${y2 * sY} L ${x2 + fx2} ${ y2 * sY + fy2 }`; } return <path d={d} key={i} strokeDasharray={dashArray} stroke={color} />; }); return ( <svg className="render-dag-tile" viewBox={`-10 -${scaleY * 10} 20 ${scaleY * 20}`} height={height} width={width} style={style} preserveAspectRatio={preserveAspectRatio}> <g stroke="var(--foreground)" fill="none" strokeWidth={strokeWidth}> {paths} {props.children} </g> </svg> ); } const Tile = React.memo(TileInner); function NodeTile( props: { line: NodeLine; isHead: boolean; isRoot: boolean; glyph: JSX.Element; /** For NodeLine.Node, the color of the vertial edge above the circle. */ aboveNodeColor?: string; } & TileProps, ) { const {line, isHead, isRoot, glyph} = props; switch (line) { case NodeLine.Ancestor: return <Tile {...props} edges={[{y1: -10, y2: 10, flag: EdgeFlag.Dash}]} />; case NodeLine.Parent: // 10.5 is used instead of 10 to avoid small gaps when the page is zoomed. return <Tile {...props} edges={[{y1: -10, y2: 10.5}]} />; case NodeLine.Node: { const edges: Edge[] = []; if (!isHead) { edges.push({y1: -10.5, color: props.aboveNodeColor}); } if (!isRoot) { edges.push({y2: 10.5}); } return ( <Tile {...props} edges={edges}> {glyph} </Tile> ); } default: return <Tile {...props} edges={[]} />; } } function PadTile(props: {line: PadLine; color?: string} & TileProps) { const {line, color} = props; switch (line) { case PadLine.Ancestor: return <Tile {...props} edges={[{y1: -10, y2: 10, flag: EdgeFlag.Dash, color}]} />; case PadLine.Parent: return <Tile {...props} edges={[{y1: -10, y2: 10, color}]} />; default: return <Tile {...props} edges={[]} />; } } function TermTile(props: TileProps) { // "~" in svg. return ( <Tile {...props}> <path d="M 0 -10 L 0 -5" strokeDasharray="3,2" /> <path d="M -7 -5 Q -3 -8, 0 -5 T 7 -5" /> </Tile> ); } function LinkTile(props: {line: LinkLine; color?: string; colorLine?: LinkLine} & TileProps) { const edges = linkLineToEdges(props.line, props.color, props.colorLine); return <Tile {...props} edges={edges} />; } function linkLineToEdges(linkLine: LinkLine, color?: string, colorLine?: LinkLine): Edge[] { const bits = linkLine.valueOf(); const colorBits = colorLine?.valueOf() ?? 0; const edges: Edge[] = []; const considerEdge = (parentBits: number, ancestorBits: number, edge: Partial<Edge>) => { const present = (bits & (parentBits | ancestorBits)) !== 0; const useColor = (colorBits & (parentBits | ancestorBits)) !== 0; const dashed = (bits & ancestorBits) !== 0; if (present) { const flag = edge.flag ?? 0 | (dashed ? EdgeFlag.Dash : 0); edges.push({...edge, flag, color: useColor ? color : undefined}); } }; considerEdge(LinkLine.VERT_PARENT, LinkLine.VERT_ANCESTOR, { y1: -10, y2: 10, flag: bits & (LinkLine.HORIZ_PARENT | LinkLine.HORIZ_ANCESTOR) ? EdgeFlag.IntersectGap : 0, }); considerEdge(LinkLine.HORIZ_PARENT, LinkLine.HORIZ_ANCESTOR, {x1: -10, x2: 10}); considerEdge(LinkLine.LEFT_MERGE_PARENT, LinkLine.LEFT_MERGE_ANCESTOR, {x1: -10, y2: -10}); considerEdge(LinkLine.RIGHT_MERGE_PARENT, LinkLine.RIGHT_MERGE_ANCESTOR, {x1: 10, y2: -10}); considerEdge(LinkLine.LEFT_FORK_PARENT | LinkLine.LEFT_FORK_ANCESTOR, 0, {x1: -10, y2: 10}); considerEdge(LinkLine.RIGHT_FORK_PARENT | LinkLine.RIGHT_FORK_ANCESTOR, 0, {x1: 10, y2: 10}); return edges; } // Svg patterns for avatar backgrounds. Those patterns are referred later by `RegularGlyph`. function SvgPattenList(props: {authors: Iterable<string>}) { return ( <svg className="render-dag-svg-patterns" viewBox={`-10 -10 20 20`}> <defs> {[...props.authors].map(author => ( <SvgPattern author={author} key={author} /> ))} </defs> </svg> ); } function authorToSvgPatternId(author: string) { return 'avatar-pattern-' + author.replace(/[^A-Z0-9a-z]/g, '_'); } function SvgPatternInner(props: {author: string}) { const {author} = props; const id = authorToSvgPatternId(author); return ( <AvatarPattern size={DEFAULT_GLYPH_RADIUS * 2} username={author} id={id} fallbackFill="var(--foreground)" /> ); } const SvgPattern = React.memo(SvgPatternInner); const YOU_ARE_HERE_COLOR = 'var(--button-primary-hover-background)'; const DEFAULT_GLYPH_RADIUS = (defaultTileWidth * 7) / 20; function RegularGlyphInner({info}: {info: DagCommitInfo}) { const stroke = info.isDot ? YOU_ARE_HERE_COLOR : 'var(--foreground)'; const r = DEFAULT_GLYPH_RADIUS; const strokeWidth = defaultStrokeWidth * 0.9; const isObsoleted = info.successorInfo != null; let fill = 'var(--foreground)'; let extraSvgElement = null; if (info.phase === 'draft') { if (isObsoleted) { // "/" inside the circle (similar to "x" in CLI) to indicate "obsoleted". fill = 'var(--background)'; const pos = r / Math.sqrt(2) - strokeWidth; extraSvgElement = ( <path d={`M ${-pos} ${pos} L ${pos} ${-pos}`} stroke={stroke} strokeWidth={strokeWidth} strokeLinecap="round" /> ); } else if (info.author.length > 0) { // Avatar for draft, non-obsoleted commits. const id = authorToSvgPatternId(info.author); fill = `url(#${id})`; } } return ( <> <circle cx={0} cy={0} r={r} fill={fill} stroke={stroke} strokeWidth={strokeWidth} /> {extraSvgElement} </> ); } export const RegularGlyph = React.memo(RegularGlyphInner, (prevProps, nextProps) => { const prevInfo = prevProps.info; const nextInfo = nextProps.info; return nextInfo.equals(prevInfo); }); /** * The default "You are here" glyph - render as a blue bubble. Intended to be used in * different `RenderDag` configurations. * * If you want to customize the rendering for the main graph, or introducing dependencies * that seem "extra" (like code review states, operation-related progress state), consider * passing the `renderGlyph` prop to `RenderDag` instead. See `CommitTreeList` for example. */ export function YouAreHereGlyph({info, children}: {info: DagCommitInfo; children?: ReactNode}) { return ( <YouAreHereLabel title={info.description} style={{marginLeft: -defaultStrokeWidth * 1.5}}> {children} </YouAreHereLabel> ); } export function defaultRenderGlyph(info: DagCommitInfo): RenderGlyphResult { if (info.isYouAreHere) { return ['replace-tile', <YouAreHereGlyph info={info} />]; } else { return ['inside-tile', <RegularGlyph info={info} />]; } } ```
/content/code_sandbox/addons/isl/src/RenderDag.tsx
xml
2016-05-05T16:53:47
2024-08-16T19:12:02
sapling
facebook/sapling
5,987
6,281
```xml import ITodoDataProvider from '../../../../dataProviders/ITodoDataProvider'; import { DisplayMode } from '@microsoft/sp-core-library'; export interface ITodoProps { dataProvider: ITodoDataProvider; webPartDisplayMode: DisplayMode; } ```
/content/code_sandbox/samples/vuejs-todo-single-file-component/src/webparts/todo/components/todo/ITodoProps.ts
xml
2016-08-30T17:21:43
2024-08-16T18:41:32
sp-dev-fx-webparts
pnp/sp-dev-fx-webparts
2,027
52
```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "path_to_url"> <mapper namespace="com.soecode.lyf.dao.AppointmentDao"> <insert id="insertAppointment"> <!-- ignore --> INSERT ignore INTO appointment (book_id, student_id) VALUES (#{bookId}, #{studentId}) </insert> <select id="queryByKeyWithBook" resultType="Appointment"> <!-- MyBatisAppointmentbook --> <!-- SQL --> SELECT a.book_id, a.student_id, a.appoint_time, b.book_id "book.book_id", b.`name` "book.name", b.number "book.number" FROM appointment a INNER JOIN book b ON a.book_id = b.book_id WHERE a.book_id = #{bookId} AND a.student_id = #{studentId} </select> </mapper> ```
/content/code_sandbox/src/main/resources/mapper/AppointmentDao.xml
xml
2016-06-18T17:58:56
2024-08-08T06:30:53
ssm
liyifeng1994/ssm
5,913
223
```xml import { onIdTokenChanged, beforeAuthStateChanged, type User, type Auth, } from 'firebase/auth' import { defineNuxtPlugin } from '#imports' /** * Sets up a watcher that mints a cookie based auth session. On the server, it reads the cookie to * generate the proper auth state. **Must be added after the firebase auth plugin.** */ export default defineNuxtPlugin((nuxtApp) => { const auth = nuxtApp.$firebaseAuth as Auth // send a post request to the server when auth state changes to mint a cookie beforeAuthStateChanged( auth, // if this fails, we rollback the auth state mintCookie, () => { // rollback the auth state mintCookie(auth.currentUser) } ) // we need both callback to avoid some race conditions onIdTokenChanged(auth, mintCookie) }) // TODO: should this be throttled to avoid multiple calls /** * Sends a post request to the server to mint a cookie based auth session. The name of the cookie is defined in the * api.session.ts file. * * @param user - the user to mint a cookie for */ async function mintCookie(user: User | null) { const jwtToken = await user?.getIdToken(/* forceRefresh */ true) // throws if the server returns an error so that beforeAuthStateChanged can catch it to cancel await $fetch( // '/api/__session-server', '/api/__session', { method: 'POST', // if the token is undefined, the server will delete the cookie body: { token: jwtToken }, } ) } ```
/content/code_sandbox/packages/nuxt/src/runtime/auth/plugin-mint-cookie.client.ts
xml
2016-01-07T22:57:53
2024-08-16T14:23:27
vuefire
vuejs/vuefire
3,833
359
```xml <Project Sdk="Microsoft.NET.Sdk"> <Import Project="..\..\configureawait.props" /> <Import Project="..\..\common.props" /> <PropertyGroup> <TargetFramework>net6.0</TargetFramework> </PropertyGroup> <ItemGroup> <None Remove="Volo.Abp.IdentityServer.SourceCode.zip" /> <Content Include="Volo.Abp.IdentityServer.SourceCode.zip"> <Pack>true</Pack> <PackagePath>content\</PackagePath> </Content> </ItemGroup> </Project> ```
/content/code_sandbox/source-code/Volo.Abp.IdentityServer.SourceCode/Volo.Abp.IdentityServer.SourceCode.csproj
xml
2016-12-03T22:56:24
2024-08-16T16:24:05
abp
abpframework/abp
12,657
121
```xml import {Inject, Injectable, PlatformTest} from "@tsed/common"; import {getJsonSchema, Groups, Name, Property, ReadOnly, Required} from "@tsed/schema"; import {TestMongooseContext} from "@tsed/testing-mongoose"; import {Immutable, Model, MongooseModel, ObjectID, SchemaIgnore} from "../src/index.js"; class BaseModel { @ObjectID("id") @Required() @Groups("!create") _id: string; @Required() @Immutable() @ReadOnly() @SchemaIgnore() @Name("created_at") @Groups("!create", "!update") createdAt: number = Date.now(); @Required() @ReadOnly() @SchemaIgnore() @Name("updated_at") @Groups("!create", "!update") updatedAt: number = Date.now(); } @Model() class DataSourceModel extends BaseModel { @Property() @ReadOnly() get test() { return "test"; } } @Injectable() class MyService { @Inject(DataSourceModel) model: MongooseModel<DataSourceModel>; save() { const instance = new this.model({}); return instance.save(); } } describe("Mongoose: ReadOnly", () => { beforeEach(TestMongooseContext.create); afterEach(TestMongooseContext.reset); it("should generate json schema", () => { const jsonSchema = getJsonSchema(DataSourceModel); expect(jsonSchema).toMatchSnapshot(); }); it("should generate model", async () => { const service = PlatformTest.get<MyService>(MyService); await service.save(); const list = await service.model.find().exec(); expect(list.length).toEqual(1); expect(list[0].toObject().test).toBeUndefined(); expect(list[0].toClass().test).toEqual("test"); }); }); ```
/content/code_sandbox/packages/orm/mongoose/test/readonly.integration.spec.ts
xml
2016-02-21T18:38:47
2024-08-14T21:19:48
tsed
tsedio/tsed
2,817
392
```xml import fs from 'fs'; import { parseChunked } from '@discoveryjs/json-ext'; import { API } from '@statoscope/types/types/validation/api'; import { Result } from '@statoscope/types/types/validation/result'; import { Config } from '@statoscope/types/types/validation/config'; import { ExecMode, ExecParams, NormalizedExecParams, } from '@statoscope/types/types/validation/rule'; import { makeRequireFromPath, PackageAliasType, resolveAliasPackage, } from '@statoscope/config/dist/path'; import { makeAPI } from './api'; import { InputFile, PluginFn, PrepareFn } from './plugin'; import { Rule, RuleDataInput } from './rule'; export default class Validator { public rootDir!: string; public config!: Config; public require!: NodeRequire; public plugins: Record< string, { aliases: string[]; prepare?: PrepareFn<unknown>; rules: Record<string, Rule<unknown, unknown>>; } > = {}; constructor(config: Config, rootDir = process.cwd()) { this.applyConfig(config, rootDir); } applyConfig(config: Config, rootDir: string): void { this.rootDir = rootDir; this.config = config; this.require = makeRequireFromPath(rootDir); if (this.config.plugins) { for (const pluginDefinition of this.config.plugins) { const pluginAlias = Array.isArray(pluginDefinition) ? pluginDefinition[0] : pluginDefinition; const normalizedPluginPath = resolveAliasPackage( PackageAliasType.PLUGIN, pluginAlias, rootDir, ); const localPluginAlias = Array.isArray(pluginDefinition) ? pluginDefinition[1] : pluginDefinition; const resolvedPluginPath = this.require.resolve(normalizedPluginPath); const pluginNS = this.require(resolvedPluginPath); const plugin = (pluginNS.default ?? pluginNS) as PluginFn<unknown>; const pluginDescription = plugin(); this.plugins[resolvedPluginPath] = { rules: {}, aliases: [localPluginAlias], prepare: pluginDescription.prepare, }; if (pluginDescription.rules) { for (const [name, rule] of Object.entries(pluginDescription.rules)) { this.plugins[resolvedPluginPath].rules[name] = rule; } } } } } resolveRule(name: string): Rule<unknown, unknown> | null { const ruleRx = /^(?:(@.+?[/\\][^/\\\s]+|[^/\\\s]+)[/\\])?(.+)/; const [, pluginAlias, ruleName] = name.match(ruleRx) || []; for (const [, pluginDesc] of Object.entries(this.plugins)) { if (pluginDesc.aliases.includes(pluginAlias)) { if (Object.prototype.hasOwnProperty.call(pluginDesc.rules, ruleName)) { return pluginDesc.rules[ruleName]; } } } return null; } async validate(input: string, reference?: string | null): Promise<Result> { const parsedInput: InputFile[] = []; let preparedInput: unknown; parsedInput.push({ name: 'input.json', data: await parseChunked(fs.createReadStream(input)), }); if (reference) { parsedInput.push({ name: 'reference.json', data: await parseChunked(fs.createReadStream(reference)), }); } const result: Result = { rules: [], files: { input: input, reference: reference, }, }; for (const [, plugin] of Object.entries(this.plugins)) { if (typeof plugin.prepare === 'function') { preparedInput = await plugin.prepare(parsedInput); } } preparedInput ??= parsedInput; const rules = Object.entries(this.config?.rules ?? {}); if (!rules.length) { console.log('[WARN] No rules has specified in statoscope config'); } for (const [ruleName, ruleDesc] of rules) { let ruleParams: unknown; let execParams: ExecParams; if (Array.isArray(ruleDesc)) { [execParams, ruleParams] = ruleDesc; } else { execParams = ruleDesc; } const normalizedExecParams = this.normalizeExecParams(execParams); if (normalizedExecParams.mode === 'off') { continue; } const resolvedRule = this.resolveRule(ruleName); if (!resolvedRule) { throw new Error(`Can't resolve rule ${ruleName}`); } const api = await this.execRule(resolvedRule, ruleParams, preparedInput); result.rules.push({ name: ruleName, api, execParams: normalizedExecParams }); } return result; } async execRule( rule: Rule<unknown, unknown>, params: unknown, data: RuleDataInput<unknown>, ): Promise<API> { const api = makeAPI(); await rule(params, data, api); return api; } normalizeExecParams(execParams: ExecParams): NormalizedExecParams { let mode: ExecMode = typeof execParams === 'string' ? execParams : 'error'; if (mode === 'warn' && this.config.warnAsError) { mode = 'error'; } return { mode, }; } } ```
/content/code_sandbox/packages/stats-validator/src/index.ts
xml
2016-11-30T14:09:21
2024-08-15T18:52:57
statoscope
statoscope/statoscope
1,423
1,138
```xml // import lazyload from "utils/lazyload"; // export default lazyload(() => import(/* webpackChunkName: "InviteView" */ "./InviteView")); export { default } from "./InviteView"; ```
/content/code_sandbox/app/src/views/misc/Invite/index.ts
xml
2016-12-01T04:36:06
2024-08-16T19:12:19
requestly
requestly/requestly
2,121
43
```xml // custom typing for import assets declare module "*.png" { const value: any; export default value; } declare module "*.styl" { const value: any; export default value; } declare module "*.css" { const value: any; export default value; } ```
/content/code_sandbox/packages/xarc-create-app/template/src/import-assets.d.ts
xml
2016-09-06T19:02:39
2024-08-11T11:43:11
electrode
electrode-io/electrode
2,103
62
```xml import { addRegistry, initialSetup } from '@verdaccio/test-cli-commons'; import { npm } from './utils'; describe('search a package', () => { jest.setTimeout(20000); let registry; beforeAll(async () => { const setup = await initialSetup(); registry = setup.registry; await registry.init(); }); test('should search a package', async () => { const resp = await npm( {}, 'search', '@verdaccio/cli', '--json', ...addRegistry(registry.getRegistryUrl()) ); const parsedBody = JSON.parse(resp.stdout as string); const pkgFind = parsedBody.find((item) => { return item.name === '@verdaccio/cli'; }); expect(pkgFind.name).toEqual('@verdaccio/cli'); }); afterAll(async () => { registry.stop(); }); }); ```
/content/code_sandbox/e2e/cli/e2e-npm6/search.spec.ts
xml
2016-04-15T16:21:12
2024-08-16T09:38:01
verdaccio
verdaccio/verdaccio
16,189
194
```xml import { each } from 'underscore'; import { HTMLParserOptions } from '../config/config'; const htmlType = 'text/html'; const defaultType = htmlType; // 'application/xml'; export default (str: string, config: HTMLParserOptions = {}) => { const parser = new DOMParser(); const mimeType = config.htmlType || defaultType; const toHTML = mimeType === htmlType; const strF = toHTML ? str : `<div>${str}</div>`; const doc = parser.parseFromString(strF, mimeType); let res: HTMLElement; if (toHTML) { if (config.asDocument) return doc; // Replicate the old parser in order to avoid breaking changes const { head, body } = doc; // Move all scripts at the bottom of the page const scripts = head.querySelectorAll('script'); each(scripts, (node) => body.appendChild(node)); // Move inside body all head children const hEls: Element[] = []; each(head.children, (n) => hEls.push(n)); each(hEls, (node, i) => body.insertBefore(node, body.children[i])); res = body; } else { res = doc.firstChild as HTMLElement; } return res; }; /** * POC, custom html parser specs * Parse an HTML string to an array of nodes * example * parse(`<div class="mycls" data-test>Hello</div><span>World <b>example</b></span>`) * // result * [ * { * tagName: 'div', * attributes: { class: 'mycls', 'data-test': '' }, * childNodes: ['Hello'], * },{ * tagName: 'span', * childNodes: [ * 'World ', * { * tagName: 'b', * childNodes: ['example'], * } * ], * } * ] * export const parseNodes = nodes => { const result = []; for (let i = 0; i < nodes.length; i++) { result.push(parseNode(nodes[i])); } return result; }; export const parseAttributes = attrs => { const result = {}; for (let j = 0; j < attrs.length; j++) { const attr = attrs[j]; const nodeName = attr.nodeName; const nodeValue = attr.nodeValue; result[nodeName] = nodeValue; } return result; }; export const parseNode = el => { // Return the string of the textnode element if (el.nodeType === 3) { return el.nodeValue; } const tagName = node.tagName ? node.tagName.toLowerCase() : ''; const attrs = el.attributes || []; const nodes = el.childNodes || []; return { ...(tagName && { tagName }), ...(attrs.length && { attributes: parseAttributes(attrs) }), ...(nodes.length && { childNodes: parseNodes(nodes) }) }; }; export default (str, config = {}) => { const result = []; const el = document.createElement('div'); el.innerHTML = str; const nodes = el.childNodes; const len = nodes.length; for (let i = 0; i < len; i++) { result.push(parseNode(nodes[i])); } return result; }; */ ```
/content/code_sandbox/src/parser/model/BrowserParserHtml.ts
xml
2016-01-22T00:23:19
2024-08-16T11:20:59
grapesjs
GrapesJS/grapesjs
21,687
717
```xml <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <PackageId>FluentFTP</PackageId> <Title>FluentFTP</Title> <Description>An FTP and FTPS client for .NET &amp; .NET Standard, optimized for speed. Provides extensive FTP commands, File uploads/downloads, SSL/TLS connections, Directory listing parsing, File hashing/checksums, File permissions/CHMOD, FTP proxies, FXP transfers, UTF-8 support, Async/await support, Powershell support and more. Written entirely in C#, with no external dependencies.</Description> <Authors>Robin Rodricks, FluentFTP Contributors</Authors> <PackageProjectUrl>path_to_url <PackageTags>ftp,ftp-client,ftps,ftps-client,ssl,tls,unix,iis,ftp-proxy</PackageTags> <DocumentationFile>bin\$(Configuration)\$(TargetFramework)\FluentFTP.xml</DocumentationFile> <SignAssembly>True</SignAssembly> <AssemblyOriginatorKeyFile>sn.snk</AssemblyOriginatorKeyFile> <Version>51.0.0</Version> <PackageIcon>logo-nuget.png</PackageIcon> <AllowUnsafeBlocks>True</AllowUnsafeBlocks> <LangVersion>10.0</LangVersion> </PropertyGroup> <PropertyGroup> <TargetFrameworks>net5.0;net6.0;net462;net472;netstandard2.0;netstandard2.1</TargetFrameworks> <Platforms>AnyCPU;x64</Platforms> <PackageReadmeFile></PackageReadmeFile> <RepositoryUrl>path_to_url <RepositoryType>git</RepositoryType> </PropertyGroup> <ItemGroup> <None Include="..\.github\logo-nuget.png"> <Pack>True</Pack> <PackagePath></PackagePath> </None> <None Include="..\LICENSE.TXT"> <Pack>True</Pack> <PackagePath></PackagePath> </None> </ItemGroup> <PropertyGroup Condition="'$(Configuration)'=='Release'"> <GeneratePackageOnBuild>True</GeneratePackageOnBuild> </PropertyGroup> <Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(Configuration)'=='Release' And '$(TargetFramework)'=='net462'"> <Exec Command="copy /Y &quot;$(ProjectDir)bin\Release\net462\FluentFTP.dll&quot; &quot;$(SolutionDir)Powershell\FluentFTP.dll&quot;" /> </Target> </Project> ```
/content/code_sandbox/FluentFTP/FluentFTP.csproj
xml
2016-10-29T06:28:31
2024-08-16T09:29:04
FluentFTP
robinrodricks/FluentFTP
3,047
565
```xml import * as React from 'react'; import { connect } from 'react-redux'; import { hashHistory } from 'react-router'; import * as toastr from 'toastr'; import objectAssign = require('object-assign'); import MemberEntity from './../../api/memberEntity'; import MemberForm from './memberForm'; import MemberErrors from '../../validations/MemberFormErrors'; import loadMember from '../../actions/loadMember'; import saveMember from '../../actions/saveMember'; import uiInputMember from '../../actions/uiInputMember'; import initializeNewMember from '../../actions/initializeNewMember'; import {UINotificationInfo} from "../../middleware/uiNotificationInfo"; import {NavigationInfo} from '../../middleware/navigationInfo' interface Props extends React.Props<MemberPage> { params : any member? : MemberEntity ,errors?: MemberErrors ,loadMember? : (id : number) => void ,fireFieldValueChanged : (fieldName : string, value : any) => void ,saveMember: (member: MemberEntity, notificationInfo : UINotificationInfo, navigationInfo : NavigationInfo) => void ,initializeNewMember: () => void } class MemberPage extends React.Component<Props, {}> { constructor(props : Props){ super(props); } componentWillMount() { // Coming from navigation var memberId = this.props.params.id; if(memberId) { var memberIdNumber : number = parseInt(memberId); this.props.loadMember(memberIdNumber); } else { this.props.initializeNewMember(); } } // on any update on the form this function will be called updateMemberFromUI(event) { var field = event.target.name; var value = event.target.value; this.props.fireFieldValueChanged(field, value); } public saveMember(event) { event.preventDefault(); const notificationInfo = new UINotificationInfo(); notificationInfo.successMessage = 'Author saved.'; notificationInfo.errorMessage = 'Failed to save author.'; const navigationInfo = new NavigationInfo(); navigationInfo.successNavigationRoute = "/members"; this.props.saveMember(this.props.member, notificationInfo, navigationInfo); } public render() { if(!this.props.member) return (<div>No data</div>) return ( <MemberForm member={this.props.member} errors={this.props.errors} onChange={this.updateMemberFromUI.bind(this)} onSave={this.saveMember.bind(this)} /> ); } } // Container const mapStateToProps = (state) => { return { member: state.member.member ,errors : state.member.errors } } const mapDispatchToProps = (dispatch) => { return { loadMember: (id : number) => {return dispatch(loadMember(id))} ,fireFieldValueChanged: (fieldName : string, value : any) => {return dispatch(uiInputMember(fieldName, value))} ,saveMember: (member: MemberEntity, notificationInfo : UINotificationInfo, navigationInfo : NavigationInfo) => {return dispatch(saveMember(member, notificationInfo, navigationInfo))} ,initializeNewMember: () => {return dispatch(initializeNewMember()) } } } const ContainerMemberPage = connect( mapStateToProps ,mapDispatchToProps )(MemberPage) export default ContainerMemberPage; ```
/content/code_sandbox/old_class_components_samples/16 Custom Middleware/src/components/member/memberPage.tsx
xml
2016-02-28T11:58:58
2024-07-21T08:53:34
react-typescript-samples
Lemoncode/react-typescript-samples
1,846
702
```xml /* * Wire * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see path_to_url * */ import {fireEvent, waitFor} from '@testing-library/react'; import {ClientType} from '@wireapp/api-client/lib/client'; import {BackendError, BackendErrorLabel} from '@wireapp/api-client/lib/http/'; import {StatusCodes} from 'http-status-codes'; import {TypeUtil} from '@wireapp/commons'; import {Login} from './Login'; import {Config, Configuration} from '../../Config'; import {actionRoot} from '../module/action'; import {initialRootState} from '../module/reducer'; import {ROUTE} from '../route'; import {mockStoreFactory} from '../util/test/mockStoreFactory'; import {mountComponent} from '../util/test/TestUtil'; describe('Login', () => { it('successfully logs in with email', async () => { const historyPushSpy = spyOn(history, 'pushState'); const email = 'email@mail.com'; const password = 'password'; spyOn(actionRoot.authAction, 'doLogin').and.returnValue(() => Promise.resolve()); const {getByTestId} = mountComponent(<Login />, mockStoreFactory()(initialRootState)); const emailInput = getByTestId('enter-email'); const passwordInput = getByTestId('enter-password'); const submitButton = getByTestId('do-sign-in'); fireEvent.change(emailInput, {target: {value: email}}); fireEvent.change(passwordInput, {target: {value: password}}); fireEvent.click(submitButton); await waitFor(() => { expect(actionRoot.authAction.doLogin).toHaveBeenCalledWith( {clientType: ClientType.PERMANENT, email, password}, undefined, ); }); expect(historyPushSpy).toHaveBeenCalledWith(expect.any(Object), expect.any(String), `#${ROUTE.HISTORY_INFO}`); }); it('redirects to client deletion page if max devices is reached', async () => { const historyPushSpy = spyOn(history, 'pushState'); const email = 'email@mail.com'; const password = 'password'; spyOn(actionRoot.authAction, 'doLogin').and.returnValue(() => Promise.reject(new BackendError('Too many clients', BackendErrorLabel.TOO_MANY_CLIENTS, StatusCodes.NOT_FOUND)), ); const {getByTestId} = mountComponent(<Login />, mockStoreFactory()(initialRootState)); const emailInput = getByTestId('enter-email'); const passwordInput = getByTestId('enter-password'); const submitButton = getByTestId('do-sign-in'); fireEvent.change(emailInput, {target: {value: email}}); fireEvent.change(passwordInput, {target: {value: password}}); fireEvent.click(submitButton); await waitFor(() => { expect(actionRoot.authAction.doLogin).toHaveBeenCalledWith( {clientType: ClientType.PERMANENT, email, password}, undefined, ); }); expect(historyPushSpy).toHaveBeenCalledWith(expect.any(Object), expect.any(String), `#${ROUTE.CLIENTS}`); }); it('successfully logs in with handle', async () => { const historyPushSpy = spyOn(history, 'pushState'); const handle = 'extra-long-handle-with-special-characters...'; const password = 'password'; spyOn(actionRoot.authAction, 'doLogin').and.returnValue(() => Promise.resolve()); const {getByTestId} = mountComponent(<Login />, mockStoreFactory()(initialRootState)); const emailInput = getByTestId('enter-email'); const passwordInput = getByTestId('enter-password'); const submitButton = getByTestId('do-sign-in'); fireEvent.change(emailInput, {target: {value: handle}}); fireEvent.change(passwordInput, {target: {value: password}}); fireEvent.click(submitButton); await waitFor(() => { expect(actionRoot.authAction.doLogin).toHaveBeenCalledWith( {clientType: ClientType.PERMANENT, handle, password}, undefined, ); }); expect(historyPushSpy).toHaveBeenCalledWith(expect.any(Object), expect.any(String), `#${ROUTE.HISTORY_INFO}`); }); it('has disabled submit button as long as one input is empty', () => { const {getByTestId} = mountComponent(<Login />, mockStoreFactory()(initialRootState)); const emailInput = getByTestId('enter-email'); const passwordInput = getByTestId('enter-password'); const submitButton = getByTestId('do-sign-in') as HTMLButtonElement; expect(submitButton.disabled).toBe(true); fireEvent.change(emailInput, {target: {value: 'e'}}); expect(submitButton.disabled).toBe(true); fireEvent.change(passwordInput, {target: {value: 'e'}}); expect(submitButton.disabled).toBe(false); }); describe('with account registration and SSO disabled', () => { it('hides the back button', () => { spyOn<{getConfig: () => TypeUtil.RecursivePartial<Configuration>}>(Config, 'getConfig').and.returnValue({ FEATURE: { ENABLE_ACCOUNT_REGISTRATION: false, ENABLE_DOMAIN_DISCOVERY: false, ENABLE_SSO: false, }, }); const {queryByTestId} = mountComponent(<Login />, mockStoreFactory()(initialRootState)); const backButton = queryByTestId('go-index'); expect(backButton).toBeNull(); }); }); describe('with account registration enabled', () => { it('shows the back button', () => { spyOn<{getConfig: () => TypeUtil.RecursivePartial<Configuration>}>(Config, 'getConfig').and.returnValue({ FEATURE: { ENABLE_ACCOUNT_REGISTRATION: true, }, }); const {getByTestId} = mountComponent(<Login />, mockStoreFactory()(initialRootState)); const backButton = getByTestId('go-index'); expect(backButton).not.toBeNull(); }); }); }); ```
/content/code_sandbox/src/script/auth/page/Login.test.tsx
xml
2016-07-21T15:34:05
2024-08-16T11:40:13
wire-webapp
wireapp/wire-webapp
1,125
1,284
```xml <?xml version="1.0" encoding="UTF-8"?> <!-- 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. --> <configuration scan="true" scanPeriod="30 seconds"> <logger name="io.pravega.cli.admin.dataRecovery" level="INFO"> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>dataRecovery.log</file> <encoder> <charset>UTF-8</charset> <Pattern>%d %-4relative [%thread] %-5level %logger{35} - %msg%n</Pattern> </encoder> </appender> </logger> <logger name="io.pravega.segmentstore.server.containers" level="INFO"> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>containers.log</file> <encoder> <charset>UTF-8</charset> <Pattern>%d %-4relative [%thread] %-5level %logger{35} - %msg%n</Pattern> </encoder> </appender> </logger> <logger name="io.pravega.segmentstore.storage" level="INFO"> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>storage.log</file> <encoder> <charset>UTF-8</charset> <Pattern>%d %-4relative [%thread] %-5level %logger{35} - %msg%n</Pattern> </encoder> </appender> </logger> <logger name="org.apache.curator.framework" level="INFO"> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>ZooKeeper.log</file> <encoder> <charset>UTF-8</charset> <Pattern>%d %-4relative [%thread] %-5level %logger{35} - %msg%n</Pattern> </encoder> </appender> </logger> </configuration> ```
/content/code_sandbox/config/admin-cli-logback.xml
xml
2016-07-11T19:41:03
2024-08-14T22:06:01
pravega
pravega/pravega
1,980
465
```xml /** * @license * * 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. */ /** * @file Simple signal dispatch mechanism. */ /** * This class provides a simple signal dispatch mechanism. Handlers can be added, and then the * `dispatch` method calls all of them. * * If specified, Callable should be an interface containing only a callable signature returning * void. Due to limitations in TypeScript, any interface containing a callable signature will be * accepted by the compiler, but the resultant signature of `dispatch` will not be correct. */ export class Signal<Callable extends Function = () => void> { private handlers = new Set<Callable>(); /** * Count of number of times this signal has been dispatched. This is incremented each time * `dispatch` is called prior to invoking the handlers. */ count = 0; constructor() { const obj = this; this.dispatch = <Callable>(<Function>function (this: any) { ++obj.count; obj.handlers.forEach((handler) => { // eslint-disable-next-line prefer-rest-params handler.apply(this, arguments); }); }); } /** * Add a handler function. If `dispatch` is currently be called, then the new handler will be * called before `dispatch` returns. * * @param handler The handler function to add. * * @return A function that unregisters the handler. */ add(handler: Callable): () => boolean { this.handlers.add(handler); return () => { return this.remove(handler); }; } /** * Remove a handler function. If `dispatch` is currently be called and the new handler has not * yet been called, then it will not be called. * * @param handler Handler to remove. * @return `true` if the handler was present, `false` otherwise. */ remove(handler: Callable): boolean { return this.handlers.delete(handler); } /** * Invokes each handler function with the same parameters (including `this`) with which it is * called. Handlers are invoked in the order in which they were added. */ dispatch: Callable; /** * Disposes of resources. No methods, including `dispatch`, may be invoked afterwards. */ dispose() { this.handlers = <any>undefined; } } export function observeSignal( callback: () => void, ...signals: { add(callback: () => void): void; remove(callback: () => void): void; }[] ) { callback(); for (let i = 0, count = signals.length; i < count; ++i) { signals[i].add(callback); } return () => { for (let i = 0, count = signals.length; i < count; ++i) { signals[i].remove(callback); } }; } /** * Simple specialization of Signal for the common case of a nullary handler signature. */ export class NullarySignal extends Signal<() => void> {} /** * Interface for a signal excluding the dispatch method. * * Unlike Signal, this interface is covariant in the type of Callable. */ export interface ReadonlySignal<Callable extends Function> { readonly count: number; add(handler: Callable): () => void; remove(handler: Callable): boolean; } export type NullaryReadonlySignal = ReadonlySignal<() => void>; export const neverSignal: NullaryReadonlySignal = { count: 0, add(_handler: any) { return () => {}; }, remove(_handler: any) { return false; }, }; ```
/content/code_sandbox/src/util/signal.ts
xml
2016-05-27T02:37:25
2024-08-16T07:24:25
neuroglancer
google/neuroglancer
1,045
810
```xml import { constants, Theme, ThemeColors } from '@devhub/core' import React, { AnchorHTMLAttributes, useCallback, useEffect, useLayoutEffect, useRef, } from 'react' import { GestureResponderEvent, StyleSheet, View } from 'react-native' import { useHover } from '../../hooks/use-hover' import { Browser } from '../../libs/browser' import { Linking } from '../../libs/linking' import { Platform } from '../../libs/platform' import { sharedStyles } from '../../styles/shared' import { EMPTY_OBJ } from '../../utils/constants' import { findNode } from '../../utils/helpers/shared' import { useTheme } from '../context/ThemeContext' import { getThemeColorOrItself } from '../themed/helpers' import { ThemedText, ThemedTextProps } from '../themed/ThemedText' import { ThemedView } from '../themed/ThemedView' import { Touchable, TouchableProps } from './Touchable' import { TouchableOpacity } from './TouchableOpacity' export interface LinkProps extends Partial<TouchableProps> { allowEmptyLink?: boolean backgroundThemeColor?: keyof ThemeColors | ((theme: Theme) => string) enableBackgroundHover?: boolean enableForegroundHover?: boolean enableTextWrapper?: boolean enableUnderlineHover?: boolean forceOpenOutsideApp?: boolean hoverBackgroundThemeColor?: keyof ThemeColors | ((theme: Theme) => string) hoverForegroundThemeColor?: keyof ThemeColors | ((theme: Theme) => string) href?: string mobileProps?: TouchableProps openOnNewTab?: boolean textProps?: ThemedTextProps tooltip?: string webProps?: AnchorHTMLAttributes<HTMLAnchorElement> } export const Link = React.forwardRef<Touchable, LinkProps>((props, ref) => { const { TouchableComponent, allowEmptyLink, analyticsLabel: _analyticsLabel, backgroundThemeColor, enableBackgroundHover: _enableBackgroundHover, enableForegroundHover: _enableForegroundHover, enableTextWrapper, enableUnderlineHover: _enableUnderlineHover, forceOpenOutsideApp, hoverBackgroundThemeColor: _hoverBackgroundThemeColor, hoverForegroundThemeColor: _hoverForegroundThemeColor, href, onPress, textProps, tooltip, ...otherProps } = props const { openOnNewTab: _openOnNewTab = !(href && href.startsWith('javascript:')), } = props const analyticsLabel = _analyticsLabel && _analyticsLabel.replace(/-/g, '_') const openOnNewTab = _openOnNewTab || Platform.isElectron const enableBackgroundHover = !!(href || onPress) && _enableBackgroundHover const enableForegroundHover = !!(href || onPress) && _enableForegroundHover const enableUnderlineHover = !!(href || onPress) && _enableUnderlineHover const theme = useTheme() const cacheRef = useRef({ isHovered: false }) const _flatContainerStyle = StyleSheet.flatten(otherProps.style) || EMPTY_OBJ const backgroundColor = (backgroundThemeColor && getThemeColorOrItself(theme, backgroundThemeColor)) || _flatContainerStyle.backgroundColor const color = textProps && textProps.color && getThemeColorOrItself(theme, textProps.color) const updateStyles = useCallback(() => { const { isHovered } = cacheRef.current const hoverBackgroundColor = enableBackgroundHover ? getThemeColorOrItself( theme, _hoverBackgroundThemeColor || 'foregroundColorTransparent10', ) : undefined const hoverForegroundColor = enableForegroundHover ? getThemeColorOrItself( theme, _hoverForegroundThemeColor || 'primaryBackgroundColor', ) : undefined if (containerRef.current && containerRef.current.setNativeProps) { containerRef.current.setNativeProps({ style: { backgroundColor: (isHovered && hoverBackgroundColor) || backgroundColor, }, }) } if (textRef.current) { textRef.current.setNativeProps({ style: { color: (isHovered && hoverForegroundColor) || color, ...(enableUnderlineHover ? { textDecorationLine: isHovered ? 'underline' : 'none' } : {}), }, }) } }, [ _hoverBackgroundThemeColor, _hoverForegroundThemeColor, backgroundThemeColor, enableBackgroundHover, enableForegroundHover, enableUnderlineHover, backgroundColor, color, textProps && textProps.color, theme, ]) const _defaultRef = useRef<View>(null) const containerRef = (ref as any) || _defaultRef const textRef = useRef<ThemedText | null>(null) const initialIsHovered = useHover( enableBackgroundHover || enableForegroundHover || enableUnderlineHover ? containerRef : null, useCallback( (isHovered) => { if (cacheRef.current.isHovered === isHovered) return cacheRef.current.isHovered = isHovered updateStyles() }, [updateStyles], ), ) cacheRef.current.isHovered = initialIsHovered useEffect(() => { return () => { textRef.current = null } }, []) const isFirstRendeRef = useRef(true) useLayoutEffect(() => { if (isFirstRendeRef.current) { isFirstRendeRef.current = false return } updateStyles() }, [updateStyles]) useEffect(() => { if (!(Platform.OS === 'web' && !Platform.supportsTouch)) return const node = findNode(containerRef) if (!node) return node.title = tooltip || '' if (!tooltip && node.removeAttribute) node.removeAttribute('title') }, [containerRef.current, tooltip]) const renderTouchable = href || onPress || allowEmptyLink const isDeepLink = href && href.startsWith(`${constants.APP_DEEP_LINK_SCHEMA}://`) let finalProps: any if (renderTouchable) { finalProps = { ...(analyticsLabel ? { analyticsCategory: 'link', analyticsAction: 'click', analyticsLabel, } : {}), ...Platform.select({ default: { ...otherProps, onPress: (e: GestureResponderEvent, ...args: any[]) => { if (e && e.isDefaultPrevented()) return if (onPress) onPress(e) if (href) { if (!forceOpenOutsideApp && href.startsWith('http')) void Browser.openURL(href) else if (!href.startsWith('javascript:')) void Linking.openURL(href) } if (e) e.preventDefault() }, } as any, web: { accessibilityRole: href && !isDeepLink ? 'link' : 'button', href: isDeepLink ? undefined : href, onPress: (e: any) => { if (e && e.isDefaultPrevented()) return if (onPress) onPress(e) if (isDeepLink && href) void Linking.openURL(href) if (e && (!href || href.startsWith('javascript:'))) e.preventDefault() }, selectable: true, target: openOnNewTab ? '_blank' : '_self', ...otherProps, } as any, }), style: [sharedStyles.fullMaxWidth, otherProps.style, { backgroundColor }], } } else { finalProps = { ...otherProps, onPress, style: [sharedStyles.fullMaxWidth, otherProps.style, { backgroundColor }], } } if ( (typeof finalProps.children === 'string' && enableTextWrapper !== false) || (typeof finalProps.children !== 'string' && enableTextWrapper === true) ) { finalProps.children = ( <ThemedText ref={textRef} {...textProps} color={color as any}> {finalProps.children} </ThemedText> ) } if (!renderTouchable) return <ThemedView ref={containerRef} {...finalProps} /> return ( <Touchable ref={containerRef} {...finalProps} TouchableComponent={TouchableComponent || TouchableOpacity} /> ) }) export type Link = ThemedView | ThemedText | Touchable ```
/content/code_sandbox/packages/components/src/components/common/Link.tsx
xml
2016-11-30T23:24:21
2024-08-16T00:24:59
devhub
devhubapp/devhub
9,652
1,816
```xml <?xml version="1.0" encoding="UTF-8"?> <!-- KATE Syntax Highlighting for RSI IDL --> <!DOCTYPE language SYSTEM "language.dtd"><!-- Created by Markus Fraenz,fraenz@linmpi.mpg.de Aug 2002 --> <language name="RSI IDL" version="3" kateversion="2.3" section="Sources" extensions="*.pro" mimetype="text/x-rsiidl-src" author="Markus Fraenz (fraenz@linmpi.mpg.de)" license=""> <highlighting> <list name="reserved words"> <item>For</item> <item>Do</item> <item>Endfor</item> <item>Repeat</item> <item>Endrep</item> <item>While</item> <item>Endwhile</item> <item>Until</item> <item>Case</item> <item>Endcase</item> <item>If</item> <item>Endif</item> <item>Else</item> <item>Endelse</item> <item>Then</item> <item>Begin</item> <item>End</item> <item>Function</item> <item>Goto</item> <item>Pro</item> <item>Eq</item> <item>Ge</item> <item>Gt</item> <item>Le</item> <item>Lt</item> <item>Ne</item> <item>Mod</item> <item>Or</item> <item>Xor</item> <item>Not</item> <item>And</item> <item>Then</item> <item>Return</item> <item>Common</item> <item>Of</item> <item>On_ioerror</item> <item>Switch</item> <item>Endswitch</item> </list> <list name="system variables"> <item>dpi</item> <item>dtor</item> <item>map</item> <item>pi</item> <item>radeg</item> <item>values</item> <item>err</item> <item>error_state</item> <item>error</item> <item>err_string</item> <item>except</item> <item>mouse</item> <item>msg_prefix</item> <item>syserror</item> <item>syserr_string</item> <item>warn</item> <item>dir</item> <item>dlm_path</item> <item>edit_input</item> <item>help_path</item> <item>journal</item> <item>more</item> <item>path</item> <item>prompt</item> <item>quiet</item> <item>version</item> <item>c</item> <item>d</item> <item>order</item> <item>p</item> <item>x</item> <item>y</item> <item>z</item> <item>stime</item> </list> <list name="types"><!-- IDL5 Data types and variable creation --> <item>Fix</item> <item>Long</item> <item>Long64</item> <item>uint</item> <item>Byte</item> <item>Float</item> <item>Double</item> <item>complex</item> <item>dcomplex</item> <item>complexarr</item> <item>dcomplexarr</item> <item>String</item> <item>Intarr</item> <item>lonarr</item> <item>lon64arr</item> <item>uintarr</item> <item>ulong</item> <item>ulonarr</item> <item>ulon64arr</item> <item>Bytarr</item> <item>Bytscl</item> <item>Fltarr</item> <item>Dblarr</item> <item>Strarr</item> <item>Objarr</item> <item>Indgen</item> <item>Findgen</item> <item>Dindgen</item> <item>Dcindgen</item> <item>cindgen</item> <item>lindgen</item> <item>bindgen</item> <item>sindgen</item> <item>uindgen</item> <item>ul64indgen</item> <item>l64indgen</item> <item>ulindgen</item> <item>Replicate</item> <item>Ptrarr</item> </list> <list name="commands"><!-- IDL5.3 build in routines, excluding lib functions and io functions --> <item>ABS</item> <item>ACOS</item> <item>ADAPT_HIST_EQUAL</item> <item>ALOG</item> <item>ALOG10</item> <item>ARG_PRESENT</item> <item>ASIN</item> <item>ASSOC</item> <item>ATAN</item> <item>AXIS</item> <item>BESELI</item> <item>BESELJ</item> <item>BESELY</item> <item>BLAS_AXPY</item> <item>BREAKPOINT</item> <item>BROYDEN</item> <item>BYTEORDER</item> <item>CALL_EXTERNAL</item> <item>CALL_FUNCTION</item> <item>CALL_METHOD</item> <item>CALL_PROCEDURE</item> <item>CATCH</item> <item>CEIL</item> <item>CHECK_MATH</item> <item>CHOLDC</item> <item>CHOLSOL</item> <item>COLOR_CONVERT</item> <item>COLOR_QUAN</item> <item>COMPILE_OPT</item> <item>COMPUTE_MESH_NORMALS</item> <item>CONJ</item> <item>CONSTRAINED_MIN</item> <item>CONTOUR</item> <item>CONVERT_COORD</item> <item>CONVOL</item> <item>CORRELATE</item> <item>COS</item> <item>COSH</item> <item>CREATE_STRUCT</item> <item>CURSOR</item> <item>DEFINE_KEY</item> <item>DEFSYSV</item> <item>DELVAR</item> <item>DEVICE</item> <item>DFPMIN</item> <item>DIALOG_MESSAGE</item> <item>DIALOG_PICKFILE</item> <item>DIALOG_PRINTERSETUP</item> <item>DIALOG_PRINTJOB</item> <item>DILATE</item> <item>DLM_LOAD</item> <item>DRAW_ROI</item> <item>ELMHES</item> <item>EMPTY</item> <item>ENABLE_SYSRTN</item> <item>ERASE</item> <item>ERODE</item> <item>ERRORF</item> <item>EXECUTE</item> <item>EXIT</item> <item>EXP</item> <item>EXPAND_PATH</item> <item>EXPINT</item> <item>FINDFILE</item> <item>FINITE</item> <item>FLOOR</item> <item>FORMAT_AXIS_VALUES</item> <item>FORWARD_FUNCTION</item> <item>FSTAT</item> <item>FULSTR</item> <item>FZ_ROOTS</item> <item>GAUSSINT</item> <item>GET_KBRD</item> <item>GETENV</item> <item>GRID_TPS</item> <item>GRID3</item> <item>HEAP_GC</item> <item>HELP</item> <item>HISTOGRAM</item> <item>HQR</item> <item>IMAGE_STATISTICS</item> <item>IMAGINARY</item> <item>INTERPOLATE</item> <item>INVERT</item> <item>ISHFT</item> <item>ISOCONTOUR</item> <item>ISOSURFACE</item> <item>JOURNAL</item> <item>KEYWORD_SET</item> <item>LABEL_REGION</item> <item>LINBCG</item> <item>LINKIMAGE</item> <item>LMGR</item> <item>LNGAMMA</item> <item>LNP_TEST</item> <item>LOADCT</item> <item>LOCALE_GET</item> <item>LSODE</item> <item>LUDC</item> <item>LUMPROVE</item> <item>LUSOL</item> <item>MACHAR</item> <item>MAKE_ARRAY</item> <item>MAP_PROJ_INFO</item> <item>MAX</item> <item>MEDIAN</item> <item>MESH_CLIP</item> <item>MESH_DECIMATE</item> <item>MESH_ISSOLID</item> <item>MESH_MERGE</item> <item>MESH_NUMTRIANGLES</item> <item>MESH_SMOOTH</item> <item>MESH_SURFACEAREA</item> <item>MESH_VALIDATE</item> <item>MESH_VOLUME</item> <item>MESSAGE</item> <item>MIN</item> <item>N_ELEMENTS</item> <item>N_PARAMS</item> <item>N_TAGS</item> <item>NEWTON</item> <item>OBJ_CLASS</item> <item>OBJ_DESTROY</item> <item>OBJ_ISA</item> <item>OBJ_NEW</item> <item>OBJ_VALID</item> <item>ON_ERROR</item> <item>OPLOT</item> <item>PARTICLE_TRACE</item> <item>PLOT</item> <item>PLOTS</item> <item>POLY_2D</item> <item>POLYFILL</item> <item>POLYFILLV</item> <item>POLYSHADE</item> <item>POWELL</item> <item>PROFILER</item> <item>PTR_FREE</item> <item>PTR_NEW</item> <item>PTR_VALID</item> <item>QROMB</item> <item>QROMO</item> <item>QSIMP</item> <item>RANDOMN</item> <item>RANDOMU</item> <item>REBIN</item> <item>REFORM</item> <item>RETALL</item> <item>RETURN</item> <item>RIEMANN</item> <item>RK4</item> <item>ROBERTS</item> <item>ROTATE</item> <item>ROUND</item> <item>SET_PLOT</item> <item>SET_SHADING</item> <item>SETENV</item> <item>SHADE_SURF</item> <item>SHADE_VOLUME</item> <item>SHIFT</item> <item>SIN</item> <item>SINH</item> <item>SIZE</item> <item>SMOOTH</item> <item>SOBEL</item> <item>SORT</item> <item>SPL_INIT</item> <item>SPL_INTERP</item> <item>SPRSAB</item> <item>SPRSAX</item> <item>SPRSIN</item> <item>SQRT</item> <item>STOP</item> <item>STRCMP</item> <item>STRCOMPRESS</item> <item>STREGEX</item> <item>STRJOIN</item> <item>STRLEN</item> <item>STRLOWCASE</item> <item>STRMATCH</item> <item>STRMESSAGE</item> <item>STRMID</item> <item>STRPOS</item> <item>STRPUT</item> <item>STRTRIM</item> <item>STRUCT_ASSIGN</item> <item>STRUCT_HIDE</item> <item>STRUPCASE</item> <item>SURFACE</item> <item>SVDC</item> <item>SVSOL</item> <item>SYSTIME</item> <item>TAG_NAMES</item> <item>TAN</item> <item>TANH</item> <item>TEMPORARY</item> <item>TETRA_CLIP</item> <item>TETRA_SURFACE</item> <item>TETRA_VOLUME</item> <item>THIN</item> <item>THREED</item> <item>TOTAL</item> <item>TRANSPOSE</item> <item>TRIANGULATE</item> <item>TRIGRID</item> <item>TRIQL</item> <item>TRIRED</item> <item>TRISOL</item> <item>TV</item> <item>TVCRS</item> <item>TVLCT</item> <item>TVRD</item> <item>TVSCLU</item> <item>USERSYM</item> <item>VALUE_LOCATE</item> <item>VOIGT</item> <item>VOXEL_PROJ</item> <item>WAIT</item> <item>WATERSHED</item> <item>WDELETE</item> <item>WHERE</item> <item>WIDGET_BASE</item> <item>WIDGET_BUTTON</item> <item>WIDGET_CONTROL</item> <item>WIDGET_DRAW</item> <item>WIDGET_DROPLIST</item> <item>WIDGET_EVENT</item> <item>WIDGET_INFO</item> <item>WIDGET_LABEL</item> <item>WIDGET_LIST</item> <item>WIDGET_SLIDER</item> <item>WIDGET_TABLE</item> <item>WIDGET_TEXT</item> <item>WINDOW</item> <item>WSET</item> <item>WSHOW</item> <item>WTN</item> <item>XYOUTS</item> </list> <list name="io commands"><!-- IDL5.3 build in I/O routines --> <item>Open</item> <item>FLUSH</item> <item>IOCTL</item> <item>RESTORE</item> <item>SAVE</item> <item>POINT_LUN</item> <item>Openr</item> <item>Openw</item> <item>Openu</item> <item>Close</item> <item>Free_lun</item> <item>get_lun</item> <item>assoc</item> <item>catch</item> <item>cd</item> <item>spawn</item> <item>eof</item> <item>print</item> <item>printf</item> <item>prints</item> <item>read</item> <item>readf</item> <item>reads</item> <item>writu</item> </list> <contexts> <context attribute="Normal Text" lineEndContext="#stay" name="Normal"> <keyword attribute="Keyword" context="#stay" String="reserved words"/> <keyword attribute="Data Type" context="#stay" String="types"/> <keyword attribute="Command" context="#stay" String="commands"/> <keyword attribute="IOCommand" context="#stay" String="io commands"/> <Float attribute="Octal" context="#stay"/> <Int attribute="Decimal" context="#stay"/> <RangeDetect attribute="String" context="#stay" char="'" char1="'"/> <RangeDetect attribute="String" context="#stay" char="&quot;" char1="&quot;"/> <DetectChar attribute="Hex" context="#stay" char="(" /> <DetectChar attribute="Hex" context="#stay" char=")" /> <DetectChar attribute="Char" context="#stay" char="[" /> <DetectChar attribute="Char" context="#stay" char="]" /> <DetectChar attribute="Float" context="#stay" char="{" /> <DetectChar attribute="Float" context="#stay" char="}" /> <DetectChar attribute="Char" context="#stay" char="$" /> <DetectChar attribute="Char" context="#stay" char="@" /> <DetectChar attribute="Char" context="#stay" char=":" /> <DetectChar attribute="Char" context="Comment" char="&#59;"/> <DetectChar attribute="Char" context="systemvarcontext" char="!" /> </context> <context attribute="Comment" lineEndContext="#pop" name="Comment"> </context> <context attribute="Char" lineEndContext="#pop" name="systemvarcontext"> <DetectChar attribute="Hex" context="#pop" char="(" /> <DetectChar attribute="Char" context="#pop" char="." /> <DetectChar attribute="Hex" context="#pop" char=" " /> <keyword attribute="Float" context="#pop" String="system variables"/> </context> </contexts> <itemDatas> <itemData name="Normal Text" defStyleNum="dsNormal"/> <itemData name="Keyword" defStyleNum="dsKeyword" color="#1414e4" selColor="#ffd60b" bold="1"/> <itemData name="Data Type" defStyleNum="dsDataType"/> <itemData name="Decimal" defStyleNum="dsDecVal" color="#000000" selColor="#ffffff"/> <itemData name="Octal" defStyleNum="dsDecVal"/> <itemData name="Hex" defStyleNum="dsDecVal"/> <itemData name="Float" defStyleNum="dsDecVal" color="#000000" selColor="#ffffff"/> <itemData name="Char" defStyleNum="dsChar"/> <itemData name="String" defStyleNum="dsString" color="#ff0000" selColor="#ff0000"/> <itemData name="Comment" defStyleNum="dsComment" color="#2b7805" selColor="#945ca4"/> <itemData name="Command" defStyleNum="dsBaseN" color="#050505" selColor="#ffffff" bold="1"/> <itemData name="IOCommand" defStyleNum="dsDataType" color="#050505" selColor="#ffffff" bold="1"/> </itemDatas> </highlighting> <general> <comments> <comment name="singleLine" start="&#59;" /> </comments> <keywords casesensitive="0" /> </general> </language> ```
/content/code_sandbox/src/data/extra/syntax-highlighting/syntax/rsiidl.xml
xml
2016-10-05T07:24:54
2024-08-16T05:03:40
vnote
vnotex/vnote
11,687
4,404
```xml import {ChangeDetectionStrategy, Component} from '@angular/core'; import {ScrollingModule} from '@angular/cdk/scrolling'; /** @title Virtual scroll context variables */ @Component({ selector: 'cdk-virtual-scroll-context-example', styleUrl: 'cdk-virtual-scroll-context-example.css', templateUrl: 'cdk-virtual-scroll-context-example.html', changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, imports: [ScrollingModule], }) export class CdkVirtualScrollContextExample { items = Array.from({length: 100000}).map((_, i) => `Item #${i}`); } ```
/content/code_sandbox/src/components-examples/cdk/scrolling/cdk-virtual-scroll-context/cdk-virtual-scroll-context-example.ts
xml
2016-01-04T18:50:02
2024-08-16T11:21:13
components
angular/components
24,263
136
```xml import chalk from 'chalk'; import checkForUpdate from 'update-check'; export default async function shouldUpdate(): Promise<void> { const packageJson = () => require('../package.json'); const update = checkForUpdate(packageJson()).catch(() => null); try { const res = await update; if (res && res.latest) { const _packageJson = packageJson(); console.log(); console.log(chalk.yellow.bold(`A new version of \`${_packageJson.name}\` is available`)); console.log('You can update by running: ' + chalk.cyan(`npm i -g ${_packageJson.name}`)); console.log(); } } catch { // ignore error } } ```
/content/code_sandbox/packages/uri-scheme/src/update.ts
xml
2016-08-15T17:14:25
2024-08-16T19:54:44
expo
expo/expo
32,004
154
```xml import styled from "styled-components"; import { spacing03 } from "@carbon/themes"; import { FC, ReactNode } from "react"; import { TransitionGroup } from "react-transition-group"; const NotificationWrapper = styled.div` position: fixed; top: 3.5rem; right: ${spacing03}; z-index: 10000; max-width: 100%; `; const NotificationContainer: FC<{ children?: ReactNode }> = ({ children }) => ( <NotificationWrapper> <TransitionGroup>{children}</TransitionGroup> </NotificationWrapper> ); export default NotificationContainer; ```
/content/code_sandbox/identity/client/src/components/notifications/NotificationContainer.tsx
xml
2016-03-20T03:38:04
2024-08-16T19:59:58
camunda
camunda/camunda
3,172
127
```xml <?xml version="1.0" encoding="UTF-8"?> <definitions xmlns="path_to_url" xmlns:xsi="path_to_url" xmlns:activiti="path_to_url" xmlns:bpmndi="path_to_url" xmlns:omgdc="path_to_url" xmlns:omgdi="path_to_url" typeLanguage="path_to_url" expressionLanguage="path_to_url" targetNamespace="path_to_url"> <process id="oneTaskProcess" name="The One Task Process"> <startEvent id="theStart" /> <sequenceFlow id="flow1" sourceRef="theStart" targetRef="theTask" /> <userTask id="theTask" name="my task"> <extensionElements> <activiti:taskListener event="create" activiti:expression="${Doesn't matter. Will be overridden}" /> </extensionElements> </userTask> <sequenceFlow id="flow2" sourceRef="theTask" targetRef="theEnd" /> <endEvent id="theEnd" /> </process> </definitions> ```
/content/code_sandbox/modules/flowable-engine/src/test/resources/org/flowable/standalone/parsing/CustomListenerFactoryTest.testCustomListenerFactory.bpmn20.xml
xml
2016-10-13T07:21:43
2024-08-16T15:23:14
flowable-engine
flowable/flowable-engine
7,715
246
```xml <epp xmlns="urn:ietf:params:xml:ns:epp-1.0"> <response> <result code="1000"> <msg>Command completed successfully</msg> </result> <resData> <domain:infData xmlns:domain="urn:ietf:params:xml:ns:domain-1.0"> <domain:name>fakesite.example</domain:name> <domain:roid>%ROID%</domain:roid> <domain:status s="ok"/> <domain:registrant>jd1234</domain:registrant> <domain:contact type="admin">sh8013</domain:contact> <domain:contact type="tech">sh8013</domain:contact> <domain:ns> <domain:hostObj>ns1.example.external</domain:hostObj> <domain:hostObj>ns2.example.external</domain:hostObj> </domain:ns> <domain:host>ns3.fakesite.example</domain:host> <domain:clID>NewRegistrar</domain:clID> <domain:crID>NewRegistrar</domain:crID> <domain:crDate>2000-06-01T00:04:00Z</domain:crDate> <domain:upID>NewRegistrar</domain:upID> <domain:upDate>2000-06-06T00:04:00Z</domain:upDate> <domain:exDate>2002-06-01T00:04:00Z</domain:exDate> <domain:authInfo> <domain:pw>2fooBAR</domain:pw> </domain:authInfo> </domain:infData> </resData> <trID> <clTRID>ABC-12345</clTRID> <svTRID>server-trid</svTRID> </trID> </response> </epp> ```
/content/code_sandbox/core/src/test/resources/google/registry/flows/domain_info_response_fakesite_ok_post_host_update.xml
xml
2016-02-29T20:16:48
2024-08-15T19:49:29
nomulus
google/nomulus
1,685
426
```xml import { Subscriber } from './Subscriber'; import { TeardownLogic } from './types'; export interface Operator<T, R> { call(subscriber: Subscriber<R>, source: any): TeardownLogic; } ```
/content/code_sandbox/deps/node-10.15.3/tools/node_modules/eslint/node_modules/rxjs/internal/Operator.d.ts
xml
2016-09-05T10:18:44
2024-08-11T13:21:40
LiquidCore
LiquidPlayer/LiquidCore
1,010
44
```xml import { Model } from 'mongoose'; import { getUniqueValue } from '@erxes/api-utils/src/core'; import { WEBHOOK_STATUS } from './definitions/constants'; import { IWebhook, IWebhookDocument, webhookSchema } from './definitions/webhooks'; import { IModels } from '../connectionResolver'; export interface IWebhookModel extends Model<IWebhookDocument> { getWebHook(_id: string): Promise<IWebhookDocument>; getWebHooks(): Promise<IWebhookDocument[]>; createWebhook(doc: IWebhook): Promise<IWebhookDocument>; updateWebhook(_id: string, doc: IWebhook): Promise<IWebhookDocument>; updateStatus(_id: string, status: string): Promise<IWebhookDocument>; removeWebhooks(_id: string): void; } export const loadWebhookClass = (models: IModels) => { class Webhook { /* * Get a Webhook */ public static async getWebHook(_id: string) { const webhook = await models.Webhooks.findOne({ _id }); if (!webhook) { throw new Error('Webhook not found'); } return webhook; } public static async getWebHooks() { return models.Webhooks.find({}); } /** * Create webhook */ public static async createWebhook(doc: IWebhook) { if (!doc.url.includes('https')) { throw new Error( 'Url is not valid. Enter valid url with ssl cerfiticate' ); } const modifiedDoc: any = { ...doc }; modifiedDoc.token = await getUniqueValue(models.Webhooks, 'token'); modifiedDoc.status = WEBHOOK_STATUS.UNAVAILABLE; return models.Webhooks.create(modifiedDoc); } public static async updateWebhook(_id: string, doc: IWebhook) { if (!doc.url.includes('https')) { throw new Error( 'Url is not valid. Enter valid url with ssl cerfiticate' ); } await models.Webhooks.updateOne( { _id }, { $set: doc }, { runValidators: true } ); return models.Webhooks.findOne({ _id }); } public static async removeWebhooks(_id) { return models.Webhooks.deleteOne({ _id }); } public static async updateStatus(_id: string, status: string) { await models.Webhooks.updateOne( { _id }, { $set: { status } }, { runValidators: true } ); return models.Webhooks.findOne({ _id }); } } webhookSchema.loadClass(Webhook); return webhookSchema; }; ```
/content/code_sandbox/packages/plugin-webhooks-api/src/models/Webhooks.ts
xml
2016-11-11T06:54:50
2024-08-16T10:26:06
erxes
erxes/erxes
3,479
579
```xml import React from 'react'; import { storiesOf } from '@storybook/react-native'; import { withKnobs } from '@storybook/addon-knobs'; import Wrapper from './../../Wrapper'; import { Example as UnorderedList } from './UnorderedList'; import { Example as StylingList } from './StylingList'; import { Example as OrderedList } from './OrderedList'; import { Example as Basic } from './Basic'; import { Example as ListWithIcon } from './ListWithIcon'; import { Example as PressableList } from './PressableList'; import { Example as VirtualizedList } from './VirtualizedList'; storiesOf('List', module) .addDecorator(withKnobs) .addDecorator((getStory: any) => <Wrapper>{getStory()}</Wrapper>) .add('Basic', () => <Basic />) .add('OrderedList', () => <OrderedList />) .add('UnorderedList', () => <UnorderedList />) .add('StylingList', () => <StylingList />) .add('Pressable List Items', () => <PressableList />) .add('List with Icon', () => <ListWithIcon />) .add('VirtualizedList ', () => <VirtualizedList />); ```
/content/code_sandbox/example/storybook/stories/components/primitives/List/index.tsx
xml
2016-04-15T11:37:23
2024-08-14T16:16:44
NativeBase
GeekyAnts/NativeBase
20,132
265
```xml <configuration> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>target/google-fcm.log</file> <append>false</append> <encoder> <pattern>%d{ISO8601} %-5level [%thread] [%logger{36}] %msg%n</pattern> </encoder> </appender> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d{HH:mm:ss.SSS} %-5level [%-20.20thread] %-36.36logger{36} %msg%n%rEx</pattern> </encoder> </appender> <appender name="CapturingAppender" class="akka.stream.alpakka.testkit.CapturingAppender"/> <logger name="akka.stream.alpakka.testkit.CapturingAppenderDelegate"> <appender-ref ref="STDOUT"/> </logger> <logger name="akka" level="DEBUG"/> <logger name="org.eclipse.jetty.servlet" level="warn"/> <root level="DEBUG"> <appender-ref ref="CapturingAppender"/> <appender-ref ref="FILE" /> </root> </configuration> ```
/content/code_sandbox/google-fcm/src/test/resources/logback-test.xml
xml
2016-10-13T13:08:14
2024-08-15T07:57:42
alpakka
akka/alpakka
1,265
280
```xml import type { RxStorage, RxTestStorage } from '../../types'; export type TestConfig = { storage: RxTestStorage; }; export declare const isDeno: boolean; export declare const isBun: boolean; export declare const isNode: boolean; export declare function setConfig(newConfig: TestConfig): void; export declare function getConfig(): TestConfig; export declare const ENV_VARIABLES: any; export declare const DEFAULT_STORAGE: string; export declare function isFastMode(): boolean; export declare function initTestEnvironment(): void; export declare function getEncryptedStorage(baseStorage?: RxStorage<any, any>): RxStorage<any, any>; export declare function isNotOneOfTheseStorages(storageNames: string[]): boolean; export declare function getPassword(): Promise<string>; ```
/content/code_sandbox/dist/types/plugins/test-utils/config.d.ts
xml
2016-12-02T19:34:42
2024-08-16T15:47:20
rxdb
pubkey/rxdb
21,054
159
```xml <?xml version="1.0" encoding="utf-8"?><HelpTOCNode Title="LoadCode Method " Url="html/9c4ff282-5122-0716-f5e3-75f6b857506a.htm"><HelpTOCNode Title="LoadCode Method (String, Object[])" Url="html/ea230527-cb73-5f65-3758-3cefe73be216.htm" /><HelpTOCNode Title="LoadCode(T) Method (String, Object[])" Url="html/10aa6cee-85d8-20ee-3805-04eb499e18c2.htm" /></HelpTOCNode> ```
/content/code_sandbox/docs/help/toc/9c4ff282-5122-0716-f5e3-75f6b857506a.xml
xml
2016-01-16T05:50:23
2024-08-14T17:35:38
cs-script
oleg-shilo/cs-script
1,583
148
```xml <vector xmlns:android="path_to_url" android:width="24dp" android:height="24dp" android:viewportHeight="24.0" android:viewportWidth="24.0"> <path android:fillColor="#FF000000" android:pathData="M19,6.41L17.59,5 12,10.59 6.41,5 5,6.41 10.59,12 5,17.59 6.41,19 12,13.41 17.59,19 19,17.59 13.41,12z" /> </vector> ```
/content/code_sandbox/app/src/main/res/drawable/ic_close_search.xml
xml
2016-09-21T08:56:16
2024-08-06T13:58:15
susi_android
fossasia/susi_android
2,419
143
```xml /* * @license Apache-2.0 * * * * 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. */ /* eslint-disable @typescript-eslint/no-unused-expressions */ import Uint8Array = require( './index' ); // TESTS // // The function returns a typed array instance... { new Uint8Array( 10 ); // $ExpectType Uint8Array new Uint8Array( [ 2, 5, 5, 7 ] ); // $ExpectType Uint8Array } // The constructor function has to be invoked with `new`... { Uint8Array( 10 ); // $ExpectError Uint8Array( [ 2, 5, 5, 7 ] ); // $ExpectError } ```
/content/code_sandbox/lib/node_modules/@stdlib/array/uint8/docs/types/test.ts
xml
2016-03-24T04:19:52
2024-08-16T09:03:19
stdlib
stdlib-js/stdlib
4,266
182
```xml <?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="path_to_url" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="de" original="../LocalizableStrings.resx"> <body> <trans-unit id="CommandDescription"> <source>Repair workload installations.</source> <target state="translated">Reparieren Sie Workloadinstallationen.</target> <note /> </trans-unit> <trans-unit id="NoWorkloadsToRepair"> <source>No workloads are installed, nothing to repair. Run `dotnet workload search` to find workloads to install.</source> <target state="translated">Es sind keine Workloads installiert, es ist keine Reparatur erforderlich. Fhren Sie dotnet workload search aus, um zu installierende Workloads zu finden.</target> <note /> </trans-unit> <trans-unit id="RepairSucceeded"> <source>Successfully repaired workloads: {0}</source> <target state="translated">Erfolgreich reparierte Workloads: {0}</target> <note /> </trans-unit> <trans-unit id="RepairingWorkloads"> <source>Repairing workload installation for workloads: {0}</source> <target state="translated">Die Workload-Installation fr Workloads wird repariert: {0}</target> <note /> </trans-unit> <trans-unit id="WorkloadRepairFailed"> <source>Workload repair failed: {0}</source> <target state="translated">Fehler bei der Reparatur von Workload: {0}</target> <note /> </trans-unit> </body> </file> </xliff> ```
/content/code_sandbox/src/Cli/dotnet/commands/dotnet-workload/repair/xlf/LocalizableStrings.de.xlf
xml
2016-07-22T21:26:02
2024-08-16T17:23:58
sdk
dotnet/sdk
2,627
440
```xml import * as React from 'react'; import { IPageSectionProps, Markdown } from '@fluentui/react-docsite-components/lib/index2'; import { ControlsAreaPage, IControlsPageProps } from '../ControlsAreaPage'; import { PivotPageProps } from './PivotPage.doc'; import { Platforms } from '../../../interfaces/Platforms'; const baseUrl = 'path_to_url export const PivotPage: React.FunctionComponent<IControlsPageProps> = props => { return ( <ControlsAreaPage {...props} {...PivotPageProps[props.platform!]} otherSections={_otherSections(props.platform) as IPageSectionProps[]} /> ); }; function _otherSections(platform?: Platforms): IPageSectionProps<Platforms>[] | undefined { switch (platform) { case 'ios': return [ { sectionName: 'Implementation', editUrl: baseUrl + 'docs/ios/PivotImplementation.md', content: ( <Markdown> { require('!raw-loader?esModule=false!@fluentui/public-docsite/src/pages/Controls/PivotPage/docs/ios/PivotImplementation.md') as string } </Markdown> ), }, ]; } } ```
/content/code_sandbox/apps/public-docsite/src/pages/Controls/PivotPage/PivotPage.tsx
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
258
```xml import { app, nativeImage, BrowserWindow } from 'electron'; import installExtension, {REDUX_DEVTOOLS, REACT_DEVELOPER_TOOLS} from 'electron-devtools-installer'; import { inject, injectable } from 'inversify'; import path from 'path'; import url from 'url'; import { Env } from '../../utils/env'; import Config from '../config'; import Logger, { $mainLogger, $ipcLogger } from '../logger'; import Platform from '../platform'; import Store from '../store'; import { IpcEvents } from '@nuclear/core'; const urlMapper: Record<Env, string> = { [Env.DEV]: url.format({ pathname: 'localhost:8080', protocol: 'http:', slashes: true }), [Env.PROD]: url.format({ pathname: path.join(__dirname, 'index.html'), protocol: 'file:', slashes: true }), [Env.TEST]: '' }; /** * Wrapper around electron BrowserWindow * @see {@link path_to_url} */ @injectable() class Window { private browserWindow: BrowserWindow; private isReady: Promise<void>; private resolve: () => void; private defaultWidth: number; private defaultHeight: number; constructor( @inject(Config) private config: Config, @inject($mainLogger) private logger: Logger, @inject($ipcLogger) private ipcLogger: Logger, @inject(Platform) private platform: Platform, @inject(Store) store: Store ) { const icon = nativeImage.createFromPath(config.icon); this.defaultWidth = config.defaultWidth; this.defaultHeight = config.defaultHeight; this.browserWindow = new BrowserWindow({ title: config.title, width: this.defaultWidth, height: this.defaultHeight, minWidth: 330, minHeight: 450, frame: !store.getOption('framelessWindow'), icon, show: false, webPreferences: { nodeIntegration: true, webSecurity: false, webviewTag: true, enableRemoteModule: true, contextIsolation: false, additionalArguments: [ store.getOption('disableGPU') && '--disable-gpu' ] } }); if (platform.isMac()) { app.dock.setIcon(icon); } if (platform.isWindows()) { this.browserWindow.flashFrame(true); this.browserWindow.once('focus', () => this.browserWindow.flashFrame(false)); } this.browserWindow.on('app-command', (e, cmd) => { if (cmd === 'browser-backward') { this.browserWindow.webContents.send(IpcEvents.NAVIGATE_BACK); } if (cmd === 'browser-forward') { this.browserWindow.webContents.send(IpcEvents.NAVIGATE_FORWARD); } }); this.isReady = new Promise((resolve) => { this.resolve = resolve; }); this.browserWindow.once('ready-to-show', () => { this.browserWindow.show(); if (config.isDev()) { this.browserWindow.webContents.openDevTools(); } this.resolve(); }); } // eslint-disable-next-line @typescript-eslint/no-explicit-any send(event: string, ...param: any[]): void { this.ipcLogger.logEvent({ direction: 'out', event, data: param[0] }); this.browserWindow.webContents.send(event, ...param); } focus() { this.browserWindow.focus(); } getBrowserWindow() { return this.browserWindow; } load() { this.browserWindow.loadURL(urlMapper[this.config.env]); return this.isReady; } minimize() { this.browserWindow.minimize(); } maximize() { if (this.platform.isMac()) { this.browserWindow.isFullScreen() ? this.browserWindow.setFullScreen(false) : this.browserWindow.setFullScreen(true); } else { this.browserWindow.isMaximized() ? this.browserWindow.unmaximize() : this.browserWindow.maximize(); } } minify() { // Unmaximize the window if it's maximized if (this.platform.isMac()) { this.browserWindow.isFullScreen() && this.browserWindow.setFullScreen(false); } else { this.browserWindow.isMaximized() && this.browserWindow.unmaximize(); } this.browserWindow.setSize(0, 0, true); } restoreDefaultSize() { this.browserWindow.setSize(this.defaultWidth, this.defaultHeight, true); } restore() { if (this.browserWindow.isMinimized()) { this.browserWindow.restore(); } } setTitle(title: string) { this.browserWindow.setTitle(title); } openDevTools() { if (this.browserWindow.webContents.isDevToolsOpened()) { this.browserWindow.webContents.closeDevTools(); } else { this.browserWindow.webContents.openDevTools(); } } async installDevTools() { try { await Promise.all([ installExtension(REACT_DEVELOPER_TOOLS), installExtension(REDUX_DEVTOOLS) ]); this.logger.log('devtools installed'); } catch (err) { this.logger.warn('something fails while trying to install devtools'); } } close() { this.browserWindow.close(); } } export default Window; ```
/content/code_sandbox/packages/main/src/services/window/index.ts
xml
2016-09-22T22:58:21
2024-08-16T15:47:39
nuclear
nukeop/nuclear
11,862
1,151
```xml import { Pipe, PipeTransform } from '@angular/core'; import { isString } from '../helpers/helpers'; @Pipe({ name: 'shorten' }) export class ShortenPipe implements PipeTransform { transform(input: string, length?: number, suffix?: string, wordBreak?: boolean): string; transform(input: any, length?: number, suffix?: string, wordBreak?: boolean): any; transform(text: any, length: number = 0, suffix: string = '', wordBreak: boolean = true): string { if (!isString(text)) { return text; } if (text.length > length) { if (wordBreak) { return text.slice(0, length) + suffix; } // tslint:disable-next-line:no-bitwise if (!!~text.indexOf(' ', length)) { return text.slice(0, text.indexOf(' ', length)) + suffix; } } return text; } } ```
/content/code_sandbox/src/ng-pipes/pipes/string/shorten.ts
xml
2016-11-24T22:03:44
2024-08-15T12:52:49
ngx-pipes
danrevah/ngx-pipes
1,589
203
```xml <?xml version="1.0" encoding="UTF-8" standalone="no"?> <document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="10117" systemVersion="15E65" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES"> <dependencies> <deployment identifier="iOS"/> <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/> </dependencies> <objects> <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/> <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/> <tableViewCell contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" rowHeight="334" id="KGk-i7-Jjw" customClass="YPLiveContentTableViewCell"> <rect key="frame" x="0.0" y="0.0" width="404" height="334"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/> <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="KGk-i7-Jjw" id="H2p-sc-9uM"> <rect key="frame" x="0.0" y="0.0" width="404" height="333"/> <autoresizingMask key="autoresizingMask"/> <subviews> <collectionView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" dataMode="none" translatesAutoresizingMaskIntoConstraints="NO" id="MUN-yc-cOs"> <rect key="frame" x="0.0" y="0.0" width="404" height="333"/> <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/> <collectionViewFlowLayout key="collectionViewLayout" minimumLineSpacing="10" minimumInteritemSpacing="10" id="miv-gp-Onf"> <size key="itemSize" width="50" height="50"/> <size key="headerReferenceSize" width="0.0" height="0.0"/> <size key="footerReferenceSize" width="0.0" height="0.0"/> <inset key="sectionInset" minX="0.0" minY="0.0" maxX="0.0" maxY="0.0"/> </collectionViewFlowLayout> <connections> <outlet property="dataSource" destination="KGk-i7-Jjw" id="lTc-ax-PZL"/> <outlet property="delegate" destination="KGk-i7-Jjw" id="8Fo-ZS-Y28"/> </connections> </collectionView> </subviews> <constraints> <constraint firstItem="MUN-yc-cOs" firstAttribute="leading" secondItem="H2p-sc-9uM" secondAttribute="leading" id="DEs-ql-eOS"/> <constraint firstItem="MUN-yc-cOs" firstAttribute="top" secondItem="H2p-sc-9uM" secondAttribute="top" id="Ta4-jX-Xgn"/> <constraint firstAttribute="bottom" secondItem="MUN-yc-cOs" secondAttribute="bottom" id="Yvg-gH-ZW5"/> <constraint firstAttribute="trailing" secondItem="MUN-yc-cOs" secondAttribute="trailing" id="tVV-Uy-feF"/> </constraints> </tableViewCellContentView> <connections> <outlet property="collectionView" destination="MUN-yc-cOs" id="xJW-yy-fZs"/> </connections> <point key="canvasLocation" x="406" y="380"/> </tableViewCell> </objects> </document> ```
/content/code_sandbox/Wuxianda/Classes/Src/Home/Sub/live/Views/YPLiveContentTableViewCell.xib
xml
2016-07-21T14:47:27
2024-08-15T07:32:25
Bilibili_Wuxianda
MichaelHuyp/Bilibili_Wuxianda
2,685
871
```xml import Settings from './containers/Settings'; import React from 'react'; import { Route, Routes, useLocation } from 'react-router-dom'; import asyncComponent from '@erxes/ui/src/components/AsyncComponent'; import queryString from 'query-string'; const GeneralSettings = asyncComponent(() => import( /* webpackChunkName: "GeneralSettings" */ './components/GeneralSettings' ) ); const StageSettings = asyncComponent(() => import( /* webpackChunkName: "StageSettings" */ './components/SaleStageSettings' ) ); const ReturnStageSettings = asyncComponent(() => import( /* webpackChunkName: "ReturnStageSettings" */ './components/ReturnStageSettings' ) ); const PipelineSettings = asyncComponent(() => import( /* webpackChunkName: "PipelineSettings" */ './components/RemPipelineSettings' ) ); const SyncHistoryList = asyncComponent(() => import( /* webpackChunkName: "CheckSyncedDeals" */ './containers/SyncHistoryList' ) ); const CheckSyncedDeals = asyncComponent(() => import( /* webpackChunkName: "CheckSyncedDeals" */ './containers/CheckSyncedDeals' ) ); const CheckSyncedOrders = asyncComponent(() => import( /* webpackChunkName: "CheckSyncedOrders" */ './containers/CheckSyncedOrders' ) ); const InventoryProducts = asyncComponent(() => import( /* webpackChunkName: "InventoryProducts" */ './containers/InventoryProducts' ) ); const InventoryCategory = asyncComponent(() => import( /* webpackChunkName: "InventoryCategors" */ './containers/InventoryCategory' ) ); const GeneralSetting = () => { return <Settings component={GeneralSettings} configCode="erkhetConfig" />; }; const StageSetting = () => { return <Settings component={StageSettings} configCode="stageInSaleConfig" />; }; const ReturnStageSetting = () => { return ( <Settings component={ReturnStageSettings} configCode="stageInReturnConfig" /> ); }; const PipelineSetting = () => { return <Settings component={PipelineSettings} configCode="remainderConfig" />; }; const SyncHistoryListComponent = () => { const location = useLocation() return ( <SyncHistoryList queryParams={queryString.parse(location.search)} /> ); }; const CheckSyncedDealList = () => { const location = useLocation() return ( <CheckSyncedDeals queryParams={queryString.parse(location.search)} /> ); }; const CheckSyncedOrderList = () => { const location = useLocation() return ( <CheckSyncedOrders queryParams={queryString.parse(location.search)} /> ); }; const InventoryProductList = () => { const location = useLocation() return ( <InventoryProducts queryParams={queryString.parse(location.search)} /> ); }; const InventoryCategoryList = () => { const location = useLocation() return ( <InventoryCategory queryParams={queryString.parse(location.search)} /> ); }; const routes = () => { return ( <Routes> <Route key="/erxes-plugin-multi-erkhet/settings/general" path="/erxes-plugin-multi-erkhet/settings/general" element={<GeneralSetting/>} /> <Route key="/erxes-plugin-multi-erkhet/settings/stage" path="/erxes-plugin-multi-erkhet/settings/stage" element={<StageSetting/>} /> <Route key="/erxes-plugin-multi-erkhet/settings/return-stage" path="/erxes-plugin-multi-erkhet/settings/return-stage" element={<ReturnStageSetting/>} /> <Route key="/erxes-plugin-multi-erkhet/settings/pipeline" path="/erxes-plugin-multi-erkhet/settings/pipeline" element={<PipelineSetting/>} /> <Route key="/multi-erkhet-history" path="/multi-erkhet-history" element={<SyncHistoryListComponent/>} /> <Route key="/check-multi-synced-deals" path="/check-multi-synced-deals" element={<CheckSyncedDealList/>} /> <Route key="/check-multi-pos-orders" path="/check-multi-pos-orders" element={<CheckSyncedOrderList/>} /> <Route key="/multi-inventory-products" path="/multi-inventory-products" element={<InventoryProductList/>} /> <Route key="/multi-inventory-category" path="/multi-inventory-category" element={<InventoryCategoryList/>} /> </Routes> ); }; export default routes; ```
/content/code_sandbox/packages/plugin-multierkhet-ui/src/routes.tsx
xml
2016-11-11T06:54:50
2024-08-16T10:26:06
erxes
erxes/erxes
3,479
1,005
```xml <?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="path_to_url"> <Import Condition="'$(ChakraBuildPathImported)'!='true'" Project="$(SolutionDir)Chakra.Build.Paths.props"/> <Import Project="$(BuildConfigPropsPath)Chakra.Build.ProjectConfiguration.props" /> <PropertyGroup Label="Globals"> <ProjectGuid>{2F6A1847-BFAF-4B8A-9463-AC39FB46B96A}</ProjectGuid> <RootNamespace>CoreManifests</RootNamespace> </PropertyGroup> <PropertyGroup Label="Configuration"> <ConfigurationType>Utility</ConfigurationType> </PropertyGroup> <Import Project="$(BuildConfigPropsPath)Chakra.Build.Default.props" /> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <Import Project="$(BuildConfigPropsPath)Chakra.Build.props" /> <ItemGroup> <CustomBuild Include="$(MSBuildThisFileDirectory)Microsoft-Scripting-Chakra-Instrumentation.man"> <FileType>Document</FileType> <Command>mc.exe /h "$(IntDir)." /W "$(EventManifestXmlPath)\winmeta.xml" /w "$(EventManifestXmlPath)\eventman.xsd" /r "$(IntDir)." /z %(Filename)Events -um /v "%(FullPath)"</Command> <Outputs>$(IntDir)\%(Filename)Events.h;$(IntDir)\%(Filename)Events.rc;$(IntDir)\%(Filename)Events_MSG00001.bin;$(IntDir)\%(Filename)EventsTEMP.bin</Outputs> </CustomBuild> </ItemGroup> <ItemGroup Label="Publish"> <PublishGenerated Include="$(ObjectPath)$(ObjectDirectory)\microsoft-scripting-chakra-instrumentationevents.h"> <DestinationFile>$(ProjectIncPath)\microsoft-scripting-chakra-instrumentationevents.h</DestinationFile> </PublishGenerated> </ItemGroup> <Import Project="$(BuildConfigPropsPath)Chakra.Build.targets" Condition="exists('$(BuildConfigPropsPath)Chakra.Build.targets')"/> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> </Project> ```
/content/code_sandbox/manifests/CoreManifests.vcxproj
xml
2016-01-05T19:05:31
2024-08-16T17:20:00
ChakraCore
chakra-core/ChakraCore
9,079
504
```xml <?xml version="1.0" encoding="utf-8"?> <RadioGroup xmlns:android="path_to_url" android:id="@+id/radio_group_themes" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <RadioButton android:id="@+id/theme_system" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/theme_system" /> <RadioButton android:id="@+id/theme_black" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/theme_black" /> <RadioButton android:id="@+id/theme_dark" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/theme_dark" /> <RadioButton android:id="@+id/theme_white" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/theme_white" /> </RadioGroup> ```
/content/code_sandbox/app/src/main/res/layout/dialog_theme_default.xml
xml
2016-02-22T10:00:46
2024-08-16T15:37:50
Images-to-PDF
Swati4star/Images-to-PDF
1,174
227
```xml <?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.Toolbar xmlns:android="path_to_url" xmlns:app="path_to_url" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="@android:color/transparent" android:theme="@style/Theme.AppCompat" app:layout_scrollFlags="scroll|enterAlways" app:popupTheme="@style/AppTheme.PopupOverlay" /> ```
/content/code_sandbox/app/src/main/res/layout/toolbar.xml
xml
2016-06-02T11:11:55
2024-08-02T07:34:23
AlgorithmVisualizer-Android
naman14/AlgorithmVisualizer-Android
1,129
117
```xml import { c } from 'ttag'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { SettingsParagraph, SettingsSectionWide } from '../account'; import Spams from './spams/Spams'; const SpamFiltersSection = () => ( <SettingsSectionWide> <SettingsParagraph learnMoreUrl={getKnowledgeBaseUrl('/spam-filtering')}> {c('FilterSettings').t`Take control over what lands in your inbox by creating the following lists:`} <ul className="mt-2 mb-0"> <li> <strong>{c('FilterSettings').t`Spam:`}</strong>{' '} {c('FilterSettings').t`To prevent junk mail from clogging up your inbox`} </li> <li> <strong>{c('FilterSettings').t`Block:`}</strong>{' '} {c('FilterSettings').t`To stop phishing or suspicious emails from entering your email system`} </li> <li> <strong>{c('FilterSettings').t`Allow:`}</strong>{' '} {c('FilterSettings').t`To ensure critical messages don't end up in spam and getting missed`} </li> </ul> </SettingsParagraph> <Spams /> </SettingsSectionWide> ); export default SpamFiltersSection; ```
/content/code_sandbox/packages/components/containers/filters/SpamFiltersSection.tsx
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
285
```xml <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="path_to_url"> <PropertyGroup> <IncludePath>$(MSBuildThisFileDirectory);$(IncludePath)</IncludePath> </PropertyGroup> <ItemDefinitionGroup> <Link> <AdditionalDependencies>$(OutDir)MoPlugin.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> </ItemDefinitionGroup> </Project> ```
/content/code_sandbox/Source/Native/MouriOptimizationPlugin/MouriOptimizationPlugin.props
xml
2016-06-29T07:49:09
2024-08-16T15:36:29
NSudo
M2TeamArchived/NSudo
1,833
101
```xml import * as React from 'react'; import AsyncStorage from '@react-native-async-storage/async-storage'; import { createDrawerNavigator } from '@react-navigation/drawer'; import { InitialState, NavigationContainer, DarkTheme as NavigationDarkTheme, DefaultTheme as NavigationDefaultTheme, } from '@react-navigation/native'; import { useFonts } from 'expo-font'; import { useKeepAwake } from 'expo-keep-awake'; import { PaperProvider, MD3DarkTheme, MD3LightTheme, MD2DarkTheme, MD2LightTheme, MD2Theme, MD3Theme, useTheme, adaptNavigationTheme, configureFonts, } from 'react-native-paper'; import { SafeAreaInsetsContext } from 'react-native-safe-area-context'; import DrawerItems from './DrawerItems'; import App from './RootNavigator'; const PERSISTENCE_KEY = 'NAVIGATION_STATE'; const PREFERENCES_KEY = 'APP_PREFERENCES'; export const PreferencesContext = React.createContext<{ toggleTheme: () => void; toggleThemeVersion: () => void; toggleCollapsed: () => void; toggleCustomFont: () => void; toggleRippleEffect: () => void; customFontLoaded: boolean; rippleEffectEnabled: boolean; collapsed: boolean; theme: MD2Theme | MD3Theme; } | null>(null); export const useExampleTheme = () => useTheme<MD2Theme | MD3Theme>(); const Drawer = createDrawerNavigator<{ Home: undefined }>(); export default function PaperExample() { useKeepAwake(); const [fontsLoaded] = useFonts({ Abel: require('../assets/fonts/Abel-Regular.ttf'), }); const [isReady, setIsReady] = React.useState(false); const [initialState, setInitialState] = React.useState< InitialState | undefined >(); const [isDarkMode, setIsDarkMode] = React.useState(false); const [themeVersion, setThemeVersion] = React.useState<2 | 3>(3); const [collapsed, setCollapsed] = React.useState(false); const [customFontLoaded, setCustomFont] = React.useState(false); const [rippleEffectEnabled, setRippleEffectEnabled] = React.useState(true); const theme = React.useMemo(() => { if (themeVersion === 2) { return isDarkMode ? MD2DarkTheme : MD2LightTheme; } return isDarkMode ? MD3DarkTheme : MD3LightTheme; }, [isDarkMode, themeVersion]); React.useEffect(() => { const restoreState = async () => { try { const savedStateString = await AsyncStorage.getItem(PERSISTENCE_KEY); const state = JSON.parse(savedStateString || ''); setInitialState(state); } catch (e) { // ignore error } finally { setIsReady(true); } }; if (!isReady) { restoreState(); } }, [isReady]); React.useEffect(() => { const restorePrefs = async () => { try { const prefString = await AsyncStorage.getItem(PREFERENCES_KEY); const preferences = JSON.parse(prefString || ''); if (preferences) { setIsDarkMode(preferences.theme === 'dark'); } } catch (e) { // ignore error } }; restorePrefs(); }, []); React.useEffect(() => { const savePrefs = async () => { try { await AsyncStorage.setItem( PREFERENCES_KEY, JSON.stringify({ theme: isDarkMode ? 'dark' : 'light', }) ); } catch (e) { // ignore error } }; savePrefs(); }, [isDarkMode]); const preferences = React.useMemo( () => ({ toggleTheme: () => setIsDarkMode((oldValue) => !oldValue), toggleCollapsed: () => setCollapsed(!collapsed), toggleCustomFont: () => setCustomFont(!customFontLoaded), toggleRippleEffect: () => setRippleEffectEnabled(!rippleEffectEnabled), toggleThemeVersion: () => { setCustomFont(false); setCollapsed(false); setThemeVersion((oldThemeVersion) => (oldThemeVersion === 2 ? 3 : 2)); setRippleEffectEnabled(true); }, customFontLoaded, rippleEffectEnabled, collapsed, theme, }), [theme, collapsed, customFontLoaded, rippleEffectEnabled] ); if (!isReady && !fontsLoaded) { return null; } const { LightTheme, DarkTheme } = adaptNavigationTheme({ reactNavigationLight: NavigationDefaultTheme, reactNavigationDark: NavigationDarkTheme, }); const CombinedDefaultTheme = { ...MD3LightTheme, ...LightTheme, colors: { ...MD3LightTheme.colors, ...LightTheme.colors, }, }; const CombinedDarkTheme = { ...MD3DarkTheme, ...DarkTheme, colors: { ...MD3DarkTheme.colors, ...DarkTheme.colors, }, }; const combinedTheme = isDarkMode ? CombinedDarkTheme : CombinedDefaultTheme; const configuredFontTheme = { ...combinedTheme, fonts: configureFonts({ config: { fontFamily: 'Abel', }, }), }; return ( <PaperProvider settings={{ rippleEffectEnabled: preferences.rippleEffectEnabled }} theme={customFontLoaded ? configuredFontTheme : theme} > <PreferencesContext.Provider value={preferences}> <React.Fragment> <NavigationContainer theme={combinedTheme} initialState={initialState} onStateChange={(state) => AsyncStorage.setItem(PERSISTENCE_KEY, JSON.stringify(state)) } > <SafeAreaInsetsContext.Consumer> {(insets) => { const { left, right } = insets || { left: 0, right: 0 }; const collapsedDrawerWidth = 80 + Math.max(left, right); return ( <Drawer.Navigator screenOptions={{ drawerStyle: collapsed && { width: collapsedDrawerWidth, }, }} drawerContent={() => <DrawerItems />} > <Drawer.Screen name="Home" component={App} options={{ headerShown: false }} /> </Drawer.Navigator> ); }} </SafeAreaInsetsContext.Consumer> </NavigationContainer> </React.Fragment> </PreferencesContext.Provider> </PaperProvider> ); } ```
/content/code_sandbox/example/src/index.tsx
xml
2016-10-19T05:56:53
2024-08-16T08:48:04
react-native-paper
callstack/react-native-paper
12,646
1,396
```xml import { c } from 'ttag'; import { Href } from '@proton/atoms/Href'; import { Toggle } from '@proton/components/components'; import type { SampleBreach } from '@proton/components/containers'; import { getUpsellText } from '@proton/components/containers/credentialLeak/helpers'; import { DARK_WEB_MONITORING_NAME } from '@proton/shared/lib/constants'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import ProtonSentinelPlusLogo from '@proton/styles/assets/img/illustrations/sentinel-shield-bolt-breach-alert.svg'; import { DrawerAppSection } from '../../shared'; interface Props { onToggleBreaches: () => void; hasBreach: boolean; sample: SampleBreach | null; count: number | null; } // translator: full sentence is: Get notified if your password or other data was leaked from a third-party service. <Learn more> const learnMoreLink = ( <Href href={getKnowledgeBaseUrl('/dark-web-monitoring')} className="inline-block">{c('Link').t`Learn more`}</Href> ); const learnMoreLinkBreach = ( <Href href={getKnowledgeBaseUrl('/dark-web-monitoring')} className="inline-block color-danger">{c('Link') .t`Learn more`}</Href> ); const FreeUserBreachToggle = ({ onToggleBreaches, hasBreach, sample, count }: Props) => { return ( <DrawerAppSection> <div className="flex flex-nowrap items-center gap-2 mt-2"> <div className="shrink-0 flex"> <img src={ProtonSentinelPlusLogo} alt="" width={22} /> </div> <h3 className="flex-1 text-rg"> <label htmlFor="breaches-toggle">{DARK_WEB_MONITORING_NAME}</label> </h3> <Toggle id="breaches-toggle" onChange={onToggleBreaches} className="shrink-0" /> </div> {hasBreach ? ( <p className="mt-1 mb-2 text-sm color-danger">{getUpsellText(sample, count, learnMoreLinkBreach)}</p> ) : ( <p className="mt-1 mb-2 text-sm color-weak"> { // translator: full sentence is: Get notified if your password or other data was leaked from a third-party service. <Learn more> c('Security Center - Info') .jt`Get notified if your password or other data was leaked from a third-party service. ${learnMoreLink}` } </p> )} </DrawerAppSection> ); }; export default FreeUserBreachToggle; ```
/content/code_sandbox/packages/components/components/drawer/views/SecurityCenter/BreachAlerts/FreeUserBreachToggle.tsx
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
584
```xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="path_to_url" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/shape_white_corner4" android:orientation="vertical" android:paddingBottom="10dp" android:paddingLeft="24dp" android:paddingRight="24dp" android:paddingTop="20dp"> <TextView android:id="@+id/edit_dialog_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="@color/black_light" android:textSize="20sp"/> <EditText android:layout_weight="1" android:gravity="bottom|left" android:id="@+id/edit_dialog_exittext" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:background="@null" android:textSize="18sp" /> <View android:id="@+id/edit_dialog_line" android:layout_width="match_parent" android:layout_height="1.5dp" android:layout_marginTop="2dp" android:background="@color/black_light" android:layout_marginBottom="15dp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="right" android:orientation="horizontal" android:paddingBottom="5dp" android:paddingTop="5dp"> <TextView android:id="@+id/edit_dialog_leftbtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/selector_widget_md_dialog" android:clickable="true" android:gravity="center_horizontal" android:minWidth="55dp" android:paddingBottom="6dp" android:paddingLeft="3dp" android:paddingRight="3dp" android:paddingTop="6dp" android:text="" android:textColor="@color/black_light" android:textSize="16sp" /> <TextView android:id="@+id/edit_dialog_rightbtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="8dp" android:background="@drawable/selector_widget_md_dialog" android:clickable="true" android:gravity="center_horizontal" android:maxWidth="90dp" android:minWidth="55dp" android:paddingBottom="6dp" android:paddingLeft="3dp" android:paddingRight="3dp" android:paddingTop="6dp" android:text="" android:textColor="@color/black_light" android:textSize="16sp" /> </LinearLayout> </LinearLayout> ```
/content/code_sandbox/library/selectordialog/src/main/res/layout/widget_edit_dialog.xml
xml
2016-09-26T09:42:41
2024-08-12T07:09:06
AndroidFire
jaydenxiao2016/AndroidFire
2,634
628
```xml // @ts-nocheck import { Flex, Tag, TagLabel } from '@chakra-ui/react'; import { chakraComponents } from 'chakra-react-select'; import { ReactElement } from 'react'; import { findType } from 'renderer/defenitions/record-object/data-types'; export const ReactSelectColumnOption = { Option: ({ children, ...properties }: { children: ReactElement; data: { type: string }; }) => ( <chakraComponents.Option {...properties}> <Flex justifyContent="space-between" w="100%"> {children} {properties.data && properties.data.type && ( <Tag variant="subtle" colorScheme="primary" size="sm" textTransform="uppercase" > <TagLabel>{findType(properties.data.type).name}</TagLabel> </Tag> )} </Flex> </chakraComponents.Option> ), }; ```
/content/code_sandbox/src/renderer/containers/filter-builder/components/react-select-column-option.tsx
xml
2016-05-14T02:18:49
2024-08-16T02:46:28
ElectroCRUD
garrylachman/ElectroCRUD
1,538
203
```xml import { GreetingService } from "./Greetings.service"; export class GreetingController { public userName: string = ""; public userJobTitle: string = ""; public webSiteTitle: string = ""; public welComeMessage: string = ""; public userImageUrl: string = ""; public greetingMessage: string = ""; public prefixWelcomeMessage: string = "Welcome to "; public static $inject: string[] = ["GreetingService", "$scope"]; constructor( // tslint:disable-next-line: no-shadowed-variable private GreetingService: GreetingService, private $scope: ng.IScope ) { this.$scope.$on( "configurationChangedGreetingWebPart", (event: ng.IAngularEvent, data: any) => { this.webSiteTitle = data.webTitle; this.userName = data.userDisplayName; this.getValues(); console.log(this.userImageUrl); //this.$scope.$apply(); } ); this.getValues(); } public getValues = () => { if (new Date().getHours() > 0 && new Date().getHours() < 12) this.greetingMessage = "Good Morning "; else if (new Date().getHours() >= 12 && new Date().getHours() <= 5) this.greetingMessage = "Good Afternoon "; else if (new Date().getHours() > 5) this.greetingMessage = "Good Evening "; if (this.userName.length == 0) this.userName = "Gaurav Goyal"; if (this.userJobTitle.length == 0) this.userJobTitle = ""; if (this.webSiteTitle.length == 0) this.webSiteTitle = this.prefixWelcomeMessage + "Demo of SPFx Web Part"; if (this.welComeMessage.length == 0) this.welComeMessage = this.greetingMessage + this.userName; // if (this.userImageUrl.length == 0) // this.userImageUrl =""; this.getCurrentUserInformation(); } public getCurrentUserInformation = () => { this.GreetingService.getCurrentUserInformation().then(ig => { this.webSiteTitle = this.prefixWelcomeMessage + this.webSiteTitle; this.userImageUrl = ig.userImageUrl; //this.userName = this.userName; this.userJobTitle = ig.userJobTitle; this.$scope.$apply(); }); } } export let GreetingComponent = { selector: "greetingComponent", template: require("./Greetings.component.html").toString(), bindings: {}, controller: GreetingController, styles:require("./Greeting.module.css").toString() }; ```
/content/code_sandbox/samples/angular-greeting/src/webparts/greetingsWebpart/app/Greetings.component.ts
xml
2016-08-30T17:21:43
2024-08-16T18:41:32
sp-dev-fx-webparts
pnp/sp-dev-fx-webparts
2,027
566
```xml <?xml version="1.0" encoding="UTF-8"?> <document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11542" systemVersion="16B2657" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="01J-lp-oVM"> <device id="retina4_7" orientation="portrait"> <adaptation id="fullscreen"/> </device> <dependencies> <deployment identifier="iOS"/> <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11524"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <scenes> <!--View Controller--> <scene sceneID="EHf-IW-A2E"> <objects> <viewController id="01J-lp-oVM" sceneMemberID="viewController"> <layoutGuides> <viewControllerLayoutGuide type="top" id="Llm-lL-Icb"/> <viewControllerLayoutGuide type="bottom" id="xb3-aO-Qok"/> </layoutGuides> <view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3"> <rect key="frame" x="0.0" y="0.0" width="375" height="667"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <color key="backgroundColor" red="0.96078431372549022" green="0.96078431372549022" blue="0.96078431372549022" alpha="1" colorSpace="calibratedRGB"/> </view> </viewController> <placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/> </objects> <point key="canvasLocation" x="53" y="375"/> </scene> </scenes> </document> ```
/content/code_sandbox/TouchBarClient/Base.lproj/LaunchScreen.storyboard
xml
2016-11-04T13:54:34
2024-07-30T06:54:33
TouchBarDemoApp
bikkelbroeders/TouchBarDemoApp
1,656
480
```xml import './fit-textareas.css'; import {isSafari} from 'webext-detect'; import fitTextarea from 'fit-textarea'; import * as pageDetect from 'github-url-detection'; import features from '../feature-manager.js'; import observe from '../helpers/selector-observer.js'; const nativeFit = CSS.supports('field-sizing', 'content'); function resetListener({target}: Event): void { const field = (target as HTMLFormElement).querySelector('textarea')!; // Delay because the field is still filled while the `reset` event is firing setTimeout(fitTextarea, 0, field); } function inputListener({target}: Event): void { fitTextarea(target as HTMLTextAreaElement); } function watchTextarea(textarea: HTMLTextAreaElement, {signal}: SignalAsOptions): void { // Disable constrained GitHub feature textarea.classList.remove('js-size-to-fit'); textarea.classList.remove('issue-form-textarea'); // Remove !important height and min-height textarea.classList.add('rgh-fit-textareas'); if (nativeFit) { return; } textarea.addEventListener('input', inputListener, {signal}); // The user triggers `input` event textarea.addEventListener('focus', inputListener, {signal}); // The user triggers `focus` event textarea.addEventListener('change', inputListener, {signal}); // File uploads trigger `change` events textarea.form?.addEventListener('reset', resetListener, {signal}); fitTextarea(textarea); } function init(signal: AbortSignal): void { // `anchored-position`: Exclude PR review box because it's in a `position:fixed` container; The scroll HAS to appear within the fixed element. // `#pull_request_body_ghost`: Special textarea that GitHub just matches to the visible textarea observe(` textarea:not( anchored-position #pull_request_review_body, #pull_request_body_ghost, #pull_request_body_ghost_ruler ) `, watchTextarea, {signal}); } void features.add(import.meta.url, { include: [ pageDetect.hasRichTextEditor, ], exclude: [ // Allow Safari only if it supports the native version () => isSafari() && !nativeFit, ], init, }); /* Test URLs: path_to_url */ ```
/content/code_sandbox/source/features/fit-textareas.tsx
xml
2016-02-15T16:45:02
2024-08-16T18:39:26
refined-github
refined-github/refined-github
24,013
486
```xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="path_to_url" package="com.vincent.filepickersample"> <application android:name=".TheApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> ```
/content/code_sandbox/app/src/main/AndroidManifest.xml
xml
2016-10-26T08:46:20
2024-08-02T07:35:09
MultiType-FilePicker
fishwjy/MultiType-FilePicker
1,398
149
```xml import { NgModule } from "@angular/core"; import { SecretsManagerSharedModule } from "../shared/sm-shared.module"; import { SecretsManagerImportErrorDialogComponent } from "./dialog/sm-import-error-dialog.component"; import { SecretsManagerExportComponent } from "./porting/sm-export.component"; import { SecretsManagerImportComponent } from "./porting/sm-import.component"; import { SecretsManagerPortingService } from "./services/sm-porting.service"; import { SettingsRoutingModule } from "./settings-routing.module"; @NgModule({ imports: [SecretsManagerSharedModule, SettingsRoutingModule], declarations: [ SecretsManagerImportComponent, SecretsManagerExportComponent, SecretsManagerImportErrorDialogComponent, ], providers: [SecretsManagerPortingService], }) export class SettingsModule {} ```
/content/code_sandbox/bitwarden_license/bit-web/src/app/secrets-manager/settings/settings.module.ts
xml
2016-03-09T23:14:01
2024-08-16T15:07:51
clients
bitwarden/clients
8,877
157
```xml /* * This software is released under MIT license. * The full license information can be found in LICENSE in the root directory of this project. */ import { renderIcon } from '../icon.renderer.js'; import { IconShapeTuple } from '../interfaces/icon.interfaces.js'; const icon = { outline: '<path d="M15.34,26.45a.8.8,0,0,0-1.13,0,.79.79,0,0,0,0,1.13L18,31.09l3.74-3.47a.79.79,0,0,0,.05-1.13.8.8,0,0,0-1.13,0L18.8,28.17V7.83l1.86,1.72a.8.8,0,1,0,1.08-1.17L18,4.91,14.26,8.38a.79.79,0,0,0,0,1.13.8.8,0,0,0,1.13,0L17.2,7.83V28.17Z"/><path d="M28,2H8A2,2,0,0,0,6,4V32a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V4A2,2,0,0,0,28,2Zm0,30H8V4H28Z"/>', solid: '<path d="M28,2H8A2,2,0,0,0,6,4V32a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V4A2,2,0,0,0,28,2ZM20.52,26.3a1,1,0,0,1,1.36,1.47L18,31.36l-3.88-3.59a1,1,0,0,1,1.36-1.47L17,27.71V8.29L15.48,9.7a1,1,0,0,1-1.36-1.47L18,4.64l3.88,3.59a1,1,0,0,1,.05,1.41,1,1,0,0,1-.73.32,1,1,0,0,1-.68-.26L19,8.29V27.71Z"/>', }; export const portraitIconName = 'portrait'; export const portraitIcon: IconShapeTuple = [portraitIconName, renderIcon(icon)]; ```
/content/code_sandbox/packages/core/src/icon/shapes/portrait.ts
xml
2016-09-29T17:24:17
2024-08-11T17:06:15
clarity
vmware-archive/clarity
6,431
610
```xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="path_to_url" xmlns:app="path_to_url" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <com.kofigyan.stateprogressbar.StateProgressBar android:id="@+id/state_progress_bar" android:layout_width="wrap_content" android:layout_height="wrap_content" app:spb_descriptionTopSpaceIncrementer="2dp" app:spb_stateDescriptionSize="20sp" app:spb_stateLineThickness="10dp" app:spb_stateSize="40dp" app:spb_stateTextSize="15sp" /> </LinearLayout> ```
/content/code_sandbox/sample/src/main/res/layout/activity_changing_states_size.xml
xml
2016-08-16T12:50:30
2024-08-13T08:27:46
StateProgressBar
kofigyan/StateProgressBar
1,537
166
```xml import React from 'react' import { View } from 'react-native' import { Theme, ThemeColors } from '@devhub/core' import { sharedStyles } from '../../styles/shared' import { useTheme } from '../context/ThemeContext' import { getThemeColorOrItself } from '../themed/helpers' import { GradientLayerOverlay } from './GradientLayerOverlay' import { GradientLayerOverlayProps, ToWithVH, } from './GradientLayerOverlay.shared' export interface TransparentTextOverlayProps extends Omit<GradientLayerOverlayProps, 'to' | 'color'> { to: ToWithVH themeColor: keyof ThemeColors | ((theme: Theme) => string | undefined) } export const TransparentTextOverlay = React.memo( React.forwardRef<View, TransparentTextOverlayProps>((props, ref) => { const { children, containerStyle, themeColor: _themeColor, to, ...otherProps } = props const theme = useTheme() const color = getThemeColorOrItself(theme, _themeColor, { enableCSSVariable: false, }) if (!color) return null return ( <View ref={ref} collapsable={false} pointerEvents="box-none" style={[ sharedStyles.flex, { alignSelf: 'stretch', flexBasis: 'auto' }, containerStyle, ]} > {(to === 'vertical' || to === 'bottom') && ( <GradientLayerOverlay {...otherProps} color={color} to="bottom" /> )} {(to === 'vertical' || to === 'top') && ( <GradientLayerOverlay {...otherProps} color={color} to="top" /> )} {(to === 'horizontal' || to === 'right') && ( <GradientLayerOverlay {...otherProps} color={color} to="right" /> )} {(to === 'horizontal' || to === 'left') && ( <GradientLayerOverlay {...otherProps} color={color} to="left" /> )} {children} </View> ) }), ) TransparentTextOverlay.displayName = 'TransparentTextOverlay' ```
/content/code_sandbox/packages/components/src/components/common/TransparentTextOverlay.tsx
xml
2016-11-30T23:24:21
2024-08-16T00:24:59
devhub
devhubapp/devhub
9,652
469
```xml /* your_sha256_hash------------- |your_sha256_hash------------*/ import { CellType } from '@jupyterlab/nbformat'; import { IDataConnector } from '@jupyterlab/statedb'; import { PartialJSONObject, PartialJSONValue, ReadonlyPartialJSONObject, ReadonlyPartialJSONValue, Token } from '@lumino/coreutils'; import { IDisposable } from '@lumino/disposable'; import { ISignal } from '@lumino/signaling'; import { ISchemaValidator } from './settingregistry'; import type { RJSFSchema, UiSchema } from '@rjsf/utils'; /** * The setting registry token. */ export const ISettingRegistry = new Token<ISettingRegistry>( '@jupyterlab/coreutils:ISettingRegistry', `A service for the JupyterLab settings system. Use this if you want to store settings for your application. See "schemaDir" for more information.` ); /** * The settings registry interface. */ export interface ISettingRegistry { /** * The data connector used by the setting registry. */ readonly connector: IDataConnector<ISettingRegistry.IPlugin, string, string>; /** * The schema of the setting registry. */ readonly schema: ISettingRegistry.ISchema; /** * The schema validator used by the setting registry. */ readonly validator: ISchemaValidator; /** * A signal that emits the name of a plugin when its settings change. */ readonly pluginChanged: ISignal<this, string>; /** * The collection of setting registry plugins. */ readonly plugins: { [name: string]: ISettingRegistry.IPlugin | undefined; }; /** * Get an individual setting. * * @param plugin - The name of the plugin whose settings are being retrieved. * * @param key - The name of the setting being retrieved. * * @returns A promise that resolves when the setting is retrieved. */ get( plugin: string, key: string ): Promise<{ composite: PartialJSONValue | undefined; user: PartialJSONValue | undefined; }>; /** * Load a plugin's settings into the setting registry. * * @param plugin - The name of the plugin whose settings are being loaded. * * @param forceTransform - An optional parameter to force replay the transforms methods. * * @returns A promise that resolves with a plugin settings object or rejects * if the plugin is not found. */ load( plugin: string, forceTransform?: boolean ): Promise<ISettingRegistry.ISettings>; /** * Reload a plugin's settings into the registry even if they already exist. * * @param plugin - The name of the plugin whose settings are being reloaded. * * @returns A promise that resolves with a plugin settings object or rejects * with a list of `ISchemaValidator.IError` objects if it fails. */ reload(plugin: string): Promise<ISettingRegistry.ISettings>; /** * Remove a single setting in the registry. * * @param plugin - The name of the plugin whose setting is being removed. * * @param key - The name of the setting being removed. * * @returns A promise that resolves when the setting is removed. */ remove(plugin: string, key: string): Promise<void>; /** * Set a single setting in the registry. * * @param plugin - The name of the plugin whose setting is being set. * * @param key - The name of the setting being set. * * @param value - The value of the setting being set. * * @returns A promise that resolves when the setting has been saved. * */ set(plugin: string, key: string, value: PartialJSONValue): Promise<void>; /** * Register a plugin transform function to act on a specific plugin. * * @param plugin - The name of the plugin whose settings are transformed. * * @param transforms - The transform functions applied to the plugin. * * @returns A disposable that removes the transforms from the registry. * * #### Notes * - `compose` transformations: The registry automatically overwrites a * plugin's default values with user overrides, but a plugin may instead wish * to merge values. This behavior can be accomplished in a `compose` * transformation. * - `fetch` transformations: The registry uses the plugin data that is * fetched from its connector. If a plugin wants to override, e.g. to update * its schema with dynamic defaults, a `fetch` transformation can be applied. */ transform( plugin: string, transforms: { [phase in ISettingRegistry.IPlugin.Phase]?: ISettingRegistry.IPlugin.Transform; } ): IDisposable; /** * Upload a plugin's settings. * * @param plugin - The name of the plugin whose settings are being set. * * @param raw - The raw plugin settings being uploaded. * * @returns A promise that resolves when the settings have been saved. */ upload(plugin: string, raw: string): Promise<void>; } /** * A namespace for setting registry interfaces. */ export namespace ISettingRegistry { /** * The primitive types available in a JSON schema. */ export type Primitive = | 'array' | 'boolean' | 'null' | 'number' | 'object' | 'string'; /** * The menu ids defined by default. */ export type DefaultMenuId = | 'jp-menu-file' | 'jp-menu-file-new' | 'jp-menu-edit' | 'jp-menu-help' | 'jp-menu-kernel' | 'jp-menu-run' | 'jp-menu-settings' | 'jp-menu-view' | 'jp-menu-tabs'; /** * An interface defining a menu. */ export interface IMenu extends PartialJSONObject { /** * Unique menu identifier */ id: DefaultMenuId | string; /** * Menu items */ items?: IMenuItem[]; /** * The rank order of the menu among its siblings. */ rank?: number; /** * Menu title * * #### Notes * Default will be the capitalized id. */ label?: string; /** * Menu icon id * * #### Note * The icon id will looked for in registered LabIcon. */ icon?: string; /** * Get the mnemonic index for the title. * * #### Notes * The default value is `-1`. */ mnemonic?: number; /** * Whether a menu is disabled. `False` by default. * * #### Notes * This allows an user to suppress a menu. */ disabled?: boolean; } /** * An interface describing a menu item. */ export interface IMenuItem extends PartialJSONObject { /** * The type of the menu item. * * The default value is `'command'`. */ type?: 'command' | 'submenu' | 'separator'; /** * The command to execute when the item is triggered. * * The default value is an empty string. */ command?: string; /** * The arguments for the command. * * The default value is an empty object. */ args?: PartialJSONObject; /** * The rank order of the menu item among its siblings. */ rank?: number; /** * The submenu for a `'submenu'` type item. * * The default value is `null`. */ submenu?: IMenu | null; /** * Whether a menu item is disabled. `false` by default. * * #### Notes * This allows an user to suppress menu items. */ disabled?: boolean; } /** * An interface describing a context menu item */ export interface IContextMenuItem extends IMenuItem { /** * The CSS selector for the context menu item. * * The context menu item will only be displayed in the context menu * when the selector matches a node on the propagation path of the * contextmenu event. This allows the menu item to be restricted to * user-defined contexts. * * The selector must not contain commas. */ selector: string; } /** * The settings for a specific plugin. */ export interface IPlugin extends PartialJSONObject { /** * The name of the plugin. */ id: string; /** * The collection of values for a specified plugin. */ data: ISettingBundle; /** * The raw user settings data as a string containing JSON with comments. */ raw: string; /** * The JSON schema for the plugin. */ schema: ISchema; /** * The published version of the NPM package containing the plugin. */ version: string; } /** * A namespace for plugin functionality. */ export namespace IPlugin { /** * A function that transforms a plugin object before it is consumed by the * setting registry. */ export type Transform = (plugin: IPlugin) => IPlugin; /** * The phases during which a transformation may be applied to a plugin. */ export type Phase = 'compose' | 'fetch'; } /** * A minimal subset of the formal JSON Schema that describes a property. */ export interface IProperty extends PartialJSONObject { /** * The default value, if any. */ default?: PartialJSONValue; /** * The schema description. */ description?: string; /** * The schema's child properties. */ properties?: { [property: string]: IProperty }; /** * The title of a property. */ title?: string; /** * The type or types of the data. */ type?: Primitive | Primitive[]; } /** * A schema type that is a minimal subset of the formal JSON Schema along with * optional JupyterLab rendering hints. */ export interface ISchema extends IProperty { /** * The JupyterLab menus that are created by a plugin's schema. */ 'jupyter.lab.menus'?: { main: IMenu[]; context: IContextMenuItem[]; }; /** * Whether the schema is deprecated. * * #### Notes * This flag can be used by functionality that loads this plugin's settings * from the registry. For example, the setting editor does not display a * plugin's settings if it is set to `true`. */ 'jupyter.lab.setting-deprecated'?: boolean; /** * The JupyterLab icon hint. */ 'jupyter.lab.setting-icon'?: string; /** * The JupyterLab icon class hint. */ 'jupyter.lab.setting-icon-class'?: string; /** * The JupyterLab icon label hint. */ 'jupyter.lab.setting-icon-label'?: string; /** * The JupyterLab toolbars created by a plugin's schema. * * #### Notes * The toolbar items are grouped by document or widget factory name * that will contain a toolbar. */ 'jupyter.lab.toolbars'?: { [factory: string]: IToolbarItem[] }; /** * A flag that indicates plugin should be transformed before being used by * the setting registry. * * #### Notes * If this value is set to `true`, the setting registry will wait until a * transformation has been registered (by calling the `transform()` method * of the registry) for the plugin ID before resolving `load()` promises. * This means that if the attribute is set to `true` but no transformation * is registered in time, calls to `load()` a plugin will eventually time * out and reject. */ 'jupyter.lab.transform'?: boolean; /** * The JupyterLab shortcuts that are created by a plugin's schema. */ 'jupyter.lab.shortcuts'?: IShortcut[]; /** * The JupyterLab metadata-form schema */ 'jupyter.lab.metadataforms'?: IMetadataForm[]; /** * The root schema is always an object. */ type: 'object'; } /** * The setting values for a plugin. */ export interface ISettingBundle extends PartialJSONObject { /** * A composite of the user setting values and the plugin schema defaults. * * #### Notes * The `composite` values will always be a superset of the `user` values. */ composite: PartialJSONObject; /** * The user setting values. */ user: PartialJSONObject; } /** * An interface for manipulating the settings of a specific plugin. */ export interface ISettings< O extends ReadonlyPartialJSONObject = ReadonlyPartialJSONObject > extends IDisposable { /** * A signal that emits when the plugin's settings have changed. */ readonly changed: ISignal<this, void>; /** * The composite of user settings and extension defaults. */ readonly composite: O; /** * The plugin's ID. */ readonly id: string; /* * The underlying plugin. */ readonly plugin: ISettingRegistry.IPlugin; /** * The plugin settings raw text value. */ readonly raw: string; /** * The plugin's schema. */ readonly schema: ISettingRegistry.ISchema; /** * The user settings. */ readonly user: O; /** * The published version of the NPM package containing these settings. */ readonly version: string; /** * Return the defaults in a commented JSON format. */ annotatedDefaults(): string; /** * Calculate the default value of a setting by iterating through the schema. * * @param key - The name of the setting whose default value is calculated. * * @returns A calculated default JSON value for a specific setting. */ default(key: string): PartialJSONValue | undefined; /** * Get an individual setting. * * @param key - The name of the setting being retrieved. * * @returns The setting value. */ get(key: string): { composite: ReadonlyPartialJSONValue | undefined; user: ReadonlyPartialJSONValue | undefined; }; /** * Remove a single setting. * * @param key - The name of the setting being removed. * * @returns A promise that resolves when the setting is removed. * * #### Notes * This function is asynchronous because it writes to the setting registry. */ remove(key: string): Promise<void>; /** * Save all of the plugin's user settings at once. */ save(raw: string): Promise<void>; /** * Set a single setting. * * @param key - The name of the setting being set. * * @param value - The value of the setting. * * @returns A promise that resolves when the setting has been saved. * * #### Notes * This function is asynchronous because it writes to the setting registry. */ set(key: string, value: PartialJSONValue): Promise<void>; /** * Validates raw settings with comments. * * @param raw - The JSON with comments string being validated. * * @returns A list of errors or `null` if valid. */ validate(raw: string): ISchemaValidator.IError[] | null; } /** * An interface describing a JupyterLab keyboard shortcut. */ export interface IShortcut extends PartialJSONObject { /** * The optional arguments passed into the shortcut's command. */ args?: PartialJSONObject; /** * The command invoked by the shortcut. */ command: string; /** * Whether a keyboard shortcut is disabled. `False` by default. */ disabled?: boolean; /** * The key sequence of the shortcut. * * ### Notes * * If this is a list like `['Ctrl A', 'B']`, the user needs to press * `Ctrl A` followed by `B` to trigger the shortcuts. */ keys: string[]; /** * The CSS selector applicable to the shortcut. */ selector: string; } /** * An interface describing the metadata form. */ export interface IMetadataForm extends PartialJSONObject { /** * The section unique ID. */ id: string; /** * The metadata schema. */ metadataSchema: IMetadataSchema; /** * The ui schema as used by react-JSON-schema-form. */ uiSchema?: { [metadataKey: string]: UiSchema }; /** * The jupyter properties. */ metadataOptions?: { [metadataKey: string]: IMetadataOptions }; /** * The section label. */ label?: string; /** * The section rank in notebooktools panel. */ rank?: number; /** * Whether to show the modified field from default value. */ showModified?: boolean; /** * Keep the plugin at origin of the metadata form. */ _origin?: string; } /** * The metadata schema as defined in JSON schema. */ export interface IMetadataSchema extends RJSFSchema { /** * The properties as defined in JSON schema, and interpretable by react-JSON-schema-form. */ properties: { [option: string]: any }; /** * The required fields. */ required?: string[]; /** * Support for allOf feature of JSON schema (useful for if/then/else). */ allOf?: Array<PartialJSONObject>; } /** * Options to customize the widget, the field and the relevant metadata. */ export interface IMetadataOptions extends PartialJSONObject { /** * Name of a custom react widget registered. */ customWidget?: string; /** * Name of a custom react field registered. */ customField?: string; /** * Metadata applied to notebook or cell. */ metadataLevel?: 'cell' | 'notebook'; /** * Cells which should have this metadata. */ cellTypes?: CellType[]; /** * Whether to avoid writing default value in metadata. */ writeDefault?: boolean; } /** * An interface describing a toolbar item. */ export interface IToolbarItem extends PartialJSONObject { /** * Unique toolbar item name */ name: string; /** * The command to execute when the item is triggered. * * The default value is an empty string. */ command?: string; /** * The arguments for the command. * * The default value is an empty object. */ args?: PartialJSONObject; /** * Whether the toolbar item is ignored (i.e. not created). `false` by default. * * #### Notes * This allows an user to suppress toolbar items. */ disabled?: boolean; /** * Item icon id * * #### Note * The id will be looked for in the LabIcon registry. * The command icon will be overridden by this label if defined. */ icon?: string; /** * Item label * * #### Note * The command label will be overridden by this label if defined. */ label?: string; /** * The rank order of the toolbar item among its siblings. */ rank?: number; /** * The type of the toolbar item. */ type?: 'command' | 'spacer'; } } ```
/content/code_sandbox/packages/settingregistry/src/tokens.ts
xml
2016-06-03T20:09:17
2024-08-16T19:12:44
jupyterlab
jupyterlab/jupyterlab
14,019
4,311
```xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="path_to_url" xmlns:xsi="path_to_url" xsi:schemaLocation="path_to_url path_to_url"> <modelVersion>4.0.0</modelVersion> <artifactId>microservice-provider-user</artifactId> <packaging>jar</packaging> <parent> <groupId>com.itmuch.cloud</groupId> <artifactId>spring-cloud-microservice-study</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <dependencies> <!-- Eureka --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> </dependencies> </project> ```
/content/code_sandbox/2016-Brixton/microservice-provider-user/pom.xml
xml
2016-08-26T09:35:58
2024-08-12T06:14:53
spring-cloud-study
eacdy/spring-cloud-study
1,042
278
```xml <?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="path_to_url"> <ItemGroup Label="ProjectConfigurations"> <ProjectConfiguration Include="debug|Win32"> <Configuration>debug</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="checked|Win32"> <Configuration>checked</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="profile|Win32"> <Configuration>profile</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="release|Win32"> <Configuration>release</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> </ItemGroup> <PropertyGroup Label="Globals"> <ProjectGuid>{BC4778D3-142F-31D0-46EC-77203F28C874}</ProjectGuid> <RootNamespace>PhysXVehicle</RootNamespace> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug|Win32'" Label="Configuration"> <ConfigurationType>StaticLibrary</ConfigurationType> <PlatformToolset>v141</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='checked|Win32'" Label="Configuration"> <ConfigurationType>StaticLibrary</ConfigurationType> <PlatformToolset>v141</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='profile|Win32'" Label="Configuration"> <ConfigurationType>StaticLibrary</ConfigurationType> <PlatformToolset>v141</PlatformToolset> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release|Win32'" Label="Configuration"> <ConfigurationType>StaticLibrary</ConfigurationType> <PlatformToolset>v141</PlatformToolset> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <ImportGroup Label="ExtensionSettings"> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='debug|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='checked|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='profile|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='release|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug|Win32'"> <OutDir>./../../../Lib/vc15win32\</OutDir> <IntDir>./Win32/PhysXVehicle/debug\</IntDir> <TargetExt>.lib</TargetExt> <TargetName>PhysX3VehicleDEBUG</TargetName> <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRules /> <CodeAnalysisRuleAssemblies /> </PropertyGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='debug|Win32'"> <ClCompile> <TreatWarningAsError>true</TreatWarningAsError> <BufferSecurityCheck>false</BufferSecurityCheck> <FloatingPointModel>Fast</FloatingPointModel> <BasicRuntimeChecks>UninitializedLocalUsageCheck</BasicRuntimeChecks> <AdditionalOptions>/GR- /GF /arch:SSE2 /MP /Wall /wd4514 /wd4820 /wd4127 /wd4710 /wd4711 /wd4435 /wd4577 /wd4464 /wd4623 /wd4626 /wd5027 /wd4987 /wd5038 /wd5045 /wd4548 /Zi /d2Zi+</AdditionalOptions> <Optimization>Disabled</Optimization> <AdditionalIncludeDirectories>./../../Common/include;./../../../../PxShared/include;./../../../../PxShared/src/foundation/include;./../../../../PxShared/src/fastxml/include;./../../../../PxShared/src/pvd/include;./../../../Include/vehicle;./../../../Include/common;./../../../Include/geometry;./../../../Include/extensions;./../../../Include/cloth;./../../../Include;./../../../Include/pvd;./../../../Include/physxprofilesdk;./../../Common/src;./../../PhysXVehicle/src;./../../PhysXMetaData/extensions/include;./../../PhysXExtensions/src/serialization/Xml;./../../PhysXMetaData/core/include;./../../PhysXVehicle/src/PhysXMetaData/include;./../../PvdSDK/src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN32;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;_WINSOCK_DEPRECATED_NO_WARNINGS;PX_PHYSX_STATIC_LIB;_DEBUG;PX_DEBUG=1;PX_CHECKED=1;PX_NVTX=1;PX_SUPPORT_PVD=1;%(PreprocessorDefinitions)</PreprocessorDefinitions> <ExceptionHandling>false</ExceptionHandling> <WarningLevel>Level4</WarningLevel> <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary> <PrecompiledHeader>NotUsing</PrecompiledHeader> <PrecompiledHeaderFile></PrecompiledHeaderFile> <ProgramDataBaseFileName>$(TargetDir)\$(TargetName).pdb</ProgramDataBaseFileName> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> </ClCompile> <Lib> <AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies> <OutputFile>$(OutDir)PhysX3VehicleDEBUG.lib</OutputFile> <AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <ProgramDatabaseFile>$(TargetDir)\$(TargetName).pdb</ProgramDatabaseFile> <TargetMachine>MachineX86</TargetMachine> </Lib> <ResourceCompile> </ResourceCompile> <ProjectReference> <LinkLibraryDependencies>true</LinkLibraryDependencies> </ProjectReference> </ItemDefinitionGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='checked|Win32'"> <OutDir>./../../../Lib/vc15win32\</OutDir> <IntDir>./Win32/PhysXVehicle/checked\</IntDir> <TargetExt>.lib</TargetExt> <TargetName>PhysX3VehicleCHECKED</TargetName> <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRules /> <CodeAnalysisRuleAssemblies /> </PropertyGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='checked|Win32'"> <ClCompile> <TreatWarningAsError>true</TreatWarningAsError> <BufferSecurityCheck>false</BufferSecurityCheck> <FloatingPointModel>Fast</FloatingPointModel> <AdditionalOptions>/GR- /GF /arch:SSE2 /MP /Wall /wd4514 /wd4820 /wd4127 /wd4710 /wd4711 /wd4435 /wd4577 /wd4464 /wd4623 /wd4626 /wd5027 /wd4987 /wd5038 /wd5045 /wd4548 /d2Zi+</AdditionalOptions> <Optimization>Full</Optimization> <AdditionalIncludeDirectories>./../../Common/include;./../../../../PxShared/include;./../../../../PxShared/src/foundation/include;./../../../../PxShared/src/fastxml/include;./../../../../PxShared/src/pvd/include;./../../../Include/vehicle;./../../../Include/common;./../../../Include/geometry;./../../../Include/extensions;./../../../Include/cloth;./../../../Include;./../../../Include/pvd;./../../../Include/physxprofilesdk;./../../Common/src;./../../PhysXVehicle/src;./../../PhysXMetaData/extensions/include;./../../PhysXExtensions/src/serialization/Xml;./../../PhysXMetaData/core/include;./../../PhysXVehicle/src/PhysXMetaData/include;./../../PvdSDK/src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN32;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;_WINSOCK_DEPRECATED_NO_WARNINGS;PX_PHYSX_STATIC_LIB;NDEBUG;PX_CHECKED=1;PX_NVTX=1;PX_SUPPORT_PVD=1;%(PreprocessorDefinitions)</PreprocessorDefinitions> <ExceptionHandling>false</ExceptionHandling> <WarningLevel>Level4</WarningLevel> <RuntimeLibrary>MultiThreaded</RuntimeLibrary> <PrecompiledHeader>NotUsing</PrecompiledHeader> <PrecompiledHeaderFile></PrecompiledHeaderFile> <ProgramDataBaseFileName>$(TargetDir)\$(TargetName).pdb</ProgramDataBaseFileName> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> </ClCompile> <Lib> <AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies> <OutputFile>$(OutDir)PhysX3VehicleCHECKED.lib</OutputFile> <AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <ProgramDatabaseFile>$(TargetDir)\$(TargetName).pdb</ProgramDatabaseFile> <TargetMachine>MachineX86</TargetMachine> </Lib> <ResourceCompile> </ResourceCompile> <ProjectReference> <LinkLibraryDependencies>true</LinkLibraryDependencies> </ProjectReference> </ItemDefinitionGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='profile|Win32'"> <OutDir>./../../../Lib/vc15win32\</OutDir> <IntDir>./Win32/PhysXVehicle/profile\</IntDir> <TargetExt>.lib</TargetExt> <TargetName>PhysX3VehiclePROFILE</TargetName> <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRules /> <CodeAnalysisRuleAssemblies /> </PropertyGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='profile|Win32'"> <ClCompile> <TreatWarningAsError>true</TreatWarningAsError> <BufferSecurityCheck>false</BufferSecurityCheck> <FloatingPointModel>Fast</FloatingPointModel> <AdditionalOptions>/GR- /GF /arch:SSE2 /MP /Wall /wd4514 /wd4820 /wd4127 /wd4710 /wd4711 /wd4435 /wd4577 /wd4464 /wd4623 /wd4626 /wd5027 /wd4987 /wd5038 /wd5045 /wd4548 /d2Zi+</AdditionalOptions> <Optimization>Full</Optimization> <AdditionalIncludeDirectories>./../../Common/include;./../../../../PxShared/include;./../../../../PxShared/src/foundation/include;./../../../../PxShared/src/fastxml/include;./../../../../PxShared/src/pvd/include;./../../../Include/vehicle;./../../../Include/common;./../../../Include/geometry;./../../../Include/extensions;./../../../Include/cloth;./../../../Include;./../../../Include/pvd;./../../../Include/physxprofilesdk;./../../Common/src;./../../PhysXVehicle/src;./../../PhysXMetaData/extensions/include;./../../PhysXExtensions/src/serialization/Xml;./../../PhysXMetaData/core/include;./../../PhysXVehicle/src/PhysXMetaData/include;./../../PvdSDK/src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN32;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;_WINSOCK_DEPRECATED_NO_WARNINGS;PX_PHYSX_STATIC_LIB;NDEBUG;PX_PROFILE=1;PX_NVTX=1;PX_SUPPORT_PVD=1;%(PreprocessorDefinitions)</PreprocessorDefinitions> <ExceptionHandling>false</ExceptionHandling> <WarningLevel>Level4</WarningLevel> <RuntimeLibrary>MultiThreaded</RuntimeLibrary> <PrecompiledHeader>NotUsing</PrecompiledHeader> <PrecompiledHeaderFile></PrecompiledHeaderFile> <ProgramDataBaseFileName>$(TargetDir)\$(TargetName).pdb</ProgramDataBaseFileName> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> </ClCompile> <Lib> <AdditionalOptions>/INCREMENTAL:NO</AdditionalOptions> <AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies> <OutputFile>$(OutDir)PhysX3VehiclePROFILE.lib</OutputFile> <AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <ProgramDatabaseFile>$(TargetDir)\$(TargetName).pdb</ProgramDatabaseFile> <TargetMachine>MachineX86</TargetMachine> </Lib> <ResourceCompile> </ResourceCompile> <ProjectReference> <LinkLibraryDependencies>true</LinkLibraryDependencies> </ProjectReference> </ItemDefinitionGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release|Win32'"> <OutDir>./../../../Lib/vc15win32\</OutDir> <IntDir>./Win32/PhysXVehicle/release\</IntDir> <TargetExt>.lib</TargetExt> <TargetName>PhysX3Vehicle</TargetName> <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRules /> <CodeAnalysisRuleAssemblies /> </PropertyGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='release|Win32'"> <ClCompile> <TreatWarningAsError>true</TreatWarningAsError> <BufferSecurityCheck>false</BufferSecurityCheck> <FloatingPointModel>Fast</FloatingPointModel> <AdditionalOptions>/GR- /GF /arch:SSE2 /MP /Wall /wd4514 /wd4820 /wd4127 /wd4710 /wd4711 /wd4435 /wd4577 /wd4464 /wd4623 /wd4626 /wd5027 /wd4987 /wd5038 /wd5045 /wd4548 /d2Zi+</AdditionalOptions> <Optimization>Full</Optimization> <AdditionalIncludeDirectories>./../../Common/include;./../../../../PxShared/include;./../../../../PxShared/src/foundation/include;./../../../../PxShared/src/fastxml/include;./../../../../PxShared/src/pvd/include;./../../../Include/vehicle;./../../../Include/common;./../../../Include/geometry;./../../../Include/extensions;./../../../Include/cloth;./../../../Include;./../../../Include/pvd;./../../../Include/physxprofilesdk;./../../Common/src;./../../PhysXVehicle/src;./../../PhysXMetaData/extensions/include;./../../PhysXExtensions/src/serialization/Xml;./../../PhysXMetaData/core/include;./../../PhysXVehicle/src/PhysXMetaData/include;./../../PvdSDK/src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN32;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;_WINSOCK_DEPRECATED_NO_WARNINGS;PX_PHYSX_STATIC_LIB;NDEBUG;PX_SUPPORT_PVD=0;%(PreprocessorDefinitions)</PreprocessorDefinitions> <ExceptionHandling>false</ExceptionHandling> <WarningLevel>Level4</WarningLevel> <RuntimeLibrary>MultiThreaded</RuntimeLibrary> <PrecompiledHeader>NotUsing</PrecompiledHeader> <PrecompiledHeaderFile></PrecompiledHeaderFile> <ProgramDataBaseFileName>$(TargetDir)\$(TargetName).pdb</ProgramDataBaseFileName> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> </ClCompile> <Lib> <AdditionalOptions>/INCREMENTAL:NO</AdditionalOptions> <AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies> <OutputFile>$(OutDir)PhysX3Vehicle.lib</OutputFile> <AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <ProgramDatabaseFile>$(TargetDir)\$(TargetName).pdb</ProgramDatabaseFile> <TargetMachine>MachineX86</TargetMachine> </Lib> <ResourceCompile> </ResourceCompile> <ProjectReference> <LinkLibraryDependencies>true</LinkLibraryDependencies> </ProjectReference> </ItemDefinitionGroup> <ItemGroup> <ClInclude Include="..\..\..\Include\vehicle\PxVehicleComponents.h"> </ClInclude> <ClInclude Include="..\..\..\Include\vehicle\PxVehicleDrive.h"> </ClInclude> <ClInclude Include="..\..\..\Include\vehicle\PxVehicleDrive4W.h"> </ClInclude> <ClInclude Include="..\..\..\Include\vehicle\PxVehicleDriveNW.h"> </ClInclude> <ClInclude Include="..\..\..\Include\vehicle\PxVehicleDriveTank.h"> </ClInclude> <ClInclude Include="..\..\..\Include\vehicle\PxVehicleNoDrive.h"> </ClInclude> <ClInclude Include="..\..\..\Include\vehicle\PxVehicleSDK.h"> </ClInclude> <ClInclude Include="..\..\..\Include\vehicle\PxVehicleShaders.h"> </ClInclude> <ClInclude Include="..\..\..\Include\vehicle\PxVehicleTireFriction.h"> </ClInclude> <ClInclude Include="..\..\..\Include\vehicle\PxVehicleUpdate.h"> </ClInclude> <ClInclude Include="..\..\..\Include\vehicle\PxVehicleUtil.h"> </ClInclude> <ClInclude Include="..\..\..\Include\vehicle\PxVehicleUtilControl.h"> </ClInclude> <ClInclude Include="..\..\..\Include\vehicle\PxVehicleUtilSetup.h"> </ClInclude> <ClInclude Include="..\..\..\Include\vehicle\PxVehicleUtilTelemetry.h"> </ClInclude> <ClInclude Include="..\..\..\Include\vehicle\PxVehicleWheels.h"> </ClInclude> </ItemGroup> <ItemGroup> <ClInclude Include="..\..\PhysXVehicle\src\PxVehicleDefaults.h"> </ClInclude> <ClInclude Include="..\..\PhysXVehicle\src\PxVehicleLinearMath.h"> </ClInclude> <ClInclude Include="..\..\PhysXVehicle\src\PxVehicleSerialization.h"> </ClInclude> <ClInclude Include="..\..\PhysXVehicle\src\PxVehicleSuspLimitConstraintShader.h"> </ClInclude> <ClInclude Include="..\..\PhysXVehicle\src\PxVehicleSuspWheelTire4.h"> </ClInclude> <ClCompile Include="..\..\PhysXVehicle\src\PxVehicleComponents.cpp"> </ClCompile> <ClCompile Include="..\..\PhysXVehicle\src\PxVehicleDrive.cpp"> </ClCompile> <ClCompile Include="..\..\PhysXVehicle\src\PxVehicleDrive4W.cpp"> </ClCompile> <ClCompile Include="..\..\PhysXVehicle\src\PxVehicleDriveNW.cpp"> </ClCompile> <ClCompile Include="..\..\PhysXVehicle\src\PxVehicleDriveTank.cpp"> </ClCompile> <ClCompile Include="..\..\PhysXVehicle\src\PxVehicleMetaData.cpp"> </ClCompile> <ClCompile Include="..\..\PhysXVehicle\src\PxVehicleNoDrive.cpp"> </ClCompile> <ClCompile Include="..\..\PhysXVehicle\src\PxVehicleSDK.cpp"> </ClCompile> <ClCompile Include="..\..\PhysXVehicle\src\PxVehicleSerialization.cpp"> </ClCompile> <ClCompile Include="..\..\PhysXVehicle\src\PxVehicleSuspWheelTire4.cpp"> </ClCompile> <ClCompile Include="..\..\PhysXVehicle\src\PxVehicleTireFriction.cpp"> </ClCompile> <ClCompile Include="..\..\PhysXVehicle\src\PxVehicleUpdate.cpp"> </ClCompile> <ClCompile Include="..\..\PhysXVehicle\src\PxVehicleWheels.cpp"> </ClCompile> <ClCompile Include="..\..\PhysXVehicle\src\VehicleUtilControl.cpp"> </ClCompile> <ClCompile Include="..\..\PhysXVehicle\src\VehicleUtilSetup.cpp"> </ClCompile> <ClCompile Include="..\..\PhysXVehicle\src\VehicleUtilTelemetry.cpp"> </ClCompile> </ItemGroup> <ItemGroup> <ClInclude Include="..\..\PhysXVehicle\src\PhysXMetaData\include\PxVehicleAutoGeneratedMetaDataObjectNames.h"> </ClInclude> <ClInclude Include="..\..\PhysXVehicle\src\PhysXMetaData\include\PxVehicleAutoGeneratedMetaDataObjects.h"> </ClInclude> <ClInclude Include="..\..\PhysXVehicle\src\PhysXMetaData\include\PxVehicleMetaDataObjects.h"> </ClInclude> </ItemGroup> <ItemGroup> <ClCompile Include="..\..\PhysXVehicle\src\PhysXMetaData\src\PxVehicleAutoGeneratedMetaDataObjects.cpp"> </ClCompile> <ClCompile Include="..\..\PhysXVehicle\src\PhysXMetaData\src\PxVehicleMetaDataObjects.cpp"> </ClCompile> </ItemGroup> <ItemGroup> </ItemGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <ImportGroup Label="ExtensionTargets"></ImportGroup> </Project> ```
/content/code_sandbox/PhysX_3.4/Source/compiler/vc15win32/PhysXVehicle.vcxproj
xml
2016-10-12T16:34:31
2024-08-16T09:40:38
PhysX-3.4
NVIDIAGameWorks/PhysX-3.4
2,343
5,067
```xml <?xml version="1.0" encoding="utf-8"?> <!-- 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. --> <ripple xmlns:android="path_to_url" android:color="@color/ripple_dark"> <item> <shape android:shape="oval"> <solid android:color="?android:colorAccent" /> </shape> </item> </ripple> ```
/content/code_sandbox/app/src/main/res/drawable/fab.xml
xml
2016-08-20T00:57:24
2024-08-09T02:01:01
LookLook
xinghongfei/LookLook
2,211
114
```xml import React, { useState } from "react"; import { RQButton } from "lib/design-system/components"; import { IoMdCopy } from "@react-icons/all-files/io/IoMdCopy"; import { PiBracketsCurlyBold } from "@react-icons/all-files/pi/PiBracketsCurlyBold"; import { BsFiletypeRaw } from "@react-icons/all-files/bs/BsFiletypeRaw"; import { MdOpenInFull } from "@react-icons/all-files/md/MdOpenInFull"; import { MdCloseFullscreen } from "@react-icons/all-files/md/MdCloseFullscreen"; import { EditorLanguage, EditorCustomToolbar } from "componentsV2/CodeEditor/types"; import { Tooltip } from "antd"; import { useTheme } from "styled-components"; import "./toolbar.scss"; import { prettifyCode } from "componentsV2/CodeEditor/utils"; import { trackCodeEditorCodePrettified, trackCodeEditorCodeMinified, trackCodeEditorCodeCopied, } from "componentsV2/CodeEditor/components/analytics"; interface CodeEditorToolbarProps { language: EditorLanguage; code: string; customOptions?: EditorCustomToolbar; onCodeFormat: (formattedCode: string) => void; isFullScreen: boolean; handleFullScreenToggle: () => void; } const CodeEditorToolbar: React.FC<CodeEditorToolbarProps> = ({ language, code, onCodeFormat, customOptions, isFullScreen = false, handleFullScreenToggle = () => {}, }) => { const theme = useTheme(); const [isCodePrettified, setIsCodePrettified] = useState(false); const [isCopied, setIsCopied] = useState(false); const handleCodeFormatting = () => { if (language === EditorLanguage.JSON) { handlePrettifyToggle(); } else { handlePrettifyCode(); } }; // This function is used for all languages except JSON const handlePrettifyCode = () => { const result = prettifyCode(code, language); if (result.success) { onCodeFormat(result.code); trackCodeEditorCodePrettified(); } }; // This function is only used for JSON code const handlePrettifyToggle = () => { if (isCodePrettified) { try { const minifiedCode = JSON.stringify(JSON.parse(code)); onCodeFormat(minifiedCode); trackCodeEditorCodeMinified(); setIsCodePrettified(false); } catch (error) { // NOOP } } else { handlePrettifyCode(); setIsCodePrettified(true); trackCodeEditorCodePrettified(); } }; const handleCopyCode = () => { navigator.clipboard.writeText(code); setIsCopied(true); trackCodeEditorCodeCopied(); setTimeout(() => { setIsCopied(false); }, 1000); }; return ( <div className="code-editor-toolbar"> <div className="code-editor-custom-options-row"> {customOptions ? ( <> {customOptions.title ? <div className="code-editor-custom-options-title">{customOptions.title}</div> : null} {customOptions.options ? ( <div className="code-editor-custom-options-block"> {customOptions.options.map((option, index) => ( <div key={index} className="code-editor-custom-option"> {option} </div> ))} </div> ) : null} </> ) : null} </div> <div className="code-editor-actions"> {/* TODO: ADD toggle search button */} <Tooltip title={isCopied ? "Copied" : "Copy code"} color={theme.colors.black} mouseEnterDelay={0.6}> <RQButton type="text" icon={<IoMdCopy />} onClick={handleCopyCode} /> </Tooltip> <Tooltip title={language === EditorLanguage.JSON && isCodePrettified ? "View raw" : "Prettify code"} color={theme.colors.black} mouseEnterDelay={0.6} > <RQButton type="text" icon={isCodePrettified ? <BsFiletypeRaw /> : <PiBracketsCurlyBold />} onClick={handleCodeFormatting} /> </Tooltip> <Tooltip color={theme.colors.black} title={isFullScreen ? "Exit full screen (esc)" : "Full screen"} placement="bottomLeft" > <RQButton type="text" icon={isFullScreen ? <MdCloseFullscreen /> : <MdOpenInFull />} onClick={handleFullScreenToggle} /> </Tooltip> </div> </div> ); }; export default CodeEditorToolbar; ```
/content/code_sandbox/app/src/componentsV2/CodeEditor/components/Editor/components/Toolbar/Toolbar.tsx
xml
2016-12-01T04:36:06
2024-08-16T19:12:19
requestly
requestly/requestly
2,121
1,036
```xml import React from 'react'; import cx from 'classnames'; import { Button as SUIButton, ButtonProps as SUIButtonProps } from 'semantic-ui-react'; import Tooltip, { TooltipProps } from '../../Tooltip'; import common from '../../../common.scss'; import styles from './styles.scss'; export type UserPanelButtonProps = SUIButtonProps & { icon: SUIButtonProps['icon']; tooltipContent: TooltipProps['content']; } const UserPanelButton: React.FC<UserPanelButtonProps> = ({ className, tooltipContent, ...rest }) => <Tooltip content={tooltipContent} position='top center' trigger={ <SUIButton className={cx( common.nuclear, styles.user_panel_button, className )} {...rest} /> } />; export default UserPanelButton; ```
/content/code_sandbox/packages/ui/lib/components/UserPanel/UserPanelButton/index.tsx
xml
2016-09-22T22:58:21
2024-08-16T15:47:39
nuclear
nukeop/nuclear
11,862
179
```xml <vector android:height="24dp" android:tint="#FFFFFF" android:viewportHeight="24.0" android:viewportWidth="24.0" android:width="24dp" xmlns:android="path_to_url"> <path android:fillColor="#FF000000" android:pathData="M14.24,12.01l2.32,2.32c0.28,-0.72 0.44,-1.51 0.44,-2.33 0,-0.82 -0.16,-1.59 -0.43,-2.31l-2.33,2.32zM19.53,6.71l-1.26,1.26c0.63,1.21 0.98,2.57 0.98,4.02s-0.36,2.82 -0.98,4.02l1.2,1.2c0.97,-1.54 1.54,-3.36 1.54,-5.31 -0.01,-1.89 -0.55,-3.67 -1.48,-5.19zM15.71,7.71L10,2L9,2v7.59L4.41,5 3,6.41 8.59,12 3,17.59 4.41,19 9,14.41L9,22h1l5.71,-5.71 -4.3,-4.29 4.3,-4.29zM11,5.83l1.88,1.88L11,9.59L11,5.83zM12.88,16.29L11,18.17v-3.76l1.88,1.88z"/> </vector> ```
/content/code_sandbox/java-sample/src/main/res/drawable/ic_bluetooth_audio_black_24dp.xml
xml
2016-11-29T06:15:08
2024-08-16T11:21:28
Android-BLE
aicareles/Android-BLE
2,623
395
```xml import { prefixToObjectMap } from '@bpinternal/const' import * as uuid from 'uuid' const ULID_LENGTH = 26 // Reference: path_to_url#canonical-string-representation export function isValidID(id: string) { // Note: UUIDs were used first and then prefixed ULIDs were introduced. return isPrefixedULID(id) || uuid.validate(id) } export function isPrefixedULID(id: string) { const [prefix, identifier] = id.split('_') if (!(prefix && identifier)) { return false } if (!Object.keys(prefixToObjectMap).includes(prefix)) { return false } if (identifier.length < ULID_LENGTH) { return false } return true } ```
/content/code_sandbox/packages/cli/src/utils/id-utils.ts
xml
2016-11-16T21:57:59
2024-08-16T18:45:35
botpress
botpress/botpress
12,401
161
```xml <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE > < _id="Foozle&#32;<![CDATA[<greeting>Hello, world!"</greeting>]]>Barzle"> <:barzle> <name foo:bar="birmese"> </name> <nickname>Owl of Shame</nickname> <data>More CDATA <![CDATA[<greeting>Hello, world!</greeting><![CDATA] <$]]> Nonsense.</data> </:barzle> ```
/content/code_sandbox/tests/core/assets/XML/utf8.xml
xml
2016-11-23T14:22:10
2024-08-16T19:27:14
Odin
odin-lang/Odin
6,364
111
```xml <!-- This MSBuild file detects the Stardew Valley install path if possible, and sets the 'GamePath' property. --> <Project xmlns="path_to_url"> <!-- import developer's custom path (if any) --> <Import Condition="$(OS) != 'Windows_NT' AND Exists('$(HOME)\stardewvalley.targets')" Project="$(HOME)\stardewvalley.targets" /> <Import Condition="$(OS) == 'Windows_NT' AND Exists('$(USERPROFILE)\stardewvalley.targets')" Project="$(USERPROFILE)\stardewvalley.targets" /> <!-- find game path --> <Choose> <When Condition="$(OS) == 'Unix' OR $(OS) == 'OSX'"> <PropertyGroup> <!-- Linux --> <GamePath Condition="!Exists('$(GamePath)')">$(HOME)/GOG Games/Stardew Valley/game</GamePath> <GamePath Condition="!Exists('$(GamePath)')">$(HOME)/.steam/steam/steamapps/common/Stardew Valley</GamePath> <GamePath Condition="!Exists('$(GamePath)')">$(HOME)/.local/share/Steam/steamapps/common/Stardew Valley</GamePath> <GamePath Condition="!Exists('$(GamePath)')">$(HOME)/.var/app/com.valvesoftware.Steam/data/Steam/steamapps/common/Stardew Valley</GamePath> <!-- macOS (may be 'Unix' or 'OSX') --> <GamePath Condition="!Exists('$(GamePath)')">/Applications/Stardew Valley.app/Contents/MacOS</GamePath> <GamePath Condition="!Exists('$(GamePath)')">$(HOME)/Library/Application Support/Steam/steamapps/common/Stardew Valley/Contents/MacOS</GamePath> </PropertyGroup> </When> <When Condition="$(OS) == 'Windows_NT'"> <PropertyGroup> <!-- registry paths --> <GamePath Condition="!Exists('$(GamePath)')">$([MSBuild]::GetRegistryValueFromView('HKEY_LOCAL_MACHINE\SOFTWARE\GOG.com\Games\1453375253', 'PATH', null, RegistryView.Registry32))</GamePath> <GamePath Condition="!Exists('$(GamePath)')">$([MSBuild]::GetRegistryValueFromView('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Steam App 413150', 'InstallLocation', null, RegistryView.Registry64, RegistryView.Registry32))</GamePath> <!-- derive from Steam library path --> <_SteamLibraryPath>$([MSBuild]::GetRegistryValueFromView('HKEY_CURRENT_USER\SOFTWARE\Valve\Steam', 'SteamPath', null, RegistryView.Registry32))</_SteamLibraryPath> <GamePath Condition="!Exists('$(GamePath)') AND '$(_SteamLibraryPath)' != ''">$(_SteamLibraryPath)\steamapps\common\Stardew Valley</GamePath> <!-- GOG paths --> <GamePath Condition="!Exists('$(GamePath)')">C:\Program Files\GalaxyClient\Games\Stardew Valley</GamePath> <GamePath Condition="!Exists('$(GamePath)')">C:\Program Files\GOG Galaxy\Games\Stardew Valley</GamePath> <GamePath Condition="!Exists('$(GamePath)')">C:\Program Files\GOG Games\Stardew Valley</GamePath> <GamePath Condition="!Exists('$(GamePath)')">C:\Program Files (x86)\GalaxyClient\Games\Stardew Valley</GamePath> <GamePath Condition="!Exists('$(GamePath)')">C:\Program Files (x86)\GOG Galaxy\Games\Stardew Valley</GamePath> <GamePath Condition="!Exists('$(GamePath)')">C:\Program Files (x86)\GOG Games\Stardew Valley</GamePath> <!-- Xbox app paths --> <!-- The Xbox app saves the install path to the registry, but we can't use it here since it saves the internal readonly path (like C:\Program Files\WindowsApps\Mutable\<package ID>) instead of the mods-enabled path (like C:\Program Files\ModifiableWindowsApps\Stardew Valley). Fortunately we can cheat a bit: players can customize the install drive, but they can't change the install path on the drive. --> <GamePath Condition="!Exists('$(GamePath)')">C:\Program Files\ModifiableWindowsApps\Stardew Valley</GamePath> <GamePath Condition="!Exists('$(GamePath)')">D:\Program Files\ModifiableWindowsApps\Stardew Valley</GamePath> <GamePath Condition="!Exists('$(GamePath)')">E:\Program Files\ModifiableWindowsApps\Stardew Valley</GamePath> <GamePath Condition="!Exists('$(GamePath)')">F:\Program Files\ModifiableWindowsApps\Stardew Valley</GamePath> <GamePath Condition="!Exists('$(GamePath)')">G:\Program Files\ModifiableWindowsApps\Stardew Valley</GamePath> <GamePath Condition="!Exists('$(GamePath)')">H:\Program Files\ModifiableWindowsApps\Stardew Valley</GamePath> <!-- Steam paths --> <GamePath Condition="!Exists('$(GamePath)')">C:\Program Files\Steam\steamapps\common\Stardew Valley</GamePath> <GamePath Condition="!Exists('$(GamePath)')">C:\Program Files (x86)\Steam\steamapps\common\Stardew Valley</GamePath> </PropertyGroup> </When> </Choose> </Project> ```
/content/code_sandbox/build/find-game-folder.targets
xml
2016-03-02T14:12:15
2024-08-16T05:34:53
SMAPI
Pathoschild/SMAPI
1,755
1,236
```xml import Datetime from '@nateradebaugh/react-datetime'; import Icon from '@erxes/ui/src/components/Icon'; import { rgba } from '@erxes/ui/src/styles/ecolor'; import colors from '@erxes/ui/src/styles/colors'; import * as React from 'react'; import styled from 'styled-components'; import styledTS from 'styled-components-ts'; export const DateWrapper = styledTS<{ color: string; hasValue?: boolean }>( styled.div )` position: relative; input { background-color: ${props => rgba(props.color, 0.1)}; color: ${props => props.color}; border: none; box-shadow: none; outline: 0; padding: 0 10px 0 25px; height: 25px; border-radius: 2px; font-weight: 500; line-height: 25px; width: ${props => (props.hasValue ? '130px' : '100px')}; font-size: 12px; &:hover { background: ${props => rgba(props.color, 0.15)}; cursor: pointer; } &:focus { box-shadow: none; } ::placeholder { color: ${props => props.color}; font-weight: 500; opacity: 1; } } > i { color: ${props => props.color}; line-height: 25px; position: absolute; left: 7px; } > button { position: absolute; right: 2px; top: 2px; bottom: 2px; padding: 0; width: 20px; border: none; color: ${props => props.color}; border-radius: 2px; background-color: ${props => rgba(props.color, 0.15)}; &:hover { background: ${props => rgba(props.color, 0.3)}; cursor: pointer; } } `; type IProps = { onChange: (value?: string | Date | null) => void; value: Date; isWarned?: boolean; }; class DueDateChanger extends React.Component<IProps> { clearDate = () => this.props.onChange(null); hasValue = () => (this.props.value ? true : false); render() { const { onChange, value, isWarned } = this.props; const color = isWarned ? colors.colorCoreRed : colors.colorPrimaryDark; return ( <DateWrapper color={color} hasValue={this.hasValue()}> <Icon icon="clock-eight" /> <Datetime inputProps={{ placeholder: 'Due date' }} dateFormat="MMM,DD YYYY" timeFormat={false} value={value} closeOnSelect={true} onChange={onChange} utc={true} /> {this.hasValue() && ( <button onClick={this.clearDate}> <Icon icon="times" /> </button> )} </DateWrapper> ); } } export default DueDateChanger; ```
/content/code_sandbox/packages/ui-tasks/src/boards/components/DueDateChanger.tsx
xml
2016-11-11T06:54:50
2024-08-16T10:26:06
erxes
erxes/erxes
3,479
684
```xml import { Component } from '@angular/core'; @Component({ selector: 'accessibility-doc', template: ` <app-docsectiontext> <h3>Screen Reader</h3> <p> Default role of the table is <i>table</i>. Header, body and footer elements use <i>rowgroup</i>, rows use <i>row</i> role, header cells have <i>columnheader</i> and body cells use <i>cell</i> roles. Sortable headers utilizer <i>aria-sort</i> attribute either set to "ascending" or "descending". </p> <p>Table rows and table cells should be specified by users using the <i>aria-posinset</i>, <i>aria-setsize</i>, <i>aria-label</i>, and <i>aria-describedby</i> attributes, as they are determined through templating.</p> <p> Built-in checkbox and radiobutton components for row selection use <i>checkbox</i> and <i>radiobutton</i>. The label to describe them is retrieved from the <i>aria.selectRow</i> and <i>aria.unselectRow</i> properties of the <a href="/configuration" class="">locale</a> API. Similarly header checkbox uses <i>selectAll</i> and <i>unselectAll</i> keys. When a row is selected, <i>aria-selected</i> is set to true on a row. </p> <p> The element to expand or collapse a row is a <i>button</i> with <i>aria-expanded</i> and <i>aria-controls</i> properties. Value to describe the buttons is derived from <i>aria.expandRow</i> and <i>aria.collapseRow</i> properties of the <a href="/configuration" class="">locale</a> API. </p> <p> The filter menu button use <i>aria.showFilterMenu</i> and <i>aria.hideFilterMenu</i> properties as <i>aria-label</i> in addition to the <i>aria-haspopup</i>, <i>aria-expanded</i> and <i>aria-controls</i> to define the relation between the button and the overlay. Popop menu has <i>dialog</i> role with <i>aria-modal</i> as focus is kept within the overlay. The operator dropdown use <i>aria.filterOperator</i> and filter constraints dropdown use <i>aria.filterConstraint</i> properties. Buttons to add rules on the other hand utilize <i>aria.addRule</i> and <i>aria.removeRule</i> properties. The footer buttons similarly use <i>aria.clear</i> and <i>aria.apply</i> properties. <i>filterInputProps</i> of the Column component can be used to define aria labels for the built-in filter components, if a custom component is used with templating you also may define your own aria labels as well. </p> <p> Editable cells use custom templating so you need to manage aria roles and attributes manually if required. The row editor controls are button elements with <i>aria.editRow</i>, <i>aria.cancelEdit</i> and <i>aria.saveEdit</i> used for the <i>aria-label</i>. </p> <p>Paginator is a standalone component used inside the Table, refer to the <a href="/paginator" class="">paginator</a> for more information about the accessibility features.</p> <h3>Keyboard Support</h3> <p>Any button element inside the Table used for cases like filter, row expansion, edit are tabbable and can be used with <i>space</i> and <i>enter</i> keys.</p> <h3>Sortable Headers Keyboard Support</h3> <div class="doc-tablewrapper"> <table class="doc-table"> <thead> <tr> <th>Key</th> <th>Function</th> </tr> </thead> <tbody> <tr> <td><i>tab</i></td> <td>Moves through the headers.</td> </tr> <tr> <td><i>enter</i></td> <td>Sorts the column.</td> </tr> <tr> <td><i>space</i></td> <td>Sorts the column.</td> </tr> </tbody> </table> </div> <h3>Filter Menu Keyboard Support</h3> <div class="doc-tablewrapper"> <table class="doc-table"> <thead> <tr> <th>Key</th> <th>Function</th> </tr> </thead> <tbody> <tr> <td><i>tab</i></td> <td>Moves through the elements inside the popup.</td> </tr> <tr> <td><i>escape</i></td> <td>Hides the popup.</td> </tr> <tr> <td><i>enter</i></td> <td>Opens the popup.</td> </tr> </tbody> </table> </div> <h3>Selection Keyboard Support</h3> <div class="doc-tablewrapper"> <table class="doc-table"> <thead> <tr> <th>Key</th> <th>Function</th> </tr> </thead> <tbody> <tr> <td><i>tab</i></td> <td>Moves focus to the first selected row, if there is none then first row receives the focus.</td> </tr> <tr> <td><i>up arrow</i></td> <td>Moves focus to the previous row.</td> </tr> <tr> <td><i>down arrow</i></td> <td>Moves focus to the next row.</td> </tr> <tr> <td><i>enter</i></td> <td>Toggles the selected state of the focused row depending on the metaKeySelection setting.</td> </tr> <tr> <td><i>space</i></td> <td>Toggles the selected state of the focused row depending on the metaKeySelection setting.</td> </tr> <tr> <td><i>home</i></td> <td>Moves focus to the first row.</td> </tr> <tr> <td><i>end</i></td> <td>Moves focus to the last row.</td> </tr> <tr> <td><i>shift</i> + <i>down arrow</i></td> <td>Moves focus to the next row and toggles the selection state.</td> </tr> <tr> <td><i>shift</i> + <i>up arrow</i></td> <td>Moves focus to the previous row and toggles the selection state.</td> </tr> <tr> <td><i>shift</i> + <i>space</i></td> <td>Selects the rows between the most recently selected row and the focused row.</td> </tr> <tr> <td><i>control</i> + <i>shift</i> + <i>home</i></td> <td>Selects the focused rows and all the options up to the first one.</td> </tr> <tr> <td><i>control</i> + <i>shift</i> + <i>end</i></td> <td>Selects the focused rows and all the options down to the last one.</td> </tr> <tr> <td><i>control</i> + <i>a</i></td> <td>Selects all rows.</td> </tr> </tbody> </table> </div> </app-docsectiontext>` }) export class AccessibilityDoc {} ```
/content/code_sandbox/src/app/showcase/doc/table/accessibilitydoc.ts
xml
2016-01-16T09:23:28
2024-08-16T19:58:20
primeng
primefaces/primeng
9,969
1,837
```xml <?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="path_to_url"> <ItemGroup Label="ProjectConfigurations"> <ProjectConfiguration Include="Debug|ARM64"> <Configuration>Debug</Configuration> <Platform>ARM64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Debug|Win32"> <Configuration>Debug</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Debug|x64"> <Configuration>Debug</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|ARM64"> <Configuration>Release</Configuration> <Platform>ARM64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|Win32"> <Configuration>Release</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|x64"> <Configuration>Release</Configuration> <Platform>x64</Platform> </ProjectConfiguration> </ItemGroup> <PropertyGroup Label="Globals"> <ProjectGuid>{B70585F8-DAB7-40FA-9904-13CF53A73A06}</ProjectGuid> <RootNamespace>BroadcastPathUpdateCustomAction</RootNamespace> <Keyword>Win32Proj</Keyword> <ProjectName>custom_actions</ProjectName> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <PlatformToolset>$(PlatformToolset)</PlatformToolset> <CharacterSet>Unicode</CharacterSet> <WholeProgramOptimization>true</WholeProgramOptimization> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <PlatformToolset>$(PlatformToolset)</PlatformToolset> <CharacterSet>Unicode</CharacterSet> <WholeProgramOptimization>true</WholeProgramOptimization> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <PlatformToolset>$(PlatformToolset)</PlatformToolset> <CharacterSet>Unicode</CharacterSet> <WholeProgramOptimization>true</WholeProgramOptimization> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <PlatformToolset>$(PlatformToolset)</PlatformToolset> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <PlatformToolset>$(PlatformToolset)</PlatformToolset> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> <ConfigurationType>DynamicLibrary</ConfigurationType> <PlatformToolset>$(PlatformToolset)</PlatformToolset> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <ImportGroup Label="ExtensionSettings"> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup> <_ProjectFileVersion>12.0.30501.0</_ProjectFileVersion> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <LinkIncremental>true</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'"> <LinkIncremental>true</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <LinkIncremental>true</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'"> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ClCompile> <Optimization>Disabled</Optimization> <AdditionalIncludeDirectories>$(WixSdkDir)\inc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions> <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks> <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary> <PrecompiledHeader>NotUsing</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> </ClCompile> <Link> <AdditionalDependencies>msi.lib;dutil.lib;wcautil.lib;version.lib;%(AdditionalDependencies)</AdditionalDependencies> <AdditionalLibraryDirectories>$(WixSdkDir)\lib\x86;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <ModuleDefinitionFile>custom_actions.def</ModuleDefinitionFile> <GenerateDebugInformation>true</GenerateDebugInformation> <SubSystem>Windows</SubSystem> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'"> <ClCompile> <Optimization>Disabled</Optimization> <AdditionalIncludeDirectories>$(WixSdkDir)\inc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions> <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks> <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary> <PrecompiledHeader>NotUsing</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> </ClCompile> <Link> <AdditionalDependencies>msi.lib;dutil.lib;wcautil.lib;version.lib;%(AdditionalDependencies)</AdditionalDependencies> <AdditionalLibraryDirectories>$(WixSdkDir)\lib\ARM64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <ModuleDefinitionFile>custom_actions.def</ModuleDefinitionFile> <GenerateDebugInformation>true</GenerateDebugInformation> <SubSystem>Windows</SubSystem> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <ClCompile> <Optimization>Disabled</Optimization> <AdditionalIncludeDirectories>$(WixSdkDir)\inc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions> <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks> <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary> <PrecompiledHeader>NotUsing</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> </ClCompile> <Link> <AdditionalDependencies>msi.lib;dutil.lib;wcautil.lib;version.lib;%(AdditionalDependencies)</AdditionalDependencies> <AdditionalLibraryDirectories>$(WixSdkDir)\lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <ModuleDefinitionFile>custom_actions.def</ModuleDefinitionFile> <GenerateDebugInformation>true</GenerateDebugInformation> <SubSystem>Windows</SubSystem> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ClCompile> <Optimization>MaxSpeed</Optimization> <IntrinsicFunctions>true</IntrinsicFunctions> <AdditionalIncludeDirectories>$(WixSdkDir)\inc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions> <RuntimeLibrary>MultiThreaded</RuntimeLibrary> <FunctionLevelLinking>true</FunctionLevelLinking> <WarningLevel>Level3</WarningLevel> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> <PrecompiledHeader>NotUsing</PrecompiledHeader> <PrecompiledHeaderFile> </PrecompiledHeaderFile> <PrecompiledHeaderOutputFile> </PrecompiledHeaderOutputFile> </ClCompile> <Link> <AdditionalDependencies>msi.lib;dutil.lib;wcautil.lib;version.lib;%(AdditionalDependencies)</AdditionalDependencies> <AdditionalLibraryDirectories>$(WixSdkDir)\lib\x86;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <ModuleDefinitionFile>custom_actions.def</ModuleDefinitionFile> <GenerateDebugInformation>true</GenerateDebugInformation> <SubSystem>Windows</SubSystem> <OptimizeReferences>true</OptimizeReferences> <EnableCOMDATFolding>true</EnableCOMDATFolding> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'"> <ClCompile> <Optimization>MaxSpeed</Optimization> <IntrinsicFunctions>true</IntrinsicFunctions> <AdditionalIncludeDirectories>$(WixSdkDir)\inc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions> <RuntimeLibrary>MultiThreaded</RuntimeLibrary> <FunctionLevelLinking>true</FunctionLevelLinking> <WarningLevel>Level3</WarningLevel> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> <PrecompiledHeader>NotUsing</PrecompiledHeader> <PrecompiledHeaderFile> </PrecompiledHeaderFile> <PrecompiledHeaderOutputFile> </PrecompiledHeaderOutputFile> </ClCompile> <Link> <AdditionalDependencies>msi.lib;dutil.lib;wcautil.lib;version.lib;%(AdditionalDependencies)</AdditionalDependencies> <AdditionalLibraryDirectories>$(WixSdkDir)\lib\ARM64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <ModuleDefinitionFile>custom_actions.def</ModuleDefinitionFile> <GenerateDebugInformation>true</GenerateDebugInformation> <SubSystem>Windows</SubSystem> <OptimizeReferences>true</OptimizeReferences> <EnableCOMDATFolding>true</EnableCOMDATFolding> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <ClCompile> <Optimization>MaxSpeed</Optimization> <IntrinsicFunctions>true</IntrinsicFunctions> <AdditionalIncludeDirectories>$(WixSdkDir)\inc;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions> <RuntimeLibrary>MultiThreaded</RuntimeLibrary> <FunctionLevelLinking>true</FunctionLevelLinking> <WarningLevel>Level3</WarningLevel> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat> <PrecompiledHeader>NotUsing</PrecompiledHeader> <PrecompiledHeaderFile> </PrecompiledHeaderFile> <PrecompiledHeaderOutputFile> </PrecompiledHeaderOutputFile> </ClCompile> <Link> <AdditionalDependencies>msi.lib;dutil.lib;wcautil.lib;version.lib;%(AdditionalDependencies)</AdditionalDependencies> <AdditionalLibraryDirectories>$(WixSdkDir)\lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <ModuleDefinitionFile>custom_actions.def</ModuleDefinitionFile> <GenerateDebugInformation>true</GenerateDebugInformation> <SubSystem>Windows</SubSystem> <OptimizeReferences>true</OptimizeReferences> <EnableCOMDATFolding>true</EnableCOMDATFolding> </Link> </ItemDefinitionGroup> <ItemGroup> <ClCompile Include="custom_actions.cc"> </ClCompile> </ItemGroup> <ItemGroup> <None Include="custom_actions.def" /> </ItemGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <ImportGroup Label="ExtensionTargets"> </ImportGroup> </Project> ```
/content/code_sandbox/current/tools/msvs/msi/custom_actions.vcxproj
xml
2016-10-10T12:09:49
2024-08-11T15:13:17
node-packer
pmq20/node-packer
3,069
3,289
```xml import { mat4, quat, vec3 } from "gl-matrix"; import { computeViewSpaceDepthFromWorldSpacePoint } from "../Camera.js"; import { Color, colorNewCopy, Magenta } from "../Color.js"; import { drawWorldSpaceAABB, drawWorldSpaceCircle, drawWorldSpacePoint, getDebugOverlayCanvas2D } from "../DebugJunk.js"; import { GfxRenderInstManager } from "../gfx/render/GfxRenderInstManager.js"; import { scaleMatrix, Vec3UnitY } from "../MathHelpers.js"; import { leftPad } from "../util.js"; import { Asset_Type, Lightmap_Asset, Mesh_Asset } from "./Assets.js"; import { TheWitnessGlobals } from "./Globals.js"; import { Mesh_Instance } from "./Render.js"; export class Entity_Manager { public flat_entity_list: Entity[] = []; public entity_list: Entity[] = []; public universe_name = `save`; public load_world(globals: TheWitnessGlobals): void { const world = globals.asset_manager.load_asset(Asset_Type.World, this.universe_name)!; for (let i = 0; i < world.length; i++) { const entity = world[i]; this.flat_entity_list.push(entity); this.entity_list[entity.portable_id] = entity; } // Set up groups & initial group visibility // Go through and register clusters. for (let i = 0; i < this.flat_entity_list.length; i++) if (this.flat_entity_list[i] instanceof Entity_Cluster) (this.flat_entity_list[i] as Entity_Cluster).validate(globals); // Initialize groups & group visibility for (let i = 0; i < this.flat_entity_list.length; i++) if (this.flat_entity_list[i] instanceof Entity_Group) (this.flat_entity_list[i] as Entity_Group).initialize(globals); // Finalize actor creation. for (let i = 0; i < this.flat_entity_list.length; i++) this.flat_entity_list[i].transport_create_hook(globals); globals.occlusion_manager.init(globals); } } export interface Portable { portable_id: number; revision_number: number; type_name: string; [k: string]: any; } function get_lightmap_page_name(base: string, state: number): string { const numChars = state < 0x101 ? 2 : 8; return `${base}_${leftPad('' + state.toString(16).toUpperCase(), numChars)}`; } export class Lightmap_Table { public dependency_array: number[]; public state_array: number[]; public lightmap_page_array: (Lightmap_Asset | null)[] = []; public current_page: Lightmap_Asset | null = null; public next_page: Lightmap_Asset | null = null; public blend: number = 1.0; public load_pages(globals: TheWitnessGlobals, entity: Entity): void { const lightmap_page_name_base = `${globals.entity_manager.universe_name}_${entity.portable_id}`; for (let i = 0; i < this.state_array.length; i++) { const state = this.state_array[i]; const lightmap_page_name = get_lightmap_page_name(lightmap_page_name_base, state); this.lightmap_page_array[i] = globals.asset_manager.load_asset(Asset_Type.Lightmap, lightmap_page_name); } this.update(); } public update(): void { // TODO(jstpierre): Update from dependencies. this.current_page = this.lightmap_page_array[0]; this.next_page = null; } } const enum Entity_Flags { LodsToNothing = 0x00001000, Invisible = 0x00008000, DoNotCull = 0x20000000, } export class Entity implements Portable { public visible = true; // debug visible flag public layer_active = true; // layer/group visible flag public type_name: string; public debug_color = colorNewCopy(Magenta); public entity_manager: Entity_Manager; public position: vec3; public scale: number; public orientation: quat; public entity_flags: Entity_Flags; public entity_name: string; public group_id: number; public mount_parent_id: number; public mount_position?: vec3; public mount_scale?: number; public mount_orientation?: quat; public mount_bone_name?: string; public version: number; public root_z: number; public cluster_id?: number; public lod_distance: number; public lightmap_table: Lightmap_Table | null; public bounding_radius: number; public bounding_center: vec3; public bounding_center_world = vec3.create(); public bounding_radius_world = 0; public mesh_instance: Mesh_Instance | null = null; // Culling Data private lod_distance_squared: number = Infinity; private cull_distance_squared: number = Infinity; // Mesh_Render_Params public model_matrix = mat4.create(); public color: Color | null; public mesh_lod: number = 0; constructor(public portable_id: number, public revision_number: number) { } public transport_create_hook(globals: TheWitnessGlobals): void { if (this.lightmap_table !== null) this.lightmap_table.load_pages(globals, this); this.visible = !(this.entity_flags & Entity_Flags.Invisible); this.updateModelMatrix(); } protected updateModelMatrix(): void { mat4.fromRotationTranslation(this.model_matrix, this.orientation, this.position); scaleMatrix(this.model_matrix, this.model_matrix, this.scale); vec3.add(this.bounding_center_world, this.bounding_center, this.position); this.bounding_radius_world = this.bounding_radius * this.scale; } private compute_lod_distance_squared(globals: TheWitnessGlobals): number { let lod_distance = this.lod_distance; if (lod_distance < 0.0) { lod_distance = globals.render_settings.lod_distance; // TODO(jstpierre): grass fade } if (!(this.entity_flags & Entity_Flags.LodsToNothing)) { // If we aren't LODing to nothing, and our mesh only has one LOD, then never switch. if (this.mesh_instance !== null && this.mesh_instance.mesh_asset.max_lod_count <= 1) return Infinity; lod_distance = Math.min(lod_distance, globals.render_settings.cluster_distance * 0.75); } if (lod_distance === 0.0) return 0.0; lod_distance += this.bounding_radius_world; return lod_distance ** 2.0; } private compute_cull_distance_squared(globals: TheWitnessGlobals): number { // noclip change: since we don't have a LOD transition animation, LodsToNothing just becomes our LOD distance if (!!(this.entity_flags & Entity_Flags.LodsToNothing)) return this.lod_distance_squared; if (this.entity_flags & (Entity_Flags.DoNotCull | Entity_Flags.LodsToNothing)) return Infinity; // TODO(jstpierre): Check for cluster // TODO(jstpierre): grass fade if (false /*this.is_detail*/) { let cull_distance = globals.render_settings.detail_cull_distance + this.bounding_radius_world; return cull_distance ** 2.0; } let cull_distance_squared = (this.bounding_radius_world ** 2.0) / (globals.render_settings.cull_threshold * 0.02); if (this.lod_distance > 0.0) cull_distance_squared = Math.max(cull_distance_squared, (this.lod_distance * 2.0 + this.bounding_radius_world) ** 2.0); return cull_distance_squared; } private update_lod_settings(globals: TheWitnessGlobals): void { this.lod_distance_squared = this.compute_lod_distance_squared(globals); this.cull_distance_squared = this.compute_cull_distance_squared(globals); } protected create_mesh_instance(globals: TheWitnessGlobals, mesh_asset: Mesh_Asset | null): void { if (mesh_asset === null) { this.mesh_instance = null; return; } this.mesh_instance = new Mesh_Instance(globals, mesh_asset); this.update_lod_settings(globals); } public prepareToRender(globals: TheWitnessGlobals, renderInstManager: GfxRenderInstManager): void { if (!this.visible || !this.layer_active) return; if (this.mesh_instance === null) return; if (this.cluster_id !== undefined && !globals.occlusion_manager.clusterIsVisible(this.cluster_id)) return; const squared_distance = vec3.squaredDistance(globals.viewpoint.cameraPos, this.bounding_center_world); if (globals.render_settings.cull_distance_enabled && squared_distance >= this.cull_distance_squared) return; this.mesh_lod = (globals.render_settings.lod_distance_enabled && squared_distance >= this.lod_distance_squared) ? 1 : 0; const depth = computeViewSpaceDepthFromWorldSpacePoint(globals.viewpoint.viewFromWorldMatrix, this.bounding_center_world); this.mesh_instance.prepareToRender(globals, renderInstManager, this, depth); } } export class Entity_Inanimate extends Entity { public mesh_name: string = ''; public color_override: number = 0; public override transport_create_hook(globals: TheWitnessGlobals): void { super.transport_create_hook(globals); if (!this.color_override) this.color = null; if (this.mesh_name) { const mesh_asset = globals.asset_manager.load_asset(Asset_Type.Mesh, this.mesh_name); this.create_mesh_instance(globals, mesh_asset); } } } export class Entity_Cluster extends Entity { public elements: number[]; public elements_static: number[]; public elements_detail: number[]; public elements_combined_meshes: number[]; public override bounding_radius: number; public override bounding_center: vec3; public cluster_flags: number; public cluster_mesh_data: Mesh_Asset | null = null; public cluster_mesh_instance: Mesh_Instance | null = null; public override transport_create_hook(globals: TheWitnessGlobals): void { super.transport_create_hook(globals); const mesh_name = `${globals.entity_manager.universe_name}_${this.portable_id}`; const mesh_data = globals.asset_manager.load_asset(Asset_Type.Mesh, mesh_name); this.cluster_mesh_data = mesh_data; if (mesh_data !== null && mesh_data.device_mesh_array.length > 0) this.cluster_mesh_instance = new Mesh_Instance(globals, mesh_data); } public validate(globals: TheWitnessGlobals): void { if (!!(this.cluster_flags & 0x02)) return; for (let i = 0; i < this.elements.length; i++) { const entity = globals.entity_manager.entity_list[this.elements[i]]; entity.cluster_id = this.portable_id; } } } export class Entity_Group extends Entity { public elements: number[] = []; public child_groups: number[] = []; public initial_group_visibility = true; public current_group_visibility = true; public initialize(globals: TheWitnessGlobals): void { this.current_group_visibility = this.initial_group_visibility; this.update_elements(globals); this.update_visibility(globals); } public update_elements(globals: TheWitnessGlobals): void { this.elements.length = 0; for (let i = 0; i < globals.entity_manager.flat_entity_list.length; i++) { const entity = globals.entity_manager.flat_entity_list[i]; if (entity.group_id === this.portable_id) { this.elements.push(entity.portable_id); if (entity instanceof Entity_Group) this.child_groups.push(entity.portable_id); } } } public update_visibility(globals: TheWitnessGlobals): void { const visible = this.visible && this.layer_active && this.current_group_visibility; for (let i = 0; i < this.elements.length; i++) { const entity = globals.entity_manager.entity_list[this.elements[i]]; entity.layer_active = visible; } for (let i = 0; i < this.child_groups.length; i++) { const entity = globals.entity_manager.entity_list[this.child_groups[i]] as Entity_Group; entity.update_visibility(globals); } } public set_group_visible(globals: TheWitnessGlobals, v: boolean): void { this.current_group_visibility = v; this.update_visibility(globals); } } export class Entity_Pattern_Point extends Entity { } export class Entity_Power_Cable extends Entity_Inanimate { } export class Entity_World extends Entity { public world_center: vec3; public world_z_min: number; public world_z_max: number; public shadow_render_count: number; } ```
/content/code_sandbox/src/TheWitness/Entity.ts
xml
2016-10-06T21:43:45
2024-08-16T17:03:52
noclip.website
magcius/noclip.website
3,206
2,777
```xml import { getMediaInfo } from './getMediaInfo'; describe('makeThumbnail', () => { it('does nothing when mime type is not supported', async () => { await expect(getMediaInfo(new Promise((resolve) => resolve('png')), new Blob(), true)).resolves.toEqual( undefined ); await expect( getMediaInfo(new Promise((resolve) => resolve('image/jpeeg')), new Blob(), false) ).resolves.toEqual(undefined); }); }); ```
/content/code_sandbox/packages/drive-store/store/_uploads/media/getMediaInfo.test.ts
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
105
```xml import { IContext } from '..'; import { IObjectTypeResolver } from '@graphql-tools/utils'; import { ICategory } from '../../db/models/category'; import { buildPostsQuery } from './Query/postQueries'; const ForumCategory: IObjectTypeResolver<ICategory, IContext> = { async parent({ parentId }, _, { models: { Category } }) { return Category.findById(parentId).lean(); }, async children({ _id }, _, { models: { Category } }) { return Category.find({ parentId: _id }).lean(); }, async descendants({ _id }, _, { models: { Category } }) { return Category.getDescendantsOf([_id.toString()]); }, async ancestors({ _id }, _, { models: { Category } }) { return Category.getAncestorsOf(_id.toString()); }, async posts({ _id }, params, { models }) { const { Post } = models; const query: any = await buildPostsQuery(models, { ...params, categoryId: [_id] }); const { limit = 0, offset = 0 } = params; return Post.find(query) .select({ content: -1 }) .skip(offset) .limit(limit) .lean(); }, async postsCount({ _id }, params, { models }) { const { Post } = models; params.categoryId = [_id]; const query: any = await buildPostsQuery(models, params); return Post.find(query).countDocuments(); }, async permissionGroupCategoryPermits( { _id }, params, { models: { PermissionGroupCategoryPermit } } ) { return await PermissionGroupCategoryPermit.find({ categoryId: _id }); } }; export default ForumCategory; ```
/content/code_sandbox/packages/plugin-forum-api/src/graphql/resolvers/ForumCategory.ts
xml
2016-11-11T06:54:50
2024-08-16T10:26:06
erxes
erxes/erxes
3,479
378
```xml export { Classic } from './classic'; export { ClassicDark } from './classicDark'; export { Academy } from './academy'; export { Light } from './light'; export { Dark } from './dark'; ```
/content/code_sandbox/src/theme/index.ts
xml
2016-05-26T09:21:04
2024-08-15T16:11:17
G2
antvis/G2
12,060
44
```xml import * as exported from "./JitsiConferenceEvents"; // this test is brittle on purpose because it's designed to ensure that the TypeScript conversion maintains backward compatibility describe( "/JitsiConferenceEvents members", () => { const { AUDIO_INPUT_STATE_CHANGE, AUDIO_UNMUTE_PERMISSIONS_CHANGED, AUTH_STATUS_CHANGED, BEFORE_STATISTICS_DISPOSED, CONFERENCE_ERROR, CONFERENCE_FAILED, CONFERENCE_JOIN_IN_PROGRESS, CONFERENCE_JOINED, CONFERENCE_LEFT, CONFERENCE_UNIQUE_ID_SET, CONFERENCE_VISITOR_CODECS_CHANGED, CONNECTION_ESTABLISHED, CONNECTION_INTERRUPTED, CONNECTION_RESTORED, DATA_CHANNEL_OPENED, DATA_CHANNEL_CLOSED, DISPLAY_NAME_CHANGED, DOMINANT_SPEAKER_CHANGED, CONFERENCE_CREATED_TIMESTAMP, DTMF_SUPPORT_CHANGED, E2EE_VERIFICATION_AVAILABLE, E2EE_VERIFICATION_READY, E2EE_VERIFICATION_COMPLETED, ENCODE_TIME_STATS_RECEIVED, ENDPOINT_MESSAGE_RECEIVED, ENDPOINT_STATS_RECEIVED, JVB121_STATUS, KICKED, PARTICIPANT_KICKED, PARTICIPANT_SOURCE_UPDATED, LAST_N_ENDPOINTS_CHANGED, FORWARDED_SOURCES_CHANGED, LOCK_STATE_CHANGED, SERVER_REGION_CHANGED, _MEDIA_SESSION_STARTED, _MEDIA_SESSION_ACTIVE_CHANGED, MEMBERS_ONLY_CHANGED, MESSAGE_RECEIVED, NO_AUDIO_INPUT, NOISY_MIC, NON_PARTICIPANT_MESSAGE_RECEIVED, PRIVATE_MESSAGE_RECEIVED, PARTCIPANT_FEATURES_CHANGED, PARTICIPANT_PROPERTY_CHANGED, P2P_STATUS, PHONE_NUMBER_CHANGED, PROPERTIES_CHANGED, RECORDER_STATE_CHANGED, VIDEO_SIP_GW_AVAILABILITY_CHANGED, VIDEO_SIP_GW_SESSION_STATE_CHANGED, START_MUTED_POLICY_CHANGED, STARTED_MUTED, SUBJECT_CHANGED, SUSPEND_DETECTED, TALK_WHILE_MUTED, TRACK_ADDED, TRACK_AUDIO_LEVEL_CHANGED, TRACK_MUTE_CHANGED, TRACK_REMOVED, TRACK_UNMUTE_REJECTED, TRANSCRIPTION_STATUS_CHANGED, USER_JOINED, USER_LEFT, USER_ROLE_CHANGED, USER_STATUS_CHANGED, VIDEO_UNMUTE_PERMISSIONS_CHANGED, VISITORS_MESSAGE, VISITORS_REJECTION, VISITORS_SUPPORTED_CHANGED, BOT_TYPE_CHANGED, LOBBY_USER_JOINED, LOBBY_USER_UPDATED, LOBBY_USER_LEFT, AV_MODERATION_APPROVED, AV_MODERATION_REJECTED, AV_MODERATION_CHANGED, AV_MODERATION_PARTICIPANT_APPROVED, AV_MODERATION_PARTICIPANT_REJECTED, BREAKOUT_ROOMS_MOVE_TO_ROOM, BREAKOUT_ROOMS_UPDATED, METADATA_UPDATED, SILENT_STATUS_CHANGED, REACTION_RECEIVED, JitsiConferenceEvents, ...others } = exported; it( "known members", () => { expect( AUDIO_INPUT_STATE_CHANGE ).toBe( 'conference.audio_input_state_changed' ); expect( AUDIO_UNMUTE_PERMISSIONS_CHANGED ).toBe( 'conference.audio_unmute_permissions_changed' ); expect( AUTH_STATUS_CHANGED ).toBe( 'conference.auth_status_changed' ); expect( BEFORE_STATISTICS_DISPOSED ).toBe( 'conference.beforeStatisticsDisposed' ); expect( CONFERENCE_ERROR ).toBe( 'conference.error' ); expect( CONFERENCE_FAILED ).toBe( 'conference.failed' ); expect( CONFERENCE_JOIN_IN_PROGRESS ).toBe( 'conference.join_in_progress' ); expect( CONFERENCE_JOINED ).toBe( 'conference.joined' ); expect( CONFERENCE_LEFT ).toBe( 'conference.left' ); expect( CONFERENCE_UNIQUE_ID_SET ).toBe( 'conference.unique_id_set' ); expect( CONFERENCE_VISITOR_CODECS_CHANGED ).toBe( 'conference.visitor_codecs_changed' ); expect( CONNECTION_ESTABLISHED ).toBe( 'conference.connectionEstablished' ); expect( CONNECTION_INTERRUPTED ).toBe( 'conference.connectionInterrupted' ); expect( CONNECTION_RESTORED ).toBe( 'conference.connectionRestored' ); expect( DATA_CHANNEL_OPENED ).toBe( 'conference.dataChannelOpened' ); expect( DATA_CHANNEL_CLOSED ).toBe( 'conference.dataChannelClosed' ); expect( DISPLAY_NAME_CHANGED ).toBe( 'conference.displayNameChanged' ); expect( DOMINANT_SPEAKER_CHANGED ).toBe( 'conference.dominantSpeaker' ); expect( CONFERENCE_CREATED_TIMESTAMP ).toBe( 'conference.createdTimestamp' ); expect( DTMF_SUPPORT_CHANGED ).toBe( 'conference.dtmfSupportChanged' ); expect( ENDPOINT_MESSAGE_RECEIVED ).toBe( 'conference.endpoint_message_received' ); expect( ENDPOINT_STATS_RECEIVED ).toBe( 'conference.endpoint_stats_received' ); expect( JVB121_STATUS ).toBe( 'conference.jvb121Status' ); expect( KICKED ).toBe( 'conference.kicked' ); expect( PARTICIPANT_KICKED ).toBe( 'conference.participant_kicked' ); expect( PARTICIPANT_SOURCE_UPDATED ).toBe( 'conference.participant_source_updated' ); expect( LAST_N_ENDPOINTS_CHANGED ).toBe( 'conference.lastNEndpointsChanged' ); expect( FORWARDED_SOURCES_CHANGED ).toBe( 'conference.forwardedSourcesChanged' ); expect( LOCK_STATE_CHANGED ).toBe( 'conference.lock_state_changed' ); expect( SERVER_REGION_CHANGED ).toBe( 'conference.server_region_changed' ); expect( _MEDIA_SESSION_STARTED ).toBe( 'conference.media_session.started' ); expect( _MEDIA_SESSION_ACTIVE_CHANGED ).toBe( 'conference.media_session.active_changed' ); expect( MEMBERS_ONLY_CHANGED ).toBe( 'conference.membersOnlyChanged' ); expect( MESSAGE_RECEIVED ).toBe( 'conference.messageReceived' ); expect( NO_AUDIO_INPUT ).toBe( 'conference.no_audio_input' ); expect( NOISY_MIC ).toBe( 'conference.noisy_mic' ); expect( NON_PARTICIPANT_MESSAGE_RECEIVED ).toBe( 'conference.non_participant_message_received' ); expect( PRIVATE_MESSAGE_RECEIVED ).toBe( 'conference.privateMessageReceived' ); expect( PARTCIPANT_FEATURES_CHANGED ).toBe( 'conference.partcipant_features_changed' ); expect( PARTICIPANT_PROPERTY_CHANGED ).toBe( 'conference.participant_property_changed' ); expect( P2P_STATUS ).toBe( 'conference.p2pStatus' ); expect( PHONE_NUMBER_CHANGED ).toBe( 'conference.phoneNumberChanged' ); expect( PROPERTIES_CHANGED ).toBe( 'conference.propertiesChanged' ); expect( RECORDER_STATE_CHANGED ).toBe( 'conference.recorderStateChanged' ); expect( VIDEO_SIP_GW_AVAILABILITY_CHANGED ).toBe( 'conference.videoSIPGWAvailabilityChanged' ); expect( VIDEO_SIP_GW_SESSION_STATE_CHANGED ).toBe( 'conference.videoSIPGWSessionStateChanged' ); expect( VISITORS_SUPPORTED_CHANGED ).toBe( 'conference.visitorsSupported' ); expect( START_MUTED_POLICY_CHANGED ).toBe( 'conference.start_muted_policy_changed' ); expect( STARTED_MUTED ).toBe( 'conference.started_muted' ); expect( SUBJECT_CHANGED ).toBe( 'conference.subjectChanged' ); expect( SUSPEND_DETECTED ).toBe( 'conference.suspendDetected' ); expect( TALK_WHILE_MUTED ).toBe( 'conference.talk_while_muted' ); expect( TRACK_ADDED ).toBe( 'conference.trackAdded' ); expect( TRACK_AUDIO_LEVEL_CHANGED ).toBe( 'conference.audioLevelsChanged' ); expect( TRACK_MUTE_CHANGED ).toBe( 'conference.trackMuteChanged' ); expect( TRACK_REMOVED ).toBe( 'conference.trackRemoved' ); expect( TRACK_UNMUTE_REJECTED ).toBe( 'conference.trackUnmuteRejected' ); expect( TRANSCRIPTION_STATUS_CHANGED ).toBe( 'conference.transcriptionStatusChanged' ); expect( USER_JOINED ).toBe( 'conference.userJoined' ); expect( USER_LEFT ).toBe( 'conference.userLeft' ); expect( USER_ROLE_CHANGED ).toBe( 'conference.roleChanged' ); expect( USER_STATUS_CHANGED ).toBe( 'conference.statusChanged' ); expect( VIDEO_UNMUTE_PERMISSIONS_CHANGED ).toBe( 'conference.video_unmute_permissions_changed' ); expect( VISITORS_MESSAGE ).toBe( 'conference.visitors_message' ); expect( VISITORS_REJECTION ).toBe( 'conference.visitors_rejection' ); expect( BOT_TYPE_CHANGED ).toBe( 'conference.bot_type_changed' ); expect( LOBBY_USER_JOINED ).toBe( 'conference.lobby.userJoined' ); expect( LOBBY_USER_UPDATED ).toBe( 'conference.lobby.userUpdated' ); expect( LOBBY_USER_LEFT ).toBe( 'conference.lobby.userLeft' ); expect( AV_MODERATION_APPROVED ).toBe( 'conference.av_moderation.approved' ); expect( AV_MODERATION_REJECTED ).toBe( 'conference.av_moderation.rejected' ); expect( AV_MODERATION_CHANGED ).toBe( 'conference.av_moderation.changed' ); expect( AV_MODERATION_PARTICIPANT_APPROVED ).toBe( 'conference.av_moderation.participant.approved' ); expect( AV_MODERATION_PARTICIPANT_REJECTED ).toBe( 'conference.av_moderation.participant.rejected' ); expect( BREAKOUT_ROOMS_MOVE_TO_ROOM ).toBe( 'conference.breakout-rooms.move-to-room' ); expect( BREAKOUT_ROOMS_UPDATED ).toBe( 'conference.breakout-rooms.updated' ); expect( METADATA_UPDATED ).toBe( 'conference.metadata.updated' ); expect( SILENT_STATUS_CHANGED ).toBe( 'conference.silentStatusChanged' ); expect( ENCODE_TIME_STATS_RECEIVED ).toBe( 'conference.encode_time_stats_received' ); expect( JitsiConferenceEvents ).toBeDefined(); expect( JitsiConferenceEvents.AUDIO_INPUT_STATE_CHANGE ).toBe( 'conference.audio_input_state_changed' ); expect( JitsiConferenceEvents.AUDIO_UNMUTE_PERMISSIONS_CHANGED ).toBe( 'conference.audio_unmute_permissions_changed' ); expect( JitsiConferenceEvents.AUTH_STATUS_CHANGED ).toBe( 'conference.auth_status_changed' ); expect( JitsiConferenceEvents.BEFORE_STATISTICS_DISPOSED ).toBe( 'conference.beforeStatisticsDisposed' ); expect( JitsiConferenceEvents.CONFERENCE_ERROR ).toBe( 'conference.error' ); expect( JitsiConferenceEvents.CONFERENCE_FAILED ).toBe( 'conference.failed' ); expect( JitsiConferenceEvents.CONFERENCE_JOIN_IN_PROGRESS ).toBe( 'conference.join_in_progress' ); expect( JitsiConferenceEvents.CONFERENCE_JOINED ).toBe( 'conference.joined' ); expect( JitsiConferenceEvents.CONFERENCE_LEFT ).toBe( 'conference.left' ); expect( JitsiConferenceEvents.CONFERENCE_UNIQUE_ID_SET ).toBe( 'conference.unique_id_set' ); expect( JitsiConferenceEvents.CONNECTION_ESTABLISHED ).toBe( 'conference.connectionEstablished' ); expect( JitsiConferenceEvents.CONNECTION_INTERRUPTED ).toBe( 'conference.connectionInterrupted' ); expect( JitsiConferenceEvents.CONNECTION_RESTORED ).toBe( 'conference.connectionRestored' ); expect( JitsiConferenceEvents.DATA_CHANNEL_OPENED ).toBe( 'conference.dataChannelOpened' ); expect( JitsiConferenceEvents.DATA_CHANNEL_CLOSED ).toBe( 'conference.dataChannelClosed' ); expect( JitsiConferenceEvents.DISPLAY_NAME_CHANGED ).toBe( 'conference.displayNameChanged' ); expect( JitsiConferenceEvents.DOMINANT_SPEAKER_CHANGED ).toBe( 'conference.dominantSpeaker' ); expect( JitsiConferenceEvents.CONFERENCE_CREATED_TIMESTAMP ).toBe( 'conference.createdTimestamp' ); expect( JitsiConferenceEvents.DTMF_SUPPORT_CHANGED ).toBe( 'conference.dtmfSupportChanged' ); expect( JitsiConferenceEvents.ENCODE_TIME_STATS_RECEIVED ).toBe( 'conference.encode_time_stats_received' ); expect( JitsiConferenceEvents.ENDPOINT_MESSAGE_RECEIVED ).toBe( 'conference.endpoint_message_received' ); expect( JitsiConferenceEvents.ENDPOINT_STATS_RECEIVED ).toBe( 'conference.endpoint_stats_received' ); expect( JitsiConferenceEvents.JVB121_STATUS ).toBe( 'conference.jvb121Status' ); expect( JitsiConferenceEvents.KICKED ).toBe( 'conference.kicked' ); expect( JitsiConferenceEvents.PARTICIPANT_KICKED ).toBe( 'conference.participant_kicked' ); expect( JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED ).toBe( 'conference.lastNEndpointsChanged' ); expect( JitsiConferenceEvents.FORWARDED_SOURCES_CHANGED ).toBe( 'conference.forwardedSourcesChanged' ); expect( JitsiConferenceEvents.LOCK_STATE_CHANGED ).toBe( 'conference.lock_state_changed' ); expect( JitsiConferenceEvents.SERVER_REGION_CHANGED ).toBe( 'conference.server_region_changed' ); expect( JitsiConferenceEvents._MEDIA_SESSION_STARTED ).toBe( 'conference.media_session.started' ); expect( JitsiConferenceEvents._MEDIA_SESSION_ACTIVE_CHANGED ).toBe( 'conference.media_session.active_changed' ); expect( JitsiConferenceEvents.MEMBERS_ONLY_CHANGED ).toBe( 'conference.membersOnlyChanged' ); expect( JitsiConferenceEvents.MESSAGE_RECEIVED ).toBe( 'conference.messageReceived' ); expect( JitsiConferenceEvents.NO_AUDIO_INPUT ).toBe( 'conference.no_audio_input' ); expect( JitsiConferenceEvents.NOISY_MIC ).toBe( 'conference.noisy_mic' ); expect( JitsiConferenceEvents.NON_PARTICIPANT_MESSAGE_RECEIVED ).toBe( 'conference.non_participant_message_received' ); expect( JitsiConferenceEvents.PRIVATE_MESSAGE_RECEIVED ).toBe( 'conference.privateMessageReceived' ); expect( JitsiConferenceEvents.PARTCIPANT_FEATURES_CHANGED ).toBe( 'conference.partcipant_features_changed' ); expect( JitsiConferenceEvents.PARTICIPANT_PROPERTY_CHANGED ).toBe( 'conference.participant_property_changed' ); expect( JitsiConferenceEvents.P2P_STATUS ).toBe( 'conference.p2pStatus' ); expect( JitsiConferenceEvents.PHONE_NUMBER_CHANGED ).toBe( 'conference.phoneNumberChanged' ); expect( JitsiConferenceEvents.PROPERTIES_CHANGED ).toBe( 'conference.propertiesChanged' ); expect( JitsiConferenceEvents.RECORDER_STATE_CHANGED ).toBe( 'conference.recorderStateChanged' ); expect( JitsiConferenceEvents.VIDEO_SIP_GW_AVAILABILITY_CHANGED ).toBe( 'conference.videoSIPGWAvailabilityChanged' ); expect( JitsiConferenceEvents.VIDEO_SIP_GW_SESSION_STATE_CHANGED ).toBe( 'conference.videoSIPGWSessionStateChanged' ); expect( JitsiConferenceEvents.START_MUTED_POLICY_CHANGED ).toBe( 'conference.start_muted_policy_changed' ); expect( JitsiConferenceEvents.STARTED_MUTED ).toBe( 'conference.started_muted' ); expect( JitsiConferenceEvents.SUBJECT_CHANGED ).toBe( 'conference.subjectChanged' ); expect( JitsiConferenceEvents.SUSPEND_DETECTED ).toBe( 'conference.suspendDetected' ); expect( JitsiConferenceEvents.TALK_WHILE_MUTED ).toBe( 'conference.talk_while_muted' ); expect( JitsiConferenceEvents.TRACK_ADDED ).toBe( 'conference.trackAdded' ); expect( JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED ).toBe( 'conference.audioLevelsChanged' ); expect( JitsiConferenceEvents.TRACK_MUTE_CHANGED ).toBe( 'conference.trackMuteChanged' ); expect( JitsiConferenceEvents.TRACK_REMOVED ).toBe( 'conference.trackRemoved' ); expect( JitsiConferenceEvents.TRACK_UNMUTE_REJECTED ).toBe( 'conference.trackUnmuteRejected' ); expect( JitsiConferenceEvents.TRANSCRIPTION_STATUS_CHANGED ).toBe( 'conference.transcriptionStatusChanged' ); expect( JitsiConferenceEvents.USER_JOINED ).toBe( 'conference.userJoined' ); expect( JitsiConferenceEvents.USER_LEFT ).toBe( 'conference.userLeft' ); expect( JitsiConferenceEvents.USER_ROLE_CHANGED ).toBe( 'conference.roleChanged' ); expect( JitsiConferenceEvents.USER_STATUS_CHANGED ).toBe( 'conference.statusChanged' ); expect( JitsiConferenceEvents.VIDEO_UNMUTE_PERMISSIONS_CHANGED ).toBe( 'conference.video_unmute_permissions_changed' ); expect( JitsiConferenceEvents.VISITORS_SUPPORTED_CHANGED ).toBe( 'conference.visitorsSupported' ); expect( JitsiConferenceEvents.BOT_TYPE_CHANGED ).toBe( 'conference.bot_type_changed' ); expect( JitsiConferenceEvents.LOBBY_USER_JOINED ).toBe( 'conference.lobby.userJoined' ); expect( JitsiConferenceEvents.LOBBY_USER_UPDATED ).toBe( 'conference.lobby.userUpdated' ); expect( JitsiConferenceEvents.LOBBY_USER_LEFT ).toBe( 'conference.lobby.userLeft' ); expect( JitsiConferenceEvents.AV_MODERATION_APPROVED ).toBe( 'conference.av_moderation.approved' ); expect( JitsiConferenceEvents.AV_MODERATION_REJECTED ).toBe( 'conference.av_moderation.rejected' ); expect( JitsiConferenceEvents.AV_MODERATION_CHANGED ).toBe( 'conference.av_moderation.changed' ); expect( JitsiConferenceEvents.AV_MODERATION_PARTICIPANT_APPROVED ).toBe( 'conference.av_moderation.participant.approved' ); expect( JitsiConferenceEvents.AV_MODERATION_PARTICIPANT_REJECTED ).toBe( 'conference.av_moderation.participant.rejected' ); expect( JitsiConferenceEvents.BREAKOUT_ROOMS_MOVE_TO_ROOM ).toBe( 'conference.breakout-rooms.move-to-room' ); expect( JitsiConferenceEvents.BREAKOUT_ROOMS_UPDATED ).toBe( 'conference.breakout-rooms.updated' ); expect( JitsiConferenceEvents.METADATA_UPDATED ).toBe( 'conference.metadata.updated' ); expect( JitsiConferenceEvents.SILENT_STATUS_CHANGED ).toBe( 'conference.silentStatusChanged' ); expect( JitsiConferenceEvents.E2EE_VERIFICATION_READY ).toBe( 'conference.e2ee.verification.ready' ); expect( JitsiConferenceEvents.E2EE_VERIFICATION_COMPLETED ).toBe( 'conference.e2ee.verification.completed' ); expect( JitsiConferenceEvents.E2EE_VERIFICATION_AVAILABLE ).toBe( 'conference.e2ee.verification.available' ); expect( JitsiConferenceEvents.REACTION_RECEIVED ).toBe( 'conference.reactionReceived' ); } ); it( "unknown members", () => { const keys = Object.keys( others ); expect( keys ).withContext( `Extra members: ${ keys.join( ", " ) }` ).toEqual( [] ); } ); } ); ```
/content/code_sandbox/JitsiConferenceEvents.spec.ts
xml
2016-01-27T22:44:09
2024-08-16T02:51:56
lib-jitsi-meet
jitsi/lib-jitsi-meet
1,328
4,009
```xml /* * @license Apache-2.0 * * * * 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. */ // TypeScript Version: 4.1 /// <reference types="@stdlib/types"/> /** * If provided a value, returns an updated sum of absolute values; otherwise, returns the current sum of absolute values. * * ## Notes * * - If provided `NaN` or a value which, when used in computations, results in `NaN`, the accumulated value is `NaN` for all future invocations. * * @param x - value * @returns sum of absolute values */ type accumulator = ( x?: number ) => number | null; /** * Returns an accumulator function which incrementally computes a sum of absolute values. * * @returns accumulator function * * @example * var accumulator = incrsumabs(); * * var v = accumulator(); * // returns null * * v = accumulator( 2.0 ); * // returns 2.0 * * v = accumulator( -3.0 ); * // returns 5.0 * * v = accumulator( -4.0 ); * // returns 9.0 * * v = accumulator(); * // returns 9.0 */ declare function incrsumabs(): accumulator; // EXPORTS // export = incrsumabs; ```
/content/code_sandbox/lib/node_modules/@stdlib/stats/incr/sumabs/docs/types/index.d.ts
xml
2016-03-24T04:19:52
2024-08-16T09:03:19
stdlib
stdlib-js/stdlib
4,266
302
```xml import { Custom } from '../../../src/data'; describe('custom', () => { it('Custom({...}) returns function preprocess data by specified callback', async () => { const data = [ { a: 1, b: 2, c: 3 }, { a: 2, b: 3, c: 4 }, { a: 3, b: 4, c: 1 }, { a: 4, b: 1, c: 2 }, ]; const c1 = Custom({ callback: undefined }); expect(await c1(data)).toBe(data); const c2 = Custom({ callback: (d) => d.filter((i) => i.a === 1), }); expect(await c2(data)).toEqual([{ a: 1, b: 2, c: 3 }]); }); }); ```
/content/code_sandbox/__tests__/unit/data/custom.spec.ts
xml
2016-05-26T09:21:04
2024-08-15T16:11:17
G2
antvis/G2
12,060
186
```xml import { mock, mockReset, MockProxy } from "jest-mock-extended"; import { BehaviorSubject, of, Subject } from "rxjs"; import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service"; import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status"; import { UserVerificationService } from "@bitwarden/common/auth/services/user-verification/user-verification.service"; import { AutofillOverlayVisibility } from "@bitwarden/common/autofill/constants"; import { AutofillSettingsServiceAbstraction } from "@bitwarden/common/autofill/services/autofill-settings.service"; import { DefaultDomainSettingsService, DomainSettingsService, } from "@bitwarden/common/autofill/services/domain-settings.service"; import { InlineMenuVisibilitySetting } from "@bitwarden/common/autofill/types"; import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service"; import { EventType } from "@bitwarden/common/enums"; import { UriMatchStrategy } from "@bitwarden/common/models/domain/domain-service"; import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { MessageListener } from "@bitwarden/common/platform/messaging"; import { Utils } from "@bitwarden/common/platform/misc/utils"; import { EventCollectionService } from "@bitwarden/common/services/event/event-collection.service"; import { FakeStateProvider, FakeAccountService, mockAccountServiceWith, subscribeTo, } from "@bitwarden/common/spec"; import { UserId } from "@bitwarden/common/types/guid"; import { FieldType, LinkedIdType, LoginLinkedId, CipherType } from "@bitwarden/common/vault/enums"; import { CipherRepromptType } from "@bitwarden/common/vault/enums/cipher-reprompt-type"; import { CardView } from "@bitwarden/common/vault/models/view/card.view"; import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view"; import { FieldView } from "@bitwarden/common/vault/models/view/field.view"; import { IdentityView } from "@bitwarden/common/vault/models/view/identity.view"; import { LoginUriView } from "@bitwarden/common/vault/models/view/login-uri.view"; import { LoginView } from "@bitwarden/common/vault/models/view/login.view"; import { CipherService } from "@bitwarden/common/vault/services/cipher.service"; import { TotpService } from "@bitwarden/common/vault/services/totp.service"; import { BrowserApi } from "../../platform/browser/browser-api"; import { BrowserScriptInjectorService } from "../../platform/services/browser-script-injector.service"; import { AutofillMessageCommand, AutofillMessageSender } from "../enums/autofill-message.enums"; import { AutofillPort } from "../enums/autofill-port.enum"; import AutofillField from "../models/autofill-field"; import AutofillPageDetails from "../models/autofill-page-details"; import AutofillScript from "../models/autofill-script"; import { createAutofillFieldMock, createAutofillPageDetailsMock, createAutofillScriptMock, createChromeTabMock, createGenerateFillScriptOptionsMock, } from "../spec/autofill-mocks"; import { flushPromises, triggerTestFailure } from "../spec/testing-utils"; import { AutoFillOptions, CollectPageDetailsResponseMessage, GenerateFillScriptOptions, PageDetail, } from "./abstractions/autofill.service"; import { AutoFillConstants } from "./autofill-constants"; import AutofillService from "./autofill.service"; const mockEquivalentDomains = [ ["example.com", "exampleapp.com", "example.co.uk", "ejemplo.es"], ["bitwarden.com", "bitwarden.co.uk", "sm-bitwarden.com"], ["example.co.uk", "exampleapp.co.uk"], ]; describe("AutofillService", () => { let autofillService: AutofillService; const cipherService = mock<CipherService>(); let inlineMenuVisibilityMock$!: BehaviorSubject<InlineMenuVisibilitySetting>; let autofillSettingsService: MockProxy<AutofillSettingsServiceAbstraction>; const mockUserId = Utils.newGuid() as UserId; const accountService: FakeAccountService = mockAccountServiceWith(mockUserId); const fakeStateProvider: FakeStateProvider = new FakeStateProvider(accountService); let domainSettingsService: DomainSettingsService; let scriptInjectorService: BrowserScriptInjectorService; const totpService = mock<TotpService>(); const eventCollectionService = mock<EventCollectionService>(); const logService = mock<LogService>(); const userVerificationService = mock<UserVerificationService>(); const billingAccountProfileStateService = mock<BillingAccountProfileStateService>(); const platformUtilsService = mock<PlatformUtilsService>(); let activeAccountStatusMock$: BehaviorSubject<AuthenticationStatus>; let authService: MockProxy<AuthService>; let configService: MockProxy<ConfigService>; let messageListener: MockProxy<MessageListener>; beforeEach(() => { scriptInjectorService = new BrowserScriptInjectorService(platformUtilsService, logService); inlineMenuVisibilityMock$ = new BehaviorSubject(AutofillOverlayVisibility.OnFieldFocus); autofillSettingsService = mock<AutofillSettingsServiceAbstraction>(); autofillSettingsService.inlineMenuVisibility$ = inlineMenuVisibilityMock$; activeAccountStatusMock$ = new BehaviorSubject(AuthenticationStatus.Unlocked); authService = mock<AuthService>(); authService.activeAccountStatus$ = activeAccountStatusMock$; configService = mock<ConfigService>(); messageListener = mock<MessageListener>(); autofillService = new AutofillService( cipherService, autofillSettingsService, totpService, eventCollectionService, logService, domainSettingsService, userVerificationService, billingAccountProfileStateService, scriptInjectorService, accountService, authService, configService, messageListener, ); domainSettingsService = new DefaultDomainSettingsService(fakeStateProvider); domainSettingsService.equivalentDomains$ = of(mockEquivalentDomains); jest.spyOn(BrowserApi, "tabSendMessage"); }); afterEach(() => { jest.clearAllMocks(); mockReset(cipherService); }); describe("collectPageDetailsFromTab$", () => { const tab = mock<chrome.tabs.Tab>({ id: 1 }); const messages = new Subject<CollectPageDetailsResponseMessage>(); function mockCollectPageDetailsResponseMessage( tab: chrome.tabs.Tab, webExtSender: chrome.runtime.MessageSender = mock<chrome.runtime.MessageSender>(), sender: string = AutofillMessageSender.collectPageDetailsFromTabObservable, ): CollectPageDetailsResponseMessage { return mock<CollectPageDetailsResponseMessage>({ tab, webExtSender, sender, }); } beforeEach(() => { messageListener.messages$.mockReturnValue(messages.asObservable()); }); it("sends a `collectPageDetails` message to the passed tab", () => { autofillService.collectPageDetailsFromTab$(tab); expect(BrowserApi.tabSendMessage).toHaveBeenCalledWith(tab, { command: AutofillMessageCommand.collectPageDetails, sender: AutofillMessageSender.collectPageDetailsFromTabObservable, tab, }); }); it("builds an array of page details from received `collectPageDetailsResponse` messages", async () => { const topLevelSender = mock<chrome.runtime.MessageSender>({ tab, frameId: 0 }); const subFrameSender = mock<chrome.runtime.MessageSender>({ tab, frameId: 1 }); const tracker = subscribeTo(autofillService.collectPageDetailsFromTab$(tab)); const pausePromise = tracker.pauseUntilReceived(2); messages.next(mockCollectPageDetailsResponseMessage(tab, topLevelSender)); messages.next(mockCollectPageDetailsResponseMessage(tab, subFrameSender)); await pausePromise; expect(tracker.emissions[1].length).toBe(2); }); it("ignores messages from a different tab", async () => { const otherTab = mock<chrome.tabs.Tab>({ id: 2 }); const tracker = subscribeTo(autofillService.collectPageDetailsFromTab$(tab)); const pausePromise = tracker.pauseUntilReceived(1); messages.next(mockCollectPageDetailsResponseMessage(tab)); messages.next(mockCollectPageDetailsResponseMessage(otherTab)); await pausePromise; expect(tracker.emissions[1]).toBeUndefined(); }); it("ignores messages from a different sender", async () => { const tracker = subscribeTo(autofillService.collectPageDetailsFromTab$(tab)); const pausePromise = tracker.pauseUntilReceived(1); messages.next(mockCollectPageDetailsResponseMessage(tab)); messages.next( mockCollectPageDetailsResponseMessage( tab, mock<chrome.runtime.MessageSender>(), "some-other-sender", ), ); await pausePromise; expect(tracker.emissions[1]).toBeUndefined(); }); }); describe("loadAutofillScriptsOnInstall", () => { let tab1: chrome.tabs.Tab; let tab2: chrome.tabs.Tab; let tab3: chrome.tabs.Tab; beforeEach(() => { tab1 = createChromeTabMock({ id: 1, url: "path_to_url" }); tab2 = createChromeTabMock({ id: 2, url: "path_to_url" }); tab3 = createChromeTabMock({ id: 3, url: "chrome-extension://some-extension-route" }); jest.spyOn(BrowserApi, "tabsQuery").mockResolvedValueOnce([tab1, tab2]); jest .spyOn(BrowserApi, "getAllFrameDetails") .mockResolvedValue([mock<chrome.webNavigation.GetAllFrameResultDetails>({ frameId: 0 })]); jest .spyOn(autofillService, "getInlineMenuVisibility") .mockResolvedValue(AutofillOverlayVisibility.OnFieldFocus); jest.spyOn(autofillService, "getAutofillOnPageLoad").mockResolvedValue(true); }); it("queries all browser tabs and injects the autofill scripts into them", async () => { jest.spyOn(autofillService, "injectAutofillScripts"); await autofillService.loadAutofillScriptsOnInstall(); await flushPromises(); expect(BrowserApi.tabsQuery).toHaveBeenCalledWith({}); expect(autofillService.injectAutofillScripts).toHaveBeenCalledWith(tab1, 0, false); expect(autofillService.injectAutofillScripts).toHaveBeenCalledWith(tab2, 0, false); }); it("skips injecting scripts into tabs that do not have an http(s) protocol", async () => { jest.spyOn(autofillService, "injectAutofillScripts"); await autofillService.loadAutofillScriptsOnInstall(); expect(BrowserApi.tabsQuery).toHaveBeenCalledWith({}); expect(autofillService.injectAutofillScripts).not.toHaveBeenCalledWith(tab3); }); it("sets up an extension runtime onConnect listener", async () => { await autofillService.loadAutofillScriptsOnInstall(); // eslint-disable-next-line no-restricted-syntax expect(chrome.runtime.onConnect.addListener).toHaveBeenCalledWith(expect.any(Function)); }); describe("handle inline menu visibility change", () => { beforeEach(async () => { await autofillService.loadAutofillScriptsOnInstall(); jest.spyOn(BrowserApi, "tabsQuery").mockResolvedValue([tab1, tab2]); jest.spyOn(BrowserApi, "tabSendMessageData").mockImplementation(); jest.spyOn(autofillService, "reloadAutofillScripts").mockImplementation(); }); it("returns early if the setting is being initialized", async () => { await flushPromises(); expect(BrowserApi.tabsQuery).toHaveBeenCalledTimes(1); expect(BrowserApi.tabSendMessageData).not.toHaveBeenCalled(); }); it("returns early if the previous setting is equivalent to the new setting", async () => { inlineMenuVisibilityMock$.next(AutofillOverlayVisibility.OnFieldFocus); await flushPromises(); expect(BrowserApi.tabsQuery).toHaveBeenCalledTimes(1); expect(BrowserApi.tabSendMessageData).not.toHaveBeenCalled(); }); describe("updates the inline menu visibility setting", () => { it("when changing the inline menu from on focus of field to on button click", async () => { inlineMenuVisibilityMock$.next(AutofillOverlayVisibility.OnButtonClick); await flushPromises(); expect(BrowserApi.tabSendMessageData).toHaveBeenCalledWith( tab1, "updateAutofillInlineMenuVisibility", { inlineMenuVisibility: AutofillOverlayVisibility.OnButtonClick }, ); expect(BrowserApi.tabSendMessageData).toHaveBeenCalledWith( tab2, "updateAutofillInlineMenuVisibility", { inlineMenuVisibility: AutofillOverlayVisibility.OnButtonClick }, ); }); it("when changing the inline menu from button click to field focus", async () => { inlineMenuVisibilityMock$.next(AutofillOverlayVisibility.OnButtonClick); inlineMenuVisibilityMock$.next(AutofillOverlayVisibility.OnFieldFocus); await flushPromises(); expect(BrowserApi.tabSendMessageData).toHaveBeenCalledWith( tab1, "updateAutofillInlineMenuVisibility", { inlineMenuVisibility: AutofillOverlayVisibility.OnFieldFocus }, ); expect(BrowserApi.tabSendMessageData).toHaveBeenCalledWith( tab2, "updateAutofillInlineMenuVisibility", { inlineMenuVisibility: AutofillOverlayVisibility.OnFieldFocus }, ); }); }); describe("reloads the autofill scripts", () => { it("when changing the inline menu from a disabled setting to an enabled setting", async () => { inlineMenuVisibilityMock$.next(AutofillOverlayVisibility.Off); inlineMenuVisibilityMock$.next(AutofillOverlayVisibility.OnFieldFocus); await flushPromises(); expect(autofillService.reloadAutofillScripts).toHaveBeenCalled(); }); it("when changing the inline menu from a enabled setting to a disabled setting", async () => { inlineMenuVisibilityMock$.next(AutofillOverlayVisibility.OnFieldFocus); inlineMenuVisibilityMock$.next(AutofillOverlayVisibility.Off); await flushPromises(); expect(autofillService.reloadAutofillScripts).toHaveBeenCalled(); }); }); }); }); describe("reloadAutofillScripts", () => { it("re-injects the autofill scripts in all tabs and disconnects all connected ports", () => { const port1 = mock<chrome.runtime.Port>(); const port2 = mock<chrome.runtime.Port>(); autofillService["autofillScriptPortsSet"] = new Set([port1, port2]); jest.spyOn(autofillService as any, "injectAutofillScriptsInAllTabs"); jest.spyOn(autofillService, "getAutofillOnPageLoad").mockResolvedValue(true); // FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling. // eslint-disable-next-line @typescript-eslint/no-floating-promises autofillService.reloadAutofillScripts(); expect(port1.disconnect).toHaveBeenCalled(); expect(port2.disconnect).toHaveBeenCalled(); expect(autofillService["autofillScriptPortsSet"].size).toBe(0); expect(autofillService["injectAutofillScriptsInAllTabs"]).toHaveBeenCalled(); }); }); describe("injectAutofillScripts", () => { const autofillBootstrapScript = "bootstrap-autofill.js"; const autofillOverlayBootstrapScript = "bootstrap-autofill-overlay.js"; const defaultAutofillScripts = ["autofiller.js", "notificationBar.js", "contextMenuHandler.js"]; const defaultExecuteScriptOptions = { runAt: "document_start" }; let tabMock: chrome.tabs.Tab; let sender: chrome.runtime.MessageSender; beforeEach(() => { configService.getFeatureFlag.mockResolvedValue(true); tabMock = createChromeTabMock(); sender = { tab: tabMock, frameId: 1 }; jest.spyOn(BrowserApi, "executeScriptInTab").mockImplementation(); jest .spyOn(autofillService, "getInlineMenuVisibility") .mockResolvedValue(AutofillOverlayVisibility.OnFieldFocus); jest.spyOn(autofillService, "getAutofillOnPageLoad").mockResolvedValue(true); }); it("accepts an extension message sender and injects the autofill scripts into the tab of the sender", async () => { await autofillService.injectAutofillScripts(sender.tab, sender.frameId, true); [autofillOverlayBootstrapScript, ...defaultAutofillScripts].forEach((scriptName) => { expect(BrowserApi.executeScriptInTab).toHaveBeenCalledWith(tabMock.id, { file: `content/${scriptName}`, frameId: sender.frameId, ...defaultExecuteScriptOptions, }); }); }); it("skips injecting autofiller script when autofill on load setting is disabled", async () => { jest.spyOn(autofillService, "getAutofillOnPageLoad").mockResolvedValue(false); await autofillService.injectAutofillScripts(sender.tab, sender.frameId, true); expect(BrowserApi.executeScriptInTab).not.toHaveBeenCalledWith(tabMock.id, { file: "content/autofiller.js", frameId: sender.frameId, ...defaultExecuteScriptOptions, }); }); it("skips injecting the autofiller script when the user's account is not unlocked", async () => { activeAccountStatusMock$.next(AuthenticationStatus.Locked); await autofillService.injectAutofillScripts(sender.tab, sender.frameId, true); expect(BrowserApi.executeScriptInTab).not.toHaveBeenCalledWith(tabMock.id, { file: "content/autofiller.js", frameId: sender.frameId, ...defaultExecuteScriptOptions, }); }); it("will inject the bootstrap-autofill-overlay script if the user has the autofill overlay enabled", async () => { await autofillService.injectAutofillScripts(sender.tab, sender.frameId); expect(BrowserApi.executeScriptInTab).toHaveBeenCalledWith(tabMock.id, { file: `content/${autofillOverlayBootstrapScript}`, frameId: sender.frameId, ...defaultExecuteScriptOptions, }); expect(BrowserApi.executeScriptInTab).not.toHaveBeenCalledWith(tabMock.id, { file: `content/${autofillBootstrapScript}`, frameId: sender.frameId, ...defaultExecuteScriptOptions, }); }); it("will inject the bootstrap-autofill script if the user does not have the autofill overlay enabled", async () => { jest .spyOn(autofillService, "getInlineMenuVisibility") .mockResolvedValue(AutofillOverlayVisibility.Off); await autofillService.injectAutofillScripts(sender.tab, sender.frameId); expect(BrowserApi.executeScriptInTab).toHaveBeenCalledWith(tabMock.id, { file: `content/${autofillBootstrapScript}`, frameId: sender.frameId, ...defaultExecuteScriptOptions, }); expect(BrowserApi.executeScriptInTab).not.toHaveBeenCalledWith(tabMock.id, { file: `content/${autofillOverlayBootstrapScript}`, frameId: sender.frameId, ...defaultExecuteScriptOptions, }); }); it("injects the content-message-handler script if not injecting on page load", async () => { await autofillService.injectAutofillScripts(sender.tab, sender.frameId, false); expect(BrowserApi.executeScriptInTab).toHaveBeenCalledWith(tabMock.id, { file: "content/content-message-handler.js", frameId: 0, ...defaultExecuteScriptOptions, }); }); }); describe("getFormsWithPasswordFields", () => { let pageDetailsMock: AutofillPageDetails; beforeEach(() => { pageDetailsMock = createAutofillPageDetailsMock(); }); it("returns an empty FormData array if no password fields are found", () => { jest.spyOn(AutofillService, "loadPasswordFields"); const formData = autofillService.getFormsWithPasswordFields(pageDetailsMock); expect(AutofillService.loadPasswordFields).toHaveBeenCalledWith( pageDetailsMock, true, true, false, true, ); expect(formData).toStrictEqual([]); }); it("returns an FormData array containing a form with it's autofill data", () => { const usernameInputField = createAutofillFieldMock({ opid: "username-field", form: "validFormId", elementNumber: 1, }); const passwordInputField = createAutofillFieldMock({ opid: "password-field", type: "password", form: "validFormId", elementNumber: 2, }); pageDetailsMock.fields = [usernameInputField, passwordInputField]; const formData = autofillService.getFormsWithPasswordFields(pageDetailsMock); expect(formData).toStrictEqual([ { form: pageDetailsMock.forms.validFormId, password: pageDetailsMock.fields[1], passwords: [pageDetailsMock.fields[1]], username: pageDetailsMock.fields[0], }, ]); }); it("narrows down three passwords that are present on a page to a single password field to autofill when only one form element is present on the page", () => { const usernameInputField = createAutofillFieldMock({ opid: "username-field", form: "validFormId", elementNumber: 1, }); const passwordInputField = createAutofillFieldMock({ opid: "password-field", type: "password", form: "validFormId", elementNumber: 2, }); const secondPasswordInputField = createAutofillFieldMock({ opid: "another-password-field", type: "password", form: undefined, elementNumber: 3, }); const thirdPasswordInputField = createAutofillFieldMock({ opid: "a-third-password-field", type: "password", form: undefined, elementNumber: 4, }); pageDetailsMock.fields = [ usernameInputField, passwordInputField, secondPasswordInputField, thirdPasswordInputField, ]; const formData = autofillService.getFormsWithPasswordFields(pageDetailsMock); expect(formData).toStrictEqual([ { form: pageDetailsMock.forms.validFormId, password: pageDetailsMock.fields[1], passwords: [ pageDetailsMock.fields[1], { ...pageDetailsMock.fields[2], form: pageDetailsMock.fields[1].form }, { ...pageDetailsMock.fields[3], form: pageDetailsMock.fields[1].form }, ], username: pageDetailsMock.fields[0], }, ]); }); it("will check for a hidden username field", () => { const usernameInputField = createAutofillFieldMock({ opid: "username-field", form: "validFormId", elementNumber: 1, isViewable: false, readonly: true, }); const passwordInputField = createAutofillFieldMock({ opid: "password-field", type: "password", form: "validFormId", elementNumber: 2, }); pageDetailsMock.fields = [usernameInputField, passwordInputField]; jest.spyOn(autofillService as any, "findUsernameField"); const formData = autofillService.getFormsWithPasswordFields(pageDetailsMock); expect(autofillService["findUsernameField"]).toHaveBeenCalledWith( pageDetailsMock, passwordInputField, true, true, false, ); expect(formData).toStrictEqual([ { form: pageDetailsMock.forms.validFormId, password: pageDetailsMock.fields[1], passwords: [pageDetailsMock.fields[1]], username: pageDetailsMock.fields[0], }, ]); }); }); describe("doAutoFill", () => { let autofillOptions: AutoFillOptions; const nothingToAutofillError = "Nothing to autofill."; const didNotAutofillError = "Did not autofill."; beforeEach(() => { autofillOptions = { cipher: mock<CipherView>({ id: "cipherId", type: CipherType.Login, }), pageDetails: [ { frameId: 1, tab: createChromeTabMock(), details: createAutofillPageDetailsMock({ fields: [ createAutofillFieldMock({ opid: "username-field", form: "validFormId", elementNumber: 1, }), createAutofillFieldMock({ opid: "password-field", type: "password", form: "validFormId", elementNumber: 2, }), ], }), }, ], tab: createChromeTabMock(), }; autofillOptions.cipher.fields = [mock<FieldView>({ name: "username" })]; autofillOptions.cipher.login.matchesUri = jest.fn().mockReturnValue(true); autofillOptions.cipher.login.username = "username"; autofillOptions.cipher.login.password = "password"; jest.spyOn(autofillService, "getDefaultUriMatchStrategy").mockResolvedValue(0); }); describe("given a set of autofill options that are incomplete", () => { it("throws an error if the tab is not provided", async () => { autofillOptions.tab = undefined; try { await autofillService.doAutoFill(autofillOptions); triggerTestFailure(); } catch (error) { expect(error.message).toBe(nothingToAutofillError); } }); it("throws an error if the cipher is not provided", async () => { autofillOptions.cipher = undefined; try { await autofillService.doAutoFill(autofillOptions); triggerTestFailure(); } catch (error) { expect(error.message).toBe(nothingToAutofillError); } }); it("throws an error if the page details are not provided", async () => { autofillOptions.pageDetails = undefined; try { await autofillService.doAutoFill(autofillOptions); triggerTestFailure(); } catch (error) { expect(error.message).toBe(nothingToAutofillError); } }); it("throws an error if the page details are empty", async () => { autofillOptions.pageDetails = []; try { await autofillService.doAutoFill(autofillOptions); triggerTestFailure(); } catch (error) { expect(error.message).toBe(nothingToAutofillError); } }); it("throws an error if an autofill did not occur for any of the passed pages", async () => { autofillOptions.tab.url = "path_to_url"; billingAccountProfileStateService.hasPremiumFromAnySource$ = of(true); try { await autofillService.doAutoFill(autofillOptions); triggerTestFailure(); } catch (error) { expect(error.message).toBe(didNotAutofillError); } }); }); it("will autofill login data for a page", async () => { jest.spyOn(autofillService as any, "generateFillScript"); jest.spyOn(autofillService as any, "generateLoginFillScript"); jest.spyOn(logService, "info"); jest.spyOn(cipherService, "updateLastUsedDate"); jest.spyOn(eventCollectionService, "collect"); const autofillResult = await autofillService.doAutoFill(autofillOptions); const currentAutofillPageDetails = autofillOptions.pageDetails[0]; expect(autofillService["generateFillScript"]).toHaveBeenCalledWith( currentAutofillPageDetails.details, { skipUsernameOnlyFill: autofillOptions.skipUsernameOnlyFill || false, onlyEmptyFields: autofillOptions.onlyEmptyFields || false, onlyVisibleFields: autofillOptions.onlyVisibleFields || false, fillNewPassword: autofillOptions.fillNewPassword || false, allowTotpAutofill: autofillOptions.allowTotpAutofill || false, autoSubmitLogin: autofillOptions.allowTotpAutofill || false, cipher: autofillOptions.cipher, tabUrl: autofillOptions.tab.url, defaultUriMatch: 0, }, ); expect(autofillService["generateLoginFillScript"]).toHaveBeenCalled(); expect(logService.info).not.toHaveBeenCalled(); expect(cipherService.updateLastUsedDate).toHaveBeenCalledWith(autofillOptions.cipher.id); expect(chrome.tabs.sendMessage).toHaveBeenCalledWith( autofillOptions.pageDetails[0].tab.id, { command: "fillForm", fillScript: { metadata: {}, properties: { delay_between_operations: 20, }, savedUrls: [], script: [ ["click_on_opid", "username-field"], ["focus_by_opid", "username-field"], ["fill_by_opid", "username-field", "username"], ["click_on_opid", "password-field"], ["focus_by_opid", "password-field"], ["fill_by_opid", "password-field", "password"], ["focus_by_opid", "password-field"], ], untrustedIframe: false, }, url: currentAutofillPageDetails.tab.url, pageDetailsUrl: "url", }, { frameId: currentAutofillPageDetails.frameId, }, expect.any(Function), ); expect(eventCollectionService.collect).toHaveBeenCalledWith( EventType.Cipher_ClientAutofilled, autofillOptions.cipher.id, ); expect(autofillResult).toBeNull(); }); it("will autofill card data for a page", async () => { autofillOptions.cipher.type = CipherType.Card; autofillOptions.cipher.card = mock<CardView>({ cardholderName: "cardholderName", }); autofillOptions.pageDetails[0].details.fields = [ createAutofillFieldMock({ opid: "cardholderName", form: "validFormId", elementNumber: 2, autoCompleteType: "cc-name", }), ]; jest.spyOn(autofillService as any, "generateCardFillScript"); jest.spyOn(eventCollectionService, "collect"); await autofillService.doAutoFill(autofillOptions); expect(autofillService["generateCardFillScript"]).toHaveBeenCalled(); expect(chrome.tabs.sendMessage).toHaveBeenCalled(); expect(eventCollectionService.collect).toHaveBeenCalledWith( EventType.Cipher_ClientAutofilled, autofillOptions.cipher.id, ); }); it("will autofill identity data for a page", async () => { autofillOptions.cipher.type = CipherType.Identity; autofillOptions.cipher.identity = mock<IdentityView>({ firstName: "firstName", middleName: "middleName", lastName: "lastName", }); autofillOptions.pageDetails[0].details.fields = [ createAutofillFieldMock({ opid: "full-name", form: "validFormId", elementNumber: 2, autoCompleteType: "full-name", }), ]; jest.spyOn(autofillService as any, "generateIdentityFillScript"); jest.spyOn(eventCollectionService, "collect"); await autofillService.doAutoFill(autofillOptions); expect(autofillService["generateIdentityFillScript"]).toHaveBeenCalled(); expect(chrome.tabs.sendMessage).toHaveBeenCalled(); expect(eventCollectionService.collect).toHaveBeenCalledWith( EventType.Cipher_ClientAutofilled, autofillOptions.cipher.id, ); }); it("blocks autofill on an untrusted iframe", async () => { autofillOptions.allowUntrustedIframe = false; autofillOptions.cipher.login.matchesUri = jest.fn().mockReturnValueOnce(false); jest.spyOn(logService, "info"); try { await autofillService.doAutoFill(autofillOptions); triggerTestFailure(); } catch (error) { expect(logService.info).toHaveBeenCalledWith( "Autofill on page load was blocked due to an untrusted iframe.", ); expect(error.message).toBe(didNotAutofillError); } }); it("allows autofill on an untrusted iframe if the passed option allowing untrusted iframes is set to true", async () => { autofillOptions.allowUntrustedIframe = true; autofillOptions.cipher.login.matchesUri = jest.fn().mockReturnValue(false); jest.spyOn(logService, "info"); await autofillService.doAutoFill(autofillOptions); expect(logService.info).not.toHaveBeenCalledWith( "Autofill on page load was blocked due to an untrusted iframe.", ); }); it("skips updating the cipher's last used date if the passed options indicate that we should skip the last used cipher", async () => { autofillOptions.skipLastUsed = true; jest.spyOn(cipherService, "updateLastUsedDate"); await autofillService.doAutoFill(autofillOptions); expect(cipherService.updateLastUsedDate).not.toHaveBeenCalled(); }); it("returns early if the fillScript cannot be generated", async () => { jest.spyOn(autofillService as any, "generateFillScript").mockReturnValueOnce(undefined); jest.spyOn(BrowserApi, "tabSendMessage"); try { await autofillService.doAutoFill(autofillOptions); triggerTestFailure(); } catch (error) { expect(autofillService["generateFillScript"]).toHaveBeenCalled(); expect(BrowserApi.tabSendMessage).not.toHaveBeenCalled(); expect(error.message).toBe(didNotAutofillError); } }); it("returns a TOTP value", async () => { const totpCode = "123456"; autofillOptions.cipher.login.totp = "totp"; billingAccountProfileStateService.hasPremiumFromAnySource$ = of(true); jest.spyOn(autofillService, "getShouldAutoCopyTotp").mockResolvedValue(true); jest.spyOn(totpService, "getCode").mockResolvedValue(totpCode); const autofillResult = await autofillService.doAutoFill(autofillOptions); expect(autofillService.getShouldAutoCopyTotp).toHaveBeenCalled(); expect(totpService.getCode).toHaveBeenCalledWith(autofillOptions.cipher.login.totp); expect(autofillResult).toBe(totpCode); }); it("does not return a TOTP value if the user does not have premium features", async () => { autofillOptions.cipher.login.totp = "totp"; billingAccountProfileStateService.hasPremiumFromAnySource$ = of(false); jest.spyOn(autofillService, "getShouldAutoCopyTotp").mockResolvedValue(true); const autofillResult = await autofillService.doAutoFill(autofillOptions); expect(autofillService.getShouldAutoCopyTotp).not.toHaveBeenCalled(); expect(totpService.getCode).not.toHaveBeenCalled(); expect(autofillResult).toBeNull(); }); it("returns a null value if the cipher type is not for a Login", async () => { autofillOptions.cipher.type = CipherType.Identity; autofillOptions.cipher.identity = mock<IdentityView>(); const autofillResult = await autofillService.doAutoFill(autofillOptions); expect(autofillResult).toBeNull(); }); it("returns a null value if the login does not contain a TOTP value", async () => { autofillOptions.cipher.login.totp = undefined; jest.spyOn(autofillService, "getShouldAutoCopyTotp"); jest.spyOn(totpService, "getCode"); const autofillResult = await autofillService.doAutoFill(autofillOptions); expect(autofillService.getShouldAutoCopyTotp).not.toHaveBeenCalled(); expect(totpService.getCode).not.toHaveBeenCalled(); expect(autofillResult).toBeNull(); }); it("returns a null value if the user cannot access premium and the organization does not use TOTP", async () => { autofillOptions.cipher.login.totp = "totp"; autofillOptions.cipher.organizationUseTotp = false; billingAccountProfileStateService.hasPremiumFromAnySource$ = of(false); const autofillResult = await autofillService.doAutoFill(autofillOptions); expect(autofillResult).toBeNull(); }); it("returns a null value if the user has disabled `auto TOTP copy`", async () => { autofillOptions.cipher.login.totp = "totp"; autofillOptions.cipher.organizationUseTotp = true; billingAccountProfileStateService.hasPremiumFromAnySource$ = of(true); jest.spyOn(autofillService, "getShouldAutoCopyTotp").mockResolvedValue(false); jest.spyOn(totpService, "getCode"); const autofillResult = await autofillService.doAutoFill(autofillOptions); expect(autofillService.getShouldAutoCopyTotp).toHaveBeenCalled(); expect(totpService.getCode).not.toHaveBeenCalled(); expect(autofillResult).toBeNull(); }); }); describe("doAutoFillOnTab", () => { let pageDetails: PageDetail[]; let tab: chrome.tabs.Tab; beforeEach(() => { tab = createChromeTabMock(); pageDetails = [ { frameId: 1, tab: createChromeTabMock(), details: createAutofillPageDetailsMock({ fields: [ createAutofillFieldMock({ opid: "username-field", form: "validFormId", elementNumber: 1, }), createAutofillFieldMock({ opid: "password-field", type: "password", form: "validFormId", elementNumber: 2, }), ], }), }, ]; }); describe("given a tab url which does not match a cipher", () => { it("will skip autofill and return a null value when triggering on page load", async () => { jest.spyOn(autofillService, "doAutoFill"); jest.spyOn(cipherService, "getNextCipherForUrl"); jest.spyOn(cipherService, "getLastLaunchedForUrl").mockResolvedValueOnce(null); jest.spyOn(cipherService, "getLastUsedForUrl").mockResolvedValueOnce(null); const result = await autofillService.doAutoFillOnTab(pageDetails, tab, false); expect(cipherService.getNextCipherForUrl).not.toHaveBeenCalled(); expect(cipherService.getLastLaunchedForUrl).toHaveBeenCalledWith(tab.url, true); expect(cipherService.getLastUsedForUrl).toHaveBeenCalledWith(tab.url, true); expect(autofillService.doAutoFill).not.toHaveBeenCalled(); expect(result).toBeNull(); }); it("will skip autofill and return a null value when triggering from a keyboard shortcut", async () => { jest.spyOn(autofillService, "doAutoFill"); jest.spyOn(cipherService, "getNextCipherForUrl").mockResolvedValueOnce(null); jest.spyOn(cipherService, "getLastLaunchedForUrl").mockResolvedValueOnce(null); jest.spyOn(cipherService, "getLastUsedForUrl").mockResolvedValueOnce(null); const result = await autofillService.doAutoFillOnTab(pageDetails, tab, true); expect(cipherService.getNextCipherForUrl).toHaveBeenCalledWith(tab.url); expect(cipherService.getLastLaunchedForUrl).not.toHaveBeenCalled(); expect(cipherService.getLastUsedForUrl).not.toHaveBeenCalled(); expect(autofillService.doAutoFill).not.toHaveBeenCalled(); expect(result).toBeNull(); }); }); describe("given a tab url which matches a cipher", () => { let cipher: CipherView; beforeEach(() => { cipher = mock<CipherView>({ reprompt: CipherRepromptType.None, localData: { lastLaunched: Date.now().valueOf(), }, }); }); it("will autofill the last launched cipher and return a TOTP value when triggering on page load", async () => { const totpCode = "123456"; const fromCommand = false; jest.spyOn(autofillService, "doAutoFill").mockResolvedValueOnce(totpCode); jest.spyOn(cipherService, "getLastLaunchedForUrl").mockResolvedValueOnce(cipher); jest.spyOn(cipherService, "getLastUsedForUrl"); jest.spyOn(cipherService, "updateLastUsedIndexForUrl"); const result = await autofillService.doAutoFillOnTab(pageDetails, tab, fromCommand); expect(cipherService.getLastLaunchedForUrl).toHaveBeenCalledWith(tab.url, true); expect(cipherService.getLastUsedForUrl).not.toHaveBeenCalled(); expect(cipherService.updateLastUsedIndexForUrl).not.toHaveBeenCalled(); expect(autofillService.doAutoFill).toHaveBeenCalledWith({ tab: tab, cipher: cipher, pageDetails: pageDetails, skipLastUsed: !fromCommand, skipUsernameOnlyFill: !fromCommand, onlyEmptyFields: !fromCommand, onlyVisibleFields: !fromCommand, fillNewPassword: fromCommand, allowUntrustedIframe: fromCommand, allowTotpAutofill: fromCommand, autoSubmitLogin: false, }); expect(result).toBe(totpCode); }); it("will autofill the last used cipher and return a TOTP value when triggering on page load ", async () => { cipher.localData.lastLaunched = Date.now().valueOf() - 30001; const totpCode = "123456"; const fromCommand = false; jest.spyOn(autofillService, "doAutoFill").mockResolvedValueOnce(totpCode); jest.spyOn(cipherService, "getLastLaunchedForUrl").mockResolvedValueOnce(cipher); jest.spyOn(cipherService, "getLastUsedForUrl").mockResolvedValueOnce(cipher); jest.spyOn(cipherService, "updateLastUsedIndexForUrl"); const result = await autofillService.doAutoFillOnTab(pageDetails, tab, fromCommand); expect(cipherService.getLastLaunchedForUrl).toHaveBeenCalledWith(tab.url, true); expect(cipherService.getLastUsedForUrl).toHaveBeenCalledWith(tab.url, true); expect(cipherService.updateLastUsedIndexForUrl).not.toHaveBeenCalled(); expect(autofillService.doAutoFill).toHaveBeenCalledWith({ tab: tab, cipher: cipher, pageDetails: pageDetails, skipLastUsed: !fromCommand, skipUsernameOnlyFill: !fromCommand, onlyEmptyFields: !fromCommand, onlyVisibleFields: !fromCommand, fillNewPassword: fromCommand, allowUntrustedIframe: fromCommand, allowTotpAutofill: fromCommand, autoSubmitLogin: false, }); expect(result).toBe(totpCode); }); it("will autofill the next cipher, update the last used cipher index, and return a TOTP value when triggering from a keyboard shortcut", async () => { const totpCode = "123456"; const fromCommand = true; jest.spyOn(autofillService, "doAutoFill").mockResolvedValueOnce(totpCode); jest.spyOn(cipherService, "getNextCipherForUrl").mockResolvedValueOnce(cipher); jest.spyOn(cipherService, "updateLastUsedIndexForUrl"); const result = await autofillService.doAutoFillOnTab(pageDetails, tab, fromCommand); expect(cipherService.getNextCipherForUrl).toHaveBeenCalledWith(tab.url); expect(cipherService.updateLastUsedIndexForUrl).toHaveBeenCalledWith(tab.url); expect(autofillService.doAutoFill).toHaveBeenCalledWith({ tab: tab, cipher: cipher, pageDetails: pageDetails, skipLastUsed: !fromCommand, skipUsernameOnlyFill: !fromCommand, onlyEmptyFields: !fromCommand, onlyVisibleFields: !fromCommand, fillNewPassword: fromCommand, allowUntrustedIframe: fromCommand, allowTotpAutofill: fromCommand, autoSubmitLogin: false, }); expect(result).toBe(totpCode); }); it("will skip autofill, launch the password reprompt window, and return a null value if the cipher re-prompt type is not `None`", async () => { cipher.reprompt = CipherRepromptType.Password; jest.spyOn(autofillService, "doAutoFill"); jest.spyOn(cipherService, "getNextCipherForUrl").mockResolvedValueOnce(cipher); jest .spyOn(userVerificationService, "hasMasterPasswordAndMasterKeyHash") .mockResolvedValueOnce(true); jest .spyOn(autofillService as any, "openVaultItemPasswordRepromptPopout") .mockImplementation(); const result = await autofillService.doAutoFillOnTab(pageDetails, tab, true); expect(cipherService.getNextCipherForUrl).toHaveBeenCalledWith(tab.url); expect(userVerificationService.hasMasterPasswordAndMasterKeyHash).toHaveBeenCalled(); expect(autofillService["openVaultItemPasswordRepromptPopout"]).toHaveBeenCalledWith(tab, { cipherId: cipher.id, action: "autofill", }); expect(autofillService.doAutoFill).not.toHaveBeenCalled(); expect(result).toBeNull(); }); it("skips autofill and does not launch the password reprompt window if the password reprompt is currently debouncing", async () => { cipher.reprompt = CipherRepromptType.Password; jest.spyOn(autofillService, "doAutoFill"); jest.spyOn(cipherService, "getNextCipherForUrl").mockResolvedValueOnce(cipher); jest .spyOn(userVerificationService, "hasMasterPasswordAndMasterKeyHash") .mockResolvedValueOnce(true); jest .spyOn(autofillService as any, "openVaultItemPasswordRepromptPopout") .mockImplementation(); jest .spyOn(autofillService as any, "isDebouncingPasswordRepromptPopout") .mockReturnValueOnce(true); const result = await autofillService.doAutoFillOnTab(pageDetails, tab, true); expect(cipherService.getNextCipherForUrl).toHaveBeenCalledWith(tab.url); expect(autofillService["openVaultItemPasswordRepromptPopout"]).not.toHaveBeenCalled(); expect(autofillService.doAutoFill).not.toHaveBeenCalled(); expect(result).toBeNull(); }); }); }); describe("doAutoFillActiveTab", () => { let pageDetails: PageDetail[]; let tab: chrome.tabs.Tab; beforeEach(() => { tab = createChromeTabMock(); pageDetails = [ { frameId: 1, tab: createChromeTabMock(), details: createAutofillPageDetailsMock({ fields: [ createAutofillFieldMock({ opid: "username-field", form: "validFormId", elementNumber: 1, }), createAutofillFieldMock({ opid: "password-field", type: "password", form: "validFormId", elementNumber: 2, }), ], }), }, ]; }); it("returns a null vault without doing autofill if the page details does not contain fields ", async () => { pageDetails[0].details.fields = []; jest.spyOn(autofillService as any, "getActiveTab"); jest.spyOn(autofillService, "doAutoFill"); const result = await autofillService.doAutoFillActiveTab(pageDetails, false); expect(autofillService["getActiveTab"]).not.toHaveBeenCalled(); expect(autofillService.doAutoFill).not.toHaveBeenCalled(); expect(result).toBeNull(); }); it("returns a null value without doing autofill if the active tab cannot be found", async () => { jest.spyOn(autofillService as any, "getActiveTab").mockResolvedValueOnce(undefined); jest.spyOn(autofillService, "doAutoFill"); const result = await autofillService.doAutoFillActiveTab(pageDetails, false); expect(autofillService["getActiveTab"]).toHaveBeenCalled(); expect(autofillService.doAutoFill).not.toHaveBeenCalled(); expect(result).toBeNull(); }); it("returns a null value without doing autofill if the active tab url cannot be found", async () => { jest.spyOn(autofillService as any, "getActiveTab").mockResolvedValueOnce({ id: 1, url: undefined, }); jest.spyOn(autofillService, "doAutoFill"); const result = await autofillService.doAutoFillActiveTab(pageDetails, false); expect(autofillService["getActiveTab"]).toHaveBeenCalled(); expect(autofillService.doAutoFill).not.toHaveBeenCalled(); expect(result).toBeNull(); }); it("queries the active tab and enacts an autofill on that tab", async () => { const totp = "123456"; const fromCommand = false; jest.spyOn(autofillService as any, "getActiveTab").mockResolvedValueOnce(tab); jest.spyOn(autofillService, "doAutoFillOnTab").mockResolvedValueOnce(totp); const result = await autofillService.doAutoFillActiveTab( pageDetails, fromCommand, CipherType.Login, ); expect(autofillService["getActiveTab"]).toHaveBeenCalled(); expect(autofillService.doAutoFillOnTab).toHaveBeenCalledWith(pageDetails, tab, fromCommand); expect(result).toBe(totp); }); it("autofills card cipher types", async () => { const cardFormPageDetails = [ { frameId: 1, tab: createChromeTabMock(), details: createAutofillPageDetailsMock({ fields: [ createAutofillFieldMock({ opid: "number-field", form: "validFormId", elementNumber: 1, }), createAutofillFieldMock({ opid: "ccv-field", form: "validFormId", elementNumber: 2, }), ], }), }, ]; const cardCipher = mock<CipherView>({ type: CipherType.Card, reprompt: CipherRepromptType.None, }); jest.spyOn(autofillService as any, "getActiveTab").mockResolvedValueOnce(tab); jest.spyOn(autofillService, "doAutoFill").mockImplementation(); jest .spyOn(autofillService["cipherService"], "getNextCardCipher") .mockResolvedValueOnce(cardCipher); await autofillService.doAutoFillActiveTab(cardFormPageDetails, true, CipherType.Card); expect(autofillService.doAutoFill).toHaveBeenCalledWith({ tab: tab, cipher: cardCipher, pageDetails: cardFormPageDetails, skipLastUsed: false, skipUsernameOnlyFill: false, onlyEmptyFields: false, onlyVisibleFields: false, fillNewPassword: false, allowUntrustedIframe: true, allowTotpAutofill: false, }); }); it("autofills identity cipher types", async () => { const identityFormPageDetails = [ { frameId: 1, tab: createChromeTabMock(), details: createAutofillPageDetailsMock({ fields: [ createAutofillFieldMock({ opid: "name-field", form: "validFormId", elementNumber: 1, }), createAutofillFieldMock({ opid: "address-field", form: "validFormId", elementNumber: 2, }), ], }), }, ]; const identityCipher = mock<CipherView>({ type: CipherType.Identity, reprompt: CipherRepromptType.None, }); jest.spyOn(autofillService as any, "getActiveTab").mockResolvedValueOnce(tab); jest.spyOn(autofillService, "doAutoFill").mockImplementation(); jest .spyOn(autofillService["cipherService"], "getNextIdentityCipher") .mockResolvedValueOnce(identityCipher); await autofillService.doAutoFillActiveTab(identityFormPageDetails, true, CipherType.Identity); expect(autofillService.doAutoFill).toHaveBeenCalledWith({ tab: tab, cipher: identityCipher, pageDetails: identityFormPageDetails, skipLastUsed: false, skipUsernameOnlyFill: false, onlyEmptyFields: false, onlyVisibleFields: false, fillNewPassword: false, allowUntrustedIframe: true, allowTotpAutofill: false, }); }); }); describe("getActiveTab", () => { it("throws are error if a tab cannot be found", async () => { jest.spyOn(BrowserApi, "getTabFromCurrentWindow").mockResolvedValueOnce(undefined); try { await autofillService["getActiveTab"](); triggerTestFailure(); } catch (error) { expect(BrowserApi.getTabFromCurrentWindow).toHaveBeenCalled(); expect(error.message).toBe("No tab found."); } }); it("returns the active tab from the current window", async () => { const tab = createChromeTabMock(); jest.spyOn(BrowserApi, "getTabFromCurrentWindow").mockResolvedValueOnce(tab); const result = await autofillService["getActiveTab"](); expect(BrowserApi.getTabFromCurrentWindow).toHaveBeenCalled(); expect(result).toBe(tab); }); }); describe("generateFillScript", () => { let defaultUsernameField: AutofillField; let defaultUsernameFieldView: FieldView; let defaultPasswordField: AutofillField; let defaultPasswordFieldView: FieldView; let pageDetail: AutofillPageDetails; let generateFillScriptOptions: GenerateFillScriptOptions; beforeEach(() => { defaultUsernameField = createAutofillFieldMock({ opid: "username-field", form: "validFormId", htmlID: "username", elementNumber: 1, }); defaultUsernameFieldView = mock<FieldView>({ name: "username", value: defaultUsernameField.value, }); defaultPasswordField = createAutofillFieldMock({ opid: "password-field", type: "password", form: "validFormId", htmlID: "password", elementNumber: 2, }); defaultPasswordFieldView = mock<FieldView>({ name: "password", value: defaultPasswordField.value, }); pageDetail = createAutofillPageDetailsMock({ fields: [defaultUsernameField, defaultPasswordField], }); generateFillScriptOptions = createGenerateFillScriptOptionsMock(); generateFillScriptOptions.cipher.fields = [ defaultUsernameFieldView, defaultPasswordFieldView, ]; }); it("returns null if the page details are not provided", async () => { const value = await autofillService["generateFillScript"]( undefined, generateFillScriptOptions, ); expect(value).toBeNull(); }); it("returns null if the passed options do not contain a valid cipher", async () => { generateFillScriptOptions.cipher = undefined; const value = await autofillService["generateFillScript"]( pageDetail, generateFillScriptOptions, ); expect(value).toBeNull(); }); describe("given a valid set of cipher fields and page detail fields", () => { it("will not attempt to fill by opid duplicate fields found within the page details", async () => { const duplicateUsernameField: AutofillField = createAutofillFieldMock({ opid: "username-field", form: "validFormId", htmlID: "username", elementNumber: 3, }); pageDetail.fields.push(duplicateUsernameField); jest.spyOn(generateFillScriptOptions.cipher, "linkedFieldValue"); jest.spyOn(autofillService as any, "findMatchingFieldIndex"); jest.spyOn(AutofillService, "fillByOpid"); await autofillService["generateFillScript"](pageDetail, generateFillScriptOptions); expect(AutofillService.fillByOpid).not.toHaveBeenCalledWith( expect.anything(), duplicateUsernameField, duplicateUsernameField.value, ); }); it("will not attempt to fill by opid fields that are not viewable and are not a `span` element", async () => { defaultUsernameField.viewable = false; jest.spyOn(AutofillService, "fillByOpid"); await autofillService["generateFillScript"](pageDetail, generateFillScriptOptions); expect(AutofillService.fillByOpid).not.toHaveBeenCalledWith( expect.anything(), defaultUsernameField, defaultUsernameField.value, ); }); it("will fill by opid fields that are not viewable but are a `span` element", async () => { defaultUsernameField.viewable = false; defaultUsernameField.tagName = "span"; jest.spyOn(AutofillService, "fillByOpid"); await autofillService["generateFillScript"](pageDetail, generateFillScriptOptions); expect(AutofillService.fillByOpid).toHaveBeenNthCalledWith( 1, expect.anything(), defaultUsernameField, defaultUsernameField.value, ); }); it("will not attempt to fill by opid fields that do not contain a property that matches the field name", async () => { defaultUsernameField.htmlID = "does-not-match-username"; jest.spyOn(AutofillService, "fillByOpid"); await autofillService["generateFillScript"](pageDetail, generateFillScriptOptions); expect(AutofillService.fillByOpid).not.toHaveBeenCalledWith( expect.anything(), defaultUsernameField, defaultUsernameField.value, ); }); it("will fill by opid fields that contain a property that matches the field name", async () => { jest.spyOn(generateFillScriptOptions.cipher, "linkedFieldValue"); jest.spyOn(autofillService as any, "findMatchingFieldIndex"); jest.spyOn(AutofillService, "fillByOpid"); await autofillService["generateFillScript"](pageDetail, generateFillScriptOptions); expect(autofillService["findMatchingFieldIndex"]).toHaveBeenCalledTimes(2); expect(generateFillScriptOptions.cipher.linkedFieldValue).not.toHaveBeenCalled(); expect(AutofillService.fillByOpid).toHaveBeenNthCalledWith( 1, expect.anything(), defaultUsernameField, defaultUsernameField.value, ); expect(AutofillService.fillByOpid).toHaveBeenNthCalledWith( 2, expect.anything(), defaultPasswordField, defaultPasswordField.value, ); }); it("it will fill by opid fields of type Linked", async () => { const fieldLinkedId: LinkedIdType = LoginLinkedId.Username; const linkedFieldValue = "linkedFieldValue"; defaultUsernameFieldView.type = FieldType.Linked; defaultUsernameFieldView.linkedId = fieldLinkedId; jest .spyOn(generateFillScriptOptions.cipher, "linkedFieldValue") .mockReturnValueOnce(linkedFieldValue); jest.spyOn(AutofillService, "fillByOpid"); await autofillService["generateFillScript"](pageDetail, generateFillScriptOptions); expect(generateFillScriptOptions.cipher.linkedFieldValue).toHaveBeenCalledTimes(1); expect(generateFillScriptOptions.cipher.linkedFieldValue).toHaveBeenCalledWith( fieldLinkedId, ); expect(AutofillService.fillByOpid).toHaveBeenNthCalledWith( 1, expect.anything(), defaultUsernameField, linkedFieldValue, ); expect(AutofillService.fillByOpid).toHaveBeenNthCalledWith( 2, expect.anything(), defaultPasswordField, defaultPasswordField.value, ); }); it("will fill by opid fields of type Boolean", async () => { defaultUsernameFieldView.type = FieldType.Boolean; defaultUsernameFieldView.value = "true"; jest.spyOn(generateFillScriptOptions.cipher, "linkedFieldValue"); jest.spyOn(AutofillService, "fillByOpid"); await autofillService["generateFillScript"](pageDetail, generateFillScriptOptions); expect(generateFillScriptOptions.cipher.linkedFieldValue).not.toHaveBeenCalled(); expect(AutofillService.fillByOpid).toHaveBeenNthCalledWith( 1, expect.anything(), defaultUsernameField, defaultUsernameFieldView.value, ); }); it("will fill by opid fields of type Boolean with a value of false if no value is provided", async () => { defaultUsernameFieldView.type = FieldType.Boolean; defaultUsernameFieldView.value = undefined; jest.spyOn(AutofillService, "fillByOpid"); await autofillService["generateFillScript"](pageDetail, generateFillScriptOptions); expect(AutofillService.fillByOpid).toHaveBeenNthCalledWith( 1, expect.anything(), defaultUsernameField, "false", ); }); }); it("returns a fill script generated for a login autofill", async () => { const fillScriptMock = createAutofillScriptMock( {}, { "username-field": "username-value", "password-value": "password-value" }, ); generateFillScriptOptions.cipher.type = CipherType.Login; jest .spyOn(autofillService as any, "generateLoginFillScript") .mockReturnValueOnce(fillScriptMock); const value = await autofillService["generateFillScript"]( pageDetail, generateFillScriptOptions, ); expect(autofillService["generateLoginFillScript"]).toHaveBeenCalledWith( { metadata: {}, properties: {}, script: [ ["click_on_opid", "username-field"], ["focus_by_opid", "username-field"], ["fill_by_opid", "username-field", "default-value"], ["click_on_opid", "password-field"], ["focus_by_opid", "password-field"], ["fill_by_opid", "password-field", "default-value"], ], }, pageDetail, { "password-field": defaultPasswordField, "username-field": defaultUsernameField, }, generateFillScriptOptions, ); expect(value).toBe(fillScriptMock); }); it("returns a fill script generated for a card autofill", async () => { const fillScriptMock = createAutofillScriptMock( {}, { "first-name-field": "first-name-value", "last-name-value": "last-name-value" }, ); generateFillScriptOptions.cipher.type = CipherType.Card; jest .spyOn(autofillService as any, "generateCardFillScript") .mockReturnValueOnce(fillScriptMock); const value = await autofillService["generateFillScript"]( pageDetail, generateFillScriptOptions, ); expect(autofillService["generateCardFillScript"]).toHaveBeenCalledWith( { metadata: {}, properties: {}, script: [ ["click_on_opid", "username-field"], ["focus_by_opid", "username-field"], ["fill_by_opid", "username-field", "default-value"], ["click_on_opid", "password-field"], ["focus_by_opid", "password-field"], ["fill_by_opid", "password-field", "default-value"], ], }, pageDetail, { "password-field": defaultPasswordField, "username-field": defaultUsernameField, }, generateFillScriptOptions, ); expect(value).toBe(fillScriptMock); }); it("returns a fill script generated for an identity autofill", async () => { const fillScriptMock = createAutofillScriptMock( {}, { "first-name-field": "first-name-value", "last-name-value": "last-name-value" }, ); generateFillScriptOptions.cipher.type = CipherType.Identity; jest .spyOn(autofillService as any, "generateIdentityFillScript") .mockReturnValueOnce(fillScriptMock); const value = await autofillService["generateFillScript"]( pageDetail, generateFillScriptOptions, ); expect(autofillService["generateIdentityFillScript"]).toHaveBeenCalledWith( { metadata: {}, properties: {}, script: [ ["click_on_opid", "username-field"], ["focus_by_opid", "username-field"], ["fill_by_opid", "username-field", "default-value"], ["click_on_opid", "password-field"], ["focus_by_opid", "password-field"], ["fill_by_opid", "password-field", "default-value"], ], }, pageDetail, { "password-field": defaultPasswordField, "username-field": defaultUsernameField, }, generateFillScriptOptions, ); expect(value).toBe(fillScriptMock); }); it("returns null if the cipher type is not for a login, card, or identity", async () => { generateFillScriptOptions.cipher.type = CipherType.SecureNote; const value = await autofillService["generateFillScript"]( pageDetail, generateFillScriptOptions, ); expect(value).toBeNull(); }); }); describe("generateLoginFillScript", () => { let fillScript: AutofillScript; let pageDetails: AutofillPageDetails; let filledFields: { [id: string]: AutofillField }; let options: GenerateFillScriptOptions; let defaultLoginUriView: LoginUriView; beforeEach(() => { fillScript = createAutofillScriptMock(); pageDetails = createAutofillPageDetailsMock(); filledFields = { "username-field": createAutofillFieldMock({ opid: "username-field", form: "validFormId", elementNumber: 1, }), "password-field": createAutofillFieldMock({ opid: "password-field", form: "validFormId", elementNumber: 2, }), "totp-field": createAutofillFieldMock({ opid: "totp-field", form: "validFormId", elementNumber: 3, }), }; defaultLoginUriView = mock<LoginUriView>({ uri: "path_to_url", match: UriMatchStrategy.Domain, }); options = createGenerateFillScriptOptionsMock(); options.cipher.login = mock<LoginView>({ uris: [defaultLoginUriView], }); options.cipher.login.matchesUri = jest.fn().mockReturnValue(true); }); it("returns null if the cipher does not have login data", async () => { options.cipher.login = undefined; jest.spyOn(autofillService as any, "inUntrustedIframe"); jest.spyOn(AutofillService, "loadPasswordFields"); jest.spyOn(autofillService as any, "findUsernameField"); jest.spyOn(AutofillService, "fieldIsFuzzyMatch"); jest.spyOn(AutofillService, "fillByOpid"); jest.spyOn(AutofillService, "setFillScriptForFocus"); const value = await autofillService["generateLoginFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(autofillService["inUntrustedIframe"]).not.toHaveBeenCalled(); expect(AutofillService.loadPasswordFields).not.toHaveBeenCalled(); expect(autofillService["findUsernameField"]).not.toHaveBeenCalled(); expect(AutofillService.fieldIsFuzzyMatch).not.toHaveBeenCalled(); expect(AutofillService.fillByOpid).not.toHaveBeenCalled(); expect(AutofillService.setFillScriptForFocus).not.toHaveBeenCalled(); expect(value).toBeNull(); }); describe("given a list of login uri views", () => { it("returns an empty array of saved login uri views if the login cipher has no login uri views", async () => { options.cipher.login.uris = []; const value = await autofillService["generateLoginFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(value.savedUrls).toStrictEqual([]); }); it("returns a list of saved login uri views within the fill script", async () => { const secondUriView = mock<LoginUriView>({ uri: "path_to_url", }); const thirdUriView = mock<LoginUriView>({ uri: "path_to_url", }); options.cipher.login.uris = [defaultLoginUriView, secondUriView, thirdUriView]; const value = await autofillService["generateLoginFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(value.savedUrls).toStrictEqual([ defaultLoginUriView.uri, secondUriView.uri, thirdUriView.uri, ]); }); it("skips adding any login uri views that have a UriMatchStrategySetting of Never to the list of saved urls", async () => { const secondUriView = mock<LoginUriView>({ uri: "path_to_url", }); const thirdUriView = mock<LoginUriView>({ uri: "path_to_url", match: UriMatchStrategy.Never, }); options.cipher.login.uris = [defaultLoginUriView, secondUriView, thirdUriView]; const value = await autofillService["generateLoginFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(value.savedUrls).toStrictEqual([defaultLoginUriView.uri, secondUriView.uri]); expect(value.savedUrls).not.toContain(thirdUriView.uri); }); }); describe("given a valid set of page details and autofill options", () => { let usernameField: AutofillField; let usernameFieldView: FieldView; let passwordField: AutofillField; let passwordFieldView: FieldView; let totpField: AutofillField; let totpFieldView: FieldView; beforeEach(() => { usernameField = createAutofillFieldMock({ opid: "username", form: "validFormId", elementNumber: 1, }); usernameFieldView = mock<FieldView>({ name: "username", }); passwordField = createAutofillFieldMock({ opid: "password", type: "password", form: "validFormId", elementNumber: 2, }); passwordFieldView = mock<FieldView>({ name: "password", }); totpField = createAutofillFieldMock({ opid: "totp", type: "text", form: "validFormId", htmlName: "totpcode", elementNumber: 3, }); totpFieldView = mock<FieldView>({ name: "totp", }); pageDetails.fields = [usernameField, passwordField, totpField]; options.cipher.fields = [usernameFieldView, passwordFieldView, totpFieldView]; options.cipher.login.matchesUri = jest.fn().mockReturnValue(true); options.cipher.login.username = "username"; options.cipher.login.password = "password"; options.cipher.login.totp = "totp"; }); it("attempts to load the password fields from hidden and read only elements if no visible password fields are found within the page details", async () => { pageDetails.fields = [ createAutofillFieldMock({ opid: "password-field", type: "password", viewable: true, readonly: true, }), ]; jest.spyOn(AutofillService, "loadPasswordFields"); await autofillService["generateLoginFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(AutofillService.loadPasswordFields).toHaveBeenCalledTimes(2); expect(AutofillService.loadPasswordFields).toHaveBeenNthCalledWith( 1, pageDetails, false, false, options.onlyEmptyFields, options.fillNewPassword, ); expect(AutofillService.loadPasswordFields).toHaveBeenNthCalledWith( 2, pageDetails, true, true, options.onlyEmptyFields, options.fillNewPassword, ); }); describe("given a valid list of forms within the passed page details", () => { beforeEach(() => { usernameField.viewable = false; usernameField.readonly = true; totpField.viewable = false; totpField.readonly = true; jest.spyOn(autofillService as any, "findUsernameField"); jest.spyOn(autofillService as any, "findTotpField"); }); it("will attempt to find a username field from hidden fields if no visible username fields are found", async () => { await autofillService["generateLoginFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(autofillService["findUsernameField"]).toHaveBeenCalledTimes(2); expect(autofillService["findUsernameField"]).toHaveBeenNthCalledWith( 1, pageDetails, passwordField, false, false, false, ); expect(autofillService["findUsernameField"]).toHaveBeenNthCalledWith( 2, pageDetails, passwordField, true, true, false, ); }); it("will not attempt to find a username field from hidden fields if the passed options indicate only visible fields should be referenced", async () => { options.onlyVisibleFields = true; await autofillService["generateLoginFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(autofillService["findUsernameField"]).toHaveBeenCalledTimes(1); expect(autofillService["findUsernameField"]).toHaveBeenNthCalledWith( 1, pageDetails, passwordField, false, false, false, ); expect(autofillService["findUsernameField"]).not.toHaveBeenNthCalledWith( 2, pageDetails, passwordField, true, true, false, ); }); it("will attempt to find a totp field from hidden fields if no visible totp fields are found", async () => { options.allowTotpAutofill = true; await autofillService["generateLoginFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(autofillService["findTotpField"]).toHaveBeenCalledTimes(2); expect(autofillService["findTotpField"]).toHaveBeenNthCalledWith( 1, pageDetails, passwordField, false, false, false, ); expect(autofillService["findTotpField"]).toHaveBeenNthCalledWith( 2, pageDetails, passwordField, true, true, false, ); }); it("will not attempt to find a totp field from hidden fields if the passed options indicate only visible fields should be referenced", async () => { options.allowTotpAutofill = true; options.onlyVisibleFields = true; await autofillService["generateLoginFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(autofillService["findTotpField"]).toHaveBeenCalledTimes(1); expect(autofillService["findTotpField"]).toHaveBeenNthCalledWith( 1, pageDetails, passwordField, false, false, false, ); expect(autofillService["findTotpField"]).not.toHaveBeenNthCalledWith( 2, pageDetails, passwordField, true, true, false, ); }); it("will not attempt to find a totp field from hidden fields if the passed options do not allow for TOTP values to be filled", async () => { options.allowTotpAutofill = false; await autofillService["generateLoginFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(autofillService["findTotpField"]).not.toHaveBeenCalled(); }); }); describe("given a list of fields without forms within the passed page details", () => { beforeEach(() => { pageDetails.forms = undefined; jest.spyOn(autofillService as any, "findUsernameField"); jest.spyOn(autofillService as any, "findTotpField"); }); it("will attempt to match a password field that does not contain a form to a username field", async () => { await autofillService["generateLoginFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(autofillService["findUsernameField"]).toHaveBeenCalledTimes(1); expect(autofillService["findUsernameField"]).toHaveBeenCalledWith( pageDetails, passwordField, false, false, true, ); }); it("will attempt to match a password field that does not contain a form to a username field that is not visible", async () => { usernameField.viewable = false; usernameField.readonly = true; await autofillService["generateLoginFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(autofillService["findUsernameField"]).toHaveBeenCalledTimes(2); expect(autofillService["findUsernameField"]).toHaveBeenNthCalledWith( 1, pageDetails, passwordField, false, false, true, ); expect(autofillService["findUsernameField"]).toHaveBeenNthCalledWith( 2, pageDetails, passwordField, true, true, true, ); }); it("will not attempt to match a password field that does not contain a form to a username field that is not visible if the passed options indicate only visible fields", async () => { usernameField.viewable = false; usernameField.readonly = true; options.onlyVisibleFields = true; await autofillService["generateLoginFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(autofillService["findUsernameField"]).toHaveBeenCalledTimes(1); expect(autofillService["findUsernameField"]).toHaveBeenNthCalledWith( 1, pageDetails, passwordField, false, false, true, ); expect(autofillService["findUsernameField"]).not.toHaveBeenNthCalledWith( 2, pageDetails, passwordField, true, true, true, ); }); it("will attempt to match a password field that does not contain a form to a TOTP field", async () => { options.allowTotpAutofill = true; await autofillService["generateLoginFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(autofillService["findTotpField"]).toHaveBeenCalledTimes(1); expect(autofillService["findTotpField"]).toHaveBeenCalledWith( pageDetails, passwordField, false, false, true, ); }); it("will attempt to match a password field that does not contain a form to a TOTP field that is not visible", async () => { options.onlyVisibleFields = false; options.allowTotpAutofill = true; totpField.viewable = false; totpField.readonly = true; await autofillService["generateLoginFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(autofillService["findTotpField"]).toHaveBeenCalledTimes(2); expect(autofillService["findTotpField"]).toHaveBeenNthCalledWith( 1, pageDetails, passwordField, false, false, true, ); expect(autofillService["findTotpField"]).toHaveBeenNthCalledWith( 2, pageDetails, passwordField, true, true, true, ); }); }); describe("given a set of page details that does not contain a password field", () => { let emailField: AutofillField; let emailFieldView: FieldView; let telephoneField: AutofillField; let telephoneFieldView: FieldView; let totpField: AutofillField; let totpFieldView: FieldView; let nonViewableField: AutofillField; let nonViewableFieldView: FieldView; beforeEach(() => { usernameField.htmlName = "username"; emailField = createAutofillFieldMock({ opid: "email", type: "email", form: "validFormId", elementNumber: 2, }); emailFieldView = mock<FieldView>({ name: "email", }); telephoneField = createAutofillFieldMock({ opid: "telephone", type: "tel", form: "validFormId", elementNumber: 3, }); telephoneFieldView = mock<FieldView>({ name: "telephone", }); totpField = createAutofillFieldMock({ opid: "totp", type: "text", form: "validFormId", htmlName: "totpcode", elementNumber: 4, }); totpFieldView = mock<FieldView>({ name: "totp", }); nonViewableField = createAutofillFieldMock({ opid: "non-viewable", form: "validFormId", viewable: false, elementNumber: 4, }); nonViewableFieldView = mock<FieldView>({ name: "non-viewable", }); pageDetails.fields = [ usernameField, emailField, telephoneField, totpField, nonViewableField, ]; options.cipher.fields = [ usernameFieldView, emailFieldView, telephoneFieldView, totpFieldView, nonViewableFieldView, ]; jest.spyOn(AutofillService, "fieldIsFuzzyMatch"); jest.spyOn(AutofillService, "fillByOpid"); }); it("will attempt to fuzzy match a username to a viewable text, email or tel field if no password fields are found and the username fill is not being skipped", async () => { await autofillService["generateLoginFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(AutofillService.fieldIsFuzzyMatch).toHaveBeenCalledTimes(4); expect(AutofillService.fieldIsFuzzyMatch).toHaveBeenNthCalledWith( 1, usernameField, AutoFillConstants.UsernameFieldNames, ); expect(AutofillService.fieldIsFuzzyMatch).toHaveBeenNthCalledWith( 2, emailField, AutoFillConstants.UsernameFieldNames, ); expect(AutofillService.fieldIsFuzzyMatch).toHaveBeenNthCalledWith( 3, telephoneField, AutoFillConstants.UsernameFieldNames, ); expect(AutofillService.fieldIsFuzzyMatch).toHaveBeenNthCalledWith( 4, totpField, AutoFillConstants.UsernameFieldNames, ); expect(AutofillService.fieldIsFuzzyMatch).not.toHaveBeenNthCalledWith( 5, nonViewableField, AutoFillConstants.UsernameFieldNames, ); expect(AutofillService.fillByOpid).toHaveBeenCalledTimes(1); expect(AutofillService.fillByOpid).toHaveBeenCalledWith( fillScript, usernameField, options.cipher.login.username, ); }); it("will not attempt to fuzzy match a username if the username fill is being skipped", async () => { options.skipUsernameOnlyFill = true; await autofillService["generateLoginFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(AutofillService.fieldIsFuzzyMatch).not.toHaveBeenCalledWith( expect.anything(), AutoFillConstants.UsernameFieldNames, ); }); it("will attempt to fuzzy match a totp field if totp autofill is allowed", async () => { options.allowTotpAutofill = true; await autofillService["generateLoginFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(AutofillService.fieldIsFuzzyMatch).toHaveBeenCalledWith( expect.anything(), AutoFillConstants.TotpFieldNames, ); }); it("will not attempt to fuzzy match a totp field if totp autofill is not allowed", async () => { options.allowTotpAutofill = false; await autofillService["generateLoginFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(AutofillService.fieldIsFuzzyMatch).not.toHaveBeenCalledWith( expect.anything(), AutoFillConstants.TotpFieldNames, ); }); }); it("returns a value indicating if the page url is in an untrusted iframe", async () => { jest.spyOn(autofillService as any, "inUntrustedIframe").mockReturnValueOnce(true); const value = await autofillService["generateLoginFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(value.untrustedIframe).toBe(true); }); it("returns a fill script used to autofill a login item", async () => { jest.spyOn(autofillService as any, "inUntrustedIframe"); jest.spyOn(AutofillService, "loadPasswordFields"); jest.spyOn(autofillService as any, "findUsernameField"); jest.spyOn(AutofillService, "fieldIsFuzzyMatch"); jest.spyOn(AutofillService, "fillByOpid"); jest.spyOn(AutofillService, "setFillScriptForFocus"); const value = await autofillService["generateLoginFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(autofillService["inUntrustedIframe"]).toHaveBeenCalledWith(pageDetails.url, options); expect(AutofillService.loadPasswordFields).toHaveBeenCalledWith( pageDetails, false, false, options.onlyEmptyFields, options.fillNewPassword, ); expect(autofillService["findUsernameField"]).toHaveBeenCalledWith( pageDetails, passwordField, false, false, false, ); expect(AutofillService.fieldIsFuzzyMatch).not.toHaveBeenCalled(); expect(AutofillService.fillByOpid).toHaveBeenCalledTimes(2); expect(AutofillService.fillByOpid).toHaveBeenNthCalledWith( 1, fillScript, usernameField, options.cipher.login.username, ); expect(AutofillService.fillByOpid).toHaveBeenNthCalledWith( 2, fillScript, passwordField, options.cipher.login.password, ); expect(AutofillService.setFillScriptForFocus).toHaveBeenCalledWith( filledFields, fillScript, ); expect(value).toStrictEqual({ autosubmit: null, metadata: {}, properties: { delay_between_operations: 20 }, savedUrls: ["path_to_url"], script: [ ["click_on_opid", "default-field"], ["focus_by_opid", "default-field"], ["fill_by_opid", "default-field", "default"], ["click_on_opid", "username"], ["focus_by_opid", "username"], ["fill_by_opid", "username", "username"], ["click_on_opid", "password"], ["focus_by_opid", "password"], ["fill_by_opid", "password", "password"], ["focus_by_opid", "password"], ], itemType: "", untrustedIframe: false, }); }); }); }); describe("generateCardFillScript", () => { let fillScript: AutofillScript; let pageDetails: AutofillPageDetails; let filledFields: { [id: string]: AutofillField }; let options: GenerateFillScriptOptions; beforeEach(() => { fillScript = createAutofillScriptMock({ script: [], }); pageDetails = createAutofillPageDetailsMock(); filledFields = { "cardholderName-field": createAutofillFieldMock({ opid: "cardholderName-field", form: "validFormId", elementNumber: 1, htmlName: "cc-name", }), "cardNumber-field": createAutofillFieldMock({ opid: "cardNumber-field", form: "validFormId", elementNumber: 2, htmlName: "cc-number", }), "expMonth-field": createAutofillFieldMock({ opid: "expMonth-field", form: "validFormId", elementNumber: 3, htmlName: "exp-month", }), "expYear-field": createAutofillFieldMock({ opid: "expYear-field", form: "validFormId", elementNumber: 4, htmlName: "exp-year", }), "code-field": createAutofillFieldMock({ opid: "code-field", form: "validFormId", elementNumber: 1, htmlName: "cvc", }), }; options = createGenerateFillScriptOptionsMock(); options.cipher.card = mock<CardView>(); }); it("returns null if the passed options contains a cipher with no card view", () => { options.cipher.card = undefined; const value = autofillService["generateCardFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(value).toBeNull(); }); describe("given an invalid autofill field", () => { const unmodifiedFillScriptValues: AutofillScript = { autosubmit: null, metadata: {}, properties: { delay_between_operations: 20 }, savedUrls: [], script: [], itemType: "", untrustedIframe: false, }; it("returns an unmodified fill script when the field is a `span` field", () => { const spanField = createAutofillFieldMock({ opid: "span-field", form: "validFormId", elementNumber: 5, htmlName: "spanField", tagName: "span", }); pageDetails.fields = [spanField]; jest.spyOn(AutofillService, "isExcludedFieldType"); const value = autofillService["generateCardFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(AutofillService["isExcludedFieldType"]).toHaveBeenCalled(); expect(value).toStrictEqual(unmodifiedFillScriptValues); }); AutoFillConstants.ExcludedAutofillTypes.forEach((excludedType) => { it(`returns an unmodified fill script when the field has a '${excludedType}' type`, () => { const invalidField = createAutofillFieldMock({ opid: `${excludedType}-field`, form: "validFormId", elementNumber: 5, htmlName: "invalidField", type: excludedType, }); pageDetails.fields = [invalidField]; jest.spyOn(AutofillService, "isExcludedFieldType"); const value = autofillService["generateCardFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(AutofillService["isExcludedFieldType"]).toHaveBeenCalledWith( invalidField, AutoFillConstants.ExcludedAutofillTypes, ); expect(value).toStrictEqual(unmodifiedFillScriptValues); }); }); it("returns an unmodified fill script when the field is not viewable", () => { const notViewableField = createAutofillFieldMock({ opid: "invalid-field", form: "validFormId", elementNumber: 5, htmlName: "invalidField", type: "text", viewable: false, }); pageDetails.fields = [notViewableField]; jest.spyOn(AutofillService, "forCustomFieldsOnly"); jest.spyOn(AutofillService, "isExcludedFieldType"); const value = autofillService["generateCardFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(AutofillService.forCustomFieldsOnly).toHaveBeenCalledWith(notViewableField); expect(AutofillService["isExcludedFieldType"]).toHaveBeenCalled(); expect(value).toStrictEqual(unmodifiedFillScriptValues); }); }); describe("given a valid set of autofill fields", () => { let cardholderNameField: AutofillField; let cardholderNameFieldView: FieldView; let cardNumberField: AutofillField; let cardNumberFieldView: FieldView; let expMonthField: AutofillField; let expMonthFieldView: FieldView; let expYearField: AutofillField; let expYearFieldView: FieldView; let codeField: AutofillField; let codeFieldView: FieldView; let brandField: AutofillField; let brandFieldView: FieldView; beforeEach(() => { cardholderNameField = createAutofillFieldMock({ opid: "cardholderName", form: "validFormId", elementNumber: 1, htmlName: "cc-name", }); cardholderNameFieldView = mock<FieldView>({ name: "cardholderName" }); cardNumberField = createAutofillFieldMock({ opid: "cardNumber", form: "validFormId", elementNumber: 2, htmlName: "cc-number", }); cardNumberFieldView = mock<FieldView>({ name: "cardNumber" }); expMonthField = createAutofillFieldMock({ opid: "expMonth", form: "validFormId", elementNumber: 3, htmlName: "exp-month", }); expMonthFieldView = mock<FieldView>({ name: "expMonth" }); expYearField = createAutofillFieldMock({ opid: "expYear", form: "validFormId", elementNumber: 4, htmlName: "exp-year", }); expYearFieldView = mock<FieldView>({ name: "expYear" }); codeField = createAutofillFieldMock({ opid: "code", form: "validFormId", elementNumber: 1, htmlName: "cvc", }); brandField = createAutofillFieldMock({ opid: "brand", form: "validFormId", elementNumber: 1, htmlName: "card-brand", }); brandFieldView = mock<FieldView>({ name: "brand" }); codeFieldView = mock<FieldView>({ name: "code" }); pageDetails.fields = [ cardholderNameField, cardNumberField, expMonthField, expYearField, codeField, brandField, ]; options.cipher.fields = [ cardholderNameFieldView, cardNumberFieldView, expMonthFieldView, expYearFieldView, codeFieldView, brandFieldView, ]; options.cipher.card.cardholderName = "testCardholderName"; options.cipher.card.number = "testCardNumber"; options.cipher.card.expMonth = "testExpMonth"; options.cipher.card.expYear = "testExpYear"; options.cipher.card.code = "testCode"; options.cipher.card.brand = "testBrand"; jest.spyOn(AutofillService, "forCustomFieldsOnly"); jest.spyOn(AutofillService, "isExcludedFieldType"); jest.spyOn(AutofillService as any, "isFieldMatch"); jest.spyOn(autofillService as any, "makeScriptAction"); jest.spyOn(AutofillService, "hasValue"); jest.spyOn(autofillService as any, "fieldAttrsContain"); jest.spyOn(AutofillService, "fillByOpid"); jest.spyOn(autofillService as any, "makeScriptActionWithValue"); }); it("returns a fill script containing all of the passed card fields", () => { const value = autofillService["generateCardFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(AutofillService.forCustomFieldsOnly).toHaveBeenCalledTimes(6); expect(AutofillService["isExcludedFieldType"]).toHaveBeenCalledTimes(6); expect(AutofillService["isFieldMatch"]).toHaveBeenCalled(); expect(autofillService["makeScriptAction"]).toHaveBeenCalledTimes(4); expect(AutofillService["hasValue"]).toHaveBeenCalledTimes(6); expect(autofillService["fieldAttrsContain"]).toHaveBeenCalledTimes(3); expect(AutofillService["fillByOpid"]).toHaveBeenCalledTimes(6); expect(autofillService["makeScriptActionWithValue"]).toHaveBeenCalledTimes(4); expect(value).toStrictEqual({ autosubmit: null, itemType: "", metadata: {}, properties: { delay_between_operations: 20, }, savedUrls: [], script: [ ["click_on_opid", "cardholderName"], ["focus_by_opid", "cardholderName"], ["fill_by_opid", "cardholderName", "testCardholderName"], ["click_on_opid", "cardNumber"], ["focus_by_opid", "cardNumber"], ["fill_by_opid", "cardNumber", "testCardNumber"], ["click_on_opid", "code"], ["focus_by_opid", "code"], ["fill_by_opid", "code", "testCode"], ["click_on_opid", "brand"], ["focus_by_opid", "brand"], ["fill_by_opid", "brand", "testBrand"], ["click_on_opid", "expMonth"], ["focus_by_opid", "expMonth"], ["fill_by_opid", "expMonth", "testExpMonth"], ["click_on_opid", "expYear"], ["focus_by_opid", "expYear"], ["fill_by_opid", "expYear", "testExpYear"], ], untrustedIframe: false, }); }); }); describe("given an expiration month field", () => { let expMonthField: AutofillField; let expMonthFieldView: FieldView; beforeEach(() => { expMonthField = createAutofillFieldMock({ opid: "expMonth", form: "validFormId", elementNumber: 3, htmlName: "exp-month", selectInfo: { options: [ ["January", "01"], ["February", "02"], ["March", "03"], ["April", "04"], ["May", "05"], ["June", "06"], ["July", "07"], ["August", "08"], ["September", "09"], ["October", "10"], ["November", "11"], ["December", "12"], ], }, }); expMonthFieldView = mock<FieldView>({ name: "expMonth" }); pageDetails.fields = [expMonthField]; options.cipher.fields = [expMonthFieldView]; options.cipher.card.expMonth = "05"; }); it("returns an expiration month parsed from found select options within the field", () => { const testValue = "sometestvalue"; expMonthField.selectInfo.options[4] = ["May", testValue]; const value = autofillService["generateCardFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(value.script[2]).toStrictEqual(["fill_by_opid", expMonthField.opid, testValue]); }); it("returns an expiration month parsed from found select options within the field when the select field has an empty option at the end of the list of options", () => { const testValue = "sometestvalue"; expMonthField.selectInfo.options[4] = ["May", testValue]; expMonthField.selectInfo.options.push(["", ""]); const value = autofillService["generateCardFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(value.script[2]).toStrictEqual(["fill_by_opid", expMonthField.opid, testValue]); }); it("returns an expiration month parsed from found select options within the field when the select field has an empty option at the start of the list of options", () => { const testValue = "sometestvalue"; expMonthField.selectInfo.options[4] = ["May", testValue]; expMonthField.selectInfo.options.unshift(["", ""]); const value = autofillService["generateCardFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(value.script[2]).toStrictEqual(["fill_by_opid", expMonthField.opid, testValue]); }); it("returns an expiration month with a zero attached if the field requires two characters, and the vault item has only one character", () => { options.cipher.card.expMonth = "5"; expMonthField.selectInfo = null; expMonthField.placeholder = "mm"; expMonthField.maxLength = 2; const value = autofillService["generateCardFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(value.script[2]).toStrictEqual(["fill_by_opid", expMonthField.opid, "05"]); }); }); describe("given an expiration year field", () => { let expYearField: AutofillField; let expYearFieldView: FieldView; beforeEach(() => { expYearField = createAutofillFieldMock({ opid: "expYear", form: "validFormId", elementNumber: 3, htmlName: "exp-year", selectInfo: { options: [ ["2023", "2023"], ["2024", "2024"], ["2025", "2025"], ], }, }); expYearFieldView = mock<FieldView>({ name: "expYear" }); pageDetails.fields = [expYearField]; options.cipher.fields = [expYearFieldView]; options.cipher.card.expYear = "2024"; }); it("returns an expiration year parsed from the select options if an exact match is found for either the select option text or value", () => { const someTestValue = "sometestvalue"; expYearField.selectInfo.options[1] = ["2024", someTestValue]; options.cipher.card.expYear = someTestValue; let value = autofillService["generateCardFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(value.script[2]).toStrictEqual(["fill_by_opid", expYearField.opid, someTestValue]); expYearField.selectInfo.options[1] = [someTestValue, "2024"]; value = autofillService["generateCardFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(value.script[2]).toStrictEqual(["fill_by_opid", expYearField.opid, someTestValue]); }); it("returns an expiration year parsed from the select options if the value of an option contains only two characters and the vault item value contains four characters", () => { const yearValue = "26"; expYearField.selectInfo.options.push(["The year 2026", yearValue]); options.cipher.card.expYear = "2026"; const value = autofillService["generateCardFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(value.script[2]).toStrictEqual(["fill_by_opid", expYearField.opid, yearValue]); }); it("returns an expiration year parsed from the select options if the vault of an option is separated by a colon", () => { const yearValue = "26"; const colonSeparatedYearValue = `2:0${yearValue}`; expYearField.selectInfo.options.push(["The year 2026", colonSeparatedYearValue]); options.cipher.card.expYear = yearValue; const value = autofillService["generateCardFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(value.script[2]).toStrictEqual([ "fill_by_opid", expYearField.opid, colonSeparatedYearValue, ]); }); it("returns an expiration year with `20` prepended to the vault item value if the field to be filled expects a `yyyy` format but the vault item only has two characters", () => { const yearValue = "26"; expYearField.selectInfo = null; expYearField.placeholder = "yyyy"; expYearField.maxLength = 4; options.cipher.card.expYear = yearValue; const value = autofillService["generateCardFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(value.script[2]).toStrictEqual([ "fill_by_opid", expYearField.opid, `20${yearValue}`, ]); }); it("returns an expiration year with only the last two values if the field to be filled expects a `yy` format but the vault item contains four characters", () => { const yearValue = "26"; expYearField.selectInfo = null; expYearField.placeholder = "yy"; expYearField.maxLength = 2; options.cipher.card.expYear = `20${yearValue}`; const value = autofillService["generateCardFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(value.script[2]).toStrictEqual(["fill_by_opid", expYearField.opid, yearValue]); }); }); describe("given a generic expiration date field", () => { let expirationDateField: AutofillField; let expirationDateFieldView: FieldView; beforeEach(() => { expirationDateField = createAutofillFieldMock({ opid: "expirationDate", form: "validFormId", elementNumber: 3, htmlName: "expiration-date", }); filledFields["exp-field"] = expirationDateField; expirationDateFieldView = mock<FieldView>({ name: "exp" }); pageDetails.fields = [expirationDateField]; options.cipher.fields = [expirationDateFieldView]; options.cipher.card.expMonth = "05"; options.cipher.card.expYear = "2024"; }); const expectedDateFormats = [ ["mm/yyyy", "05/2024"], ["mm/yy", "05/24"], ["yyyy/mm", "2024/05"], ["yy/mm", "24/05"], ["mm-yyyy", "05-2024"], ["mm-yy", "05-24"], ["yyyy-mm", "2024-05"], ["yy-mm", "24-05"], ["yyyymm", "202405"], ["yymm", "2405"], ["mmyyyy", "052024"], ["mmyy", "0524"], ]; expectedDateFormats.forEach((dateFormat, index) => { it(`returns an expiration date format matching '${dateFormat[0]}'`, () => { expirationDateField.placeholder = dateFormat[0]; if (index === 0) { options.cipher.card.expYear = "24"; } if (index === 1) { options.cipher.card.expMonth = "5"; } const value = autofillService["generateCardFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(value.script[2]).toStrictEqual(["fill_by_opid", "expirationDate", dateFormat[1]]); }); }); it("returns an expiration date format matching `yyyy-mm` if no valid format can be identified", () => { const value = autofillService["generateCardFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(value.script[2]).toStrictEqual(["fill_by_opid", "expirationDate", "2024-05"]); }); }); }); describe("inUntrustedIframe", () => { it("returns a false value if the passed pageUrl is equal to the options tabUrl", async () => { const pageUrl = "path_to_url"; const tabUrl = "path_to_url"; const generateFillScriptOptions = createGenerateFillScriptOptionsMock({ tabUrl }); generateFillScriptOptions.cipher.login.matchesUri = jest.fn().mockReturnValueOnce(true); const result = await autofillService["inUntrustedIframe"](pageUrl, generateFillScriptOptions); expect(generateFillScriptOptions.cipher.login.matchesUri).not.toHaveBeenCalled(); expect(result).toBe(false); }); it("returns a false value if the passed pageUrl matches the domain of the tabUrl", async () => { const pageUrl = "path_to_url"; const tabUrl = "path_to_url"; const equivalentDomains = new Set([ "ejemplo.es", "example.co.uk", "example.com", "exampleapp.com", ]); const generateFillScriptOptions = createGenerateFillScriptOptionsMock({ tabUrl }); generateFillScriptOptions.cipher.login.matchesUri = jest.fn().mockReturnValueOnce(true); const result = await autofillService["inUntrustedIframe"](pageUrl, generateFillScriptOptions); expect(generateFillScriptOptions.cipher.login.matchesUri).toHaveBeenCalledWith( pageUrl, equivalentDomains, generateFillScriptOptions.defaultUriMatch, ); expect(result).toBe(false); }); it("returns a true value if the passed pageUrl does not match the domain of the tabUrl", async () => { const equivalentDomains = new Set([ "ejemplo.es", "example.co.uk", "example.com", "exampleapp.com", ]); domainSettingsService.equivalentDomains$ = of([["not-example.com"]]); const pageUrl = "path_to_url"; const tabUrl = "path_to_url"; const generateFillScriptOptions = createGenerateFillScriptOptionsMock({ tabUrl }); generateFillScriptOptions.cipher.login.matchesUri = jest.fn().mockReturnValueOnce(false); const result = await autofillService["inUntrustedIframe"](pageUrl, generateFillScriptOptions); expect(generateFillScriptOptions.cipher.login.matchesUri).toHaveBeenCalledWith( pageUrl, equivalentDomains, generateFillScriptOptions.defaultUriMatch, ); expect(result).toBe(true); }); }); describe("fieldAttrsContain", () => { let cardNumberField: AutofillField; beforeEach(() => { cardNumberField = createAutofillFieldMock({ opid: "cardNumber", form: "validFormId", elementNumber: 1, htmlName: "card-number", }); }); it("returns false if a field is not passed", () => { const value = autofillService["fieldAttrsContain"](null, "data-foo"); expect(value).toBe(false); }); it("returns false if the field does not contain the passed attribute", () => { const value = autofillService["fieldAttrsContain"](cardNumberField, "data-foo"); expect(value).toBe(false); }); it("returns true if the field contains the passed attribute", () => { const value = autofillService["fieldAttrsContain"](cardNumberField, "card-number"); expect(value).toBe(true); }); }); describe("generateIdentityFillScript", () => { let fillScript: AutofillScript; let pageDetails: AutofillPageDetails; let filledFields: { [id: string]: AutofillField }; let options: GenerateFillScriptOptions; beforeEach(() => { fillScript = createAutofillScriptMock({ script: [] }); pageDetails = createAutofillPageDetailsMock(); filledFields = {}; options = createGenerateFillScriptOptionsMock(); options.cipher.identity = mock<IdentityView>(); }); it("returns null if an identify is not found within the cipher", async () => { options.cipher.identity = null; jest.spyOn(autofillService as any, "makeScriptAction"); jest.spyOn(autofillService as any, "makeScriptActionWithValue"); const value = await autofillService["generateIdentityFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(value).toBeNull(); expect(autofillService["makeScriptAction"]).not.toHaveBeenCalled(); expect(autofillService["makeScriptActionWithValue"]).not.toHaveBeenCalled(); }); describe("given a set of page details that contains fields", () => { const firstName = "John"; const middleName = "A"; const lastName = "Doe"; beforeEach(() => { pageDetails.fields = []; jest.spyOn(AutofillService, "forCustomFieldsOnly"); jest.spyOn(AutofillService, "isExcludedFieldType"); jest.spyOn(AutofillService as any, "isFieldMatch"); jest.spyOn(autofillService as any, "makeScriptAction"); jest.spyOn(autofillService as any, "makeScriptActionWithValue"); }); let isRefactorFeatureFlagSet = false; for (let index = 0; index < 2; index++) { describe(`when the isRefactorFeatureFlagSet is ${isRefactorFeatureFlagSet}`, () => { beforeEach(() => { configService.getFeatureFlag.mockResolvedValue(isRefactorFeatureFlagSet); }); afterAll(() => { isRefactorFeatureFlagSet = true; }); it("will not attempt to match custom fields", async () => { const customField = createAutofillFieldMock({ tagName: "span" }); pageDetails.fields.push(customField); const value = await autofillService["generateIdentityFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(AutofillService.forCustomFieldsOnly).toHaveBeenCalledWith(customField); expect(AutofillService["isExcludedFieldType"]).toHaveBeenCalled(); expect(AutofillService["isFieldMatch"]).not.toHaveBeenCalled(); expect(value.script).toStrictEqual([]); }); it("will not attempt to match a field that is of an excluded type", async () => { const excludedField = createAutofillFieldMock({ type: "hidden" }); pageDetails.fields.push(excludedField); const value = await autofillService["generateIdentityFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(AutofillService.forCustomFieldsOnly).toHaveBeenCalledWith(excludedField); expect(AutofillService["isExcludedFieldType"]).toHaveBeenCalledWith( excludedField, AutoFillConstants.ExcludedAutofillTypes, ); expect(AutofillService["isFieldMatch"]).not.toHaveBeenCalled(); expect(value.script).toStrictEqual([]); }); it("will not attempt to match a field that is not viewable", async () => { const viewableField = createAutofillFieldMock({ viewable: false }); pageDetails.fields.push(viewableField); const value = await autofillService["generateIdentityFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(AutofillService.forCustomFieldsOnly).toHaveBeenCalledWith(viewableField); expect(AutofillService["isExcludedFieldType"]).toHaveBeenCalled(); expect(AutofillService["isFieldMatch"]).not.toHaveBeenCalled(); expect(value.script).toStrictEqual([]); }); it("will match a full name field to the vault item identity value", async () => { const fullNameField = createAutofillFieldMock({ opid: "fullName", htmlName: "full-name", }); pageDetails.fields = [fullNameField]; options.cipher.identity.firstName = firstName; options.cipher.identity.middleName = middleName; options.cipher.identity.lastName = lastName; const value = await autofillService["generateIdentityFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(autofillService["makeScriptActionWithValue"]).toHaveBeenCalledWith( fillScript, `${firstName} ${middleName} ${lastName}`, fullNameField, filledFields, ); expect(value.script[2]).toStrictEqual([ "fill_by_opid", fullNameField.opid, `${firstName} ${middleName} ${lastName}`, ]); }); it("will match a full name field to the a vault item that only has a last name", async () => { const fullNameField = createAutofillFieldMock({ opid: "fullName", htmlName: "full-name", }); pageDetails.fields = [fullNameField]; options.cipher.identity.firstName = ""; options.cipher.identity.middleName = ""; options.cipher.identity.lastName = lastName; const value = await autofillService["generateIdentityFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(autofillService["makeScriptActionWithValue"]).toHaveBeenCalledWith( fillScript, lastName, fullNameField, filledFields, ); expect(value.script[2]).toStrictEqual(["fill_by_opid", fullNameField.opid, lastName]); }); it("will match first name, middle name, and last name fields to the vault item identity value", async () => { const firstNameField = createAutofillFieldMock({ opid: "firstName", htmlName: "first-name", }); const middleNameField = createAutofillFieldMock({ opid: "middleName", htmlName: "middle-name", }); const lastNameField = createAutofillFieldMock({ opid: "lastName", htmlName: "last-name", }); pageDetails.fields = [firstNameField, middleNameField, lastNameField]; options.cipher.identity.firstName = firstName; options.cipher.identity.middleName = middleName; options.cipher.identity.lastName = lastName; const value = await autofillService["generateIdentityFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(autofillService["makeScriptActionWithValue"]).toHaveBeenCalledWith( fillScript, options.cipher.identity.firstName, firstNameField, filledFields, ); expect(autofillService["makeScriptActionWithValue"]).toHaveBeenCalledWith( fillScript, options.cipher.identity.middleName, middleNameField, filledFields, ); expect(autofillService["makeScriptActionWithValue"]).toHaveBeenCalledWith( fillScript, options.cipher.identity.lastName, lastNameField, filledFields, ); expect(value.script[2]).toStrictEqual(["fill_by_opid", firstNameField.opid, firstName]); expect(value.script[5]).toStrictEqual([ "fill_by_opid", middleNameField.opid, middleName, ]); expect(value.script[8]).toStrictEqual(["fill_by_opid", lastNameField.opid, lastName]); }); it("will match title and email fields to the vault item identity value", async () => { const titleField = createAutofillFieldMock({ opid: "title", htmlName: "title" }); const emailField = createAutofillFieldMock({ opid: "email", htmlName: "email" }); pageDetails.fields = [titleField, emailField]; const title = "Mr."; const email = "email@example.com"; options.cipher.identity.title = title; options.cipher.identity.email = email; const value = await autofillService["generateIdentityFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(autofillService["makeScriptActionWithValue"]).toHaveBeenCalledWith( fillScript, options.cipher.identity.title, titleField, filledFields, ); expect(autofillService["makeScriptActionWithValue"]).toHaveBeenCalledWith( fillScript, options.cipher.identity.email, emailField, filledFields, ); expect(value.script[2]).toStrictEqual(["fill_by_opid", titleField.opid, title]); expect(value.script[5]).toStrictEqual(["fill_by_opid", emailField.opid, email]); }); it("will match a full address field to the vault item identity values", async () => { const fullAddressField = createAutofillFieldMock({ opid: "fullAddress", htmlName: "address", }); pageDetails.fields = [fullAddressField]; const address1 = "123 Main St."; const address2 = "Apt. 1"; const address3 = "P.O. Box 123"; options.cipher.identity.address1 = address1; options.cipher.identity.address2 = address2; options.cipher.identity.address3 = address3; const value = await autofillService["generateIdentityFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(autofillService["makeScriptActionWithValue"]).toHaveBeenCalledWith( fillScript, `${address1}, ${address2}, ${address3}`, fullAddressField, filledFields, ); expect(value.script[2]).toStrictEqual([ "fill_by_opid", fullAddressField.opid, `${address1}, ${address2}, ${address3}`, ]); }); it("will match address1, address2, address3, postalCode, city, state, country, phone, username, and company fields to their corresponding vault item identity values", async () => { const address1Field = createAutofillFieldMock({ opid: "address1", htmlName: "address-1", }); const address2Field = createAutofillFieldMock({ opid: "address2", htmlName: "address-2", }); const address3Field = createAutofillFieldMock({ opid: "address3", htmlName: "address-3", }); const postalCodeField = createAutofillFieldMock({ opid: "postalCode", htmlName: "postal-code", }); const cityField = createAutofillFieldMock({ opid: "city", htmlName: "city" }); const stateField = createAutofillFieldMock({ opid: "state", htmlName: "state" }); const countryField = createAutofillFieldMock({ opid: "country", htmlName: "country" }); const phoneField = createAutofillFieldMock({ opid: "phone", htmlName: "phone" }); const usernameField = createAutofillFieldMock({ opid: "username", htmlName: "username", }); const companyField = createAutofillFieldMock({ opid: "company", htmlName: "company" }); pageDetails.fields = [ address1Field, address2Field, address3Field, postalCodeField, cityField, stateField, countryField, phoneField, usernameField, companyField, ]; const address1 = "123 Main St."; const address2 = "Apt. 1"; const address3 = "P.O. Box 123"; const postalCode = "12345"; const city = "City"; const state = "TX"; const country = "US"; const phone = "123-456-7890"; const username = "username"; const company = "Company"; options.cipher.identity.address1 = address1; options.cipher.identity.address2 = address2; options.cipher.identity.address3 = address3; options.cipher.identity.postalCode = postalCode; options.cipher.identity.city = city; options.cipher.identity.state = state; options.cipher.identity.country = country; options.cipher.identity.phone = phone; options.cipher.identity.username = username; options.cipher.identity.company = company; const value = await autofillService["generateIdentityFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(value.script).toContainEqual(["fill_by_opid", address1Field.opid, address1]); expect(value.script).toContainEqual(["fill_by_opid", address2Field.opid, address2]); expect(value.script).toContainEqual(["fill_by_opid", address3Field.opid, address3]); expect(value.script).toContainEqual(["fill_by_opid", postalCodeField.opid, postalCode]); expect(value.script).toContainEqual(["fill_by_opid", cityField.opid, city]); expect(value.script).toContainEqual(["fill_by_opid", stateField.opid, state]); expect(value.script).toContainEqual(["fill_by_opid", countryField.opid, country]); expect(value.script).toContainEqual(["fill_by_opid", phoneField.opid, phone]); expect(value.script).toContainEqual(["fill_by_opid", usernameField.opid, username]); expect(value.script).toContainEqual(["fill_by_opid", companyField.opid, company]); }); it("will find the two character IsoState value for an identity cipher that contains the full name of a state", async () => { const stateField = createAutofillFieldMock({ opid: "state", htmlName: "state" }); pageDetails.fields = [stateField]; const state = "California"; options.cipher.identity.state = state; const value = await autofillService["generateIdentityFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(autofillService["makeScriptActionWithValue"]).toHaveBeenCalledWith( fillScript, "CA", expect.anything(), expect.anything(), ); expect(value.script[2]).toStrictEqual(["fill_by_opid", stateField.opid, "CA"]); }); it("will find the two character IsoProvince value for an identity cipher that contains the full name of a province", async () => { const stateField = createAutofillFieldMock({ opid: "state", htmlName: "state" }); pageDetails.fields = [stateField]; const state = "Ontario"; options.cipher.identity.state = state; const value = await autofillService["generateIdentityFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(autofillService["makeScriptActionWithValue"]).toHaveBeenCalledWith( fillScript, "ON", expect.anything(), expect.anything(), ); expect(value.script[2]).toStrictEqual(["fill_by_opid", stateField.opid, "ON"]); }); it("will find the two character IsoCountry value for an identity cipher that contains the full name of a country", async () => { const countryField = createAutofillFieldMock({ opid: "country", htmlName: "country" }); pageDetails.fields = [countryField]; const country = "Somalia"; options.cipher.identity.country = country; const value = await autofillService["generateIdentityFillScript"]( fillScript, pageDetails, filledFields, options, ); expect(autofillService["makeScriptActionWithValue"]).toHaveBeenCalledWith( fillScript, "SO", expect.anything(), expect.anything(), ); expect(value.script[2]).toStrictEqual(["fill_by_opid", countryField.opid, "SO"]); }); }); } }); }); describe("isExcludedType", () => { it("returns true if the passed type is within the excluded type list", () => { const value = AutofillService["isExcludedType"]( "hidden", AutoFillConstants.ExcludedAutofillTypes, ); expect(value).toBe(true); }); it("returns true if the passed type is within the excluded type list", () => { const value = AutofillService["isExcludedType"]( "text", AutoFillConstants.ExcludedAutofillTypes, ); expect(value).toBe(false); }); }); describe("isSearchField", () => { it("returns true if the passed field type is 'search'", () => { const typedSearchField = createAutofillFieldMock({ type: "search" }); const value = AutofillService["isSearchField"](typedSearchField); expect(value).toBe(true); }); it("returns true if the passed field type is missing and another checked attribute value contains a reference to search", () => { const untypedSearchField = createAutofillFieldMock({ htmlID: "aSearchInput", placeholder: null, type: null, value: null, }); const value = AutofillService["isSearchField"](untypedSearchField); expect(value).toBe(true); }); it("returns false if the passed field is not a search field", () => { const typedSearchField = createAutofillFieldMock(); const value = AutofillService["isSearchField"](typedSearchField); expect(value).toBe(false); }); it("validates attribute identifiers with mixed camel case and non-alpha characters", () => { const attributes: Record<string, boolean> = { _$1_go_look: true, go_look: true, goLook: true, go1look: true, "go look": true, look_go: true, findPerson: true, query$1: true, look_goo: false, golook: false, lookgo: false, logonField: false, ego_input: false, "Gold Password": false, searching_for: false, person_finder: false, }; const autofillFieldMocks = Object.keys(attributes).map((key) => createAutofillFieldMock({ htmlID: key }), ); autofillFieldMocks.forEach((field) => { const value = AutofillService["isSearchField"](field); expect(value).toBe(attributes[field.htmlID]); }); }); }); describe("isFieldMatch", () => { it("returns true if the passed value is equal to one of the values in the passed options list", () => { const passedAttribute = "cc-name"; const passedOptions = ["cc-name", "cc_full_name"]; const value = AutofillService["isFieldMatch"](passedAttribute, passedOptions); expect(value).toBe(true); }); it("should returns true if the passed options contain a value within the containsOptions list and the passed value partial matches the option", () => { const passedAttribute = "cc-name-full"; const passedOptions = ["cc-name", "cc_full_name"]; const containsOptions = ["cc-name"]; const value = AutofillService["isFieldMatch"]( passedAttribute, passedOptions, containsOptions, ); expect(value).toBe(true); }); it("returns false if the value is not a partial match to an option found within the containsOption list", () => { const passedAttribute = "cc-full-name"; const passedOptions = ["cc-name", "cc_full_name"]; const containsOptions = ["cc-name"]; const value = AutofillService["isFieldMatch"]( passedAttribute, passedOptions, containsOptions, ); expect(value).toBe(false); }); }); describe("makeScriptAction", () => { let fillScript: AutofillScript; let options: GenerateFillScriptOptions; let mockLoginView: any; let fillFields: { [key: string]: AutofillField }; const filledFields = {}; beforeEach(() => { fillScript = createAutofillScriptMock({}); options = createGenerateFillScriptOptionsMock({}); mockLoginView = mock<LoginView>() as any; options.cipher.login = mockLoginView; fillFields = { "username-field": createAutofillFieldMock({ opid: "username-field" }), }; jest.spyOn(autofillService as any, "makeScriptActionWithValue"); }); it("makes a call to makeScriptActionWithValue using the passed dataProp value", () => { const dataProp = "username-field"; autofillService["makeScriptAction"]( fillScript, options.cipher.login, fillFields, filledFields, dataProp, ); expect(autofillService["makeScriptActionWithValue"]).toHaveBeenCalledWith( fillScript, mockLoginView[dataProp], fillFields[dataProp], filledFields, ); }); it("makes a call to makeScriptActionWithValue using the passed fieldProp value used for fillFields", () => { const dataProp = "value"; const fieldProp = "username-field"; autofillService["makeScriptAction"]( fillScript, options.cipher.login, fillFields, filledFields, dataProp, fieldProp, ); expect(autofillService["makeScriptActionWithValue"]).toHaveBeenCalledWith( fillScript, mockLoginView[dataProp], fillFields[fieldProp], filledFields, ); }); }); describe("makeScriptActionWithValue", () => { let fillScript: AutofillScript; let options: GenerateFillScriptOptions; let mockLoginView: any; let fillFields: { [key: string]: AutofillField }; const filledFields = {}; beforeEach(() => { fillScript = createAutofillScriptMock({}); options = createGenerateFillScriptOptionsMock({}); mockLoginView = mock<LoginView>() as any; options.cipher.login = mockLoginView; fillFields = { "username-field": createAutofillFieldMock({ opid: "username-field" }), }; jest.spyOn(autofillService as any, "makeScriptActionWithValue"); jest.spyOn(AutofillService, "hasValue"); jest.spyOn(AutofillService, "fillByOpid"); }); it("will not add an autofill action to the fill script if the value does not exist", () => { const dataValue = ""; autofillService["makeScriptActionWithValue"]( fillScript, dataValue, fillFields["username-field"], filledFields, ); expect(AutofillService.hasValue).toHaveBeenCalledWith(dataValue); expect(AutofillService.fillByOpid).not.toHaveBeenCalled(); }); it("will not add an autofill action to the fill script if a field is not passed", () => { const dataValue = "username"; autofillService["makeScriptActionWithValue"](fillScript, dataValue, null, filledFields); expect(AutofillService.hasValue).toHaveBeenCalledWith(dataValue); expect(AutofillService.fillByOpid).not.toHaveBeenCalled(); }); it("will add an autofill action to the fill script", () => { const dataValue = "username"; autofillService["makeScriptActionWithValue"]( fillScript, dataValue, fillFields["username-field"], filledFields, ); expect(AutofillService.hasValue).toHaveBeenCalledWith(dataValue); expect(AutofillService.fillByOpid).toHaveBeenCalledWith( fillScript, fillFields["username-field"], dataValue, ); }); describe("given a autofill field value that indicates the field is a `select` input", () => { it("will not add an autofil action to the fill script if the dataValue cannot be found in the select options", () => { const dataValue = "username"; const selectField = createAutofillFieldMock({ opid: "username-field", tagName: "select", type: "select-one", selectInfo: { options: [["User Name", "Some Other Username Value"]], }, }); autofillService["makeScriptActionWithValue"]( fillScript, dataValue, selectField, filledFields, ); expect(AutofillService.hasValue).toHaveBeenCalledWith(dataValue); expect(AutofillService.fillByOpid).not.toHaveBeenCalled(); }); it("will update the data value to the value found in the select options, and add an autofill action to the fill script", () => { const dataValue = "username"; const selectField = createAutofillFieldMock({ opid: "username-field", tagName: "select", type: "select-one", selectInfo: { options: [["username", "Some Other Username Value"]], }, }); autofillService["makeScriptActionWithValue"]( fillScript, dataValue, selectField, filledFields, ); expect(AutofillService.hasValue).toHaveBeenCalledWith(dataValue); expect(AutofillService.fillByOpid).toHaveBeenCalledWith( fillScript, selectField, "Some Other Username Value", ); }); }); }); describe("loadPasswordFields", () => { let pageDetails: AutofillPageDetails; let passwordField: AutofillField; beforeEach(() => { pageDetails = createAutofillPageDetailsMock({}); passwordField = createAutofillFieldMock({ opid: "password-field", type: "password", form: "validFormId", }); jest.spyOn(AutofillService, "forCustomFieldsOnly"); }); it("returns an empty array if passed a field that is a `span` element", () => { const customField = createAutofillFieldMock({ tagName: "span" }); pageDetails.fields = [customField]; const result = AutofillService.loadPasswordFields(pageDetails, false, false, false, false); expect(AutofillService.forCustomFieldsOnly).toHaveBeenCalledWith(customField); expect(result).toStrictEqual([]); }); it("returns an empty array if passed a disabled field", () => { passwordField.disabled = true; pageDetails.fields = [passwordField]; const result = AutofillService.loadPasswordFields(pageDetails, false, false, false, false); expect(result).toStrictEqual([]); }); describe("given a field that is readonly", () => { it("returns an empty array if the field cannot be readonly", () => { passwordField.readonly = true; pageDetails.fields = [passwordField]; const result = AutofillService.loadPasswordFields(pageDetails, false, false, false, false); expect(result).toStrictEqual([]); }); it("returns the field within an array if the field can be readonly", () => { passwordField.readonly = true; pageDetails.fields = [passwordField]; const result = AutofillService.loadPasswordFields(pageDetails, false, true, false, true); expect(result).toStrictEqual([passwordField]); }); }); describe("give a field that is not of type `password`", () => { beforeEach(() => { passwordField.type = "text"; }); it("returns an empty array if the field type is not `text`", () => { passwordField.type = "email"; pageDetails.fields = [passwordField]; const result = AutofillService.loadPasswordFields(pageDetails, false, false, false, false); expect(result).toStrictEqual([]); }); it("returns an empty array if the `htmlID`, `htmlName`, or `placeholder` of the field's values do not include the word `password`", () => { pageDetails.fields = [passwordField]; const result = AutofillService.loadPasswordFields(pageDetails, false, false, false, false); expect(result).toStrictEqual([]); }); it("returns an empty array if the `htmlID` of the field is `null", () => { passwordField.htmlID = null; pageDetails.fields = [passwordField]; const result = AutofillService.loadPasswordFields(pageDetails, false, false, false, false); expect(result).toStrictEqual([]); }); it("returns an empty array if the `htmlID` of the field is equal to `onetimepassword`", () => { passwordField.htmlID = "onetimepassword"; pageDetails.fields = [passwordField]; const result = AutofillService.loadPasswordFields(pageDetails, false, false, false, false); expect(result).toStrictEqual([]); }); it("returns the field in an array if the field's htmlID contains the word `password`", () => { passwordField.htmlID = "password"; pageDetails.fields = [passwordField]; const result = AutofillService.loadPasswordFields(pageDetails, false, false, false, false); expect(result).toStrictEqual([passwordField]); }); it("returns the an empty array if the field's htmlID contains the words `password` and `captcha`", () => { passwordField.htmlID = "inputPasswordCaptcha"; pageDetails.fields = [passwordField]; const result = AutofillService.loadPasswordFields(pageDetails, false, false, false, false); expect(result).toStrictEqual([]); }); it("returns the field in an array if the field's htmlName contains the word `password`", () => { passwordField.htmlName = "password"; pageDetails.fields = [passwordField]; const result = AutofillService.loadPasswordFields(pageDetails, false, false, false, false); expect(result).toStrictEqual([passwordField]); }); it("returns the an empty array if the field's htmlName contains the words `password` and `captcha`", () => { passwordField.htmlName = "inputPasswordCaptcha"; pageDetails.fields = [passwordField]; const result = AutofillService.loadPasswordFields(pageDetails, false, false, false, false); expect(result).toStrictEqual([]); }); it("returns the field in an array if the field's placeholder contains the word `password`", () => { passwordField.placeholder = "password"; pageDetails.fields = [passwordField]; const result = AutofillService.loadPasswordFields(pageDetails, false, false, false, false); expect(result).toStrictEqual([passwordField]); }); it("returns the an empty array if the field's placeholder contains the words `password` and `captcha`", () => { passwordField.placeholder = "inputPasswordCaptcha"; pageDetails.fields = [passwordField]; const result = AutofillService.loadPasswordFields(pageDetails, false, false, false, false); expect(result).toStrictEqual([]); }); it("returns the an empty array if any of the field's checked attributed contain the words `captcha` while any other attribute contains the word `password` and no excluded terms", () => { passwordField.htmlID = "inputPasswordCaptcha"; passwordField.htmlName = "captcha"; passwordField.placeholder = "Enter password"; pageDetails.fields = [passwordField]; const result = AutofillService.loadPasswordFields(pageDetails, false, false, false, false); expect(result).toStrictEqual([]); }); }); describe("given a field that is not viewable", () => { it("returns an empty array if the field cannot be hidden", () => { passwordField.viewable = false; pageDetails.fields = [passwordField]; const result = AutofillService.loadPasswordFields(pageDetails, false, false, false, false); expect(result).toStrictEqual([]); }); it("returns the field within an array if the field can be hidden", () => { passwordField.viewable = false; pageDetails.fields = [passwordField]; const result = AutofillService.loadPasswordFields(pageDetails, true, false, false, true); expect(result).toStrictEqual([passwordField]); }); }); describe("given a need for the passed to be empty", () => { it("returns an empty array if the passed field contains a value that is not null or empty", () => { passwordField.value = "Some Password Value"; pageDetails.fields = [passwordField]; const result = AutofillService.loadPasswordFields(pageDetails, false, false, true, false); expect(result).toStrictEqual([]); }); it("returns the field within an array if the field contains a null value", () => { passwordField.value = null; pageDetails.fields = [passwordField]; const result = AutofillService.loadPasswordFields(pageDetails, false, false, true, false); expect(result).toStrictEqual([passwordField]); }); it("returns the field within an array if the field contains an empty value", () => { passwordField.value = ""; pageDetails.fields = [passwordField]; const result = AutofillService.loadPasswordFields(pageDetails, false, false, true, false); expect(result).toStrictEqual([passwordField]); }); }); describe("given a field with a new password", () => { beforeEach(() => { passwordField.autoCompleteType = "new-password"; }); it("returns an empty array if not filling a new password and the autoCompleteType is `new-password`", () => { pageDetails.fields = [passwordField]; const result = AutofillService.loadPasswordFields(pageDetails, false, false, false, false); expect(result).toStrictEqual([]); }); it("returns the field within an array if filling a new password and the autoCompleteType is `new-password`", () => { pageDetails.fields = [passwordField]; const result = AutofillService.loadPasswordFields(pageDetails, false, false, false, true); expect(result).toStrictEqual([passwordField]); }); }); }); describe("findUsernameField", () => { let pageDetails: AutofillPageDetails; let usernameField: AutofillField; let passwordField: AutofillField; beforeEach(() => { pageDetails = createAutofillPageDetailsMock({}); usernameField = createAutofillFieldMock({ opid: "username-field", type: "text", form: "validFormId", elementNumber: 0, }); passwordField = createAutofillFieldMock({ opid: "password-field", type: "password", form: "validFormId", elementNumber: 1, }); pageDetails.fields = [usernameField, passwordField]; jest.spyOn(AutofillService, "forCustomFieldsOnly"); jest.spyOn(autofillService as any, "findMatchingFieldIndex"); }); it("returns null when passed a field that is a `span` element", () => { const field = createAutofillFieldMock({ tagName: "span" }); pageDetails.fields = [field]; const result = autofillService["findUsernameField"](pageDetails, field, false, false, false); expect(AutofillService.forCustomFieldsOnly).toHaveBeenCalledWith(field); expect(result).toBe(null); }); it("returns null when the passed username field has a larger elementNumber than the passed password field", () => { usernameField.elementNumber = 2; const result = autofillService["findUsernameField"]( pageDetails, passwordField, false, false, false, ); expect(result).toBe(null); }); it("returns null if the passed username field is disabled", () => { usernameField.disabled = true; const result = autofillService["findUsernameField"]( pageDetails, passwordField, false, false, false, ); expect(result).toBe(null); }); describe("given a field that is readonly", () => { beforeEach(() => { usernameField.readonly = true; }); it("returns null if the field cannot be readonly", () => { const result = autofillService["findUsernameField"]( pageDetails, passwordField, false, false, false, ); expect(result).toBe(null); }); it("returns the field if the field can be readonly", () => { const result = autofillService["findUsernameField"]( pageDetails, passwordField, false, true, false, ); expect(result).toBe(usernameField); }); }); describe("given a username field that does not contain a form that matches the password field", () => { beforeEach(() => { usernameField.form = "invalidFormId"; usernameField.type = "tel"; }); it("returns null if the field cannot be without a form", () => { const result = autofillService["findUsernameField"]( pageDetails, passwordField, false, false, false, ); expect(result).toBe(null); }); it("returns the field if the username field can be without a form", () => { const result = autofillService["findUsernameField"]( pageDetails, passwordField, false, false, true, ); expect(result).toBe(usernameField); }); }); describe("given a field that is not viewable", () => { beforeEach(() => { usernameField.viewable = false; usernameField.type = "email"; }); it("returns null if the field cannot be hidden", () => { const result = autofillService["findUsernameField"]( pageDetails, passwordField, false, false, false, ); expect(result).toBe(null); }); it("returns the field if the field can be hidden", () => { const result = autofillService["findUsernameField"]( pageDetails, passwordField, true, false, false, ); expect(result).toBe(usernameField); }); }); it("returns null if the username field does not have a type of `text`, `email`, or `tel`", () => { usernameField.type = "checkbox"; const result = autofillService["findUsernameField"]( pageDetails, passwordField, false, false, false, ); expect(result).toBe(null); }); it("returns the username field whose attributes most closely describe the username of the password field", () => { const usernameField2 = createAutofillFieldMock({ opid: "username-field-2", type: "text", form: "validFormId", htmlName: "username", elementNumber: 1, }); const usernameField3 = createAutofillFieldMock({ opid: "username-field-3", type: "text", form: "validFormId", elementNumber: 1, }); passwordField.elementNumber = 3; pageDetails.fields = [usernameField, usernameField2, usernameField3, passwordField]; const result = autofillService["findUsernameField"]( pageDetails, passwordField, false, false, false, ); expect(result).toBe(usernameField2); expect(autofillService["findMatchingFieldIndex"]).toHaveBeenCalledTimes(2); expect(autofillService["findMatchingFieldIndex"]).not.toHaveBeenCalledWith( usernameField3, AutoFillConstants.UsernameFieldNames, ); }); }); describe("findTotpField", () => { let pageDetails: AutofillPageDetails; let passwordField: AutofillField; let totpField: AutofillField; beforeEach(() => { pageDetails = createAutofillPageDetailsMock({}); passwordField = createAutofillFieldMock({ opid: "password-field", type: "password", form: "validFormId", elementNumber: 0, }); totpField = createAutofillFieldMock({ opid: "totp-field", type: "text", form: "validFormId", htmlName: "totp", elementNumber: 1, }); pageDetails.fields = [passwordField, totpField]; jest.spyOn(AutofillService, "forCustomFieldsOnly"); jest.spyOn(autofillService as any, "findMatchingFieldIndex"); jest.spyOn(AutofillService, "fieldIsFuzzyMatch"); }); it("returns null when passed a field that is a `span` element", () => { const field = createAutofillFieldMock({ tagName: "span" }); pageDetails.fields = [field]; const result = autofillService["findTotpField"](pageDetails, field, false, false, false); expect(AutofillService.forCustomFieldsOnly).toHaveBeenCalledWith(field); expect(result).toBe(null); }); it("returns null if the passed totp field is disabled", () => { totpField.disabled = true; const result = autofillService["findTotpField"]( pageDetails, passwordField, false, false, false, ); expect(result).toBe(null); }); describe("given a field that is readonly", () => { beforeEach(() => { totpField.readonly = true; }); it("returns null if the field cannot be readonly", () => { const result = autofillService["findTotpField"]( pageDetails, passwordField, false, false, false, ); expect(result).toBe(null); }); it("returns the field if the field can be readonly", () => { const result = autofillService["findTotpField"]( pageDetails, passwordField, false, true, false, ); expect(result).toBe(totpField); }); }); describe("given a totp field that does not contain a form that matches the password field", () => { beforeEach(() => { totpField.form = "invalidFormId"; }); it("returns null if the field cannot be without a form", () => { const result = autofillService["findTotpField"]( pageDetails, passwordField, false, false, false, ); expect(result).toBe(null); }); it("returns the field if the username field can be without a form", () => { const result = autofillService["findTotpField"]( pageDetails, passwordField, false, false, true, ); expect(result).toBe(totpField); }); }); describe("given a field that is not viewable", () => { beforeEach(() => { totpField.viewable = false; totpField.type = "number"; }); it("returns null if the field cannot be hidden", () => { const result = autofillService["findTotpField"]( pageDetails, passwordField, false, false, false, ); expect(result).toBe(null); }); it("returns the field if the field can be hidden", () => { const result = autofillService["findTotpField"]( pageDetails, passwordField, true, false, false, ); expect(result).toBe(totpField); }); }); it("returns null if the totp field does not have a type of `text`, or `number`", () => { totpField.type = "checkbox"; const result = autofillService["findTotpField"]( pageDetails, passwordField, false, false, false, ); expect(result).toBe(null); }); it("returns the field if the autoCompleteType is `one-time-code`", () => { totpField.autoCompleteType = "one-time-code"; jest.spyOn(autofillService as any, "findMatchingFieldIndex").mockReturnValueOnce(-1); const result = autofillService["findTotpField"]( pageDetails, passwordField, false, false, false, ); expect(result).toBe(totpField); }); }); describe("findMatchingFieldIndex", () => { beforeEach(() => { jest.spyOn(autofillService as any, "fieldPropertyIsMatch"); }); it("returns the index of a value that matches a property prefix", () => { const attributes = [ ["htmlID", "id"], ["htmlName", "name"], ["label-aria", "label"], ["label-tag", "label"], ["label-right", "label"], ["label-left", "label"], ["placeholder", "placeholder"], ]; const value = "username"; attributes.forEach((attribute) => { const field = createAutofillFieldMock({ [attribute[0]]: value }); const result = autofillService["findMatchingFieldIndex"](field, [ `${attribute[1]}=${value}`, ]); expect(autofillService["fieldPropertyIsMatch"]).toHaveBeenCalledWith( field, attribute[0], value, ); expect(result).toBe(0); }); }); it("returns the index of a value that matches a property", () => { const attributes = [ "htmlID", "htmlName", "label-aria", "label-tag", "label-right", "label-left", "placeholder", ]; const value = "username"; attributes.forEach((attribute) => { const field = createAutofillFieldMock({ [attribute]: value }); const result = autofillService["findMatchingFieldIndex"](field, [value]); expect(result).toBe(0); }); }); }); describe("fieldPropertyIsPrefixMatch", () => { it("returns true if the field contains a property whose value is a match", () => { const field = createAutofillFieldMock({ htmlID: "username" }); const result = autofillService["fieldPropertyIsPrefixMatch"]( field, "htmlID", "id=username", "id", ); expect(result).toBe(true); }); it("returns false if the field contains a property whose value is not a match", () => { const field = createAutofillFieldMock({ htmlID: "username" }); const result = autofillService["fieldPropertyIsPrefixMatch"]( field, "htmlID", "id=some-othername", "id", ); expect(result).toBe(false); }); }); describe("fieldPropertyIsMatch", () => { let field: AutofillField; beforeEach(() => { field = createAutofillFieldMock(); jest.spyOn(AutofillService, "hasValue"); }); it("returns false if the property within the field does not have a value", () => { field.htmlID = ""; const result = autofillService["fieldPropertyIsMatch"](field, "htmlID", "some-value"); expect(AutofillService.hasValue).toHaveBeenCalledWith(""); expect(result).toBe(false); }); it("returns true if the property within the field provides a value that is equal to the passed `name`", () => { field.htmlID = "some-value"; const result = autofillService["fieldPropertyIsMatch"](field, "htmlID", "some-value"); expect(AutofillService.hasValue).toHaveBeenCalledWith("some-value"); expect(result).toBe(true); }); describe("given a passed `name` value that is expecting a regex check", () => { it("returns false if the property within the field fails the `name` regex check", () => { field.htmlID = "some-false-value"; const result = autofillService["fieldPropertyIsMatch"](field, "htmlID", "regex=some-value"); expect(result).toBe(false); }); it("returns true if the property within the field equals the `name` regex check", () => { field.htmlID = "some-value"; const result = autofillService["fieldPropertyIsMatch"](field, "htmlID", "regex=some-value"); expect(result).toBe(true); }); it("returns true if the property within the field has a partial match to the `name` regex check", () => { field.htmlID = "some-value"; const result = autofillService["fieldPropertyIsMatch"](field, "htmlID", "regex=value"); expect(result).toBe(true); }); it("will log an error when the regex triggers a catch block", () => { field.htmlID = "some-value"; jest.spyOn(autofillService["logService"], "error"); const result = autofillService["fieldPropertyIsMatch"](field, "htmlID", "regex=+"); expect(autofillService["logService"].error).toHaveBeenCalled(); expect(result).toBe(false); }); }); describe("given a passed `name` value that is checking comma separated values", () => { it("returns false if the property within the field does not have a value that matches the values within the `name` CSV", () => { field.htmlID = "some-false-value"; const result = autofillService["fieldPropertyIsMatch"]( field, "htmlID", "csv=some-value,some-other-value,some-third-value", ); expect(result).toBe(false); }); it("returns true if the property within the field matches a value within the `name` CSV", () => { field.htmlID = "some-other-value"; const result = autofillService["fieldPropertyIsMatch"]( field, "htmlID", "csv=some-value,some-other-value,some-third-value", ); expect(result).toBe(true); }); }); }); describe("fieldIsFuzzyMatch", () => { let field: AutofillField; const fieldProperties = [ "htmlID", "htmlName", "label-aria", "label-tag", "label-top", "label-left", "placeholder", ]; beforeEach(() => { field = createAutofillFieldMock(); jest.spyOn(AutofillService, "hasValue"); jest.spyOn(AutofillService as any, "fuzzyMatch"); }); it("returns false if the field properties do not have any values", () => { fieldProperties.forEach((property) => { field[property] = ""; }); const result = AutofillService["fieldIsFuzzyMatch"](field, ["some-value"]); expect(AutofillService.hasValue).toHaveBeenCalledTimes(7); expect(AutofillService["fuzzyMatch"]).not.toHaveBeenCalled(); expect(result).toBe(false); }); it("returns false if the field properties do not have a value that is a fuzzy match", () => { fieldProperties.forEach((property) => { field[property] = "some-false-value"; const result = AutofillService["fieldIsFuzzyMatch"](field, ["some-value"]); expect(AutofillService.hasValue).toHaveBeenCalled(); expect(AutofillService["fuzzyMatch"]).toHaveBeenCalledWith( ["some-value"], "some-false-value", ); expect(result).toBe(false); field[property] = ""; }); }); it("returns true if the field property has a value that is a fuzzy match", () => { fieldProperties.forEach((property) => { field[property] = "some-value"; const result = AutofillService["fieldIsFuzzyMatch"](field, ["some-value"]); expect(AutofillService.hasValue).toHaveBeenCalled(); expect(AutofillService["fuzzyMatch"]).toHaveBeenCalledWith(["some-value"], "some-value"); expect(result).toBe(true); field[property] = ""; }); }); }); describe("fuzzyMatch", () => { it("returns false if the passed options is null", () => { const result = AutofillService["fuzzyMatch"](null, "some-value"); expect(result).toBe(false); }); it("returns false if the passed options contains an empty array", () => { const result = AutofillService["fuzzyMatch"]([], "some-value"); expect(result).toBe(false); }); it("returns false if the passed value is null", () => { const result = AutofillService["fuzzyMatch"](["some-value"], null); expect(result).toBe(false); }); it("returns false if the passed value is an empty string", () => { const result = AutofillService["fuzzyMatch"](["some-value"], ""); expect(result).toBe(false); }); it("returns false if the passed value is not present in the options array", () => { const result = AutofillService["fuzzyMatch"](["some-value"], "some-other-value"); expect(result).toBe(false); }); it("returns true if the passed value is within the options array", () => { const result = AutofillService["fuzzyMatch"]( ["some-other-value", "some-value"], "some-value", ); expect(result).toBe(true); }); }); describe("hasValue", () => { it("returns false if the passed string is null", () => { const result = AutofillService.hasValue(null); expect(result).toBe(false); }); it("returns false if the passed string is an empty string", () => { const result = AutofillService.hasValue(""); expect(result).toBe(false); }); it("returns true if the passed string is not null or an empty string", () => { const result = AutofillService.hasValue("some-value"); expect(result).toBe(true); }); }); describe("setFillScriptForFocus", () => { let usernameField: AutofillField; let passwordField: AutofillField; let filledFields: { [key: string]: AutofillField }; let fillScript: AutofillScript; beforeEach(() => { usernameField = createAutofillFieldMock({ opid: "username-field", type: "text", form: "validFormId", elementNumber: 0, }); passwordField = createAutofillFieldMock({ opid: "password-field", type: "password", form: "validFormId", elementNumber: 1, }); filledFields = { "username-field": usernameField, "password-field": passwordField, }; fillScript = createAutofillScriptMock({ script: [] }); }); it("returns a fill script with an unmodified actions list if an empty filledFields value is passed", () => { const result = AutofillService.setFillScriptForFocus({}, fillScript); expect(result.script).toStrictEqual([]); }); it("returns a fill script with the password field prioritized when adding a `focus_by_opid` action", () => { const result = AutofillService.setFillScriptForFocus(filledFields, fillScript); expect(result.script).toStrictEqual([["focus_by_opid", "password-field"]]); }); it("returns a fill script with the username field if a password field is not present when adding a `focus_by_opid` action", () => { delete filledFields["password-field"]; const result = AutofillService.setFillScriptForFocus(filledFields, fillScript); expect(result.script).toStrictEqual([["focus_by_opid", "username-field"]]); }); }); describe("fillByOpid", () => { let usernameField: AutofillField; let fillScript: AutofillScript; beforeEach(() => { usernameField = createAutofillFieldMock({ opid: "username-field", type: "text", form: "validFormId", elementNumber: 0, }); fillScript = createAutofillScriptMock({ script: [] }); }); it("returns a list of fill script actions for the passed field", () => { usernameField.maxLength = 5; AutofillService.fillByOpid(fillScript, usernameField, "some-long-value"); expect(fillScript.script).toStrictEqual([ ["click_on_opid", "username-field"], ["focus_by_opid", "username-field"], ["fill_by_opid", "username-field", "some-long-value"], ]); }); it("returns only the `fill_by_opid` action if the passed field is a `span` element", () => { usernameField.tagName = "span"; AutofillService.fillByOpid(fillScript, usernameField, "some-long-value"); expect(fillScript.script).toStrictEqual([ ["fill_by_opid", "username-field", "some-long-value"], ]); }); }); describe("forCustomFieldsOnly", () => { it("returns a true value if the passed field has a tag name of `span`", () => { const field = createAutofillFieldMock({ tagName: "span" }); const result = AutofillService.forCustomFieldsOnly(field); expect(result).toBe(true); }); it("returns a false value if the passed field does not have a tag name of `span`", () => { const field = createAutofillFieldMock({ tagName: "input" }); const result = AutofillService.forCustomFieldsOnly(field); expect(result).toBe(false); }); }); describe("isDebouncingPasswordRepromptPopout", () => { it("returns false and sets up the debounce if a master password reprompt window is not currently opening", () => { jest.spyOn(globalThis, "setTimeout"); const result = autofillService["isDebouncingPasswordRepromptPopout"](); expect(result).toBe(false); expect(globalThis.setTimeout).toHaveBeenCalledWith(expect.any(Function), 100); expect(autofillService["currentlyOpeningPasswordRepromptPopout"]).toBe(true); }); it("returns true if a master password reprompt window is currently opening", () => { autofillService["currentlyOpeningPasswordRepromptPopout"] = true; const result = autofillService["isDebouncingPasswordRepromptPopout"](); expect(result).toBe(true); }); it("resets the currentlyOpeningPasswordRepromptPopout value to false after the debounce has occurred", () => { jest.useFakeTimers(); const result = autofillService["isDebouncingPasswordRepromptPopout"](); jest.advanceTimersByTime(100); expect(result).toBe(false); expect(autofillService["currentlyOpeningPasswordRepromptPopout"]).toBe(false); }); }); describe("handleInjectedScriptPortConnection", () => { it("ignores port connections that do not have the correct port name", () => { const port = mock<chrome.runtime.Port>({ name: "some-invalid-port-name", onDisconnect: { addListener: jest.fn() }, }) as any; autofillService["handleInjectedScriptPortConnection"](port); expect(port.onDisconnect.addListener).not.toHaveBeenCalled(); expect(autofillService["autofillScriptPortsSet"].size).toBe(0); }); it("adds the connect port to the set of injected script ports and sets up an onDisconnect listener", () => { const port = mock<chrome.runtime.Port>({ name: AutofillPort.InjectedScript, onDisconnect: { addListener: jest.fn() }, }) as any; jest.spyOn(autofillService as any, "handleInjectScriptPortOnDisconnect"); autofillService["handleInjectedScriptPortConnection"](port); expect(port.onDisconnect.addListener).toHaveBeenCalledWith( autofillService["handleInjectScriptPortOnDisconnect"], ); expect(autofillService["autofillScriptPortsSet"].size).toBe(1); }); }); describe("handleInjectScriptPortOnDisconnect", () => { it("ignores port disconnections that do not have the correct port name", () => { autofillService["autofillScriptPortsSet"].add(mock<chrome.runtime.Port>()); autofillService["handleInjectScriptPortOnDisconnect"]( mock<chrome.runtime.Port>({ name: "some-invalid-port-name", }), ); expect(autofillService["autofillScriptPortsSet"].size).toBe(1); }); it("removes the port from the set of injected script ports", () => { const port = mock<chrome.runtime.Port>({ name: AutofillPort.InjectedScript, }) as any; autofillService["autofillScriptPortsSet"].add(port); autofillService["handleInjectScriptPortOnDisconnect"](port); expect(autofillService["autofillScriptPortsSet"].size).toBe(0); }); }); }); ```
/content/code_sandbox/apps/browser/src/autofill/services/autofill.service.spec.ts
xml
2016-03-09T23:14:01
2024-08-16T15:07:51
clients
bitwarden/clients
8,877
37,839
```xml <?xml version="1.0" encoding="UTF-8"?> <testsuites> <testsuite name="tensorflow/python/kernel_tests/concat_op_test" tests="1" failures="0" errors="1"> <testcase name="tensorflow/python/kernel_tests/concat_op_test" status="run"><error message="exited with error code 1"></error></testcase> </testsuite> </testsuites> ```
/content/code_sandbox/testlogs/python27/2016_07_17/tensorflow/python/kernel_tests/concat_op_test/test.xml
xml
2016-03-12T06:26:47
2024-08-12T19:21:52
tensorflow-on-raspberry-pi
samjabrahams/tensorflow-on-raspberry-pi
2,242
92
```xml <?xml version="1.0" encoding="UTF-8" standalone="no"?> <document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="10116" systemVersion="15E65" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="ZRB-0S-R4F"> <dependencies> <deployment identifier="iOS"/> <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/> </dependencies> <scenes> <!--Advance View Controller--> <scene sceneID="i9r-rZ-Uxz"> <objects> <viewController id="ZRB-0S-R4F" customClass="AdvanceViewController" sceneMemberID="viewController"> <layoutGuides> <viewControllerLayoutGuide type="top" id="hOx-M5-8bX"/> <viewControllerLayoutGuide type="bottom" id="q4K-hw-7AM"/> </layoutGuides> <view key="view" contentMode="scaleToFill" id="cvW-dY-UkR" customClass="GLKView"> <rect key="frame" x="0.0" y="0.0" width="600" height="600"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/> </view> </viewController> <placeholder placeholderIdentifier="IBFirstResponder" id="Xpp-St-IOk" userLabel="First Responder" sceneMemberID="firstResponder"/> </objects> <point key="canvasLocation" x="-1111" y="213"/> </scene> </scenes> </document> ```
/content/code_sandbox/Tutorial10-平截体优化/LearnOpenGLES/Base.lproj/Main.storyboard
xml
2016-03-11T07:58:04
2024-08-16T03:42:56
LearnOpenGLES
loyinglin/LearnOpenGLES
1,618
413
```xml import React, { useContext, useMemo, useReducer } from 'react'; import PropTypes from 'prop-types'; import omit from 'lodash/omit'; import pick from 'lodash/pick'; import DropdownMenu from './DropdownMenu'; import { PLACEMENT_8 } from '@/internals/constants'; import { useClassNames } from '@/internals/hooks'; import { mergeRefs, placementPolyfill, warnOnce } from '@/internals/utils'; import { TypeAttributes, WithAsProps, RsRefForwardingComponent } from '@/internals/types'; import { IconProps } from '@rsuite/icons/lib/Icon'; import { deprecatePropType, oneOf } from '@/internals/propTypes'; import DropdownItem from './DropdownItem'; import DropdownContext, { DropdownContextProps } from './DropdownContext'; import Menu, { MenuButtonTrigger } from '@/internals/Menu/Menu'; import DropdownToggle from './DropdownToggle'; import kebabCase from 'lodash/kebabCase'; import NavContext from '../Nav/NavContext'; import { initialState, reducer } from './DropdownState'; import Button from '../Button'; import Nav from '../Nav'; import DropdownSeparator from './DropdownSeparator'; export type DropdownTrigger = 'click' | 'hover' | 'contextMenu'; export interface DropdownProps<T = any> extends WithAsProps, Omit<React.HTMLAttributes<HTMLElement>, 'onSelect' | 'title'> { /** Define the title as a submenu */ title?: React.ReactNode; /** Set the icon */ icon?: React.ReactElement<IconProps>; /** The option to activate the state, corresponding to the eventkey in the Dropdown.item */ activeKey?: T; /** Triggering events */ trigger?: DropdownTrigger | DropdownTrigger[]; /** The placement of Menu */ placement?: TypeAttributes.Placement8; /** Whether or not component is disabled */ disabled?: boolean; /** The style of the menu */ menuStyle?: React.CSSProperties; /** A css class to apply to the Toggle DOM node */ toggleClassName?: string; /** The value of the current option */ eventKey?: T; /** You can use a custom element type for this toggle component */ toggleAs?: React.ElementType; /** No caret variation */ noCaret?: boolean; /** * Controlled open state */ open?: boolean; /** * Whether dropdown is initially open */ defaultOpen?: boolean; /** * @deprecated */ renderTitle?: (children: React.ReactNode) => React.ReactNode; /** Custom Toggle */ renderToggle?: (props: WithAsProps, ref: React.Ref<any>) => any; /** The callback function that the menu closes */ onClose?: () => void; /** Menu Pop-up callback function */ onOpen?: () => void; /** Callback function for menu state switching */ onToggle?: (open?: boolean) => void; /** Selected callback function */ onSelect?: (eventKey: T | undefined, event: React.SyntheticEvent) => void; } export interface DropdownComponent extends RsRefForwardingComponent<'div', DropdownProps> { // Infer toggleAs props <ToggleAs extends React.ElementType = typeof Button>( props: DropdownProps & { ref?: React.Ref<any>; toggleAs?: ToggleAs; } & React.ComponentProps<ToggleAs>, context: any ): JSX.Element | null; Item: typeof DropdownItem; Menu: typeof DropdownMenu; Separator: typeof DropdownSeparator; } /** * The `Dropdown` component is used to select an option from a set of options. * @see path_to_url * * The `<Dropdown>` API * - When used inside `<Sidenav>`, renders a `<TreeviewRootItem>`; * - Otherwise renders a `<MenuRoot>` */ const Dropdown: DropdownComponent = React.forwardRef<HTMLElement>((props: DropdownProps, ref) => { const { activeKey, onSelect, ...rest } = props; const { as: Component = 'div', title, onClose, onOpen, onToggle, trigger = 'click', placement = 'bottomStart', toggleAs, toggleClassName, open, defaultOpen, classPrefix = 'dropdown', className, disabled, children, menuStyle, style, ...toggleProps } = rest; const nav = useContext(NavContext); const { merge, withClassPrefix } = useClassNames(classPrefix); const { withClassPrefix: withMenuClassPrefix, merge: mergeMenuClassName } = useClassNames('dropdown-menu'); const menuButtonTriggers = useMemo<MenuButtonTrigger[] | undefined>(() => { if (!trigger) { return undefined; } const triggerMap: { [key: string]: MenuButtonTrigger } = { hover: 'mouseover', click: 'click', contextMenu: 'contextmenu' }; if (!Array.isArray(trigger)) { return [triggerMap[trigger]]; } return trigger.map(t => triggerMap[t]); }, [trigger]); const [{ items }, dispatch] = useReducer(reducer, initialState); const hasSelectedItem = useMemo(() => { return items.some(item => item.props.selected); }, [items]); const dropdownContextValue = useMemo<DropdownContextProps>(() => { return { activeKey, onSelect, hasSelectedItem, dispatch }; }, [activeKey, onSelect, hasSelectedItem, dispatch]); // Deprecate <Dropdown> within <Nav> usage // in favor of <Nav.Menu> API if (nav) { warnOnce('Usage of <Dropdown> within <Nav> is deprecated. Replace with <Nav.Menu>'); return <Nav.Menu ref={ref} {...props} />; } const renderMenuButton = (menuButtonProps, menuButtonRef) => ( <DropdownToggle ref={menuButtonRef} as={toggleAs} className={toggleClassName} placement={placement} disabled={disabled} {...omit(menuButtonProps, ['open'])} {...omit(toggleProps, ['data-testid'])} > {title} </DropdownToggle> ); return ( <DropdownContext.Provider value={dropdownContextValue}> <Menu open={open} defaultOpen={defaultOpen} menuButtonText={title} renderMenuButton={renderMenuButton} disabled={disabled} openMenuOn={menuButtonTriggers} renderMenuPopup={({ open, ...popupProps }, popupRef) => { const menuClassName = mergeMenuClassName(className, withMenuClassPrefix({})); return ( <ul ref={popupRef} className={menuClassName} style={menuStyle} hidden={!open} {...popupProps} > {children} </ul> ); }} onToggleMenu={open => { onToggle?.(open); if (open) { onOpen?.(); } else { onClose?.(); } }} > {({ open, ...menuContainer }, menuContainerRef: React.Ref<HTMLElement>) => { const classes = merge( className, withClassPrefix({ [`placement-${kebabCase(placementPolyfill(placement))}`]: !!placement, disabled, open, 'selected-within': hasSelectedItem }) ); return ( <Component ref={mergeRefs(ref, menuContainerRef)} className={classes} {...menuContainer} {...pick(toggleProps, ['data-testid'])} style={style} /> ); }} </Menu> </DropdownContext.Provider> ); }) as unknown as DropdownComponent; Dropdown.Item = DropdownItem; Dropdown.Menu = DropdownMenu; Dropdown.Separator = DropdownSeparator; Dropdown.displayName = 'Dropdown'; Dropdown.propTypes = { activeKey: PropTypes.any, classPrefix: PropTypes.string, trigger: PropTypes.oneOfType([PropTypes.array, oneOf(['click', 'hover', 'contextMenu'])]), placement: oneOf(PLACEMENT_8), title: PropTypes.node, disabled: PropTypes.bool, icon: PropTypes.node, menuStyle: PropTypes.object, className: PropTypes.string, toggleClassName: PropTypes.string, children: PropTypes.node, open: deprecatePropType(PropTypes.bool), eventKey: PropTypes.any, as: PropTypes.elementType, toggleAs: PropTypes.elementType, noCaret: PropTypes.bool, style: PropTypes.object, onClose: PropTypes.func, onOpen: PropTypes.func, onToggle: PropTypes.func, onSelect: PropTypes.func, onMouseEnter: PropTypes.func, onMouseLeave: PropTypes.func, onContextMenu: PropTypes.func, onClick: PropTypes.func, renderToggle: PropTypes.func }; export default Dropdown; ```
/content/code_sandbox/src/Dropdown/Dropdown.tsx
xml
2016-06-06T02:27:46
2024-08-16T16:41:54
rsuite
rsuite/rsuite
8,263
1,868
```xml import * as React from 'react'; import { Position } from '../../Positioning'; import type { IButtonStyles, IButtonProps } from '../../Button'; import type { IIconProps } from '../../Icon'; import type { ITheme, IStyle, IShadowDomStyle } from '../../Styling'; import type { IKeytipProps } from '../../Keytip'; import type { IRefObject, IStyleFunctionOrObject } from '../../Utilities'; /** * {@docCategory SpinButton} */ export interface ISpinButton { /** * Current committed/validated value of the control. Note that this does *not* update on every * keystroke while the user is editing text in the input field. * "committed" the edit yet by focusing away (blurring) or pressing enter, */ value?: string; /** * Sets focus to the control. */ focus: () => void; } /** * {@docCategory SpinButton} */ export enum KeyboardSpinDirection { down = -1, notSpinning = 0, up = 1, } /** * {@docCategory SpinButton} */ export interface ISpinButtonProps extends React.HTMLAttributes<HTMLDivElement>, React.RefAttributes<HTMLDivElement> { /** * Gets the component ref. */ componentRef?: IRefObject<ISpinButton>; /** * Initial value of the control (assumed to be valid). Updates to this prop will not be respected. * * Use this if you intend for the SpinButton to be an uncontrolled component which maintains its * own value. For a controlled component, use `value` instead. (Mutually exclusive with `value`.) * @defaultvalue 0 */ defaultValue?: string; /** * Current value of the control (assumed to be valid). * * Only provide this if the SpinButton is a controlled component where you are maintaining its * current state and passing updates based on change events; otherwise, use the `defaultValue` * property. (Mutually exclusive with `defaultValue`.) */ value?: string; /** * Min value of the control. If not provided, the control has no minimum value. */ min?: number; /** * Max value of the control. If not provided, the control has no maximum value. */ max?: number; /** * Difference between two adjacent values of the control. * This value is used to calculate the precision of the input if no `precision` is given. * The precision calculated this way will always be \>= 0. * @defaultvalue 1 */ step?: number; /** * A description of the control for the benefit of screen reader users. */ ariaLabel?: string; /** * ID of a label which describes the control, if not using the default label. */ ariaDescribedBy?: string; /** * A more descriptive title for the control, visible on its tooltip. */ title?: string; /** * Whether or not the control is disabled. */ disabled?: boolean; /** * Custom className for the control. */ className?: string; /** * Descriptive label for the control. */ label?: string; /** * Where to position the control's label. * @defaultvalue Left */ labelPosition?: Position; /** * Props for an icon to display alongside the control's label. */ iconProps?: IIconProps; /** * Callback for when the committed/validated value changes. This is called *after* `onIncrement`, * `onDecrement`, or `onValidate`, on the following events: * - User presses the up/down buttons (on single press or every spin) * - User presses the up/down arrow keys (on single press or every spin) * - User *commits* edits to the input text by focusing away (blurring) or pressing enter. * Note that this is NOT called for every key press while the user is editing. */ onChange?: (event: React.SyntheticEvent<HTMLElement>, newValue?: string) => void; /** * Callback for when the entered value should be validated. * @param value - The entered value to validate * @param event - The event that triggered this validate, if any (for accessibility) * @returns If a string is returned, it will be used as the new value */ onValidate?: (value: string, event?: React.SyntheticEvent<HTMLElement>) => string | void; /** * Callback for when the increment button or up arrow key is pressed. * @param value - The current value to be incremented * @param event - The event that triggered this increment * @returns If a string is returned, it will be used as the new value */ onIncrement?: ( value: string, event?: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>, ) => string | void; /** * Callback for when the decrement button or down arrow key is pressed. * @param value - The current value to be decremented * @param event - The event that triggered this decrement * @returns If a string is returned, it will be used as the new value */ onDecrement?: ( value: string, event?: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>, ) => string | void; /** * Callback for when the user focuses the control. */ onFocus?: React.FocusEventHandler<HTMLInputElement>; /** * Callback for when the control loses focus. */ onBlur?: React.FocusEventHandler<HTMLInputElement>; /** * Custom props for the increment button. */ incrementButtonIcon?: IIconProps; /** * Custom props for the decrement button. */ decrementButtonIcon?: IIconProps; /** * Custom styling for individual elements within the control. */ styles?: IStyleFunctionOrObject<ISpinButtonStyleProps, ISpinButtonStyles>; /** * Custom styles for the up arrow button. * * Note: The buttons are in a checked state when arrow keys are used to increment/decrement * the SpinButton. Use `rootChecked` instead of `rootPressed` for styling when that is the case. */ upArrowButtonStyles?: Partial<IButtonStyles>; /** * Custom styles for the down arrow button. * * Note: The buttons are in a checked state when arrow keys are used to increment/decrement * the SpinButton. Use `rootChecked` instead of `rootPressed` for styling when that is the case. */ downArrowButtonStyles?: Partial<IButtonStyles>; /** * Theme provided by HOC. */ theme?: ITheme; /** * Accessible label text for the increment button (for screen reader users). */ incrementButtonAriaLabel?: string; /** * Accessible label text for the decrement button (for screen reader users). */ decrementButtonAriaLabel?: string; /** * How many decimal places the value should be rounded to. * * The default is calculated based on the precision of `step`: i.e. if step = 1, precision = 0. * step = 0.0089, precision = 4. step = 300, precision = 2. step = 23.00, precision = 2. */ precision?: number; /** * The position in the parent set (if in a set). */ ariaPositionInSet?: number; /** * The total size of the parent set (if in a set). */ ariaSetSize?: number; /** * Sets the control's aria-valuenow. This is the numeric form of `value`. * Providing this only makes sense when using as a controlled component. */ ariaValueNow?: number; /* * Sets the control's aria-valuetext. * Providing this only makes sense when using as a controlled component. */ ariaValueText?: string; /** * Keytip for the control. */ keytipProps?: IKeytipProps; /** * Additional props for the input field. */ inputProps?: React.InputHTMLAttributes<HTMLElement | HTMLInputElement>; /** * Additional props for the up and down arrow buttons. */ iconButtonProps?: IButtonProps; } /** * {@docCategory SpinButton} */ export interface ISpinButtonStyles extends IShadowDomStyle { /** * Styles for the root of the component. */ root: IStyle; /** * Style for the label wrapper element, which contains the icon and label. */ labelWrapper: IStyle; /** * Style for the icon. */ icon: IStyle; /** * Style for the label text. */ label: IStyle; /** * Style for the wrapper element of the input field and arrow buttons. */ spinButtonWrapper: IStyle; /** * Styles for the input. */ input: IStyle; /** * Styles for the arrowButtonsContainer */ arrowButtonsContainer: IStyle; } /** * {@docCategory SpinButton} */ export interface ISpinButtonStyleProps { theme: ITheme; className: string | undefined; disabled: boolean; isFocused: boolean; keyboardSpinDirection: KeyboardSpinDirection; labelPosition: Position; } ```
/content/code_sandbox/packages/react/src/components/SpinButton/SpinButton.types.ts
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
2,046
```xml import * as React from 'react'; import createSvgIcon from '../utils/createSvgIcon'; const Link12Icon = createSvgIcon({ svg: ({ classes }) => ( <svg xmlns="path_to_url" viewBox="0 0 2048 2048" className={classes.svg} focusable="false"> <path d="M1707 715q76 27 139 75t108 111 69 138 25 156q0 106-40 199t-110 162-163 110-199 41h-512q-106 0-199-40t-162-110-110-163-41-199q0-106 40-199t110-162 163-110 199-41h171q0 35-13 66t-37 54-55 36-66 14q-71 0-133 27t-108 73-73 109-27 133q0 71 27 133t73 108 108 73 133 27h512q70 0 132-27t109-73 73-108 27-133q0-92-46-168t-124-123V715zM171 683q0 91 46 167t124 124v189q-76-27-139-75T94 977 25 839 0 683q0-106 40-199t110-162 163-110 199-41h512q106 0 199 40t162 110 110 163 41 199q0 106-40 199t-110 162-163 110-199 41H853q0-35 13-66t37-54 54-37 67-14q70 0 132-27t109-73 73-108 27-133q0-70-26-132t-73-109-109-74-133-27H512q-71 0-133 27t-108 73-73 109-27 133z" /> </svg> ), displayName: 'Link12Icon', }); export default Link12Icon; ```
/content/code_sandbox/packages/react-icons-mdl2/src/components/Link12Icon.tsx
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
479
```xml /* eslint-disable @typescript-eslint/no-unused-vars */ import { combineReducers, reduceReducers, Loop, LoopReducer, LoopReducerWithDefinedState, getModel, getCmd, CmdType, } from '../../index'; import { Action } from 'redux'; type ReducedState = { add: number; mult: number; }; const initialState: ReducedState = { add: 0, mult: 2, }; type AddAction = Action<'add'> & { value: number; }; type MultiplyAction = Action<'multiply'> & { value: number; }; const addReducer: LoopReducer<ReducedState, AddAction> = ( state = initialState, action ) => { if (action.type === 'add') { return { ...state, add: state.add + action.value }; } return state; }; const multReducer: LoopReducerWithDefinedState<ReducedState, MultiplyAction> = ( state, action ) => { if (action.type === 'multiply') { return { ...state, mult: state.mult * action.value }; } return state; }; const add = (value: number): AddAction => ({ type: 'add', value, }); const multiply = (value: number): MultiplyAction => ({ type: 'multiply', value, }); const reducer = reduceReducers(addReducer, multReducer); const result1: Loop<ReducedState> = reducer(undefined, add(5)); const result2: Loop<ReducedState> = reducer(initialState, multiply(5)); const newState: ReducedState = getModel(result2); const cmd: CmdType | null = getCmd(result2); ```
/content/code_sandbox/test/typescript/reduce-reducers.ts
xml
2016-01-05T20:46:03
2024-08-02T02:20:10
redux-loop
redux-loop/redux-loop
1,960
358
```xml // See LICENSE.txt for license information. import React from 'react'; import {StyleSheet} from 'react-native'; import Tag, {BotTag, GuestTag} from '@components/tag'; import {t} from '@i18n'; type HeaderTagProps = { isAutomation?: boolean; isAutoResponder?: boolean; showGuestTag?: boolean; } const style = StyleSheet.create({ tag: { marginLeft: 0, marginRight: 5, marginBottom: 5, }, }); const HeaderTag = ({ isAutomation, isAutoResponder, showGuestTag, }: HeaderTagProps) => { if (isAutomation) { return ( <BotTag style={style.tag} testID='post_header.bot.tag' /> ); } else if (showGuestTag) { return ( <GuestTag style={style.tag} testID='post_header.guest.tag' /> ); } else if (isAutoResponder) { return ( <Tag id={t('post_info.auto_responder')} defaultMessage={'Automatic Reply'} style={style.tag} testID='post_header.auto_responder.tag' /> ); } return null; }; export default HeaderTag; ```
/content/code_sandbox/app/components/post_list/post/header/tag/index.tsx
xml
2016-10-07T16:52:32
2024-08-16T12:08:38
mattermost-mobile
mattermost/mattermost-mobile
2,155
270
```xml import React from 'react'; import { Dropdown } from '../..'; export default { title: 'Components/Dropdown' }; export const Search = () => <Dropdown search selection options={[{ text: 'abc', value: 'abc' }, { text: 'qwe', value: 'qwe' }, { text: 'zxc', value: 'zxc' }]} defaultValue='default' />; ```
/content/code_sandbox/packages/ui/stories/components/dropdown.stories.tsx
xml
2016-09-22T22:58:21
2024-08-16T15:47:39
nuclear
nukeop/nuclear
11,862
102
```xml import {Buffer} from '@luma.gl/core'; import type {AnimationProps} from '@luma.gl/engine'; import { Model, CubeGeometry, AnimationLoopTemplate, loadImageBitmap, AsyncTexture } from '@luma.gl/engine'; import {Matrix4} from '@math.gl/core'; export const title = 'Rotating Cube'; export const description = 'Shows rendering a basic triangle.'; const TEXTURE_URL = 'path_to_url const SHADER_WGSL = /* WGSL */ ` struct Uniforms { modelViewProjectionMatrix : mat4x4<f32>, }; @binding(0) @ group(0) var<uniform> app : Uniforms; struct VertexOutput { @builtin(position) Position : vec4<f32>, @location(0) fragUV : vec2<f32>, @location(1) fragPosition: vec4<f32>, }; @vertex fn vertedMain( @location(0) positions : vec4<f32>, @location(1) texCoords : vec2<f32>) -> VertexOutput { var output : VertexOutput; output.Position = app.modelViewProjectionMatrix * positions; output.fragUV = texCoords; output.fragPosition = 0.5 * (positions + vec4<f32>(1.0, 1.0, 1.0, 1.0)); return output; } @group(0) @binding(1) var uSampler: sampler; @group(0) @binding(2) var uTexture: texture_2d<f32>; @fragment fn fragmentMain(@location(0) fragUV: vec2<f32>, @location(1) fragPosition: vec4<f32>) -> @location(0) vec4<f32> { let flippedUV = vec2<f32>(1.0 - fragUV.x, fragUV.y); return textureSample(uTexture, uSampler, flippedUV) * fragPosition; } `; // GLSL const VS_GLSL = /* glsl */ `\ #version 300 es #define SHADER_NAME cube-vs uniform appUniforms { mat4 modelViewProjectionMatrix; } app; // CUBE GEOMETRY layout(location=0) in vec3 positions; layout(location=1) in vec2 texCoords; out vec2 fragUV; out vec4 fragPosition; void main() { gl_Position = app.modelViewProjectionMatrix * vec4(positions, 1.0); fragUV = texCoords; fragPosition = vec4(positions, 1.); // fragPosition = 0.5 * (vec4(position, 1.) + vec4(1., 1., 1., 1.)); } `; const FS_GLSL = /* glsl */ `\ #version 300 es #define SHADER_NAME cube-fs precision highp float; uniform sampler2D uTexture; in vec2 fragUV; in vec4 fragPosition; layout (location=0) out vec4 fragColor; void main() { fragColor = texture(uTexture, vec2(fragUV.x, 1.0 - fragUV.y));; } `; const UNIFORM_BUFFER_SIZE = 4 * 16; // 4x4 matrix export default class AppAnimationLoopTemplate extends AnimationLoopTemplate { model: Model; uniformBuffer: Buffer; constructor({device}: AnimationProps) { super(); // Fetch the image and upload it into a GPUTexture. const texture = new AsyncTexture(device, { data: loadImageBitmap(TEXTURE_URL), // usage: Texture.TEXTURE | Texture.COPY_DST | Texture.RENDER_ATTACHMENT, mipmaps: true, // Create mipmaps sampler: { // linear filtering for smooth interpolation. magFilter: 'linear', minFilter: 'linear', addressModeU: 'clamp-to-edge', addressModeV: 'clamp-to-edge' } }); this.uniformBuffer = device.createBuffer({ id: 'uniforms', byteLength: UNIFORM_BUFFER_SIZE, usage: Buffer.UNIFORM | Buffer.COPY_DST }); this.model = new Model(device, { id: 'cube', source: SHADER_WGSL, vs: VS_GLSL, fs: FS_GLSL, geometry: new CubeGeometry({indices: false}), bindings: { app: this.uniformBuffer, uSampler: texture.sampler, uTexture: texture }, parameters: { depthWriteEnabled: true, // Fragment closest to the camera is rendered in front. depthCompare: 'less' // depthFormat: 'depth24plus', // cullMode: 'back' // Faces pointing away will be occluded by faces pointing toward the camera. } }); } onFinalize() { this.model.destroy(); this.uniformBuffer.destroy(); } onRender({device}: AnimationProps) { const projectionMatrix = new Matrix4(); const viewMatrix = new Matrix4(); const modelViewProjectionMatrix = new Matrix4(); const aspect = device.canvasContext?.getAspect(); const now = Date.now() / 1000; viewMatrix .identity() .translate([0, 0, -4]) .rotateAxis(1, [Math.sin(now), Math.cos(now), 0]); projectionMatrix.perspective({fovy: (2 * Math.PI) / 5, aspect, near: 1, far: 100.0}); modelViewProjectionMatrix.copy(viewMatrix).multiplyLeft(projectionMatrix); this.uniformBuffer.write(new Float32Array(modelViewProjectionMatrix)); const renderPass = device.beginRenderPass({clearColor: [0, 0, 0, 1]}); this.model.draw(renderPass); renderPass.end(); } } ```
/content/code_sandbox/wip/examples-wip/webgpu/textured-cube/app.ts
xml
2016-01-25T09:41:59
2024-08-16T10:03:05
luma.gl
visgl/luma.gl
2,280
1,254
```xml import { useCallback, useEffect } from 'react'; import { createSelector } from '@reduxjs/toolkit'; import type { WasmApiExchangeRate, WasmFiatCurrencySymbol } from '@proton/andromeda'; import { baseUseSelector } from '@proton/react-redux-store'; import { createHooks } from '@proton/redux-utilities'; import { exchangeRateThunk, selectExchangeRate } from '../slices'; import { getKeyAndTs } from '../slices/exchangeRate'; export const exchangeRateHooks = createHooks(exchangeRateThunk, selectExchangeRate); export const useGetExchangeRate = () => { const get = exchangeRateHooks.useGet(); return useCallback( async (fiat: WasmFiatCurrencySymbol, date?: Date) => { const results = await get({ thunkArg: [fiat, date] }); const [key] = getKeyAndTs(fiat, date); return results[key]; }, [get] ); }; export const useExchangeRate = (fiat: WasmFiatCurrencySymbol) => { const getExchangeRate = useGetExchangeRate(); const [, loading] = exchangeRateHooks.useValue(); const exchangeRateSimpleSelector = createSelector( selectExchangeRate, (result): [WasmApiExchangeRate | undefined, boolean] => { const { value } = result; const rate = value?.[fiat]; return [rate, loading]; } ); useEffect(() => { void getExchangeRate(fiat); }, [fiat, getExchangeRate]); return baseUseSelector(exchangeRateSimpleSelector); }; ```
/content/code_sandbox/applications/wallet/src/app/store/hooks/useExchangeRate.ts
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
346
```xml import { Polygon } from "../shapes/Polygon.js"; import { attrAutoFillSvg, attrFill, attrPolyPoints, attrScale, attrStroke, attrTitle, } from "./AttrHelper.js"; import { RenderProps } from "./Renderer.js"; const RenderPolygon = ( shape: Polygon<number>, { canvasSize, titleCache }: RenderProps, ): SVGPolygonElement => { const elem = document.createElementNS( "path_to_url", "polygon", ); // Keep track of which input properties we programatically mapped const attrToNotAutoMap: string[] = []; // Map/Fill the shape attributes while keeping track of input properties mapped attrToNotAutoMap.push(...attrFill(shape, elem)); attrToNotAutoMap.push(...attrStroke(shape, elem)); attrToNotAutoMap.push(...attrTitle(shape, elem, titleCache)); attrToNotAutoMap.push(...attrScale(shape, elem)); attrToNotAutoMap.push(...attrPolyPoints(shape, canvasSize, elem)); // Directly Map across any "unknown" SVG properties attrAutoFillSvg(shape, elem, attrToNotAutoMap); return elem; }; export default RenderPolygon; ```
/content/code_sandbox/packages/core/src/renderer/Polygon.ts
xml
2016-09-22T04:47:19
2024-08-16T13:00:54
penrose
penrose/penrose
6,760
263
```xml /* * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. */ import {makeAutoObservable} from 'mobx'; import {getStateLocally, storeStateLocally} from 'modules/utils/localStorage'; type OperationsPanelRef = React.RefObject<HTMLElement> | null; type State = { isFiltersCollapsed: boolean; isOperationsCollapsed: boolean; operationsPanelRef: OperationsPanelRef; }; const DEFAULT_STATE: State = { isFiltersCollapsed: false, isOperationsCollapsed: true, operationsPanelRef: null, }; class PanelStates { state: State = {...DEFAULT_STATE}; constructor() { const {isFiltersCollapsed = false, isOperationsCollapsed = true} = getStateLocally('panelStates'); this.state.isFiltersCollapsed = isFiltersCollapsed; this.state.isOperationsCollapsed = isOperationsCollapsed; makeAutoObservable(this); } setOperationsPanelRef = (ref: OperationsPanelRef) => { this.state.operationsPanelRef = ref; }; toggleFiltersPanel = () => { storeStateLocally( { isFiltersCollapsed: !this.state.isFiltersCollapsed, }, 'panelStates', ); this.state.isFiltersCollapsed = !this.state.isFiltersCollapsed; }; toggleOperationsPanel = () => { storeStateLocally( { isOperationsCollapsed: !this.state.isOperationsCollapsed, }, 'panelStates', ); this.state.isOperationsCollapsed = !this.state.isOperationsCollapsed; }; expandFiltersPanel = () => { storeStateLocally({isFiltersCollapsed: false}, 'panelStates'); this.state.isFiltersCollapsed = false; }; expandOperationsPanel = () => { storeStateLocally({isOperationsCollapsed: false}, 'panelStates'); this.state.isOperationsCollapsed = false; }; reset = () => { this.state = {...DEFAULT_STATE}; }; } export const panelStatesStore = new PanelStates(); ```
/content/code_sandbox/operate/client/src/modules/stores/panelStates.ts
xml
2016-03-20T03:38:04
2024-08-16T19:59:58
camunda
camunda/camunda
3,172
427
```xml import { HttpResponse } from '@standardnotes/responses' import { ListAuthenticatorsRequestParams, DeleteAuthenticatorRequestParams, VerifyAuthenticatorRegistrationResponseRequestParams, GenerateAuthenticatorAuthenticationOptionsRequestParams, } from '../../Request' import { ListAuthenticatorsResponseBody, DeleteAuthenticatorResponseBody, GenerateAuthenticatorRegistrationOptionsResponseBody, VerifyAuthenticatorRegistrationResponseBody, GenerateAuthenticatorAuthenticationOptionsResponseBody, } from '../../Response' export interface AuthenticatorServerInterface { list(params: ListAuthenticatorsRequestParams): Promise<HttpResponse<ListAuthenticatorsResponseBody>> delete(params: DeleteAuthenticatorRequestParams): Promise<HttpResponse<DeleteAuthenticatorResponseBody>> generateRegistrationOptions(): Promise<HttpResponse<GenerateAuthenticatorRegistrationOptionsResponseBody>> verifyRegistrationResponse( params: VerifyAuthenticatorRegistrationResponseRequestParams, ): Promise<HttpResponse<VerifyAuthenticatorRegistrationResponseBody>> generateAuthenticationOptions( params: GenerateAuthenticatorAuthenticationOptionsRequestParams, ): Promise<HttpResponse<GenerateAuthenticatorAuthenticationOptionsResponseBody>> } ```
/content/code_sandbox/packages/api/src/Domain/Server/Authenticator/AuthenticatorServerInterface.ts
xml
2016-12-05T23:31:33
2024-08-16T06:51:19
app
standardnotes/app
5,180
215
```xml // SHE library // // This file is released under the terms of the MIT license. // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <Cocoa/Cocoa.h> #include "she/osx/app.h" #include "base/thread.h" #include "she/osx/app_delegate.h" extern int app_main(int argc, char* argv[]); namespace she { class OSXApp::Impl { public: bool init() { m_app = [NSApplication sharedApplication]; m_appDelegate = [OSXAppDelegate new]; [m_app setActivationPolicy:NSApplicationActivationPolicyRegular]; [m_app setDelegate:m_appDelegate]; // Don't activate the application ignoring other apps. This is // called by OS X when the application is launched by the user // from the application bundle. In this way, we can execute // aseprite from the command line/bash scripts and the app will // not be activated. //[m_app activateIgnoringOtherApps:YES]; return true; } // We might need to call this function when the app is launched from // Steam. It appears that there is a bug on OS X Steam client where // the app is launched, activated, and then the Steam client is // activated again. void activateApp() { [m_app activateIgnoringOtherApps:YES]; } void finishLaunching() { [m_app finishLaunching]; } private: NSApplication* m_app; OSXAppDelegate* m_appDelegate; }; static OSXApp* g_instance = nullptr; // static OSXApp* OSXApp::instance() { return g_instance; } OSXApp::OSXApp() : m_impl(new Impl) { ASSERT(!g_instance); g_instance = this; } OSXApp::~OSXApp() { ASSERT(g_instance == this); g_instance = nullptr; } bool OSXApp::init() { return m_impl->init(); } void OSXApp::activateApp() { m_impl->activateApp(); } void OSXApp::finishLaunching() { m_impl->finishLaunching(); } } // namespace she ```
/content/code_sandbox/src/she/osx/app.mm
xml
2016-08-31T17:26:42
2024-08-16T11:45:24
LibreSprite
LibreSprite/LibreSprite
4,717
461
```xml import { Alert, confirm } from "@erxes/ui/src/utils"; import { BarItems, DataWithLoader, Pagination, Table, Wrapper, __, } from "@erxes/ui/src"; import Button from "@erxes/ui/src/components/Button"; import CheckSyncedOrdersSidebar from "./CheckSyncedOrdersSidebar"; import FormControl from "@erxes/ui/src/components/form/Control"; import React from "react"; import Row from "./CheckSyncedOrdersRow"; import { Title } from "@erxes/ui-settings/src/styles"; import { menuDynamic } from "../../constants"; type Props = { totalCount: number; loading: boolean; orders: any[]; queryParams: any; isAllSelected: boolean; bulk: any[]; emptyBulk: () => void; checkSynced: ( doc: { orderIds: string[] }, emptyBulk: () => void ) => Promise<any>; toggleBulk: () => void; toggleAll: (targets: any[], containerId: string) => void; unSyncedOrderIds: string[]; syncedOrderInfos: any; toSyncMsdOrders: (orderIds: string[]) => void; toSendMsdOrders: (orderIds: string[]) => void; }; class CheckSyncedOrders extends React.Component<Props> { constructor(props: Props) { super(props); } renderRow = () => { const { orders, toggleBulk, bulk, unSyncedOrderIds, toSyncMsdOrders, toSendMsdOrders, syncedOrderInfos, } = this.props; return orders?.map((order) => ( <Row key={order._id} order={order} toggleBulk={toggleBulk} isChecked={bulk.includes(order)} isUnsynced={unSyncedOrderIds.includes(order._id)} toSync={toSyncMsdOrders} toSend={toSendMsdOrders} syncedInfo={syncedOrderInfos[order._id] || {}} /> )); }; onChange = () => { const { toggleAll, orders } = this.props; toggleAll(orders, "orders"); }; checkSynced = async (_orders: any) => { const orderIds: string[] = []; _orders.forEach((order) => { orderIds.push(order._id); }); await this.props.checkSynced({ orderIds }, this.props.emptyBulk); }; render() { const { totalCount, queryParams, isAllSelected, bulk, loading, unSyncedOrderIds, toSyncMsdOrders, syncedOrderInfos, } = this.props; const tablehead = [ "Number", "Total Amount", "Created At", "Paid At", "Synced Date", "Synced bill Number", "Synced customer", "Sync Actions", ]; const Content = ( <Table $bordered={true}> <thead> <tr> <th style={{ width: 60 }}> <FormControl checked={isAllSelected} componentclass="checkbox" onChange={this.onChange} /> </th> {tablehead?.map((p) => <th key={p}>{p || ""}</th>)} </tr> </thead> <tbody>{this.renderRow()}</tbody> </Table> ); const sidebar = <CheckSyncedOrdersSidebar queryParams={queryParams} />; const onClickCheck = () => { confirm() .then(async () => { this.setState({ contentLoading: true }); await this.checkSynced(bulk); this.setState({ contentLoading: false }); }) .catch((error) => { Alert.error(error.message); this.setState({ contentLoading: false }); }); }; const onClickSync = () => confirm() .then(() => { toSyncMsdOrders(unSyncedOrderIds); }) .catch((error) => { Alert.error(error.message); }); const actionBarRight = ( <BarItems> {bulk.length > 0 && ( <Button btnStyle="success" icon="check-circle" onClick={onClickCheck}> Check </Button> )} {unSyncedOrderIds.length > 0 && ( <Button btnStyle="warning" size="small" icon="sync" onClick={onClickSync} > {`Sync all (${unSyncedOrderIds.length})`} </Button> )} </BarItems> ); const content = ( <DataWithLoader data={Content} loading={loading} count={totalCount} emptyText="Empty list" emptyImage="/images/actions/1.svg" /> ); return ( <Wrapper header={ <Wrapper.Header title={__(`Check erkhet`)} queryParams={queryParams} submenu={menuDynamic} /> } leftSidebar={sidebar} actionBar={ <Wrapper.ActionBar left={<Title>{__(`Orders (${totalCount})`)}</Title>} right={actionBarRight} background="colorWhite" wideSpacing={true} /> } content={content} footer={<Pagination count={totalCount} />} hasBorder={true} transparent={true} /> ); } } export default CheckSyncedOrders; ```
/content/code_sandbox/packages/plugin-msdynamic-ui/src/components/syncedOrders/CheckSyncedOrders.tsx
xml
2016-11-11T06:54:50
2024-08-16T10:26:06
erxes
erxes/erxes
3,479
1,169
```xml import * as React from "react"; import styled from "styled-components"; import Frame from "../components/Frame"; import { EmbedProps as Props } from "."; function Spotify({ matches, ...props }: Props) { let pathname = ""; try { const parsed = new URL(props.attrs.href); pathname = parsed.pathname; } catch (err) { pathname = ""; } const normalizedPath = pathname.replace(/^\/embed/, "/"); let height; if (normalizedPath.includes("episode") || normalizedPath.includes("show")) { height = 232; } else if (normalizedPath.includes("track")) { height = 80; } else { height = 380; } return ( <SpotifyFrame {...props} width="100%" height={`${height}px`} src={`path_to_url{normalizedPath}`} title="Spotify Embed" allow="encrypted-media" /> ); } const SpotifyFrame = styled(Frame)` border-radius: 13px; `; export default Spotify; ```
/content/code_sandbox/shared/editor/embeds/Spotify.tsx
xml
2016-05-22T21:31:47
2024-08-16T19:57:22
outline
outline/outline
26,751
223
```xml <?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="path_to_url"> <ItemGroup Label="ProjectConfigurations"> <ProjectConfiguration Include="Debug|Win32"> <Configuration>Debug</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|Win32"> <Configuration>Release</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> </ItemGroup> <PropertyGroup Label="Globals"> <ProjectGuid>{BD075706-11E9-403B-A2E3-A5E1397E53EF}</ProjectGuid> <Keyword>Win32Proj</Keyword> <RootNamespace>PersistentConnectionSample</RootNamespace> <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\</SolutionDir> <DownloadNuGetExe Condition=" '$(DownloadNuGetExe)' == '' ">true</DownloadNuGetExe> <RestorePackages>true</RestorePackages> <WindowsTargetPlatformVersion>10.0.16299.0</WindowsTargetPlatformVersion> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <PlatformToolset>v141</PlatformToolset> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v141</PlatformToolset> <WholeProgramOptimization>true</WholeProgramOptimization> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <ImportGroup Label="ExtensionSettings"> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <LinkIncremental>true</LinkIncremental> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <LinkIncremental>false</LinkIncremental> </PropertyGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ClCompile> <PrecompiledHeader>Use</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <Optimization>Disabled</Optimization> <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions> <SDLCheck>true</SDLCheck> </ClCompile> <Link> <SubSystem>Console</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ClCompile> <WarningLevel>Level3</WarningLevel> <PrecompiledHeader>Use</PrecompiledHeader> <Optimization>MaxSpeed</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions> <SDLCheck>true</SDLCheck> </ClCompile> <Link> <SubSystem>Console</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> </Link> </ItemDefinitionGroup> <ItemGroup> <ClInclude Include="stdafx.h" /> </ItemGroup> <ItemGroup> <ClCompile Include="PersistentConnectionSample.cpp" /> <ClCompile Include="stdafx.cpp"> <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader> <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader> </ClCompile> </ItemGroup> <ItemGroup> <None Include="packages.config" /> </ItemGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <ImportGroup Label="ExtensionTargets"> <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" /> <Import Project="..\..\packages\cpprestsdk.v140.windesktop.msvcstl.dyn.rt-dyn.2.7.0\build\native\cpprestsdk.v140.windesktop.msvcstl.dyn.rt-dyn.targets" Condition="Exists('..\..\packages\cpprestsdk.v140.windesktop.msvcstl.dyn.rt-dyn.2.7.0\build\native\cpprestsdk.v140.windesktop.msvcstl.dyn.rt-dyn.targets')" /> <Import Project="..\..\packages\Microsoft.AspNet.SignalR.Client.Cpp.v140.WinDesktop.1.0.0-beta1\build\native\Microsoft.AspNet.SignalR.Client.Cpp.v140.WinDesktop.targets" Condition="Exists('..\..\packages\Microsoft.AspNet.SignalR.Client.Cpp.v140.WinDesktop.1.0.0-beta1\build\native\Microsoft.AspNet.SignalR.Client.Cpp.v140.WinDesktop.targets')" /> </ImportGroup> <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild"> <PropertyGroup> <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see path_to_url The missing file is {0}.</ErrorText> </PropertyGroup> <Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" /> <Error Condition="!Exists('..\..\packages\cpprestsdk.v140.windesktop.msvcstl.dyn.rt-dyn.2.7.0\build\native\cpprestsdk.v140.windesktop.msvcstl.dyn.rt-dyn.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\cpprestsdk.v140.windesktop.msvcstl.dyn.rt-dyn.2.7.0\build\native\cpprestsdk.v140.windesktop.msvcstl.dyn.rt-dyn.targets'))" /> <Error Condition="!Exists('..\..\packages\Microsoft.AspNet.SignalR.Client.Cpp.v140.WinDesktop.1.0.0-beta1\build\native\Microsoft.AspNet.SignalR.Client.Cpp.v140.WinDesktop.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\Microsoft.AspNet.SignalR.Client.Cpp.v140.WinDesktop.1.0.0-beta1\build\native\Microsoft.AspNet.SignalR.Client.Cpp.v140.WinDesktop.targets'))" /> </Target> </Project> ```
/content/code_sandbox/clients/cpp/samples/PersistentConnectionSample/PersistentConnectionSample.vcxproj
xml
2016-10-17T16:39:15
2024-08-15T16:33:14
SignalR
aspnet/SignalR
2,383
1,773
```xml /** * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { type PropsWithChildren } from 'react'; /** * Root style-reset for full-screen React Native web apps with a root `<ScrollView />` should use the following styles to ensure native parity. [Learn more](path_to_url#root-element). */ export function ScrollViewStyleReset() { return ( <style id="expo-reset" dangerouslySetInnerHTML={{ __html: `#root,body,html{height:100%}body{overflow:hidden}#root{display:flex}`, }} /> ); } export function Html({ children }: PropsWithChildren) { return ( <html lang="en"> <head> <meta charSet="utf-8" /> <meta httpEquiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <ScrollViewStyleReset /> </head> <body>{children}</body> </html> ); } ```
/content/code_sandbox/packages/expo-router/src/static/html.tsx
xml
2016-08-15T17:14:25
2024-08-16T19:54:44
expo
expo/expo
32,004
245
```xml import ServerModule from '@gqlapp/module-server-ts'; import Report from '../sql'; import schema from './schema.graphql'; import resolvers from './resolvers'; import resources from './locales'; export default new ServerModule({ schema: [schema], createResolversFunc: [resolvers], createContextFunc: [() => ({ Report: new Report() })], localization: [{ ns: 'PdfReport', resources }], }); ```
/content/code_sandbox/modules/reports/server-ts/pdf/index.ts
xml
2016-09-08T16:44:45
2024-08-16T06:17:16
apollo-universal-starter-kit
sysgears/apollo-universal-starter-kit
1,684
91
```xml import { Component, OnInit } from '@angular/core'; import { AngularFirestore, DocumentChangeAction } from '@angular/fire/compat/firestore'; import { Observable } from 'rxjs'; @Component({ selector: 'app-protected-lazy', templateUrl: './protected-lazy.component.html', styleUrls: ['./protected-lazy.component.css'] }) export class ProtectedLazyComponent implements OnInit { public snapshot: Observable<DocumentChangeAction<unknown>[]>; constructor(private afs: AngularFirestore) { this.snapshot = afs.collection('test').snapshotChanges(); } ngOnInit(): void { } } ```
/content/code_sandbox/samples/compat/src/app/protected-lazy/protected-lazy.component.ts
xml
2016-01-11T20:47:23
2024-08-14T12:09:31
angularfire
angular/angularfire
7,648
122
```xml /* * Wire * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see path_to_url * */ import switchPath from 'switch-path'; export type Routes = Record<string, ((x: any) => void) | null>; const defaultRoute: Routes = { // do nothing if url was not matched '*': null, }; let routes: Routes = {}; function parseRoute() { const currentPath = window.location.hash.replace('#', '') || '/'; const {value} = switchPath(currentPath, routes); return typeof value === 'function' ? value() : value; } export const configureRoutes = (routeDefinitions: Routes): void => { routes = {...defaultRoute, ...routeDefinitions}; window.addEventListener('hashchange', parseRoute); parseRoute(); }; export const navigate = (path: string, stateObj?: {}) => { setHistoryParam(path, stateObj); parseRoute(); }; export const setHistoryParam = (path: string, stateObj: {} = window.history.state) => { window.history.replaceState(stateObj, '', `#${path}`); }; ```
/content/code_sandbox/src/script/router/Router.ts
xml
2016-07-21T15:34:05
2024-08-16T11:40:13
wire-webapp
wireapp/wire-webapp
1,125
296
```xml <?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="path_to_url"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">iPhoneSimulator</Platform> <ProjectTypeGuids>{EE2C853D-36AF-4FDB-B1AD-8E90477E2198};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> <ProjectGuid>{20D55DE9-D8AF-4963-B2B4-D7E8A91FCA9C}</ProjectGuid> <OutputType>Library</OutputType> <RootNamespace>MyKeyboardExtension</RootNamespace> <IPhoneResourcePrefix>Resources</IPhoneResourcePrefix> <AssemblyName>MyKeyboardExtension</AssemblyName> <LangVersion>latest</LangVersion> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|iPhoneSimulator' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\iPhoneSimulator\Debug</OutputPath> <DefineConstants>DEBUG;</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <MtouchArch>x86_64</MtouchArch> <MtouchLink>None</MtouchLink> <MtouchDebug>true</MtouchDebug> <MtouchProfiling>true</MtouchProfiling> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|iPhoneSimulator' "> <DebugType>full</DebugType> <Optimize>true</Optimize> <OutputPath>bin\iPhoneSimulator\Release</OutputPath> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <MtouchArch>x86_64</MtouchArch> <MtouchLink>None</MtouchLink> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|iPhone' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\iPhone\Debug</OutputPath> <DefineConstants>DEBUG;</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <MtouchArch>ARM64</MtouchArch> <CodesignEntitlements>Entitlements.plist</CodesignEntitlements> <MtouchProfiling>true</MtouchProfiling> <CodesignKey>iPhone Developer</CodesignKey> <MtouchDebug>true</MtouchDebug> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|iPhone' "> <DebugType>full</DebugType> <Optimize>true</Optimize> <OutputPath>bin\iPhone\Release</OutputPath> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <CodesignEntitlements>Entitlements.plist</CodesignEntitlements> <MtouchArch>ARM64</MtouchArch> <CodesignKey>iPhone Developer</CodesignKey> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Xml" /> <Reference Include="System.Core" /> <Reference Include="Xamarin.iOS" /> </ItemGroup> <ItemGroup> <Folder Include="Resources\" /> </ItemGroup> <ItemGroup> <None Include="Info.plist" /> <None Include="Entitlements.plist" /> </ItemGroup> <ItemGroup> <Compile Include="KeyboardViewController.cs" /> <Compile Include="KeyboardViewController.designer.cs"> <DependentUpon>KeyboardViewController.cs</DependentUpon> </Compile> </ItemGroup> <Import Project="$(MSBuildExtensionsPath)\Xamarin\iOS\Xamarin.iOS.AppExtension.CSharp.targets" /> </Project> ```
/content/code_sandbox/tests/common/TestProjects/MyKeyboardExtension/MyKeyboardExtension.csproj
xml
2016-04-20T18:24:26
2024-08-16T13:29:19
xamarin-macios
xamarin/xamarin-macios
2,436
947