text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import React, { useMemo } from 'react';
import { Checkbox, Tooltip } from 'antd';
import { useTable } from 'react-table';
import refractor, { RefractorNode, AST } from 'refractor';
/** @jsx jsx */
import { css, jsx } from '@emotion/core';
import createElement from './create-element';
const codeDeletionStyle = css`
background-color: #3e3133;
`;
const codeAdditionStyle = css`
background-color: rgb(53, 59, 69);
`;
const lineNumberCellStyle = css`
width: 52px;
font-family: dm, Menlo, Monaco, 'Courier New', monospace;
font-weight: normal;
font-size: 12px;
letter-spacing: 0px;
color: #858585;
margin-right: 16px;
width: 32px;
margin-left: 4px;
display: inline-block;
text-align: right;
`;
const diffCodeCellStyle = (
isHidden: boolean,
isCodeAddition: boolean,
isCodeDeletion: boolean,
) => css`
white-space: pre;
padding-right: 32px;
width: auto;
display: inline-block;
opacity: ${isHidden || isCodeDeletion ? 0.3 : 1};
font-size: 14px;
font-weight: ${isCodeAddition ? 700 : 'normal'};
`;
const newLineRegex = /\n/g;
function getNewLines(str: string) {
return str.match(newLineRegex);
}
function getLineNumbers(props: {
code: string;
startingLineNumber: number;
style?: Function | { [attr: string]: any };
}) {
const { code, startingLineNumber = 0, style = {} } = props;
return code
.replace(/\n$/, '')
.split('\n')
.map((_, i) => {
const number = i + startingLineNumber;
return (
<span
key={`line-${i}`}
className="react-syntax-highlighter-line-number"
style={typeof style === 'function' ? style(number) : style}
>
{`${number}\n`}
</span>
);
});
}
function getLineChecker(props: {
lines: string[];
startingLineNumber?: number;
style?: Function | { [attr: string]: any };
lineProps?: LineProps;
}) {
const { lines, startingLineNumber = 0, style = {}, lineProps = {} } = props;
return lines.map((_, i) => {
const number = i + startingLineNumber;
const { isHidden = false } =
(typeof lineProps === 'function' ? lineProps(i) : lineProps) || {};
return (
<Tooltip placement="left" title={isHidden ? '显示此行' : '隐藏此行'}>
<span
key={`line-${i}`}
className="react-syntax-highlighter-line-number"
style={typeof style === 'function' ? style(number) : style}
css={css`
display: inline-block;
height: 22px;
`}
>
<Checkbox
value={i}
css={css`
padding-left: 12px;
`}
/>
</span>
</Tooltip>
);
});
}
function createLineElement(props: {
children: RefractorNode[];
className?: string[];
}): AST.Element {
const { children, className = [] } = props;
const properties: AST.Properties = {};
properties.className = properties.className
? className.concat(properties.className)
: className;
return {
type: 'element',
tagName: 'span',
properties,
children,
};
}
function flattenCodeTree(
tree: RefractorNode[],
className: string[] = [],
newTree: RefractorNode[] = [],
) {
for (let i = 0; i < tree.length; i++) {
const node = tree[i];
if (node.type === 'text') {
newTree.push(
createLineElement({
children: [node],
className,
}),
);
} else if (node.children) {
const classNames = className.concat(node.properties.className!);
newTree = newTree.concat(flattenCodeTree(node.children, classNames));
}
}
return newTree;
}
export function wrapLinesInSpan(
codeTree: RefractorNode[],
lineProps?: LineProps,
) {
const tree = flattenCodeTree(codeTree);
const newTree = [];
let lastLineBreakIndex = -1;
let index = 0;
while (index < tree.length) {
const node = tree[index] as AST.Element;
const value = (node.children[0] as AST.Text).value;
const newLines = getNewLines(value);
if (newLines) {
const splitValue = value.split('\n');
splitValue.forEach((text, i) => {
const newChild: AST.Text = { type: 'text', value: `${text}\n` };
if (i === 0) {
const children = tree.slice(lastLineBreakIndex + 1, index).concat(
createLineElement({
children: [newChild],
className: node.properties.className,
}),
);
newTree.push(createLineElement({ children }));
} else if (i === splitValue.length - 1) {
const stringChild = (tree[index + 1] as AST.Element)?.children[0];
if (stringChild) {
const lastLineInPreviousSpan: AST.Text = {
type: 'text',
value: `${text}`,
};
const newElem = createLineElement({
children: [lastLineInPreviousSpan],
className: node.properties.className,
});
tree.splice(index + 1, 0, newElem);
} else {
newTree.push(
createLineElement({
children: [newChild],
className: node.properties.className,
}),
);
}
} else {
newTree.push(
createLineElement({
children: [newChild],
className: node.properties.className,
}),
);
}
});
lastLineBreakIndex = index;
}
index++;
}
if (lastLineBreakIndex !== tree.length - 1) {
const children = tree.slice(lastLineBreakIndex + 1, tree.length);
if (children && children.length) {
newTree.push(createLineElement({ children }));
}
}
return newTree;
}
type RendererProps = {
rows: RefractorNode[];
stylesheet: { [attr: string]: any };
useInlineStyles: boolean;
};
function defaultRenderer(props: RendererProps) {
const { rows, stylesheet, useInlineStyles } = props;
return rows.map((node, i) =>
createElement({
node,
stylesheet,
useInlineStyles,
key: `code-segement${i}`,
}),
);
}
export function getCodeTree(code: string, language: string = 'text') {
const defaultCodeValue: AST.Text[] = [{ type: 'text', value: code }];
try {
return language && language !== 'text'
? refractor.highlight(code, language)
: defaultCodeValue;
} catch (e) {
return defaultCodeValue;
}
}
type LineTagPropsFunction = (lineNumber: number) => { [attr: string]: any };
type LineProps = LineTagPropsFunction | { [attr: string]: any };
export interface SyntaxHighlighterProps {
code: string;
language?: string;
style?: any;
astGenerator?: typeof refractor;
customStyle?: any;
wrapLines: boolean;
lineProps?: LineProps;
useInlineStyles?: boolean;
showLineNumbers?: boolean;
startingLineNumber?: number;
lineNumberStyle?: any;
renderer?: (props: RendererProps) => (string | JSX.Element)[];
[rest: string]: any;
}
export default function(
defaultAstGenerator: typeof refractor,
defaultStyle: any,
) {
return function SyntaxHighlighter({
code,
language,
style = defaultStyle,
customStyle = {},
useInlineStyles = true,
showLineNumbers = false,
showLineChecker = false,
startingLineNumber = 1,
lineNumberStyle,
wrapLines,
lineProps = {},
renderer = defaultRenderer,
astGenerator = defaultAstGenerator,
...rest
}: SyntaxHighlighterProps) {
const lineNumbers = showLineNumbers
? getLineNumbers({ code, startingLineNumber, style: lineNumberStyle })
: [];
const lineCheckers = showLineChecker
? getLineChecker({
lines: code.replace(/\n$/, '').split('\n'),
lineProps,
})
: [null];
const defaultPreStyle = style.hljs ||
style['pre[class*="language-"]'] || {
backgroundColor: '#fff',
};
const preProps = useInlineStyles
? Object.assign({}, rest, {
style: Object.assign({}, defaultPreStyle, customStyle),
})
: Object.assign({}, rest, { className: 'hljs' });
/*
* some custom renderers rely on individual row elements so we need to turn wrapLines on
* if renderer is provided and wrapLines is undefined
*/
wrapLines = renderer && wrapLines === undefined ? true : wrapLines;
const codeTree = getCodeTree(code, language);
const tree = wrapLines ? wrapLinesInSpan(codeTree, lineProps) : codeTree;
const renderCodeRows = renderer({
rows: tree,
stylesheet: { ...style, paddingRight: '32px' },
useInlineStyles,
});
const vanillaData = lineNumbers.map((lineNumber, index) => ({
lineNumber,
diffCodeRow: renderCodeRows[index],
lineChecker: lineCheckers[index],
}));
const columns = useMemo(
() => [
{
Header: 'diffBlock',
columns: [
{
Header: 'Diff 选中/可见',
accessor: 'lineChecker',
},
{
Header: '行号',
accessor: 'lineNumber',
},
{
Header: '代码块',
accessor: 'diffCodeRow',
},
],
},
],
[],
);
const data = useMemo(() => vanillaData, [vanillaData]);
const { getTableProps, getTableBodyProps, rows, prepareRow } = useTable({
columns,
data,
});
return (
<div>
<div
css={css`
overflow-x: auto;
padding-bottom: 16px;
`}
>
<table
{...preProps}
{...getTableProps()}
css={css`
width: 100%;
border-spacing: 0;
border-collapse: collapse;
& td {
padding: 0;
border: none;
}
font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo,
Courier, monospace;
`}
>
<tbody {...getTableBodyProps()}>
{rows.map((row, rowIndex) => {
const {
isCodeAddition = false,
isCodeDeletion = false,
isHidden = false,
} =
(typeof lineProps === 'function'
? lineProps(rowIndex)
: lineProps) || {};
const styleMap = [
{ width: '28px' },
lineNumberCellStyle,
diffCodeCellStyle(isHidden, isCodeAddition, isCodeDeletion),
];
prepareRow(row);
return (
<tr
{...row.getRowProps()}
css={css`
white-space: pre;
${isCodeAddition && codeAdditionStyle}
${isCodeDeletion && codeDeletionStyle}
`}
>
{row.cells.map((cell, cellIndex) => {
return (
<td {...cell.getCellProps()} css={styleMap[cellIndex]}>
{cell.render('Cell')}
</td>
);
})}
</tr>
);
})}
</tbody>
</table>
</div>
</div>
);
};
} | the_stack |
import { useApolloClient } from "@apollo/client";
import classNames from 'classnames';
import React, { useCallback, useEffect, useState } from 'react';
import { AnalyticsContext, useTracking } from "../../lib/analyticsEvents";
import { userHasNewTagSubscriptions } from "../../lib/betas";
import { subscriptionTypes } from '../../lib/collections/subscriptions/schema';
import { tagGetUrl } from '../../lib/collections/tags/helpers';
import { useMulti } from '../../lib/crud/withMulti';
import { truncate } from '../../lib/editor/ellipsize';
import { Link } from '../../lib/reactRouterWrapper';
import { useLocation } from '../../lib/routeUtil';
import { Components, registerComponent } from '../../lib/vulcan-lib';
import { useCurrentUser } from '../common/withUser';
import { MAX_COLUMN_WIDTH } from '../posts/PostsPage/PostsPage';
import { EditTagForm } from './EditTagPage';
import { useTagBySlug } from './useTag';
import { forumTypeSetting, taggingNameCapitalSetting } from '../../lib/instanceSettings';
const isEAForum = forumTypeSetting.get() === 'EAForum'
// Also used in TagCompareRevisions, TagDiscussionPage
export const styles = (theme: ThemeType): JssStyles => ({
rootGivenImage: {
marginTop: 185,
[theme.breakpoints.down('sm')]: {
marginTop: 130,
},
},
imageContainer: {
width: '100%',
'& > img': {
height: 300,
objectFit: 'cover',
width: '100%',
},
position: 'absolute',
top: 90,
[theme.breakpoints.down('sm')]: {
width: 'unset',
'& > img': {
height: 200,
width: '100%',
},
top: 77,
left: -4,
right: -4,
},
},
centralColumn: {
marginLeft: "auto",
marginRight: "auto",
maxWidth: MAX_COLUMN_WIDTH,
},
header: {
paddingTop: 19,
paddingBottom: 5,
paddingLeft: 42,
paddingRight: 42,
background: theme.palette.panelBackground.default,
},
tableOfContentsWrapper: {
position: "relative",
top: 12,
},
titleRow: {
[theme.breakpoints.up('sm')]: {
display: 'flex',
justifyContent: 'space-between',
}
},
title: {
...theme.typography.display3,
...theme.typography.commentStyle,
marginTop: 0,
fontWeight: 600,
fontVariant: "small-caps"
},
notifyMeButton: {
[theme.breakpoints.down('xs')]: {
marginTop: 6,
},
},
nonMobileButtonRow: {
[theme.breakpoints.down('xs')]: {
// Ensure this takes priority over the properties in TagPageButtonRow
display: 'none !important',
},
},
mobileButtonRow: {
[theme.breakpoints.up('sm')]: {
display: 'none !important',
},
},
editMenu: {
[theme.breakpoints.down('xs')]: {
marginTop: 16,
marginBottom: 8,
},
},
wikiSection: {
paddingTop: 5,
paddingLeft: 42,
paddingRight: 42,
paddingBottom: 12,
marginBottom: 24,
background: theme.palette.panelBackground.default,
},
tagHeader: {
display: "flex",
justifyContent: "space-between",
alignItems: "center",
...theme.typography.body2,
...theme.typography.commentStyle,
},
postsTaggedTitle: {
color: theme.palette.grey[600]
},
pastRevisionNotice: {
...theme.typography.commentStyle,
fontStyle: 'italic'
},
nextLink: {
...theme.typography.commentStyle
},
randomTagLink: {
...theme.typography.commentStyle,
fontSize: "1.16rem",
color: theme.palette.grey[600],
display: "inline-block",
marginTop: 8,
marginBottom: 8,
},
});
export const tagPostTerms = (tag: TagBasicInfo | null, query: any) => {
if (!tag) return
return ({
...query,
filterSettings: {tags:[{tagId: tag._id, tagName: tag.name, filterMode: "Required"}]},
view: "tagRelevance",
tagId: tag._id,
})
}
const TagPage = ({classes}: {
classes: ClassesType
}) => {
const {
PostsListSortDropdown, PostsList2, ContentItemBody, Loading, AddPostsToTag, Error404,
PermanentRedirect, HeadTags, UsersNameDisplay, TagFlagItem, TagDiscussionSection, Typography,
TagPageButtonRow, ToCColumn, TableOfContents, TableOfContentsRow, TagContributorsList,
SubscribeButton, CloudinaryImage2, TagIntroSequence, SectionTitle, ContentStyles
} = Components;
const currentUser = useCurrentUser();
const { query, params: { slug } } = useLocation();
const { revision } = query;
const contributorsLimit = 7;
const { tag, loading: loadingTag } = useTagBySlug(slug, revision ? "TagPageWithRevisionFragment" : "TagPageFragment", {
extraVariables: revision ? {
version: 'String',
contributorsLimit: 'Int',
} : {
contributorsLimit: 'Int',
},
extraVariablesValues: revision ? {
version: revision,
contributorsLimit,
} : {
contributorsLimit,
},
});
const [truncated, setTruncated] = useState(true)
const [editing, setEditing] = useState(!!query.edit)
const [hoveredContributorId, setHoveredContributorId] = useState<string|null>(null);
const { captureEvent } = useTracking()
const client = useApolloClient()
const multiTerms = {
allPages: {view: "allPagesByNewest"},
myPages: {view: "userTags", userId: currentUser?._id},
//tagFlagId handled as default case below
}
const { results: otherTagsWithNavigation } = useMulti({
terms: ["allPages", "myPages"].includes(query.focus) ? multiTerms[query.focus] : {view: "tagsByTagFlag", tagFlagId: query.focus},
collectionName: "Tags",
fragmentName: 'TagWithFlagsFragment',
limit: 1500,
skip: !query.flagId
})
const tagPositionInList = otherTagsWithNavigation?.findIndex(tagInList => tag?._id === tagInList._id);
// We have to handle updates to the listPosition explicitly, since we have to deal with three cases
// 1. Initially the listPosition is -1 because we don't have a list at all yet
// 2. Then we have the real position
// 3. Then we remove the tagFlag, we still want it to have the right next button
const [nextTagPosition, setNextTagPosition] = useState<number | null>(null);
useEffect(() => {
// Initial list position setting
if (tagPositionInList && tagPositionInList >= 0) {
setNextTagPosition(tagPositionInList + 1)
}
if (nextTagPosition !== null && tagPositionInList && tagPositionInList < 0) {
// Here we want to decrement the list positions by one, because we removed the original tag and so
// all the indices are moved to the next
setNextTagPosition(nextTagPosition => (nextTagPosition || 1) - 1)
}
//eslint-disable-next-line react-hooks/exhaustive-deps
}, [tagPositionInList])
const nextTag = otherTagsWithNavigation && (nextTagPosition !== null && nextTagPosition >= 0) && otherTagsWithNavigation[nextTagPosition]
const expandAll = useCallback(() => {
setTruncated(false)
}, []);
const onHoverContributor = useCallback((userId: string) => {
setHoveredContributorId(userId);
}, []);
if (loadingTag)
return <Loading/>
if (!tag)
return <Error404/>
// If the slug in our URL is not the same as the slug on the tag, redirect to the canonical slug page
if (tag.oldSlugs?.filter(slug => slug !== tag.slug)?.includes(slug)) {
return <PermanentRedirect url={tagGetUrl(tag)} />
}
// if no sort order was selected, try to use the tag page's default sort order for posts
query.sortedBy = query.sortedBy || tag.postsDefaultSortOrder
const terms = {
...tagPostTerms(tag, query),
limit: 15
}
const clickReadMore = () => {
setTruncated(false)
captureEvent("readMoreClicked", {tagId: tag._id, tagName: tag.name, pageSectionContext: "wikiSection"})
}
const htmlWithAnchors = tag.tableOfContents?.html || tag.description?.html;
const description = (truncated && !tag.wikiOnly && !isEAForum)
? truncate(htmlWithAnchors, tag.descriptionTruncationCount || 4, "paragraphs", "<span>...<p><a>(Read More)</a></p></span>")
: htmlWithAnchors
const headTagDescription = tag.description?.plaintextDescription || `All posts related to ${tag.name}, sorted by relevance`
const tagFlagItemType = {
allPages: "allPages",
myPages: "userPages"
}
return <AnalyticsContext
pageContext='tagPage'
tagName={tag.name}
tagId={tag._id}
sortedBy={query.sortedBy || "relevance"}
limit={terms.limit}
>
<HeadTags
description={headTagDescription}
/>
{hoveredContributorId && <style>
{`.by_${hoveredContributorId} {background: rgba(95, 155, 101, 0.35);}`}
</style>}
{tag.bannerImageId && <div className={classes.imageContainer}>
<CloudinaryImage2
publicId={tag.bannerImageId}
height={300}
fullWidthHeader
/>
</div>}
<div className={tag.bannerImageId ? classes.rootGivenImage : ''}>
<ToCColumn
tableOfContents={
tag.tableOfContents
? <span className={classes.tableOfContentsWrapper}>
<TableOfContents
sectionData={tag.tableOfContents}
title={tag.name}
onClickSection={expandAll}
/>
<Link to="/tags/random" className={classes.randomTagLink}>
Random {taggingNameCapitalSetting.get()}
</Link>
<TableOfContentsRow href="#" divider={true}/>
<TagContributorsList onHoverUser={onHoverContributor} tag={tag}/>
</span>
: null
}
header={<div className={classNames(classes.header,classes.centralColumn)}>
{query.flagId && <span>
<Link to={`/tags/dashboard?focus=${query.flagId}`}>
<TagFlagItem
itemType={["allPages", "myPages"].includes(query.flagId) ? tagFlagItemType[query.flagId] : "tagFlagId"}
documentId={query.flagId}
/>
</Link>
{nextTag && <span onClick={() => setEditing(true)}><Link
className={classes.nextLink}
to={tagGetUrl(nextTag, {flagId: query.flagId, edit: true})}>
Next Tag ({nextTag.name})
</Link></span>}
</span>}
<div className={classes.titleRow}>
<Typography variant="display3" className={classes.title}>
{tag.name}
</Typography>
<TagPageButtonRow tag={tag} editing={editing} setEditing={setEditing} className={classNames(classes.editMenu, classes.mobileButtonRow)} />
{!tag.wikiOnly && !editing && userHasNewTagSubscriptions(currentUser) &&
<SubscribeButton
tag={tag}
className={classes.notifyMeButton}
subscribeMessage="Subscribe"
unsubscribeMessage="Unsubscribe"
subscriptionType={subscriptionTypes.newTagPosts}
/>
}
</div>
<TagPageButtonRow tag={tag} editing={editing} setEditing={setEditing} className={classNames(classes.editMenu, classes.nonMobileButtonRow)} />
</div>}
>
<div className={classNames(classes.wikiSection,classes.centralColumn)}>
<AnalyticsContext pageSectionContext="wikiSection">
{ revision && tag.description && (tag.description as TagRevisionFragment_description).user && <div className={classes.pastRevisionNotice}>
You are viewing revision {tag.description.version}, last edited by <UsersNameDisplay user={(tag.description as TagRevisionFragment_description).user}/>
</div>}
{editing ? <EditTagForm
tag={tag}
successCallback={ async () => {
setEditing(false)
await client.resetStore()
}}
cancelCallback={() => setEditing(false)}
/> :
<div onClick={clickReadMore}>
<ContentStyles contentType="tag">
<ContentItemBody
dangerouslySetInnerHTML={{__html: description||""}}
description={`tag ${tag.name}`}
className={classes.description}
/>
</ContentStyles>
</div>}
</AnalyticsContext>
</div>
<div className={classes.centralColumn}>
{editing && <TagDiscussionSection
key={tag._id}
tag={tag}
/>}
{tag.sequence && <TagIntroSequence tag={tag} />}
{!tag.wikiOnly && <AnalyticsContext pageSectionContext="tagsSection">
{tag.sequence ?
<SectionTitle title={`Posts tagged ${tag.name}`}>
<PostsListSortDropdown value={query.sortedBy || "relevance"}/>
</SectionTitle> :
<div className={classes.tagHeader}>
<div className={classes.postsTaggedTitle}>Posts tagged <em>{tag.name}</em></div>
<PostsListSortDropdown value={query.sortedBy || "relevance"}/>
</div>
}
<PostsList2
terms={terms}
enableTotal
tagId={tag._id}
itemsPerPage={200}
>
<AddPostsToTag tag={tag} />
</PostsList2>
</AnalyticsContext>}
</div>
</ToCColumn>
</div>
</AnalyticsContext>
}
const TagPageComponent = registerComponent("TagPage", TagPage, {styles});
declare global {
interface ComponentTypes {
TagPage: typeof TagPageComponent
}
} | the_stack |
import { ConcreteRequest } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type NewWorksForYouRailQueryVariables = {
cursor?: string | null | undefined;
count: number;
};
export type NewWorksForYouRailQueryResponse = {
readonly me: {
readonly " $fragmentRefs": FragmentRefs<"NewWorksForYouRail_me">;
} | null;
};
export type NewWorksForYouRailQuery = {
readonly response: NewWorksForYouRailQueryResponse;
readonly variables: NewWorksForYouRailQueryVariables;
};
/*
query NewWorksForYouRailQuery(
$cursor: String
$count: Int!
) {
me {
...NewWorksForYouRail_me_1G22uz
id
}
}
fragment NewWorksForYouRail_me_1G22uz on Me {
newWorksByInterestingArtists(first: $count, after: $cursor) {
pageInfo {
hasNextPage
startCursor
endCursor
}
edges {
node {
...SmallTileRail_artworks
id
__typename
}
cursor
}
}
}
fragment SmallTileRail_artworks on Artwork {
href
saleMessage
artistNames
slug
internalID
sale {
isAuction
isClosed
displayTimelyAt
endAt
id
}
saleArtwork {
counts {
bidderPositions
}
currentBid {
display
}
id
}
partner {
name
id
}
image {
imageURL
}
}
*/
const node: ConcreteRequest = (function(){
var v0 = {
"defaultValue": null,
"kind": "LocalArgument",
"name": "count"
},
v1 = {
"defaultValue": null,
"kind": "LocalArgument",
"name": "cursor"
},
v2 = [
{
"kind": "Variable",
"name": "after",
"variableName": "cursor"
},
{
"kind": "Variable",
"name": "first",
"variableName": "count"
}
],
v3 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
};
return {
"fragment": {
"argumentDefinitions": [
(v0/*: any*/),
(v1/*: any*/)
],
"kind": "Fragment",
"metadata": null,
"name": "NewWorksForYouRailQuery",
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Me",
"kind": "LinkedField",
"name": "me",
"plural": false,
"selections": [
{
"args": [
{
"kind": "Variable",
"name": "count",
"variableName": "count"
},
{
"kind": "Variable",
"name": "cursor",
"variableName": "cursor"
}
],
"kind": "FragmentSpread",
"name": "NewWorksForYouRail_me"
}
],
"storageKey": null
}
],
"type": "Query",
"abstractKey": null
},
"kind": "Request",
"operation": {
"argumentDefinitions": [
(v1/*: any*/),
(v0/*: any*/)
],
"kind": "Operation",
"name": "NewWorksForYouRailQuery",
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Me",
"kind": "LinkedField",
"name": "me",
"plural": false,
"selections": [
{
"alias": null,
"args": (v2/*: any*/),
"concreteType": "ArtworkConnection",
"kind": "LinkedField",
"name": "newWorksByInterestingArtists",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "PageInfo",
"kind": "LinkedField",
"name": "pageInfo",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "hasNextPage",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "startCursor",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "endCursor",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "ArtworkEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Artwork",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "href",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "saleMessage",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "artistNames",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "slug",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "internalID",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Sale",
"kind": "LinkedField",
"name": "sale",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "isAuction",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "isClosed",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "displayTimelyAt",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "endAt",
"storageKey": null
},
(v3/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "SaleArtwork",
"kind": "LinkedField",
"name": "saleArtwork",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "SaleArtworkCounts",
"kind": "LinkedField",
"name": "counts",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "bidderPositions",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "SaleArtworkCurrentBid",
"kind": "LinkedField",
"name": "currentBid",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "display",
"storageKey": null
}
],
"storageKey": null
},
(v3/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Partner",
"kind": "LinkedField",
"name": "partner",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "name",
"storageKey": null
},
(v3/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "image",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "imageURL",
"storageKey": null
}
],
"storageKey": null
},
(v3/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "cursor",
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": (v2/*: any*/),
"filters": null,
"handle": "connection",
"key": "NewWorksForYouRail_newWorksByInterestingArtists",
"kind": "LinkedHandle",
"name": "newWorksByInterestingArtists"
},
(v3/*: any*/)
],
"storageKey": null
}
]
},
"params": {
"id": "e5a3c3f31d5c73ae34ae834bf4bc900f",
"metadata": {},
"name": "NewWorksForYouRailQuery",
"operationKind": "query",
"text": null
}
};
})();
(node as any).hash = '3ca133779de35482c427c6135fc2a0dc';
export default node; | the_stack |
import * as React from "react";
import { useQuery } from "relay-hooks";
import type { Area } from "react-easy-crop/types";
import useMeasure from "react-use-measure";
import {
Button,
FormControl,
Slider,
SliderFilledTrack,
SliderThumb,
SliderTrack,
Stack,
Text,
FormLabel,
Input,
Image,
Grid,
GridItem,
Heading,
} from "@chakra-ui/react";
import graphql from "babel-plugin-relay/macro";
import { loadImage } from "../util";
import { tokenImageCropper_TokenLibraryImagesQuery } from "./__generated__/tokenImageCropper_TokenLibraryImagesQuery.graphql";
import { useStaticRef } from "../hooks/use-static-ref";
import { useWindowDimensions } from "../hooks/use-window-dimensions";
import type CropperType from "react-easy-crop";
const TokenLibraryImagesQuery = graphql`
query tokenImageCropper_TokenLibraryImagesQuery($sourceImageSha256: String!) {
tokenImages(first: 20, sourceImageSha256: $sourceImageSha256) {
edges {
node {
id
title
url
}
}
}
}
`;
export const TokenImageCropper = (props: {
imageUrl: string;
sourceImageHash: string;
onConfirm: (
params:
| {
type: "File";
file: File;
title: string;
}
| {
type: "TokenImage";
tokenImageId: string;
}
) => unknown;
onClose: () => void;
}): React.ReactElement => {
const [crop, setCrop] = React.useState({ x: 0, y: 0 });
const [zoom, setZoom] = React.useState(1);
const [rotation, setRotation] = React.useState(0);
const [croppedAreaPixels, setCroppedAreaPixels] = React.useState<Area | null>(
null
);
const [title, setTitle] = React.useState("New Token Image");
const data = useQuery<tokenImageCropper_TokenLibraryImagesQuery>(
TokenLibraryImagesQuery,
useStaticRef(() => ({
sourceImageSha256: props.sourceImageHash,
}))
);
const windowDimensions = useWindowDimensions();
const [imageDimensions, setImageDimensions] = React.useState<{
width: number;
height: number;
} | null>(null);
const [ref, bounds] = useMeasure();
const cropperRef = React.useRef<CropperType | null>();
const [cropSize, setCropSize] = React.useState<null | {
width: number;
height: number;
minZoom: number;
maxZoom: number;
}>(null);
React.useEffect(() => {
if (!cropperRef.current?.imageRef || bounds.height === 0) {
return;
}
const imageDimensions = {
width: cropperRef.current.imageRef.width,
height: cropperRef.current.imageRef.height,
};
let ratio = imageDimensions.width / imageDimensions.height;
let width = imageDimensions.width;
let height = imageDimensions.height;
const minBoundSide = Math.min(bounds.width - 30, bounds.height - 30);
let sideLength = Math.min(minBoundSide, width);
let minZoom = sideLength / imageDimensions.width;
if (ratio > 1) {
sideLength = Math.min(minBoundSide, height);
minZoom = sideLength / imageDimensions.height;
}
let maxZoom = (imageDimensions.width * 4) / sideLength;
setCropSize({ height: sideLength, width: sideLength, minZoom, maxZoom });
setZoom((zoom) => {
if (zoom < minZoom) {
return minZoom;
}
if (zoom > maxZoom) {
return maxZoom;
}
return zoom;
});
}, [windowDimensions, imageDimensions, bounds]);
return (
<>
<Grid
position="absolute"
h="100vh"
width="100%"
templateRows="repeat(4, 1fr)"
templateColumns="repeat(5, 1fr)"
gap={4}
zIndex={1}
padding={4}
>
<GridItem
rowSpan={{ base: 1, xl: 4 }}
colSpan={{ base: 5, xl: 1 }}
display="flex"
alignItems="center"
>
{data.data?.tokenImages?.edges.length ? (
<Stack
spacing={2}
padding={3}
borderRadius={3}
background="white"
maxHeight={500}
zIndex={10}
width="100%"
maxWidth={{ base: undefined, xl: "300px" }}
>
<Heading size="xs">Token Images from this Source</Heading>
<Stack direction={{ base: "row", xl: "column" }}>
{data.data.tokenImages.edges.map((edge) => (
<Grid
templateRows="repeat(3, 1fr)"
templateColumns="repeat(5, 1fr)"
gap={2}
height={75}
>
<GridItem colSpan={2} rowSpan={3}>
<Image
src={edge.node.url}
key={edge.node.id}
height={75}
width={75}
/>
</GridItem>
<GridItem colSpan={3} rowSpan={1}>
<Text
paddingTop={3}
width="100%"
backgroundColor="white"
fontSize="xs"
maxWidth={100}
whiteSpace="nowrap"
textOverflow="ellipsis"
overflow="hidden"
>
{edge.node.title}
</Text>
</GridItem>
<GridItem colSpan={3} rowSpan={2}>
<Button
size="sm"
onClick={() => {
props.onConfirm({
type: "TokenImage",
tokenImageId: edge.node.id,
});
}}
>
Use this image.
</Button>
</GridItem>
</Grid>
))}
</Stack>
</Stack>
) : null}
</GridItem>
<GridItem
colSpan={{ base: 5, xl: 4 }}
rowSpan={{ base: 3, xl: 3 }}
ref={ref}
position="relative"
>
<Cropper
// @ts-ignore
ref={cropperRef}
image={props.imageUrl}
crop={crop}
rotation={rotation}
minZoom={cropSize?.minZoom ?? 1}
maxZoom={cropSize?.maxZoom ?? 1}
zoom={zoom}
onRotationChange={(rotation) => {
setRotation(rotation);
}}
onCropChange={setCrop}
onCropComplete={(_, croppedAreaPixels) => {
setCroppedAreaPixels(croppedAreaPixels);
}}
onZoomChange={setZoom}
onMediaLoaded={({ width, height }) => {
setImageDimensions({ width, height });
}}
cropSize={cropSize ?? undefined}
style={{
containerStyle: {
height: bounds.height,
width: bounds.width,
overflow: "visible",
},
}}
/>
</GridItem>
<GridItem
colSpan={{ base: 5, xl: 4 }}
rowSpan={{ base: 2, xl: 1 }}
display="flex"
justifyContent="center"
>
<Stack
background="white"
padding={5}
borderRadius={3}
maxWidth={600}
spacing={4}
zIndex={100}
height="fit-content"
alignSelf="flex-end"
>
<Text fontSize="small">
Please select a rectangular part from the image that will be used
as the token image.
</Text>
<FormControl id="slider">
<FormLabel fontSize="small">Zoom</FormLabel>
<Slider
aria-label="slider-zoom"
min={cropSize?.minZoom}
max={cropSize?.maxZoom}
step={0.01}
value={zoom}
onChange={(zoom) => setZoom(zoom)}
size="sm"
>
<SliderTrack>
<SliderFilledTrack />
</SliderTrack>
<SliderThumb />
</Slider>
</FormControl>
<FormControl id="rotation">
<FormLabel fontSize="small">Rotation</FormLabel>
<Slider
aria-label="slider-rotation"
min={0}
max={360}
step={0.01}
value={rotation}
onChange={(rotation) => setRotation(rotation)}
size="sm"
>
<SliderTrack>
<SliderFilledTrack />
</SliderTrack>
<SliderThumb />
</Slider>
</FormControl>
<FormControl id="token-title">
<FormLabel fontSize="small">Title</FormLabel>
<Input
value={title}
onChange={(ev) => setTitle(ev.target.value)}
size="sm"
/>
</FormControl>
<Stack
spacing={4}
direction="row"
align="center"
alignSelf="flex-end"
>
<Button onClick={props.onClose} variant="ghost">
Abort
</Button>
<Button
colorScheme="teal"
isDisabled={croppedAreaPixels === null}
onClick={async () => {
if (!croppedAreaPixels) {
return;
}
const file = await cropImage(
props.imageUrl,
croppedAreaPixels,
rotation
);
props.onConfirm({ type: "File", file, title });
}}
>
Confirm
</Button>
</Stack>
</Stack>
</GridItem>
</Grid>
</>
);
};
const Cropper = React.lazy(() => import("react-easy-crop"));
const cropImage = async (imageUrl: string, crop: Area, rotation: number) => {
const image = await loadImage(imageUrl).promise;
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d")!;
const maxSize = Math.max(image.width, image.height);
const safeArea = 2 * ((maxSize / 2) * Math.sqrt(2));
// set each dimensions to double largest dimension to allow for a safe area for the
// image to rotate in without being clipped by canvas context
canvas.width = safeArea;
canvas.height = safeArea;
// translate canvas context to a central location on image to allow rotating around the center.
ctx.translate(safeArea / 2, safeArea / 2);
ctx.rotate(degreeToRadian(rotation));
ctx.translate(-safeArea / 2, -safeArea / 2);
ctx.drawImage(
image,
safeArea / 2 - image.width * 0.5,
safeArea / 2 - image.height * 0.5
);
const data = ctx.getImageData(0, 0, safeArea, safeArea);
// set canvas width to final desired crop size - this will clear existing context
canvas.width = crop.width;
canvas.height = crop.height;
// paste generated rotate image with correct offsets for x,y crop values.
ctx.putImageData(
data,
Math.round(0 - safeArea / 2 + image.width * 0.5 - crop.x),
Math.round(0 - safeArea / 2 + image.height * 0.5 - crop.y)
);
return await new Promise<File>((resolve, reject) => {
canvas.toBlob((blob) => {
if (blob === null) {
return reject(new Error("Unexpected error."));
}
resolve(new File([blob], "image.webp"));
}, "image/webp");
});
};
const degreeToRadian = (degree: number) => (degree * Math.PI) / 180; | the_stack |
import { methodCall } from "@okikio/manager";
import { animate, tweenAttr } from "@okikio/animate";
import { interpolate } from "polymorph-js";
import type { IAnimationOptions, TypePlayStates } from "@okikio/animate";
// I added extra code to the demo to support Chrome 77 and below
let playbackFn = (containerSel, anims) => {
let playstateEl = document.querySelector(`${containerSel} #playstate-toggle`) as HTMLInputElement;
let progressEl = document.querySelector(`${containerSel} #progress`) as HTMLInputElement;
let progressOutputEl = document.querySelector(`${containerSel} #progress-output`);
let oldState: "pending" | TypePlayStates;
let updatePlayState = () => {
oldState = anims[0].getPlayState();
if (oldState == "idle") oldState = "paused";
else if (oldState == "pending") oldState = "running";
playstateEl.setAttribute("data-playstate", oldState);
};
anims[0]
.on("finish begin", updatePlayState)
.on("update", (progress) => {
progress = progress.toFixed(4);
progressEl.value = `` + progress;
progressOutputEl.textContent = `${Math.round(progress)}%`;
});
let clickFn = () => {
if (anims[0].is("running")) methodCall(anims, "pause");
else if (anims[0].is("finished")) methodCall(anims, "reset");
else methodCall(anims, "play");
updatePlayState();
};
let inputFn = () => {
let percent = Number(progressEl.value);
methodCall(anims, "setProgress", percent);
methodCall(anims, "pause");
}
let changeFn = () => {
oldState !== "paused" ? methodCall(anims, "play") : methodCall(anims, "pause");
updatePlayState();
}
playstateEl.addEventListener("click", clickFn);
progressEl.addEventListener("input", inputFn);
progressEl.addEventListener("change", changeFn);
anims[0].on("stop", () => {
playstateEl.removeEventListener("click", clickFn);
progressEl.removeEventListener("input", inputFn);
progressEl.removeEventListener("change", changeFn);
anims = null;
});
}
let random = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min;
/* Properties Section */
// Playback Controls Demo
export let svgAnim1, svgAnim2, empty, anim, motionPath, getTotalLength;
export let run = () => {
// Based on an example by animateplus
(() => {
let containerSel = ".morph-demo";
let usingDPathEl = document.querySelector(`${containerSel} #using-d`);
let usingPolymorphPathEl = document.querySelector(`${containerSel} #using-polymorph-js`);
if (usingDPathEl) {
let InitialStyle = getComputedStyle(usingDPathEl);
svgAnim1 = animate({
target: usingDPathEl,
duration: 1800,
easing: "ease",
loop: 4,
direction: "alternate",
"d": [
InitialStyle.getPropertyValue("d"),
`path("M2,5 S2,14 4,5 S7,8 8,4")`
],
stroke: [
InitialStyle.getPropertyValue("stroke"),
`rgb(96, 165, 250)`
],
});
}
if (usingDPathEl && usingPolymorphPathEl) {
let InitialStyle = getComputedStyle(usingPolymorphPathEl);
let startPath = usingPolymorphPathEl.getAttribute("d");
let endPath =
"M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z";
let options: IAnimationOptions = {
duration: 1800,
easing: "ease",
loop: 4,
fillMode: "both",
direction: "alternate",
};
svgAnim2 = animate({
target: usingPolymorphPathEl,
options,
fill: [
InitialStyle.getPropertyValue("stroke"),
`rgb(96, 165, 250)`
],
// You can also use custom properties when animating
// I chose to use them for this example
// Read more here [https://css-tricks.com/a-complete-guide-to-custom-properties/]
"--stroke": [
InitialStyle.getPropertyValue("stroke"),
`rgb(96, 165, 250)`
],
});
let morph = interpolate([startPath, endPath], {
addPoints: 0,
origin: { x: 0, y: 0 },
optimize: "fill",
precision: 3
});
empty = tweenAttr({
target: usingPolymorphPathEl,
options,
d: progress => morph(progress),
easing: "linear"
});
playbackFn(containerSel, [empty, svgAnim1, svgAnim2]);
}
})();
(() => {
let containerSel = ".playback-demo";
let DOMNodes = document.querySelectorAll(`${containerSel} .el`);
if (DOMNodes.length) {
anim = animate({
target: DOMNodes,
// keyframes(_, total, target) {
// let bgColor = getComputedStyle(target).getPropertyValue("background-color");
// let [r, g, b] = [
// random(0, 255),
// random(0, 255),
// random(0, 255)
// ];
// return [
// {
// translateX: 0,
// translateY: 0,
// scale: 1,
// opacity: 0.5,
// rotate: 0,
// "background-color": bgColor
// },
// {
// "translate-x": random(50, 400),
// translateY: (random(-50, 50) * total),
// scale: 1 + random(0.025, 1.75),
// opacity: 0.5 + Math.min(random(0.025, total) / total, 0.5),
// rotate: random(-360, 360),
// backgroundColor: `rgb(${r}, ${g}, ${b})`
// }
// ];
// },
"background-color": (...args) => {
let [, , target] = args;
let [r, g, b] = [
random(0, 255),
random(0, 255),
random(0, 255)
]
return [
getComputedStyle(target).getPropertyValue("background-color"),
`rgb(${r}, ${g}, ${b})`
];
},
"translate-x": () => [0, random(50, 400)],
translateY(...args) {
let [, total] = args;
return [0, (random(-50, 50) * total)];
},
scale() {
return [1, 1 + random(0.025, 1.75)];
},
opacity(...args) {
let [, total] = args;
return [0.5, 0.5 + Math.min(random(0.025, total) / total, 0.5)];
},
rotate: () => [0, random(-360, 360)],
borderRadius: () => ["3px", `${random(10, 35)}%`],
duration: () => random(1200, 1800),
delay: () => random(0, 400),
// It is best to use the onfinish() method, but in this situation fillMode works best
loop: 2,
speed: (i) => 1.5 - (i * 0.125),
fillMode: "both",
direction: "alternate",
easing: "in-out-back",
padEndDelay: true,
autoplay: true
});
let addBtn = document.querySelector("#add-el") as HTMLElement;
let removeBtn = document.querySelector("#remove-el") as HTMLElement;
let elPlacement = document.querySelector(".el-placement") as HTMLElement;
let contain = document.createElement("div");
contain.className = "contain";
contain.innerHTML = `
<div class="el"></div>
<div class="el-initial"></div>`.trim();
addBtn.onclick = () => {
let _contain = contain.cloneNode(true) as HTMLElement;
let el = _contain.querySelector(".el");
elPlacement.appendChild(_contain);
anim.add(el);
// To support older browsers I can't use partial keyframes
let transition = animate({
target: _contain,
opacity: [0, 1],
height: [0, "4vmin"],
marginBottom: [0, 5],
fillMode: "forwards",
duration: 400,
easing: "out"
}).then(() => {
transition.stop();
transition = null;
_contain = null;
el = null;
});
};
removeBtn.onclick = () => {
let contain = elPlacement.querySelector(".contain") as HTMLElement;
let el = contain?.querySelector(".el") as HTMLElement;
anim.remove(el);
// To support older browsers I can't use partial keyframes
let style = getComputedStyle(contain);
let marginBottom = style.getPropertyValue("margin-bottom");
let height = style.getPropertyValue("height");
let transition = animate({
target: contain,
opacity: [1, 0],
height: [height, 0],
"margin-bottom": [marginBottom, 0],
fillMode: "forwards",
duration: 400,
easing: "out"
}).then(() => {
contain?.remove();
transition.stop();
transition = null;
contain = null;
el = null;
});
};
playbackFn(containerSel, [anim]);
}
})();
(() => {
let options: IAnimationOptions = {
padEndDelay: true,
easing: "linear",
duration: 2000,
loop: 4,
speed: 1,
};
let containerSel = ".motion-path-demo";
let el = document.querySelector('.motion-path .el-1') as HTMLElement;
if (el) {
// To support older browsers I can't use partial keyframes
motionPath = animate({
target: el,
"offsetDistance": ["0%", "100%"],
...options
});
}
let path = document.querySelector('.motion-path path') as SVGPathElement;
let el2 = document.querySelector('.motion-path .el-2') as HTMLElement;
if (path && el2) {
let pts: Set<number[]> = new Set();
let rotateArr: number[] = [];
let len = path.getTotalLength();
let ptAtZero = path.getPointAtLength(0);
for (var i = 0; i < len; i++) {
let { x, y } = path.getPointAtLength(i);
pts.add([x, y]);
let { x: x0, y: y0 } = i - 1 >= 1 ? path.getPointAtLength(i - 1) : ptAtZero;
let { x: x1, y: y1 } = i + 1 >= 1 ? path.getPointAtLength(i + 1) : ptAtZero;
let calc = +(Math.atan2(y0 - y1, x0 - x1) * 180 / Math.PI);
rotateArr.push(calc);
}
getTotalLength = animate({
target: el2,
translate: [...pts],
rotate: rotateArr,
fillMode: "both",
...options,
});
playbackFn(containerSel, [motionPath, getTotalLength]);
}
})();
};
export let stop = () => {
svgAnim1?.stop();
svgAnim2?.stop();
empty?.stop();
anim?.stop();
motionPath?.stop();
getTotalLength?.stop();
} | the_stack |
////// DEFAULT INTERFACES
////interface IFoo {
//// n: number;
//// s: string;
//// f(i: number, s: string): string;
//// a: number[];
////}
////interface IBar {
//// foo: IFoo;
////}
////// CONTEXT: Class property declaration
////class C1T5 {
//// /*1*/foo: (i: number, s: string) => number = function(/*2*/i) {
//// return /*3*/i;
//// }
////}
////// CONTEXT: Module property declaration
////module C2T5 {
//// export var /*4*/foo: (i: number, s: string) => number = function(/*5*/i) {
//// return /*6*/i;
//// }
////}
////// CONTEXT: Variable declaration
////var /*7*/c3t1: (s: string) => string = (function(/*8*/s) { return /*9*/s });
////var /*10*/c3t2 = <IFoo>({
//// n: 1
////})
////var /*11*/c3t3: number[] = [];
////var /*12*/c3t4: () => IFoo = function() { return <IFoo>({}) };
////var /*13*/c3t5: (n: number) => IFoo = function(/*14*/n) { return <IFoo>({}) };
////var /*15*/c3t6: (n: number, s: string) => IFoo = function(/*16*/n, /*17*/s) { return <IFoo>({}) };
////var /*18*/c3t7: {
//// (n: number): number;
//// (s1: string): number;
////};
////var /*20*/c3t8: (n: number, s: string) => number = function(/*21*/n) { return n; };
////var /*22*/c3t9: number[][] = [[],[]];
////var /*23*/c3t10: IFoo[] = [<IFoo>({}),<IFoo>({})];
////var /*24*/c3t11: {(n: number, s: string): string;}[] = [function(/*25*/n, /*26*/s) { return s; }];
////var /*27*/c3t12: IBar = {
//// /*28*/foo: <IFoo>({})
////}
////var /*29*/c3t13 = <IFoo>({
//// /*30*/f: function(/*31*/i, /*32*/s) { return s; }
////})
////var /*33*/c3t14 = <IFoo>({
//// /*34*/a: []
////})
////// CONTEXT: Class property assignment
////class C4T5 {
//// /*35*/foo: (i: number, s: string) => string;
//// constructor() {
//// this.foo = function(/*36*/i, /*37*/s) {
//// return s;
//// }
//// }
////}
////// CONTEXT: Module property assignment
////module C5T5 {
//// export var /*38*/foo: (i: number, s: string) => string;
//// foo = function(/*39*/i, /*40*/s) {
//// return s;
//// }
////}
////// CONTEXT: Variable assignment
////var /*41*/c6t5: (n: number) => IFoo;
////c6t5 = <(n: number) => IFoo>function(/*42*/n) { return <IFoo>({}) };
////// CONTEXT: Array index assignment
////var /*43*/c7t2: IFoo[];
/////*44*/c7t2[0] = <IFoo>({n: 1});
////// CONTEXT: Object property assignment
////interface IPlaceHolder {
//// t1: (s: string) => string;
//// t2: IFoo;
//// t3: number[];
//// t4: () => IFoo;
//// t5: (n: number) => IFoo;
//// t6: (n: number, s: string) => IFoo;
//// t7: {
//// (n: number, s: string): number;
//// //(s1: string, s2: string): number;
//// };
//// t8: (n: number, s: string) => number;
//// t9: number[][];
//// t10: IFoo[];
//// t11: {(n: number, s: string): string;}[];
//// t12: IBar;
//// t13: IFoo;
//// t14: IFoo;
//// }
////var objc8: {
//// t1: (s: string) => string;
//// t2: IFoo;
//// t3: number[];
//// t4: () => IFoo;
//// t5: (n: number) => IFoo;
//// t6: (n: number, s: string) => IFoo;
//// t7: {
//// (n: number, s: string): number;
//// //(s1: string, s2: string): number;
//// };
//// t8: (n: number, s: string) => number;
//// t9: number[][];
//// t10: IFoo[];
//// t11: {(n: number, s: string): string;}[];
//// t12: IBar;
//// t13: IFoo;
//// t14: IFoo;
////} = <IPlaceHolder>({});
////objc8./*45*/t1 = (function(/*46*/s) { return s });
////objc8./*47*/t2 = <IFoo>({
//// n: 1
////});
////objc8./*48*/t3 = [];
////objc8./*49*/t4 = function() { return <IFoo>({}) };
////objc8./*50*/t5 = function(/*51*/n) { return <IFoo>({}) };
////objc8./*52*/t6 = function(/*53*/n, /*54*/s) { return <IFoo>({}) };
////objc8./*55*/t7 = function(n: number) { return n };
////objc8./*56*/t8 = function(/*57*/n) { return n; };
////objc8./*58*/t9 = [[],[]];
////objc8./*59*/t10 = [<IFoo>({}),<IFoo>({})];
////objc8./*60*/t11 = [function (/*61*/n, /*62*/s) { return s; }];
////objc8./*63*/t12 = {
//// /*64*/foo: <IFoo>({})
////}
////objc8./*65*/t13 = <IFoo>({
//// /*66*/f: function(/*67*/i, /*68*/s) { return s; }
////})
////objc8./*69*/t14 = <IFoo>({
//// /*70*/a: []
////})
////// CONTEXT: Function call
////function c9t5(f: (n: number) => IFoo) {};
////c9t5(function(/*71*/n) {
//// return <IFoo>({});
////});
////// CONTEXT: Return statement
////var /*72*/c10t5: () => (n: number) => IFoo = function() { return function(/*73*/n) { return <IFoo>({}) } };
////// CONTEXT: Newing a class
////class C11t5 { constructor(f: (n: number) => IFoo) { } };
////var i = new C11t5(function(/*74*/n) { return <IFoo>({}) });
////// CONTEXT: Type annotated expression
////var /*75*/c12t1 = <(s: string) => string> (function (/*76*/s) { return s });
////var /*77*/c12t2 = <IFoo> ({
//// n: 1
////});
////var /*78*/c12t3 = <number[]> [];
////var /*79*/c12t4 = <() => IFoo> function() { return <IFoo>({}) };
////var /*80*/c12t5 = <(n: number) => IFoo> function(/*81*/n) { return <IFoo>({}) };
////var /*82*/c12t6 = <(n: number, s: string) => IFoo> function(/*83*/n, /*84*/s) { return <IFoo>({}) };
////var /*85*/c12t7 = <{
//// (n: number, s: string): number;
//// //(s1: string, s2: string): number;
////}> function(n:number) { return n };
////var /*86*/c12t8 = <(n: number, s: string) => number> function (/*87*/n) { return n; };
////var /*88*/c12t9 = <number[][]> [[],[]];
////var /*89*/c12t10 = <IFoo[]> [<IFoo>({}),<IFoo>({})];
////var /*90*/c12t11 = <{ (n: number, s: string): string; }[]>[function (/*91*/n, /*92*/s) { return s; }];
////var /*93*/c12t12 = <IBar> {
//// /*94*/foo: <IFoo>({})
////}
////var /*95*/c12t13 = <IFoo> ({
//// /*96*/f: function(/*97*/i, /*98*/s) { return s; }
////})
////var /*99*/c12t14 = <IFoo> ({
//// /*100*/a: []
////})
////// CONTEXT: Contextual typing declarations
////// contextually typing function declarations
////function EF1(a: number, b:number):number;
////function /*101*/EF1(/*102*/a,/*103*/b) { return a+b; }
////var efv = EF1(1,2);
////// contextually typing from ambient class declarations
////declare class Point
////{
//// constructor(x: number, y: number);
//// x: number;
//// y: number;
//// add(dx: number, dy: number): Point;
//// static origin: Point;
////}
////Point./*110*/origin = new /*111*/Point(0, 0);
////Point.prototype./*112*/add = function (/*113*/dx, /*114*/dy) {
//// return new Point(this.x + dx, this.y + dy);
////};
////Point.prototype = {
//// x: 0,
//// y: 0,
//// /*115*/add: function (/*116*/dx, /*117*/dy) {
//// return new Point(this.x + dx, this.y + dy);
//// }
////};
verify.quickInfos({
1: "(property) C1T5.foo: (i: number, s: string) => number",
2: "(parameter) i: number",
3: "(parameter) i: number",
4: "var C2T5.foo: (i: number, s: string) => number",
5: "(parameter) i: number",
6: "(parameter) i: number",
7: "var c3t1: (s: string) => string",
8: "(parameter) s: string",
9: "(parameter) s: string",
10: "var c3t2: IFoo",
11: "var c3t3: number[]",
12: "var c3t4: () => IFoo",
13: "var c3t5: (n: number) => IFoo",
14: "(parameter) n: number",
15: "var c3t6: (n: number, s: string) => IFoo",
16: "(parameter) n: number",
17: "(parameter) s: string",
18: "var c3t7: {\n (n: number): number;\n (s1: string): number;\n}",
20: "var c3t8: (n: number, s: string) => number",
21: "(parameter) n: number",
22: "var c3t9: number[][]",
23: "var c3t10: IFoo[]",
24: "var c3t11: ((n: number, s: string) => string)[]",
25: "(parameter) n: number",
26: "(parameter) s: string",
27: "var c3t12: IBar",
28: "(property) foo: IFoo",
29: "var c3t13: IFoo",
30: "(property) f: (i: number, s: string) => string",
31: "(parameter) i: number",
32: "(parameter) s: string",
33: "var c3t14: IFoo",
34: "(property) a: undefined[]",
35: "(property) C4T5.foo: (i: number, s: string) => string",
36: "(parameter) i: number",
37: "(parameter) s: string",
38: "var C5T5.foo: (i: number, s: string) => string",
39: "(parameter) i: number",
40: "(parameter) s: string",
41: "var c6t5: (n: number) => IFoo",
42: "(parameter) n: number",
43: "var c7t2: IFoo[]",
44: "var c7t2: IFoo[]",
45: "(property) t1: (s: string) => string",
46: "(parameter) s: string",
47: "(property) t2: IFoo",
48: "(property) t3: number[]",
49: "(property) t4: () => IFoo",
50: "(property) t5: (n: number) => IFoo",
51: "(parameter) n: number",
52: "(property) t6: (n: number, s: string) => IFoo",
53: "(parameter) n: number",
54: "(parameter) s: string",
55: "(property) t7: (n: number, s: string) => number",
56: "(property) t8: (n: number, s: string) => number",
57: "(parameter) n: number",
58: "(property) t9: number[][]",
59: "(property) t10: IFoo[]",
60: "(property) t11: ((n: number, s: string) => string)[]",
61: "(parameter) n: number",
62: "(parameter) s: string",
63: "(property) t12: IBar",
64: "(property) foo: IFoo",
65: "(property) t13: IFoo",
66: "(property) f: (i: number, s: string) => string",
67: "(parameter) i: number",
68: "(parameter) s: string",
69: "(property) t14: IFoo",
70: "(property) a: undefined[]",
71: "(parameter) n: number",
72: "var c10t5: () => (n: number) => IFoo",
73: "(parameter) n: number",
74: "(parameter) n: number",
75: "var c12t1: (s: string) => string",
76: "(parameter) s: string",
77: "var c12t2: IFoo",
78: "var c12t3: number[]",
79: "var c12t4: () => IFoo",
80: "var c12t5: (n: number) => IFoo",
81: "(parameter) n: number",
82: "var c12t6: (n: number, s: string) => IFoo",
83: "(parameter) n: number",
84: "(parameter) s: string",
85: "var c12t7: (n: number, s: string) => number",
86: "var c12t8: (n: number, s: string) => number",
87: "(parameter) n: number",
88: "var c12t9: number[][]",
89: "var c12t10: IFoo[]",
90: "var c12t11: ((n: number, s: string) => string)[]",
91: "(parameter) n: number",
92: "(parameter) s: string",
93: "var c12t12: IBar",
94: "(property) foo: IFoo",
95: "var c12t13: IFoo",
96: "(property) f: (i: number, s: string) => string",
97: "(parameter) i: number",
98: "(parameter) s: string",
99: "var c12t14: IFoo",
100: "(property) a: undefined[]",
101: "function EF1(a: number, b: number): number",
102: "(parameter) a: any",
103: "(parameter) b: any",
110: "(property) Point.origin: Point",
111: "constructor Point(x: number, y: number): Point",
112: "(method) Point.add(dx: number, dy: number): Point",
113: "(parameter) dx: number",
114: "(parameter) dy: number",
115: "(property) add: (dx: number, dy: number) => Point",
116: "(parameter) dx: number",
117: "(parameter) dy: number"
}); | the_stack |
import * as child_process from "child_process";
import * as os from "os";
type EmptyCallback = () => void | Promise<void>;
type ErrorCallback = (err?: string) => void | Promise<void>;
type GenericCallback<T> = (err?: string | null, result?: T) => void | Promise<void>;
type SimpleCallback<T> = (result?: T) => void | Promise<void>;
type LogCallback = (msg: any) => void | Promise<void>;
type SecondParameterOf<T extends (...args: any[]) => any> = T extends (
arg0: any,
arg1: infer R,
...args: any[]
) => any
? R
: never;
/** Infers the return type from a callback-style API and strips out null and undefined */
type NonNullCallbackReturnTypeOf<T extends (...args: any[]) => any> = Exclude<
SecondParameterOf<T>,
null | undefined
>;
/** Infers the return type from a callback-style API and and leaves null and undefined in */
type CallbackReturnTypeOf<T extends (...args: any[]) => any> = SecondParameterOf<T>;
/** Returns a type that requires at least one of the properties from the given type */
type AtLeastOne<T, U = { [K in keyof T]-?: T[K] }> = { [K in keyof U]: { [P in K]: U[P] } }[keyof U];
/** Returns all possible keys of a union of objects */
type AllKeys<T> = T extends any ? keyof T : never;
/** Simplifies mapped types to their basic forms */
type Simplify<U> = U extends infer O ? { [K in keyof O]: O[K] } : never;
/** Takes an object type and adds all missing properties from the Keys union with type never */
type AddMissingNever<T, Keys extends string | number | symbol> = {
[K in Keys]: K extends keyof T ? T[K] : never;
};
/**
* Takes a union of objects and returns an object type
* which has all properties that exist on at least one of the objects.
*
* E.g. CombineObjectUnion<{a: 1} | {b: 2}> = {a: 1; b: 2};
*/
type CombineObjectUnion<
T,
Keys extends string | number | symbol = AllKeys<T>,
O = T extends any ? AddMissingNever<T, Keys> : never
> = Simplify<{ [K in Keys]: K extends keyof O ? O[K] : never }>
/**
* Takes a union of ioBroker Object types and returns a combined object type
* which has all properties that could exist on at least one of the objects.
*
* Note: This is not entirely sound to work with, but better for JS and working with read objects
*/
type AnyOf<
T,
Keys extends string | number | symbol = AllKeys<T>,
O = T extends any ? AddMissingNever<T, Keys> : never
> = Simplify<{
[K in Keys]: K extends keyof O ? (
O[K] extends any[] ? O[K]
: O[K] extends Record<any, any> ? CombineObjectUnion<O[K]>
: O[K]
) : never;
}>;
// tslint:disable:no-namespace
declare global {
namespace iobJS {
enum StateQuality {
good = 0x00, // or undefined or null
bad = 0x01,
general_problem = 0x01,
general_device_problem = 0x41,
general_sensor_problem = 0x81,
device_not_connected = 0x42,
sensor_not_connected = 0x82,
device_reports_error = 0x44,
sensor_reports_error = 0x84,
}
type PrimitiveTypeStateValue = string | number | boolean;
type StateValue = null | PrimitiveTypeStateValue | PrimitiveTypeStateValue[] | Record<string, any>;
interface State<T extends StateValue = any> {
/** The value of the state. */
val: T;
/** Direction flag: false for desired value and true for actual value. Default: false. */
ack: boolean;
/** Unix timestamp. Default: current time */
ts: number;
/** Unix timestamp of the last time the value changed */
lc: number;
/** Name of the adapter instance which set the value, e.g. "system.adapter.web.0" */
from: string;
/** Optional time in seconds after which the state is reset to null */
expire?: number;
/** Optional quality of the state value */
q?: StateQuality;
/** Optional comment */
c?: string;
/** Discriminant property to switch between AbsentState and State<T> */
notExist: undefined;
}
type SettableState = AtLeastOne<State>;
interface AbsentState {
val: null;
notExist: true;
ack: undefined;
ts: undefined;
lc: undefined;
from: undefined;
expire: undefined;
q: undefined;
c: undefined;
}
type Languages = 'en' | 'de' | 'ru' | 'pt' | 'nl' | 'fr' | 'it' | 'es' | 'pl' | 'zh-cn';
type StringOrTranslated = string | { [lang in Languages]?: string; };
type CommonType = "number" | "string" | "boolean" | "array" | "object" | "mixed" | "file";
/** Defines access rights for a single object type */
interface ObjectOperationPermissions {
/** Whether a user may enumerate objects of this type */
list: boolean;
/** Whether a user may read objects of this type */
read: boolean;
/** Whether a user may write objects of this type */
write: boolean;
/** Whether a user may create objects of this type */
create: boolean;
/** Whether a user may delete objects of this type */
delete: boolean;
}
/** Defines the rights a user or group has to change objects */
interface ObjectPermissions {
/** The access rights for files */
file: ObjectOperationPermissions;
/** The access rights for objects */
object: ObjectOperationPermissions;
/** The access rights for users/groups */
users: ObjectOperationPermissions;
/** The access rights for states */
state?: ObjectOperationPermissions;
}
/** Defined the complete set of access rights a user has */
interface PermissionSet extends ObjectPermissions {
/** The name of the user this ACL is for */
user: string;
/** The name of the groups this ACL was merged from */
groups: string[];
/** The access rights for certain commands */
other: {
execute: boolean;
http: boolean;
sendto: boolean;
};
}
interface ObjectACL {
/** Full name of the user who owns this object, e.g. "system.user.admin" */
owner: string;
/** Full name of the group who owns this object, e.g. "system.group.administrator" */
ownerGroup: string;
/** Linux-type permissions defining access to this object */
object: number;
}
/** Defines access rights for a single state object */
interface StateACL extends ObjectACL {
/** Linux-type permissions defining access to this state */
state: number;
}
/** Defines the existing object types in ioBroker */
type ObjectType =
| 'state'
| 'channel'
| 'device'
| 'folder'
| 'enum'
| 'adapter'
| 'config'
| 'group'
| 'host'
| 'instance'
| 'meta'
| 'script'
| 'user'
| 'chart';
// Define the naming schemes for objects so we can provide more specific types for get/setObject
namespace ObjectIDs {
// Guaranteed meta objects
type Meta =
| `${string}.${number}`
| `${string}.${"meta" | "admin"}`
| `${string}.meta.${string}`
| `${string}.${number}.meta.${string}`;
// Unsure, can be folder, device, channel or state
// --> We need this match to avoid matching the more specific types below
type Misc =
| `system.host.${string}.${string}`
| `0_userdata.0.${string}`;
// Guaranteed channel objects
type Channel =
| `script.js.${"common" | "global"}`
| `${string}.${number}.info`;
// Either script or channel object
type ScriptOrChannel = `script.js.${string}`;
// Guaranteed state objects
type State =
| `system.adapter.${string}.${number}.${string}`;
// Guaranteed enum objects
type Enum = `enum.${string}`;
// Guaranteed instance objects
type Instance = `system.adapter.${string}.${number}`;
// Guaranteed adapter objects
type Adapter = `system.adapter.${string}`;
// Guaranteed group objects
type Group = `system.group.${string}`;
// Guaranteed user objects
type User = `system.user.${string}`;
// Guaranteed host objects
type Host = `system.host.${string}`;
// Guaranteed config objects
type Config = `system.${"certificates" | "config" | "repositories"}`;
// Unsure, can be folder, device, channel or state (or whatever an adapter does)
type AdapterScoped =
| `${string}.${number}.${string}`;
/** All possible typed object IDs */
type Any =
| Meta
| Misc
| Channel
| ScriptOrChannel
| State
| Enum
| Instance
| Adapter
| Group
| User
| Host
| Config
| AdapterScoped;
}
type ObjectIdToObjectType<
T extends string,
Read extends "read" | "write" = "read",
O =
// State must come before Adapter or system.adapter.admin.0.foobar will resolve to AdapterObject
T extends ObjectIDs.State ? StateObject :
// Instance and Adapter must come before meta or `system.adapter.admin` will resolve to MetaObject
T extends ObjectIDs.Instance ? InstanceObject :
T extends ObjectIDs.Adapter ? AdapterObject :
T extends ObjectIDs.Channel ? ChannelObject :
T extends ObjectIDs.Meta ? MetaObject :
T extends ObjectIDs.Misc ? AdapterScopedObject :
T extends ObjectIDs.ScriptOrChannel ? (ScriptObject | ChannelObject) :
T extends ObjectIDs.Enum ? EnumObject :
T extends ObjectIDs.Group ? GroupObject :
T extends ObjectIDs.User ? UserObject :
T extends ObjectIDs.Host ? HostObject :
T extends ObjectIDs.Config ? OtherObject & { type: "config" } :
T extends ObjectIDs.AdapterScoped ? AdapterScopedObject :
iobJS.AnyObject
// When reading objects we should be less strict so working with the return type is less of a pain to work with
> = Read extends "read" ? AnyOf<O> : O;
interface ObjectCommon {
/** The name of this object as a simple string or an object with translations */
name: StringOrTranslated;
/** When set to true, this object may not be deleted */
dontDelete?: true;
/** When set to true, this object is only visible when expert mode is turned on in admin */
expert?: true;
// Icon and role aren't defined in SCHEMA.md,
// but they are being used by some adapters
/** Icon for this object */
icon?: string;
/** role of the object */
role?: string;
}
interface StateCommon extends ObjectCommon {
/** Type of this state. See https://github.com/ioBroker/ioBroker/blob/master/doc/SCHEMA.md#state-commonrole for a detailed description */
type?: CommonType;
/** minimum value */
min?: number;
/** maximum value */
max?: number;
/** allowed interval for numeric values */
step?: number;
/** unit of the value */
unit?: string;
/** description of this state */
desc?: StringOrTranslated;
/** if this state is readable */
read: boolean;
/** if this state is writable */
write: boolean;
/** role of the state (used in user interfaces to indicate which widget to choose) */
role: string;
/** the default value */
def?: any;
/** the default status of the ack flag */
defAck?: boolean;
/** Configures this state as an alias for another state */
alias?: {
/** The target state id or two target states used for reading and writing values */
id: string | { read: string; write: string };
/** An optional conversion function when reading, e.g. `"(val − 32) * 5/9"` */
read?: string;
/** An optional conversion function when reading, e.g. `"(val * 9/5) + 32"` */
write?: string;
};
/**
* Dictionary of possible values for this state in the form
* <pre>
* {
* "internal value 1": "displayed value 1",
* "internal value 2": "displayed value 2",
* ...
* }
* </pre>
* In old ioBroker versions, this could also be a string of the form
* "val1:text1;val2:text2" (now deprecated)
*/
states?: Record<string, string> | string;
/** ID of a helper state indicating if the handler of this state is working */
workingID?: string;
/** attached history information */
history?: any;
/** Custom settings for this state */
custom?: Record<string, any>;
/**
* Settings for IOT adapters and how the state should be named in e.g. Alexa.
* The string "ignore" is a special case, causing the state to be ignored.
*/
smartName?: string | ({ [lang in Languages]?: string; } & {
/** Which kind of device this is */
smartType?: string | null;
/** Which value to set when the ON command is issued */
byOn?: string | null;
});
}
interface ChannelCommon extends ObjectCommon {
/** description of this channel */
desc?: string;
// Make it possible to narrow the object type using the custom property
custom?: undefined;
}
interface DeviceCommon extends ObjectCommon {
// TODO: any other definition for device?
// Make it possible to narrow the object type using the custom property
custom?: undefined;
}
interface EnumCommon extends ObjectCommon {
/** The IDs of the enum members */
members?: string[];
// Make it possible to narrow the object type using the custom property
custom?: undefined;
}
interface MetaCommon extends ObjectCommon {
// Meta objects have to additional CommonTypes
type: CommonType | "meta.user" | "meta.folder";
// Make it possible to narrow the object type using the custom property
custom?: undefined;
}
type InstanceMode = 'none' | 'daemon' | 'subscribe' | 'schedule' | 'once' | 'extension';
interface InstanceCommon extends ObjectCommon {
/** The name of the host where this instance is running */
host: string;
enabled: boolean;
/** How and when this instance should be started */
mode: InstanceMode;
// Make it possible to narrow the object type using the custom property
custom?: undefined;
}
interface HostCommon extends ObjectCommon {
/** The display name of this host */
name: string;
title: string;
installedVersion: string; // e.g. 1.2.3 (following semver)
/** The command line of the executable */
cmd: string;
hostname: string;
/** An array of IP addresses this host exposes */
address: string[]; // IPv4 or IPv6
type: 'js-controller';
platform: 'Javascript/Node.js';
// Make it possible to narrow the object type using the custom property
custom?: undefined;
}
interface HostNative {
process: {
title: string;
versions: NodeJS.ProcessVersions;
env: Record<string, string>;
};
os: {
hostname: string,
type: ReturnType<typeof os["type"]>;
platform: ReturnType<typeof os["platform"]>;
arch: ReturnType<typeof os["arch"]>;
release: ReturnType<typeof os["release"]>;
endianness: ReturnType<typeof os["endianness"]>;
tmpdir: ReturnType<typeof os["tmpdir"]>;
};
hardware: {
cpus: ReturnType<typeof os["cpus"]>;
totalmem: ReturnType<typeof os["totalmem"]>;
networkInterfaces: ReturnType<typeof os["networkInterfaces"]>;
};
}
interface UserCommon extends ObjectCommon {
/** The username */
name: string;
/** The hashed password */
password: string;
/** Whether this user is enabled */
enabled: boolean;
// Make it possible to narrow the object type using the custom property
custom?: undefined;
}
interface GroupCommon extends ObjectCommon {
/** The name of this group */
name: string;
/** The users of this group */
members: string[]; // system.user.name, ...
/** The default permissions of this group */
acl: Omit<PermissionSet, "user" | "groups">;
// Make it possible to narrow the object type using the custom property
custom?: undefined;
}
interface ScriptCommon extends ObjectCommon {
name: string;
/** Defines the type of the script, e.g. TypeScript/ts, JavaScript/js or Blockly */
engineType: string;
/** The instance id of the instance which executes this script */
engine: string;
/** The source code of this script */
source: string;
debug: boolean;
verbose: boolean;
/** Whether this script should be executed */
enabled: boolean;
/** Is used to determine whether a script has changed and needs to be recompiled */
sourceHash?: string;
/** If the script uses a compiled language like TypeScript, this contains the compilation output */
compiled?: string;
/** If the script uses a compiled language like TypeScript, this contains the generated declarations (global scripts only) */
declarations?: string;
// Make it possible to narrow the object type using the custom property
custom?: undefined;
}
type WelcomeScreenEntry = string | {
link: string;
name: string;
img: string;
color: string;
};
interface AdapterCommon extends ObjectCommon {
/** Custom attributes to be shown in admin in the object browser */
adminColumns?: any[];
/** Settings for custom Admin Tabs */
adminTab?: {
name?: string;
/** Icon name for FontAwesome */
"fa-icon"?: string;
/** If true, the Tab is not reloaded when the configuration changes */
ignoreConfigUpdate?: boolean;
/** Which URL should be loaded in the tab. Supports placeholders like http://%ip%:%port% */
link?: string;
/** If true, only one instance of this tab will be created for all instances */
singleton?: boolean;
};
allowInit?: boolean;
/** Possible values for the instance mode (if more than one is possible) */
availableModes?: InstanceMode[];
/** Whether this adapter includes custom blocks for Blockly. If true, `admin/blockly.js` must exist. */
blockly?: boolean;
/** Where the adapter will get its data from. Set this together with @see dataSource */
connectionType?: "local" | "cloud";
/** If true, this adapter can be started in compact mode (in the same process as other adpaters) */
compact?: boolean;
/** The directory relative to iobroker-data where the adapter stores the data. Supports the placeholder `%INSTANCE%`. This folder will be backed up and restored automatically. */
dataFolder?: string;
/** How the adapter will mainly receive its data. Set this together with @see connectionType */
dataSource?: "poll" | "push" | "assumption";
/** A record of ioBroker adapters (including "js-controller") and version ranges which are required for this adapter. */
dependencies?: Array<Record<string, string>>;
/** Which files outside of the README.md have documentation for the adapter */
docs?: Partial<Record<Languages, string | string[]>>;
/** Whether new instances should be enabled by default. *Should* be `false`! */
enabled: boolean;
/** If true, all previous data in the target directory (web) should be deleted before uploading */
eraseOnUpload?: boolean;
/** URL of an external icon that is shown for adapters that are not installed */
extIcon?: string;
/** Whether this adapter responds to `getHistory` messages */
getHistory?: boolean;
/** Filename of the local icon which is shown for installed adapters. Should be located in the `admin` directory */
icon?: string;
/** Which version of this adapter is installed */
installedVersion: string;
keywords?: string[];
/** A dictionary of links to web services this adapter provides */
localLinks?: Record<string, string>;
/** @deprecated Use @see localLinks */
localLink?: string;
logLevel?: LogLevel;
/** Whether this adapter receives logs from other hosts and adapters (e.g. to strore them somewhere) */
logTransporter?: boolean;
/** Path to the start file of the adapter. Should be the same as in `package.json` */
main?: string;
/** Whether the admin tab is written in materialize style. Required for Admin 3+ */
materializeTab: boolean;
/** Whether the admin configuration dialog is written in materialize style. Required for Admin 3+ */
materialize: boolean;
/** If `true`, the object `system.adapter.<adaptername>.<adapterinstance>.messagebox will be created to send messages to the adapter (used for email, pushover, etc...) */
messagebox?: true;
mode: InstanceMode;
/** Name of the adapter (without leading `ioBroker.`) */
name: string;
/** If `true`, no configuration dialog will be shown */
noConfig?: true;
/** If `true`, this adapter's instances will not be shown in the admin overview screen. Useful for icon sets and widgets... */
noIntro?: true;
/** Set to `true` if the adapter is not available in the official ioBroker repositories. */
noRepository?: true;
/** If `true`, manual installation from GitHub is not possible */
nogit?: true;
/** If `true`, this adapter cannot be deleted or updated manually. */
nondeletable?: true;
/** If `true`, this "adapter" only contains HTML files and no main executable */
onlyWWW?: boolean;
/** Used to configure native (OS) dependencies of this adapter that need to be installed with system package manager before installing the adapter */
osDependencies?: {
/** For OSX */
darwin: string[];
/** For Linux */
linux: string[];
/** For Windows */
win32: string[];
};
/** Which OSes this adapter supports */
os?: "linux" | "darwin" | "win32" | Array<("linux" | "darwin" | "win32")>;
platform: "Javascript/Node.js";
/** The keys of common attributes (e.g. `history`) which are not deleted in a `setObject` call even if they are not present. Deletion must be done explicitly by setting them to `null`. */
preserveSettings?: string | string[];
/** Which adapters must be restarted after installing or updating this adapter. */
restartAdapters?: string[];
/** If the adapter runs in `schedule` mode, this contains the CRON */
schedule?: string;
serviceStates?: boolean | string;
/** Whether this adapter may only be installed once per host */
singletonHost?: boolean;
/** Whether this adapter may only be installed once in the whole system */
singleton?: boolean;
/** Whether the adapter must be stopped before an update */
stopBeforeUpdate?: boolean;
/** Overrides the default timeout that ioBroker will wait before force-stopping the adapter */
stopTimeout?: number;
subscribable?: boolean;
subscribe?: any; // ?
/** If `true`, this adapter provides custom per-state settings. Requires a `custom_m.html` file in the `admin` directory. */
supportCustoms?: boolean;
/** Whether the adapter supports the signal stopInstance via messagebox */
supportStopInstance?: boolean;
/** The translated names of this adapter to be shown in the admin UI */
titleLang?: Record<Languages, string>;
/** @deprecated The name of this adapter to be shown in the admin UI. Use @see titleLang instead. */
title?: string;
/** The type of this adapter */
type?: string;
/** If `true`, the `npm` package must be installed with the `--unsafe-perm` flag */
unsafePerm?: true;
/** The available version in the ioBroker repo. */
version: string;
/** If `true`, the adapter will be started if any value is written into `system.adapter.<name>.<instance>.wakeup. Normally the adapter should stop after processing the event. */
wakeup?: boolean;
/** Include the adapter version in the URL of the web adapter, e.g. `http://ip:port/1.2.3/material` instead of `http://ip:port/material` */
webByVersion?: boolean;
/** Whether the web server in this adapter can be extended with plugin/extensions */
webExtendable?: boolean;
/** Relative path to a module that contains an extension for the web adapter. Use together with @see native.webInstance to configure which instances this affects */
webExtension?: string;
webPreSettings?: any; // ?
webservers?: any; // ?
/** A list of pages that should be shown on the "web" index page */
welcomeScreen?: WelcomeScreenEntry[];
/** A list of pages that should be shown on the ioBroker cloud index page */
welcomeScreenPro?: WelcomeScreenEntry[];
wwwDontUpload?: boolean;
// Make it possible to narrow the object type using the custom property
custom?: undefined;
}
interface OtherCommon extends ObjectCommon {
[propName: string]: any;
// Make it possible to narrow the object type using the custom property
custom?: undefined;
}
/* Base type for Objects. Should not be used directly */
interface BaseObject {
/** The ID of this object */
_id: string;
type: ObjectType; // specified in the derived interfaces
// Ideally we would limit this to JSON-serializable objects, but TypeScript doesn't allow this
// without bugging users to change their code --> https://github.com/microsoft/TypeScript/issues/15300
native: Record<string, any>;
common: Record<string, any>;
enums?: Record<string, string>;
acl?: ObjectACL;
from?: string;
/** The user who created or updated this object */
user?: string;
ts?: number;
}
interface StateObject extends BaseObject {
type: 'state';
common: StateCommon;
acl?: StateACL;
}
interface PartialStateObject extends Partial<Omit<StateObject, 'common' | 'acl'>> {
common?: Partial<StateCommon>;
acl?: Partial<StateACL>;
}
interface ChannelObject extends BaseObject {
type: 'channel';
common: ChannelCommon;
}
interface PartialChannelObject
extends Partial<Omit<ChannelObject, 'common'>> {
common?: Partial<ChannelCommon>;
}
interface DeviceObject extends BaseObject {
type: 'device';
common: DeviceCommon;
}
interface PartialDeviceObject extends Partial<Omit<DeviceObject, 'common'>> {
common?: Partial<DeviceCommon>;
}
interface FolderObject extends BaseObject {
type: 'folder';
// Nothing is set in stone here, so start with allowing every property
common: OtherCommon;
}
interface PartialFolderObject extends Partial<Omit<FolderObject, 'common'>> {
common?: Partial<OtherCommon>;
}
interface EnumObject extends BaseObject {
type: 'enum';
common: EnumCommon;
}
interface PartialEnumObject extends Partial<Omit<EnumObject, 'common'>> {
common?: Partial<EnumCommon>;
}
interface MetaObject extends BaseObject {
type: 'meta';
common: MetaCommon;
}
interface PartialMetaObject extends Partial<Omit<MetaObject, 'common'>> {
common?: Partial<MetaCommon>;
}
interface InstanceObject extends BaseObject {
type: 'instance';
common: InstanceCommon;
}
interface PartialInstanceObject extends Partial<Omit<InstanceObject, 'common'>> {
common?: Partial<InstanceCommon>;
}
interface AdapterObject extends BaseObject {
type: 'adapter';
common: AdapterCommon;
/** An array of `native` properties which cannot be accessed from outside the defining adapter */
protectedNative?: string[];
/** Like protectedNative, but the properties are also encrypted and decrypted automatically */
encryptedNative?: string[];
}
interface PartialAdapterObject extends Partial<Omit<AdapterObject, 'common'>> {
common?: Partial<AdapterCommon>;
}
interface HostObject extends BaseObject {
type: 'host';
common: HostCommon;
native: HostNative;
}
interface PartialHostObject extends Partial<Omit<HostObject, 'common' | 'native'>> {
common?: Partial<HostCommon>;
native?: Partial<HostNative>;
}
interface UserObject extends BaseObject {
type: 'user';
common: UserCommon;
}
interface PartialUserObject extends Partial<Omit<UserObject, 'common'>> {
common?: Partial<UserCommon>;
}
interface GroupObject extends BaseObject {
type: 'group';
common: GroupCommon;
}
interface PartialGroupObject extends Partial<Omit<GroupObject, 'common'>> {
common?: Partial<GroupCommon>;
}
interface ScriptObject extends BaseObject {
type: 'script';
common: ScriptCommon;
}
interface PartialScriptObject extends Partial<Omit<ScriptObject, 'common'>> {
common?: Partial<ScriptCommon>;
}
interface OtherObject extends BaseObject {
type: 'config' | 'chart';
common: OtherCommon;
}
interface PartialOtherObject extends Partial<Omit<OtherObject, 'common'>> {
common?: Partial<OtherCommon>;
}
type AnyObject =
| StateObject
| ChannelObject
| DeviceObject
| FolderObject
| EnumObject
| MetaObject
| HostObject
| AdapterObject
| InstanceObject
| UserObject
| GroupObject
| ScriptObject
| OtherObject;
type AnyPartialObject =
| PartialStateObject
| PartialChannelObject
| PartialDeviceObject
| PartialFolderObject
| PartialEnumObject
| PartialMetaObject
| PartialHostObject
| PartialAdapterObject
| PartialInstanceObject
| PartialUserObject
| PartialGroupObject
| PartialScriptObject
| PartialOtherObject;
/** All objects that usually appear in an adapter scope */
type AdapterScopedObject = FolderObject | DeviceObject | ChannelObject | StateObject;
// For all objects that are exposed to the user we need to tone the strictness down.
// Otherwise, every operation on objects becomes a pain to work with
type Object = AnyObject;
// In set[Foreign]Object[NotExists] methods, the ID and acl of the object is optional
type SettableObjectWorker<T> = T extends AnyObject ? Omit<T, '_id' | 'acl'> & {
_id?: T['_id'];
acl?: T['acl'];
} : never;
// in extend[Foreign]Object, most properties are optional
type PartialObjectWorker<T> = T extends AnyObject ? AnyPartialObject & { type?: T["type"] } : never;
type PartialObject<T extends AnyObject = AnyObject> = PartialObjectWorker<T>;
// Convenient definitions for manually specifying settable object types
type SettableObject<T extends AnyObject = AnyObject> = SettableObjectWorker<T>;
type SettableStateObject = SettableObject<StateObject>;
type SettableChannelObject = SettableObject<ChannelObject>;
type SettableDeviceObject = SettableObject<DeviceObject>;
type SettableFolderObject = SettableObject<FolderObject>;
type SettableEnumObject = SettableObject<EnumObject>;
type SettableMetaObject = SettableObject<MetaObject>;
type SettableHostObject = SettableObject<HostObject>;
type SettableAdapterObject = SettableObject<AdapterObject>;
type SettableInstanceObject = SettableObject<InstanceObject>;
type SettableUserObject = SettableObject<UserObject>;
type SettableGroupObject = SettableObject<GroupObject>;
type SettableScriptObject = SettableObject<ScriptObject>;
type SettableOtherObject = SettableObject<OtherObject>;
/** Represents the change of a state */
interface ChangedStateObject<TOld extends StateValue = any, TNew extends StateValue = TOld> extends StateObject {
common: StateCommon;
native: Record<string, any>;
id?: string;
name?: string;
channelId?: string;
channelName?: string;
deviceId?: string;
deviceName?: string;
/** The IDs of enums this state is assigned to. For example ["enum.functions.Licht","enum.rooms.Garten"] */
enumIds?: string[];
/** The names of enums this state is assigned to. For example ["Licht","Garten"] */
enumNames?: string[];
/** new state */
state: State<TNew>;
/** @deprecated Use state instead **/
newState: State<TNew>;
/** previous state */
oldState: State<TOld>;
/** Name of the adapter instance which set the value, e.g. "system.adapter.web.0" */
from?: string;
/** Unix timestamp. Default: current time */
ts?: number;
/** Unix timestamp of the last time the value changed */
lc?: number;
/** Direction flag: false for desired value and true for actual value. Default: false. */
ack?: boolean;
}
type GetStateCallback<T extends StateValue = any> = (err?: string | null, state?: State<T> | AbsentState) => void | Promise<void>;
type ExistsStateCallback = (err?: string | null, exists?: Boolean) => void | Promise<void>;
type GetBinaryStateCallback = (err?: string | null, state?: Buffer) => void | Promise<void>;
type GetBinaryStatePromise = Promise<NonNullCallbackReturnTypeOf<GetBinaryStateCallback>>;
type SetStateCallback = (err?: string | null, id?: string) => void | Promise<void>;
type SetStatePromise = Promise<NonNullCallbackReturnTypeOf<SetStateCallback>>;
type StateChangeHandler<TOld extends StateValue = any, TNew extends TOld = any> = (obj: ChangedStateObject<TOld, TNew>) => void | Promise<void>;
type SetObjectCallback = (err?: string | null, obj?: { id: string }) => void | Promise<void>;
type SetObjectPromise = Promise<NonNullCallbackReturnTypeOf<SetObjectCallback>>;
type GetObjectCallback<T extends string = string> = (err?: string | null, obj?: ObjectIdToObjectType<T> | null) => void;
type GetObjectPromise<T extends string = string> = Promise<CallbackReturnTypeOf<GetObjectCallback<T>>>;
type LogLevel = "silly" | "debug" | "info" | "warn" | "error" | "force";
type ReadFileCallback = (err?: string | null, file?: Buffer | string, mimeType?: string) => void | Promise<void>;
type ReadFilePromise = Promise<NonNullCallbackReturnTypeOf<ReadFileCallback>>;
/** Callback information for a passed message */
interface MessageCallbackInfo {
/** The original message payload */
message: string | object;
/** ID of this callback */
id: number;
// ???
ack: boolean;
/** Timestamp of this message */
time: number;
}
type MessageCallback = (result?: any) => void | Promise<void>;
interface Subscription {
name: string;
pattern: string | RegExp | string[] | iobJS.SubscribeOptions | iobJS.SubscribeTime | iobJS.AstroSchedule;
}
interface SubscribeOptions {
/** "and" or "or" logic to combine the conditions (default: "and") */
logic?: "and" | "or";
/** name is equal or matches to given one or name marches to any item in given list */
id?: string | string[] | SubscribeOptions[] | RegExp | RegExp[];
/** name is equal or matches to given one */
name?: string | string[] | RegExp;
/** type of change */
change?: "eq" | "ne" | "gt" | "ge" | "lt" | "le" | "any";
val?: StateValue;
/** New value must not be equal to given one */
valNe?: StateValue;
/** New value must be greater than given one */
valGt?: number;
/** New value must be greater or equal to given one */
valGe?: number;
/** New value must be smaller than given one */
valLt?: number;
/** New value must be smaller or equal to given one */
valLe?: number;
/** Acknowledged state of new value is equal to given one */
ack?: boolean;
/** Previous value must be equal to given one */
oldVal?: StateValue;
/** Previous value must be not equal to given one */
oldValNe?: StateValue;
/** Previous value must be greater than given one */
oldValGt?: number;
/** Previous value must be greater or equal given one */
oldValGe?: number;
/** Previous value must be smaller than given one */
oldValLt?: number;
/** Previous value must be smaller or equal to given one */
oldValLe?: number;
/** Acknowledged state of previous value is equal to given one */
oldAck?: boolean;
/** New value time stamp must be equal to given one (state.ts == ts) */
ts?: number;
/** New value time stamp must be not equal to the given one (state.ts != ts) */
tsGt?: number;
/** New value time stamp must be greater than given value (state.ts > ts) */
tsGe?: number;
/** New value time stamp must be greater or equal to given one (state.ts >= ts) */
tsLt?: number;
/** New value time stamp must be smaller than given one (state.ts < ts) */
tsLe?: number;
/** Previous time stamp must be equal to given one (oldState.ts == ts) */
oldTs?: number;
/** Previous time stamp must be not equal to the given one (oldState.ts != ts) */
oldTsGt?: number;
/** Previous time stamp must be greater than given value (oldState.ts > ts) */
oldTsGe?: number;
/** Previous time stamp must be greater or equal to given one (oldState.ts >= ts) */
oldTsLt?: number;
/** Previous time stamp must be smaller than given one (oldState.ts < ts) */
oldTsLe?: number;
/** Last change time stamp must be equal to given one (state.lc == lc) */
lc?: number;
/** Last change time stamp must be not equal to the given one (state.lc != lc) */
lcGt?: number;
/** Last change time stamp must be greater than given value (state.lc > lc) */
lcGe?: number;
/** Last change time stamp must be greater or equal to given one (state.lc >= lc) */
lcLt?: number;
/** Last change time stamp must be smaller than given one (state.lc < lc) */
lcLe?: number;
/** Previous last change time stamp must be equal to given one (oldState.lc == lc) */
oldLc?: number;
/** Previous last change time stamp must be not equal to the given one (oldState.lc != lc) */
oldLcGt?: number;
/** Previous last change time stamp must be greater than given value (oldState.lc > lc) */
oldLcGe?: number;
/** Previous last change time stamp must be greater or equal to given one (oldState.lc >= lc) */
oldLcLt?: number;
/** Previous last change time stamp must be smaller than given one (oldState.lc < lc) */
oldLcLe?: number;
/** Channel ID must be equal or match to given one */
channelId?: string | string[] | RegExp;
/** Channel name must be equal or match to given one */
channelName?: string | string[] | RegExp;
/** Device ID must be equal or match to given one */
deviceId?: string | string[] | RegExp;
/** Device name must be equal or match to given one */
deviceName?: string | string[] | RegExp;
/** State belongs to given enum or one enum ID of state satisfy the given regular expression */
enumId?: string | string[] | RegExp;
/** State belongs to given enum or one enum name of state satisfy the given regular expression */
enumName?: string | string[] | RegExp;
/** New value is from defined adapter */
from?: string | string[] | RegExp;
/** New value is not from defined adapter */
fromNe?: string | string[] | RegExp;
/** Old value is from defined adapter */
oldFrom?: string | string[] | RegExp;
/** Old value is not from defined adapter */
oldFromNe?: string | string[] | RegExp;
}
interface QueryResult extends Iterable<string> {
/** State-ID */
[index: number]: string;
/** Number of matched states */
length: number;
/** Contains the error if one happened */
error?: string;
/**
* Executes a function for each state id in the result array
* The execution is canceled if a callback returns false
*/
each(callback?: (id: string, index: number) => boolean | void | Promise<void>): this;
/**
* Returns the first state found by this query.
* If the adapter is configured to subscribe to all states on start,
* this can be called synchronously and immediately returns the state.
* Otherwise you need to provide a callback.
*/
getState<T extends StateValue = any>(callback: GetStateCallback<T>): void;
getState<T extends StateValue = any>(): State<T> | null | undefined;
getStateAsync<T extends StateValue = any>(): Promise<State<T> | null | undefined>;
/**
* Returns the first state found by this query.
* If the adapter is configured to subscribe to all states on start,
* this can be called synchronously and immediately returns the state.
* Otherwise you need to provide a callback.
*/
getBinaryState(callback: GetBinaryStateCallback): void;
getBinaryState(): Buffer | null | undefined;
getBinaryStateAsync(): Promise<Buffer | null | undefined>;
/**
* Sets all queried states to the given value.
*/
setState(state: State | StateValue | SettableState, ack?: boolean, callback?: SetStateCallback): this;
setStateAsync(state: State | StateValue | SettableState, ack?: boolean): Promise<void>;
/**
* Sets all queried binary states to the given value.
*/
setBinaryState(state: Buffer, ack?: boolean, callback?: SetStateCallback): this;
setBinaryStateAsync(state: Buffer, ack?: boolean): Promise<void>;
/**
* Subscribes the given callback to changes of the matched states.
*/
on(callback: StateChangeHandler): this;
}
/**
* * "sunrise": sunrise (top edge of the sun appears on the horizon)
* * "sunriseEnd": sunrise ends (bottom edge of the sun touches the horizon)
* * "goldenHourEnd": morning golden hour (soft light, best time for photography) ends
* * "solarNoon": solar noon (sun is in the highest position)
* * "goldenHour": evening golden hour starts
* * "sunsetStart": sunset starts (bottom edge of the sun touches the horizon)
* * "sunset": sunset (sun disappears below the horizon, evening civil twilight starts)
* * "dusk": dusk (evening nautical twilight starts)
* * "nauticalDusk": nautical dusk (evening astronomical twilight starts)
* * "night": night starts (dark enough for astronomical observations)
* * "nightEnd": night ends (morning astronomical twilight starts)
* * "nauticalDawn": nautical dawn (morning nautical twilight starts)
* * "dawn": dawn (morning nautical twilight ends, morning civil twilight starts)
* * "nadir": nadir (darkest moment of the night, sun is in the lowest position)
*/
type AstroPattern = "sunrise" | "sunriseEnd" | "goldenHourEnd" | "solarNoon" | "goldenHour" | "sunsetStart" | "sunset" | "dusk" | "nauticalDusk" | "night" | "nightEnd" | "nauticalDawn" | "dawn" | "nadir";
interface AstroSchedule {
astro: AstroPattern;
/**
* Shift to the astro schedule.
*/
shift?: number;
}
interface AstroDate {
astro: AstroPattern;
/** Offset to the astro event in minutes */
offset?: number;
/** Date for which the astro time is wanted */
date?: Date;
}
/**
* from https://github.com/node-schedule/node-schedule
*/
interface ScheduleRule {
/**
* Day of the month.
*/
date?: number | number[] | string | string[];
/**
* Day of the week.
*/
dayOfWeek?: number | number[] | string | string[];
/**
* Hour.
*/
hour?: number | number[] | string | string[];
/**
* Minute.
*/
minute?: number | number[] | string | string[];
/**
* Month.
*/
month?: number | number[] | string | string[];
/**
* Second.
*/
second?: number | number[] | string | string[];
/**
* Year.
*/
year?: number | number[] | string | string[];
/**
* timezone which should be used
* https://github.com/moment/moment-timezone
*/
tz?: string;
}
/**
* from https://github.com/node-schedule/node-schedule
*/
interface ScheduleRuleConditional {
/**
* set a start time for schedule
* a Data object or a dateString resp a number in milliseconds which can create a Date object
*/
start?: Date | string | number;
/**
* set an end time for schedule
* a Data object or a dateString resp a number in milliseconds which can create a Date object
*/
end?: Date | string | number;
/**
* timezone which should be used
* https://github.com/moment/moment-timezone
*/
tz?: string;
/**
* scheduling rule
* schedule rule, a Data object or a dateString resp a number in milliseconds which can create a Date object
*/
rule: ScheduleRule | Date | string | number;
}
interface LogMessage {
severity: LogLevel; // severity
ts: number; // timestamp as Date.now()
message: string; // message
from: string; // origin of the message
}
type SchedulePattern = ScheduleRule | ScheduleRuleConditional | Date | string | number;
interface SubscribeTime {
time: SchedulePattern;
}
interface StateTimer {
id: number;
left: number;
delay: number;
val: any;
ack: boolean;
}
type MessageSubscribeID = number;
interface MessageTarget {
/** Javascript Instance */
instance?: string;
/** Script name */
script?: string;
/** Message name */
message: string;
}
} // end namespace iobJS
// =======================================================
// available functions in the sandbox
// =======================================================
// The already pre-loaded request module
const request: typeof import("request");
/**
* The instance number of the JavaScript adapter this script runs in
*/
const instance: number;
/**
* The name of the current script
*/
// @ts-ignore We need this variable although it conflicts with lib.es6
const name: string;
/**
* The name of the current script
*/
const scriptName: string;
/**
* Queries all states with the given selector
* @param selector See @link{https://github.com/ioBroker/ioBroker.javascript#---selector} for a description
*/
function $(selector: string): iobJS.QueryResult;
/**
* Prints a message in the ioBroker log
* @param message The message to print
* @param severity (optional) severity of the message. default = "info"
*/
function log(message: string, severity?: iobJS.LogLevel): void;
// console functions
// @ts-ignore We need this variable although it conflicts with the node typings
namespace console {
/** log message with debug level */
function debug(message: string): void;
/** log message with info level (default output level for all adapters) */
function info(message: string): void;
/** log message with warning severity */
function warn(message: string): void;
/** log message with error severity */
function error(message: string): void;
}
/**
* Executes a system command
*/
function exec(command: string, callback?: (err: Error | null | undefined, stdout: string, stderr: string) => void | Promise<void>): child_process.ChildProcess;
/**
* Sends an email using the email adapter.
* See the adapter documentation for a description of the msg parameter.
*/
function email(msg: any): void;
/**
* Sends a pushover message using the pushover adapter.
* See the adapter documentation for a description of the msg parameter.
*/
function pushover(msg: any): void;
/**
* Subscribe to changes of the matched states.
*/
function on(pattern: string | RegExp | string[], handler: iobJS.StateChangeHandler): any;
function on(
astroOrScheduleOrOptions: iobJS.AstroSchedule | iobJS.SubscribeTime | iobJS.SubscribeOptions,
handler: iobJS.StateChangeHandler
): any;
/**
* Subscribe to changes of the matched states.
*/
function subscribe(pattern: string | RegExp | string[], handler: iobJS.StateChangeHandler): any;
function subscribe(
astroOrScheduleOrOptions: iobJS.AstroSchedule | iobJS.SubscribeTime | iobJS.SubscribeOptions,
handler: iobJS.StateChangeHandler
): any;
/**
* Registers a one-time subscription which automatically unsubscribes after the first invocation
*/
function once(
pattern: string | RegExp | string[] | iobJS.AstroSchedule | iobJS.SubscribeTime | iobJS.SubscribeOptions,
handler: iobJS.StateChangeHandler
): any;
function once(
pattern: string | RegExp | string[] | iobJS.AstroSchedule | iobJS.SubscribeTime | iobJS.SubscribeOptions
): Promise<iobJS.ChangedStateObject>;
/**
* Causes all changes of the state with id1 to the state with id2.
* The return value can be used to unsubscribe later
*/
function on(id1: string, id2: string): any;
/**
* Watches the state with id1 for changes and overwrites the state with id2 with value2 when any occur.
* @param id1 The state to watch for changes
* @param id2 The state to update when changes occur
* @param value2 The value to write into state `id2` when `id1` gets changed
*/
function on(id1: string, id2: string, value2: any): any;
/**
* Causes all changes of the state with id1 to the state with id2
*/
function subscribe(id1: string, id2: string): any;
/**
* Watches the state with id1 for changes and overwrites the state with id2 with value2 when any occur.
* @param id1 The state to watch for changes
* @param id2 The state to update when changes occur
* @param value2 The value to write into state `id2` when `id1` gets changed
*/
function subscribe(id1: string, id2: string, value2: any): any;
/**
* Returns the list of all currently active subscriptions
*/
function getSubscriptions(): { [id: string]: iobJS.Subscription[] };
/**
* Unsubscribe from changes of the given object ID(s) or handler(s)
*/
function unsubscribe(id: string | string[]): boolean;
function unsubscribe(handler: any | any[]): boolean;
function adapterSubscribe(id: string): void;
function adapterUnsubscribe(id: string): void;
/**
* Schedules a function to be executed on a defined schedule.
* The return value can be used to clear the schedule later.
*/
function schedule(pattern: string | iobJS.SchedulePattern, callback: EmptyCallback): any;
function schedule(date: Date, callback: EmptyCallback): any;
function schedule(astro: iobJS.AstroSchedule, callback: EmptyCallback): any;
/**
* Clears a schedule. Returns true if it was successful.
*/
function clearSchedule(schedule: any): boolean;
/**
* Calculates the astro time which corresponds to the given pattern.
* For valid patterns, see @link{https://github.com/ioBroker/ioBroker.javascript#astro--function}
* @param date (optional) The date for which the astro time should be calculated. Default = today
* @param offsetMinutes (optional) The amount of minutes to be added to the return value.
*/
function getAstroDate(pattern: string, date?: Date | number, offsetMinutes?: number): Date;
/**
* Determines if now is between sunrise and sunset.
*/
function isAstroDay(): boolean;
/**
* Sets a state to the given value
* @param id The ID of the state to be set
*/
function setState(id: string, state: iobJS.State | iobJS.StateValue | iobJS.SettableState, callback?: iobJS.SetStateCallback): void;
function setState(id: string, state: iobJS.State | iobJS.StateValue | iobJS.SettableState, ack: boolean, callback?: iobJS.SetStateCallback): void;
function setStateAsync(id: string, state: iobJS.State | iobJS.StateValue | iobJS.SettableState, ack?: boolean): iobJS.SetStatePromise;
/**
* Sets a state to the given value after a timeout has passed.
* Returns the timer so it can be manually cleared with clearStateDelayed
* @param id The ID of the state to be set
* @param delay The delay in milliseconds
* @param clearRunning (optional) Whether an existing timeout for this state should be cleared
* @returns If a delayed setState was scheduled, this returns the timer id, otherwise null.
*/
function setStateDelayed(id: string, state: iobJS.State | iobJS.StateValue | iobJS.SettableState, delay: number, clearRunning: boolean, callback?: iobJS.SetStateCallback): number | null;
function setStateDelayed(id: string, state: iobJS.State | iobJS.StateValue | iobJS.SettableState, ack: boolean, clearRunning: boolean, callback?: iobJS.SetStateCallback): number | null;
function setStateDelayed(id: string, state: iobJS.State | iobJS.StateValue | iobJS.SettableState, ack: boolean, delay: number, callback?: iobJS.SetStateCallback): number | null;
function setStateDelayed(id: string, state: iobJS.State | iobJS.StateValue | iobJS.SettableState, delay: number, callback?: iobJS.SetStateCallback): number | null;
function setStateDelayed(id: string, state: iobJS.State | iobJS.StateValue | iobJS.SettableState, callback?: iobJS.SetStateCallback): number | null;
function setStateDelayed(id: string, state: iobJS.State | iobJS.StateValue | iobJS.SettableState, ack: boolean, delay: number, clearRunning: boolean, callback?: iobJS.SetStateCallback): number | null;
/**
* Clears a timer created by setStateDelayed
* @param id The state id for which the timer should be cleared
* @param timerID (optional) ID of the specific timer to clear. If none is given, all timers are cleared.
*/
function clearStateDelayed(id: string, timerID?: number): boolean;
/**
* Returns information about a specific timer created with `setStateDelayed`.
* @param timerId The timer id that was returned by `setStateDelayed`.
*/
function getStateDelayed(timerId: number): iobJS.StateTimer | null;
/**
* Returns a list of all timers created with `setStateDelayed`. Can be limited to a specific state id.
* @param id The state id for which the timers should be.
*/
function getStateDelayed(id?: string): iobJS.StateTimer[];
/**
* Sets a binary state to the given value
* @param id The ID of the state to be set
*/
function setBinaryState(id: string, state: Buffer, callback?: iobJS.SetStateCallback): void;
function setBinaryStateAsync(id: string, state: Buffer): iobJS.SetStatePromise;
/**
* Returns the state with the given ID.
* If the adapter is configured to subscribe to all states on start,
* this can be called synchronously and immediately returns the state.
* Otherwise you need to provide a callback.
*/
function getState<T extends iobJS.StateValue = any>(id: string, callback: iobJS.GetStateCallback<T>): void;
function getState<T extends iobJS.StateValue = any>(id: string): iobJS.State<T> | iobJS.AbsentState;
function getStateAsync<T extends iobJS.StateValue = any>(id: string): Promise<iobJS.State<T>>;
/**
* Returns the binary state with the given ID.
* If the adapter is configured to subscribe to all states on start,
* this can be called synchronously and immediately returns the state.
* Otherwise you need to provide a callback.
*/
function getBinaryState(id: string, callback: iobJS.GetStateCallback): void;
function getBinaryState(id: string): Buffer;
function getBinaryStateAsync(id: string): iobJS.GetBinaryStatePromise;
/**
* Checks if the state with the given ID exists
*/
function existsState(id: string, callback: iobJS.ExistsStateCallback): void;
function existsState(id: string): boolean;
function existsStateAsync(id: string): Promise<boolean>;
/**
* Checks if the object with the given ID exists
*/
function existsObject(id: string): boolean;
function existsObjectAsync(id: string): Promise<boolean>;
/**
* Returns the IDs of the states with the given name
* @param name Name of the state
* @param forceArray (optional) Ensures that the return value is always an array, even if only one ID was found.
*/
function getIdByName(name: string, forceArray?: boolean): string | string[];
/**
* Reads an object from the object db.
* @param enumName Which enum should be included in the returned object. `true` to return all enums.
*/
function getObject<T extends string>(id: T, enumName?: string | true): iobJS.ObjectIdToObjectType<T, "read">;
function getObject<T extends string>(id: T, callback: iobJS.GetObjectCallback<T>): void;
function getObject<T extends string>(id: T, enumName: string | true, callback: iobJS.GetObjectCallback<T>): void;
function getObjectAsync<T extends string>(id: T, enumName?: string | true): iobJS.GetObjectPromise<T>;
/** Creates or overwrites an object in the object db */
function setObject(id: string, obj: iobJS.SettableObject, callback?: iobJS.SetObjectCallback): void;
function setObjectAsync(id: string, obj: iobJS.SettableObject): iobJS.SetObjectPromise;
/** Extend an object and create it if it might not exist */
function extendObject(id: string, objPart: iobJS.PartialObject, callback?: iobJS.SetObjectCallback): void;
function extendObjectAsync(id: string, objPart: iobJS.PartialObject): iobJS.SetObjectPromise;
/** Deletes an object in the object db */
function deleteObject(id: string, callback?: ErrorCallback): void;
function deleteObject(id: string, recursive: boolean, callback?: ErrorCallback): void;
function deleteObjectAsync(id: string, recursive?: boolean): Promise<void>;
function getEnums(enumName?: string): any;
/**
* Creates a state and the corresponding object under the javascript namespace.
* @param name The name of the state without the namespace
* @param initValue (optional) Initial value of the state
* @param forceCreation (optional) Override the state if it already exists
* @param common (optional) Common part of the state object
* @param native (optional) Native part of the state object
* @param callback (optional) Called after the state was created
*/
function createState(name: string, callback?: iobJS.SetStateCallback): void;
function createState(name: string, initValue: iobJS.StateValue, callback?: iobJS.SetStateCallback): void;
function createState(name: string, initValue: iobJS.StateValue, forceCreation: boolean, callback?: iobJS.SetStateCallback): void;
function createState(name: string, initValue: iobJS.StateValue, forceCreation: boolean, common: Partial<iobJS.StateCommon>, callback?: iobJS.SetStateCallback): void;
function createState(name: string, initValue: iobJS.StateValue, forceCreation: boolean, common: Partial<iobJS.StateCommon>, native: any, callback?: iobJS.SetStateCallback): void;
function createState(name: string, common: Partial<iobJS.StateCommon>, callback?: iobJS.SetStateCallback): void;
function createState(name: string, initValue: iobJS.StateValue, common: Partial<iobJS.StateCommon>, callback?: iobJS.SetStateCallback): void;
function createState(name: string, common: Partial<iobJS.StateCommon>, native: any, callback?: iobJS.SetStateCallback): void;
function createState(name: string, initValue: iobJS.StateValue, common: Partial<iobJS.StateCommon>, native: any, callback?: iobJS.SetStateCallback): void;
function createStateAsync(name: string, initValue?: iobJS.StateValue, forceCreation?: boolean, common?: Partial<iobJS.StateCommon>, native?: any): iobJS.SetStatePromise;
function createStateAsync(name: string, common: Partial<iobJS.StateCommon>): iobJS.SetStatePromise;
function createStateAsync(name: string, common: Partial<iobJS.StateCommon>, native?: any): iobJS.SetStatePromise;
function createStateAsync(name: string, initValue: iobJS.StateValue, common: Partial<iobJS.StateCommon>): iobJS.SetStatePromise;
function createStateAsync(name: string, initValue: iobJS.StateValue, common: Partial<iobJS.StateCommon>, native?: any): iobJS.SetStatePromise;
/**
* Deletes the state with the given ID
* @param callback (optional) Is called after the state was deleted (or not).
*/
function deleteState(id: string, callback?: GenericCallback<boolean>): void;
function deleteStateAsync(id: string): Promise<boolean>;
/**
* Sends a message to a specific instance or all instances of some specific adapter.
* @param instanceName The instance to send this message to.
* If the ID of an instance is given (e.g. "admin.0"), only this instance will receive the message.
* If the name of an adapter is given (e.g. "admin"), all instances of this adapter will receive it.
* @param command (optional) Command name of the target instance. Default: "send"
* @param message The message (e.g. params) to send.
*/
function sendTo(instanceName: string, message: string | object, callback?: iobJS.MessageCallback | iobJS.MessageCallbackInfo): void;
function sendTo(instanceName: string, command: string, message: string | object, callback?: iobJS.MessageCallback | iobJS.MessageCallbackInfo): void;
type CompareTimeOperations =
"between" | "not between" |
">" | ">=" | "<" | "<=" | "==" | "<>"
;
/**
* Compares two or more times
* @param timeToCompare - The time to compare with startTime and/or endTime. If none is given, the current time is used
*/
function compareTime(
startTime: string | number | Date | iobJS.AstroDate,
endTime: string | number | Date | iobJS.AstroDate,
operation: CompareTimeOperations,
timeToCompare?: string | number | Date | iobJS.AstroDate,
): boolean;
/** Sets up a callback which is called when the script stops */
function onStop(callback: (cb?: EmptyCallback) => void, timeout?: number): void;
function formatValue(value: number | string, format?: any): string;
function formatValue(value: number | string, decimals: number, format?: any): string;
function formatDate(dateObj: string | Date | number, format: string, language?: string): string;
function formatDate(dateObj: string | Date | number, isDuration: boolean | string, format: string, language?: string): string;
function getDateObject(date: number | string | Date): Date;
/**
* Writes a file.
* @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0"
* @param name File name
* @param data Contents of the file
* @param callback Is called when the operation has finished (successfully or not)
*/
function writeFile(id: string, name: string, data: Buffer | string, callback: ErrorCallback): void;
function writeFileAsync(id: string, name: string, data: Buffer | string): Promise<void>;
/**
* Reads a file.
* @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0"
* @param name File name
* @param callback Is called when the operation has finished (successfully or not)
*/
function readFile(id: string, name: string, callback: iobJS.ReadFileCallback): void;
function readFileAsync(id: string, name: string): iobJS.ReadFilePromise;
/**
* Deletes a file.
* @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0"
* @param name File name
* @param callback Is called when the operation has finished (successfully or not)
*/
function unlink(id: string, name: string, callback: ErrorCallback): void;
function unlinkAsync(id: string, name: string): Promise<void>;
/**
* Deletes a file.
* @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0"
* @param name File name
* @param callback Is called when the operation has finished (successfully or not)
*/
function delFile(id: string, name: string, callback: ErrorCallback): void;
function delFileAsync(id: string, name: string): Promise<void>;
function getHistory(instance: any, options: any, callback: any): any;
/**
* Starts or restarts a script by name
* @param scriptName (optional) Name of the script. If none is given, the current script is (re)started.
*/
function runScript(scriptName?: string, callback?: ErrorCallback): boolean;
function runScriptAsync(scriptName?: string): Promise<void>;
/**
* Starts or restarts a script by name
* @param scriptName (optional) Name of the script. If none is given, the current script is (re)started.
* @param ignoreIfStarted If set to true, running scripts will not be restarted.
* @param callback (optional) Is called when the script has finished (successfully or not)
*/
function startScript(scriptName: string | undefined, ignoreIfStarted: boolean, callback?: GenericCallback<boolean>): boolean;
function startScriptAsync(scriptName?: string | undefined, ignoreIfStarted?: boolean): Promise<void>;
/**
* Starts or restarts a script by name
* @param scriptName (optional) Name of the script. If none is given, the current script is (re)started.
* @param callback (optional) Is called when the script has finished (successfully or not)
*/
function startScript(scriptName?: string, callback?: GenericCallback<boolean>): boolean;
/**
* Stops a script by name
* @param scriptName (optional) Name of the script. If none is given, the current script is stopped.
*/
function stopScript(scriptName: string | undefined, callback?: GenericCallback<boolean>): boolean;
function stopScriptAsync(scriptName?: string): Promise<void>;
function isScriptActive(scriptName: string): boolean;
/** Converts a value to an integer */
function toInt(val: any): number;
/** Converts a value to a floating point number */
function toFloat(val: any): number;
/** Converts a value to a boolean */
function toBoolean(val: any): boolean;
/**
* Digs in an object for the property value at the given path.
* @param obj The object to dig in
* @param path The path of the property to dig for in the given object
*/
function getAttr(obj: string | Record<string, any>, path: string | string[]): any;
/**
* Sends a message to another script.
* @param target Message name or target object
* @param data Any data, that should be sent to message bus
* @param options Actually only {timeout: X} is supported as option
* @param callback Callback to get the result from other script
* @return ID of the subscription. It could be used for un-subscribe.
*/
function messageTo(target: iobJS.MessageTarget | string, data: any, options?: any, callback?: SimpleCallback<any>): iobJS.MessageSubscribeID;
/**
* Process message from other script.
* @param message Message name
* @param callback Callback to send the result to other script
*/
function onMessage(message: string, callback?: SimpleCallback<any>);
/**
* Unregister onmessage handler
* @param id Message subscription id from onMessage or by message name
* @return true if subscription exists and was deleted.
*/
function onMessageUnregister(id: iobJS.MessageSubscribeID | string): boolean;
/**
* Receives logs of specified severity level in script.
* @param severity Severity level
* @param callback Callback to send the result to other script
*/
function onLog(severity: iobJS.LogLevel | "*", callback: SimpleCallback<iobJS.LogMessage>);
/**
* Unsubscribe log handler.
* @param idOrCallbackOrSeverity Message subscription id from onLog or by callback function
* @return true if subscription exists and was deleted.
*/
function onLogUnregister(idOrCallbackOrSeverity: iobJS.MessageSubscribeID | SimpleCallback<iobJS.LogMessage> | iobJS.LogLevel | "*"): boolean;
/** `await` this method to pause for the given number of milliseconds */
function wait(ms: number): Promise<void>;
/** `await` this method to pause for the given number of milliseconds */
function sleep(ms: number): Promise<void>;
} | the_stack |
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { expect, StoryConfig } from '..'
import { generateComponentExamples } from '../utils/generateComponentExamples'
type Props = {
variant: 'circle' | 'rectangle'
show: boolean
message: string | null
children: null
}
class TestComponent extends Component<Props> {
static propTypes = {
variant: PropTypes.oneOf(['circle', 'rectangle']),
show: PropTypes.bool,
message: PropTypes.object,
children: PropTypes.node
}
static defaultProps = {
variant: 'circle',
show: true,
message: null,
children: null
}
render() {
return React.createElement('span')
}
}
describe('generateComponentExamples', () => {
it('should work with no propValues defined', () => {
const config: StoryConfig<Props> = {
sectionProp: 'variant',
getComponentProps: (_props) => {
return { variant: 'circle', show: true }
},
getParameters: (_page) => {
return { delay: 200 }
},
maxExamples: 500
}
expect(generateComponentExamples(TestComponent, config))
.excludingEvery(['key'])
.to.deep.equal([
{
sectionName: 'circle',
propName: 'variant',
propValue: 'circle',
pages: [
{
examples: [
{
Component: TestComponent,
componentProps: { variant: 'circle', show: true },
exampleProps: {}
}
],
parameters: { delay: 200 },
index: 0
}
]
}
])
})
it('should work with propValues defined', () => {
const config: StoryConfig<Props> = {
sectionProp: 'variant',
propValues: {
variant: ['circle', 'rectangle'],
show: [true, false]
},
getParameters: (_page) => {
return { delay: 200 }
},
maxExamples: 500
}
expect(generateComponentExamples(TestComponent, config))
.excludingEvery(['key'])
.to.deep.equal([
{
sectionName: 'circle',
propName: 'variant',
propValue: 'circle',
pages: [
{
examples: [
{
Component: TestComponent,
componentProps: { variant: 'circle', show: true },
exampleProps: {}
},
{
Component: TestComponent,
componentProps: { variant: 'circle', show: false },
exampleProps: {}
}
],
parameters: { delay: 200 },
index: 0
}
]
},
{
sectionName: 'rectangle',
propName: 'variant',
propValue: 'rectangle',
pages: [
{
examples: [
{
Component: TestComponent,
componentProps: { variant: 'rectangle', show: true },
exampleProps: {}
},
{
Component: TestComponent,
componentProps: { variant: 'rectangle', show: false },
exampleProps: {}
}
],
parameters: { delay: 200 },
index: 0
}
]
}
])
})
it('should filter', () => {
const config: StoryConfig<Props> = {
sectionProp: 'variant',
propValues: {
variant: ['circle', 'rectangle'],
show: [true, false]
},
maxExamples: 100,
filter: (props: Props) => !props.show && props.variant === 'circle'
}
expect(generateComponentExamples(TestComponent, config))
.excludingEvery(['key'])
.to.deep.equal([
{
sectionName: 'circle',
propName: 'variant',
propValue: 'circle',
pages: [
{
examples: [
{
Component: TestComponent,
componentProps: { variant: 'circle', show: true },
exampleProps: {}
}
],
parameters: {},
index: 0
}
]
},
{
sectionName: 'rectangle',
propName: 'variant',
propValue: 'rectangle',
pages: [
{
examples: [
{
Component: TestComponent,
componentProps: { variant: 'rectangle', show: true },
exampleProps: {}
},
{
Component: TestComponent,
componentProps: { variant: 'rectangle', show: false },
exampleProps: {}
}
],
parameters: {},
index: 0
}
]
}
])
})
it('should handle object type config props', () => {
const config: StoryConfig<Props> = {
sectionProp: 'variant',
propValues: {
children: [
<span key={1}>child 1</span>,
<div key={2}>child 2</div>,
<h1 key={3}>child 3</h1>
]
},
maxExamples: 100
}
expect(generateComponentExamples(TestComponent, config))
.excludingEvery([
'key',
'$$typeof',
'_owner',
'ref',
'defaultProps',
'propTypes',
'_store'
])
.to.deep.equal([
{
pages: [
{
examples: [
{
Component: {
displayName: 'TestComponent'
},
componentProps: {
children: {
props: {
children: 'child 1'
},
type: 'span'
}
},
exampleProps: {}
},
{
Component: {
displayName: 'TestComponent'
},
componentProps: {
children: {
props: {
children: 'child 2'
},
type: 'div'
}
},
exampleProps: {}
},
{
Component: {
displayName: 'TestComponent'
},
componentProps: {
children: {
props: {
children: 'child 3'
},
type: 'h1'
}
},
exampleProps: {}
}
],
index: 0,
parameters: {}
}
],
propName: 'variant',
propValue: 'Examples',
sectionName: 'Examples'
}
])
})
it('should handle excluded props', () => {
const config: StoryConfig<Props> = {
sectionProp: 'variant',
propValues: {
variant: ['circle', 'rectangle'],
show: [true, false]
},
excludeProps: ['show'],
maxExamples: 100
}
expect(generateComponentExamples(TestComponent, config))
.excludingEvery([
'key',
'$$typeof',
'_owner',
'ref',
'defaultProps',
'propTypes',
'_store'
])
.to.deep.equal([
{
pages: [
{
examples: [
{
Component: {
displayName: 'TestComponent'
},
componentProps: {
variant: 'circle'
},
exampleProps: {}
}
],
index: 0,
parameters: {}
}
],
propName: 'variant',
propValue: 'circle',
sectionName: 'circle'
},
{
pages: [
{
examples: [
{
Component: {
displayName: 'TestComponent'
},
componentProps: {
variant: 'rectangle'
},
exampleProps: {}
}
],
index: 0,
parameters: {}
}
],
propName: 'variant',
propValue: 'rectangle',
sectionName: 'rectangle'
}
])
})
it('should handle example props', () => {
const config: StoryConfig<Props> = {
sectionProp: 'variant',
propValues: {
variant: ['circle', 'rectangle'],
show: [true, false]
},
getExampleProps: (_props) => {
return { message: 'hello' }
},
maxExamples: 100
}
expect(generateComponentExamples(TestComponent, config))
.excludingEvery([
'key',
'$$typeof',
'_owner',
'ref',
'defaultProps',
'propTypes',
'_store'
])
.to.deep.equal([
{
pages: [
{
examples: [
{
Component: {
displayName: 'TestComponent'
},
componentProps: {
show: true,
variant: 'circle'
},
exampleProps: {
message: 'hello'
}
},
{
Component: {
displayName: 'TestComponent'
},
componentProps: {
show: false,
variant: 'circle'
},
exampleProps: {
message: 'hello'
}
}
],
index: 0,
parameters: {}
}
],
propName: 'variant',
propValue: 'circle',
sectionName: 'circle'
},
{
pages: [
{
examples: [
{
Component: {
displayName: 'TestComponent'
},
componentProps: {
show: true,
variant: 'rectangle'
},
exampleProps: {
message: 'hello'
}
},
{
Component: {
displayName: 'TestComponent'
},
componentProps: {
show: false,
variant: 'rectangle'
},
exampleProps: {
message: 'hello'
}
}
],
index: 0,
parameters: {}
}
],
propName: 'variant',
propValue: 'rectangle',
sectionName: 'rectangle'
}
])
})
}) | the_stack |
import { Component, EventEmitter, HostListener, Input, Output, ViewChild } from '@angular/core';
import * as moment from 'moment';
import * as d3 from 'd3';
@Component({
selector: 'wikift-contribution',
templateUrl: './wikift-contribution.component.html',
styles: [`
:host {
position: relative;
user-select: none;
-ms-user-select: none;
-moz-user-select: none;
-webkit-user-select: none;
}
:host >>> .item {
cursor: pointer;
}
:host >>> .label {
cursor: pointer;
fill: rgb(170, 170, 170);
}
:host >>> .heatmap-tooltip {
pointer-events: none;
position: absolute;
z-index: 9999;
overflow: hidden;
padding: 0.3rem;
font-size: 12px;
line-height: 14px;
color: rgb(51, 51, 51);
background: #495057;
white-space: nowrap;
overflow: hidden;
color: #ffffff;
padding: 1rem;
border-radius: 0.3rem;
text-overflow: ellipsis;
display: inline-block;
}
`]
})
export class WikiftContributionComponent {
// 图表容器
@ViewChild('wikiftContribution')
element: any;
// 渲染数据
@Input()
data: Array<object>;
// 颜色
@Input()
color = '#7bc96f';
// 时区
@Input()
locale = 'zh-cn';
@Output()
handler: EventEmitter<object> = new EventEmitter<object>();
@Output()
onChange: EventEmitter<object> = new EventEmitter<object>();
// 默认配置
private gutter = 5;
private item_gutter = 1;
private width = 1000;
private height = 200;
private item_size = 10;
private label_padding = 40;
private max_block_height = 20;
private transition_duration = 500;
private in_transition = false;
// tooltip 配置
private tooltip_width = 250;
private tooltip_padding = 15;
private selected = {};
// D3
private svg: any;
private items: any;
private labels: any;
private buttons: any;
private tooltip: any;
ngOnChanges() {
if (!this.data) {
return;
}
this.drawChart();
}
ngAfterViewInit() {
// 设置为中国时区
const element = this.element.nativeElement;
// 初始化 svg
this.svg = d3.select(element)
.append('svg')
.attr('class', 'svg');
// 初始化 svg 全局容器
this.items = this.svg.append('g');
this.labels = this.svg.append('g');
this.buttons = this.svg.append('g');
// 添加 tooltip
this.tooltip = d3.select(element).append('div')
.attr('class', 'heatmap-tooltip')
.style('opacity', 0);
this.calculateDimensions();
this.drawChart();
}
getNumberOfWeeks() {
const dayIndex = Math.round((+moment() - +moment().subtract(1, 'year').startOf('week')) / 86400000);
const colIndex = Math.trunc(dayIndex / 7);
const numWeeks = colIndex + 1;
return numWeeks;
}
/**
* 计算图尺寸
*/
calculateDimensions() {
const element = this.element.nativeElement;
this.width = element.clientWidth < 1000 ? 1000 : element.clientWidth;
this.item_size = ((this.width - this.label_padding) / this.getNumberOfWeeks() - this.gutter);
this.height = this.label_padding + 7 * (this.item_size + this.gutter);
this.svg.attr('width', this.width).attr('height', this.height);
}
/**
* 绘制图表
*/
drawChart() {
if (!this.svg || !this.data) {
return;
}
this.drawYearOverview();
this.onChange.emit({
start: moment(this.selected['date']).startOf('year'),
end: moment(this.selected['date']).endOf('year'),
});
}
/**
* 根据年份进行绘制图表
*/
drawYearOverview() {
moment.locale(this.locale);
// 定义开始/结束时间
const start_of_year = moment(this.selected['date']).startOf('year');
const end_of_year = moment(this.selected['date']).endOf('year');
// 填充年度数据
const year_data = this.data.filter((d: any) => {
return start_of_year <= moment(d.date) && moment(d.date) < end_of_year;
});
// 计算当前年份数据最大值
const max_value = d3.max(year_data, (d: any) => {
return d.total;
});
const color = d3.scaleLinear<string>()
.range(['#ffffff', this.color])
.domain([-0.15 * max_value, max_value]);
this.items.selectAll('.item-circle').remove();
this.items.selectAll('.item-circle')
.data(year_data)
.enter()
.append('rect')
.attr('class', 'item item-circle')
.style('opacity', 0)
.attr('x', (d: any) => {
return this.calcItemX(d, start_of_year) + (this.item_size - this.calcItemSize(d, max_value)) / 2;
})
.attr('y', (d: any) => {
return this.calcItemY(d) + (this.item_size - this.calcItemSize(d, max_value)) / 2;
})
.attr('width', (d: any) => {
return this.calcItemSize(d, max_value);
})
.attr('height', (d: any) => {
return this.calcItemSize(d, max_value);
})
.attr('fill', (d: any) => {
return (d.total > 0) ? color(d.total) : '#ebedf0';
})
.on('mouseover', (d: any) => {
if (this.in_transition) {
return;
}
const circle = d3.select(d3.event.currentTarget);
const repeat = () => {
circle.transition()
.duration(this.transition_duration)
.ease(d3.easeLinear)
.attr('x', (d: any) => {
return this.calcItemX(d, start_of_year) - (this.item_size * 1.1 - this.item_size) / 2;
})
.attr('y', (d: any) => {
return this.calcItemY(d) - (this.item_size * 1.1 - this.item_size) / 2;
})
.attr('width', this.item_size * 1.1)
.attr('height', this.item_size * 1.1)
.transition()
.duration(this.transition_duration)
.ease(d3.easeLinear)
.attr('x', (d: any) => {
return this.calcItemX(d, start_of_year) + (this.item_size - this.calcItemSize(d, max_value)) / 2;
})
.attr('y', (d: any) => {
return this.calcItemY(d) + (this.item_size - this.calcItemSize(d, max_value)) / 2;
})
.attr('width', (d: any) => {
return this.calcItemSize(d, max_value);
})
.attr('height', (d: any) => {
return this.calcItemSize(d, max_value);
})
.on('end', repeat);
};
repeat();
let tooltip_html = '';
tooltip_html += '<div><strong>' + (d.total ? d.total : '0') + ' 条数据创建于 ' + moment(d.date).format('dddd, MMM Do YYYY') + '</strong></div>';
let x = this.calcItemX(d, start_of_year) + this.item_size / 2;
if (this.width - x < (this.tooltip_width + this.tooltip_padding * 3)) {
x -= this.tooltip_width + this.tooltip_padding * 2;
}
const y = this.calcItemY(d) + this.item_size / 2;
this.tooltip.html(tooltip_html)
.style('left', x + 'px')
.style('top', y + 'px')
.transition()
.duration(this.transition_duration / 2)
.ease(d3.easeLinear)
.style('opacity', 1);
})
.on('mouseout', () => {
if (this.in_transition) {
return;
}
d3.select(d3.event.currentTarget).transition()
.duration(this.transition_duration / 2)
.ease(d3.easeLinear)
.attr('x', (d: any) => {
return this.calcItemX(d, start_of_year) + (this.item_size - this.calcItemSize(d, max_value)) / 2;
})
.attr('y', (d: any) => {
return this.calcItemY(d) + (this.item_size - this.calcItemSize(d, max_value)) / 2;
})
.attr('width', (d: any) => {
return this.calcItemSize(d, max_value);
})
.attr('height', (d: any) => {
return this.calcItemSize(d, max_value);
});
this.hideTooltip();
})
.transition()
.delay(() => {
return (Math.cos(Math.PI * Math.random()) + 1) * this.transition_duration;
})
.duration(() => {
return this.transition_duration;
})
.ease(d3.easeLinear)
.style('opacity', 1)
.call((transition: any, callback: any) => {
if (transition.empty()) {
callback();
}
let n = 0;
transition
.each(() => ++n)
.on('end', function () {
if (!--n) {
callback.apply(this, arguments);
}
});
}, () => {
this.in_transition = false;
});
// 添加当前年份下所有月份
const month_labels = d3.timeMonths(start_of_year.toDate(), end_of_year.toDate());
const monthScale = d3.scaleLinear()
.range([0, this.width])
.domain([0, month_labels.length]);
this.labels.selectAll('.label-month').remove();
this.labels.selectAll('.label-month')
.data(month_labels)
.enter()
.append('text')
.attr('class', 'label label-month')
.attr('font-size', () => {
return Math.floor(this.label_padding / 3) + 'px';
})
.text((d: any) => {
return d.toLocaleDateString(this.locale, { month: 'short' });
})
.attr('x', (d: any, i: number) => {
return monthScale(i) + (monthScale(i) - monthScale(i - 1)) / 2;
})
.attr('y', this.label_padding / 2)
.on('mouseenter', (d: any) => {
if (this.in_transition) {
return;
}
const selected_month = moment(d);
this.items.selectAll('.item-circle')
.transition()
.duration(this.transition_duration)
.ease(d3.easeLinear)
.style('opacity', (d: any) => {
return moment(d.date).isSame(selected_month, 'month') ? 1 : 0.1;
});
})
.on('mouseout', () => {
if (this.in_transition) {
return;
}
this.items.selectAll('.item-circle')
.transition()
.duration(this.transition_duration)
.ease(d3.easeLinear)
.style('opacity', 1);
})
// 添加当前年份所有天数数据
const day_labels = d3.timeDays(
moment().startOf('week').toDate(),
moment().endOf('week').toDate()
);
const dayScale = d3.scaleBand()
.rangeRound([this.label_padding, this.height])
.domain(day_labels.map((d: any) => {
return moment(d).weekday().toString();
}));
this.labels.selectAll('.label-day').remove();
this.labels.selectAll('.label-day')
.data(day_labels)
.enter()
.append('text')
.attr('class', 'label label-day')
.attr('x', this.label_padding / 3)
.attr('y', (d: any, i: number) => {
return dayScale((i).toString()) + dayScale.bandwidth() / 1.75;
})
.style('text-anchor', 'left')
.attr('font-size', () => {
return Math.floor(this.label_padding / 3) + 'px';
})
.text((d: any) => {
// 中文截取汉字
if (this.locale === 'zh-cn') {
return moment(d).format('dddd')[2];
}
return moment(d).format('dddd')[0];
})
.on('mouseenter', (d: any) => {
if (this.in_transition) {
return;
}
const selected_day = moment(d);
this.items.selectAll('.item-circle')
.transition()
.duration(this.transition_duration)
.ease(d3.easeLinear)
.style('opacity', (d: any) => {
return (moment(d.date).day() === selected_day.day()) ? 1 : 0.1;
});
})
.on('mouseout', () => {
if (this.in_transition) {
return;
}
this.items.selectAll('.item-circle')
.transition()
.duration(this.transition_duration)
.ease(d3.easeLinear)
.style('opacity', 1);
});
}
calcItemX(d: any, start_of_year: any) {
const date = moment(d.date);
const dayIndex = Math.round((+date - +moment(start_of_year).startOf('week')) / 86400000);
const colIndex = Math.trunc(dayIndex / 7);
return colIndex * (this.item_size + this.gutter) + this.label_padding;
}
calcItemY(d: any) {
return this.label_padding + moment(d.date).weekday() * (this.item_size + this.gutter);
}
calcItemSize(d: any, max: number) {
if (max <= 0) {
return this.item_size;
}
return this.item_size * 0.75 + (this.item_size * d.total / max) * 0.25;
}
hideTooltip() {
this.tooltip.transition()
.duration(this.transition_duration / 2)
.ease(d3.easeLinear)
.style('opacity', 0);
}
formatTime(seconds: number) {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds - (hours * 3600)) / 60);
let time = '';
if (hours > 0) {
time += hours === 1 ? '1 hour ' : hours + ' hours ';
}
if (minutes > 0) {
time += minutes === 1 ? '1 minute' : minutes + ' minutes';
}
if (hours === 0 && minutes === 0) {
time = Math.round(seconds) + ' seconds';
}
return time;
}
} | the_stack |
import * as cp from 'child_process';
import * as fs from 'fs';
import {
DocumentFormattingEditProvider,
DocumentRangeFormattingEditProvider,
ExtensionContext,
Range,
TextDocument,
TextEdit,
Uri,
languages,
window
} from 'vscode';
import { Configuration } from '../configuration/Configuration';
import { getDocumentFilter } from '../configuration/mod';
import { FileSystem } from '../file_system/FileSystem';
import { ChildLogger } from '../logging/child_logger';
const ansiRegex = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;
interface RustFmtDiff {
startLine: number;
newLines: string[];
removedLines: number;
}
export class FormattingManager implements DocumentFormattingEditProvider, DocumentRangeFormattingEditProvider {
private _newFormatRegex: RegExp = /^Diff in (.*) at line (\d+):$/;
private _configuration: Configuration;
private _logger: ChildLogger;
public static async create(
context: ExtensionContext,
configuration: Configuration,
logger: ChildLogger
): Promise<FormattingManager | undefined> {
const rustfmtPath: string | undefined = await FileSystem.findExecutablePath(configuration.getRustfmtPath());
if (rustfmtPath === undefined) {
return undefined;
}
return new FormattingManager(context, configuration, logger);
}
public provideDocumentFormattingEdits(document: TextDocument): Thenable<TextEdit[]> {
return this.formattingEdits(document);
}
public provideDocumentRangeFormattingEdits(document: TextDocument, range: Range): Thenable<TextEdit[]> {
return this.formattingEdits(document, range);
}
/**
* To create an instance of the class use the method `create`
* @param context The extension context
* @param configuration The configuration
* @param logger the logger used to create a child logger to log messages
*/
private constructor(
context: ExtensionContext,
configuration: Configuration,
logger: ChildLogger
) {
this._configuration = configuration;
this._logger = logger.createChildLogger('FormattingManager: ');
context.subscriptions.push(
languages.registerDocumentFormattingEditProvider(
getDocumentFilter(),
this
),
languages.registerDocumentRangeFormattingEditProvider(
getDocumentFilter(),
this
)
);
}
private formattingEdits(document: TextDocument, range?: Range): Thenable<TextEdit[]> {
const logger = this._logger.createChildLogger('formattingEdits: ');
return new Promise((resolve, reject) => {
const fileName = document.fileName + '.fmt';
fs.writeFileSync(fileName, document.getText());
const rustfmtPath = this._configuration.getRustfmtPath();
logger.debug(`rustfmtPath=${rustfmtPath}`);
const args = ['--skip-children', '--write-mode=diff'];
if (range !== undefined) {
args.push('--file-lines',
`[{"file":"${fileName}","range":[${range.start.line + 1}, ${range.end.line + 1}]}]`);
} else {
args.push(fileName);
}
logger.debug(`args=${JSON.stringify(args)}`);
const env = Object.assign({ TERM: 'xterm' }, process.env);
cp.execFile(rustfmtPath, args, { env: env }, (err, stdout, stderr) => {
try {
if (err && (<any>err).code === 'ENOENT') {
window.showInformationMessage('The "rustfmt" command is not available. Make sure it is installed.');
return resolve([]);
}
// rustfmt will return with exit code 3 when it encounters code that could not
// be automatically formatted. However, it will continue to format the rest of the file.
// New releases will return exit code 4 when the write mode is diff and a valid diff is provided.
// For these reasons, if the exit code is 1 or 2, then it should be treated as an error.
const hasFatalError = (err && (err as any).code < 3);
if ((err || stderr.length) && hasFatalError) {
logger.debug('cannot format due to syntax errors');
window.setStatusBarMessage('$(alert) Cannot format due to syntax errors', 5000);
return reject();
}
return resolve(this.parseDiff(document.uri, stdout));
} catch (e) {
logger.error(`e=${e}`);
reject(e);
} finally {
fs.unlinkSync(fileName);
}
});
});
}
private cleanDiffLine(line: string): string {
if (line.endsWith('\u23CE')) {
return line.slice(1, -1) + '\n';
}
return line.slice(1);
}
private stripColorCodes(input: string): string {
return input.replace(ansiRegex, '');
}
private parseDiffOldFormat(fileToProcess: Uri, diff: string): RustFmtDiff[] {
const patches: RustFmtDiff[] = [];
let currentPatch: RustFmtDiff | undefined = undefined;
let currentFile: Uri | undefined = undefined;
for (const line of diff.split(/\n/)) {
if (line.startsWith('Diff of')) {
currentFile = Uri.file(line.slice('Diff of '.length, -1));
}
if (!currentFile) {
continue;
}
if (currentFile.toString() !== fileToProcess.toString() + '.fmt') {
continue;
}
if (line.startsWith('Diff at line')) {
if (currentPatch != null) {
patches.push(currentPatch);
}
currentPatch = {
startLine: parseInt(line.slice('Diff at line'.length), 10),
newLines: [],
removedLines: 0
};
} else if (currentPatch !== undefined) {
if (line.startsWith('+')) {
currentPatch.newLines.push(this.cleanDiffLine(line));
} else if (line.startsWith('-')) {
currentPatch.removedLines += 1;
} else if (line.startsWith(' ')) {
currentPatch.newLines.push(this.cleanDiffLine(line));
currentPatch.removedLines += 1;
}
}
}
if (currentPatch) {
patches.push(currentPatch);
}
return patches;
}
private parseDiffNewFormat(fileToProcess: Uri, diff: string): RustFmtDiff[] {
const patches: RustFmtDiff[] = [];
let currentPatch: RustFmtDiff | undefined = undefined;
let currentFilePath: string | undefined = undefined;
const fileToProcessPath = Uri.file(fileToProcess.path + '.fmt').fsPath;
for (const line of diff.split(/\n/)) {
if (line.startsWith('Diff in')) {
const matches = this._newFormatRegex.exec(line);
if (!matches) {
continue;
}
// Filter out malformed lines
if (matches.length !== 3) {
continue;
}
// If we begin a new diff while already building one, push it as its now complete
if (currentPatch !== undefined) {
patches.push(currentPatch);
}
// The .path uncanonicalizes the path, which then gets turned into a Uri.
// The .fsPath on both the current file and file to process fix the remaining differences.
currentFilePath = Uri.file(Uri.file(matches[1]).path).fsPath;
currentPatch = {
startLine: parseInt(matches[2], 10),
newLines: [],
removedLines: 0
};
}
// We haven't managed to figure out what file we're diffing yet, this shouldn't happen.
// Probably a malformed diff.
if (!currentFilePath) {
continue;
}
if (currentFilePath !== fileToProcessPath) {
continue;
}
if (!currentPatch) {
continue;
}
if (line.startsWith('+')) {
currentPatch.newLines.push(this.cleanDiffLine(line));
} else if (line.startsWith('-')) {
currentPatch.removedLines += 1;
} else if (line.startsWith(' ')) {
currentPatch.newLines.push(this.cleanDiffLine(line));
currentPatch.removedLines += 1;
}
}
// We've reached the end of the data, push the current patch if we were building one
if (currentPatch) {
patches.push(currentPatch);
}
return patches;
}
private parseDiff(fileToProcess: Uri, diff: string): TextEdit[] {
diff = this.stripColorCodes(diff);
let patches: RustFmtDiff[] = [];
const oldFormat = diff.startsWith('Diff of');
if (oldFormat) {
patches = this.parseDiffOldFormat(fileToProcess, diff);
} else {
patches = this.parseDiffNewFormat(fileToProcess, diff);
}
let cummulativeOffset = 0;
const textEdits = patches.map(patch => {
const newLines = patch.newLines;
const removedLines = patch.removedLines;
const startLine = patch.startLine - 1 + cummulativeOffset;
const endLine = removedLines === 0 ? startLine : startLine + removedLines - 1;
const range = new Range(startLine, 0, endLine, Number.MAX_SAFE_INTEGER);
cummulativeOffset += (removedLines - newLines.length);
const lastLineIndex = newLines.length - 1;
newLines[lastLineIndex] = newLines[lastLineIndex].replace('\n', '');
return TextEdit.replace(range, newLines.join(''));
});
return textEdits;
}
} | the_stack |
import * as assert from "assert";
import * as debug from "debug";
import * as fs from "fs";
import * as llvm from "llvm-node";
import * as path from "path";
import * as ts from "typescript";
import {CompilationContext} from "../../compilation-context";
import {wasmOpt} from "../../external-tools/binaryen-opt";
import {s2wasm} from "../../external-tools/binaryen-s2wasm";
import {wasmAs} from "../../external-tools/binaryen-wasm-as";
import {LLVMLink} from "../../external-tools/llvm-link";
import {llc} from "../../external-tools/llvm-llc";
import {optimize, optimizeLinked} from "../../external-tools/llvm-opt";
import {BuildDirectory} from "../build-directory";
import {CodeGenerationContext} from "../code-generation-context";
import {CodeGenerator} from "../code-generator";
import {DefaultCodeGenerationContextFactory} from "../default-code-generation-context-factory";
import {FunctionBuilder} from "../util/function-builder";
import {createResolvedFunctionFromSignature} from "../value/resolved-function";
import {NoopSourceFileRewriter} from "./llvm-emit-source-file-rewriter";
import {PerFileCodeGeneratorSourceFileRewriter} from "./per-file-code-generator-source-file-rewriter";
import {PerFileSourceFileRewirter} from "./per-file-source-file-rewriter";
import {WastMetaData} from "./wast-meta-data";
const WASM_TRIPLE = "wasm32-unknown-unknown";
const LOG = debug("code-generation/per-file-code-generator");
interface SourceFileState {
context: CodeGenerationContext;
sourceFileRewriter: PerFileSourceFileRewirter;
requestEmitHelper: (emitHelper: ts.EmitHelper) => void;
}
/**
* Code Generator that creates a dedicate WASM Module for each source file
*/
export class PerFileCodeGenerator implements CodeGenerator {
private sourceFileStates = new Map<string, SourceFileState>();
constructor(private context: llvm.LLVMContext, private codeGenerationContextFactory = new DefaultCodeGenerationContextFactory()) {
}
beginSourceFile(sourceFile: ts.SourceFile, compilationContext: CompilationContext, requestEmitHelper: (emitHelper: ts.EmitHelper) => void) {
const context = this.createContext(sourceFile, compilationContext);
const emitsWasm = !compilationContext.compilerOptions.emitLLVM;
this.sourceFileStates.set(sourceFile.fileName, {
context,
requestEmitHelper,
sourceFileRewriter: emitsWasm ? new PerFileCodeGeneratorSourceFileRewriter(context) : new NoopSourceFileRewriter()
});
}
generateEntryFunction(functionDeclaration: ts.FunctionDeclaration): ts.FunctionDeclaration {
const state = this.getSourceFileState(functionDeclaration);
const context = state.context;
// function is async, therefore, return type is a promise of T. We compile it down to a function just returning T
const signature = context.typeChecker.getSignatureFromDeclaration(functionDeclaration);
const resolvedFunction = createResolvedFunctionFromSignature(signature, context.compilationContext);
const mangledName = `_${resolvedFunction.functionName}`;
const builder = FunctionBuilder.create(resolvedFunction, context)
.name(mangledName)
.externalLinkage();
builder.define(resolvedFunction.definition!);
context.addEntryFunction(mangledName);
return state.sourceFileRewriter.rewriteEntryFunction(mangledName, functionDeclaration, state.requestEmitHelper);
}
completeSourceFile(sourceFile: ts.SourceFile): ts.SourceFile {
const state = this.getSourceFileState(sourceFile);
const context = state.context;
if (context.module.empty || context.getEntryFunctionNames().length === 0) {
return sourceFile;
}
if (context.requiresGc) {
context.module.getOrInsertFunction("speedyJsGc", llvm.FunctionType.get(llvm.Type.getVoidTy(context.llvmContext), [], false));
}
LOG(`Emit module for source file ${sourceFile.fileName}.`);
// llvm.verifyModule(context.module);
this .writeModule(sourceFile, state);
LOG(`Module for source file ${sourceFile.fileName} emitted.`);
return state.sourceFileRewriter.rewriteSourceFile(sourceFile, state.requestEmitHelper);
}
completeCompilation() {
this.sourceFileStates.clear();
}
private writeModule(sourceFile: ts.SourceFile, state: SourceFileState) {
const context = state.context;
const buildDirectory = BuildDirectory.createTempBuildDirectory();
const plainFileName = path.basename(sourceFile.fileName.replace(".ts", ""));
if (context.compilationContext.compilerOptions.emitLLVM) {
const llvmIR = context.module.print();
context.compilationContext.compilerHost.writeFile(getOutputFileName(sourceFile, context, ".ll"), llvmIR, false);
} else {
const transforms = PerFileCodeGenerator.createTransformationChain(context);
const transformationContext = {
sourceFile,
codeGenerationContext: context,
buildDirectory,
plainFileName,
sourceFileRewriter: state.sourceFileRewriter
};
const biteCodeFileName = buildDirectory.getTempFileName(`${plainFileName}.bc`);
llvm.writeBitcodeToFile(context.module, biteCodeFileName);
transforms.reduce((inputFileName, transformation) => transformation.transform(inputFileName, transformationContext), biteCodeFileName);
}
buildDirectory.remove();
}
private static createTransformationChain(context: CodeGenerationContext) {
const optimizationLevel = context.compilationContext.compilerOptions.optimizationLevel;
const transforms: TransformationStep[] = [
LinkTransformationStep.createRuntimeLinking()
];
if (optimizationLevel !== "0") {
transforms.push(new OptimizationTransformationStep());
}
transforms.push(
LinkTransformationStep.createSharedLibsLinking(),
new LinkTimeOptimizationTransformationStep());
if (context.compilationContext.compilerOptions.saveBc) {
transforms.push(new CopyFileToOutputDirectoryTransformationStep(".bc", true));
}
transforms.push(
new LLCTransformationStep(),
new S2WasmTransformationStep()
);
if (context.compilationContext.compilerOptions.binaryenOpt && optimizationLevel !== "0") {
transforms.push(new BinaryenOptTransformationStep());
}
if (context.compilationContext.compilerOptions.saveWast) {
transforms.push(new CopyFileToOutputDirectoryTransformationStep(".wast"));
}
transforms.push(new WasmToAsTransformationStep());
return transforms;
}
private getSourceFileState(node: ts.Node): SourceFileState {
const sourceFile = node.getSourceFile();
const state = this.sourceFileStates.get(sourceFile.fileName);
// tslint:disable-next-line:max-line-length
assert(state, `First call beginSourceFile before calling any other functions on the code generator (state missing for source file ${sourceFile.fileName}).`);
return state!;
}
private createContext(sourceFile: ts.SourceFile, compilationContext: CompilationContext): CodeGenerationContext {
const relativePath = path.relative(compilationContext.rootDir, sourceFile.fileName);
const module = new llvm.Module(sourceFile.moduleName || relativePath, this.context);
module.sourceFileName = relativePath;
const target = llvm.TargetRegistry.lookupTarget(WASM_TRIPLE);
const targetMachine = target.createTargetMachine(WASM_TRIPLE, "generic");
module.dataLayout = targetMachine.createDataLayout();
module.targetTriple = WASM_TRIPLE;
return this.codeGenerationContextFactory.createContext(compilationContext, module);
}
}
interface TransformationContext {
plainFileName: string;
buildDirectory: BuildDirectory;
sourceFile: ts.SourceFile;
codeGenerationContext: CodeGenerationContext;
sourceFileRewriter: PerFileSourceFileRewirter;
}
interface TransformationStep {
/**
* Performs the transformation
* @param inputFileName the input file name
* @return the name of the output file name
*/
transform(inputFileName: string, transformationContext: TransformationContext): string;
}
class OptimizationTransformationStep implements TransformationStep {
transform(inputFileName: string, {plainFileName, buildDirectory, codeGenerationContext}: TransformationContext): string {
const optimizedFileName = buildDirectory.getTempFileName(`${plainFileName}-opt.bc`);
const optimizationLevel = codeGenerationContext.compilationContext.compilerOptions.optimizationLevel;
return optimize(inputFileName, optimizedFileName, optimizationLevel);
}
}
class LinkTransformationStep implements TransformationStep {
static createRuntimeLinking() {
return new LinkTransformationStep(true);
}
static createSharedLibsLinking() {
return new LinkTransformationStep(false);
}
private constructor(private runtime: boolean) {
}
transform(inputFileName: string, {plainFileName, buildDirectory, codeGenerationContext}: TransformationContext): string {
const llvmLinker = new LLVMLink(buildDirectory);
const entryFunctions = codeGenerationContext.getEntryFunctionNames();
llvmLinker.addByteCodeFile(inputFileName);
if (this.runtime) {
llvmLinker.addRuntime(codeGenerationContext.compilationContext.compilerOptions.unsafe);
} else {
llvmLinker.addSharedLibs();
}
return llvmLinker.link(buildDirectory.getTempFileName(`${plainFileName}-linked.o`), entryFunctions);
}
}
class LinkTimeOptimizationTransformationStep implements TransformationStep {
transform(inputFileName: string, {plainFileName, buildDirectory, codeGenerationContext}: TransformationContext): string {
const optimizedFileName = buildDirectory.getTempFileName(`${plainFileName}-lopt.bc`);
const entryFunctionNames = codeGenerationContext.getEntryFunctionNames();
return optimizeLinked(inputFileName, entryFunctionNames, optimizedFileName, codeGenerationContext.compilationContext.compilerOptions.optimizationLevel);
}
}
class CopyFileToOutputDirectoryTransformationStep implements TransformationStep {
constructor(private extension: string, private binary = false) {}
transform(inputFileName: string, {plainFileName, buildDirectory, sourceFile, codeGenerationContext}: TransformationContext): string {
const outputFileName = getOutputFileName(sourceFile, codeGenerationContext, this.extension);
if (this.binary) {
// ts writeFile seems not to support binary output, therefore use fs directly
fs.writeFileSync(outputFileName, fs.readFileSync(inputFileName));
} else {
// has the advantage that it can be intercepted by the in memory compiler
codeGenerationContext.compilationContext.compilerHost.writeFile(outputFileName, ts.sys.readFile(inputFileName), false);
}
return inputFileName;
}
}
class LLCTransformationStep implements TransformationStep {
transform(inputFileName: string, { plainFileName, buildDirectory }: TransformationContext): string {
return llc(inputFileName, buildDirectory.getTempFileName(`${plainFileName}.s`));
}
}
class S2WasmTransformationStep implements TransformationStep {
transform(inputFileName: string, {buildDirectory, plainFileName, codeGenerationContext, sourceFileRewriter}: TransformationContext): string {
const compilerOptions = codeGenerationContext.compilationContext.compilerOptions;
const wastFileName = s2wasm(inputFileName, buildDirectory.getTempFileName(`${plainFileName}.wast`), compilerOptions);
const glue = S2WasmTransformationStep.getGlueMetadata(wastFileName);
sourceFileRewriter.setWastMetaData(glue);
return wastFileName;
}
// glue code https://github.com/kripken/emscripten/blob/5387c1e5f1f55b69c41b94cf044062c59e052f0b/emscripten.py#L1415
private static getGlueMetadata(wastFileName: string): WastMetaData {
const wastContent = ts.sys.readFile(wastFileName);
const parts = wastContent.split("\n;; METADATA:");
const metaDataRaw = parts[1];
return JSON.parse(metaDataRaw);
}
}
class BinaryenOptTransformationStep implements TransformationStep {
transform(inputFileName: string, { buildDirectory, plainFileName, codeGenerationContext }: TransformationContext): string {
const outputFile = buildDirectory.getTempFileName(`${plainFileName}-opt.wast`);
return wasmOpt(inputFileName, outputFile);
}
}
class WasmToAsTransformationStep implements TransformationStep {
transform(inputFileName: string, { buildDirectory, plainFileName, sourceFileRewriter, sourceFile, codeGenerationContext}: TransformationContext): string {
const wasmFileName = buildDirectory.getTempFileName(`${plainFileName}.wasm`);
wasmAs(inputFileName, wasmFileName);
const wasmFileWriter = codeGenerationContext.compilationContext.compilerOptions.wasmFileWriter;
const finalWasmFileName = getOutputFileName(sourceFile, codeGenerationContext);
const wasmFetchExpression = wasmFileWriter.writeWasmFile(finalWasmFileName, fs.readFileSync(wasmFileName), codeGenerationContext);
sourceFileRewriter.setWasmUrl(wasmFetchExpression);
return wasmFileName;
}
}
function getOutputFileName(sourceFile: ts.SourceFile, context: CodeGenerationContext, fileExtension = ".wasm") {
const withNewExtension = sourceFile.fileName.replace(".ts", fileExtension);
if (context.compilationContext.compilerOptions.outDir) {
const relativeName = path.relative(context.compilationContext.rootDir, withNewExtension);
return path.join(context.compilationContext.compilerOptions.outDir, relativeName);
}
return withNewExtension;
} | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [codedeploy](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awscodedeploy.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Codedeploy extends PolicyStatement {
public servicePrefix = 'codedeploy';
/**
* Statement provider for service [codedeploy](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awscodedeploy.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Add tags to one or more on-premises instances.
*
* Access Level: Tagging
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_AddTagsToOnPremisesInstances.html
*/
public toAddTagsToOnPremisesInstances() {
return this.to('AddTagsToOnPremisesInstances');
}
/**
* Gets information about one or more application revisions.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_BatchGetApplicationRevisions.html
*/
public toBatchGetApplicationRevisions() {
return this.to('BatchGetApplicationRevisions');
}
/**
* Get information about multiple applications associated with the IAM user.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_BatchGetApplications.html
*/
public toBatchGetApplications() {
return this.to('BatchGetApplications');
}
/**
* Get information about one or more deployment groups.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_BatchGetDeploymentGroups.html
*/
public toBatchGetDeploymentGroups() {
return this.to('BatchGetDeploymentGroups');
}
/**
* Gets information about one or more instance that are part of a deployment group.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_BatchGetDeploymentInstances.html
*/
public toBatchGetDeploymentInstances() {
return this.to('BatchGetDeploymentInstances');
}
/**
* Returns an array of one or more targets associated with a deployment. This method works with all compute types and should be used instead of the deprecated BatchGetDeploymentInstances. The maximum number of targets that can be returned is 25.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_BatchGetDeploymentTargets.html
*/
public toBatchGetDeploymentTargets() {
return this.to('BatchGetDeploymentTargets');
}
/**
* Get information about multiple deployments associated with the IAM user.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_BatchGetDeployments.html
*/
public toBatchGetDeployments() {
return this.to('BatchGetDeployments');
}
/**
* Get information about one or more on-premises instances.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_BatchGetOnPremisesInstances.html
*/
public toBatchGetOnPremisesInstances() {
return this.to('BatchGetOnPremisesInstances');
}
/**
* Starts the process of rerouting traffic from instances in the original environment to instances in thereplacement environment without waiting for a specified wait time to elapse.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_ContinueDeployment.html
*/
public toContinueDeployment() {
return this.to('ContinueDeployment');
}
/**
* Create an application associated with the IAM user.
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_CreateApplication.html
*/
public toCreateApplication() {
return this.to('CreateApplication');
}
/**
* Create CloudFormation deployment to cooperate ochestration for a CloudFormation stack update.
*
* Access Level: Write
*/
public toCreateCloudFormationDeployment() {
return this.to('CreateCloudFormationDeployment');
}
/**
* Create a deployment for an application associated with the IAM user.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_CreateDeployment.html
*/
public toCreateDeployment() {
return this.to('CreateDeployment');
}
/**
* Create a custom deployment configuration associated with the IAM user.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_CreateDeploymentConfig.html
*/
public toCreateDeploymentConfig() {
return this.to('CreateDeploymentConfig');
}
/**
* Create a deployment group for an application associated with the IAM user.
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_CreateDeploymentGroup.html
*/
public toCreateDeploymentGroup() {
return this.to('CreateDeploymentGroup');
}
/**
* Delete an application associated with the IAM user.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_DeleteApplication.html
*/
public toDeleteApplication() {
return this.to('DeleteApplication');
}
/**
* Delete a custom deployment configuration associated with the IAM user.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_DeleteDeploymentConfig.html
*/
public toDeleteDeploymentConfig() {
return this.to('DeleteDeploymentConfig');
}
/**
* Delete a deployment group for an application associated with the IAM user.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_DeleteDeploymentGroup.html
*/
public toDeleteDeploymentGroup() {
return this.to('DeleteDeploymentGroup');
}
/**
* Deletes a GitHub account connection.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_DeleteGitHubAccountToken.html
*/
public toDeleteGitHubAccountToken() {
return this.to('DeleteGitHubAccountToken');
}
/**
* Delete resources associated with the given external Id.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_DeleteResourcesByExternalId.html
*/
public toDeleteResourcesByExternalId() {
return this.to('DeleteResourcesByExternalId');
}
/**
* Deregister an on-premises instance.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_DeregisterOnPremisesInstance.html
*/
public toDeregisterOnPremisesInstance() {
return this.to('DeregisterOnPremisesInstance');
}
/**
* Get information about a single application associated with the IAM user.
*
* Access Level: List
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_GetApplication.html
*/
public toGetApplication() {
return this.to('GetApplication');
}
/**
* Get information about a single application revision for an application associated with the IAM user.
*
* Access Level: List
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_GetApplicationRevision.html
*/
public toGetApplicationRevision() {
return this.to('GetApplicationRevision');
}
/**
* Get information about a single deployment to a deployment group for an application associated with the IAM user.
*
* Access Level: List
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_GetDeployment.html
*/
public toGetDeployment() {
return this.to('GetDeployment');
}
/**
* Get information about a single deployment configuration associated with the IAM user.
*
* Access Level: List
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_GetDeploymentConfig.html
*/
public toGetDeploymentConfig() {
return this.to('GetDeploymentConfig');
}
/**
* Get information about a single deployment group for an application associated with the IAM user.
*
* Access Level: List
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_GetDeploymentGroup.html
*/
public toGetDeploymentGroup() {
return this.to('GetDeploymentGroup');
}
/**
* Get information about a single instance in a deployment associated with the IAM user.
*
* Access Level: List
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_GetDeploymentInstance.html
*/
public toGetDeploymentInstance() {
return this.to('GetDeploymentInstance');
}
/**
* Returns information about a deployment target.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_GetDeploymentTarget.html
*/
public toGetDeploymentTarget() {
return this.to('GetDeploymentTarget');
}
/**
* Get information about a single on-premises instance.
*
* Access Level: List
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_GetOnPremisesInstance.html
*/
public toGetOnPremisesInstance() {
return this.to('GetOnPremisesInstance');
}
/**
* Get information about all application revisions for an application associated with the IAM user.
*
* Access Level: List
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_ListApplicationRevisions.html
*/
public toListApplicationRevisions() {
return this.to('ListApplicationRevisions');
}
/**
* Get information about all applications associated with the IAM user.
*
* Access Level: List
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_ListApplications.html
*/
public toListApplications() {
return this.to('ListApplications');
}
/**
* Get information about all deployment configurations associated with the IAM user.
*
* Access Level: List
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_ListDeploymentConfigs.html
*/
public toListDeploymentConfigs() {
return this.to('ListDeploymentConfigs');
}
/**
* Get information about all deployment groups for an application associated with the IAM user.
*
* Access Level: List
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_ListDeploymentGroups.html
*/
public toListDeploymentGroups() {
return this.to('ListDeploymentGroups');
}
/**
* Get information about all instances in a deployment associated with the IAM user.
*
* Access Level: List
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_ListDeploymentInstances.html
*/
public toListDeploymentInstances() {
return this.to('ListDeploymentInstances');
}
/**
* Returns an array of target IDs that are associated a deployment.
*
* Access Level: List
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_ListDeploymentTargets.html
*/
public toListDeploymentTargets() {
return this.to('ListDeploymentTargets');
}
/**
* Get information about all deployments to a deployment group associated with the IAM user, or to get all deployments associated with the IAM user.
*
* Access Level: List
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_ListDeployments.html
*/
public toListDeployments() {
return this.to('ListDeployments');
}
/**
* Lists the names of stored connections to GitHub accounts.
*
* Access Level: List
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_ ListGitHubAccountTokenNames.html
*/
public toListGitHubAccountTokenNames() {
return this.to('ListGitHubAccountTokenNames');
}
/**
* Get a list of one or more on-premises instance names.
*
* Access Level: List
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_ListOnPremisesInstances.html
*/
public toListOnPremisesInstances() {
return this.to('ListOnPremisesInstances');
}
/**
* Returns a list of tags for the resource identified by a specified ARN. Tags are used to organize and categorize your CodeDeploy resources.
*
* Access Level: List
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_ ListTagsForResource.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Notify a lifecycle event hook execution status for associated deployment with the IAM user.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_PutLifecycleEventHookExecutionStatus.html
*/
public toPutLifecycleEventHookExecutionStatus() {
return this.to('PutLifecycleEventHookExecutionStatus');
}
/**
* Register information about an application revision for an application associated with the IAM user.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_RegisterApplicationRevision.html
*/
public toRegisterApplicationRevision() {
return this.to('RegisterApplicationRevision');
}
/**
* Register an on-premises instance.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_RegisterOnPremisesInstance.html
*/
public toRegisterOnPremisesInstance() {
return this.to('RegisterOnPremisesInstance');
}
/**
* Remove tags from one or more on-premises instances.
*
* Access Level: Tagging
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_RemoveTagsFromOnPremisesInstances.html
*/
public toRemoveTagsFromOnPremisesInstances() {
return this.to('RemoveTagsFromOnPremisesInstances');
}
/**
* In a blue/green deployment, overrides any specified wait time and starts terminating instances immediately after the traffic routing is complete.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_ SkipWaitTimeForInstanceTermination.html
*/
public toSkipWaitTimeForInstanceTermination() {
return this.to('SkipWaitTimeForInstanceTermination');
}
/**
* Description for StopDeployment
*
* Access Level: Write
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_StopDeployment.html
*/
public toStopDeployment() {
return this.to('StopDeployment');
}
/**
* Associates the list of tags in the input Tags parameter with the resource identified by the ResourceArn input parameter.
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_TagResource.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Disassociates a resource from a list of tags. The resource is identified by the ResourceArn input parameter. The tags are identfied by the list of keys in the TagKeys input parameter.
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_UntagResource.html
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Description for UpdateApplication
*
* Access Level: Write
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_UpdateApplication.html
*/
public toUpdateApplication() {
return this.to('UpdateApplication');
}
/**
* Change information about a single deployment group for an application associated with the IAM user.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_UpdateDeploymentGroup.html
*/
public toUpdateDeploymentGroup() {
return this.to('UpdateDeploymentGroup');
}
protected accessLevelList: AccessLevelList = {
"Tagging": [
"AddTagsToOnPremisesInstances",
"RemoveTagsFromOnPremisesInstances",
"TagResource",
"UntagResource"
],
"Read": [
"BatchGetApplicationRevisions",
"BatchGetApplications",
"BatchGetDeploymentGroups",
"BatchGetDeploymentInstances",
"BatchGetDeploymentTargets",
"BatchGetDeployments",
"BatchGetOnPremisesInstances",
"GetDeploymentTarget"
],
"Write": [
"ContinueDeployment",
"CreateApplication",
"CreateCloudFormationDeployment",
"CreateDeployment",
"CreateDeploymentConfig",
"CreateDeploymentGroup",
"DeleteApplication",
"DeleteDeploymentConfig",
"DeleteDeploymentGroup",
"DeleteGitHubAccountToken",
"DeleteResourcesByExternalId",
"DeregisterOnPremisesInstance",
"PutLifecycleEventHookExecutionStatus",
"RegisterApplicationRevision",
"RegisterOnPremisesInstance",
"SkipWaitTimeForInstanceTermination",
"StopDeployment",
"UpdateApplication",
"UpdateDeploymentGroup"
],
"List": [
"GetApplication",
"GetApplicationRevision",
"GetDeployment",
"GetDeploymentConfig",
"GetDeploymentGroup",
"GetDeploymentInstance",
"GetOnPremisesInstance",
"ListApplicationRevisions",
"ListApplications",
"ListDeploymentConfigs",
"ListDeploymentGroups",
"ListDeploymentInstances",
"ListDeploymentTargets",
"ListDeployments",
"ListGitHubAccountTokenNames",
"ListOnPremisesInstances",
"ListTagsForResource"
]
};
/**
* Adds a resource of type application to the statement
*
* https://docs.aws.amazon.com/codedeploy/latest/userguide/auth-and-access-control-permissions-reference.html
*
* @param applicationName - Identifier for the applicationName.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onApplication(applicationName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:codedeploy:${Region}:${Account}:application:${ApplicationName}';
arn = arn.replace('${ApplicationName}', applicationName);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type deploymentconfig to the statement
*
* https://docs.aws.amazon.com/codedeploy/latest/userguide/auth-and-access-control-permissions-reference.html
*
* @param deploymentConfigurationName - Identifier for the deploymentConfigurationName.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onDeploymentconfig(deploymentConfigurationName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:codedeploy:${Region}:${Account}:deploymentconfig:${DeploymentConfigurationName}';
arn = arn.replace('${DeploymentConfigurationName}', deploymentConfigurationName);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type deploymentgroup to the statement
*
* https://docs.aws.amazon.com/codedeploy/latest/userguide/auth-and-access-control-permissions-reference.html
*
* @param applicationName - Identifier for the applicationName.
* @param deploymentGroupName - Identifier for the deploymentGroupName.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onDeploymentgroup(applicationName: string, deploymentGroupName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:codedeploy:${Region}:${Account}:deploymentgroup:${ApplicationName}/${DeploymentGroupName}';
arn = arn.replace('${ApplicationName}', applicationName);
arn = arn.replace('${DeploymentGroupName}', deploymentGroupName);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type instance to the statement
*
* https://docs.aws.amazon.com/codedeploy/latest/userguide/auth-and-access-control-permissions-reference.html
*
* @param instanceName - Identifier for the instanceName.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onInstance(instanceName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:codedeploy:${Region}:${Account}:instance:${InstanceName}';
arn = arn.replace('${InstanceName}', instanceName);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
} | the_stack |
import { OperationVariables } from '@apollo/client/core'
import { useSubscription } from '../../src'
import {
ExampleDocument,
ExampleUpdatedSubscription,
ExampleUpdatedSubscriptionVariables,
ExampleTypedSubscriptionDocument,
} from '../fixtures/graphql-example-types'
import { assertExactType } from './assertions'
// =============================================================================
// With no types:
// - TResult should be `any`
// - TVariables should be `undefined`
// =============================================================================
{
const useSubscription_NoTypes = useSubscription(ExampleDocument)
// Result type should match the passed in subscription type
const useSubscription_NoTypesResult = useSubscription_NoTypes.result.value
useSubscription_NoTypesResult.type.is.any
// Variables type should be `undefined`
const useSubscription_NoTypesVariables = useSubscription_NoTypes.variables.value
assertExactType<typeof useSubscription_NoTypesVariables, undefined>(
useSubscription_NoTypesVariables,
)
// Result data type should be any
useSubscription_NoTypes.onResult(result => result?.data.type.is.any)
}
// =============================================================================
// With only subscription type:
// - TResult should be the subscription type
// - TVariables should be `undefined`
// =============================================================================
{
const useSubscription_OnlySubscriptionType = useSubscription<ExampleUpdatedSubscription>(
ExampleDocument,
)
// Result type should match the passed in subscription type
const useSubscription_OnlySubscriptionTypeResult =
useSubscription_OnlySubscriptionType.result.value
assertExactType<typeof useSubscription_OnlySubscriptionTypeResult, ExampleUpdatedSubscription | null | undefined>(
useSubscription_OnlySubscriptionTypeResult,
)
// Variables type should be `undefined`
const useSubscription_OnlySubscriptionTypeVariables =
useSubscription_OnlySubscriptionType.variables.value
assertExactType<typeof useSubscription_OnlySubscriptionTypeVariables, undefined>(
useSubscription_OnlySubscriptionTypeVariables,
)
// Result data type should be the passed in result
useSubscription_OnlySubscriptionType.onResult(result => result?.data?.exampleUpdated.name)
}
// =============================================================================
// With only Subscription type but passing in variables:
// - TResult should be the Subscription type
// - TVariables should be OperationVariables
// =============================================================================
{
const useSubscription_WithVars = useSubscription<ExampleUpdatedSubscription>(ExampleDocument, {
id: 'asdf',
})
// Result type should match the passed in subscription type
const useSubscription_WithVarsResult = useSubscription_WithVars.result.value
assertExactType<typeof useSubscription_WithVarsResult, ExampleUpdatedSubscription | null | undefined>(
useSubscription_WithVarsResult,
)
// Variables type should match the passed in variables type
const useSubscription_WithVarsVariables = useSubscription_WithVars.variables.value
assertExactType<typeof useSubscription_WithVarsVariables, OperationVariables | undefined>(
useSubscription_WithVarsVariables,
)
// Result data type should be the passed in result
useSubscription_WithVars.onResult(result => result?.data?.exampleUpdated.name)
}
// =============================================================================
// With all types
// - TResult should be the subscription type
// - TVariables should be the variables type
// =============================================================================
{
const useSubscription_AllTyped = useSubscription<
ExampleUpdatedSubscription,
ExampleUpdatedSubscriptionVariables
>(ExampleDocument, { id: 'k3x47b' })
// Result type should match the passed in subscription type
const useSubscription_AllTypedResult = useSubscription_AllTyped.result.value
assertExactType<typeof useSubscription_AllTypedResult, ExampleUpdatedSubscription | null | undefined>(
useSubscription_AllTypedResult,
)
// Variables type should match the passed in variables type
const useSubscription_AllTypedVariables = useSubscription_AllTyped.variables.value
assertExactType<typeof useSubscription_AllTypedVariables, ExampleUpdatedSubscriptionVariables | undefined>(
useSubscription_AllTypedVariables,
)
// Result data type should be the passed in result
useSubscription_AllTyped.onResult(result => result?.data?.exampleUpdated.name)
}
// =============================================================================
// With all types and without variables because the query has optional variables
// - TResult should be the subscription type
// - TVariables should be the variables type
// =============================================================================
{
const useSubscription_AllTyped = useSubscription<
ExampleUpdatedSubscription,
ExampleUpdatedSubscriptionVariables
>(ExampleDocument)
// Result type should match the passed in subscription type
const useSubscription_AllTypedResult = useSubscription_AllTyped.result.value
assertExactType<typeof useSubscription_AllTypedResult, ExampleUpdatedSubscription | null | undefined>(
useSubscription_AllTypedResult,
)
// Variables type should match the passed in variables type
const useSubscription_AllTypedVariables = useSubscription_AllTyped.variables.value
assertExactType<typeof useSubscription_AllTypedVariables, ExampleUpdatedSubscriptionVariables | undefined>(
useSubscription_AllTypedVariables,
)
// Result data type should be the passed in result
useSubscription_AllTyped.onResult(result => result?.data?.exampleUpdated.name)
}
// =============================================================================
// With subscription types, and no variables
// - TResult should be the subscription type
// - TVariables should be `undefined`
// =============================================================================
{
const useSubscription_OnlySubscriptionType_NoVarsWithOptions = useSubscription<
ExampleUpdatedSubscription
>(ExampleDocument, undefined, {
clientId: '89E3Yh',
})
// Result type should match the passed in subscription type
const useSubscription_OnlySubscriptionType_NoVarsWithOptionsResult =
useSubscription_OnlySubscriptionType_NoVarsWithOptions.result.value
assertExactType<
typeof useSubscription_OnlySubscriptionType_NoVarsWithOptionsResult,
ExampleUpdatedSubscription | null | undefined
>(useSubscription_OnlySubscriptionType_NoVarsWithOptionsResult)
// Variables type should be `undefined`
const useSubscription_OnlySubscriptionType_NoVarsWithOptionsVariables =
useSubscription_OnlySubscriptionType_NoVarsWithOptions.variables.value
assertExactType<
typeof useSubscription_OnlySubscriptionType_NoVarsWithOptionsVariables,
null | undefined
>(useSubscription_OnlySubscriptionType_NoVarsWithOptionsVariables)
// Result data type should be the passed in result
useSubscription_OnlySubscriptionType_NoVarsWithOptions.onResult(
result => result?.data?.exampleUpdated.name,
)
}
// =============================================================================
// With subscription types, variables, and options
// - TResult should be the subscription type
// - TVariables should be the variables type
// =============================================================================
{
const useSubscription_WithOptions = useSubscription<
ExampleUpdatedSubscription,
ExampleUpdatedSubscriptionVariables
>(
ExampleDocument,
{ id: '4E79Lq' },
{
clientId: '8nf38r',
debounce: 1500,
enabled: true,
fetchPolicy: 'cache-first',
throttle: 1500,
},
)
const useSubscription_WithOptionsResult = useSubscription_WithOptions.result.value
assertExactType<typeof useSubscription_WithOptionsResult, ExampleUpdatedSubscription | null | undefined>(
useSubscription_WithOptionsResult,
)
const useSubscription_WithOptionsVariables = useSubscription_WithOptions.variables.value
assertExactType<typeof useSubscription_WithOptionsVariables, ExampleUpdatedSubscriptionVariables | undefined>(
useSubscription_WithOptionsVariables,
)
// Result data type should be the passed in result
useSubscription_WithOptions.onResult(result => result?.data?.exampleUpdated.name)
}
// =============================================================================
// With a TypedQueryDocument:
// - TResult should be the subscription type
// - TVariables should be the variables type
// =============================================================================
{
const useSubscription_AllTyped = useSubscription(ExampleTypedSubscriptionDocument, { id: 'k3x47b' })
// Result type should match the passed in subscription type
const useSubscription_AllTypedResult = useSubscription_AllTyped.result.value
assertExactType<typeof useSubscription_AllTypedResult, ExampleUpdatedSubscription | null | undefined>(
useSubscription_AllTypedResult,
)
// Variables type should match the passed in variables type
const useSubscription_AllTypedVariables = useSubscription_AllTyped.variables.value
assertExactType<typeof useSubscription_AllTypedVariables, ExampleUpdatedSubscriptionVariables | undefined>(
useSubscription_AllTypedVariables,
)
// Result data type should be the passed in result
useSubscription_AllTyped.onResult(result => result?.data?.exampleUpdated.name)
}
// // ====== Expected failures, uncomment to test ======
// // @ts-expect-error - should require variables to be OperationType
// const useSubscription_NoTypesBadVariables = useSubscription(ExampleDocument, 'failme')
// // @ts-expect-error - should require variables to be OperationType
// const useSubscriptionBadSubscriptionVariables = useSubscription<ExampleUpdatedSubscription>(ExampleDocument, 'failme')
// // @ts-expect-error - should require variables to be OperationType
// const useSubscriptionBadVariables = useSubscription<ExampleUpdatedSubscription, ExampleUpdatedSubscriptionVariables>(ExampleDocument, 'failme')
// // @ts-expect-error - this should expect two arguments
// const useSubscription_AllTypedMissingVariables = useSubscription<ExampleUpdatedSubscription, ExampleUpdatedSubscriptionVariables>(ExampleDocument) | the_stack |
import { Loki } from "../../loki/src/loki";
import { StorageAdapter } from "../../common/types";
import { PLUGINS } from "../../common/plugin";
/**
* An adapter for adapters. Converts a non reference mode adapter into a reference mode adapter
* which can perform destructuring and partitioning. Each collection will be stored in its own key/save and
* only dirty collections will be saved. If you turn on paging with default page size of 25megs and save
* a 75 meg collection it should use up roughly 3 save slots (key/value pairs sent to inner adapter).
* A dirty collection that spans three pages will save all three pages again
* Paging mode was added mainly because Chrome has issues saving 'too large' of a string within a
* single IndexedDB row. If a single document update causes the collection to be flagged as dirty, all
* of that collection's pages will be written on next save.
*/
export class PartitioningAdapter implements StorageAdapter {
public mode: string;
private _adapter: StorageAdapter;
private _dbref: Loki;
private _dbname: string;
private _pageIterator: PartitioningAdapter.PageIterator;
private _paging: boolean;
private _pageSize: number;
private _delimiter: string;
private _dirtyPartitions: number[];
/**
* Registers the partitioning adapter as plugin.
*/
static register(): void {
PLUGINS["PartitioningAdapter"] = PartitioningAdapter;
}
/**
* Deregisters the partitioning storage as plugin.
*/
static deregister(): void {
delete PLUGINS["PartitioningAdapter"];
}
/**
* @param {object} adapter - reference to a 'non-reference' mode loki adapter instance.
* @param {boolean} paging - (default: false) set to true to enable paging collection data.
* @param {number} pageSize - (default : 25MB) you can use this to limit size of strings passed to inner adapter.
* @param {string} delimiter - allows you to override the default delimiter
*/
constructor(adapter: StorageAdapter, {paging = false, pageSize = 25 * 1024 * 1024, delimiter = "$<\n"} = {}) {
this.mode = "reference";
this._adapter = null;
this._dbref = null;
this._dbname = "";
this._pageIterator = {};
// verify user passed an appropriate adapter
if (adapter) {
if (adapter.mode === "reference") {
throw new Error("LokiPartitioningAdapter cannot be instantiated with a reference mode adapter.");
} else {
this._adapter = adapter;
}
} else {
throw new Error("LokiPartitioningAdapter requires a (non-reference mode) adapter on construction.");
}
this._paging = paging;
this._pageSize = pageSize;
this._delimiter = delimiter;
}
/**
* Loads a database which was partitioned into several key/value saves.
* (Loki persistence adapter interface function)
*
* @param {string} dbname - name of the database (filename/keyname)
* @returns {Promise} a Promise that resolves after the database was loaded
*/
public loadDatabase(dbname: string): Promise<any> {
this._dbname = dbname;
this._dbref = new Loki(dbname);
// load the db container (without data)
return this._adapter.loadDatabase(dbname).then((result: string) => {
if (typeof result !== "string") {
throw new Error("LokiPartitioningAdapter received an unexpected response from inner adapter loadDatabase()");
}
// I will want to use loki destructuring helper methods so i will inflate into typed instance
let db = JSON.parse(result);
this._dbref.loadJSONObject(db);
db = null;
if (this._dbref._collections.length === 0) {
return this._dbref;
}
this._pageIterator = {
collection: 0,
pageIndex: 0
};
return this._loadNextPartition(0).then(() => this._dbref);
});
}
/**
* Used to sequentially load each collection partition, one at a time.
*
* @param {int} partition - ordinal collection position to load next
* @returns {Promise} a Promise that resolves after the next partition is loaded
*/
private _loadNextPartition(partition: number): Promise<void> {
if (this._paging === true) {
this._pageIterator.pageIndex = 0;
return this._loadNextPage();
}
const keyname = this._dbname + "." + partition;
return this._adapter.loadDatabase(keyname).then((result: string) => {
this._dbref._collections[partition]._data = this._dbref.deserializeCollection(result, {
delimited: true
});
if (++partition < this._dbref._collections.length) {
return this._loadNextPartition(partition);
}
return Promise.resolve();
});
}
/**
* Used to sequentially load the next page of collection partition, one at a time.
*
* @returns {Promise} a Promise that resolves after the next page is loaded
*/
private _loadNextPage(): Promise<void> {
// calculate name for next saved page in sequence
const keyname = this._dbname + "." + this._pageIterator.collection + "." + this._pageIterator.pageIndex;
// load whatever page is next in sequence
return this._adapter.loadDatabase(keyname).then((result: string) => {
let data = result.split(this._delimiter);
result = ""; // free up memory now that we have split it into array
let dlen = data.length;
// detect if last page by presence of final empty string element and remove it if so
const isLastPage = (data[dlen - 1] === "");
if (isLastPage) {
data.pop();
dlen = data.length;
// empty collections are just a delimiter meaning two blank items
if (data[dlen - 1] === "" && dlen === 1) {
data.pop();
dlen = data.length;
}
}
// convert stringified array elements to object instances and push to collection data
for (let idx = 0; idx < dlen; idx++) {
this._dbref._collections[this._pageIterator.collection]._data.push(JSON.parse(data[idx]));
data[idx] = null;
}
data = [];
// if last page, we are done with this partition
if (isLastPage) {
// if there are more partitions, kick off next partition load
if (++this._pageIterator.collection < this._dbref._collections.length) {
return this._loadNextPartition(this._pageIterator.collection);
}
} else {
this._pageIterator.pageIndex++;
return this._loadNextPage();
}
return Promise.resolve();
});
}
/**
* Saves a database by partioning into separate key/value saves.
* (Loki 'reference mode' persistence adapter interface function)
*
* @param {string} dbname - name of the database (filename/keyname)
* @param {object} dbref - reference to database which we will partition and save.
* @returns {Promise} a Promise that resolves after the database was deleted
*
*/
public exportDatabase(dbname: string, dbref: Loki): Promise<void> {
this._dbref = dbref;
this._dbname = dbname;
// queue up dirty partitions to be saved
this._dirtyPartitions = [-1];
for (let idx = 0; idx < dbref._collections.length; idx++) {
if (dbref._collections[idx]._dirty) {
this._dirtyPartitions.push(idx);
}
}
return this._saveNextPartition();
}
/**
* Helper method used internally to save each dirty collection, one at a time.
*
* @returns {Promise} a Promise that resolves after the next partition is saved
*/
private _saveNextPartition(): Promise<void> {
const partition = this._dirtyPartitions.shift();
const keyname = this._dbname + ((partition === -1) ? "" : ("." + partition));
// if we are doing paging and this is collection partition
if (this._paging && partition !== -1) {
this._pageIterator = {
collection: partition,
docIndex: 0,
pageIndex: 0
};
// since saveNextPage recursively calls itself until done, our callback means this whole paged partition is finished
return this._saveNextPage().then(() => {
if (this._dirtyPartitions.length !== 0) {
return this._saveNextPartition();
}
return Promise.resolve();
});
}
// otherwise this is 'non-paged' partioning...
const result = this._dbref.serializeDestructured({
partitioned: true,
delimited: true,
partition
});
return this._adapter.saveDatabase(keyname, result as string).then(() => {
if (this._dirtyPartitions.length !== 0) {
return this._saveNextPartition();
}
return Promise.resolve();
});
}
/**
* Helper method used internally to generate and save the next page of the current (dirty) partition.
*
* @returns {Promise} a Promise that resolves after the next partition is saved
*/
private _saveNextPage(): Promise<void> {
const coll = this._dbref._collections[this._pageIterator.collection];
const keyname = this._dbname + "." + this._pageIterator.collection + "." + this._pageIterator.pageIndex;
let pageLen = 0;
const cdlen = coll._data.length;
const delimlen = this._delimiter.length;
let serializedObject = "";
let pageBuilder = "";
let doneWithPartition = false;
let doneWithPage = false;
const pageSaveCallback = () => {
pageBuilder = "";
// update meta properties then continue process by invoking callback
if (!doneWithPartition) {
this._pageIterator.pageIndex++;
return this._saveNextPage();
}
return Promise.resolve();
};
if (coll._data.length === 0) {
doneWithPartition = true;
}
while (!doneWithPartition && !doneWithPage) {
if (!doneWithPartition) {
// serialize object
serializedObject = JSON.stringify(coll._data[this._pageIterator.docIndex]);
pageBuilder += serializedObject;
pageLen += serializedObject.length;
// if no more documents in collection to add, we are done with partition
if (++this._pageIterator.docIndex >= cdlen) doneWithPartition = true;
}
// if our current page is bigger than defined pageSize, we are done with page
if (pageLen >= this._pageSize) doneWithPage = true;
// if not done with current page, need delimiter before next item
// if done with partition we also want a delmiter to indicate 'end of pages' final empty row
if (!doneWithPage || doneWithPartition) {
pageBuilder += this._delimiter;
pageLen += delimlen;
}
}
// if we are done with page save it and pass off to next recursive call or callback
return this._adapter.saveDatabase(keyname, pageBuilder).then(pageSaveCallback);
}
}
namespace PartitioningAdapter {
export interface PageIterator {
collection?: number;
docIndex?: number;
pageIndex?: number;
}
} | the_stack |
import React from "react";
import { render } from "react-dom";
import clone from "clone-deep";
import { act, Simulate } from "react-dom/test-utils";
import { useConnect } from "frontity";
import useInfiniteScroll from "../../use-infinite-scroll";
import * as useArchiveInfiniteScroll from "../";
jest.mock("../../use-infinite-scroll", () => ({
__esModule: true,
default: jest.fn(),
}));
jest.mock("frontity", () => ({
useConnect: jest.fn(),
connect: jest.fn((fn) => fn),
css: jest.fn(),
}));
const App = ({ options }: { options?: any }) => {
useArchiveInfiniteScroll.default(options);
return <div />;
};
const AppWithButton = ({ options }: { options?: any }) => {
const { fetchNext } = useArchiveInfiniteScroll.default(options);
return (
<div>
<button onClick={fetchNext}>Fetch Next</button>
</div>
);
};
let container: HTMLDivElement;
const spiedUseArchiveInfiniteScroll = jest.spyOn(
useArchiveInfiniteScroll,
"default"
);
const mockedUseInfiniteScroll = useInfiniteScroll as jest.MockedFunction<
typeof useInfiniteScroll
>;
const mockedUseConnect = useConnect as jest.MockedFunction<typeof useConnect>;
const sourceGet = jest.fn();
const sourceFetch = jest.fn();
const routerUpdateState = jest.fn();
const browserState: { [key: string]: unknown; infiniteScroll?: unknown } = {
someOtherPackage: {},
};
const initialStore = {
state: {
router: {
link: "/",
state: browserState,
},
source: {
get: sourceGet,
},
},
actions: {
source: { fetch: sourceFetch },
router: { updateState: routerUpdateState },
},
};
let store = initialStore;
beforeEach(() => {
store = clone(initialStore);
container = document.createElement("div");
container.id = "container";
document.body.appendChild(container);
mockedUseConnect.mockReturnValue(store);
});
afterEach(() => {
document.body.removeChild(container);
container = null;
spiedUseArchiveInfiniteScroll.mockClear();
mockedUseInfiniteScroll.mockReset();
mockedUseConnect.mockReset();
sourceGet.mockReset();
sourceFetch.mockReset();
routerUpdateState.mockReset();
});
describe("useArchiveInfiniteScroll", () => {
test("should update the browser state on mount (without existing state)", () => {
sourceGet.mockReturnValue({
link: "/",
isReady: false,
isFetching: false,
});
act(() => {
render(<App />, container);
});
expect(spiedUseArchiveInfiniteScroll).toHaveBeenCalledTimes(1);
expect(routerUpdateState).toHaveBeenCalledTimes(1);
expect(routerUpdateState).toHaveBeenCalledWith({
someOtherPackage: {},
infiniteScroll: {
links: ["/"],
},
});
});
test("should update the browser state on mount (with existing state)", () => {
store.state.router.state.infiniteScroll = {
limit: 2,
links: ["/", "/page/2/", "/page/3/"],
};
sourceGet.mockReturnValue({
link: "/page/3/",
isReady: false,
isFetching: false,
});
act(() => {
render(<App />, container);
});
expect(spiedUseArchiveInfiniteScroll).toHaveBeenCalledTimes(1);
expect(routerUpdateState).toHaveBeenCalledTimes(1);
expect(routerUpdateState).toHaveBeenCalledWith({
someOtherPackage: {},
infiniteScroll: {
limit: 2,
links: ["/", "/page/2/", "/page/3/"],
},
});
});
test("should update the browser state on mount (with options)", () => {
sourceGet.mockReturnValue({
link: "/",
isReady: false,
isFetching: false,
});
act(() => {
render(<App options={{ limit: 3 }} />, container);
});
expect(spiedUseArchiveInfiniteScroll).toHaveBeenCalledTimes(1);
expect(routerUpdateState).toHaveBeenCalledTimes(1);
expect(routerUpdateState).toHaveBeenCalledWith({
someOtherPackage: {},
infiniteScroll: {
limit: 3,
links: ["/"],
},
});
});
test("should not update the browser state if `options.active` is false", () => {
sourceGet.mockReturnValue({
link: "/",
isReady: false,
isFetching: false,
});
act(() => {
render(<App options={{ active: false }} />, container);
});
expect(spiedUseArchiveInfiniteScroll).toHaveBeenCalledTimes(1);
expect(routerUpdateState).not.toHaveBeenCalled();
});
test("should return the right object", () => {
store.state.router.link = "/page/2/";
store.state.router.state.infiniteScroll = {
links: ["/", "/page/2/", "/page/3/"],
};
sourceGet.mockReturnValue({
link: "/page/3/",
isReady: true,
isFetching: false,
});
act(() => {
render(<App />, container);
});
expect(spiedUseArchiveInfiniteScroll).toHaveBeenCalledTimes(1);
expect(spiedUseArchiveInfiniteScroll).toHaveReturnedWith({
pages: [
{
key: "/",
link: "/",
isLast: false,
Wrapper: expect.any(Function),
},
{
key: "/page/2/",
link: "/page/2/",
isLast: false,
Wrapper: expect.any(Function),
},
{
key: "/page/3/",
link: "/page/3/",
isLast: true,
Wrapper: expect.any(Function),
},
],
isLimit: false,
isFetching: false,
isError: false,
fetchNext: expect.any(Function),
});
});
test("should return `isLast` false when the last page is not ready", () => {
store.state.router.link = "/page/2/";
store.state.router.state.infiniteScroll = {
links: ["/", "/page/2/", "/page/3/"],
};
sourceGet.mockReturnValue({
link: "/page/3/",
isReady: false,
isFetching: false,
});
act(() => {
render(<App />, container);
});
expect(spiedUseArchiveInfiniteScroll).toHaveBeenCalledTimes(1);
expect(spiedUseArchiveInfiniteScroll).toHaveReturnedWith({
pages: [
{
key: "/",
link: "/",
isLast: false,
Wrapper: expect.any(Function),
},
{
key: "/page/2/",
link: "/page/2/",
isLast: true,
Wrapper: expect.any(Function),
},
{
key: "/page/3/",
link: "/page/3/",
isLast: false,
Wrapper: expect.any(Function),
},
],
isLimit: false,
isFetching: false,
isError: false,
fetchNext: expect.any(Function),
});
});
test("should return `isLimit` true when limit has been reached, there is next page, and it's not being fetched", () => {
store.state.router.state.infiniteScroll = { links: ["/"] };
sourceGet.mockReturnValue({
link: "/",
next: "/page/2/",
isArchive: true,
isReady: true,
isFetching: false,
});
act(() => {
render(<App options={{ limit: 1 }} />, container);
});
expect(spiedUseArchiveInfiniteScroll).toHaveBeenCalledTimes(1);
expect(spiedUseArchiveInfiniteScroll).toHaveReturnedWith({
pages: [
{
key: "/",
link: "/",
isLast: true,
Wrapper: expect.any(Function),
},
],
isLimit: true,
isFetching: false,
isError: false,
fetchNext: expect.any(Function),
});
});
test("should return `isLimit` false and `isFetching` true when limit has been reached, there is next page but is already being fetched", () => {
store.state.router.state.infiniteScroll = { links: ["/", "/page/2/"] };
sourceGet.mockReturnValue({
link: "/page/2/",
next: "/page/3/",
isArchive: true,
isReady: false,
isFetching: true,
});
act(() => {
render(<App options={{ limit: 1 }} />, container);
});
expect(spiedUseArchiveInfiniteScroll).toHaveBeenCalledTimes(1);
expect(spiedUseArchiveInfiniteScroll).toHaveReturnedWith({
pages: [
{
key: "/",
link: "/",
isLast: true,
Wrapper: expect.any(Function),
},
{
key: "/page/2/",
link: "/page/2/",
isLast: false,
Wrapper: expect.any(Function),
},
],
isLimit: false,
isFetching: true,
isError: false,
fetchNext: expect.any(Function),
});
});
test("should return `isLimit` false when limit has been reached but there isn't a next page", () => {
sourceGet.mockReturnValue({
link: "/",
isReady: true,
isFetching: false,
});
act(() => {
render(<App options={{ limit: 1 }} />, container);
});
expect(spiedUseArchiveInfiniteScroll).toHaveBeenCalledTimes(1);
expect(spiedUseArchiveInfiniteScroll).toHaveReturnedWith({
pages: [
{
key: "/",
link: "/",
isLast: true,
Wrapper: expect.any(Function),
},
],
isLimit: false,
isFetching: false,
isError: false,
fetchNext: expect.any(Function),
});
});
test("should return `isLimit` false when the limit has not been reached", () => {
sourceGet.mockReturnValue({
link: "/",
next: "/page/2/",
isArchive: true,
isReady: true,
isFetching: false,
});
act(() => {
render(<App options={{ limit: 3 }} />, container);
});
expect(spiedUseArchiveInfiniteScroll).toHaveBeenCalledTimes(1);
expect(spiedUseArchiveInfiniteScroll).toHaveReturnedWith({
pages: [
{
key: "/",
link: "/",
isLast: true,
Wrapper: expect.any(Function),
},
],
isLimit: false,
isFetching: false,
isError: false,
fetchNext: expect.any(Function),
});
});
test("should return `isError` true when current page is unavailable", () => {
store.state.router.state.infiniteScroll = { links: ["/", "/page/2/"] };
sourceGet.mockReturnValue({
isReady: true,
isError: true,
isFetching: false,
});
act(() => {
render(<App />, container);
});
expect(spiedUseArchiveInfiniteScroll).toHaveBeenCalledTimes(1);
expect(spiedUseArchiveInfiniteScroll).toHaveReturnedWith({
pages: [
{
key: "/",
link: "/",
isLast: true,
Wrapper: expect.any(Function),
},
{
key: "/page/2/",
link: "/page/2/",
isLast: false,
Wrapper: expect.any(Function),
},
],
isLimit: false,
isFetching: false,
isError: true,
fetchNext: expect.any(Function),
});
});
test("`fetchNext` should fetch next page if it's not ready and not fetching", () => {
sourceGet.mockReturnValue({
link: "/",
next: "/page/2/",
isArchive: true,
isReady: true,
isFetching: false,
});
act(() => {
render(<AppWithButton options={{ limit: 1 }} />, container);
});
routerUpdateState.mockClear();
sourceGet.mockReturnValue({
link: "/page/2/",
isReady: false,
isFetching: false,
});
act(() => {
Simulate.click(container.querySelector("button"));
});
expect(routerUpdateState).toHaveBeenCalledTimes(1);
expect(routerUpdateState).toHaveBeenCalledWith({
someOtherPackage: {},
infiniteScroll: {
links: ["/", "/page/2/"],
},
});
expect(sourceFetch).toHaveBeenCalledTimes(1);
expect(sourceFetch).toHaveBeenCalledWith("/page/2/");
});
test("`fetchNext` should not fetch next page if it's ready", () => {
sourceGet.mockReturnValue({
link: "/",
next: "/page/2/",
isArchive: true,
isReady: true,
isFetching: false,
});
act(() => {
render(<AppWithButton options={{ limit: 1 }} />, container);
});
routerUpdateState.mockClear();
sourceGet.mockReturnValue({
link: "/page/2/",
isReady: true,
isFetching: false,
});
act(() => {
Simulate.click(container.querySelector("button"));
});
expect(routerUpdateState).toHaveBeenCalledTimes(1);
expect(routerUpdateState).toHaveBeenCalledWith({
someOtherPackage: {},
infiniteScroll: {
links: ["/", "/page/2/"],
},
});
expect(sourceFetch).not.toHaveBeenCalled();
});
test("`fetchNext` should not fetch next page if it's fetching", () => {
sourceGet.mockReturnValue({
link: "/",
next: "/page/2/",
isArchive: true,
isReady: true,
isFetching: false,
});
act(() => {
render(<AppWithButton options={{ limit: 1 }} />, container);
});
routerUpdateState.mockClear();
sourceGet.mockReturnValue({
link: "/page/2/",
isReady: false,
isFetching: true,
});
act(() => {
Simulate.click(container.querySelector("button"));
});
expect(routerUpdateState).toHaveBeenCalledTimes(1);
expect(routerUpdateState).toHaveBeenCalledWith({
someOtherPackage: {},
infiniteScroll: {
links: ["/", "/page/2/"],
},
});
expect(sourceFetch).not.toHaveBeenCalled();
});
test("`fetchNext` should do nothing if there isn't next page", () => {
sourceGet.mockReturnValue({
link: "/",
isReady: true,
isFetching: false,
});
act(() => {
render(<AppWithButton options={{ limit: 1 }} />, container);
});
routerUpdateState.mockClear();
sourceGet.mockReturnValue({
link: "/page/2/",
isReady: false,
isFetching: false,
});
act(() => {
Simulate.click(container.querySelector("button"));
});
expect(routerUpdateState).not.toHaveBeenCalled();
expect(sourceFetch).not.toHaveBeenCalled();
});
test("`fetchNext` should do nothing if the next page is already in the links", () => {
store.state.router.state.infiniteScroll = {
links: ["/page/2/", "/"],
};
sourceGet.mockReturnValue({
link: "/",
next: "/page/2/",
isArchive: true,
isReady: true,
isFetching: false,
});
act(() => {
render(<AppWithButton options={{ limit: 1 }} />, container);
});
routerUpdateState.mockClear();
sourceGet.mockReturnValue({
link: "/page/2/",
isReady: false,
isFetching: false,
});
act(() => {
Simulate.click(container.querySelector("button"));
});
expect(routerUpdateState).not.toHaveBeenCalled();
expect(sourceFetch).not.toHaveBeenCalled();
});
test("`fetchNext` should do nothing if `options.active` is false", () => {
store.state.router.link = "/page-one/";
sourceGet.mockReturnValue({
link: "/page-one/",
next: "/page-two/",
isArchive: true,
isReady: true,
isFetching: false,
});
act(() => {
render(<AppWithButton options={{ active: false }} />, container);
});
routerUpdateState.mockClear();
sourceGet.mockReturnValue({
link: "/page-two/",
isReady: false,
isFetching: false,
});
act(() => {
Simulate.click(container.querySelector("button"));
});
expect(routerUpdateState).not.toHaveBeenCalled();
expect(sourceFetch).not.toHaveBeenCalled();
});
test("`fetchNext` should request the last page if `isError` is true", () => {
store.state.router.link = "/page-one/";
sourceGet.mockReturnValue({
isReady: true,
isFetching: false,
isError: true,
});
act(() => {
render(<AppWithButton />, container);
});
routerUpdateState.mockClear();
act(() => {
Simulate.click(container.querySelector("button"));
});
expect(routerUpdateState).not.toHaveBeenCalled();
expect(sourceFetch).toHaveBeenCalledTimes(1);
expect(sourceFetch).toHaveBeenCalledWith("/page-one/", { force: true });
});
});
describe("Wrapper", () => {
test("should return children if IntersectionObserver is not supported", () => {
const Wrapper = useArchiveInfiniteScroll.wrapperGenerator({ link: "/" });
sourceGet.mockReturnValue({
isReady: true,
});
mockedUseInfiniteScroll.mockReturnValue({ supported: false });
act(() => {
render(
<Wrapper key="fake-key">
<div id="children" />
</Wrapper>,
container
);
});
expect(mockedUseInfiniteScroll).toHaveBeenCalledTimes(1);
expect(container).toMatchSnapshot();
});
test("should return null if the current element is not ready", () => {
const Wrapper = useArchiveInfiniteScroll.wrapperGenerator({ link: "/" });
sourceGet.mockReturnValue({
isReady: false,
});
mockedUseInfiniteScroll.mockReturnValue({ supported: false });
act(() => {
render(
<Wrapper key="fake-key">
<div id="children" />
</Wrapper>,
container
);
});
expect(mockedUseInfiniteScroll).toHaveBeenCalledTimes(1);
expect(container).toMatchSnapshot();
});
test("should return children inside a wrapper", () => {
store.state.router.state.infiniteScroll = { limit: 1 };
const Wrapper = useArchiveInfiniteScroll.wrapperGenerator({ link: "/" });
sourceGet.mockReturnValue({ isReady: true });
mockedUseInfiniteScroll.mockReturnValue({
supported: true,
fetchRef: jest.fn(),
routeRef: jest.fn(),
} as any);
act(() => {
render(
<Wrapper key="fake-key">
<div id="children" />
</Wrapper>,
container
);
});
expect(mockedUseInfiniteScroll).toHaveBeenCalledTimes(1);
expect(container).toMatchSnapshot();
});
test("should return children and fetcher inside a wrapper", () => {
const Wrapper = useArchiveInfiniteScroll.wrapperGenerator({ link: "/" });
sourceGet.mockReturnValue({ isReady: true });
mockedUseInfiniteScroll.mockReturnValue({
supported: true,
fetchRef: jest.fn(),
routeRef: jest.fn(),
} as any);
act(() => {
render(
<Wrapper key="fake-key">
<div id="children" />
</Wrapper>,
container
);
});
expect(mockedUseInfiniteScroll).toHaveBeenCalledTimes(1);
expect(container).toMatchSnapshot();
});
test("should call `useInfiniteScroll` with `currentLink` and `nextLink`", () => {
const Wrapper = useArchiveInfiniteScroll.wrapperGenerator({ link: "/" });
const firstData = {
next: "/page/2/",
isArchive: true,
isReady: true,
};
const secondData = {
link: "/page/2/",
isReady: false,
};
sourceGet
// The first state.source.get() of the ArchiveWrapper, which needs it to
// check if there is a next page.
.mockReturnValueOnce(firstData)
// The second state.source.get() of the ArchiveWrapper, which needs it to
// get the link of the next page.
.mockReturnValueOnce(secondData)
// The state.source.get() of the InternalWrapper, which needs it to see if
// the current link is ready or is an error.
.mockReturnValueOnce(firstData);
mockedUseInfiniteScroll.mockReturnValue({
supported: true,
fetchRef: jest.fn(),
routeRef: jest.fn(),
} as any);
act(() => {
render(
<Wrapper key="fake-key">
<div id="children" />
</Wrapper>,
container
);
});
expect(mockedUseInfiniteScroll).toHaveBeenCalledTimes(1);
expect(mockedUseInfiniteScroll).toHaveBeenCalledWith({
currentLink: "/",
nextLink: "/page/2/",
});
});
}); | the_stack |
declare namespace JQueryTouchSwipe {
/**
* Event handler for pointer related events.
*/
export type PointerHandler =
/**
* @param event The original event object
* @param target The element clicked on.
*/
(this: HTMLElement, event: JQuery.TriggeredEvent, target: HTMLElement) => void;
/**
* Event handler for swipe related events.
*/
export type SwipeHandler =
/**
* @param event The original event object
* @param direction The direction the user swiped in.
* @param distance The distance the user swiped.
* @param duration The duration of the swipe in milliseconds.
* @param fingerCount The number of fingers used.
* @param fingerData The coordinates of fingers in event.
* @param currentDirection The current direction the user is swiping.
*/
(
this: HTMLElement,
event: JQuery.TriggeredEvent,
direction: DirectionsEnum[keyof DirectionsEnum],
distance: number,
duration: number,
fingerCount: FingersEnum[keyof FingersEnum],
fingerData: FingerData,
currentDirection: DirectionsEnum[keyof DirectionsEnum]
) => void;
/**
* Event handler for swipe related events during a certain phase.
*/
export type SwipePhaseHandler =
/**
* @param event The original event object
* @param phase The phase of the swipe event.
* @param direction The direction the user swiped in.
* @param distance The distance the user swiped.
* @param duration The duration of the swipe in milliseconds.
* @param fingerCount The number of fingers used.
* @param fingerData The coordinates of fingers in event.
* @param currentDirection The current direction the user is swiping.
*/
(
this: HTMLElement,
event: JQuery.TriggeredEvent,
phase: PhasesEnum[keyof PhasesEnum],
direction: DirectionsEnum[keyof DirectionsEnum],
distance: number,
duration: number,
fingerCount: FingersEnum[keyof FingersEnum],
fingerData: FingerData,
currentDirection: DirectionsEnum[keyof DirectionsEnum]
) => void;
/**
* Event handler for pinch related events.
*/
export type PinchHandler =
/**
* @param event The original event object
* @param direction The direction the user swiped in.
* @param distance The distance the user swiped.
* @param duration The duration of the swipe in milliseconds.
* @param fingerCount The number of fingers used.
* @param zoom The zoom/scale level the user pinched too, 0-1.
* @param currentDirection The current direction the user is swiping.
*/
(
this: HTMLElement,
event: JQuery.TriggeredEvent,
direction: DirectionsEnum[keyof DirectionsEnum],
distance: number,
duration: number,
fingerCount: FingersEnum[keyof FingersEnum],
zoom: number,
currentDirection: DirectionsEnum[keyof DirectionsEnum]
) => void;
/**
* Event handler for pinch related events during a certain phase.
*/
export type PinchPhaseHandler =
/**
* @param event The original event object
* @param phase The phase of the swipe event.
* @param direction The direction the user swiped in.
* @param distance The distance the user swiped.
* @param duration The duration of the swipe in milliseconds.
* @param fingerCount The number of fingers used.
* @param zoom The zoom/scale level the user pinched too, 0-1.
* @param currentDirection The current direction the user is swiping.
*/
(
this: HTMLElement,
event: JQuery.TriggeredEvent,
phase: PhasesEnum[keyof PhasesEnum],
direction: DirectionsEnum[keyof DirectionsEnum],
distance: number,
duration: number,
fingerCount: FingersEnum[keyof FingersEnum],
zoom: number,
currentDirection: DirectionsEnum[keyof DirectionsEnum]
) => void;
/**
* The direction constants that are passed to the event handlers. These properties are read-only, attempting to
* change them will not alter the values passed to the event handlers.
*/
export interface DirectionsEnum {
/**
* Constant indicating the left direction.
*/
LEFT: "left";
/**
* Constant indicating the right direction.
*/
RIGHT: "right";
/**
* Constant indicating the up direction.
*/
UP: "up";
/**
* Constant indicating the down direction.
*/
DOWN: "down";
/**
* Constant indicating the in direction.
*/
IN: "in";
/**
* Constant indicating the out direction.
*/
OUT: "out";
}
/**
* Constants representing the number of fingers used in a swipe. These are used to set both the value of fingers in
* the options object, as well as the value of the fingers event property. These properties are read-only,
* attempting to change them will not alter the values passed to the event handlers.
*/
export interface FingersEnum {
/**
* Constant indicating 1 finger is to be detected / was detected.
*/
ONE: 1;
/**
* Constant indicating 2 finger is to be detected / was detected.
*/
TWO: 2;
/**
* Constant indicating 3 finger is to be detected / was detected.
*/
THREE: 3;
/**
* Constant indicating 4 finger is to be detected / was detected.
*/
FOUR: 4;
/**
* Constant indicating 5 finger is to be detected / was detected.
*/
FIVE: 5;
/**
* Constant indicating any combination of finger are to be detected.
*/
ALL: "all";
}
/**
* The page scroll constants that can be used to set the value of {@link TouchSwipeSettings.allowPageScroll} option.
* These properties are read-only.
*/
export interface PageScrollEnum {
/**
* Constant indicating no page scrolling is allowed.
*
* The page will not scroll when user swipes.
*/
NONE: "none";
/**
* Constant indicating horizontal page scrolling is allowed.
*
* Will force page to scroll on horizontal swipes.
*/
HORIZONTAL: "horizontal";
/**
* Constant indicating vertical page scrolling is allowed.
*
* Will force page to scroll on vertical swipes.
*/
VERTICAL: "vertical";
/**
* Constant indicating either horizontal or vertical will be allowed, depending on the swipe handlers
* registered.
*
* All undefined swipes will cause the page to scroll in that direction.
*/
AUTO: "auto";
}
/**
* The phases that a touch event goes through. The phase is passed to the event handlers. These properties are
* read-only, attempting to change them will not alter the values passed to the event handlers.
*/
export interface PhasesEnum {
/**
* Constant indicating the start phase of the touch event.
*/
PHASE_START: "start";
/**
* Constant indicating the move phase of the touch event.
*/
PHASE_MOVE: "move";
/**
* Constant indicating the end phase of the touch event.
*/
PHASE_END: "end";
/**
* Constant indicating the cancel phase of the touch event.
*/
PHASE_CANCEL: "cancel";
}
/**
* Represents some details about the position of the fingers.
*/
export interface FingerData {
/**
* The point where the swipe started.
*/
start: CartesianPoint;
/**
* The point where the finger(s) were more recently.
*/
last: CartesianPoint;
/**
* The point where the swipe ended.
*/
end: CartesianPoint;
}
/**
* Represents a two dimensional point in a cartesian coordinate system.
*/
export interface CartesianPoint {
/**
* The horizontal coordinate of the point.
*/
x: number;
/**
* The vertical coordinate of the point.
*/
y: number;
}
/**
* Optional settings that can be passed when creating a new touch swipe instance to customize its behavior.
*/
export interface TouchSwipeSettings {
/**
* A handler triggered when a user reaches {@link longTapThreshold} on the item.
*
* Defaults to `null`.
*/
hold: PointerHandler | null;
/**
* How the browser handles page scrolls when the user is swiping on a touchSwipe object. See {@link pageScroll}.
*
* Defaults to `auto`.
*/
allowPageScroll: PageScrollEnum[keyof PageScrollEnum];
/**
* The number of pixels that the user must move their finger back from the original swipe direction to cancel
* the gesture.
*
* Defaults to `null`.
*/
cancelThreshold: number | null;
/**
* A handler triggered when a user double taps on the item. The delay between taps can be set with the
* {@link doubleTapThreshold} property.
*
* Defaults to `null`.
*/
doubleTap: PointerHandler | null;
/**
* Time in milliseconds between 2 taps to count as a double tap.
*
* Defaults to `200`.
*/
doubleTapThreshold: number;
/**
* A jQuery selector that specifies child elements that do NOT trigger swipes. By default this excludes elements
* with the class `.noSwipe`.
*
* Defaults to `".noSwipe"`.
*/
excludedElements: string;
/**
* If `true` mouse events are used when run on a non-touch device, `false` will stop swipes being triggered by
* mouse events on non-touch devices.
*
* Defaults to `true`.
*/
fallbackToMouseEvents: boolean;
/**
* Time in milliseconds between releasing multiple fingers. If 2 fingers are down, and are released one after
* the other, if they are within this threshold, it counts as a simultaneous release.
*
* Defaults to `250`.
*/
fingerReleaseThreshold: number;
/**
* The number of fingers to detect in a swipe. Any swipes that do not meet this requirement will NOT trigger
* swipe handlers.
*
* Defaults to `1`.
*/
fingers: number;
/**
* A handler triggered when a user long taps on the item. The delay between start and end can be set with the
* {@link longTapThreshold} property.
*
* Defaults to `null`.
*/
longTap: PointerHandler | null;
/**
* Time in milliseconds between tap and release for a long tap.
*
* Defaults to `500`.
*/
longTapThreshold: number;
/**
* Time, in milliseconds, between `touchStart` and `touchEnd` must NOT exceed in order to be considered a swipe.
*
* Defaults to `null`.
*/
maxTimeThreshold: number | null;
/**
* A handler triggered for pinch in events. See also the `pinchIn` event.
*
* Defaults to `null`.
*/
pinchIn: PinchHandler | null;
/**
* A handler triggered for pinch out events. See also the `pinchOut` event.
*
* Defaults to `null`.
*/
pinchOut: PinchHandler | null;
/**
* A handler triggered for every phase of a pinch. See also the `pinchStatus` event.
*
* Defaults to `null`.
*/
pinchStatus: PinchPhaseHandler;
/**
* The number of pixels that the user must pinch their finger by before it is considered a pinch.
*
* Defaults to `20`.
*/
pinchThreshold: number;
/**
* By default events are cancelled, so the page does not move. You can disable this so both native events fire
* as well as your handlers.
*
* Defaults to `true`.
*/
preventDefaultEvents: boolean;
/**
* A handler to catch all swipes. See also the `swipe` event.
*
* Defaults to `null`.
*/
swipe: SwipeHandler | null;
/**
* A handler that is triggered for `down` swipes. See also the `swipeDown` event.
*
* Defaults to `null`.
*/
swipeDown: SwipeHandler | null;
/**
* A handler that is triggered for `left` swipes. See also the `swipeLeft` event.
*
* Defaults to `null`.
*/
swipeLeft: SwipeHandler | null;
/**
* A handler that is triggered for `right` swipes. See also the `swipeRight` event.
*
* Defaults to `null`.
*/
swipeRight: SwipeHandler | null;
/**
* A handler triggered for every phase of the swipe. See also the `swipeStatus` event.
*
* Defaults to `null`.
*/
swipeStatus: SwipePhaseHandler | null;
/**
* A handler that is triggered for `up` swipes. See also the `swipeUp` event.
*
* Defaults to `null`.
*/
swipeUp: SwipeHandler | null;
/**
* A handler triggered when a user just taps on the item, rather than swipes it. If they do not move, tap is
* triggered, if they do move, it is not.
*
* Defaults to `null`.
*/
tap: PointerHandler | null;
/**
* The number of pixels that the user must move their finger by before it is considered a swipe.
*
* Defaults to `75`.
*/
threshold: number;
/**
* If `true`, the swipe events are triggered when the touch end event is received (user releases finger). If
* `false`, it will be triggered on reaching the threshold, and then cancel the touch event automatically.
*
* Defaults to `true`.
*/
triggerOnTouchEnd: boolean;
/**
* If true, then when the user leaves the swipe object, the swipe will end and trigger appropriate handlers.
*
* Defaults to `false`.
*/
triggerOnTouchLeave: boolean;
}
/**
* The main API entry point of the touch swipe jQuery plugin accessible via `$.swipe`.
*/
export interface TouchSwipeNamespace<TElement = HTMLElement> {
/**
* Initializes TouchSwipe with the given settings.
* @return this jQuery instance for chaining.
*/
(settings?: Partial<JQueryTouchSwipe.TouchSwipeSettings>): JQuery<TElement>;
/**
* Destroy the swipe plugin completely. To use any swipe methods, you must re initialize the plugin.
* @param method The method to call on the TouchSwipe plugin.
* @return this jQuery instance for chaining.
*/
(method: "destroy"): JQuery<TElement>;
/**
* Disables the swipe plugin
* @param method The method to call on the TouchSwipe plugin.
* @return this jQuery instance for chaining.
*/
(method: "disable"): JQuery<TElement>;
/**
* Re-enables the swipe plugin with the previous configuration
* @param method The method to call on the TouchSwipe plugin.
* @return this jQuery instance for chaining.
*/
(method: "enable"): JQuery<TElement>;
/**
* Retrieves the option with the given name.
* @typeparam K Name of the option to retrieve.
* @param method The method to call on the TouchSwipe plugin.
* @param name Name of the option to retrieve.
* @return The current value of the given option.
*/
<K extends keyof TouchSwipeSettings>(method: "option", name: K): TouchSwipeSettings[K];
/**
* Updates the given option with a new value.
* @typeparam K Name of the option to retrieve.
* @param method The method to call on the TouchSwipe plugin.
* @param name Name of the option to update.
* @param value New value for the option.
* @return The current value of the given option.
*/
<K extends keyof TouchSwipeSettings>(method: "option", name: K, value: TouchSwipeSettings[K]): JQuery<TElement>;
/**
* Updates the given options.
* @param method The method to call on the TouchSwipe plugin.
* @param settings The new settings to apply.
* @return The current value of the given option.
*/
(method: "option", settings: Partial<TouchSwipeSettings>): JQuery<TElement>;
/**
* Retrieves the current settings of the TouchSwipe plugin.
* @param method The method to call on the TouchSwipe plugin.
* @return The current settings.
*/
(method: "option"): TouchSwipeSettings;
/**
* The direction constants that are passed to the event handlers.
*/
directions: DirectionsEnum;
/**
* Constants representing the number of fingers used in a swipe.
*/
fingers: FingersEnum;
/**
* The page scroll constants that can be used to set the value of
* {@link JQueryTouchSwipe.TouchSwipeSettings.allowPageScroll|TouchSwipeSettings.allowPageScroll} option.
*/
pageScroll: PageScrollEnum;
/**
* The phases that a touch event goes through.
*/
phases: PhasesEnum;
/**
* The version of the plugin.
*/
version: string;
}
}
interface JQuery<TElement = HTMLElement> {
/**
* The main function of the TouchSwipe plugin
*
* Also contains some constants and the default settings.
*/
swipe: JQueryTouchSwipe.TouchSwipeNamespace<TElement>;
} | the_stack |
import { CommonModule } from '@angular/common';
import { InjectionToken, PipeTransform, Provider, Type } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserModule, HAMMER_GESTURE_CONFIG } from '@angular/platform-browser';
import { RecursivePartial } from './models/recursive-partial';
import { Renderer } from './models/renderer';
import { Rendering, RenderOptions } from './models/rendering';
import { TestSetup } from './models/test-setup';
import './test-frameworks/shallow-matchers';
import { AngularModule } from './models/angular-module';
import { InvalidStaticPropertyMockError } from './tools/mock-statics';
import { createService } from './tools/create-service';
/**
* Test setup wrapper. This class tracks all the test module configurations including
* mocks and providers. When test setup is complet, you can render with the `render` method.
*/
export class Shallow<TTestTarget> {
// tslint:disable: member-ordering
readonly setup: TestSetup<TTestTarget>;
/**
* Instruct *all* shallow-render tests to prevent mocking of a particular:
* * Service
* * Directive
* * Component
* * Module
* * InjectionToken
* * PipeTransform
*
* NOTE: Designed to be used in a global test setup
* If you wish to avoid mocking for a specific test (or test file) @see Shallow#dontMock
*/
static neverMock(...things: any[]) {
this._neverMock.push(...things);
return Shallow;
}
private static readonly _neverMock: any[] = [];
/**
* Instruct *all* shallow-render tests to always add providers to the test module.
* This is useful to mimic the
* Module.forRoot() pattern where dynamic injectables are provided at the app
* root level. You can `alwaysProvide` root-only injectables to all your specs
* with this method.
*
* NOTE: Designed to be used in a global test setup
* If you wish to add a provider for a specific test (or test file) @see Shallow#provide
*
* https://getsaf.github.io/shallow-render/#global-providers-with-alwaysprovide
*/
static alwaysProvide(...providers: Provider[]) {
this._alwaysProvide.push(...providers);
return Shallow;
}
private static readonly _alwaysProvide: Provider[] = [];
/**
* Instruct *all* shallow-render tests to always mock an injectable in a particular way.
*
* NOTE: Designed to be used in a global test setup
* If you wish to add a provider for a specific test (or test file) @see Shallow#mock
*
*
* @example
* Shallow.alwaysMock(MyService, {fetchItems: () => Promise.resolve(['one', 'two', 'three'])});
*
* @link https://getsaf.github.io/shallow-render/#global-mocks-with-alwaysmock
*/
static alwaysMock<TProvider>(
thing: Type<TProvider> | InjectionToken<TProvider>,
stubs: RecursivePartial<TProvider>
): typeof Shallow {
const mock = Shallow._alwaysMock.get(thing) || {};
this._alwaysMock.set(thing, { ...mock, ...(stubs as object) });
return Shallow;
}
private static readonly _alwaysMock = new Map<Type<any> | InjectionToken<any>, any>();
/**
* Instruct *all* shallow-render tests to always mock pipe.
*
* NOTE: Designed to be used in a global test setup
* If you wish to mock a pipe for a specific test (or test file) @see Shallow#mockPipe
*
* @link https://getsaf.github.io/shallow-render/#mocking-pipes-with-mockpipe
*/
static alwaysMockPipe<TPipe extends PipeTransform>(pipe: Type<TPipe>, transform: TPipe['transform']) {
this._alwaysMockPipes.set(pipe, transform);
return this;
}
private static readonly _alwaysMockPipes = new Map<
PipeTransform | Type<PipeTransform>,
// tslint:disable-next-line: ban-types
Function
>();
/**
* Instruct *all* shallow-render tests to replace references to one module with another module.
*
* This can be useful to automatically inject "test" modules in your tests.
*
* @example
* Shallow.alwaysReplaceModule(HTTPClientModule, HTTPClientTestingModule);
*
* NOTE: Designed to be used in a global test setup
* If you wish to replace modules for a specific test (or test file) @see Shallow#replaceModule
*
* @link https://getsaf.github.io/shallow-render/#replace-a-module-with-a-test-module
*/
static alwaysReplaceModule(originalModule: AngularModule, replacementModule: AngularModule): typeof Shallow {
this._alwaysReplaceModule.set(originalModule, replacementModule);
return Shallow;
}
private static readonly _alwaysReplaceModule = new Map<AngularModule, AngularModule>();
/**
* Instruct *all* shallow-render tests to import a given `AngularModule`.
*
* NOTE: Designed to be used in a global test setup
* If you wish to import modules for a specific test (or test file) @see Shallow#import
*/
static alwaysImport(...imports: AngularModule[]) {
this._alwaysImport.push(...imports);
return Shallow;
}
private static readonly _alwaysImport: AngularModule[] = [];
/**
* Instruct *all* shallow-render tests to always render templates assocuated with
* mocked structural directives. The default behavior is not to render structural directives
* until the user specifically enables the directive in their test.
*
* @see Shallow.alwaysWithStructuralDirective
* @see Rendering#renderStructuralDirective
*
* NOTE: Designed to be used in a global test setup
* If you wish to control structural directives manually in a specific test (or test file) @see Rendering#renderStructuralDirective
*
* @link https://getsaf.github.io/shallow-render/#structural-directives
*/
public static alwaysRenderStructuralDirectives() {
this._alwaysRenderStructuralDirectives = true;
return Shallow;
}
private static _alwaysRenderStructuralDirectives = false;
/**
* Instruct *all* shallow-render tests to enforce the default render state of a given directive.
*
* This can be useful when you have certain structural directives that are commonly desired to be
* have their contents rendered in your tests.
*
* --or--
*
* If you want to render all structural directives by default but toggle certain ones off.
*
* @see Shallow.alwaysRenderStructuralDirectives
* @see Rendering#renderStructuralDirective
*
* NOTE: Designed to be used in a global test setup
* If you wish to control structural directives manually in a specific test (or test file) @see Rendering#renderStructuralDirective
*
* @link https://getsaf.github.io/shallow-render/#structural-directives
*/
public static alwaysWithStructuralDirective(directive: Type<any>, renderContents: boolean = true) {
this._alwaysWithStructuralDirectives.set(directive, renderContents);
return Shallow;
}
private static readonly _alwaysWithStructuralDirectives = new Map<Type<any>, boolean>();
constructor(testComponentOrService: Type<TTestTarget>, testModule: AngularModule) {
this.setup = new TestSetup(testComponentOrService, testModule);
this.setup.dontMock.push(testComponentOrService, ...Shallow._neverMock);
this.setup.providers.unshift(...Shallow._alwaysProvide);
this.setup.imports.push(...Shallow._alwaysImport);
this.setup.alwaysRenderStructuralDirectives = Shallow._alwaysRenderStructuralDirectives;
Shallow._alwaysMock.forEach((value, key) => this.setup.mocks.set(key, value));
Shallow._alwaysMockPipes.forEach((value, key) => this.setup.mockPipes.set(key, value));
Shallow._alwaysReplaceModule.forEach((value, key) => this.setup.moduleReplacements.set(key, value));
Shallow._alwaysWithStructuralDirectives.forEach((value, key) =>
this.setup.withStructuralDirectives.set(key, value)
);
}
/**
* Enforce the default render state of a given directive's contents.
*
* Note: If you wish to control structural directives globally @see Shallow.alwaysWithStructuralDirective
*
* @link https://getsaf.github.io/shallow-render/#structural-directives
*/
withStructuralDirective(directive: Type<any>, renderContents = true) {
this.setup.withStructuralDirectives.set(directive, renderContents);
return this;
}
/**
* Adds a compontnt/directive to the test module's `declarations` array.
*
* NOTE: Generally speaking, your declarations should be supplied in your modules. Use of this function
* should be take with caution because it can mask issues with missing declarations in your modules.
*/
declare(...declarations: Type<any>[]): this {
this.setup.declarations.push(...declarations);
return this;
}
/**
* Adds a provider to the test module's `providers` array.
*
* Can be usefult to supply Singleton services (aka: services that are `providedIn: 'root'`).
*
* Providers can match any structure allowed Angular's module system
*
* @example
* shallow.pro({ provide: MyService, useClass: MyMockService });
*
* @link https://getsaf.github.io/shallow-render/#use-a-manual-mock-instance-or-class
*/
provide(...providers: Provider[]): this {
this.setup.providers.unshift(...providers);
return this;
}
/**
* Adds a pre-defined and pre-mocked provider to the test module. Useful when you have
* a test-double service that you wish to use instead of a given service:
*
* Providers can match any structure allowed Angular's module system
*
* @example
* shallow.provideMock({ provide: MyService, useClass: MyMockService });
*
* @link https://getsaf.github.io/shallow-render/#use-a-manual-mock-instance-or-class
*/
provideMock(...providers: Provider[]): this {
this.setup.providers.unshift(...providers);
this.setup.dontMock.push(...providers);
return this;
}
/**
* Instructs shallow to avoid mocking a particular injectable in a test.
*
* This can be any of the following types:
* * Service
* * Directive
* * Component
* * Module
* * InjectionToken
* * PipeTransform
*
* @example
* // While testing a ListComponent, you may want to use the *real* child component too
* shallow.dontMock(ListItemComponent)
*
* @link https://getsaf.github.io/shallow-render/#skip-mocking-with-dontmock
*/
dontMock(...things: any[]): this {
this.setup.dontMock.push(...things);
return this;
}
/**
* Provides mock functions and properties to your test module for a given injectable.
*
* @example
* shallow.mock(MyService, {fetchItems: () => Promise.resolve(['one', 'two', 'three'])});
*
* @link https://getsaf.github.io/shallow-render/#mocking
*/
mock<TMock>(thingToMock: Type<TMock> | InjectionToken<TMock>, stubs: RecursivePartial<TMock>): this {
const mock = this.setup.mocks.get(thingToMock);
if (typeof mock === 'object') {
this.setup.mocks.set(thingToMock, { ...mock, ...(stubs as object) });
} else {
this.setup.mocks.set(thingToMock, stubs);
}
return this;
}
/**
* Allows mocking static properties (or properties of plain JS objects) in your test.
*
* Note: These mocks are reset after your test completes so there is no data-bleed between tests.
*
* @example
* shallow.mockStatic(STATIC_STATUS_CONFIG, {customStatus: 'Mock Status Value Here'});
*
* @link https://getsaf.github.io/shallow-render/#static-function-mocks
*/
mockStatic<TMock extends object>(obj: TMock, stubs: RecursivePartial<TMock>): this {
InvalidStaticPropertyMockError.checkMockForStaticProperties(stubs);
const mock = this.setup.staticMocks.get(obj) || {};
this.setup.staticMocks.set(obj, { ...mock, ...(stubs as object) });
return this;
}
/**
* Mocks a pipe to transform in a specific way for your test.
*
* By default, all pipes are mocked to simply return the same value that was input as their output
*
* @example
* // Fake the tranlate pipe to do simple text reversal
* shallow.mockPipe(TranslatePipe, input => input.split('').reverse().join(''));
*
* @link https://getsaf.github.io/shallow-render/#mocking-pipes-with-mockpipe
*/
mockPipe<TPipe extends PipeTransform>(pipe: Type<TPipe>, transform: TPipe['transform']) {
this.setup.mockPipes.set(pipe, transform);
return this;
}
/**
* Replace any reference to a module with a different module
*
* This can be useful to automatically inject "test" modules in your tests.
*
* NOTE: If you wish to replace modules globally @see Shallow.alwaysReplaceModule
*
* @example
* shallow.replaceModule(HTTPClientModule, HTTPClientTestingModule);
*
* @link https://getsaf.github.io/shallow-render/#replace-a-module-with-a-test-module
*/
replaceModule(originalModule: AngularModule, replacementModule: AngularModule): this {
this.setup.moduleReplacements.set(originalModule, replacementModule);
return this;
}
/**
* Adds imports to the TestModule
*
* Note: If you wish to import modules globally @see Shallow#import
*/
import(...imports: AngularModule[]) {
this.setup.imports.push(...imports);
return this;
}
/**
* Renders the test component
*
* You may optionally suppoly custom bindings to your template.
*
* @example
* const rendering = await shallow.render(
* '<my-component [myLabel]="label" [myFlag]="flag" (myOutput)="output"></my-component>',
* {
* bind: {
* label: "Foo",
* flag: true,
* output: () => console.log("output fired"),
* },
* }
* );
*
* @link https://getsaf.github.io/shallow-render/#rendering
*/
render(): Promise<Rendering<TTestTarget, never>>;
/**
* Renders the test component with an HTML template.
*
* You may optionally suppoly custom bindings to your template.
*
* @example
* const rendering = await shallow.render(
* '<my-component [myLabel]="label" [myFlag]="flag" (myOutput)="output"></my-component>',
* {
* bind: {
* label: "Foo",
* flag: true,
* output: () => console.log("output fired"),
* },
* }
* );
*
* @link https://getsaf.github.io/shallow-render/#rendering
*/
render<TBindings>(
html: string,
renderOptions?: Partial<RenderOptions<TBindings>>
): Promise<Rendering<TTestTarget, TBindings>>;
/**
* Renders the test component
*
* You may optionally suppoly custom bindings to your template.
*
* @example
* const rendering = await shallow.render(
* '<my-component [myLabel]="label" [myFlag]="flag" (myOutput)="output"></my-component>',
* {
* bind: {
* label: "Foo",
* flag: true,
* output: () => console.log("output fired"),
* },
* }
* );
*
* @link https://getsaf.github.io/shallow-render/#rendering
*/
render<TBindings extends RecursivePartial<TTestTarget>>(
renderOptions?: Partial<RenderOptions<TBindings>>
): Promise<Rendering<TTestTarget, TBindings>>;
async render<TBindings>(
htmlOrRenderOptions?: string | Partial<RenderOptions<TBindings>>,
renderOptions?: Partial<RenderOptions<TBindings>>
) {
const renderer = new Renderer(this.setup);
if (typeof htmlOrRenderOptions === 'string') {
return renderer.render(htmlOrRenderOptions, renderOptions);
} else if (htmlOrRenderOptions !== undefined) {
return renderer.render(htmlOrRenderOptions);
} else {
return renderer.render();
}
}
/**
* Creates an instance of a service for testing.
*
* Services can be tested in a similar manner as components.
*
* @example
* const shallow = new Shallow(MyService, MyModule).mock(DependentService, {get: () => 'mocked!'})
* const {instance} = shallow.createService;
*
* @link https://getsaf.github.io/shallow-render/#testing-services
*/
createService() {
return createService(this.setup);
}
}
Shallow.neverMock(CommonModule, BrowserModule, FormsModule, ReactiveFormsModule, HAMMER_GESTURE_CONFIG); | the_stack |
import React, { useState, useCallback, useRef, useMemo } from 'react';
import { UUIFunctionComponent, UUIFunctionComponentProps } from '../../core';
import { createComponentPropTypes, PropTypes, ExtraPropTypes } from '../../utils/createPropTypes';
import { YearMonthSelect as UUIYearMonthSelect } from './YearMonthSelect';
import { DateSelect as UUIDateSelect } from './DateSelect';
import { DateTimeShortcut as UUIDateTimeShortcut } from './DateTimeShortcut';
import { Popover as UUIPopover } from '../Popover/Popover';
import { TextField as UUITextField } from '../Input/TextField';
import { isAfter, startOfMonth, add, isBefore, isSameMonth } from 'date-fns';
import { DateTimeShortcutOption, DateTimeShortcutOptionPropTypes } from './DateTimeShortcut';
import { usePendingValue } from '../../hooks/usePendingValue';
import { Icons } from '../../icons/Icons';
import { compact } from 'lodash-es';
import { formatDate, tryParseDateFromString } from './utils/DateUtils';
export type DateRangePickerValue = [Date, Date];
export type DateRangePickerShortCut = DateTimeShortcutOption<DateRangePickerValue>;
export interface DateRangePickerFeatureProps {
value: DateRangePickerValue | null;
onChange: (value: DateRangePickerValue | null) => void;
shortcuts?: DateRangePickerShortCut[];
startPlaceholder?: string;
endPlaceholder?: string;
}
export const DateRangePickerPropTypes = createComponentPropTypes<DateRangePickerFeatureProps>({
value: ExtraPropTypes.nullable(PropTypes.arrayOf(PropTypes.instanceOf(Date).isRequired).isRequired),
onChange: PropTypes.func.isRequired,
shortcuts: PropTypes.arrayOf(DateTimeShortcutOptionPropTypes),
startPlaceholder: PropTypes.string,
endPlaceholder: PropTypes.string,
})
interface DateRangePickerInnerValue {
startYearMonth: Date;
endYearMonth: Date;
startDate: Date | null;
endDate: Date | null;
startInput: string;
endInput: string;
}
export const DateRangePicker = UUIFunctionComponent({
name: 'DateRangePicker',
nodes: {
Root: 'div',
ConnectIcon: Icons.ArrowRight,
CalendarIcon: Icons.Calendar,
Popover: UUIPopover,
TextField: UUITextField,
Activator: 'div',
Container: 'div',
Toolbar: 'div',
Main: 'div',
StartSection: 'div',
EndSection: 'div',
YearMonthSelect: UUIYearMonthSelect,
DateSelect: UUIDateSelect,
DateTimeShortcut: UUIDateTimeShortcut,
},
propTypes: DateRangePickerPropTypes,
}, (props: DateRangePickerFeatureProps, { nodes }) => {
const {
Root, ConnectIcon, CalendarIcon, Popover, TextField,
Activator, Container, Toolbar, Main, StartSection, EndSection,
YearMonthSelect, DateSelect, DateTimeShortcut,
} = nodes
const startInputRef = useRef<HTMLInputElement | null>(null)
const endInputRef = useRef<HTMLInputElement | null>(null)
const [whichFocusing, setWhichFocusing] = useState<'start' | 'end'>()
const [active, setActive] = useState(false)
const [hoverDate, setHoverDate] = useState<Date>()
const initialInnerValue = useMemo<DateRangePickerInnerValue>(() => {
if (props.value === null) {
return {
startDate: null,
endDate: null,
startInput: '',
endInput: '',
startYearMonth: startOfMonth(new Date),
endYearMonth: add(startOfMonth(new Date), { months: 1 }),
}
}
return {
startDate: props.value[0],
endDate: props.value[1],
startInput: formatDate(props.value[0]),
endInput: formatDate(props.value[1]),
startYearMonth: startOfMonth(props.value[0]),
endYearMonth: isSameMonth(props.value[0], props.value[1]) ? add(startOfMonth(props.value[1]), { months: 1 }) : props.value[1],
}
}, [props.value])
const [innerValue, setInnerValue, resetInnerValue] = usePendingValue<DateRangePickerInnerValue>(initialInnerValue, (value) => {
if (value.startDate && value.endDate) {
handleValueOnChange([value.startDate, value.endDate])
setActive(false)
}
}, { resetWhenInitialValueChanged: true })
const selectedDates = useMemo(() => {
return compact([innerValue.startDate, innerValue.endDate])
}, [innerValue.endDate, innerValue.startDate])
const handleValueOnChange = useCallback((value: [Date, Date] | null) => {
const sortedValue = value?.sort((i, j) => Number(i) - Number(j)) || null
props.onChange(sortedValue)
}, [props])
/**
*
*/
const handleInputOnSubmit = useCallback((type: 'start' | 'end') => {
if (innerValue.startDate && innerValue.endDate) {
const originalInput = formatDate(props.value && (type === 'start' ? props.value[0] : props.value[1]))
const input = type === 'start' ? innerValue.startInput : innerValue.endInput
if (originalInput === input) return;
try {
if (input === '') {
handleValueOnChange(null)
} else {
const result = tryParseDateFromString(input)
handleValueOnChange(type === 'start' ? [result, innerValue.endDate] : [innerValue.startDate, result])
}
} catch {
resetInnerValue()
}
}
}, [handleValueOnChange, innerValue.endInput, innerValue.endDate, innerValue.startInput, innerValue.startDate, props.value, resetInnerValue])
/**
* handle user change year or month in YearMonthSelect.
*/
const handleStartYearMonthSelect = useCallback((value: Date) => {
setInnerValue((oldValue) => {
const startYearMonthDate = value
let endYearMonthDate = oldValue.endYearMonth
if (!isBefore(startYearMonthDate, endYearMonthDate)) {
endYearMonthDate = add(startYearMonthDate, { months: 1 })
}
return {
...oldValue,
startYearMonth: startYearMonthDate,
endYearMonth: endYearMonthDate,
}
})
}, [setInnerValue])
const handleEndYearMonthSelect = useCallback((value: Date) => {
setInnerValue((oldValue) => {
const endYearMonthDate = value
let startYearMonthDate = oldValue.startYearMonth
if (!isAfter(endYearMonthDate, startYearMonthDate)) {
startYearMonthDate = add(endYearMonthDate, { months: -1 })
}
return {
...oldValue,
startYearMonth: startYearMonthDate,
endYearMonth: endYearMonthDate,
}
})
}, [setInnerValue])
/**
* handle user select date in DateSelect.
*/
const handleDateSelect = useCallback((value: Date) => {
let shouldSubmit = false
let newStartValue = innerValue.startDate
let newEndValue = innerValue.endDate
if (
(newStartValue !== null && newEndValue !== null) ||
(newStartValue === null && newEndValue === null)
) {
if (whichFocusing === 'end') {
newStartValue = null
newEndValue = value
} else {
newStartValue = value
newEndValue = null
}
} else {
if (newStartValue === null) newStartValue = value
if (newEndValue === null) newEndValue = value
if (isAfter(newStartValue, newEndValue)) {
const tmp = new Date(newStartValue)
newStartValue = new Date(newEndValue)
newEndValue = tmp
}
shouldSubmit = true
}
setInnerValue((oldValue) => {
return {
...oldValue,
startDate: newStartValue,
startInput: formatDate(newStartValue),
endDate: newEndValue,
endInput: formatDate(newEndValue),
}
}, shouldSubmit)
}, [innerValue.endDate, innerValue.startDate, setInnerValue, whichFocusing])
return (
<Root>
<Popover
placement={'bottom-start'}
active={active}
onClickAway={() => { setActive(false); resetInnerValue(); }}
activator={
<Activator
onClick={() => {
setActive(true)
setTimeout(() => {
if (whichFocusing === undefined && startInputRef.current) {
startInputRef.current.focus()
}
}, 0)
}}
>
<TextField
placeholder={props.startPlaceholder}
value={innerValue.startInput}
onChange={(value) => { setInnerValue((oldValue) => ({ ...oldValue, startInput: value })) }}
customize={{
Input: {
ref: startInputRef,
onFocus: () => {
setWhichFocusing('start')
},
onBlur: () => {
setWhichFocusing(undefined)
handleInputOnSubmit('start')
},
onKeyDown: (event) => {
if (event.key === 'Enter') {
handleInputOnSubmit('start')
}
}
}
}}
/>
<ConnectIcon />
<TextField
placeholder={props.endPlaceholder}
value={innerValue.endInput}
onChange={(value) => { setInnerValue((oldValue) => ({ ...oldValue, endInput: value })) }}
customize={{
Input: {
ref: endInputRef,
onFocus: () => {
setWhichFocusing('end')
},
onBlur: () => {
setWhichFocusing(undefined)
handleInputOnSubmit('end')
},
onKeyDown: (event) => {
if (event.key === 'Enter') {
handleInputOnSubmit('end')
}
}
}
}}
/>
<CalendarIcon />
</Activator>
}
>
<Container>
<Toolbar>
{props.shortcuts && (
<DateTimeShortcut
options={props.shortcuts}
onSelect={(value) => {
handleValueOnChange(value)
setActive(false)
}}
/>
)}
</Toolbar>
<Main tabIndex={-1}>
<StartSection>
<YearMonthSelect
value={innerValue.startYearMonth}
onChange={handleStartYearMonthSelect}
/>
<DateSelect
yearMonth={innerValue.startYearMonth}
selectedDates={selectedDates}
onSelect={handleDateSelect}
hoverDate={hoverDate}
onHoverDateChange={(date) => { setHoverDate(date) }}
/>
</StartSection>
<EndSection>
<YearMonthSelect
value={innerValue.endYearMonth}
onChange={handleEndYearMonthSelect}
/>
<DateSelect
yearMonth={innerValue.endYearMonth}
selectedDates={selectedDates}
onSelect={handleDateSelect}
hoverDate={hoverDate}
onHoverDateChange={(date) => { setHoverDate(date) }}
/>
</EndSection>
</Main>
</Container>
</Popover>
</Root>
)
})
export type DateRangePickerProps = UUIFunctionComponentProps<typeof DateRangePicker> | the_stack |
import {Constructor} from '../../../../types/GlobalTypes';
import {BaseController} from './_BaseController';
import {Material} from 'three/src/materials/Material';
import {Texture} from 'three/src/textures/Texture';
import {BaseMatNodeType} from '../_Base';
import {ParamConfig} from '../../utils/params/ParamsConfig';
import {NodeContext} from '../../../poly/NodeContext';
import {NodePathParam} from '../../../params/NodePath';
import {BooleanParam} from '../../../params/Boolean';
import {BaseNodeType} from '../../_Base';
import {BaseParamType} from '../../../params/_Base';
import {ShaderMaterial} from 'three/src/materials/ShaderMaterial';
import {IUniform} from 'three/src/renderers/shaders/UniformsLib';
import {IUniforms, ShaderMaterialWithCustomMaterials} from '../../../../core/geometry/Material';
import {NODE_PATH_DEFAULT} from '../../../../core/Walker';
import {CustomMaterialName} from '../../gl/code/assemblers/materials/_BaseMaterial';
import {Poly} from '../../../Poly';
export function TextureMapParamConfig<TBase extends Constructor>(Base: TBase) {
return class Mixin extends Base {
useMap = ParamConfig.BOOLEAN(0);
map = ParamConfig.NODE_PATH(NODE_PATH_DEFAULT.NODE.EMPTY, {visibleIf: {useMap: 1}});
};
}
// class TextureMapMaterial<T extends string> extends Material {
// [T]!: Texture | null;
// }
// class TextureMapParamsConfig extends TextureMapParamConfig(NodeParamsConfig) {}
// class TextureMapMatNode extends TypedMatNode<TextureMapMaterial, TextureMapParamsConfig> {
// createMaterial() {
// return new TextureMapMaterial();
// }
// }
type FilterFlags<Base, Condition> = {
[Key in keyof Base]: Base[Key] extends Condition ? Key : never;
};
type AllowedNames<Base, Condition> = FilterFlags<Base, Condition>[keyof Base];
type SubType<Base, Condition> = Pick<Base, AllowedNames<Base, Condition>>;
// type test = FilterFlags<MeshLambertMaterial, Texture|null>
// type test2 = AllowedNames<MeshLambertMaterial, Texture|null>
// type test3 = SubType<MeshLambertMaterial, Texture|null>
export function BooleanParamOptions(controller_class: typeof BaseTextureMapController) {
return {
cook: false,
callback: (node: BaseNodeType, param: BaseParamType) => {
controller_class.update(node as BaseMatNodeType);
},
};
}
interface OperatorPathOptionsOptions {
types?: string[];
}
export function OperatorPathOptions(
controller: typeof BaseTextureMapController,
use_map_name: string,
options?: OperatorPathOptionsOptions
) {
return {
visibleIf: {[use_map_name]: 1},
nodeSelection: {context: NodeContext.COP, types: options?.types},
cook: false,
callback: (node: BaseNodeType, param: BaseParamType) => {
controller.update(node as BaseMatNodeType);
},
};
}
type TextureUpdateCallback<O extends Object> = (
material: Material,
object: O,
mat_attrib_name: keyof SubType<O, Texture | null>,
texture: Texture
) => void;
type TextureRemoveCallback<O extends Object> = (
material: Material,
object: O,
mat_attrib_name: keyof SubType<O, Texture | null>
) => void;
type CurrentMaterial = Material | ShaderMaterial;
export interface UpdateOptions {
directParams?: boolean;
uniforms?: boolean;
// define?: boolean;
// define_uv?: boolean;
}
export class BaseTextureMapController extends BaseController {
constructor(protected node: BaseMatNodeType, protected _update_options: UpdateOptions) {
super(node);
// if (this._update_options.define == null) {
// this._update_options.define = true;
// }
// if (this._update_options.define_uv == null) {
// this._update_options.define_uv = true;
// }
}
protected add_hooks(use_map_param: BooleanParam, path_param: NodePathParam) {
use_map_param.addPostDirtyHook('TextureController', () => {
this.update();
});
path_param.addPostDirtyHook('TextureController', () => {
this.update();
});
}
static update(node: BaseNodeType) {}
async _update<M extends CurrentMaterial>(
material: M,
mat_attrib_name: string,
use_map_param: BooleanParam,
path_param: NodePathParam
) {
if (this._update_options.uniforms) {
const shader_material = material as ShaderMaterial;
const attr_name = mat_attrib_name as keyof SubType<IUniforms, Texture | null>;
await this._update_texture_on_uniforms(shader_material, attr_name, use_map_param, path_param);
}
if (this._update_options.directParams) {
const mat = material as Material;
const attr_name = mat_attrib_name as keyof SubType<Material, Texture | null>;
await this._update_texture_on_material(mat, attr_name, use_map_param, path_param);
}
}
//
//
// FOR CASES WHERE THE TEXTURE IS ON THE UNIFORMS
//
//
async _update_texture_on_uniforms<O extends IUniform>(
material: ShaderMaterial,
mat_attrib_name: keyof SubType<O, Texture | null>,
use_map_param: BooleanParam,
path_param: NodePathParam
) {
this._update_required_attribute(
material,
material.uniforms,
mat_attrib_name as never,
use_map_param,
path_param,
this._apply_texture_on_uniforms.bind(this),
this._remove_texture_from_uniforms.bind(this)
);
}
private _apply_texture_on_uniforms<O extends IUniforms>(
material: Material,
uniforms: O,
mat_attrib_name: keyof SubType<O, Texture | null>,
texture: Texture
) {
const has_texture = uniforms[mat_attrib_name] != null && uniforms[mat_attrib_name].value != null;
let new_texture_is_different = false;
if (has_texture) {
const current_texture: Texture = (<unknown>uniforms[mat_attrib_name].value) as Texture;
if (current_texture.uuid != texture.uuid) {
new_texture_is_different = true;
}
}
if (!has_texture || new_texture_is_different) {
const uniform = uniforms[mat_attrib_name];
// check as the uniform may not exist on a customMaterial
if (uniform) {
uniforms[mat_attrib_name].value = texture as any;
}
// currently removing the settings of defines USE_MAP or USE_UV
// as this seems to conflict with setting .map on the material itself.
// ideally I should test if .alphaMap and .envMap still work
// if (this._do_update_define()) {
// if (material.defines) {
// const define_name = this._define_name(`${mat_attrib_name}`);
// material.defines[define_name] = 3;
// }
// }
// if (this._update_options.define_uv) {
// if (material.defines) {
// material.defines['USE_UV'] = 5;
// }
// }
this._apply_texture_on_material(material, material, mat_attrib_name as any, texture);
material.needsUpdate = true;
const customMaterials = (material as ShaderMaterialWithCustomMaterials).customMaterials;
if (customMaterials) {
const customNames: CustomMaterialName[] = Object.keys(customMaterials) as CustomMaterialName[];
for (let customName of customNames) {
const customMaterial = customMaterials[customName];
if (customMaterial) {
this._apply_texture_on_uniforms(
customMaterial,
customMaterial.uniforms as O,
mat_attrib_name,
texture
);
}
}
}
}
}
private _remove_texture_from_uniforms<U extends IUniforms>(
material: Material,
uniforms: U,
mat_attrib_name: keyof SubType<U, Texture | null>
) {
if (!uniforms[mat_attrib_name]) {
Poly.warn(`'${mat_attrib_name}' uniform not found. existing uniforms are:`, Object.keys(uniforms).sort());
return;
}
if (uniforms[mat_attrib_name].value) {
uniforms[mat_attrib_name].value = null;
// if (this._do_update_define()) {
// if (material.defines) {
// // const define_name = this._define_name(`${mat_attrib_name}`);
// // delete material.defines[define_name];
// }
// }
this._remove_texture_from_material(material, material, mat_attrib_name as any);
material.needsUpdate = true;
const customMaterials = (material as ShaderMaterialWithCustomMaterials).customMaterials;
if (customMaterials) {
const customNames: CustomMaterialName[] = Object.keys(customMaterials) as CustomMaterialName[];
for (let customName of customNames) {
const customMaterial = customMaterials[customName];
if (customMaterial) {
this._remove_texture_from_uniforms(
customMaterial,
customMaterial.uniforms as U,
mat_attrib_name
);
}
}
}
}
}
// private _define_name(mat_attrib_name: string): string {
// return 'USE_' + mat_attrib_name.replace('_', '').toUpperCase();
// }
//
//
// FOR CASES WHERE THE TEXTURE IS ON THE MATERIAL
//
//
async _update_texture_on_material<M extends Material>(
material: M,
mat_attrib_name: keyof SubType<M, Texture | null>,
use_map_param: BooleanParam,
path_param: NodePathParam
) {
this._update_required_attribute(
material,
material,
mat_attrib_name,
use_map_param,
path_param,
this._apply_texture_on_material.bind(this),
this._remove_texture_from_material.bind(this)
);
}
private _apply_texture_on_material<M extends Material>(
material: Material,
texture_owner: M,
mat_attrib_name: keyof SubType<M, Texture | null>,
texture: Texture
) {
const has_texture = texture_owner[mat_attrib_name] != null;
let new_texture_is_different = false;
if (has_texture) {
const current_texture: Texture = (<unknown>texture_owner[mat_attrib_name]) as Texture;
if (current_texture.uuid != texture.uuid) {
new_texture_is_different = true;
}
}
if (!has_texture || new_texture_is_different) {
texture_owner[mat_attrib_name] = texture as any;
material.needsUpdate = true;
}
}
private _remove_texture_from_material<M extends Material>(
material: Material,
texture_owner: M,
mat_attrib_name: keyof SubType<M, Texture | null>
) {
if (texture_owner[mat_attrib_name]) {
texture_owner[mat_attrib_name] = null as any;
material.needsUpdate = true;
}
}
//
//
// MAIN ALGO to decide if texture should be updated
//
//
private async _update_required_attribute<O extends Object>(
material: Material,
texture_owner: O,
mat_attrib_name: keyof SubType<O, Texture | null>,
use_map_param: BooleanParam,
path_param: NodePathParam,
update_callback: TextureUpdateCallback<O>,
remove_callback: TextureRemoveCallback<O>
) {
if (use_map_param.isDirty()) {
await use_map_param.compute();
}
const use_map: boolean = use_map_param.value;
if (use_map) {
if (path_param.isDirty()) {
await path_param.compute();
}
const texture_node = path_param.value.nodeWithContext(NodeContext.COP);
if (texture_node) {
const container = await texture_node.compute();
const texture = container.texture();
if (texture) {
update_callback(material, texture_owner, mat_attrib_name, texture);
return;
}
}
}
// this is not wrapped in an else clause after the "if (use_map) {"
// as we should come here after any of the errors above, if any is triggered
remove_callback(material, texture_owner, mat_attrib_name);
}
// private _do_update_define(): boolean {
// if (this._update_options.define == null) {
// return true;
// }
// return this._update_options.define;
// }
} | the_stack |
module Cats.Util {
/**
* Some help to find based on the file name extension either the computer language (for the editor)
* or the mimetype (for the icons in the file navigator)
*/
export class MimeTypeFinder {
/**
* Find the mimetype for a file name
*/
static lookup(filename:string, fallback?:string) {
return this.types[OS.File.PATH.extname(filename)] || fallback || this.default_type;
}
private static default_type = 'application/octet-stream';
static types:Map<string> = {
".3gp": "video/3gpp",
".a": "application/octet-stream",
".ai": "application/postscript",
".aif": "audio/x-aiff",
".aiff": "audio/x-aiff",
".arj": "application/x-arj-compressed",
".asc": "application/pgp-signature",
".asf": "video/x-ms-asf",
".asm": "text/x-asm",
".asx": "video/x-ms-asf",
".atom": "application/atom+xml",
".au": "audio/basic",
".avi": "video/x-msvideo",
".bat": "application/x-msdownload",
".bcpio": "application/x-bcpio",
".bin": "application/octet-stream",
".bmp": "image/bmp",
".bz2": "application/x-bzip2",
".c": "text/x-c",
".cab": "application/vnd.ms-cab-compressed",
".cc": "text/x-c",
".ccad": "application/clariscad",
".chm": "application/vnd.ms-htmlhelp",
".class": "application/octet-stream",
".cod": "application/vnd.rim.cod",
".com": "application/x-msdownload",
".conf": "text/plain",
".cpio": "application/x-cpio",
".cpp": "text/x-c",
".cpt": "application/mac-compactpro",
".crt": "application/x-x509-ca-cert",
".csh": "application/x-csh",
".css": "text/css",
".csv": "text/csv",
".cxx": "text/x-c",
".dart": "application/dart",
".deb": "application/x-debian-package",
".der": "application/x-x509-ca-cert",
".diff": "text/x-diff",
".djv": "image/vnd.djvu",
".djvu": "image/vnd.djvu",
".dl": "video/dl",
".dll": "application/x-msdownload",
".dmg": "application/octet-stream",
".doc": "application/msword",
".dot": "application/msword",
".drw": "application/drafting",
".dtd": "application/xml-dtd",
".dvi": "application/x-dvi",
".dwg": "application/acad",
".dxf": "application/dxf",
".dxr": "application/x-director",
".ear": "application/java-archive",
".eml": "message/rfc822",
".eps": "application/postscript",
".etx": "text/x-setext",
".exe": "application/x-msdownload",
".ez": "application/andrew-inset",
".f": "text/x-fortran",
".f77": "text/x-fortran",
".f90": "text/x-fortran",
".fli": "video/x-fli",
".flv": "video/x-flv",
".for": "text/x-fortran",
".gem": "application/octet-stream",
".gemspec": "text/x-script.ruby",
".gif": "image/gif",
".gl": "video/gl",
".gtar": "application/x-gtar",
".gz": "application/x-gzip",
".h": "text/x-c",
".hdf": "application/x-hdf",
".hh": "text/x-c",
".hqx": "application/mac-binhex40",
".htm": "text/html",
".html": "text/html",
".ice": "x-conference/x-cooltalk",
".ico": "image/vnd.microsoft.icon",
".ics": "text/calendar",
".ief": "image/ief",
".ifb": "text/calendar",
".igs": "model/iges",
".ips": "application/x-ipscript",
".ipx": "application/x-ipix",
".iso": "application/octet-stream",
".jad": "text/vnd.sun.j2me.app-descriptor",
".jar": "application/java-archive",
".java": "text/x-java-source",
".jnlp": "application/x-java-jnlp-file",
".jpeg": "image/jpeg",
".jpg": "image/jpeg",
".js": "application/javascript",
".json": "application/json",
".latex": "application/x-latex",
".log": "text/plain",
".lsp": "application/x-lisp",
".lzh": "application/octet-stream",
".m": "text/plain",
".m3u": "audio/x-mpegurl",
".m4v": "video/mp4",
".man": "text/troff",
".mathml": "application/mathml+xml",
".mbox": "application/mbox",
".mdoc": "text/troff",
".me": "text/troff",
".mid": "audio/midi",
".midi": "audio/midi",
".mif": "application/x-mif",
".mime": "www/mime",
".mml": "application/mathml+xml",
".mng": "video/x-mng",
".mov": "video/quicktime",
".movie": "video/x-sgi-movie",
".mp3": "audio/mpeg",
".mp4": "video/mp4",
".mp4v": "video/mp4",
".mpeg": "video/mpeg",
".mpg": "video/mpeg",
".mpga": "audio/mpeg",
".ms": "text/troff",
".msi": "application/x-msdownload",
".nc": "application/x-netcdf",
".oda": "application/oda",
".odp": "application/vnd.oasis.opendocument.presentation",
".ods": "application/vnd.oasis.opendocument.spreadsheet",
".odt": "application/vnd.oasis.opendocument.text",
".ogg": "application/ogg",
".ogm": "application/ogg",
".p": "text/x-pascal",
".pas": "text/x-pascal",
".pbm": "image/x-portable-bitmap",
".pdf": "application/pdf",
".pem": "application/x-x509-ca-cert",
".pgm": "image/x-portable-graymap",
".pgn": "application/x-chess-pgn",
".pgp": "application/pgp",
".pkg": "application/octet-stream",
".pl": "text/x-script.perl",
".pm": "application/x-perl",
".png": "image/png",
".pnm": "image/x-portable-anymap",
".ppm": "image/x-portable-pixmap",
".pps": "application/vnd.ms-powerpoint",
".ppt": "application/vnd.ms-powerpoint",
".ppz": "application/vnd.ms-powerpoint",
".pre": "application/x-freelance",
".prt": "application/pro_eng",
".ps": "application/postscript",
".psd": "image/vnd.adobe.photoshop",
".py": "text/x-script.python",
".qt": "video/quicktime",
".ra": "audio/x-realaudio",
".rake": "text/x-script.ruby",
".ram": "audio/x-pn-realaudio",
".rar": "application/x-rar-compressed",
".ras": "image/x-cmu-raster",
".rb": "text/x-script.ruby",
".rdf": "application/rdf+xml",
".rgb": "image/x-rgb",
".rm": "audio/x-pn-realaudio",
".roff": "text/troff",
".rpm": "application/x-redhat-package-manager",
".rss": "application/rss+xml",
".rtf": "text/rtf",
".rtx": "text/richtext",
".ru": "text/x-script.ruby",
".s": "text/x-asm",
".scm": "application/x-lotusscreencam",
".set": "application/set",
".sgm": "text/sgml",
".sgml": "text/sgml",
".sh": "application/x-sh",
".shar": "application/x-shar",
".sig": "application/pgp-signature",
".silo": "model/mesh",
".sit": "application/x-stuffit",
".skt": "application/x-koan",
".smil": "application/smil",
".snd": "audio/basic",
".so": "application/octet-stream",
".sol": "application/solids",
".spl": "application/x-futuresplash",
".src": "application/x-wais-source",
".stl": "application/SLA",
".stp": "application/STEP",
".sv4cpio": "application/x-sv4cpio",
".sv4crc": "application/x-sv4crc",
".svg": "image/svg+xml",
".svgz": "image/svg+xml",
".swf": "application/x-shockwave-flash",
".t": "text/troff",
".tar": "application/x-tar",
".tbz": "application/x-bzip-compressed-tar",
".tcl": "application/x-tcl",
".tex": "application/x-tex",
".texi": "application/x-texinfo",
".texinfo": "application/x-texinfo",
".text": "text/plain",
".tgz": "application/x-tar-gz",
".tif": "image/tiff",
".tiff": "image/tiff",
".torrent": "application/x-bittorrent",
".tr": "text/troff",
".ts": "application/x-typescript",
".tsi": "audio/TSP-audio",
".tsp": "application/dsptype",
".tsv": "text/tab-separated-values",
".txt": "text/plain",
".unv": "application/i-deas",
".ustar": "application/x-ustar",
".vcd": "application/x-cdlink",
".vcf": "text/x-vcard",
".vcs": "text/x-vcalendar",
".vda": "application/vda",
".vivo": "video/vnd.vivo",
".vrm": "x-world/x-vrml",
".vrml": "model/vrml",
".war": "application/java-archive",
".wav": "audio/x-wav",
".wax": "audio/x-ms-wax",
".wma": "audio/x-ms-wma",
".wmv": "video/x-ms-wmv",
".wmx": "video/x-ms-wmx",
".wrl": "model/vrml",
".wsdl": "application/wsdl+xml",
".wvx": "video/x-ms-wvx",
".xbm": "image/x-xbitmap",
".xhtml": "application/xhtml+xml",
".xls": "application/vnd.ms-excel",
".xlw": "application/vnd.ms-excel",
".xml": "application/xml",
".xpm": "image/x-xpixmap",
".xsl": "application/xml",
".xslt": "application/xslt+xml",
".xwd": "image/x-xwindowdump",
".xyz": "chemical/x-pdb",
".yaml": "text/yaml",
".yml": "text/yaml",
".zip": "application/zip"
};
}
} | the_stack |
import { findPackageDirs } from "@adpt/utils";
import * as path from "path";
import * as vm from "vm";
// tslint:disable-next-line:variable-name no-var-requires
const Module = require("module");
import * as ld from "lodash";
import {
InternalError,
isError,
ProjectCompileError,
ProjectRunError,
ThrewNonError
} from "../error";
import { trace, tracef } from "../utils";
import { CompileError } from "./compile";
import { ChainableHost } from "./hosts";
const builtInModules = new Set<string>(Module.builtinModules);
const debugVm = false;
const packageDirs = findPackageDirs(__dirname);
// Remove each line that has a filename that's in our dist/src/ts directory
// or our src/ts directory (depending on how the module is installed).
// There are often 2-3 of these compilation-related frames between each
// stack frame that the user cares about, which makes the backtraces super
// confusing for them.
const tsStackExclude = RegExp("\n.*?\\(" + packageDirs.root + "(?:/dist)?/src/ts/.*?$", "mg");
// Script.runInContext is the call that starts the user's project script.
// Delete that line and all following lines.
const ctxStackEnd = /\n[^\n]*Script\.runInContext(?:.|\n)*/;
function getProjectStack(projectError: Error): string {
if (projectError.stack) {
let ctxStack = projectError.stack.replace(ctxStackEnd, "");
ctxStack = ctxStack.replace(tsStackExclude, "");
return ctxStack;
}
return "[No stack]";
}
export interface Extensions {
[ext: string]: any;
}
export interface RequireCache {
[abspath: string]: NodeModule;
}
interface Modules {
[abspath: string]: VmModule;
}
function isRelative(loc: string) {
return loc.startsWith("./") || loc.startsWith("../");
}
export class VmModule {
extensions: Extensions;
requireCache: RequireCache;
_compile = this.runJs;
ctxModule: NodeModule;
vmModules: Modules;
private hostModCache: any;
constructor(public id: string, private vmContext: vm.Context | undefined,
public host: ChainableHost,
public parent?: VmModule) {
if (parent) {
this.extensions = parent.extensions;
this.requireCache = parent.requireCache;
this.hostModCache = parent.hostModCache;
this.vmModules = parent.vmModules;
} else {
this.extensions = Object.create(null);
this.requireCache = Object.create(null);
this.hostModCache = Object.create(null);
this.vmModules = Object.create(null);
this.extensions[".js"] = this.runJsModule.bind(this);
this.extensions[".json"] = this.runJsonModule.bind(this);
}
this.ctxModule = new Module(id, (parent && parent.ctxModule) || null);
this.ctxModule.filename = id;
}
/**
* Init that happens only once per VmContext, after the context's VM has
* been created. This should be called on the "main" module for the context
* ONLY.
* @param ctx The vm context where the DOM code will run.
*/
initMain(ctx: vm.Context) {
if (this.parent) throw new InternalError(`initMain should only be called on top-level VmModule`);
this.vmContext = ctx;
// NOTE(mark): There's some strange behavior with allowing this
// module to be re-loaded in the context when used alongside
// source-map-support in unit tests. Even though callsites overrides
// Error.prepareStackTrace with its own function, that function
// never gets called. If you figure out why, remove this.
this.loadHostMod("callsites");
}
@tracef(debugVm)
requireResolve(request: string, options?: { paths?: string[] }) {
if (options) {
throw new Error("require.resolve options not supported yet.");
}
const resolved = this.host.resolveModuleName(request, this.id, true);
if (resolved) return resolved.resolvedFileName;
if (isRelative(request)) request = path.join(path.dirname(this.id), request);
if (!path.isAbsolute(request)) {
// mimic Node's error for this case.
const err = new Error(`Cannot find module '${request}'`);
(err as any).code = "MODULE_NOT_FOUND";
throw err;
}
return require.resolve(request, options);
}
@tracef(debugVm)
require(modName: string) {
let hostMod = this.requireHostMod(modName);
if (hostMod !== undefined) return hostMod;
if (builtInModules.has(modName)) {
hostMod = this.requireBuiltin(modName);
if (hostMod === undefined) throw new InternalError(`Cannot find module '${modName}'`);
return hostMod;
}
let resolved: string | undefined;
try {
resolved = this.requireResolve(modName);
} catch (e) {
if (!ld.isError(e)) throw e;
if (!e.message.startsWith("Cannot find")) throw e;
}
if (resolved) {
const resolvedPath = resolved;
const cached = this.requireCache[resolvedPath];
if (cached) return cached.exports;
const newMod = new VmModule(resolvedPath, this.vmContext, this.host,
this);
this.vmModules[resolvedPath] = newMod;
this.requireCache[resolvedPath] = newMod.ctxModule;
const ext = path.extname(resolvedPath) || ".js";
// Run the module
this.extensions[ext](newMod, resolvedPath);
newMod.ctxModule.loaded = true;
return newMod.ctxModule.exports;
}
throw new Error(`Unable to find module ${modName} ` +
`imported from ${this.id}`);
}
@tracef(debugVm)
registerExt(ext: string, func: (mod: VmModule, fileName: string) => void) {
this.extensions[ext] = func;
}
private loadHostMod(modName: string) {
const cached = this.hostModCache[modName];
if (cached !== undefined) return cached;
const mod = require(modName);
this.hostModCache[modName] = mod;
return mod;
}
@tracef(debugVm)
private requireHostMod(modName: string) {
return this.hostModCache[modName];
}
@tracef(debugVm)
private requireBuiltin(modName: string) {
try {
return this.loadHostMod(modName);
} catch (e) {
if (e.code === "MODULE_NOT_FOUND") return undefined;
throw e;
}
}
@tracef(debugVm)
private runJsonModule(mod: VmModule, filename: string) {
const contents = this.host.readFile(filename);
if (contents == null) {
throw new Error(`Unable to find file contents for ${filename}`);
}
try {
mod.ctxModule.exports = JSON.parse(contents);
} catch (err) {
err.message = filename + ": " + err.message;
throw err;
}
}
@tracef(debugVm)
private runJsModule(mod: VmModule, filename: string) {
const contents = this.host.readFile(filename);
if (contents == null) {
throw new Error(`Unable to find file contents for ${filename}`);
}
return mod.runJs(contents, filename);
}
@tracef(debugVm)
private runJs(content: string, filename: string) {
if (!this.vmContext) throw new Error(`vmContext is not set`);
const wrapper = Module.wrap(content);
const compiled = vm.runInContext(wrapper, this.vmContext, { filename });
const require = (() => {
const ret: NodeRequire = this.require.bind(this) as NodeRequire;
ret.resolve = this.requireResolve.bind(this);
ret.cache = this.requireCache;
return ret;
})();
const dirname = path.dirname(filename);
try {
return compiled.call(this.ctxModule.exports, this.ctxModule.exports,
require, this.ctxModule, filename, dirname);
} catch (err) {
if ((err instanceof ProjectRunError) ||
(err instanceof CompileError)) {
throw err;
}
if (!isError(err)) err = new ThrewNonError(err);
throw new ProjectRunError(err, getProjectStack(err), err.stack);
}
}
}
// Javascript defines a set of properties that should be available on the
// global object. V8 takes care of those. Only add the ones that Node defines.
const hostGlobals = () => ({
version: parseInt(process.versions.node.split(".")[0], 10),
process,
console,
setTimeout,
setInterval,
setImmediate,
clearTimeout,
clearInterval,
clearImmediate,
Buffer,
});
/*
* Prepares a context object to be the global object within a new
* V8 context.
*/
export class VmContext {
mainModule: VmModule;
constructor(public vmGlobal: any, dirname: string, public filename: string,
public host: ChainableHost) {
vmGlobal.__filename = filename;
vmGlobal.__dirname = dirname;
const module = new VmModule(filename, undefined, host, undefined);
this.mainModule = module;
vmGlobal.exports = module.ctxModule.exports;
vmGlobal.module = module.ctxModule;
vmGlobal.require = module.require.bind(module);
vmGlobal.global = vmGlobal;
const hGlobals = hostGlobals();
for (const prop of Object.keys(hGlobals)) {
vmGlobal[prop] = (hGlobals as any)[prop];
}
vm.createContext(vmGlobal);
module.initMain(vmGlobal);
}
@tracef(debugVm)
run(jsText: string): any {
let val;
try {
// Execute the program
val = vm.runInContext(jsText, this.vmGlobal, { filename: this.filename });
} catch (err) {
// Translate internal error that has all the diags in it
// to an external API text-only version.
if (err instanceof CompileError) {
err = new ProjectCompileError(err.message);
}
if (!isError(err)) err = new ThrewNonError(err);
if (!(err instanceof ProjectRunError)) {
err = new ProjectRunError(err, getProjectStack(err), err.stack);
}
throw err;
}
if (debugVm) {
trace(debugVm, `RESULT: ${JSON.stringify(val, null, 2)}`);
}
return val;
}
} | the_stack |
module Kiwi.Input {
/**
* Handles the dispatching and management of touch based events for the game. When the Touch manager is created TEN finger objects are created and used when the user interacts with the screen. Those finger are what you can use to create games that make the most out of multitouch events.
*
* @class Touch
* @constructor
* @namespace Kiwi.Input
* @param game {Game} the game that this touch manager belongs to.
* @return {Touch} This object.
*
*/
export class Touch {
constructor(game: Kiwi.Game) {
this._game = game;
}
/**
* The type of object that this is.
* @method objType
* @return {String} "TouchManager"
* @public
*/
public objType():string {
return "TouchManager";
}
/**
* If the touch inputs are enabled on the current device (and so if the events will fire) or not.
* @property touchEnabled
* @type boolean
* @public
*/
public touchEnabled: boolean;
/**
* The game that this touch manager belongs to.
* @property _game
* @type Game
* @private
**/
private _game: Kiwi.Game;
/**
* The dom element that these touch events are to take place on. This is usally set to be the stage/game container.
* @property _domElement
* @type HTMLElement
* @default null
* @private
**/
private _domElement: HTMLElement = null;
/**
* Contains a list of all of the fingers that are used for the touch events.
* @property _fingers
* @type Array
* @private
*/
private _fingers: Finger[];
/**
* Get the fingers that are being used.
* @type Finger[]
* @public
*/
public get fingers(): Kiwi.Input.Finger[] {
return this._fingers;
}
/**
* The first finger that is used for touch events.
* @property finger1
* @type Finger
* @public
*/
public finger1: Kiwi.Input.Finger;
/**
* The second finger that is used for touch events.
* @property finger2
* @type Finger
* @public
*/
public finger2: Kiwi.Input.Finger;
/**
* The third finger that is used for touch events.
* @property finger3
* @type Finger
* @public
*/
public finger3: Kiwi.Input.Finger;
/**
* The fourth finger that is used for touch events.
* @property finger4
* @type Finger
* @public
*/
public finger4: Kiwi.Input.Finger;
/**
* Finger number five that is used for touch events.
* @property finger5
* @type Finger
* @public
*/
public finger5: Kiwi.Input.Finger;
/**
* Finger number six, that is used for touch events.
* @property finger6
* @type Finger
* @public
*/
public finger6: Kiwi.Input.Finger;
/**
* The seventh finger used for touch events.
* @property finger7
* @type Finger
* @public
*/
public finger7: Kiwi.Input.Finger;
/**
* Finger number eight
* @property finger8
* @type Finger
* @public
*/
public finger8: Kiwi.Input.Finger;
/**
* The ninth finger that is used for touch events.
* @property finger9
* @type Finger
* @public
*/
public finger9: Kiwi.Input.Finger;
/**
* The tenth finger that is used for touch events.
* @property finger10
* @type Finger
* @public
*/
public finger10: Kiwi.Input.Finger;
/**
* The latest finger that was used for any task.
* @property latestFinger
* @type Finger
* @public
*/
public latestFinger: Kiwi.Input.Finger;
/**
* A boolean that will roughly indicate if any finger is currently down.
* @property isDown
* @type boolean
* @default false
* @public
*/
public isDown: boolean = false;
/**
* If all the fingers are up.
* @property isUp
* @type boolean
* @default true
* @public
*/
public isUp: boolean = true;
/**
* A Kiwi Signal that dispatches an event when a user presses down on the stage.
* @property touchDown
* @type Signal
* @public
* @deprecated
*/
public touchDown: Kiwi.Signal;
/**
* A Kiwi Signal that dispatches an event when a user presses down on the stage.
* @property onDown
* @type Signal
* @public
*/
public get onDown(): Kiwi.Signal {
return this.touchDown;
}
/**
* A Kiwi Signal that dispatches an event when a user releases a finger off of the stage.
* @property touchUp
* @type Signal
* @public
* @deprecated
*/
public touchUp: Kiwi.Signal;
/**
* A Kiwi Signal that dispatches an event when a user releases a finger off of the stage.
* @property onUp
* @type Signal
* @public
*/
public get onUp(): Kiwi.Signal {
return this.touchUp;
}
/**
* A Kiwi Signal that dispatches an event when a touch event is cancelled for the some reason.
* @property touchCancel
* @type Signal
* @public
* @deprecated
*/
public touchCancel: Kiwi.Signal;
/**
* A Kiwi Signal that dispatches an event when a touch event is cancelled for the some reason.
* @property onCancel
* @type Signal
* @public
*/
public get onCancel(): Kiwi.Signal {
return this.touchCancel;
}
/**
* An internal Kiwi method that runs when the DOM is loaded and the touch manager can now 'boot' up.
* @method boot
* @public
*/
public boot() {
this._domElement = this._game.stage.container;
this.finger1 = new Kiwi.Input.Finger(this._game);
this.finger2 = new Kiwi.Input.Finger(this._game);
this.finger3 = new Kiwi.Input.Finger(this._game);
this.finger4 = new Kiwi.Input.Finger(this._game);
this.finger5 = new Kiwi.Input.Finger(this._game);
this.finger6 = new Kiwi.Input.Finger(this._game);
this.finger7 = new Kiwi.Input.Finger(this._game);
this.finger8 = new Kiwi.Input.Finger(this._game);
this.finger9 = new Kiwi.Input.Finger(this._game);
this.finger10 = new Kiwi.Input.Finger(this._game);
this._fingers = [this.finger1, this.finger2, this.finger3, this.finger4, this.finger5, this.finger6, this.finger7, this.finger8, this.finger9, this.finger10];
this.latestFinger = this.finger1;
this.touchDown = new Kiwi.Signal();
this.touchUp = new Kiwi.Signal();
this.touchCancel = new Kiwi.Signal();
this.start();
}
/**
* Starts up the event listeners that are being used on the touch manager.
* @method start
* @public
*/
public start() {
if (Kiwi.DEVICE.touch) {
this.touchEnabled = true;
this._onTouchStartBind = this.onTouchStart.bind(this);
this._onTouchMoveBind = this.onTouchMove.bind(this);
this._onTouchEndBind = this.onTouchEnd.bind(this);
this._onTouchEnterBind = this.onTouchEnter.bind(this);
this._onTouchLeaveBind = this.onTouchLeave.bind(this);
this._onTouchCancelBind = this.onTouchCancel.bind(this);
if (this._game.deviceTargetOption === Kiwi.TARGET_BROWSER) {
//Uses the concept of pointers?
if (Kiwi.DEVICE.pointerEnabled) {
var pointerUp = 'pointerup',
pointerDown = 'pointerdown',
pointerEnter = 'pointerenter',
pointerLeave = 'pointerleave',
pointerCancel = 'pointercancel',
pointerMove = 'pointermove';
//Is it IE 10?
if (window["PointerEvent"]) {
// IE11 - Use standard event names
} else if ((window["MSPointerEvent"])) {
// IE10 compatibility
var pointerUp = 'MSPointerUp',
pointerDown = 'MSPointerDown',
pointerEnter = 'MSPointerEnter',
pointerLeave = 'MSPointerLeave',
pointerCancel = 'MSPointerCancel',
pointerMove = 'MSPointerMove';
}
this._onTouchStartBind = this.onPointerStart.bind(this);
this._onTouchMoveBind = this.onPointerMove.bind(this);
this._onTouchEndBind = this.onPointerEnd.bind(this);
this._onTouchEnterBind = this.onPointerEnter.bind(this);
this._onTouchLeaveBind = this.onPointerLeave.bind(this);
this._onTouchCancelBind = this.onPointerCancel.bind(this);
this._domElement.addEventListener(pointerUp, this._onTouchStartBind, false);
this._domElement.addEventListener(pointerMove, this._onTouchMoveBind, false);
this._domElement.addEventListener(pointerDown, this._onTouchEndBind, false);
this._domElement.addEventListener(pointerEnter, this._onTouchEnterBind, false);
this._domElement.addEventListener(pointerLeave, this._onTouchLeaveBind, false);
this._domElement.addEventListener(pointerCancel, this._onTouchCancelBind, false);
} else {
//Regular touch events
this._domElement.addEventListener('touchstart', this._onTouchStartBind, false);
this._domElement.addEventListener('touchmove', this._onTouchMoveBind, false);
this._domElement.addEventListener('touchend', this._onTouchEndBind, false);
this._domElement.addEventListener('touchenter', this._onTouchEnterBind, false);
this._domElement.addEventListener('touchleave', this._onTouchLeaveBind, false);
this._domElement.addEventListener('touchcancel', this._onTouchCancelBind, false);
document.addEventListener('touchmove', (event) => this.consumeTouchMove(event), false);
}
} else if (this._game.deviceTargetOption === Kiwi.TARGET_COCOON) {
this._game.stage.canvas.addEventListener('touchstart', this._onTouchStartBind, false);
this._game.stage.canvas.addEventListener('touchmove', this._onTouchMoveBind, false);
this._game.stage.canvas.addEventListener('touchend', this._onTouchEndBind, false);
this._game.stage.canvas.addEventListener('touchenter', this._onTouchEnterBind, false);
this._game.stage.canvas.addEventListener('touchleave', this._onTouchLeaveBind, false);
this._game.stage.canvas.addEventListener('touchcancel', this._onTouchCancelBind, false);
}
} else {
this.touchEnabled = false;
}
}
/**
* Prevent iOS bounce-back (doesn't work?)
* @method consumeTouchMove
* @param {Any} event
* @public
*/
private consumeTouchMove(event) {
event.preventDefault();
}
/**
* Gets the position of the latest finger on the x axis.
* @property x
* @type number
* @public
*/
public get x(): number {
return this.latestFinger.x;
}
/**
* Gets the position of the latest finger on the y axis.
* @property y
* @type number
* @public
*/
public get y(): number {
return this.latestFinger.y;
}
/**
* The developer defined maximum number of touch events.
* By default this is set to 10 but this can be set to be lower.
* @property _maxPointers
* @type number
* @default 10
* @private
*/
private _maxPointers: number = 10;
/**
* Sets the maximum number of point of contact that are allowed on the game stage at one point.
* The maximum number of points that are allowed is 10, and the minimum is 0.
* @property maximumPointers
* @type number
* @public
*/
public set maximumPointers(val:number) {
if (val < 0)
val = 1;
if (val > this._fingers.length) val = this._fingers.length;
this._maxPointers = val;
}
/**
* Gets the maximum number of points of contact that are allowed on the game stage at one point.
* @type number
* @public
*/
public get maximumPointers(): number {
return this._maxPointers;
}
/**
*-------------------------
* Generic Methods for Dealing with Pointers
*-------------------------
*/
/**
* This method is in charge of registering a "finger" (either from a Touch/Pointer start method) and assigning it a Finger,
* You have to pass this method a id which is used to idenfied when released/cancelled.
* @method _registerFinger
* @param event {Any}
* @param id {Number}
* @private
*/
private _registerFinger(event, id:number) {
for (var f = 0; f < this._maxPointers; f++) {
if (this._fingers[f].active === false) {
this._fingers[f].id = id;
this._fingers[f].start(event);
this.latestFinger = this._fingers[f];
this.touchDown.dispatch(this._fingers[f].x, this._fingers[f].y, this._fingers[f].timeDown, this._fingers[f].timeUp, this._fingers[f].duration, this._fingers[f]);
this.isDown = true;
this.isUp = false;
break;
}
}
}
/**
* This method is in charge of deregistering (removing) a "finger" when it has been released,
* You have to pass this method a id which is used to identfy the finger to deregister.
* @method _deregisterFinger
* @param event {Any}
* @param id {Number}
* @private
*/
private _deregisterFinger(event, id) {
var finger = null;
for (var f = 0; f < this._fingers.length; f++) {
if (this._fingers[f].active && this._fingers[f].id === id) {
this._fingers[f].stop(event);
this.latestFinger = this._fingers[f];
finger = this._fingers[f];
this.isDown = false;
this.isUp = true;
break;
}
}
//Loop through the fingers and check to see that none of them are down.
for (var i = 0; i < this._fingers.length; i++) {
if (this._fingers[i].active === true) {
this.isDown = true;
this.isUp = false;
}
}
if (finger !== null) {
this.touchUp.dispatch(finger.x, finger.y, finger.timeDown, finger.timeUp, finger.duration, finger);
}
}
/**
* This method is in charge of cancelling (removing) a "finger".
* You have to pass this method a id which is used to idenfied the finger that was cancelled.
* @method _cancelFinger
* @param event {Any}
* @param id {Number}
* @private
*/
private _cancelFinger(event, id) {
for (var f = 0; f < this._fingers.length; f++) {
if (this._fingers[f].active && this._fingers[f].id === id) {
this._fingers[f].stop(event);
this.touchCancel.dispatch(this._fingers[f].x, this._fingers[f].y, this._fingers[f].timeDown, this._fingers[f].timeUp, this._fingers[f].duration, this._fingers[f]);
break;
}
}
//loop through the fingers and check to see that none of them are down.
for (var i = 0; i < this._fingers.length; i++) {
if (this._fingers[i].active) {
this.isDown = true;
this.isUp = false;
}
}
}
/**
* This method is in charge of creating and assigning (removing) a "finger" when it has entered the dom element.
* You have to pass this method a id which is used to idenfied the finger that was cancelled.
* @method _enterFinger
* @param event {Any}
* @param id {Number}
* @private
*/
private _enterFinger(event, id) {
for (var f = 0; f < this._maxPointers; f++) {
if (this._fingers[f].active === false) {
this._fingers[f].id = id;
this._fingers[f].start(event);
this.latestFinger = this._fingers[f];
this.isDown = true;
this.isUp = false;
break;
}
}
}
/**
* This method is in charge of removing an assigned "finger" when it has left the DOM Elemetn.
* You have to pass this method a id which is used to idenfied the finger that left.
* @method _leaveFinger
* @param event {Any}
* @param id {Number}
* @private
*/
private _leaveFinger(event, id) {
for (var f = 0; f < this._fingers.length; f++) {
if (this._fingers[f].active && this._fingers[f].id === id) {
this._fingers[f].leave(event);
break;
}
}
}
/**
* This method is in charge of updating the coordinates of a "finger" when it has moved..
* You have to pass this method a id which is used to idenfied the finger that moved.
* @method _moveFinger
* @param event {Any}
* @param id {Number}
* @private
*/
private _moveFinger(event, id) {
for (var f = 0; f < this._fingers.length; f++) {
if (this._fingers[f].active && this._fingers[f].id === id) {
this._fingers[f].move(event);
this.latestFinger = this._fingers[f];
break;
}
}
}
/**
*-------------------
* Touch Events
*-------------------
**/
/**
* This method runs when the a touch start event is fired by the browser and then assigns the event to a pointer that is currently not active.
* https://developer.mozilla.org/en-US/docs/DOM/TouchList
* @method onTouchStart
* @param {Any} event
* @private
*/
private onTouchStart(event) {
//Stop corresponding mouse events from firing.
event.preventDefault();
for (var i = 0; i < event.changedTouches.length; i++) {
this._registerFinger(event.changedTouches[i], event.changedTouches[i].identifier);
}
}
/**
* Doesn't appear to be supported by most browsers yet but if it was it would fire events when a touch is canceled.
* http://www.w3.org/TR/touch-events/#dfn-touchcancel
* @method onTouchCancel
* @param {Any} event
* @private
*/
private onTouchCancel(event) {
event.preventDefault();
for (var i = 0; i < event.changedTouches.length; i++) {
this._cancelFinger(event.changedTouches[i], event.changedTouches[i].identifier);
}
}
/**
* Doesn't appear to be supported by most browsers yet. But if it was would fire events when touch events enter an element.
* @method onTouchEnter
* @param {Any} event
* @private
*/
private onTouchEnter(event) {
//Stop corresponding mouse events from firing.
event.preventDefault();
// For touch enter and leave its a list of the touch points that have entered or left the target
for (var i = 0; i < event.changedTouches.length; i++) {
this._enterFinger(event.changedTouches[i], event.changedTouches[i].identifier);
}
}
/**
* Doesn't appear to be supported by most browsers yet. Would fire events when a 'finger' leaves an element.
* Would be handly for when an finger 'leaves' the stage.
* @method onTouchLeave
* @param {Any} event
* @private
*/
private onTouchLeave(event) {
//Stops corresponding mouse events from firing
event.preventDefault();
// For touch enter and leave its a list of the touch points that have entered or left the target
for (var i = 0; i < event.changedTouches.length; i++) {
this._leaveFinger(event.changedTouches[i], event.changedTouches[i].identifier);
}
}
/**
* When a touch pointer moves. This method updates the appropriate pointer.
* @method onTouchMove
* @param {Any} event
* @private
*/
private onTouchMove(event) {
//Stop cooresponding mouse events from firing
event.preventDefault();
for (var i = 0; i < event.changedTouches.length; i++) {
this._moveFinger(event.changedTouches[i], event.changedTouches[i].identifier);
}
}
/**
* When a touch event gets released.
* https://developer.mozilla.org/en-US/docs/DOM/TouchList
* @method onTouchEnd
* @param {Any} event
* @private
*/
private onTouchEnd(event) {
//Stop cooresponding mouse events from firing
event.preventDefault();
for (var i = 0; i < event.changedTouches.length; i++) {
this._deregisterFinger(event.changedTouches[i], event.changedTouches[i].identifier);
}
}
/**
*-------------------
* Pointer Events
*-------------------
**/
/**
* Event that is fired when a pointer is initially pressed.
* @method onPointerStart
* @param event {PointerEvent}
* @private
*/
private onPointerStart(event: MSPointerEvent) {
if (event.type === 'touch' || event.type === "pointerdown") {
this._registerFinger(event, event.pointerId);
}
}
/**
* Event that is fired by a pointer event listener upon a pointer canceling for some reason.
* @method onPointerCancel
* @param event {PointerEvent}
* @private
*/
private onPointerCancel(event: MSPointerEvent) {
if (event.type === 'touch' || event.type === "pointercancel") {
this._cancelFinger(event, event.pointerId);
}
}
/**
* Event that is fired by a pointer event listener upon a pointer entering the DOM Element the event listener is attached to.
* @method onPointerEnter
* @param event {PointerEvent}
* @private
*/
private onPointerEnter(event: MSPointerEvent) {
if (event.type === 'touch' || event.type === "pointerenter") {
this._enterFinger(event, event.pointerId);
}
}
/**
* Event that is fired by a pointer event listener upon a pointer being leaving the DOM Element the event listener is attached to.
* @method onPointerLeave
* @param event {PointerEvent}
* @private
*/
private onPointerLeave(event: MSPointerEvent) {
if (event.type === 'touch' || event.type === "pointerleave") {
this._leaveFinger(event, event.pointerId);
}
}
/**
* Event that is fired by a pointer event listener upon a pointer moving.
* @method onPointerMove
* @param event {PointerEvent}
*/
private onPointerMove(event: MSPointerEvent) {
if (event.type === 'touch' || event.type === "pointermove") {
this._moveFinger(event, event.pointerId);
}
}
/**
* Event that is fired by a pointer event listener upon a pointer being released.
* @method onPointerEnd
* @param event {PointerEvent}
* @private
*/
private onPointerEnd(event: MSPointerEvent) {
if (event.type === 'touch' || event.type === "pointerup") {
this._deregisterFinger(event, event.pointerId);
}
}
/**
*-----------------
* Normal Methods
*-----------------
**/
/**
* The update loop fro the touch manager.
* @method update
* @public
*/
public update() {
if (this.touchEnabled && this.isDown) {
for (var i = 0; i < this._fingers.length; i++) {
if (this._fingers[i].active) {
this._fingers[i].update();
}
}
}
}
/**
* This method removes all of the event listeners and thus 'stops' the touch manager.
* @method stop
* @public
*/
public stop() {
if (!this.touchEnabled) return;
if (this._game.deviceTargetOption === Kiwi.TARGET_BROWSER) {
//Uses the concept of pointers?
if (Kiwi.DEVICE.pointerEnabled) {
var pointerUp = 'pointerup',
pointerDown = 'pointerdown',
pointerEnter = 'pointerenter',
pointerLeave = 'pointerleave',
pointerCancel = 'pointercancel',
pointerMove = 'pointermove';
//Is it IE 10?
if (window["PointerEvent"]) {
// IE11 - Use standard event names
} else if ((window["MSPointerEvent"])) {
// IE10 compatibility
var pointerUp = 'MSPointerUp',
pointerDown = 'MSPointerDown',
pointerEnter = 'MSPointerEnter',
pointerLeave = 'MSPointerLeave',
pointerCancel = 'MSPointerCancel',
pointerMove = 'MSPointerMove';
}
this._domElement.removeEventListener(pointerUp, this._onTouchStartBind, false);
this._domElement.removeEventListener(pointerMove, this._onTouchMoveBind, false);
this._domElement.removeEventListener(pointerDown, this._onTouchEndBind, false);
this._domElement.removeEventListener(pointerEnter, this._onTouchEnterBind, false);
this._domElement.removeEventListener(pointerLeave, this._onTouchLeaveBind, false);
this._domElement.removeEventListener(pointerCancel, this._onTouchCancelBind, false);
} else {
//Regular touch events
this._domElement.removeEventListener('touchstart', this._onTouchStartBind, false);
this._domElement.removeEventListener('touchmove', this._onTouchMoveBind, false);
this._domElement.removeEventListener('touchend', this._onTouchEndBind, false);
this._domElement.removeEventListener('touchenter', this._onTouchEnterBind, false);
this._domElement.removeEventListener('touchleave', this._onTouchLeaveBind, false);
this._domElement.removeEventListener('touchcancel', this._onTouchCancelBind, false);
}
} else if (this._game.deviceTargetOption === Kiwi.TARGET_COCOON) {
this._game.stage.canvas.removeEventListener('touchstart', this._onTouchStartBind, false);
this._game.stage.canvas.removeEventListener('touchmove', this._onTouchMoveBind, false);
this._game.stage.canvas.removeEventListener('touchend', this._onTouchEndBind, false);
this._game.stage.canvas.removeEventListener('touchenter', this._onTouchEnterBind, false);
this._game.stage.canvas.removeEventListener('touchleave', this._onTouchLeaveBind, false);
this._game.stage.canvas.removeEventListener('touchcancel', this._onTouchCancelBind, false);
}
delete this._onTouchStartBind;
delete this._onTouchMoveBind;
delete this._onTouchEndBind;
delete this._onTouchEnterBind;
delete this._onTouchLeaveBind;
delete this._onTouchCancelBind;
}
/**
* Resets all of the fingers/pointers to their default states.
* @method reset
* @public
*/
public reset() {
for (var i = 0; i < this._fingers.length; i++) {
this._fingers[i].reset();
}
}
/**
* The binding of the 'onTouchStart' method.
*
* @property _onTouchStartBind
* @type Function
* @since 1.3.0
* @private
*/
private _onTouchStartBind;
/**
* The binding of the 'onTouchMove' method.
*
* @property _onTouchMoveBind
* @type Function
* @since 1.3.0
* @private
*/
private _onTouchMoveBind;
/**
* The binding of the 'onTouchEnd' method.
*
* @property _onTouchEndBind
* @type Function
* @since 1.3.0
* @private
*/
private _onTouchEndBind;
/**
* The binding of the 'onTouchEnter' method.
*
* @property _onTouchEnterBind
* @type Function
* @since 1.3.0
* @private
*/
private _onTouchEnterBind;
/**
* The binding of the 'onTouchLeave' method.
*
* @property _onTouchLeaveBind
* @type Function
* @since 1.3.0
* @private
*/
private _onTouchLeaveBind;
/**
* The binding of the 'onTouchCancel' method.
*
* @property _onTouchCancelBind
* @type Function
* @since 1.3.0
* @private
*/
private _onTouchCancelBind;
}
} | the_stack |
import react = require('react');
import react_dom = require('react-dom');
import style = require('ts-style');
import colors = require('./colors');
import { div } from '../base/dom_factory';
import fonts = require('./fonts');
import reactutil = require('../base/reactutil');
import ripple = require('./ripple');
import style_util = require('../base/style_util');
// http://www.google.co.uk/design/spec/components/menus.html
var theme = style.create(
{
menu: {
position: 'absolute',
paddingTop: 8,
paddingBottom: 8,
boxSizing: 'border-box',
boxShadow: 'rgba(0, 0, 0, 0.26) 0px 1px 2px 2px',
backgroundColor: 'white',
overflowY: 'hidden',
transform: 'translate3d(0,0,0)',
transition: style_util.transitionOn({
opacity: 0.3,
transform: 0.3,
}),
// container which holds the menu itself and the overlay
// which covers the background
container: {
position: 'absolute',
left: 0,
top: 0,
right: 0,
bottom: 0,
},
// overlay which appears behind the menu
// and intercepts click/touch events to
// dismiss the menu.
//
// On small screens it also serves to
// dim the background to highlight the menu
overlay: {
position: 'fixed',
left: 0,
right: 0,
top: 0,
bottom: 0,
backgroundColor: '#000',
opacity: 0.01,
transition: style_util.transitionOn({
opacity: 0.3,
}),
},
item: {
position: 'relative',
paddingLeft: 16,
paddingRight: 16,
fontSize: 16,
cursor: 'pointer',
userSelect: 'none',
verticalAlign: 'middle',
lineHeight: '48px',
height: 48,
textOverflow: 'ellipsis',
':hover': {
backgroundColor: colors.MATERIAL_GREY_P200,
},
label: {
width: '100%',
height: '100%',
// give menu item label its own stacking context so
// that it renders on top of ripple effect
transform: 'translate3d(0,0,0)',
},
},
},
},
__filename
);
export interface MenuItem {
label: string;
onClick: () => void;
}
interface MenuState {
document?: Document;
transition?: reactutil.TransitionState;
showTime?: Date;
}
export interface MenuProps extends react.Props<void> {
/** The source rect of the icon which triggered the
* menu.
*/
sourceRect: reactutil.Rect;
/** The viewport within which the menu is being
* displayed.
*/
viewportRect: reactutil.Rect;
/** List of menu items to display in the menu. */
items: MenuItem[];
/** Callback to invoke when the menu is dismissed. */
onDismiss: () => void;
/** Z-index of the menu container. */
zIndex: number;
}
function measureText(document: Document, text: string, font: string) {
if (!document) {
// in non-browser contexts, use a dummy value
return text.length * 10;
}
var HELPER_CANVAS_ID = 'materialMenuCanvas';
var menuCanvas = <HTMLCanvasElement>document.getElementById(
HELPER_CANVAS_ID
);
if (!menuCanvas) {
menuCanvas = document.createElement('canvas');
menuCanvas.id = HELPER_CANVAS_ID;
menuCanvas.style.display = 'none';
document.body.appendChild(menuCanvas);
}
var context = <CanvasRenderingContext2D>menuCanvas.getContext('2d');
context.font = font;
return context.measureText(text).width;
}
/** A material-design style menu.
*
* See http://www.google.co.uk/design/spec/components/menus.html
*
* On small screens, this component automatically
* displays as a bottom sheet
* (see http://www.google.co.uk/design/spec/components/bottom-sheets.html)
*
* This component must be rendered inside a react.TransitionGroup component
* for it to be displayed.
*/
export class Menu extends react.Component<MenuProps, MenuState> {
private menu: HTMLElement;
private transitionListener: reactutil.TransitionEndListener;
constructor(props: MenuProps) {
super(props);
this.state = {
document: null,
showTime: new Date(),
transition: reactutil.TransitionState.WillEnter,
};
}
private transitionProperty() {
return this.displayAsSheet() ? 'transform' : 'opacity';
}
componentWillEnter(callback: () => void) {
this.setState({ transition: reactutil.TransitionState.WillEnter });
setTimeout(() => {
this.setState({ transition: reactutil.TransitionState.Entered });
}, 10);
this.transitionListener = new reactutil.TransitionEndListener(
this.menu,
this.transitionProperty(),
() => {
callback();
}
);
}
componentDidEnter() {
this.transitionListener.remove();
}
componentWillLeave(callback: () => void) {
this.setState({ transition: reactutil.TransitionState.Leaving });
this.transitionListener = new reactutil.TransitionEndListener(
this.menu,
this.transitionProperty(),
() => {
callback();
}
);
}
componentDidLeave() {
this.transitionListener.remove();
}
componentDidMount() {
this.setState({
document: (<HTMLElement>react_dom.findDOMNode(this)).ownerDocument,
showTime: new Date(),
});
}
// returns true if this menu should be displayed
// as a sheet sliding in from one edge of the app.
//
// Referred to as a 'Bottom Sheet' in the Material Design
// specs
private displayAsSheet() {
var SMALL_SCREEN_WIDTH_THRESHOLD = 400;
return (
reactutil.rectWidth(this.props.viewportRect) <
SMALL_SCREEN_WIDTH_THRESHOLD
);
}
private getMenuRect() {
// On large screens (tablet, desktop), the menu is
// positioned such that one of the corners is aligned
// with a corner of the source rect. If space permits,
// this is the top-left corner. Otherwise one of the
// other corners is aligned.
//
// On small screens (phone), the menu will slide in
// from one of the edges of the display and use the
// full width of that edge
var MENU_ITEM_HEIGHT = 48;
var VIEWPORT_EDGE_MARGIN = 3;
var viewRect = this.props.viewportRect;
var srcRect = {
left: this.props.sourceRect.left,
right: this.props.sourceRect.right,
top: this.props.sourceRect.top,
bottom: this.props.sourceRect.bottom,
};
srcRect.left = Math.max(
srcRect.left,
viewRect.left + VIEWPORT_EDGE_MARGIN
);
srcRect.right = Math.min(
srcRect.right,
viewRect.right - VIEWPORT_EDGE_MARGIN
);
srcRect.top = Math.max(
srcRect.top,
viewRect.top + VIEWPORT_EDGE_MARGIN
);
srcRect.bottom = Math.min(
srcRect.bottom,
viewRect.bottom - VIEWPORT_EDGE_MARGIN
);
var menuRect: reactutil.Rect;
var expandedHeight = this.props.items.length * MENU_ITEM_HEIGHT;
expandedHeight += theme.menu.paddingTop + theme.menu.paddingBottom;
// ideally this should be adjusted to fit the text
// of menu items
var menuWidth = 0;
var itemFont = theme.menu.item.fontSize + 'px ' + fonts.FAMILY;
this.props.items.forEach(item => {
// under Firefox a small amount of extra padding needs to be added
// to the computed text width to avoid wrapping
const TEXT_PADDING = 5;
var itemWidth =
measureText(this.state.document, item.label, itemFont) +
TEXT_PADDING;
menuWidth = Math.max(menuWidth, itemWidth);
});
menuWidth += theme.menu.item.paddingLeft + theme.menu.item.paddingRight;
if (this.displayAsSheet()) {
// show menu at bottom of display
menuRect = {
left: viewRect.left,
bottom: viewRect.bottom,
right: viewRect.right,
top: viewRect.bottom - expandedHeight,
};
} else {
var hasSpaceToRight = viewRect.right - srcRect.left > menuWidth;
var hasSpaceBelow = viewRect.bottom - srcRect.top > expandedHeight;
if (hasSpaceToRight) {
if (hasSpaceBelow) {
// align TL of source rect with TL of menu
menuRect = {
top: srcRect.top,
left: srcRect.left,
right: srcRect.left + menuWidth,
bottom: srcRect.top + expandedHeight,
};
} else {
// align BL of source rect with BL of menu
menuRect = {
top: srcRect.bottom - expandedHeight,
left: srcRect.left,
right: srcRect.left + menuWidth,
bottom: srcRect.bottom,
};
}
} else {
if (hasSpaceBelow) {
// align TR of source rect with TR of menu
menuRect = {
top: srcRect.top,
left: srcRect.right - menuWidth,
right: srcRect.right,
bottom: srcRect.top + expandedHeight,
};
} else {
// align BR of source rect with BR of menu
menuRect = {
top: srcRect.bottom - expandedHeight,
left: srcRect.right - menuWidth,
right: srcRect.right,
bottom: srcRect.bottom,
};
}
}
}
return menuRect;
}
render() {
var menuItems = this.props.items.map(item => {
return div(
style.mixin(theme.menu.item, {
key: item.label,
onClick: () => {
// when the menu is first opened, ignore any immediate taps that
// might still be events from the user tapping to open the menu
var MIN_ITEM_CLICK_DELAY = 500;
if (
Date.now() - this.state.showTime.getTime() <
MIN_ITEM_CLICK_DELAY
) {
return;
}
setTimeout(() => {
item.onClick();
this.props.onDismiss();
}, 300);
},
}),
ripple.InkRippleF({ radius: 100 }),
div(style.mixin(theme.menu.item.label), item.label)
);
});
var menuRect = this.getMenuRect();
var menuOpacity = 0;
var menuTransform = 'translateY(0px)';
var enteringOrLeaving =
this.state.transition !== reactutil.TransitionState.Entered;
if (!enteringOrLeaving || this.displayAsSheet()) {
// menus fade in. Sheets slide in from a screen edge
menuOpacity = 1.0;
}
var overlayStyles: any[] = [theme.menu.overlay];
if (this.displayAsSheet()) {
if (!enteringOrLeaving) {
// see http://www.google.co.uk/design/spec/components/bottom-sheets.html#bottom-sheets-specs
overlayStyles.push({ opacity: 0.2 });
} else {
menuTransform =
'translateY(' + reactutil.rectHeight(menuRect) + 'px)';
}
}
return div(
style.mixin([
theme.menu.container,
{
zIndex: this.props.zIndex,
},
]),
div(
style.mixin(overlayStyles, {
onClick: (e: react.MouseEvent<Element>) => {
this.props.onDismiss();
},
})
),
div(
style.mixin(theme.menu, {
ref: (el: HTMLElement) => (this.menu = el),
style: reactutil.prefix({
top: menuRect.top,
left: menuRect.left,
width: menuRect.right - menuRect.left,
height: menuRect.bottom - menuRect.top,
opacity: menuOpacity,
transform: menuTransform,
}),
}),
menuItems
)
);
}
}
export var MenuF = react.createFactory(Menu); | the_stack |
import { $, $Events } from '../$'
import { SELF } from '../../constant/SELF'
import { DuplicatedInputFoundError } from '../../exception/DuplicatedInputFoundError'
import { DuplicatedOutputFoundError } from '../../exception/DuplicatedOutputFoundError'
import { InputNotFoundError } from '../../exception/InputNotFoundError'
import { InvalidArgumentType } from '../../exception/InvalidArgumentType'
import { OutputNotFoundError } from '../../exception/OutputNotFoundError'
import { U, U_EE } from '../../interface/U'
import { Pin } from '../../Pin'
import { PinOpt } from '../../PinOpt'
import { PinOpts } from '../../PinOpts'
import { Pins } from '../../Pins'
import { Pod } from '../../pod'
import { System } from '../../system'
import forEachKeyValue from '../../system/core/object/ForEachKeyValue/f'
import { Dict } from '../../types/Dict'
import { IO } from '../../types/IO'
import { None } from '../../types/None'
import { Unlisten } from '../../types/Unlisten'
import { pull, push, removeAt } from '../../util/array'
import { mapObjVK } from '../../util/object'
export type PinMap<T> = Dict<Pin<T[keyof T]>>
const toPinMap = <T>(
names: string[]
): {
[K in keyof T]?: Pin<T[K]>
} => {
return names.reduce(
(acc, name) => ({
...acc,
[name]: new Pin(),
}),
{}
)
}
export interface ION {
i?: string[]
o?: string[]
}
export interface Opt {
input?: PinOpts
output?: PinOpts
}
export const DEFAULT_PIN_OPT: PinOpt = {
ref: false,
}
export type PinOf<T> = Pin<T[keyof T]>
export type UnitEvents<_EE extends Dict<any[]>> = $Events<_EE & U_EE> & U_EE
export class Unit<
I extends Dict<any> = any,
O extends Dict<any> = any,
_EE extends UnitEvents<_EE> & Dict<any[]> = UnitEvents<U_EE>
>
extends $<_EE>
implements U<I, O>
{
public __: string[] = ['U']
public $parent: Unit | null = null
public $path: string[] = []
public $id: string | null = null
public _input: Pins<I> = {}
public _output: Pins<O> = {}
public _data_input: Pins<any> = {}
public _data_output: Pins<any> = {}
public _ref_input: Pins<any> = {}
public _ref_output: Pins<any> = {}
protected _i_opt: Dict<PinOpt> = {}
protected _o_opt: Dict<PinOpt> = {}
protected _i_name_set: Set<string> = new Set()
protected _o_name_set: Set<string> = new Set()
protected _d_i_name: Set<string> = new Set()
protected _d_o_name: Set<string> = new Set()
protected _r_i_name: Set<string> = new Set()
protected _r_o_name: Set<string> = new Set()
protected _o_count: number = 0
protected _i_count: number = 0
protected _d_i_count: number = 0
protected _d_o_count: number = 0
protected _r_i_count: number = 0
protected _r_o_count: number = 0
protected _err: string | null = null
protected _selfPin: Pin<U>
public ref: any | null = null
public _paused: boolean = true
public _opt: Opt
constructor(
{ i = [], o = [] }: ION,
opt: Opt = {},
system: System,
pod: Pod
) {
super(system, pod)
const { input, output } = opt
const inputMap = toPinMap<I>(i)
const outputMap = toPinMap<O>(o)
this.setInputs(inputMap, input)
this.setOutputs(outputMap, output)
this._selfPin = new Pin<U>({ data: this, constant: false })
this._selfPin.addListener('drop', () => {
throw new Error('Self Pin should never be dropped!')
})
}
public isPinIgnored(type: IO, name: string): boolean {
const pin = this.getPin(type, name)
const ignored = pin.ignored()
return ignored
}
public setParent(parent: Unit | null) {
this.$parent = parent
this.emit('parent', this.$parent)
}
public setPinIgnored(type: IO, name: string, ignored: boolean): void {
if (type === 'input') {
this.setInputIgnored(name, ignored)
} else {
this.setOutputIgnored(name, ignored)
}
}
private _memSetPinOptData(type: IO, name: string): void {
if (type === 'input') {
this._memSetInputData(name)
} else {
this._memSetOutputData(name)
}
}
private _memSetInputData(name: string): void {
const input = this._input[name]
this._memRemoveRefInput(name)
this._memAddDataInput(name, input)
}
private _memSetOutputData(name: string): void {
const output = this._output[name]
this._memRemoveRefOutput(name)
this._memAddDataOutput(name, output)
}
private _memSetPinRef(type: IO, name: string): void {
if (type === 'input') {
this._memSetInputRef(name)
} else {
this._memSetOutputRef(name)
}
}
private _memSetInputRef(name: string): void {
const input = this._input[name]
this._memRemoveDataInput(name)
this._memAddRefInput(name, input)
}
private _memSetOutputRef(name: string): void {
const output = this._output[name]
this._memRemoveDataOutput(name)
this._memAddRefOutput(name, output)
}
public setPinRef(type: IO, name: string, ref: boolean): void {
if (ref) {
if (this.hasRefPinNamed(type, name)) {
return
} else {
this._memSetPinRef(type, name)
}
} else {
if (this.hasPinNamed(type, name)) {
return
} else {
this._memSetPinOptData(type, name)
}
}
}
public setInputRef(name: string, ref: boolean): void {
this.setPinRef('input', name, ref)
}
public setOutputRef(name: string, ref: boolean): void {
this.setPinRef('output', name, ref)
}
public setInputIgnored(name: string, ignore: boolean): boolean {
const input = this.getInput(name)
if (this.hasRefInputNamed(name)) {
return
}
return input.ignored(ignore)
}
public setOutputIgnored(name: string, ignore: boolean): boolean {
if (this.hasRefOutputNamed(name)) {
return
}
const output = this.getOutput(name)
return output.ignored(ignore)
}
public setInputs(inputs: Pins<I>, opts: PinOpts = {}): void {
for (let name in inputs) {
const input = inputs[name]
const opt = opts[name]
this.setInput(name, input, opt)
}
}
public setPin(
name: string,
type: IO,
pin: Pin<any>,
opt: PinOpt = DEFAULT_PIN_OPT
) {
if (type === 'input') {
this.setInput(name, pin, opt)
} else {
this.setOutput(name, pin, opt)
}
}
public setInput<K extends keyof I>(
name: string,
input: Pin<I[K]>,
opt: PinOpt = DEFAULT_PIN_OPT
) {
this._setInput(name, input, opt)
this.emit('set_input', name, input, opt)
}
public _setInput<K extends keyof I>(
name: K,
input: Pin<I[K]>,
opt: PinOpt = DEFAULT_PIN_OPT
) {
if (this.hasInputNamed(name)) {
this.removeInput(name)
}
this._i_count++
this._i_name_set.add(name)
this._input[name] = input
this._i_opt[name] = opt
const { ref } = opt
if (ref) {
this._memAddRefInput(name, input)
} else {
this._memAddDataInput(name, input)
}
}
private _memAddDataInput(name: string, input: PinOf<I>): void {
this._d_i_count++
this._d_i_name.add(name)
this._data_input[name] = input
}
private _memAddRefInput(name: string, input: PinOf<I>): void {
this._r_i_count++
this._r_i_name.add(name)
this._ref_input[name] = input
}
private _validateInputName(name: any): void {
if (typeof name === 'string') {
if (!this.hasInputNamed(name)) {
throw new InputNotFoundError(name)
}
} else {
console.trace('name', name)
throw new InvalidArgumentType('name should be a string')
}
}
private _validateOutputName(name: any): void {
if (typeof name === 'string') {
if (!this.hasOutputNamed(name)) {
throw new OutputNotFoundError(name)
}
} else {
throw new InvalidArgumentType('name should be a string')
}
}
public addInput(
name: string,
input: Pin<any>,
opt: PinOpt = DEFAULT_PIN_OPT
): void {
if (this.hasInputNamed(name)) {
throw new DuplicatedInputFoundError(name)
}
this.setInput(name, input, opt)
}
public removeInput(name: string): void {
if (!this.hasInputNamed(name)) {
throw new InputNotFoundError(name)
}
const input = this._input[name]
this._i_count--
this._i_name_set.delete(name)
delete this._input[name]
const opt = this._i_opt[name]
const { ref } = opt
if (ref) {
this._memRemoveRefInput(name)
} else {
this._memRemoveDataInput(name)
}
this.emit('remove_input', name, input)
}
private _memRemoveDataInput = (name: string): void => {
this._d_i_count--
this._d_i_name.delete(name)
delete this._data_input[name]
}
private _memRemoveRefInput = (name: string): void => {
this._r_i_count--
this._r_i_name.delete(name)
delete this._ref_input[name]
}
public setOutputs(outputs: Pins<O>, opts: PinOpts = {}): void {
for (let name in outputs) {
const output = outputs[name]
const opt = opts[name]
this.setOutput(name, output, opt)
}
}
public setOutput<K extends keyof O>(
name: K,
output: Pin<O[K]>,
opt: PinOpt = DEFAULT_PIN_OPT
) {
this._setOutput(name, output, opt)
this.emit('set_output', name, output, opt)
}
public _setOutput<K extends keyof O>(
name: K,
output: Pin<O[K]>,
opt: PinOpt = DEFAULT_PIN_OPT
) {
if (this.hasOutputNamed(name)) {
this.removeOutput(name)
}
if (name === SELF) {
this._selfPin = output
}
this._o_count++
this._o_name_set.add(name)
this._o_opt[name] = opt
const { ref } = opt
if (ref) {
this._memAddRefOutput(name, output)
} else {
this._memAddDataOutput(name, output)
}
this._output[name] = output
}
private _memAddRefOutput = (name: string, output: Pin<O[keyof O]>): void => {
this._r_o_count++
this._r_o_name.add(name)
this._memSetRefOutput(name, output)
}
private _memSetRefOutput = (name: string, output: Pin<O[keyof O]>): void => {
this._ref_output[name] = output
}
private _memAddDataOutput = (name: string, output: Pin<O[keyof O]>): void => {
this._d_o_count++
this._d_o_name.add(name)
this._memSetDataOutput(name, output)
}
private _memSetDataOutput = (name: string, output: Pin<O[keyof O]>): void => {
this._data_output[name] = output
}
public addOutput(
name: string,
output: Pin<any>,
opt: PinOpt = DEFAULT_PIN_OPT
): void {
if (this.hasOutputNamed(name)) {
throw new DuplicatedOutputFoundError(name)
}
this.setOutput(name, output, opt)
}
private _memRemoveRefPin = (type: IO, name: string): void => {
if (type === 'input') {
this._memRemoveRefInput(name)
} else {
this._memRemoveRefOutput(name)
}
}
private _memRemoveRefOutput = (name: string): void => {
this._r_o_count--
this._r_o_name.delete(name)
delete this._ref_output[name]
}
private _memRemoveDataOutput = (name: string): void => {
this._d_o_count--
this._d_o_name.delete(name)
delete this._data_output[name]
}
public removeOutput(name: string): void {
if (!this.hasOutputNamed(name)) {
throw new OutputNotFoundError(name)
}
this._o_count--
this._o_name_set.delete(name)
const opt = this._o_opt[name]
const { ref } = opt
if (ref) {
this._memRemoveRefOutput(name)
} else {
this._memRemoveDataOutput(name)
}
const output = this._output[name]
delete this._output[name]
this.emit('remove_output', name, output)
}
public removePin(type: IO, name: string): void {
if (type === 'input') {
this.removeInput(name)
} else {
this.removeOutput(name)
}
}
public getPin(type: IO, pinId: string): Pin<any> {
if (type === 'input') {
return this.getInput(pinId)
} else {
return this.getOutput(pinId)
}
}
public getInputs(): Pins<I> {
return this._input
}
public getDataInputs(): Pins<Partial<I>> {
return this._data_input
}
public getRefInputs(): Pins<Partial<I>> {
return this._ref_input
}
public getInput(name: string): Pin<any> {
this._validateInputName(name)
return this._input[name]
}
public getOutputs(): Pins<O> {
return this._output
}
public getDataOutputs(): Pins<Partial<O>> {
return this._data_output
}
public getRefOutputs(): Pins<Partial<O>> {
return this._ref_output
}
public getOutput(name: string): Pin<any> {
if (name === SELF) {
return this._selfPin
}
this._validateOutputName(name)
return this._output[name]
}
public push<K extends keyof I>(name: string, data: any): void {
this.pushInput(name, data)
}
public pushInput<K extends keyof I>(name: string, data: I[K]): void {
this._validateInputName(name)
this.getInput(name).push(data)
}
public pushAllInput<K extends keyof I>(data: Dict<I[K]>): void {
forEachKeyValue(data, (value, name) => this.pushInput(name, value))
}
public pushOutput<K extends keyof O>(name: string, data: O[K]): void {
this.getOutput(name).push(data)
}
public pushAllOutput<K extends keyof O>(data: Dict<O[K]>): void {
forEachKeyValue(data, (value, name) => this.pushOutput(name, value))
}
public pushAll<K extends keyof I>(data: Dict<I[K]>): void {
this.pushAllInput(data)
}
public takeInput<K extends keyof O>(name: string): O[K] {
this._validateInputName(name)
return this.getInput(name).take()
}
public takeOutput<K extends keyof O>(name: string): O[K] {
return this.getOutput(name).take()
}
// short for takeOutput
public take<K extends keyof O>(name: string): O[K] {
return this.takeOutput(name)
}
public takeAll(): Dict<any> {
return mapObjVK(this._output, (output) => output.take())
}
public peakInput<K extends keyof I>(name: string): I[K] {
return this.getInput(name).peak()
}
public peakOutput<K extends keyof O>(name: string): O[K] {
return this.getOutput(name).peak()
}
public peak<K extends keyof O>(name: string): O[K] {
return this.peakOutput(name)
}
public peakAllOutput(): Dict<any> {
return mapObjVK(this._output, (pin) => pin.peak())
}
public peakAll(): Dict<any> {
return this.peakAllOutput()
}
public hasPinNamed(type: IO, name: string): boolean {
if (type === 'input') {
return this.hasInputNamed(name)
} else {
return this.hasOutputNamed(name)
}
}
public hasInputNamed(name: string): boolean {
return this._input[name] !== undefined
}
public hasOutputNamed(name: string): boolean {
return this._output[name] !== undefined
}
public hasRefPinNamed(type: IO, name: string): boolean {
if (type === 'input') {
return this.hasRefInputNamed(name)
} else {
return this.hasRefOutputNamed(name)
}
}
public hasRefInputNamed(name: string): boolean {
return this._r_i_name.has(name)
}
public renamePin(type: IO, name: string, newName: string): void {
if (type === 'input') {
this.renameInput(name, newName)
} else {
this.renameOutput(name, newName)
}
}
public renameInput(name: keyof I, newName: keyof I): void {
if (!this.hasInputNamed(name)) {
throw new InputNotFoundError(name)
}
const input = this._input[name]
const opt = this._i_opt[name]
this._i_name_set.delete(name)
this._i_name_set.add(newName)
delete this._input[name]
this._input[newName] = input
delete this._i_opt[name]
this._i_opt[newName] = opt
const { ref } = opt
if (ref) {
this._r_i_name.delete(name)
this._r_i_name.add(newName)
delete this._ref_input[name]
this._ref_input[newName] = input
} else {
this._d_i_name.delete(name)
this._d_i_name.add(newName)
delete this._data_input[name]
this._data_input[newName] = input
}
this.emit('rename_input', name, newName)
}
public renameOutput(name: keyof O, newName: keyof O): void {
if (!this.hasOutputNamed(name)) {
throw new InputNotFoundError(name)
}
const output = this._output[name]
const opt = this._o_opt[name]
this._o_name_set.delete(name)
this._o_name_set.add(newName)
delete this._output[name]
this._output[newName] = output
delete this._o_opt[name]
this._o_opt[newName] = opt
const { ref } = opt
if (ref) {
this._r_o_name.delete(name)
this._r_o_name.add(newName)
delete this._ref_output[name]
this._ref_output[newName] = output
} else {
this._d_o_name.delete(name)
this._d_o_name.add(newName)
delete this._data_output[name]
this._data_output[newName] = output
}
this.emit('rename_output', name, newName)
}
public getInputOpt(name: string): PinOpt {
return this._i_opt[name]
}
public getOutputOpt(name: string): PinOpt {
return this._o_opt[name]
}
public hasRefOutputNamed(name: string): boolean {
return this._r_o_name.has(name)
}
public getInputCount(): number {
return this._i_count
}
public getOutputCount(): number {
return this._o_count
}
public getInputNames(): string[] {
return Object.keys(this._input)
}
public getOutputNames(): string[] {
return Object.keys(this._output)
}
public setPinData(type: IO, pinId: string, data: any): void {
const pin = this.getPin(type, pinId)
// AD HOC
try {
pin.push(data)
} catch (err) {
this.err(err.message.toLowerCase())
}
}
public removePinData(type: IO, pinId: string): void {
const pin = this.getPin(type, pinId)
pin.take()
}
public setInputConstant(pinId: string, constant: boolean): void {
const input = this.getInput(pinId)
input.constant(constant)
}
public setOutputConstant(pinId: string, constant: boolean): void {
const output = this.getOutput(pinId)
output.constant(constant)
}
public getCatchErr(): boolean {
return this._catchErr
}
private _catcherCallback: ((err: string | null) => void)[] = []
private _catcherDoneCount: number = 0
private _catcherDone: boolean[] = []
protected _catchErr: boolean = false
protected _caughtErr: string | null = null
public caughtErr(): string | null {
return this._caughtErr
}
public catch(callback: (err: string) => void): {
unlisten: Unlisten
done: () => void
} {
push(this._catcherCallback, callback)
push(this._catcherDone, false)
this._catchErr = true
const err = this._err
if (err) {
this._err = null
this._caughtErr = err
this.emit('catch_err', err)
}
const _check_all_done = () => {
if (this._catcherDoneCount === this._catcherCallback.length) {
_all_done()
}
}
const _all_done = () => {
const caughtErr = this._caughtErr
this._caughtErr = null
this._catcherDoneCount = 0
this._catcherDone.fill(false)
this.emit('take_caught_err', caughtErr)
}
const unlisten = () => {
const i = this._catcherCallback.indexOf(callback)
if (i > -1) {
pull(this._catcherCallback, callback)
const done = this._catcherDone[i]
removeAt(this._catcherDone, i)
if (this._catcherCallback.length === 0) {
const err = this._caughtErr
this._catchErr = false
if (err !== null) {
this._caughtErr = null
this.err(err)
this.emit('take_caught_err', err)
}
}
if (!done) {
_check_all_done()
}
} else {
throw new Error('Unregistered Catcher cannot call unlisten')
}
}
const done = () => {
if (this._caughtErr) {
const i = this._catcherCallback.indexOf(callback)
if (i > -1) {
const done = this._catcherDone[i]
if (done) {
throw new Error('Catcher cannot be done twice')
} else {
this._catcherDone[i] = true
this._catcherDoneCount++
_check_all_done()
}
} else {
throw new Error('Unregistered Catcher cannot call done')
}
} else {
throw new Error("Catcher cannot call done when there's no Caught Error")
}
}
return { unlisten, done }
}
public getConfig(): Opt {
return this._opt
}
// just a little more helpful log
protected _log(...args: any[]) {
console.log(`[${this.constructor.name}]`, ...args)
}
public reset(): void {
this.takeErr()
this.emit('reset')
}
public pause(): void {
if (!this._paused) {
this._paused = true
this.emit('pause')
}
}
public play(): void {
if (this._paused) {
this._paused = false
this.emit('play')
}
}
public paused(): boolean {
return this._paused
}
public getSelfPin(): Pin<U> {
return this._selfPin
}
public err(err?: string | Error | None): string | null {
// console.log('Unit', 'err', err)
// everything is alright when there is no err
if (err) {
if (err instanceof Error) {
err = err.message
}
if (this._catchErr) {
this._caughtErr = err
for (const callback of this._catcherCallback) {
callback(err)
}
} else {
// exceptions in unit are isolated to the unit
// they do not kill the application
// they are expected though to stop the unit from functioning
this._err = err
this.emit('err', err)
}
}
return this._err
}
public hasErr(): boolean {
return this._err !== null
}
public getErr(): string | null {
return this._err
}
public takeErr(): string | null {
const err = this._err
if (err) {
this._err = null
this.emit('take_err', err)
}
return err
}
public takeCaughtErr(): string | null {
const err = this._caughtErr
if (err) {
this._caughtErr = null
for (const callback of this._catcherCallback) {
callback(null)
}
this.emit('take_caught_err', err)
}
return err
}
public destroy(): void {
super.destroy()
}
public getPinData(): { input: Dict<any>; output: Dict<any> } {
const data: { input: Dict<any>; output: Dict<any> } = {
input: {},
output: {},
}
forEachKeyValue(this._input, (input, inputId) => {
data.input[inputId] = input.peak()
})
forEachKeyValue(this._output, (output, outputId) => {
data.output[outputId] = output.peak()
})
return data
}
public getInputData(): Dict<any> {
const data: Dict<any> = {}
forEachKeyValue(this._input, (input, inputId) => {
if (!input.empty()) {
const datum = input.peak()
data[inputId] = datum
}
})
return data
}
public getRefInputData(): Dict<U> {
const data: Dict<any> = {}
forEachKeyValue(this._ref_input, (input, inputId) => {
if (!input.empty()) {
let datum = input.peak()
data[inputId] = datum
}
})
return data
}
} | the_stack |
'use strict';
import { Store as RelayModernStore, RecordSource, Environment as RelayModernEnvironment } from '../src';
import { Network as RelayNetwork, Observable as RelayObservable, createOperationDescriptor, createReaderSelector } from 'relay-runtime';
import { createPersistedStorage } from './Utils';
const { generateAndCompile } = require('./TestCompiler');;
jest.useFakeTimers();
const RelayRecordSource = {
create: (data) => new RecordSource({ storage: createPersistedStorage(), initialState: { ...data } }),
};
describe('executeMutation() with global invalidation', () => {
let callbacks;
let commentID;
let CommentFragment;
let CommentQuery;
let complete;
let CreateCommentMutation;
let environment;
let error;
let fetch;
let operation;
let queryOperation;
let source;
let store;
let subject;
let variables;
let queryVariables;
beforeEach(async () => {
jest.resetModules();
commentID = 'comment-id';
({ CreateCommentMutation, CommentFragment, CommentQuery } = generateAndCompile(`
mutation CreateCommentMutation($input: CommentCreateInput!) {
commentCreate(input: $input) {
comment {
id
body {
text
}
}
}
}
fragment CommentFragment on Comment {
id
body {
text
}
}
query CommentQuery($id: ID!) {
node(id: $id) {
id
...CommentFragment
}
}
`));
variables = {
input: {
clientMutationId: '0',
feedbackId: '1',
},
};
queryVariables = {
id: commentID,
};
operation = createOperationDescriptor(CreateCommentMutation, variables);
queryOperation = createOperationDescriptor(CommentQuery, queryVariables);
fetch = jest.fn((_query, _variables, _cacheConfig) =>
RelayObservable.create((sink) => {
subject = sink;
}),
);
source = RelayRecordSource.create({
'client:root': {
__id: 'client:root',
__typename: '__Root',
'node(id:"comment-id")': { __ref: 'comment-id' },
},
});
store = new RelayModernStore(source, { storage: createPersistedStorage(), defaultTTL: -1 });
environment = new RelayModernEnvironment({
network: RelayNetwork.create(fetch),
store,
});
await environment.hydrate();
complete = jest.fn();
error = jest.fn();
callbacks = { complete, error };
});
it('global invalidation is a no-op if called during optimistic update', () => {
const selector = createReaderSelector(CommentFragment, commentID, {}, queryOperation.request);
const snapshot = environment.lookup(selector);
const callback = jest.fn();
environment.subscribe(snapshot, callback);
environment
.executeMutation({
operation,
optimisticUpdater: (_store) => {
// Invalidate store
_store.invalidateStore();
const comment = _store.create(commentID, 'Comment');
comment.setValue(commentID, 'id');
const body = _store.create(commentID + '.text', 'Text');
comment.setLinkedRecord(body, 'body');
body.setValue('Give Relay', 'text');
},
})
.subscribe(callbacks);
// Results of execution are asserted in ExecuteMutation-test.js
// Assert that store invalidation during optimistic update
// was a no-op
expect(environment.check(queryOperation)).toEqual({
status: 'available',
fetchTime: null,
});
});
describe('when store invalidated inside updater after server payload', () => {
it('correctly invalidates the store when query has never been written before', () => {
const selector = createReaderSelector(CommentFragment, commentID, {}, queryOperation.request);
const snapshot = environment.lookup(selector);
const callback = jest.fn();
environment.subscribe(snapshot, callback);
environment
.executeMutation({
operation,
updater: (_store) => {
_store.invalidateStore();
const comment = _store.get(commentID);
if (!comment) {
throw new Error('Expected comment to be in the store');
}
const body = comment.getLinkedRecord('body');
if (!body) {
throw new Error('Expected comment to have a body');
}
const bodyValue: string | null = body.getValue('text');
if (bodyValue == null) {
throw new Error('Expected comment body to have text');
}
body.setValue(bodyValue.toUpperCase(), 'text');
},
})
.subscribe(callbacks);
callback.mockClear();
subject.next({
data: {
commentCreate: {
comment: {
id: commentID,
body: {
text: 'Gave Relay', // server data is lowercase
},
},
},
},
});
subject.complete();
// Results of execution are asserted in ExecuteMutation-test.js
// Assert that store was correctly invalidated
expect(environment.check(queryOperation)).toEqual({ status: 'stale' });
// Assert that operation that was written during the same update as invalidation
// is also stale
expect(environment.check(operation)).toEqual({ status: 'stale' });
});
it('correctly invalidates the store when query was written before invalidation', () => {
// Write operation before running invalidation
environment.retain(queryOperation);
environment.commitPayload(queryOperation, {
node: {
__typename: 'Comment',
id: commentID,
body: {
text: 'Foo',
},
},
});
jest.runOnlyPendingTimers();
// Execute mutation
const selector = createReaderSelector(CommentFragment, commentID, {}, queryOperation.request);
const snapshot = environment.lookup(selector);
const callback = jest.fn();
environment.subscribe(snapshot, callback);
environment
.executeMutation({
operation,
updater: (_store) => {
_store.invalidateStore();
const comment = _store.get(commentID);
if (!comment) {
throw new Error('Expected comment to be in the store');
}
const body = comment.getLinkedRecord('body');
if (!body) {
throw new Error('Expected comment to have a body');
}
const bodyValue: string | null = body.getValue('text');
if (bodyValue == null) {
throw new Error('Expected comment body to have text');
}
body.setValue(bodyValue.toUpperCase(), 'text');
},
})
.subscribe(callbacks);
callback.mockClear();
subject.next({
data: {
commentCreate: {
comment: {
id: commentID,
body: {
text: 'Gave Relay', // server data is lowercase
},
},
},
},
});
subject.complete();
// Results of execution are asserted in ExecuteMutation-test.js
// Assert that store was correctly invalidated
expect(environment.check(queryOperation)).toEqual({ status: 'stale' });
// Assert that operation that was written during the same update as invalidation
// is also stale
expect(environment.check(operation)).toEqual({ status: 'stale' });
});
it('correctly invalidates the store when query is written after invalidation', () => {
// Execute mutation
const selector = createReaderSelector(CommentFragment, commentID, {}, queryOperation.request);
const snapshot = environment.lookup(selector);
const callback = jest.fn();
environment.subscribe(snapshot, callback);
environment
.executeMutation({
operation,
updater: (_store) => {
_store.invalidateStore();
const comment = _store.get(commentID);
if (!comment) {
throw new Error('Expected comment to be in the store');
}
const body = comment.getLinkedRecord('body');
if (!body) {
throw new Error('Expected comment to have a body');
}
const bodyValue: string | null = body.getValue('text');
if (bodyValue == null) {
throw new Error('Expected comment body to have text');
}
body.setValue(bodyValue.toUpperCase(), 'text');
},
})
.subscribe(callbacks);
callback.mockClear();
subject.next({
data: {
commentCreate: {
comment: {
id: commentID,
body: {
text: 'Gave Relay', // server data is lowercase
},
},
},
},
});
subject.complete();
// Results of execution are asserted in ExecuteMutation-test.js
// Assert that query is currently stale
expect(environment.check(queryOperation)).toEqual({ status: 'stale' });
// Assert that operation that was written during the same update as invalidation
// is also stale
expect(environment.check(operation)).toEqual({ status: 'stale' });
// Write operation after running invalidation
environment.retain(queryOperation);
const fetchTime = Date.now();
jest.spyOn(global.Date, 'now').mockImplementation(() => fetchTime);
environment.commitPayload(queryOperation, {
node: {
__typename: 'Comment',
id: commentID,
body: {
text: 'Foo',
},
},
});
jest.runOnlyPendingTimers();
// Assert that query is currently stale
expect(environment.check(queryOperation)).toEqual({
status: 'available',
fetchTime,
});
// Assert that operation that was written during the same update as invalidation
// is still stale
expect(environment.check(operation)).toEqual({ status: 'stale' });
});
});
}); | the_stack |
// IMPORTANT
// This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually.
// In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator
// Generated from: https://storagetransfer.googleapis.com/$discovery/rest?version=v1
/// <reference types="gapi.client" />
declare namespace gapi.client {
/** Load Google Storage Transfer API v1 */
function load(name: "storagetransfer", version: "v1"): PromiseLike<void>;
function load(name: "storagetransfer", version: "v1", callback: () => any): void;
const googleServiceAccounts: storagetransfer.GoogleServiceAccountsResource;
const transferJobs: storagetransfer.TransferJobsResource;
const transferOperations: storagetransfer.TransferOperationsResource;
namespace storagetransfer {
interface AwsAccessKey {
/**
* AWS access key ID.
* Required.
*/
accessKeyId?: string;
/**
* AWS secret access key. This field is not returned in RPC responses.
* Required.
*/
secretAccessKey?: string;
}
interface AwsS3Data {
/**
* AWS access key used to sign the API requests to the AWS S3 bucket.
* Permissions on the bucket must be granted to the access ID of the
* AWS access key.
* Required.
*/
awsAccessKey?: AwsAccessKey;
/**
* S3 Bucket name (see
* [Creating a bucket](http://docs.aws.amazon.com/AmazonS3/latest/dev/create-bucket-get-location-example.html)).
* Required.
*/
bucketName?: string;
}
interface Date {
/**
* Day of month. Must be from 1 to 31 and valid for the year and month, or 0
* if specifying a year/month where the day is not significant.
*/
day?: number;
/** Month of year. Must be from 1 to 12. */
month?: number;
/**
* Year of date. Must be from 1 to 9999, or 0 if specifying a date without
* a year.
*/
year?: number;
}
interface ErrorLogEntry {
/** A list of messages that carry the error details. */
errorDetails?: string[];
/**
* A URL that refers to the target (a data source, a data sink,
* or an object) with which the error is associated.
* Required.
*/
url?: string;
}
interface ErrorSummary {
/** Required. */
errorCode?: string;
/**
* Count of this type of error.
* Required.
*/
errorCount?: string;
/** Error samples. */
errorLogEntries?: ErrorLogEntry[];
}
interface GcsData {
/**
* Google Cloud Storage bucket name (see
* [Bucket Name Requirements](https://cloud.google.com/storage/docs/bucket-naming#requirements)).
* Required.
*/
bucketName?: string;
}
interface GoogleServiceAccount {
/** Required. */
accountEmail?: string;
}
interface HttpData {
/**
* The URL that points to the file that stores the object list entries.
* This file must allow public access. Currently, only URLs with HTTP and
* HTTPS schemes are supported.
* Required.
*/
listUrl?: string;
}
interface ListOperationsResponse {
/** The standard List next-page token. */
nextPageToken?: string;
/** A list of operations that matches the specified filter in the request. */
operations?: Operation[];
}
interface ListTransferJobsResponse {
/** The list next page token. */
nextPageToken?: string;
/** A list of transfer jobs. */
transferJobs?: TransferJob[];
}
interface ObjectConditions {
/**
* `excludePrefixes` must follow the requirements described for
* `includePrefixes`.
*
* The max size of `excludePrefixes` is 1000.
*/
excludePrefixes?: string[];
/**
* If `includePrefixes` is specified, objects that satisfy the object
* conditions must have names that start with one of the `includePrefixes`
* and that do not start with any of the `excludePrefixes`. If `includePrefixes`
* is not specified, all objects except those that have names starting with
* one of the `excludePrefixes` must satisfy the object conditions.
*
* Requirements:
*
* * Each include-prefix and exclude-prefix can contain any sequence of
* Unicode characters, of max length 1024 bytes when UTF8-encoded, and
* must not contain Carriage Return or Line Feed characters. Wildcard
* matching and regular expression matching are not supported.
*
* * Each include-prefix and exclude-prefix must omit the leading slash.
* For example, to include the `requests.gz` object in a transfer from
* `s3://my-aws-bucket/logs/y=2015/requests.gz`, specify the include
* prefix as `logs/y=2015/requests.gz`.
*
* * None of the include-prefix or the exclude-prefix values can be empty,
* if specified.
*
* * Each include-prefix must include a distinct portion of the object
* namespace, i.e., no include-prefix may be a prefix of another
* include-prefix.
*
* * Each exclude-prefix must exclude a distinct portion of the object
* namespace, i.e., no exclude-prefix may be a prefix of another
* exclude-prefix.
*
* * If `includePrefixes` is specified, then each exclude-prefix must start
* with the value of a path explicitly included by `includePrefixes`.
*
* The max size of `includePrefixes` is 1000.
*/
includePrefixes?: string[];
/**
* `maxTimeElapsedSinceLastModification` is the complement to
* `minTimeElapsedSinceLastModification`.
*/
maxTimeElapsedSinceLastModification?: string;
/**
* If unspecified, `minTimeElapsedSinceLastModification` takes a zero value
* and `maxTimeElapsedSinceLastModification` takes the maximum possible
* value of Duration. Objects that satisfy the object conditions
* must either have a `lastModificationTime` greater or equal to
* `NOW` - `maxTimeElapsedSinceLastModification` and less than
* `NOW` - `minTimeElapsedSinceLastModification`, or not have a
* `lastModificationTime`.
*/
minTimeElapsedSinceLastModification?: string;
}
interface Operation {
/**
* If the value is `false`, it means the operation is still in progress.
* If `true`, the operation is completed, and either `error` or `response` is
* available.
*/
done?: boolean;
/** The error result of the operation in case of failure or cancellation. */
error?: Status;
/** Represents the transfer operation object. */
metadata?: Record<string, any>;
/**
* The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name`
* should have the format of `transferOperations/some/unique/name`.
*/
name?: string;
/**
* The normal response of the operation in case of success. If the original
* method returns no data on success, such as `Delete`, the response is
* `google.protobuf.Empty`. If the original method is standard
* `Get`/`Create`/`Update`, the response should be the resource. For other
* methods, the response should have the type `XxxResponse`, where `Xxx`
* is the original method name. For example, if the original method name
* is `TakeSnapshot()`, the inferred response type is
* `TakeSnapshotResponse`.
*/
response?: Record<string, any>;
}
interface Schedule {
/**
* The last day the recurring transfer will be run. If `scheduleEndDate`
* is the same as `scheduleStartDate`, the transfer will be executed only
* once.
*/
scheduleEndDate?: Date;
/**
* The first day the recurring transfer is scheduled to run. If
* `scheduleStartDate` is in the past, the transfer will run for the first
* time on the following day.
* Required.
*/
scheduleStartDate?: Date;
/**
* The time in UTC at which the transfer will be scheduled to start in a day.
* Transfers may start later than this time. If not specified, recurring and
* one-time transfers that are scheduled to run today will run immediately;
* recurring transfers that are scheduled to run on a future date will start
* at approximately midnight UTC on that date. Note that when configuring a
* transfer with the Cloud Platform Console, the transfer's start time in a
* day is specified in your local timezone.
*/
startTimeOfDay?: TimeOfDay;
}
interface Status {
/** The status code, which should be an enum value of google.rpc.Code. */
code?: number;
/**
* A list of messages that carry the error details. There is a common set of
* message types for APIs to use.
*/
details?: Array<Record<string, any>>;
/**
* A developer-facing error message, which should be in English. Any
* user-facing error message should be localized and sent in the
* google.rpc.Status.details field, or localized by the client.
*/
message?: string;
}
interface TimeOfDay {
/**
* Hours of day in 24 hour format. Should be from 0 to 23. An API may choose
* to allow the value "24:00:00" for scenarios like business closing time.
*/
hours?: number;
/** Minutes of hour of day. Must be from 0 to 59. */
minutes?: number;
/** Fractions of seconds in nanoseconds. Must be from 0 to 999,999,999. */
nanos?: number;
/**
* Seconds of minutes of the time. Must normally be from 0 to 59. An API may
* allow the value 60 if it allows leap-seconds.
*/
seconds?: number;
}
interface TransferCounters {
/** Bytes that are copied to the data sink. */
bytesCopiedToSink?: string;
/** Bytes that are deleted from the data sink. */
bytesDeletedFromSink?: string;
/** Bytes that are deleted from the data source. */
bytesDeletedFromSource?: string;
/** Bytes that failed to be deleted from the data sink. */
bytesFailedToDeleteFromSink?: string;
/**
* Bytes found in the data source that are scheduled to be transferred,
* which will be copied, excluded based on conditions, or skipped due to
* failures.
*/
bytesFoundFromSource?: string;
/** Bytes found only in the data sink that are scheduled to be deleted. */
bytesFoundOnlyFromSink?: string;
/** Bytes in the data source that failed during the transfer. */
bytesFromSourceFailed?: string;
/**
* Bytes in the data source that are not transferred because they already
* exist in the data sink.
*/
bytesFromSourceSkippedBySync?: string;
/** Objects that are copied to the data sink. */
objectsCopiedToSink?: string;
/** Objects that are deleted from the data sink. */
objectsDeletedFromSink?: string;
/** Objects that are deleted from the data source. */
objectsDeletedFromSource?: string;
/** Objects that failed to be deleted from the data sink. */
objectsFailedToDeleteFromSink?: string;
/**
* Objects found in the data source that are scheduled to be transferred,
* which will be copied, excluded based on conditions, or skipped due to
* failures.
*/
objectsFoundFromSource?: string;
/** Objects found only in the data sink that are scheduled to be deleted. */
objectsFoundOnlyFromSink?: string;
/** Objects in the data source that failed during the transfer. */
objectsFromSourceFailed?: string;
/**
* Objects in the data source that are not transferred because they already
* exist in the data sink.
*/
objectsFromSourceSkippedBySync?: string;
}
interface TransferJob {
/** This field cannot be changed by user requests. */
creationTime?: string;
/** This field cannot be changed by user requests. */
deletionTime?: string;
/**
* A description provided by the user for the job. Its max length is 1024
* bytes when Unicode-encoded.
*/
description?: string;
/** This field cannot be changed by user requests. */
lastModificationTime?: string;
/**
* A globally unique name assigned by Storage Transfer Service when the
* job is created. This field should be left empty in requests to create a new
* transfer job; otherwise, the requests result in an `INVALID_ARGUMENT`
* error.
*/
name?: string;
/** The ID of the Google Cloud Platform Console project that owns the job. */
projectId?: string;
/** Schedule specification. */
schedule?: Schedule;
/**
* Status of the job. This value MUST be specified for
* `CreateTransferJobRequests`.
*
* NOTE: The effect of the new job status takes place during a subsequent job
* run. For example, if you change the job status from `ENABLED` to
* `DISABLED`, and an operation spawned by the transfer is running, the status
* change would not affect the current operation.
*/
status?: string;
/** Transfer specification. */
transferSpec?: TransferSpec;
}
interface TransferOperation {
/** Information about the progress of the transfer operation. */
counters?: TransferCounters;
/** End time of this transfer execution. */
endTime?: string;
/** Summarizes errors encountered with sample error log entries. */
errorBreakdowns?: ErrorSummary[];
/** A globally unique ID assigned by the system. */
name?: string;
/**
* The ID of the Google Cloud Platform Console project that owns the operation.
* Required.
*/
projectId?: string;
/** Start time of this transfer execution. */
startTime?: string;
/** Status of the transfer operation. */
status?: string;
/** The name of the transfer job that triggers this transfer operation. */
transferJobName?: string;
/**
* Transfer specification.
* Required.
*/
transferSpec?: TransferSpec;
}
interface TransferOptions {
/**
* Whether objects should be deleted from the source after they are
* transferred to the sink. Note that this option and
* `deleteObjectsUniqueInSink` are mutually exclusive.
*/
deleteObjectsFromSourceAfterTransfer?: boolean;
/**
* Whether objects that exist only in the sink should be deleted. Note that
* this option and `deleteObjectsFromSourceAfterTransfer` are mutually
* exclusive.
*/
deleteObjectsUniqueInSink?: boolean;
/** Whether overwriting objects that already exist in the sink is allowed. */
overwriteObjectsAlreadyExistingInSink?: boolean;
}
interface TransferSpec {
/** An AWS S3 data source. */
awsS3DataSource?: AwsS3Data;
/** A Google Cloud Storage data sink. */
gcsDataSink?: GcsData;
/** A Google Cloud Storage data source. */
gcsDataSource?: GcsData;
/** An HTTP URL data source. */
httpDataSource?: HttpData;
/**
* Only objects that satisfy these object conditions are included in the set
* of data source and data sink objects. Object conditions based on
* objects' `lastModificationTime` do not exclude objects in a data sink.
*/
objectConditions?: ObjectConditions;
/**
* If the option `deleteObjectsUniqueInSink` is `true`, object conditions
* based on objects' `lastModificationTime` are ignored and do not exclude
* objects in a data source or a data sink.
*/
transferOptions?: TransferOptions;
}
interface UpdateTransferJobRequest {
/**
* The ID of the Google Cloud Platform Console project that owns the job.
* Required.
*/
projectId?: string;
/**
* The job to update. `transferJob` is expected to specify only three fields:
* `description`, `transferSpec`, and `status`. An UpdateTransferJobRequest
* that specifies other fields will be rejected with an error
* `INVALID_ARGUMENT`.
* Required.
*/
transferJob?: TransferJob;
/**
* The field mask of the fields in `transferJob` that are to be updated in
* this request. Fields in `transferJob` that can be updated are:
* `description`, `transferSpec`, and `status`. To update the `transferSpec`
* of the job, a complete transfer specification has to be provided. An
* incomplete specification which misses any required fields will be rejected
* with the error `INVALID_ARGUMENT`.
*/
updateTransferJobFieldMask?: string;
}
interface GoogleServiceAccountsResource {
/**
* Returns the Google service account that is used by Storage Transfer
* Service to access buckets in the project where transfers
* run or in other projects. Each Google service account is associated
* with one Google Cloud Platform Console project. Users
* should add this service account to the Google Cloud Storage bucket
* ACLs to grant access to Storage Transfer Service. This service
* account is created and owned by Storage Transfer Service and can
* only be used by Storage Transfer Service.
*/
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* The ID of the Google Cloud Platform Console project that the Google service
* account is associated with.
* Required.
*/
projectId: string;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<GoogleServiceAccount>;
}
interface TransferJobsResource {
/** Creates a transfer job that runs periodically. */
create(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<TransferJob>;
/** Gets a transfer job. */
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/**
* The job to get.
* Required.
*/
jobName: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* The ID of the Google Cloud Platform Console project that owns the job.
* Required.
*/
projectId?: string;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<TransferJob>;
/** Lists transfer jobs. */
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/**
* A list of query parameters specified as JSON text in the form of
* {"project_id":"my_project_id",
* "job_names":["jobid1","jobid2",...],
* "job_statuses":["status1","status2",...]}.
* Since `job_names` and `job_statuses` support multiple values, their values
* must be specified with array notation. `project_id` is required. `job_names`
* and `job_statuses` are optional. The valid values for `job_statuses` are
* case-insensitive: `ENABLED`, `DISABLED`, and `DELETED`.
*/
filter?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The list page size. The max allowed value is 256. */
pageSize?: number;
/** The list page token. */
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListTransferJobsResponse>;
/**
* Updates a transfer job. Updating a job's transfer spec does not affect
* transfer operations that are running already. Updating the scheduling
* of a job is not allowed.
*/
patch(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/**
* The name of job to update.
* Required.
*/
jobName: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<TransferJob>;
}
interface TransferOperationsResource {
/** Cancels a transfer. Use the get method to check whether the cancellation succeeded or whether the operation completed despite cancellation. */
cancel(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the operation resource to be cancelled. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
/** This method is not supported and the server returns `UNIMPLEMENTED`. */
delete(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the operation resource to be deleted. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
/**
* Gets the latest state of a long-running operation. Clients can use this
* method to poll the operation result at intervals as recommended by the API
* service.
*/
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the operation resource. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Operation>;
/**
* Lists operations that match the specified filter in the request. If the
* server doesn't support this method, it returns `UNIMPLEMENTED`.
*
* NOTE: the `name` binding allows API services to override the binding
* to use different resource name schemes, such as `users/*/operations`. To
* override the binding, API services can add a binding such as
* `"/v1/{name=users/*}/operations"` to their service configuration.
* For backwards compatibility, the default name includes the operations
* collection id, however overriding users must ensure the name binding
* is the parent resource, without the operations collection id.
*/
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/**
* A list of query parameters specified as JSON text in the form of {\"project_id\" : \"my_project_id\", \"job_names\" : [\"jobid1\", \"jobid2\",...],
* \"operation_names\" : [\"opid1\", \"opid2\",...], \"transfer_statuses\":[\"status1\", \"status2\",...]}. Since `job_names`, `operation_names`, and
* `transfer_statuses` support multiple values, they must be specified with array notation. `job_names`, `operation_names`, and `transfer_statuses` are
* optional.
*/
filter?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The value `transferOperations`. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The list page size. The max allowed value is 256. */
pageSize?: number;
/** The list page token. */
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListOperationsResponse>;
/** Pauses a transfer operation. */
pause(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/**
* The name of the transfer operation.
* Required.
*/
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
/** Resumes a transfer operation that is paused. */
resume(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/**
* The name of the transfer operation.
* Required.
*/
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
}
}
} | the_stack |
import {ObjectFormat, FieldType, ConceptType} from '@google/dscc';
/**
* This file provides the mock "data" received
* by your visualization code when you develop
* locally.
*
*/
export const message: ObjectFormat = {
tables: {
DEFAULT: [
{
dimID: ['20160228'],
metricID: [5.497282126241078],
},
{
dimID: ['20160227'],
metricID: [1.7849991884376002],
},
{
dimID: ['20160226'],
metricID: [3.6951131605214327],
},
{
dimID: ['20160225'],
metricID: [4.425749177168392],
},
{
dimID: ['20160224'],
metricID: [6.02078932905799],
},
{
dimID: ['20160223'],
metricID: [2.159520908381245],
},
{
dimID: ['20160222'],
metricID: [1.4574190317115754],
},
{
dimID: ['20160221'],
metricID: [4.993713844467656],
},
{
dimID: ['20160220'],
metricID: [5.811167482902135],
},
{
dimID: ['20160219'],
metricID: [5.466459959022769],
},
{
dimID: ['20160218'],
metricID: [1.5217095262576177],
},
{
dimID: ['20160217'],
metricID: [2.7248381125378054],
},
{
dimID: ['20160216'],
metricID: [3.2216148107443874],
},
{
dimID: ['20160215'],
metricID: [2.802966655574305],
},
{
dimID: ['20160214'],
metricID: [2.8325728966815626],
},
{
dimID: ['20160213'],
metricID: [4.78738448961993],
},
{
dimID: ['20160212'],
metricID: [3.733526048977902],
},
{
dimID: ['20160211'],
metricID: [3.3787552698419026],
},
{
dimID: ['20160210'],
metricID: [4.025778778051834],
},
{
dimID: ['20160209'],
metricID: [5.35835164970315],
},
{
dimID: ['20160208'],
metricID: [2.963131601596341],
},
{
dimID: ['20160207'],
metricID: [4.947689713018692],
},
{
dimID: ['20160206'],
metricID: [1.8820670314435788],
},
{
dimID: ['20160205'],
metricID: [4.87865547464154],
},
{
dimID: ['20160204'],
metricID: [3.4008552077242595],
},
{
dimID: ['20160203'],
metricID: [5.527218073402578],
},
{
dimID: ['20160202'],
metricID: [3.74802231619604],
},
{
dimID: ['20160201'],
metricID: [0.32142154440233073],
},
],
},
fields: {
dimID: [
{
id: 'qt_3zx5rwt08b',
name: '1 Month Times',
type: FieldType.YEAR_MONTH_DAY,
concept: ConceptType.DIMENSION,
},
],
metricID: [
{
id: 'qt_0grczm838b',
name: 'Really small numbers',
type: FieldType.NUMBER,
concept: ConceptType.METRIC,
},
],
},
style: {
fillRadar: {
value: true,
defaultValue: false,
},
fillOpacity: {
value: 0.5,
defaultValue: 0.2,
},
showMarkers: {
value: true,
defaultValue: true,
},
markerType: {
value: 'default',
defaultValue: 'default',
},
fillColor1: {
value: {
color: '#CDDC39',
opacity: 1,
},
defaultValue: {
color: '#008FFB',
},
},
fillColor2: {
value: {
color: '#0EE396',
},
defaultValue: {
color: '#0EE396',
},
},
fillColor3: {
value: {
color: '#FEB019',
},
defaultValue: {
color: '#FEB019',
},
},
fillColor4: {
value: {
color: '#FF4560',
},
defaultValue: {
color: '#FF4560',
},
},
fillColor5: {
value: {
color: '#775DD0',
},
defaultValue: {
color: '#775DD0',
},
},
plotColor1: {
value: {
color: 'green',
},
defaultValue: {
color: '#FFFFFF',
},
},
plotColor2: {
value: {
color: '#FFFFFF',
opacity: 1,
},
defaultValue: {
color: '#FFFFFF',
},
},
enableXAxis: {
value: true,
defaultValue: true,
},
enableYAxis: {
value: true,
defaultValue: true,
},
axisFontColor: {
value: {
color: 'red',
opacity: 1,
},
defaultValue: {
color: '#0000ff',
},
},
axisFontSize: {
value: 11,
defaultValue: 10,
},
axisFontFamily: {
value: 'Arial',
defaultValue: 'auto',
},
enableLegend:{
value:true,
defaultValue:true
},
legendPosition:{
value:"bottom",
defaultValue:"bottom"
}
},
theme: {
themeFillColor: {
color: '#ffffff',
themeRef: {
index: 0,
},
},
themeFontColor: {
color: '#000000',
themeRef: {
index: 1,
},
},
themeFontFamily: 'Roboto',
themeAccentFillColor: {
color: '#e0e0e0',
themeRef: {
index: 2,
},
},
themeAccentFontColor: {
color: '#000000',
themeRef: {
index: 3,
},
},
themeAccentFontFamily: 'Roboto',
themeSeriesColor: [
{
color: '#0072f0',
seriesRef: {
index: 0,
},
themeRef: {
index: 4,
},
},
{
color: '#00b6cb',
seriesRef: {
index: 1,
},
themeRef: {
index: 5,
},
},
{
color: '#f10096',
seriesRef: {
index: 2,
},
themeRef: {
index: 6,
},
},
{
color: '#f66d00',
seriesRef: {
index: 3,
},
themeRef: {
index: 7,
},
},
{
color: '#ffa800',
seriesRef: {
index: 4,
},
themeRef: {
index: 8,
},
},
{
color: '#7cb342',
seriesRef: {
index: 5,
},
themeRef: {
index: 9,
},
},
{
color: '#5e35b1',
seriesRef: {
index: 6,
},
},
{
color: '#03a9f4',
seriesRef: {
index: 7,
},
},
{
color: '#ec407a',
seriesRef: {
index: 8,
},
},
{
color: '#ff7043',
seriesRef: {
index: 9,
},
},
{
color: '#737373',
seriesRef: {
index: 10,
},
},
{
color: '#f15a60',
seriesRef: {
index: 11,
},
},
{
color: '#7ac36a',
seriesRef: {
index: 12,
},
},
{
color: '#5a9bd4',
seriesRef: {
index: 13,
},
},
{
color: '#faa75a',
seriesRef: {
index: 14,
},
},
{
color: '#9e67ab',
seriesRef: {
index: 15,
},
},
{
color: '#ce7058',
seriesRef: {
index: 16,
},
},
{
color: '#d77fb3',
seriesRef: {
index: 17,
},
},
{
color: '#81d4fa',
seriesRef: {
index: 18,
},
},
{
color: '#f48fb1',
seriesRef: {
index: 19,
},
},
],
themeIncreaseColor: {
color: '#388e3c',
},
themeDecreaseColor: {
color: '#f44336',
},
themeGridColor: {
color: '#d1d1d1',
},
},
interactions: {},
};
export const message2: ObjectFormat = {
tables: {
DEFAULT: [
{
dimID: ['1'],
metricID: [2, 3],
},
{
dimID: ['2'],
metricID: [3, 4],
},
{
dimID: ['3'],
metricID: [4, 5],
},
{
dimID: ['4'],
metricID: [5, 6],
},
{
dimID: ['5'],
metricID: [6, 7],
},
],
},
fields: {
dimID: [
{
id: 'qt_3zx5rwt08b',
name: '1 Month Times',
type: FieldType.YEAR_MONTH_DAY,
concept: ConceptType.DIMENSION,
},
],
metricID: [
{
id: 'qt_0grczm838b',
name: 'Really small numbers',
type: FieldType.NUMBER,
concept: ConceptType.METRIC,
},
{
id: 'qt_0grczm838a',
name: 'Kind of small numbers',
type: FieldType.NUMBER,
concept: ConceptType.METRIC,
},
],
},
style: {
fillRadar: {
value: true,
defaultValue: false,
},
fillOpacity: {
value: 0.5,
defaultValue: 0.2,
},
showMarkers: {
value: true,
defaultValue: true,
},
markerType: {
value: 'default',
defaultValue: 'default',
},
fillColor1: {
value: {
color: '#CDDC39',
opacity: 1,
},
defaultValue: {
color: '#008FFB',
},
},
fillColor2: {
value: {
color: '#0EE396',
},
defaultValue: {
color: '#0EE396',
},
},
fillColor3: {
value: {
color: '#FEB019',
},
defaultValue: {
color: '#FEB019',
},
},
fillColor4: {
value: {
color: '#FF4560',
},
defaultValue: {
color: '#FF4560',
},
},
fillColor5: {
value: {
color: '#775DD0',
},
defaultValue: {
color: '#775DD0',
},
},
plotColor1: {
value: {
color: 'green',
},
defaultValue: {
color: '#FFFFFF',
},
},
plotColor2: {
value: {
color: '#FFFFFF',
opacity: 1,
},
defaultValue: {
color: '#FFFFFF',
},
},
enableXAxis: {
value: true,
defaultValue: true,
},
enableYAxis: {
value: true,
defaultValue: true,
},
axisFontColor: {
value: {
color: 'red',
opacity: 1,
},
defaultValue: {
color: '#0000ff',
},
},
axisFontSize: {
value: 11,
defaultValue: 10,
},
axisFontFamily: {
value: 'Arial',
defaultValue: 'auto',
},
},
theme: {
themeFillColor: {
color: '#ffffff',
themeRef: {
index: 0,
},
},
themeFontColor: {
color: '#000000',
themeRef: {
index: 1,
},
},
themeFontFamily: 'Roboto',
themeAccentFillColor: {
color: '#e0e0e0',
themeRef: {
index: 2,
},
},
themeAccentFontColor: {
color: '#000000',
themeRef: {
index: 3,
},
},
themeAccentFontFamily: 'Roboto',
themeSeriesColor: [
{
color: '#0072f0',
seriesRef: {
index: 0,
},
themeRef: {
index: 4,
},
},
{
color: '#00b6cb',
seriesRef: {
index: 1,
},
themeRef: {
index: 5,
},
},
{
color: '#f10096',
seriesRef: {
index: 2,
},
themeRef: {
index: 6,
},
},
{
color: '#f66d00',
seriesRef: {
index: 3,
},
themeRef: {
index: 7,
},
},
{
color: '#ffa800',
seriesRef: {
index: 4,
},
themeRef: {
index: 8,
},
},
{
color: '#7cb342',
seriesRef: {
index: 5,
},
themeRef: {
index: 9,
},
},
{
color: '#5e35b1',
seriesRef: {
index: 6,
},
},
{
color: '#03a9f4',
seriesRef: {
index: 7,
},
},
{
color: '#ec407a',
seriesRef: {
index: 8,
},
},
{
color: '#ff7043',
seriesRef: {
index: 9,
},
},
{
color: '#737373',
seriesRef: {
index: 10,
},
},
{
color: '#f15a60',
seriesRef: {
index: 11,
},
},
{
color: '#7ac36a',
seriesRef: {
index: 12,
},
},
{
color: '#5a9bd4',
seriesRef: {
index: 13,
},
},
{
color: '#faa75a',
seriesRef: {
index: 14,
},
},
{
color: '#9e67ab',
seriesRef: {
index: 15,
},
},
{
color: '#ce7058',
seriesRef: {
index: 16,
},
},
{
color: '#d77fb3',
seriesRef: {
index: 17,
},
},
{
color: '#81d4fa',
seriesRef: {
index: 18,
},
},
{
color: '#f48fb1',
seriesRef: {
index: 19,
},
},
],
themeIncreaseColor: {
color: '#388e3c',
},
themeDecreaseColor: {
color: '#f44336',
},
themeGridColor: {
color: '#d1d1d1',
},
},
interactions: {},
}; | the_stack |
import * as path from "path";
import { DataType } from "./dataType";
import { Scope, unscopedPrecedence } from "./scope";
import { Location, TextDocument, Range, Uri, Position, WorkspaceConfiguration, workspace } from "vscode";
import { getCfScriptRanges, isCfcFile, getClosingPosition } from "../utils/contextUtil";
import { Component, getApplicationUri, getServerUri, COMPONENT_EXT } from "./component";
import { UserFunction, UserFunctionSignature, Argument, getLocalVariables, UserFunctionVariable, parseScriptFunctionArgs, functionValuePattern, isUserFunctionVariable } from "./userFunction";
import * as cachedEntities from "../features/cachedEntities";
import { equalsIgnoreCase } from "../utils/textUtil";
import { MyMap, MySet } from "../utils/collections";
import { parseAttributes, Attributes } from "./attribute";
import { getTagPattern, OutputVariableTags, VariableAttribute, parseTags, Tag, getCfStartTagPattern, getCfScriptTagPatternIgnoreBody, parseStartTags, StartTag } from "./tag";
import { Properties, Property } from "./property";
import { getSelectColumnsFromQueryText, Query, QueryColumns, queryValuePattern } from "./query";
import { CFMLEngineName, CFMLEngine } from "../utils/cfdocs/cfmlEngine";
import { DocumentStateContext, DocumentPositionStateContext } from "../utils/documentUtil";
import { getScriptFunctionArgRanges } from "./function";
import { constructParameterLabel } from "./parameter";
// FIXME: Erroneously matches implicit struct key assignments using = since '{' can also open a code block. Also matches within string or comment.
const cfscriptVariableAssignmentPattern = /(((?:^|[;{}]|\bfor\s*\(|\bcase\s+.+?:|\bdefault\s*:|\bfinal)\s*(\bvar\s+)?(?:(application|arguments|attributes|caller|cffile|cgi|client|cookie|flash|form|local|request|server|session|static|this|thistag|thread|url|variables)\s*(?:\.\s*|\[\s*(['"])))?)([a-zA-Z_$][$\w]*)\5\s*\]?(?:\s*(?:\.\s*|\[\s*(['"])?)[$\w]+\7(?:\s*\])?)*\s*=\s*)([^=][^;]*)/gi;
const forInVariableAssignmentPattern = /((?:\bfor\s*\()\s*(\bvar\s+)?(?:(application|arguments|attributes|caller|cffile|cgi|client|cookie|flash|form|local|request|server|session|static|this|thistag|thread|url|variables)\s*(?:\.\s*|\[\s*(['"])))?)([a-zA-Z_$][$\w]*)\4\s*\]?(?:\s*(?:\.\s*|\[\s*(['"])?)[$\w]+\6(?:\s*\])?)*(?:\s+in\s+)/gi;
const tagVariableAssignmentPattern = /((<cfset\s+(?:final\s+)?(var\s+)?(?:(application|arguments|attributes|caller|cffile|cgi|client|cookie|flash|form|local|request|server|session|static|this|thistag|thread|url|variables)\s*(?:\.\s*|\[\s*(['"])))?)([a-zA-Z_$][$\w]*)\5\s*\]?(?:\s*(?:\.\s*|\[\s*(['"])?)[$\w]+\7(?:\s*\])?)*\s*=\s*)([^=][^>]*)/gi;
const tagParamPattern = getTagPattern("cfparam");
const scriptParamPattern = /\b(cfparam\s*\(\s*|param\s+)([^;]*);/gi;
// Does not match when a function is part of the expression
const variableExpressionPattern = /\b((application|arguments|attributes|caller|cffile|cgi|client|cookie|flash|form|local|request|server|session|static|this|thistag|thread|url|variables)\s*(?:\.\s*|\[\s*(['"])))?([a-zA-Z_$][$\w]*)\3\s*\]?(?:\s*(?:\.\s*|\[\s*(['"])?)[$\w]+\5(?:\s*\])?)*/i;
const variableExpressionPrefixPattern = /\b((application|arguments|attributes|caller|cffile|cgi|client|cookie|flash|form|local|request|server|session|static|this|thistag|thread|url|variables)\s*(?:\.\s*|\[\s*(['"])))?([a-zA-Z_$][$\w]*)\3\s*\]?(?:\s*(?:\.\s*|\[\s*(['"])?)[$\w]+\5(?:\s*\])?)*\s*(?:\.\s*|\[\s*['"]?)$/i;
// TODO: Import outputVariableTags from tag.ts when bug is found/resolved
// const outputVariableTags: OutputVariableTags = getOutputVariableTags();
const outputVariableTags: OutputVariableTags = {
"cfchart": [
{
attributeName: "name",
dataType: DataType.Binary
}
],
"cfcollection": [
{
attributeName: "name",
dataType: DataType.Query
}
],
"cfdbinfo": [
{
attributeName: "name",
dataType: DataType.Any
}
],
"cfdirectory": [
{
attributeName: "name",
dataType: DataType.Query
}
],
"cfdocument": [
{
attributeName: "name",
dataType: DataType.Binary
}
],
"cfexecute": [
{
attributeName: "variable",
dataType: DataType.String
}
],
"cffeed": [
{
attributeName: "name",
dataType: DataType.Struct
},
{
attributeName: "query",
dataType: DataType.Query
}
],
"cffile": [
{
attributeName: "result",
dataType: DataType.Struct
},
{
attributeName: "variable",
dataType: DataType.Any
}
],
"cfftp": [
{
attributeName: "name",
dataType: DataType.Query
},
{
attributeName: "result",
dataType: DataType.Struct
}
],
"cfhtmltopdf": [
{
attributeName: "name",
dataType: DataType.Binary
}
],
"cfhttp": [
{
attributeName: "name",
dataType: DataType.Query
},
{
attributeName: "result",
dataType: DataType.Struct
}
],
"cfimage": [
{
attributeName: "name",
dataType: DataType.Any
},
{
attributeName: "structName",
dataType: DataType.Struct
}
],
"cfimap": [
{
attributeName: "name",
dataType: DataType.Query
}
],
// cfinvoke dataType could be taken from function return type
"cfinvoke": [
{
attributeName: "returnvariable",
dataType: DataType.Any
}
],
"cfldap": [
{
attributeName: "name",
dataType: DataType.Query
}
],
// cfloop dataTypes are conditional
"cfloop": [
{
attributeName: "index",
dataType: DataType.Any
},
{
attributeName: "item",
dataType: DataType.Any
}
],
"cfntauthenticate": [
{
attributeName: "result",
dataType: DataType.Any
},
],
// cfobject excluded and handled elsewhere
// cfparam excluded and handled elsewhere
"cfpdf": [
{
attributeName: "name",
dataType: DataType.Binary
},
],
"cfpop": [
{
attributeName: "name",
dataType: DataType.Query
},
],
"cfprocparam": [
{
attributeName: "variable",
dataType: DataType.Any
},
],
"cfprocresult": [
{
attributeName: "name",
dataType: DataType.Query
},
],
// cfproperty excluded and handled elsewhere
"cfquery": [
{
attributeName: "name",
dataType: DataType.Query
},
{
attributeName: "result",
dataType: DataType.Struct
}
],
"cfregistry": [
{
attributeName: "name",
dataType: DataType.Query
},
{
attributeName: "variable",
dataType: DataType.Any
}
],
"cfreport": [
{
attributeName: "name",
dataType: DataType.Any
},
],
"cfsavecontent": [
{
attributeName: "variable",
dataType: DataType.String
},
],
"cfsearch": [
{
attributeName: "name",
dataType: DataType.Query
},
],
"cfsharepoint": [
{
attributeName: "name",
dataType: DataType.Any
},
],
"cfspreadsheet": [
{
attributeName: "name",
dataType: DataType.Any
},
{
attributeName: "query",
dataType: DataType.Query
}
],
"cfstoredproc": [
{
attributeName: "result",
dataType: DataType.Struct
},
],
"cfwddx": [
{
attributeName: "output",
dataType: DataType.Any
},
],
"cfxml": [
{
attributeName: "variable",
dataType: DataType.XML
},
],
"cfzip": [
{
attributeName: "name",
dataType: DataType.Query
},
{
attributeName: "variable",
dataType: DataType.Any
},
],
};
/**
* Checks whether the given identifier uses the constant naming convention
* @param ident The identifier to test
*/
export function usesConstantConvention(ident: string): boolean {
return ident === ident.toUpperCase();
}
/**
* Returns a regular expression that matches when prefixed by a specified unscoped variable accessing a property
* @param variableName The name of a variable
*/
export function getVariablePrefixPattern(variableName: string) {
let pattern: string = `(?:^|[^.\\s])\\s*(?:\\b${variableName}\\s*(?:\\.\\s*|\\[\\s*['"]))$`;
return new RegExp(pattern, "i");
}
/**
* Returns a regular expression that matches a variable (or similar) and captures its parts
* 1. variable prefix
* 2. variable scope
* 3. quote
* 4. variable name
*/
export function getVariableExpressionPrefixPattern() {
return variableExpressionPrefixPattern;
}
/**
* Returns all of the variables declared
* @param documentStateContext Contextual information for a given document's state
* @param isScript Whether this document or range is defined entirely in CFScript
* @param docRange Range within which to check
*/
export function parseVariableAssignments(documentStateContext: DocumentStateContext, isScript: boolean, docRange?: Range): Variable[] {
let variables: Variable[] = [];
const document: TextDocument = documentStateContext.document;
const documentUri: Uri = document.uri;
let textOffset: number = 0;
let documentText: string = documentStateContext.sanitizedDocumentText;
if (docRange && document.validateRange(docRange)) {
textOffset = document.offsetAt(docRange.start);
documentText = documentText.slice(textOffset, document.offsetAt(docRange.end));
}
const cfmlEngineSettings: WorkspaceConfiguration = workspace.getConfiguration("cfml.engine");
const userEngineName: CFMLEngineName = CFMLEngineName.valueOf(cfmlEngineSettings.get<string>("name"));
const userEngine: CFMLEngine = new CFMLEngine(userEngineName, cfmlEngineSettings.get<string>("version"));
// Add function arguments
if (isCfcFile(document)) {
const comp: Component = cachedEntities.getComponent(document.uri);
if (comp) {
comp.functions.forEach((func: UserFunction) => {
if (!func.isImplicit && (!docRange || (func.bodyRange && func.bodyRange.contains(docRange)))) {
if (func.signatures) {
func.signatures.forEach((signature: UserFunctionSignature) => {
signature.parameters.forEach((param: Argument) => {
const argName: string = param.name;
if (getMatchingVariables(variables, argName, Scope.Arguments).length === 0) {
variables.push({
identifier: argName,
dataType: param.dataType,
scope: Scope.Arguments,
final: false,
description: param.description,
declarationLocation: new Location(
document.uri,
param.nameRange
),
initialValue: param.default
});
}
});
});
}
}
});
}
}
// params
let paramMatch: RegExpExecArray = null;
const paramPattern: RegExp = isScript ? scriptParamPattern : tagParamPattern;
while (paramMatch = paramPattern.exec(documentText)) {
const paramPrefix: string = paramMatch[1];
const paramAttr: string = paramMatch[2];
const paramAttributeRange = new Range(
document.positionAt(textOffset + paramMatch.index + paramPrefix.length),
document.positionAt(textOffset + paramMatch.index + paramPrefix.length + paramAttr.length)
);
const parsedAttr: Attributes = parseAttributes(document, paramAttributeRange);
if (!parsedAttr.has("name") || !parsedAttr.get("name").value) {
continue;
}
let paramType: DataType = DataType.Any;
let paramTypeComponentUri: Uri = undefined;
if (parsedAttr.has("type") && !!parsedAttr.get("type").value) {
paramType = DataType.paramTypeToDataType(parsedAttr.get("type").value);
} else if (parsedAttr.has("default") && parsedAttr.get("default").value !== undefined) {
const inferredType: [DataType, Uri] = DataType.inferDataTypeFromValue(parsedAttr.get("default").value, documentUri);
paramType = inferredType[0];
paramTypeComponentUri = inferredType[1];
}
const paramName = parsedAttr.get("name").value;
const paramNameMatch = variableExpressionPattern.exec(paramName);
if (!paramNameMatch) {
continue;
}
const varNamePrefix: string = paramNameMatch[1];
const varNamePrefixLen: number = varNamePrefix ? varNamePrefix.length : 0;
const scope: string = paramNameMatch[2];
const varName: string = paramNameMatch[4];
let scopeVal: Scope = Scope.Unknown;
if (scope) {
scopeVal = Scope.valueOf(scope);
}
const varRangeStart = parsedAttr.get("name").valueRange.start.translate(0, varNamePrefixLen);
const varRange = new Range(
varRangeStart,
varRangeStart.translate(0, varName.length)
);
const matchingVars = getMatchingVariables(variables, varName, scopeVal);
if (matchingVars.length > 0) {
if (matchingVars.length > 1 || matchingVars[0].declarationLocation.range.start.isBefore(varRange.start)) {
continue;
} else {
// Remove entry
variables = variables.filter((variable: Variable) => {
return variable !== matchingVars[0];
});
}
}
const initialValue: string = parsedAttr.has("default") ? parsedAttr.get("default").value : undefined;
variables.push({
identifier: varName,
dataType: paramType,
dataTypeComponentUri: paramTypeComponentUri,
scope: scopeVal,
final: false,
declarationLocation: new Location(
document.uri,
varRange
),
initialValue: initialValue
});
}
// variable assignments
let variableMatch: RegExpExecArray = null;
const variableAssignmentPattern: RegExp = isScript ? cfscriptVariableAssignmentPattern : tagVariableAssignmentPattern;
while (variableMatch = variableAssignmentPattern.exec(documentText)) {
const initValuePrefix: string = variableMatch[1];
const varPrefix: string = variableMatch[2];
const varScope: string = variableMatch[3];
const scope: string = variableMatch[4];
const varName: string = variableMatch[6];
const initValue: string = variableMatch[8];
// TODO: Does not account for arguments being overridden.
let scopeVal: Scope = Scope.Unknown;
if (scope) {
scopeVal = Scope.valueOf(scope);
} else if (varScope) {
scopeVal = Scope.Local;
}
const varMatchStartOffset: number = textOffset + variableMatch.index + varPrefix.length;
const varRange = new Range(
document.positionAt(varMatchStartOffset),
document.positionAt(varMatchStartOffset + varName.length)
);
const matchingVars: Variable[] = getMatchingVariables(variables, varName, scopeVal);
if (matchingVars.length > 0) {
if (matchingVars.length > 1 || matchingVars[0].declarationLocation.range.start.isBefore(varRange.start)) {
continue;
} else {
// Remove entry
variables = variables.filter((variable: Variable) => {
return variable !== matchingVars[0];
});
}
}
if (scopeVal === Scope.Unknown) {
scopeVal = Scope.Variables;
}
const inferredType: [DataType, Uri] = DataType.inferDataTypeFromValue(initValue, documentUri);
let thisVar: Variable = {
identifier: varName,
dataType: inferredType[0],
dataTypeComponentUri: inferredType[1],
scope: scopeVal,
final: false,
declarationLocation: new Location(
document.uri,
varRange
)
};
if (inferredType[0] === DataType.Query) {
let valueMatch: RegExpExecArray = null;
if (valueMatch = queryValuePattern.exec(initValue)) {
const fullValueMatch: string = valueMatch[0];
const functionName: string = valueMatch[1];
const initValueOffset = textOffset + variableMatch.index + initValuePrefix.length;
const paramsStartOffset: number = initValueOffset + valueMatch.index + fullValueMatch.length;
const paramsEndOffset: number = initValueOffset + initValue.length - 1;
const paramsRange = new Range(document.positionAt(paramsStartOffset), document.positionAt(paramsEndOffset));
const paramRanges: Range[] = getScriptFunctionArgRanges(documentStateContext, paramsRange);
if (paramRanges.length > 0) {
const firstParamText: string = document.getText(paramRanges[0]);
// TODO: If not string literal, but string variable, retrieve string value from variable. Account for using named param.
if (DataType.isStringLiteral(firstParamText)) {
const firstParamVal: string = DataType.getStringLiteralValue(firstParamText);
let columns: QueryColumns;
if (equalsIgnoreCase(functionName, "queryNew")) {
columns = new MySet(firstParamVal.split(","));
} else {
columns = getSelectColumnsFromQueryText(firstParamVal);
}
if (columns.size > 0) {
let query: Query = thisVar as Query;
query.selectColumnNames = columns;
thisVar = query;
}
}
}
}
} else if (inferredType[0] === DataType.Function) {
let userFunction: UserFunctionVariable = thisVar as UserFunctionVariable;
let valueMatch: RegExpExecArray = null;
if (valueMatch = functionValuePattern.exec(initValue)) {
const fullValueMatch: string = valueMatch[0];
const initValueOffset = textOffset + variableMatch.index + initValuePrefix.length;
const paramsStartOffset: number = initValueOffset + valueMatch.index + fullValueMatch.length;
const paramsEndPosition: Position = getClosingPosition(documentStateContext, paramsStartOffset, ")");
const paramsRange = new Range(
document.positionAt(paramsStartOffset),
paramsEndPosition.translate(0, -1)
);
userFunction.signature = {
parameters: parseScriptFunctionArgs(documentStateContext, paramsRange, [])
};
thisVar = userFunction;
}
}
thisVar.initialValue = initValue;
variables.push(thisVar);
}
if (!isScript || userEngine.supportsScriptTags()) {
// Tags with output attributes
let foundOutputVarTags: MySet<string> = new MySet();
let cfTagMatch: RegExpExecArray = null;
const cfTagPattern: RegExp = isScript ? getCfScriptTagPatternIgnoreBody() : getCfStartTagPattern();
while (cfTagMatch = cfTagPattern.exec(documentText)) {
const tagName = cfTagMatch[2].toLowerCase();
if (!foundOutputVarTags.has(tagName) && outputVariableTags.hasOwnProperty(tagName)) {
foundOutputVarTags.add(tagName);
}
}
foundOutputVarTags.forEach((tagName: string) => {
const tagOutputAttributes: VariableAttribute[] = outputVariableTags[tagName];
const parsedOutputVariableTags: StartTag[] = (tagName === "cfquery" ? parseTags(documentStateContext, tagName, docRange) : parseStartTags(documentStateContext, tagName, isScript, docRange));
parsedOutputVariableTags.forEach((tag: StartTag) => {
const tagAttributes: Attributes = tag.attributes;
tagOutputAttributes.filter((tagOutputAttribute: VariableAttribute) => {
return tagAttributes.has(tagOutputAttribute.attributeName);
}).forEach((tagOutputAttribute: VariableAttribute) => {
const attributeName: string = tagOutputAttribute.attributeName;
const attributeVal: string = tagAttributes.get(attributeName).value;
if (!attributeVal) {
return;
}
const varExpressionMatch: RegExpExecArray = variableExpressionPattern.exec(attributeVal);
if (!varExpressionMatch) {
return;
}
const varNamePrefix: string = varExpressionMatch[1];
const varNamePrefixLen: number = varNamePrefix ? varNamePrefix.length : 0;
const scope: string = varExpressionMatch[2];
const varName: string = varExpressionMatch[4];
let scopeVal: Scope = Scope.Unknown;
if (scope) {
scopeVal = Scope.valueOf(scope);
}
const varRangeStart: Position = tagAttributes.get(attributeName).valueRange.start.translate(0, varNamePrefixLen);
const varRange = new Range(
varRangeStart,
varRangeStart.translate(0, varName.length)
);
const matchingVars: Variable[] = getMatchingVariables(variables, varName, scopeVal);
if (matchingVars.length > 0) {
if (matchingVars.length > 1 || matchingVars[0].declarationLocation.range.start.isBefore(varRange.start)) {
return;
} else {
// Remove entry
variables = variables.filter((variable: Variable) => {
return variable !== matchingVars[0];
});
}
}
if (scopeVal === Scope.Unknown) {
scopeVal = Scope.Variables;
}
let outputVar: Variable = {
identifier: varName,
dataType: tagOutputAttribute.dataType,
scope: scopeVal,
final: false,
declarationLocation: new Location(
document.uri,
varRange
)
};
if (tagName === "cfquery" && "bodyRange" in tag) {
const queryTag = tag as Tag;
const bodyText: string = document.getText(queryTag.bodyRange);
const columns: QueryColumns = getSelectColumnsFromQueryText(bodyText);
if (columns.size > 0) {
let query: Query = outputVar as Query;
query.selectColumnNames = columns;
outputVar = query;
}
}
variables.push(outputVar);
});
});
});
}
if (!isScript) {
// Check cfscript sections
const cfScriptRanges: Range[] = getCfScriptRanges(document, docRange);
cfScriptRanges.forEach((range: Range) => {
const cfscriptVars: Variable[] = parseVariableAssignments(documentStateContext, true, range);
cfscriptVars.forEach((scriptVar: Variable) => {
const matchingVars: Variable[] = getMatchingVariables(variables, scriptVar.identifier, scriptVar.scope);
if (matchingVars.length === 0) {
variables.push(scriptVar);
} else if (matchingVars.length === 1 && scriptVar.declarationLocation.range.start.isBefore(matchingVars[0].declarationLocation.range.start)) {
// Replace entry
const matchingIndex: number = variables.findIndex((value: Variable) => {
return value.scope === scriptVar.scope && equalsIgnoreCase(value.identifier, scriptVar.identifier);
});
if (matchingIndex !== -1) {
variables[matchingIndex] = scriptVar;
}
}
});
});
} else {
// Check for-in loops
let forInVariableMatch: RegExpExecArray = null;
while (forInVariableMatch = forInVariableAssignmentPattern.exec(documentText)) {
const varPrefix: string = forInVariableMatch[1];
const varScope: string = forInVariableMatch[2];
const scope: string = forInVariableMatch[3];
const varName: string = forInVariableMatch[5];
let scopeVal: Scope = Scope.Unknown;
if (scope) {
scopeVal = Scope.valueOf(scope);
} else if (varScope) {
scopeVal = Scope.Local;
}
const varMatchStartOffset = textOffset + forInVariableMatch.index + varPrefix.length;
const varRange = new Range(
document.positionAt(varMatchStartOffset),
document.positionAt(varMatchStartOffset + varName.length)
);
const matchingVars = getMatchingVariables(variables, varName, scopeVal);
if (matchingVars.length > 0) {
if (matchingVars.length > 1 || matchingVars[0].declarationLocation.range.start.isBefore(varRange.start)) {
continue;
} else {
// Remove entry
variables = variables.filter((variable: Variable) => {
return variable !== matchingVars[0];
});
}
}
if (scopeVal === Scope.Unknown) {
scopeVal = Scope.Variables;
}
variables.push({
identifier: varName,
dataType: DataType.Any,
scope: scopeVal,
final: false,
declarationLocation: new Location(
document.uri,
varRange
)
});
}
}
return variables;
}
/**
* Returns Variable array representation of Properties
* @param properties The properties of a component to convert
* @param documentUri The URI of the document in which these properties are declared
*/
export function propertiesToVariables(properties: Properties, documentUri: Uri): Variable[] {
let propertyVars: Variable[] = [];
properties.forEach((prop: Property) => {
propertyVars.push({
identifier: prop.name,
dataType: prop.dataType,
dataTypeComponentUri: prop.dataTypeComponentUri,
scope: Scope.Variables,
final: false,
declarationLocation: new Location(documentUri, prop.propertyRange),
description: prop.description
});
});
return propertyVars;
}
/**
* Returns Variable array representation of Arguments
* @param args The arguments of a function to convert
* @param documentUri The URI of the document in which these arguments are declared
*/
export function argumentsToVariables(args: Argument[], documentUri: Uri): Variable[] {
return args.map((arg: Argument) => {
const argVar: Variable = {
identifier: arg.name,
dataType: arg.dataType,
dataTypeComponentUri: arg.dataTypeComponentUri,
scope: Scope.Arguments,
final: false,
declarationLocation: new Location(documentUri, arg.nameRange),
description: arg.description
};
return argVar;
});
}
/**
* Returns the variable that best matches the given name and scope
* @param variables The variables to check
* @param varName The variable name for which to check
* @param scope The variable's scope
*/
export function getBestMatchingVariable(variables: Variable[], varName: string, varScope?: Scope): Variable | undefined {
let foundVar: Variable;
if (varScope) {
foundVar = variables.find((currentVar: Variable) => {
return currentVar.scope === varScope && equalsIgnoreCase(currentVar.identifier, varName);
});
if (!foundVar && unscopedPrecedence.includes(varScope)) {
foundVar = variables.find((currentVar: Variable) => {
return currentVar.scope === Scope.Unknown && equalsIgnoreCase(currentVar.identifier, varName);
});
}
} else {
for (const checkScope of unscopedPrecedence) {
foundVar = variables.find((currentVar: Variable) => {
return currentVar.scope === checkScope && equalsIgnoreCase(currentVar.identifier, varName);
});
if (foundVar) {
return foundVar;
}
}
foundVar = variables.find((currentVar: Variable) => {
return currentVar.scope === Scope.Unknown && equalsIgnoreCase(currentVar.identifier, varName);
});
}
return foundVar;
}
/**
* Returns the variables that match the given name and scope
* @param variables The variables to check
* @param varName The variable name for which to check
* @param scope The variable's scope
*/
export function getMatchingVariables(variables: Variable[], varName: string, scope = Scope.Unknown): Variable[] {
let checkScopes: Scope[];
if (scope === Scope.Unknown) {
checkScopes = [Scope.Local, Scope.Arguments, Scope.Variables, Scope.Unknown];
} else {
checkScopes = [scope];
}
return variables.filter((variable: Variable) => {
return checkScopes.includes(variable.scope) && equalsIgnoreCase(variable.identifier, varName);
});
}
/**
* Gets the application variables for the given document
* @param baseUri The URI of the document for which the Application file will be found
*/
export function getApplicationVariables(baseUri: Uri): Variable[] {
let applicationVariables: Variable[] = [];
const applicationUri: Uri = getApplicationUri(baseUri);
if (applicationUri) {
const cachedApplicationVariables: Variable[] = cachedEntities.getApplicationVariables(applicationUri);
if (cachedApplicationVariables) {
applicationVariables = cachedApplicationVariables;
}
}
return applicationVariables;
}
/**
* Gets the server variables
* @param baseUri The URI of the document for which the Server file will be found
*/
export function getServerVariables(baseUri: Uri): Variable[] {
let serverVariables: Variable[] = [];
const serverUri: Uri = getServerUri(baseUri);
if (serverUri) {
serverVariables = cachedEntities.getServerVariables(serverUri);
}
return serverVariables;
}
/**
* Collects all variable assignments accessible based on the given documentPositionStateContext
* @param documentPositionStateContext The contextual information of the state of a document and the cursor position
*/
export function collectDocumentVariableAssignments(documentPositionStateContext: DocumentPositionStateContext): Variable[] {
let allVariableAssignments: Variable[] = [];
if (documentPositionStateContext.isCfmFile) {
const docVariableAssignments: Variable[] = parseVariableAssignments(documentPositionStateContext, false);
allVariableAssignments = allVariableAssignments.concat(docVariableAssignments);
} else if (documentPositionStateContext.isCfcFile) {
const thisComponent = documentPositionStateContext.component;
if (thisComponent) {
const documentUri: Uri = documentPositionStateContext.document.uri;
// properties
const componentProperties: Properties = thisComponent.properties;
allVariableAssignments = allVariableAssignments.concat(propertiesToVariables(componentProperties, documentUri));
// component variables
let currComponent: Component = thisComponent;
let componentVariables: Variable[] = [];
while (currComponent) {
const currComponentVariables: Variable[] = currComponent.variables.filter((variable: Variable) => {
return !componentVariables.some((existingVariable: Variable) => {
return existingVariable.scope === variable.scope && equalsIgnoreCase(existingVariable.identifier, variable.identifier);
});
});
componentVariables = componentVariables.concat(currComponentVariables);
// Also check in init function
const initMethod: string = currComponent.initmethod ? currComponent.initmethod.toLowerCase() : "init";
if (currComponent.functions.has(initMethod)) {
const currInitFunc: UserFunction = currComponent.functions.get(initMethod);
if (currInitFunc.bodyRange) {
const currInitVariables: Variable[] = parseVariableAssignments(documentPositionStateContext, currComponent.isScript, currInitFunc.bodyRange).filter((variable: Variable) => {
return [Scope.Variables, Scope.This].includes(variable.scope) && !componentVariables.some((existingVariable: Variable) => {
return existingVariable.scope === variable.scope && equalsIgnoreCase(existingVariable.identifier, variable.identifier);
});
});
componentVariables = componentVariables.concat(currInitVariables);
}
}
allVariableAssignments = allVariableAssignments.concat(componentVariables);
if (currComponent.extends) {
currComponent = cachedEntities.getComponent(currComponent.extends);
} else {
currComponent = undefined;
}
}
// function arguments
let functionArgs: Argument[] = [];
thisComponent.functions.filter((func: UserFunction) => {
return func.bodyRange && func.bodyRange.contains(documentPositionStateContext.position) && func.signatures && func.signatures.length !== 0;
}).forEach((func: UserFunction) => {
func.signatures.forEach((signature: UserFunctionSignature) => {
functionArgs = signature.parameters;
});
});
allVariableAssignments = allVariableAssignments.concat(argumentsToVariables(functionArgs, documentUri));
// function local variables
let localVariables: Variable[] = [];
thisComponent.functions.filter((func: UserFunction) => {
return func.bodyRange && func.bodyRange.contains(documentPositionStateContext.position);
}).forEach((func: UserFunction) => {
localVariables = localVariables.concat(getLocalVariables(func, documentPositionStateContext, thisComponent.isScript));
});
allVariableAssignments = allVariableAssignments.concat(localVariables);
}
}
return allVariableAssignments;
}
/**
* Creates a type string for the given variable
* @param variable A variable for which to get the type
*/
export function getVariableTypeString(variable: Variable): string {
let varType: string = variable.dataType;
if (variable.dataTypeComponentUri) {
varType = path.basename(variable.dataTypeComponentUri.fsPath, COMPONENT_EXT);
} else if (variable.dataType === DataType.Function) {
let argString: string = "...";
if (isUserFunctionVariable(variable)) {
argString = variable.signature.parameters.map(constructParameterLabel).join(", ");
}
varType = `function(${argString})`;
}
return varType;
}
// TODO: Add identifierRange and have declarationLocation contain full declaration range
export interface Variable {
identifier: string;
dataType: DataType;
dataTypeComponentUri?: Uri; // Only when dataType is Component
scope: Scope;
final: boolean;
declarationLocation: Location;
description?: string;
initialValue?: string;
}
export class VariablesByScope extends MyMap<Scope, Variable[]> { }
export class VariablesByUri extends MyMap<string, Variable[]> { } // key is Uri.toString()
export interface Struct extends Variable {
keys: StructKeys;
}
export class StructKeys extends MySet<Variable> { } | the_stack |
import * as chai from 'chai';
import {Server} from '../../src/server';
import {TestHelper} from '../TestHelper';
import {User} from '../../src/models/User';
import {WhitelistUser} from '../../src/models/WhitelistUser';
import {IWhitelistUser} from '../../../shared/models/IWhitelistUser';
import {FixtureUtils} from '../../fixtures/FixtureUtils';
import {ICourse} from '../../../shared/models/ICourse';
import {IUser} from '../../../shared/models/IUser';
import {Course} from '../../src/models/Course';
const app = new Server().app;
const BASE_URL = '/api/whitelist';
const testHelper = new TestHelper(BASE_URL);
describe('Whitelist', () => {
beforeEach(() => testHelper.resetForNextTest());
describe(`GET ${BASE_URL}`, () => {
it('should get a whitelist user', async () => {
const course: ICourse = await FixtureUtils.getRandomCourse();
const teacher = await FixtureUtils.getRandomTeacherForCourse(course);
const newWhitelistUser: IWhitelistUser = new WhitelistUser({
firstName: 'Max',
lastName: 'Mustermann',
uid: '123456',
courseId: course._id
});
const createdWhitelistUser: IWhitelistUser = await WhitelistUser.create(newWhitelistUser);
const res = await testHelper.commonUserGetRequest(teacher, `/${createdWhitelistUser._id.toString()}`);
res.status.should.be.equal(200);
res.body.firstName.should.be.equal(newWhitelistUser.firstName);
res.body.lastName.should.be.equal(newWhitelistUser.lastName);
res.body.uid.should.be.equal(newWhitelistUser.uid);
});
it('should deny access to whitelist user data for an unauthorized teacher', async () => {
const course: ICourse = await FixtureUtils.getRandomCourse();
const teacher = await FixtureUtils.getUnauthorizedTeacherForCourse(course);
const newWhitelistUser: IWhitelistUser = new WhitelistUser({
firstName: 'Max',
lastName: 'Mustermann',
uid: '123456',
courseId: course._id
});
const createdWhitelistUser: IWhitelistUser = await WhitelistUser.create(newWhitelistUser);
const res = await testHelper.commonUserGetRequest(teacher, `/${createdWhitelistUser._id.toString()}`);
res.status.should.be.equal(403);
});
it('should deny access to whitelist user data for a student', async () => {
const course: ICourse = await FixtureUtils.getRandomCourse();
const student = await User.findById(course.students[0]);
const newWhitelistUser: IWhitelistUser = new WhitelistUser({
firstName: 'Max',
lastName: 'Mustermann',
uid: '123456',
courseId: course._id
});
const createdWhitelistUser: IWhitelistUser = await WhitelistUser.create(newWhitelistUser);
const res = await testHelper.commonUserGetRequest(student, `/${createdWhitelistUser._id.toString()}`);
res.status.should.be.equal(403);
});
});
describe(`POST ${BASE_URL}`, () => {
it('should create a new whitelist user', async () => {
const course: ICourse = await FixtureUtils.getRandomCourse();
const whitelistUser: any = {
firstName: 'Max',
lastName: 'Mustermann',
uid: '1236456',
courseId: course._id
};
const teacher = await FixtureUtils.getRandomTeacherForCourse(course);
const res = await testHelper.commonUserPostRequest(teacher, '', whitelistUser);
res.status.should.be.equal(200);
res.body.firstName.should.be.equal(whitelistUser.firstName.toLowerCase());
res.body.lastName.should.be.equal(whitelistUser.lastName.toLowerCase());
res.body.uid.should.be.equal(whitelistUser.uid.toLowerCase());
});
it('should fail with wrong authorization', async () => {
const course: ICourse = await FixtureUtils.getRandomCourse();
const whitelistUser: any = {
firstName: 'Max',
lastName: 'Mustermann',
uid: '1236456',
courseId: course._id
};
const res = await chai.request(app)
.post(`${BASE_URL}/`)
.set('Cookie', `token=awf`)
.send(whitelistUser)
.catch(err => err.response);
res.status.should.be.equal(401);
});
it('should add an user by synchronizing', async () => {
const course: ICourse = await FixtureUtils.getRandomCourse();
const teacher = await FixtureUtils.getRandomTeacherForCourse(course);
const user: IUser = await User.create(
{ uid: '1236456',
password: 'test1234',
email: 'test@ok.com',
profile: {
firstName: 'Max',
lastName: 'Mustermann'
}}
);
const whitelistUser: any = {
firstName: user.profile.firstName,
lastName: user.profile.lastName,
uid: user.uid,
courseId: course._id
};
const res = await testHelper.commonUserPostRequest(teacher, '', whitelistUser);
res.status.should.be.equal(200);
const resCourse = await Course.findById(course._id).populate('students');
const addedUsers: IUser[] = resCourse.students.filter(stud => stud.uid === user.uid);
addedUsers.length.should.be.not.eq(0);
addedUsers[0].uid.should.be.eq(whitelistUser.uid);
addedUsers[0].profile.firstName.should.be.eq(whitelistUser.firstName);
addedUsers[0].profile.lastName.should.be.eq(whitelistUser.lastName);
});
it('should fail to create a new whitelist user for an unauthorized teacher', async () => {
const course: ICourse = await FixtureUtils.getRandomCourse();
const whitelistUser: any = {
firstName: 'Max',
lastName: 'Mustermann',
uid: '1236456',
courseId: course._id
};
const teacher = await FixtureUtils.getUnauthorizedTeacherForCourse(course);
const res = await testHelper.commonUserPostRequest(teacher, '', whitelistUser);
res.status.should.be.equal(403);
});
});
// The corresponding route has been disabled since it appears to be unused and insufficiently secured.
/*
describe(`PUT ${BASE_URL}`, () => {
it('should update a whitelist user', async () => {
const teacher = await FixtureUtils.getRandomTeacher();
const course: ICourse = await FixtureUtils.getRandomCourse();
const newWhitelistUser: IWhitelistUser = new WhitelistUser({
firstName: 'Max',
lastName: 'Mustermann',
uid: '123456',
courseId: course._id
});
const createdWhitelistUser = await WhitelistUser.create(newWhitelistUser);
const res = await testHelper.commonUserPutRequest(teacher, `/${createdWhitelistUser._id}`, createdWhitelistUser);
res.status.should.be.equal(200);
res.body.firstName.should.be.equal(newWhitelistUser.firstName);
res.body.lastName.should.be.equal(newWhitelistUser.lastName);
res.body.uid.should.be.equal(newWhitelistUser.uid);
});
it('should fail with wrong authorization', async () => {
const course: ICourse = await FixtureUtils.getRandomCourse();
const newWhitelistUser: IWhitelistUser = new WhitelistUser({
firstName: 'Max',
lastName: 'Mustermann',
uid: '123456',
courseId: course._id
});
const createdWhitelistUser = await WhitelistUser.create(newWhitelistUser);
const res = await chai.request(app)
.put(`${BASE_URL}/${createdWhitelistUser._id}`)
.send(createdWhitelistUser)
.set('Cookie', `token=awf`)
.catch(err => err.response);
res.status.should.be.equal(401);
});
});
*/
describe(`DELETE ${BASE_URL}`, () => {
it('should delete a whitelist user', async () => {
const course: ICourse = await FixtureUtils.getRandomCourse();
const teacher = await FixtureUtils.getRandomTeacherForCourse(course);
const newWhitelistUser: IWhitelistUser = new WhitelistUser({
firstName: 'Max',
lastName: 'Mustermann',
uid: '123456',
courseId: course._id
});
const createdWhitelistUser = await WhitelistUser.create(newWhitelistUser);
const res = await testHelper.commonUserDeleteRequest(teacher, `/${createdWhitelistUser._id}`);
res.status.should.be.equal(200);
});
it('should fail with wrong authorization', async () => {
const course: ICourse = await FixtureUtils.getRandomCourse();
const newWhitelistUser: IWhitelistUser = new WhitelistUser({
firstName: 'Max',
lastName: 'Mustermann',
uid: '123456',
courseId: course._id
});
const createdWhitelistUser = await WhitelistUser.create(newWhitelistUser);
const res = await chai.request(app)
.del(`${BASE_URL}/${createdWhitelistUser._id}`)
.set('Cookie', `token=awf`)
.catch(err => err.response);
res.status.should.be.equal(401);
});
it('should delete an user by synchronizing', async () => {
const course: ICourse = await FixtureUtils.getRandomCourse();
const teacher = await FixtureUtils.getRandomTeacherForCourse(course);
const member = course.students[0];
const newWhitelistUser: IWhitelistUser = new WhitelistUser({
firstName: member.profile.firstName,
lastName: member.profile.lastName,
uid: member.uid,
courseId: course._id
});
const createdWhitelistUser = await WhitelistUser.create(newWhitelistUser);
course.whitelist = course.whitelist.concat(createdWhitelistUser);
await Course.findByIdAndUpdate(course._id, course);
const res = await testHelper.commonUserDeleteRequest(teacher, `/${createdWhitelistUser._id}`);
res.status.should.be.equal(200);
const resCourse = await Course.findById(course._id).populate('students');
const emptyUsers: IUser[] = resCourse.students.filter(stud => stud.uid === member.uid);
emptyUsers.length.should.be.eq(0);
});
it('should fail to delete for an unauthorized teacher', async () => {
const course: ICourse = await FixtureUtils.getRandomCourse();
const teacher = await FixtureUtils.getUnauthorizedTeacherForCourse(course);
const newWhitelistUser: IWhitelistUser = new WhitelistUser({
firstName: 'Max',
lastName: 'Mustermann',
uid: '123456',
courseId: course._id
});
const createdWhitelistUser = await WhitelistUser.create(newWhitelistUser);
const res = await testHelper.commonUserDeleteRequest(teacher, `/${createdWhitelistUser._id}`);
res.status.should.be.equal(403);
});
});
}); | the_stack |
import {isPlainObject} from 'lodash';
import {defaultMergeItem, initialState as defaultInitialState} from '../defaults';
import {find, getGerundName, getIdKey, isFunction, isObject, isString, ucfirst} from '../helpers/util';
import {getActionType, getTypesScope} from '../types';
import {
Action,
ConfigActionsOptions,
Context,
ReduceOptions,
Reducer,
ReducerMapObject,
State,
UnknownObject
} from '../typings';
const getUpdateArrayData = (action: Action, itemId: string | number): UnknownObject | undefined => {
const actionOpts = action.options || {};
const idKey = getIdKey(action, {multi: false});
if (!isPlainObject(action.context)) {
return {};
}
const actionContext = action.context as UnknownObject;
return actionOpts.assignResponse
? find(action.payload?.body as Array<UnknownObject>, {
[idKey]: itemId
})
: Object.keys(actionContext).reduce<UnknownObject>((soFar, key) => {
if (key !== 'ids') {
soFar[key] = actionContext[key as keyof Context];
}
return soFar;
}, {});
};
const getIdFromAction = (action: Action, {multi}: {multi: boolean}): [string, unknown] => {
const idKey = getIdKey(action, {multi});
const {context, options = {}} = action;
const {params = {}} = options;
if (params[idKey]) {
return [idKey, params[idKey]];
}
if (isObject(context) && context[idKey]) {
return [idKey, context[idKey]];
}
if (isString(context)) {
return [idKey, context];
}
return [idKey, undefined];
// throw new Error(
// `Failed to resolve id with key="${idKey}" from context=${JSON.stringify(context)} or params=${JSON.stringify(
// params
// )}`
// );
};
const createDefaultReducers = <T extends UnknownObject>(reduceOptions: ReduceOptions<T>): ReducerMapObject<T> => {
const initialState = defaultInitialState as State<T>;
const mergeItem = reduceOptions.mergeItem || defaultMergeItem;
return {
create: (state = initialState, action): State<T> => {
const actionOpts = action.options || {};
switch (action.status) {
case 'pending':
// @TODO optimistic updates?
return {
...state,
isCreating: true
};
case 'resolved': {
const nextState: Partial<State<T>> = {};
if (actionOpts.assignResponse) {
const createdItem = action.payload?.body as T;
nextState.items = (state.items || []).concat(createdItem);
}
return {
...state,
isCreating: false,
...nextState
};
}
case 'rejected':
return {
...state,
isCreating: false
};
default:
return state;
}
},
fetch: (state = initialState, action) => {
switch (action.status) {
case 'pending': {
const actionOpts = action.options || {};
const didInvalidate = !!actionOpts.invalidateState;
return {
...state,
isFetching: true,
didInvalidate,
...(didInvalidate ? {items: []} : {})
};
}
case 'resolved': {
const nextState: Partial<State<T>> = {};
const {body, contentRange, code, receivedAt = Date.now()} = action.payload || {};
nextState.items = body as T[];
const isPartialContent = code === 206;
if (isPartialContent && contentRange && contentRange.first > 0) {
nextState.items = state.items
.slice(0, contentRange.first)
.concat(nextState.items)
.concat(state.items.slice(contentRange.last, state.items.length));
}
return {
...state,
isFetching: false,
didInvalidate: false,
lastUpdated: receivedAt,
...nextState
};
}
case 'rejected':
return {
...state,
isFetching: false
};
default:
return state;
}
},
get: (state = initialState, action) => {
const actionOpts = action.options || {};
switch (action.status) {
case 'pending': {
const [idKey, id] = getIdFromAction(action, {multi: false});
const hasConflictingContext = id && state.item ? state.item[idKey] !== id : false;
const didInvalidate = !!actionOpts.invalidateState || hasConflictingContext;
return {
...state,
isFetchingItem: true,
didInvalidateItem: didInvalidate,
...(didInvalidate ? {item: null} : {})
};
}
case 'resolved': {
const {body, receivedAt = Date.now()} = action.payload || {};
const partialItem = body as Partial<T>;
const nextItem = (actionOpts.mergeResponse ? mergeItem(state.item, partialItem) : partialItem) as T;
const nextState: Partial<State<T>> = {item: {...nextItem}};
if (actionOpts.assignResponse) {
const idKey = getIdKey(action, {multi: false});
const prevListItemIndex = state.items.findIndex((el) => el[idKey] === partialItem[idKey]);
if (prevListItemIndex !== -1) {
const prevListItem = state.items[prevListItemIndex];
const nextListItem = actionOpts.mergeResponse ? mergeItem(prevListItem, partialItem) : (partialItem as T);
state.items.splice(prevListItemIndex, 1, nextListItem);
nextState.items = state.items.slice();
}
}
return {
...state,
isFetchingItem: false,
didInvalidateItem: false,
lastUpdatedItem: receivedAt,
...nextState
};
}
case 'rejected':
return {
...state,
isFetchingItem: false
};
default:
return state;
}
},
update: (state = initialState, action) => {
const actionOpts = action.options || {};
switch (action.status) {
case 'pending':
// Update object in store as soon as possible?
return {
...state,
isUpdating: true
};
case 'resolved': {
// Assign context or returned object
const [idKey, id] = getIdFromAction(action, {multi: false});
const update = (actionOpts.assignResponse ? action.payload?.body : action.context) as Partial<T>;
const listItemIndex = state.items.findIndex((el) => el[idKey] === id);
const updatedItems = state.items.slice();
if (listItemIndex !== -1) {
updatedItems[listItemIndex] = {
...updatedItems[listItemIndex],
...update
};
}
const updatedItem = state.item && state.item[idKey] === id ? mergeItem(state.item, update) : state.item;
return {
...state,
isUpdating: false,
items: updatedItems,
item: updatedItem
};
}
case 'rejected':
return {
...state,
isUpdating: false
};
default:
return state;
}
},
updateMany: (state = initialState, action) => {
switch (action.status) {
case 'pending':
// Update object in store as soon as possible?
return {
...state,
isUpdatingMany: true
};
case 'resolved': {
// Assign context or returned object
const idKey = getIdKey(action, {multi: false});
const [, ids] = getIdFromAction(action, {multi: true});
const updatedItems = state.items.map((item) => {
if (!ids || (ids as string[]).includes(item[idKey] as string)) {
const updatedItem = getUpdateArrayData(action, item[idKey] as string);
return updatedItem
? {
...item,
...updatedItem
}
: item;
}
return item;
});
// Also impact state.item? (@TODO opt-in/defautl?)
const updatedItem =
state.item && (!ids || (ids as string[]).includes(state.item[idKey] as string))
? {
...state.item,
...getUpdateArrayData(action, state.item[idKey] as string)
}
: state.item;
return {
...state,
isUpdatingMany: false,
items: updatedItems,
item: updatedItem
};
}
case 'rejected':
return {
...state,
isUpdatingMany: false
};
default:
return state;
}
},
delete: (state = initialState, action) => {
switch (action.status) {
case 'pending':
// Update object in store as soon as possible?
return {
...state,
isDeleting: true
};
case 'resolved': {
// @NOTE Do not update items array when an empty context was provided
// Can happen with custom resource not using id params
if (!action.context) {
return {...state, isDeleting: false};
}
const [idKey, id] = getIdFromAction(action, {multi: false});
return {
...state,
isDeleting: false,
items: [...state.items.filter((el) => id && el[idKey] !== id)]
};
}
case 'rejected':
return {
...state,
isDeleting: false
};
default:
return state;
}
},
deleteMany: (state = initialState, action) => {
switch (action.status) {
case 'pending':
// Update object in store as soon as possible?
return {
...state,
isDeletingMany: true
};
case 'resolved': {
const idKey = getIdKey(action, {multi: false});
const [, ids] = getIdFromAction(action, {multi: true});
if (!ids) {
return {
...state,
isDeletingMany: false,
items: [],
item: null
};
}
return {
...state,
isDeletingMany: false,
items: [...state.items.filter((el) => !(ids as string[]).includes(el[idKey] as string))],
item: state.item && (ids as string[]).includes(state.item[idKey] as string) ? null : state.item
};
}
case 'rejected':
return {
...state,
isDeletingMany: false
};
default:
return state;
}
}
};
};
const createReducer = <T extends UnknownObject>(
actionId: string,
reduceOptions: ReduceOptions<T>,
defaultReducers = createDefaultReducers<T>(reduceOptions)
): Reducer<T> => {
// Custom reducers
if (reduceOptions.reduce && isFunction(reduceOptions.reduce)) {
return reduceOptions.reduce;
}
// Do require a custom reduce function for pure actions
if (reduceOptions.isPure) {
throw new Error(`Missing \`reduce\` option for pure action \`${actionId}\``);
}
// Default reducers
if (defaultReducers[actionId]) {
return defaultReducers[actionId] as Reducer<T>;
}
// Custom actions
const gerundName = reduceOptions.gerundName || getGerundName(actionId);
const gerundStateKey = `is${ucfirst(gerundName)}`;
return (state = defaultInitialState as State<T>, action): State<T> => {
switch (action.status) {
case 'pending':
// Update object in store as soon as possible?
return {
...state,
[gerundStateKey]: true
};
case 'resolved': // eslint-disable-line
return {
...state,
[gerundStateKey]: false
};
case 'rejected':
return {
...state,
[gerundStateKey]: false
};
default:
return state;
}
};
};
const createReducers = <T extends UnknownObject>(
actions: ConfigActionsOptions = {},
reduceOptions: ReduceOptions<T> = {}
): ReducerMapObject<T> => {
const actionKeys = Object.keys(actions);
const defaultReducers = createDefaultReducers<T>(reduceOptions);
return actionKeys.reduce<ReducerMapObject<T>>((actionReducers, actionId) => {
// d(omit(actions[actionId], SUPPORTED_REDUCE_OPTS));
const combinedReduceOptions: ReduceOptions<T> = {
...reduceOptions,
...actions[actionId]
// ...pick<ConfigActionOptions>(actions[actionId], (SUPPORTED_REDUCE_OPTS as unknown) as keyof ConfigActionOptions)
};
const reducerKey = getActionType(actionId).toLowerCase();
actionReducers[reducerKey] = createReducer<T>(actionId, combinedReduceOptions, defaultReducers);
return actionReducers;
}, {});
};
type CreateRootReducerOptions = {
resourceName: string;
scope?: string;
};
const createRootReducer = <T extends UnknownObject>(
reducers: ReducerMapObject<T> = {},
{resourceName, scope = getTypesScope(resourceName)}: CreateRootReducerOptions
): Reducer<T> => {
const scopeNamespace = scope ? `${scope}/` : '';
const rootReducer: Reducer<T> = (
state = {
...(defaultInitialState as State<T>)
},
action
) => {
// Only process relevant namespace
if (scopeNamespace && !String(action.type).startsWith(scopeNamespace)) {
return state;
}
// Only process relevant action type
const type = action.type.substr(scopeNamespace.length).toLowerCase();
// Check for a matching reducer
if (reducers[type]) {
return reducers[type](state, action);
}
return state;
};
return rootReducer;
};
export {defaultInitialState as initialState, createReducer, createReducers, createRootReducer}; | the_stack |
import {
chain,
Decoder,
DecoderError,
number,
stringUnion,
} from "tiny-decoders";
// It's tempting to put a random number or something in the ID, but in case
// something goes wrong and a rogue container is left behind it's always
// possible to find and remove it if the ID is known. Also, RendererProgram and
// ElementManager might not get the same random number.
export const CONTAINER_ID = `__${META_SLUG}WebExt`;
export type LogLevel = ReturnType<typeof LogLevel>;
export const LogLevel = stringUnion({
error: null,
warn: null,
log: null,
debug: null,
});
export const LOG_LEVELS: { [key in LogLevel]: number } = {
error: 0,
warn: 1,
log: 2,
debug: 3,
};
export const DEFAULT_LOG_LEVEL: LogLevel = PROD
? "warn"
: decode(LogLevel, DEFAULT_LOG_LEVEL_CONFIG);
export function log(level: LogLevel, ...args: Array<unknown>): void {
if (LOG_LEVELS[level] > LOG_LEVELS[log.level]) {
return;
}
const method = getLogMethod(level);
method.call(
console,
`[${META_SLUG}]`,
formatDate(new Date()),
window.location.protocol.endsWith("-extension:")
? "extension page"
: window.location.href,
"\n ",
...args
);
}
// The main `Program` for each entrypoint modifies this property. A little ugly,
// but very convenient.
log.level = DEFAULT_LOG_LEVEL;
function formatDate(date: Date): string {
const pad = (num: number, length: number = 2): string =>
num.toString().padStart(length, "0");
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(
date.getDate()
)} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(
date.getSeconds()
)}.${pad(date.getMilliseconds(), 3)}`;
}
/* eslint-disable no-console */
function getLogMethod(level: LogLevel): typeof console.log {
switch (level) {
case "error":
return console.error;
case "warn":
return console.warn;
case "log":
return console.log;
case "debug":
return console.debug;
}
}
/* eslint-enable no-console */
export function addEventListener<
EventName extends string,
EventType extends Event
>(
target: EventTarget,
eventName: EventName,
listener: (event: EventType) => void,
name: string,
options: { capture?: boolean; passive?: boolean } = {}
): () => void {
const wrappedListener = (event: EventType): void => {
try {
listener(event);
} catch (error) {
log("error", name, error, event);
}
};
const fullOptions = { capture: true, passive: true, ...options };
target.addEventListener(
eventName,
// @ts-expect-error This is fine. I have no idea how to fix.
wrappedListener,
fullOptions
);
return () => {
target.removeEventListener(
eventName,
// @ts-expect-error This is fine. I have no idea how to fix.
wrappedListener,
fullOptions
);
};
}
export function addListener<
Listener extends (...args: Array<never>) => void,
Options
>(
target: {
addListener: (listener: Listener, options?: Options) => void;
removeListener: (listener: Listener) => void;
},
listener: Listener,
name: string,
options?: Options
): () => void {
// @ts-expect-error This is fine. I have no idea how to fix.
const wrappedListener: Listener = (...args) => {
try {
listener(...args);
} catch (error) {
log("error", name, error, ...args);
}
};
if (options === undefined) {
target.addListener(wrappedListener);
} else {
target.addListener(wrappedListener, options);
}
return () => {
target.removeListener(wrappedListener);
};
}
export function timeout(duration: number, callback: () => unknown): () => void {
const timeoutId = setTimeout(callback, duration);
return () => {
clearTimeout(timeoutId);
};
}
export class Resets {
_callbacks: Array<() => unknown> = [];
add(...callbacks: Array<() => unknown>): void {
this._callbacks.push(...callbacks);
}
reset(): void {
for (const callback of this._callbacks) {
callback();
}
this._callbacks = [];
}
}
/**
* Divides `array` into two arrays, `left`, and `right`, using `fn`. If
* `fn(item)` returns `true`, `item` is placed in `left`, otherwise in `right`.
*/
export function partition<T>(
array: Array<T>,
fn: (item: T, index: number, array: Array<T>) => boolean
): [Array<T>, Array<T>] {
const left: Array<T> = [];
const right: Array<T> = [];
array.forEach((item, index) => {
if (fn(item, index, array)) {
left.push(item);
} else {
right.push(item);
}
});
return [left, right];
}
export function makeRandomToken(): string {
const array = new Uint32Array(3);
window.crypto.getRandomValues(array);
return array.join("");
}
export type Box = {
x: number;
y: number;
width: number;
height: number;
};
type IntermediateRect = {
left: number;
right: number;
top: number;
bottom: number;
};
// Turn a `ClientRect` into a `Box` using the coordinates of the topmost
// viewport. Only the part of the `ClientRect` visible through all viewports end
// up in the `Box`.
export function getVisibleBox(
passedRect: ClientRect,
viewports: Array<Box>
): Box | undefined {
// No shortcuts (such as summing up viewport x:s and y:s) can be taken here,
// since each viewport (frame) clips the visible area. We have to loop them
// all through.
const visibleRect = viewports.reduceRight<IntermediateRect>(
(rect, viewport) => ({
left: viewport.x + Math.max(rect.left, 0),
right: viewport.x + Math.min(rect.right, viewport.width),
top: viewport.y + Math.max(rect.top, 0),
bottom: viewport.y + Math.min(rect.bottom, viewport.height),
}),
passedRect
);
const width = visibleRect.right - visibleRect.left;
const height = visibleRect.bottom - visibleRect.top;
// If `visibleRect` has a nonsensical width or height it means it is not
// visible within `viewports`.
return width <= 0 || height <= 0
? undefined
: {
x: visibleRect.left,
y: visibleRect.top,
width,
height,
};
}
export function getViewport(): Box {
// In `<frameset>` documents `.scrollingElement` is null so fall back to
// `.documentElement`.
const scrollingElement =
document.scrollingElement ?? document.documentElement;
if (scrollingElement === null) {
return {
x: 0,
y: 0,
width: window.innerWidth,
height: window.innerHeight,
};
}
// `scrollingElement.client{Width,Height}` is the size of the viewport without
// scrollbars (unlike `window.inner{Width,Height}` which include the
// scrollbars). This works in both Firefox and Chrome, quirks and non-quirks
// mode and with strange styling like setting a width on `<html>`.
return {
x: 0,
y: 0,
width: scrollingElement.clientWidth,
height: scrollingElement.clientHeight,
};
}
export function setStyles(
element: HTMLElement,
styles: Record<string, string>
): void {
for (const [property, value] of Object.entries(styles)) {
element.style.setProperty(property, value, "important");
}
}
export const NON_WHITESPACE = /\S/;
export const LAST_NON_WHITESPACE = /\S\s*$/;
export const SKIP_TEXT_ELEMENTS = new Set<string>([
// Ignore the default text in the HTML of `<textarea>` (if any), which is not
// updated as the user types.
"TEXTAREA",
// Ignore the text of `<option>`s inside `<select>` and `<datalist>`, most
// of which are not visible.
"SELECT",
"DATALIST",
// Ignore fallback content inside `<canvas>`, `<audio>` and `<video>`.
"CANVAS",
"AUDIO",
"VIDEO",
// Google has `<style>` elements inside some `<div>`s with click listeners.
"STYLE",
// If we ignore `<style>` we could just as well ignore `<script>` too.
"SCRIPT",
// Finally, ignore the two elements with the most text of all. They aren’t
// useful and cause performance issues.
"HTML",
"BODY",
]);
function shouldSkipElementText(element: HTMLElement): boolean {
return (
// Checking `.nodeName` is ~3x faster than `instanceof` in the link monster
// demo.
SKIP_TEXT_ELEMENTS.has(element.nodeName) ||
// Shadow hosts _can_ have text that is never displayed. Ideally we should
// catch closed shadow roots as well, but it’s unclear if it’s worth the
// trouble.
element.shadowRoot !== null
);
}
export function* walkTextNodes(
element: HTMLElement
): Generator<Text, void, void> {
let ignoreText = false;
if (!shouldSkipElementText(element)) {
for (const node of element.childNodes) {
if (node instanceof Text) {
if (!ignoreText) {
// Detect 1px elements with `overflow: hidden;` used to visually hide
// screen reader text. One has to measure the _element_ – because the
// (clipped) _text_ still has a reasonable size!
const parentRect = element.getBoundingClientRect();
const isScreenReaderOnly =
parentRect.width <= 1 && parentRect.height <= 1;
if (isScreenReaderOnly) {
ignoreText = true;
} else {
yield node;
}
}
} else if (node instanceof HTMLElement) {
yield* walkTextNodes(node);
}
}
}
}
// This is like `element.textContent`, except it skips the content of some
// elements (see `walkTextNodes`). This does not seem to be slower than
// `.textContent`.
export function extractText(element: HTMLElement): string {
if (shouldSkipElementText(element)) {
return "";
}
const onlyChild =
element.childNodes.length === 1 ? element.childNodes[0] : undefined;
return onlyChild !== undefined && onlyChild instanceof Text
? onlyChild.data
: // This line is sufficient by itself. The above is just a performance
// optimization for a common case (a single text node child).
Array.from(walkTextNodes(element), (node) => node.data).join("");
}
export function getTextRects({
element,
viewports,
words,
checkElementAtPoint = true,
}: {
element: HTMLElement;
viewports: Array<Box>;
words: Set<string>;
checkElementAtPoint?: boolean;
}): Array<Box> {
const text = extractText(element).toLowerCase();
const ranges = [];
for (const word of words) {
let index = -1;
while ((index = text.indexOf(word, index + 1)) >= 0) {
ranges.push({
start: index,
end: index + word.length,
range: document.createRange(),
});
}
}
if (ranges.length === 0) {
return [];
}
let index = 0;
for (const node of walkTextNodes(element)) {
const nextIndex = index + node.length;
for (const { start, end, range } of ranges) {
if (start >= index && start < nextIndex) {
range.setStart(node, start - index);
}
if (end >= index && end <= nextIndex) {
range.setEnd(node, end - index);
}
}
index = nextIndex;
}
const [offsetX, offsetY] = viewports.reduceRight(
([x, y], viewport) => [x + viewport.x, y + viewport.y],
[0, 0]
);
return ranges.flatMap(({ range }) => {
const rects = range.getClientRects();
return Array.from(rects, (rect) => {
const box = getVisibleBox(rect, viewports);
if (box === undefined) {
return [];
}
if (!checkElementAtPoint) {
return box;
}
const elementAtPoint = getElementFromPoint(
element,
Math.round(box.x + box.width / 2 - offsetX),
Math.round(box.y + box.height / 2 - offsetY)
);
return elementAtPoint !== undefined && element.contains(elementAtPoint)
? box
: [];
}).flat();
});
}
export function getElementFromPoint(
element: HTMLElement,
x: number,
y: number
): HTMLElement | undefined {
const root = element.getRootNode();
const doc =
root instanceof Document || root instanceof ShadowRoot ? root : document;
const elementFromPoint = doc.elementFromPoint(x, y);
return elementFromPoint === null
? undefined
: (elementFromPoint as HTMLElement);
}
export function getElementsFromPoint(
element: HTMLElement,
x: number,
y: number
): Array<HTMLElement> {
const root = element.getRootNode();
const doc =
root instanceof Document || root instanceof ShadowRoot ? root : document;
return doc.elementsFromPoint(x, y) as Array<HTMLElement>;
}
export function getLabels(
element: HTMLElement
): NodeListOf<HTMLLabelElement> | undefined {
// @ts-expect-error Only some types of elements have `.labels`, and I'm not going to `instanceof` check them all.
const labels: unknown = element.labels; // eslint-disable-line prefer-destructuring
return labels instanceof NodeList
? (labels as NodeListOf<HTMLLabelElement>)
: undefined;
}
export function classlist(
...args: Array<Record<string, boolean> | string>
): string {
return args
.flatMap((arg) =>
typeof arg === "string"
? arg
: Object.entries(arg)
.filter(([, enabled]) => enabled)
.map(([className]) => className)
)
.join(" ");
}
export function isMixedCase(string: string): boolean {
return string.toLowerCase() !== string && string.toUpperCase() !== string;
}
export function splitEnteredText(enteredText: string): Array<string> {
return enteredText.split(" ").filter((word) => word !== "");
}
// Deep equal for JSON data.
export function deepEqual(a: unknown, b: unknown): boolean {
if (a === b) {
return true;
}
if (Array.isArray(a) && Array.isArray(b)) {
if (a.length !== b.length) {
return false;
}
for (let index = a.length - 1; index >= 0; index--) {
if (!deepEqual(a[index], b[index])) {
return false;
}
}
return true;
}
if (
typeof a === "object" &&
a !== null &&
typeof b === "object" &&
b !== null
) {
const keysA = Object.keys(a);
const keysB = Object.keys(b);
if (keysA.length !== keysB.length) {
return false;
}
const keys = new Set(keysA.concat(keysB));
for (const key of keys) {
if (
!deepEqual(
(a as Record<string, unknown>)[key],
(b as Record<string, unknown>)[key]
)
) {
return false;
}
}
return true;
}
return false;
}
export const UnsignedInt: Decoder<number> = chain(number, (value) => {
if (!(Number.isFinite(value) && value >= 0 && Number.isInteger(value))) {
throw new DecoderError({
message: `Expected an unsigned finite integer`,
value,
});
}
return value;
});
export function normalizeUnsignedInt(
value: string,
defaultValue: number
): string {
const parsed = parseFloat(value);
const defaulted =
Number.isFinite(parsed) && parsed >= 0 && Number.isInteger(parsed)
? parsed
: defaultValue;
return defaulted.toString();
}
export const UnsignedFloat: Decoder<number> = chain(number, (value) => {
if (!(Number.isFinite(value) && value >= 0)) {
throw new DecoderError({
message: "Expected an unsigned finite float",
value,
});
}
return value;
});
export function normalizeUnsignedFloat(
value: string,
defaultValue: number
): string {
const parsed = parseFloat(value);
const defaulted =
Number.isFinite(parsed) && parsed >= 0 ? parsed : defaultValue;
return defaulted.toString();
}
export function decode<T>(
decoder: Decoder<T>,
value: unknown,
errors?: Array<string>,
map?: Map<string, Array<number | string>>
): T {
const localErrors: Array<DecoderError> = [];
try {
const result = decoder(value, localErrors);
if (errors !== undefined) {
for (const error of localErrors) {
const originalPath = map?.get(JSON.stringify(error.path));
if (originalPath !== undefined) {
error.path = originalPath;
}
errors.push(error.format());
}
}
return result;
} catch (error) {
if (error instanceof DecoderError) {
const originalPath = map?.get(JSON.stringify(error.path));
if (originalPath !== undefined) {
error.path = originalPath;
}
throw new TypeError(error.format());
} else {
throw error;
}
}
}
export function fireAndForget(
promise: Promise<void>,
name: string,
...args: Array<unknown>
): void {
promise.catch((error) => {
log("error", name, error, ...args);
});
} | the_stack |
// The MIT License (MIT)
//
// vs-deploy (https://github.com/mkloubert/vs-deploy)
// Copyright (c) Marcel Joachim Kloubert <marcel.kloubert@gmx.net>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
import * as deploy_contracts from './contracts';
import * as deploy_helpers from './helpers';
import * as deploy_targets from './targets';
import * as FS from 'fs';
import * as i18 from './i18';
import * as Moment from 'moment';
import * as Path from 'path';
import * as vs_deploy from './deploy';
import * as vscode from 'vscode';
import * as Workflows from 'node-workflows';
interface PackageWithSyncFilter {
filter: deploy_contracts.SyncWhenOpenFileFilter;
package: deploy_contracts.DeployPackage;
}
function normalizeFilePath(file: string): string {
return deploy_helpers.replaceAllStrings(file, Path.sep, '/');
}
/**
* Synchronizes a document after it has been opened.
*
* @param {vscode.TextDocument} doc The document.
*
* @returns {Promise<any>} The promise.
*/
export function syncDocumentWhenOpen(doc: vscode.TextDocument): Promise<any> {
return syncFileWhenOpen.apply(this, [ doc.fileName ]);
}
/**
* Synchronizes a document after it has been opened.
*
* @param {vscode.TextDocument} doc The document.
*
* @returns {Promise<any>} The promise.
*/
export function syncFileWhenOpen(file: string): Promise<any> {
let me: vs_deploy.Deployer = this;
let cfg = me.config;
let lastConfigUpdate = me.lastConfigUpdate;
let startTime = me.startTime;
return new Promise<any>((resolve, reject) => {
try {
if (!lastConfigUpdate || !startTime || deploy_helpers.isEmptyString(file)) {
resolve();
return;
}
file = normalizeFilePath(file);
let wf = Workflows.create();
wf.next((ctx) => {
ctx.result = [];
});
me.getPackages().forEach(pkg => {
wf.next(async (ctx) => {
let packagesAndFilters: PackageWithSyncFilter[] = ctx.result;
if (!deploy_helpers.isNullOrUndefined(pkg.syncWhenOpen)) {
if (false !== pkg.syncWhenOpen) {
let filter: deploy_contracts.SyncWhenOpenFileFilter;
let fastFileCheck = deploy_helpers.toBooleanSafe(pkg.fastCheckOnSync,
deploy_helpers.toBooleanSafe(cfg.fastCheckOnSync));
if (true === pkg.syncWhenOpen) {
// files of package
filter = deploy_helpers.cloneObject(pkg);
filter.target = <any>pkg.targets;
}
else {
if ('object' === typeof pkg.syncWhenOpen) {
filter = pkg.syncWhenOpen;
}
else {
// target name
filter = deploy_helpers.cloneObject(pkg);
filter.target = deploy_helpers.toStringSafe(pkg.syncWhenOpen);
}
}
let fileChecker: () => boolean;
if (fastFileCheck) {
fileChecker = () => {
return deploy_helpers.doesFileMatchByFilter(file, filter);
};
}
else {
let filesByFilter = await deploy_helpers.getFilesByFilterAsync(filter, me.useGitIgnoreStylePatternsInFilter(filter));
filesByFilter = filesByFilter.map(x => normalizeFilePath(x));
fileChecker = () => {
return filesByFilter.indexOf(file) > -1;
};
}
if (fileChecker()) {
packagesAndFilters.push({
filter: filter,
package: pkg,
});
}
}
}
});
});
wf.start().then((packagesAndFilters: PackageWithSyncFilter[]) => {
if (packagesAndFilters.length < 1) {
resolve();
return;
}
let targets = me.getTargets();
let wfPackages = Workflows.create();
wfPackages.next((ctxPkg) => {
return new Promise<any>((res, rej) => {
FS.lstat(file, (err, stats) => {
if (err) {
rej(err);
}
else {
ctxPkg.value = stats;
res();
}
});
});
});
packagesAndFilters.forEach(pf => {
let alwaysSyncIfNewer = deploy_helpers.toBooleanSafe(pf.package.alwaysSyncIfNewer,
deploy_helpers.toBooleanSafe(cfg.alwaysSyncIfNewer));
let timeToCompareWithLocalFile: Moment.Moment;
if (deploy_helpers.toBooleanSafe(cfg.useWorkspaceStartTimeForSyncWhenOpen,
deploy_helpers.toBooleanSafe(pf.package.useWorkspaceStartTimeForSyncWhenOpen))) {
timeToCompareWithLocalFile = startTime;
}
else {
timeToCompareWithLocalFile = lastConfigUpdate;
}
let targetNames: string[] = deploy_helpers.asArray(pf.filter.target);
targetNames = targetNames.map(x => deploy_helpers.normalizeString(x));
targetNames = targetNames.filter(x => '' !== x);
if (targetNames.length < 1) {
// from package
targetNames = deploy_helpers.asArray(pf.package.targets);
}
// cleanups
targetNames = deploy_helpers.asArray(targetNames);
targetNames = targetNames.map(x => deploy_helpers.normalizeString(x));
targetNames = targetNames.filter(x => '' !== x);
targetNames = deploy_helpers.distinctArray(targetNames);
let machtingTargets = targets.filter(t => {
return targetNames.indexOf( deploy_helpers.normalizeString(t.name) )
> -1;
});
deploy_targets.getPluginsForTarget(machtingTargets, me.plugins).forEach(targetWithPlugin => {
let supportedPlugins = targetWithPlugin.plugins
.filter(x => x.canPull && x.canGetFileInfo);
supportedPlugins.forEach(pi => {
wfPackages.next((ctxPkg) => {
let fileStats: FS.Stats = ctxPkg.value;
return new Promise<any>((res, rej) => {
let syncCompletedInvoked = false;
let syncCompleted = (err: any, okMsg?: string) => {
if (syncCompletedInvoked) {
return;
}
syncCompletedInvoked = true;
if (err) {
me.outputChannel.appendLine(i18.t('failed', err));
rej(err);
}
else {
me.outputChannel.appendLine(okMsg);
res();
}
};
try {
// output channel message
{
let targetName = deploy_helpers.toStringSafe(targetWithPlugin.target.name).trim();
let pullingMsg: string;
if ('' !== targetName) {
targetName = ` ('${targetName}')`;
}
pullingMsg = i18.t('sync.file.synchronize', file, targetName);
me.outputChannel.append(pullingMsg);
}
// get info of remote file
Promise.resolve( pi.getFileInfo(file, targetWithPlugin.target) ).then((fi) => {
if (fi) {
if (fi.exists) {
try {
let remoteFileIsNewer = false;
if (fi.modifyTime) {
remoteFileIsNewer = fi.modifyTime.isAfter(fileStats.mtime);
}
if (remoteFileIsNewer) {
// sync local with remote file ...
if (alwaysSyncIfNewer || timeToCompareWithLocalFile.isAfter(fileStats.mtime)) {
// ... if local not changed
// since the current session
if (!syncCompletedInvoked) {
pi.pullFile(file, targetWithPlugin.target, {
onCompleted: (sender, e) => {
syncCompleted(e.error, i18.t('ok'));
}
});
}
}
else {
syncCompleted(null, i18.t('sync.file.localChangedWithinSession'));
}
}
else {
syncCompleted(null, i18.t('sync.file.localIsNewer'));
}
}
catch (e) {
syncCompleted(e);
}
}
else {
syncCompleted(null, i18.t('sync.file.doesNotExistOnRemote'));
}
}
else {
syncCompleted(null, i18.t('canceled'));
}
}).catch((err) => {
syncCompleted(err); // could not get file info
});
}
catch (e) {
syncCompleted(e);
}
});
});
});
});
});
wfPackages.start().then(() => {
resolve();
}).catch((err) => {
reject(err);
});
}).catch((err) => {
reject(err);
});
}
catch (e) {
reject(e);
}
});
} | the_stack |
import React, {RefObject} from 'react';
import GridVisualization from './GridVisualization';
import GridForeground from './GridForeground';
import Stats from './Stats';
import GridBackground from './GridBackground';
import {Node} from '../../pathfinding/algorithms/Node';
import PathfinderBuilder from '../../pathfinding/builders/PathfinderBuilder';
import Pathfinder from '../../pathfinding/algorithms/Pathfinder';
import {euclidean} from '../../pathfinding/algorithms/Heuristics';
import TerrainGeneratorBuilder, {RANDOM_TERRAIN} from '../../pathfinding/builders/TerrainGeneratorBuilder';
import {createTileData, Point, Tile, TileData} from '../../pathfinding/core/Components';
import {HashSet, stringify} from '../../pathfinding/structures/Hash';
import AppSettings from '../../utils/AppSettings';
import VirtualTimer from '../../utils/VirtualTimer';
interface IProps {
tileWidth: number,
settings: Readonly<AppSettings>,
onChangeVisualizing: (visualizing: boolean) => void;
}
interface IState {
time: number,
length: number,
cost: number,
nodes: number,
algorithm: string,
tilesX: number,
tilesY: number
}
/**
* Component to encapsulate and perform all pathfinding operations
* Exposes functions to initiate pathfinding or draw terrain
*/
class PathfindingVisualizer extends React.Component<IProps,IState>
{
//references to expose background and foreground grids to parent
private background: RefObject<GridVisualization> = React.createRef();
private foreground: RefObject<GridForeground> = React.createRef();
private visualized = false;
private visualizing = false;
private visualTimeouts: VirtualTimer[] = [];
private generations: Node[] = [];
private paused = false;
private wasPaused = false; //paused before alt tab?
private mazeTile: TileData = createTileData(true);
private readonly tileWidth: number
constructor(props: IProps) {
super(props);
const w = document.documentElement.clientWidth;
const h = document.documentElement.clientHeight;
this.tileWidth = this.props.tileWidth;
const tilesX = Math.floor(w / this.tileWidth) + 1;
const tilesY = Math.floor((h - 75 - 30) / this.tileWidth) + 1;
this.state = {
time: -1,
length: -1,
cost: -1,
nodes: -1,
algorithm: '',
tilesX: tilesX,
tilesY: tilesY
}
}
onWindowResize = () => {
const w = document.documentElement.clientWidth;
const h = document.documentElement.clientHeight;
const tilesX = Math.floor(w / this.tileWidth) + 1;
const tilesY = Math.floor((h - 75 - 30) / this.tileWidth) + 1;
this.setState(prevState => ({
tilesX: prevState.tilesX < tilesX ? tilesX : prevState.tilesX,
tilesY: prevState.tilesY < tilesY ? tilesY : prevState.tilesY
}));
}
onWindowBlur = () => {
this.wasPaused = this.isPaused();
if(!this.wasPaused) {
this.pausePathfinding();
}
}
onWindowFocus = () => {
if(this.isPaused() && !this.wasPaused) {
this.resumePathfinding();
}
}
/**
* Automatically pause/resume the visualization when user alt tabs
*/
componentDidMount() {
window.addEventListener('resize', this.onWindowResize);
window.addEventListener('blur', this.onWindowBlur);
window.addEventListener('focus', this.onWindowFocus);
}
componentWillUnmount() {
window.removeEventListener('resize', this.onWindowResize);
window.removeEventListener('blur', this.onWindowBlur);
window.removeEventListener('focus', this.onWindowFocus);
}
/**
* Prevents pathfinding grid from being updated unless the algorithm stats
* have changed (meaning an algorithm was visualized)
* Doesn't prevent Foreground and background from being updated automatically
* when their state changes
* @param nextProps
* @param nextState
*/
shouldComponentUpdate(nextProps: Readonly<IProps>, nextState: Readonly<IState>) {
const prevState = this.state;
const prevProps = this.props;
return JSON.stringify(prevState) !== JSON.stringify(nextState) ||
JSON.stringify(prevProps) !== JSON.stringify(nextProps);
}
changeTile(data: TileData) {
this.mazeTile = data; //enables weighted terrain
this.foreground.current!.changeTile(data);
}
isPaused() {
return this.paused;
}
/**
* Pause the delayed pathfinding algorithm being performed
*/
pausePathfinding() {
this.paused = true;
for(const timeout of this.visualTimeouts) {
timeout.pause();
}
}
/**
* Resume the delayed pathfinding algorithm being performed
* Will reset the timeouts to the last time the timeout was paused/started
* if not properly called while the timeout is paused
*/
resumePathfinding() {
this.paused = false;
for(const timeout of this.visualTimeouts) {
timeout.resume();
}
}
/**
* Performs the pathfinding algorithm on the grid and visualizes it
*/
doPathfinding() {
this.clearPath();
const settings = this.props.settings;
const pathfinder = this.getPathfinder(settings);
const path = this.findPath(pathfinder);
this.generations = pathfinder.getRecentGenerations();
this.visualizeGenerations(this.generations);
this.addArrowGenerations(this.generations);
this.drawPath(path);
}
/**
* Performs the pathfinding algorithm on the grid and visualizes it with delays between successive
* node generations
* If the grid is currently visualizing, the visualization stops instead
*/
doDelayedPathfinding() {
const settings = this.props.settings;
const background = this.background.current!;
background.enableAnimations();
this.paused = false;
this.clearVisualization();
this.clearPath();
this.visualized = false;
const foreground = this.foreground.current!;
foreground.toggleDisable();
if(!this.visualizing) { //start visualization if not visualizing
this.visualizing = true;
this.props.onChangeVisualizing(this.visualizing);
const pathfinder = this.getPathfinder(settings);
const path = this.findPath(pathfinder);
const promises: Promise<VirtualTimer>[] = []; //to call function when timeouts finish
this.visualTimeouts = [];
const baseIncrement = settings.delayInc;
let delay = 0;
this.generations = pathfinder.getRecentGenerations();
const generationSet = new HashSet(); //to keep track of rediscovered nodes
this.generations.forEach((generation) => {
const promise = new Promise<VirtualTimer>((resolve) => {
//each generation gets a higher timeout
const timeout = new VirtualTimer(() => {
this.visualizeGenerationAndArrows(generation);
resolve(timeout);
}, delay);
this.visualTimeouts.push(timeout);
});
promises.push(promise);
if(!generationSet.has(stringify(generation.tile.point))) {
//rediscovered nodes shouldn't add a delay to visualization
delay += baseIncrement;
}
generationSet.add(stringify(generation.tile.point));
});
//call functions when timeouts finish
Promise.all(promises).then(() => {
this.drawPath(path);
foreground.toggleDisable();
this.visualizing = false;
this.visualized = true;
this.props.onChangeVisualizing(this.visualizing);
background.disableAnimations();
});
} else { //stop visualizing if currently visualizing
for (const timeout of this.visualTimeouts) {
timeout.clear();
}
this.visualizing = false;
this.props.onChangeVisualizing(this.visualizing);
}
}
/**
* Get the pathfinder for the settings
* @param settings
*/
getPathfinder(settings: AppSettings) {
const algorithmKey = settings.algorithm;
const algorithm = settings.bidirectional && PathfinderBuilder.hasBidirectional(algorithmKey) ?
PathfinderBuilder.makeBidirectional(algorithmKey) : algorithmKey;
return new PathfinderBuilder(this.foreground.current!.state.grid)
.setAlgorithm(algorithm)
.setHeuristic(settings.heuristicKey)
.setNavigator(settings.navigatorKey)
.build();
}
/**
* Find path with a given pathfinder, includes benchmarking
* @param pathfinder
*/
findPath(pathfinder: Pathfinder) {
const foreground = this.foreground.current!;
const t0 = performance.now();
const path = pathfinder.findPath(foreground.state.initial, foreground.state.goal);
const t1 = performance.now();
const t2 = t1 - t0;
this.setState({
time: t2,
nodes: pathfinder.getRecentNodes(),
length: calcLength(foreground.state.initial, path),
cost: calcCost(foreground.state.grid.get(foreground.state.initial), path),
algorithm: pathfinder.getAlgorithmName()
});
return path;
}
/**
* Draw path on the grid and change length on ui
* @param path
*/
drawPath(path: Tile[]) {
const foreground = this.foreground.current!
path.unshift(this.foreground.current!.state.grid.get(foreground.state.initial));
this.foreground.current!.drawPath(path);
}
/**
* Called when child foreground moves a tile
*/
onTilesDragged() {
if(this.visualized) {
this.clearVisualization();
this.doPathfinding();
this.visualized = true;
}
}
/**
* Create terrain on the grid foreground
*/
createTerrain(mazeType: number, useMazeTile: boolean) {
if(this.visualizing) {
return;
}
this.clearTiles();
this.clearPath();
this.clearVisualization();
const foreground = this.foreground.current!;
const end = this.calcEndPointInView();
const newState = (mazeType !== RANDOM_TERRAIN) ? {
initial: {
x: 1, y: 1
},
goal: {
x: end.x-2, y: end.y-2
}
} : {
initial: {
x: 1, y: ((end.y-1) / 2) >> 0
},
goal: {
x: end.x-2, y: ((end.y-1) / 2) >> 0
}
};
foreground.setState(newState,() => {
const prevGrid = foreground.state.grid;
const generator = new TerrainGeneratorBuilder()
.setDimensions(
prevGrid.getWidth(),
prevGrid.getHeight()
)
.setGeneratorType(mazeType)
.setIgnorePoints([foreground.state.initial, foreground.state.goal])
.setTileData(useMazeTile ? this.mazeTile : getSolid())
.build();
const topLeft = {
x: 1, y: 1
};
const bottomRight = {
x: end.x-2, y: end.y-2
};
const grid = generator.generateTerrain(topLeft, bottomRight);
foreground.drawGrid(grid);
});
}
/**
* Calculate the end/goal point in view of the screen
* Used to calculate the terrain dimensions
*/
calcEndPointInView() {
const end = this.calcEndPoint();
const xEnd = end.x;
const yEnd = end.y;
const xFloor = Math.floor(xEnd);
const yFloor = Math.floor(yEnd);
const xDecimal = xEnd - xFloor;
const yDecimal = yEnd - yFloor;
let x = xDecimal > 0.05 ? Math.ceil(xEnd) : xFloor;
let y = yDecimal > 0.05 ? Math.ceil(yEnd) : yFloor;
if(x > this.state.tilesX) {
x = this.state.tilesX
}
if(y > this.state.tilesY) {
y = this.state.tilesY
}
return {
x: x, y: y
}
}
calcEndPoint() {
const xEnd = Math.round(document.documentElement.clientWidth / this.tileWidth);
const yEnd = Math.round((document.documentElement.clientHeight - 30 - 75) / this.tileWidth);
return {
x: xEnd, y: yEnd
}
}
resetPoints() {
if(!this.visualizing) {
this.foreground.current!.resetPoints();
}
}
clearPath = () => {
this.foreground.current!.erasePath();
}
clearTiles() {
this.foreground.current!.clearTiles();
}
clearTilesChecked() {
if(!this.visualizing) {
this.foreground.current!.clearTiles();
}
}
clearVisualization() {
this.visualized = false;
this.background.current!.clear();
}
clearVisualizationChecked() {
if(!this.visualizing) {
this.visualized = false;
this.background.current!.clear();
}
}
visualizeGenerations(generations: Node[]) {
this.background.current!.visualizeGenerations(generations);
this.visualized = true;
}
addArrowGenerations(generations: Node[]) {
this.background.current!.addArrowGenerations(generations);
}
visualizeGenerationAndArrows(generation: Node) {
this.background.current!.visualizeGenerationAndArrows(generation);
}
/**
* Renders the sub components of the visualizer needed to show
* the algorithm stats,
* the grid itself,
* the visualization of the algorithm,
* and the maze the pathfinder solves
*/
render() {
return (
<div>
<Stats
algorithm={this.state.algorithm}
length={this.state.length}
cost={this.state.cost}
time={this.state.time}
nodes={this.state.nodes}
/>
<div>
<GridBackground
tileWidth={this.tileWidth}
width={this.state.tilesX}
height={this.state.tilesY}
/>
<GridVisualization
ref={this.background}
settings={this.props.settings}
tileWidth={this.tileWidth}
width={this.state.tilesX}
height={this.state.tilesY}
/>
<GridForeground
ref={this.foreground}
onTilesDragged={() => this.onTilesDragged()}
tileSize={this.tileWidth}
width={this.state.tilesX}
height={this.state.tilesY}
end={this.calcEndPoint()}
/>
</div>
</div>
);
}
}
function getSolid() {
return {
pathCost: 1,
isSolid: true
}
}
function calcLength(initial: Point, path: Tile[]) {
if(path.length === 0) {
return 0;
}
let len = euclidean(initial, path[0].point);
for (let i = 0; i < path.length - 1; i++) {
len += euclidean(path[i].point, path[i + 1].point);
}
return +(len).toFixed(3);
}
function calcCost(initial: Tile, path: Tile[]) {
if(path.length === 0) {
return 0;
}
let len = euclidean(initial.point, path[0].point) * path[0].data.pathCost;
for (let i = 0; i < path.length - 1; i++) {
len += euclidean(path[i].point, path[i + 1].point) * path[i + 1].data.pathCost;
}
return +(len).toFixed(3);
}
export default PathfindingVisualizer; | the_stack |
'use strict';
import {Position, Range} from 'vscode-languageserver';
// 'sticky' flag is not yet supported :()
const lineEndingRE = /([^\r\n]*)(\r\n|\r|\n)?/;
export interface RangeDelta {
start: Position;
end: Position;
linesDelta: number;
charactersDelta: number; // delta for positions on the same line as the end position
}
export function positionIsEqual(pos1: Position, pos2: Position) : boolean {
return pos1.line===pos2.line && pos1.character === pos2.character;
}
export function positionIsBefore(pos1: Position, pos2: Position) : boolean {
return (pos1.line < pos2.line || (pos1.line===pos2.line && pos1.character < pos2.character));
}
export function positionIsBeforeOrEqual(pos1: Position, pos2: Position) : boolean {
return (pos1.line < pos2.line || (pos1.line===pos2.line && pos1.character <= pos2.character));
}
export function positionIsAfter(pos1: Position, pos2: Position) : boolean {
return (pos1.line > pos2.line || (pos1.line===pos2.line && pos1.character > pos2.character));
}
export function positionIsAfterOrEqual(pos1: Position, pos2: Position) : boolean {
return (pos1.line > pos2.line || (pos1.line===pos2.line && pos1.character >= pos2.character));
}
export function rangeContains(range: Range, pos: Position) : boolean {
return !positionIsBefore(pos,range.start) && positionIsBefore(pos,range.end);
}
export function rangeContainsOrTouches(range: Range, pos: Position) : boolean {
return !positionIsBeforeOrEqual(pos,range.start) && positionIsBeforeOrEqual(pos,range.end);
}
export function rangeIntersects(range1: Range, range2: Range) : boolean {
return rangeContains(range1,range2.start) || rangeContains(range1,range2.end);
}
export function rangeTouches(range1: Range, range2: Range) : boolean {
return rangeContainsOrTouches(range1,range2.start) || rangeContainsOrTouches(range1,range2.end);
}
export function rangeToString(r: Range) {
return `${r.start.line}:${r.start.character}-${r.end.line}:${r.end.character}`;
}
// enum PositionComparison {
// Before = 0,
// Equal = 1,
// After = 2,
// }
// export function comparePositions(pos1: Position, pos2: Position) : PositionComparison {
// if(pos1.line < pos2.line)
// return PositionComparison.Before;
// else if(pos1.line > pos2.line)
// return PositionComparison.After;
// else if(pos1.character < pos2.character)
// return PositionComparison.Before;
// else if(pos1.character > pos2.character)
// return PositionComparison.After;
// else
// return PositionComparison.Equal;
// }
// enum PositionRangeIntersection {
// Before = 1 << 0, // 001
// Within = 1 << 1, // 010
// After = 1 << 2, // 100
// AtStart = 3, // 011
// AtEnd = 1 << 1, // 10
// }
// export function positionRangeIntersection(pos: Position, range: Range) : PositionRangeIntersection {
// switch(comparePositions(pos,range.start)) {
// case PositionComparison.Before:
// return PositionRangeIntersection.Before;
// case PositionComparison.Equal:
// case PositionComparison.After:
// // pos.line >= range.end.line
// if(pos.line > range.end.line || pos.character > range.end.character)
// return PositionRangeIntersection.After;
// else
// return PositionRangeIntersection.Within;
// }
// }
// enum EndPositionRangeIntersection {
// EndBefore = 1,
// EndAfter = 2,
// EndWithin = 3,
// }
// export function endPositionRangeIntersection(pos: Position, range: Range) : EndPositionRangeIntersection {
// switch(comparePositions(pos,range.start)) {
// case PositionComparison.Before:
// case PositionComparison.Equal:
// return EndPositionRangeIntersection.EndBefore;
// case PositionComparison.After:
// // pos.line >= range.end.line
// if(pos.line > range.end.line || pos.character > range.end.character)
// return EndPositionRangeIntersection.EndAfter;
// else
// return EndPositionRangeIntersection.EndWithin;
// }
// }
// enum RangeIntersection {
// StartBefore = PositionRangeIntersection.Before, // 1 = 0001
// StartAfter = PositionRangeIntersection.After, // 2 = 0010
// StartWithin = PositionRangeIntersection.Within, // 3 = 0011
// EndBefore = EndPositionRangeIntersection.EndBefore, // 1 << 2 = 0100
// EndAfter = EndPositionRangeIntersection.EndAfter, // 2 << 2 = 1000
// EndWithin = EndPositionRangeIntersection.EndWithin, // 3 << 2 = 1100
// /** Ex: [++++ ----] or [++++----] */
// Before = StartBefore | EndBefore,
// /** Ex: [+++**---] */
// OverlapBefore = StartBefore | EndWithin,
// /** Ex: [+++***] or [+++***+++] or [***+++] */
// Contains,
// /** Ex: [****] */
// Equal,
// /** Ex: [---***] or [---***] or [---***---] */
// Within,
// /** Ex: [---**+++] */
// OverlapAfter,
// /** Ex: [---- ++++] or [----++++] */
// After
// }
// export function rangeIntersection(range1: Range, range2: Range) : RangeIntersection {
// let result = <number>comparePositions(range1.start,range2.start) | (<number>comparePositions(range1.start,range2.start)) << 3;
// if(result & RangeIntersection.StartLT || result & RangeIntersection.StartEq)
// result|= RangeIntersection.StartLE;
// else if(result & RangeIntersection.StartGT || result & RangeIntersection.StartEq)
// result|= RangeIntersection.StartGE;
// if(result & RangeIntersection.EndLT || result & RangeIntersection.StartEq)
// result|= RangeIntersection.StartLE;
// else if(result & RangeIntersection.StartGT || result & RangeIntersection.StartEq)
// result|= RangeIntersection.StartGE;
// return result;
// }
/** Calculates the offset into text of pos, where textStart is the position where text starts and both pos and textStart are absolute positions
* @return the offset into text indicated by pos, or -1 if pos is out of range
*
* 'abc\ndef'
* 'acbX\ndef'
* +++*** --> +++_***
* */
export function relativeOffsetAtAbsolutePosition(text: string, textStart: Position, pos: Position) : number {
let line = textStart.line;
let currentOffset = 0;
// count the relative lines and offset w.r.t text
while(line < pos.line) {
const match = lineEndingRE.exec(text.substring(currentOffset));
++line; // there was a new line
currentOffset += match[0].length;
}
if(line > pos.line)
return -1
else if(textStart.line === pos.line)
return Math.max(-1, pos.character - textStart.character);
else // if(line === pos.line)
return Math.max(-1, pos.character + currentOffset);
}
export function offsetAt(text: string, pos: Position) : number {
let line = pos.line;
let lastIndex = 0;
while (line > 0) {
const match = lineEndingRE.exec(text.substring(lastIndex));
if(match[2] === '' || match[2] === undefined) // no line-ending found
return -1; // the position is beyond the length of text
else {
lastIndex+= match[0].length;
--line;
}
}
return lastIndex + pos.character;
}
/**
* @returns the Position (line, column) for the location (character position), assuming that text begins at start
*/
export function positionAtRelative(start: Position, text: string, offset: number) : Position {
if(offset > text.length)
offset = text.length;
let line = start.line;
let currentOffset = 0; // offset into text we are current at; <= `offset`
let lineOffset = start.character;
while(true) {
const match = lineEndingRE.exec(text.substring(currentOffset));
// match[0] -- characters plus newline
// match[1] -- characters up to newline
// match[2] -- newline (\n, \r, or \r\n)
if(!match || match[0].length === 0 || currentOffset + match[1].length >= offset)
return Position.create(line, lineOffset + Math.max(offset - currentOffset, 0))
currentOffset+= match[0].length;
lineOffset = 0;
++line;
}
}
/**
* @returns the Position (line, column) for the location (character position), assuming that text begins at start.
*
* @param offset -- counts all newlines (e.g. '\r\n') as *one character*
*/
export function positionAtRelativeCNL(start: Position, text: string, offset: number) : Position {
if(offset > text.length) {
return positionAtRelative(start, text, text.length);
}
let line = start.line;
let currentOffset = 0; // offset into text we are current at; <= `offset`
let lineOffset = start.character;
while(true) {
const match = lineEndingRE.exec(text.substring(currentOffset));
// match[0] -- characters plus newline
// match[1] -- characters up to newline
// match[2] -- newline (\n, \r, or \r\n)
if(!match || match[0].length === 0 || match[1].length >= offset)
return Position.create(line, lineOffset + offset)
currentOffset+= match[0].length;
offset -= match[1].length + (match[2]===undefined ? 0 : 1);
lineOffset = 0;
++line;
}
}
/**
* @returns the Position (line, column) for the location (character position)
*/
export function positionAt(text: string, offset: number) : Position {
if(offset > text.length)
offset = text.length;
let line = 0;
let lastIndex = 0;
while(true) {
const match = lineEndingRE.exec(text.substring(lastIndex));
if(lastIndex + match[1].length >= offset)
return Position.create(line, Math.max(offset - lastIndex,0))
lastIndex+= match[0].length;
++line;
}
}
/**
* @returns the lines and characters represented by the text
*/
export function toRangeDelta(oldRange:Range, text: string) : RangeDelta {
const newEnd = positionAt(text,text.length);
let charsDelta;
if(oldRange.start.line === oldRange.end.line)
charsDelta = newEnd.character - (oldRange.end.character-oldRange.start.character);
else
charsDelta = newEnd.character - oldRange.end.character;
return {
start: oldRange.start,
end: oldRange.end,
linesDelta: newEnd.line-(oldRange.end.line-oldRange.start.line),
charactersDelta: charsDelta
};
}
export function positionRangeDeltaTranslate(pos: Position, delta: RangeDelta) : Position {
if(positionIsBefore(pos,delta.end))
return pos;
else if (delta.end.line === pos.line) {
let x = pos.character + delta.charactersDelta;
if (delta.linesDelta > 0)
x = x - delta.end.character;
else if (delta.start.line === delta.end.line + delta.linesDelta && delta.linesDelta < 0)
x = x + delta.start.character;
return Position.create(pos.line + delta.linesDelta, x);
}
else // if(pos.line > delta.end.line)
return Position.create(pos.line + delta.linesDelta, pos.character);
}
export function positionRangeDeltaTranslateEnd(pos: Position, delta: RangeDelta) : Position {
if(positionIsBeforeOrEqual(pos,delta.start))
return pos;
else {
// Calculate the shifted position
let result : Position;
if (delta.end.line === pos.line) {
let x = pos.character + delta.charactersDelta;
if (delta.linesDelta > 0)
x = x - delta.end.character;
else if (delta.start.line === delta.end.line + delta.linesDelta && delta.linesDelta < 0)
x = x + delta.start.character;
result = Position.create(pos.line + delta.linesDelta, x);
} else // if(pos.line > delta.end.line)
result = Position.create(pos.line + delta.linesDelta, pos.character);
// But do not move above that delta's start position
if(positionIsBefore(result,delta.start))
return delta.start;
else
return result;
}
// if(positionIsEqual(pos,delta.end) && (delta.linesDelta > 0 || (delta.linesDelta == 0 && delta.charactersDelta > 0)))
// return pos; // equal, but the change is extending from the end instead of moving intop the end
// else if (delta.end.line === pos.line) {
// let x = pos.character + delta.charactersDelta;
// if (delta.linesDelta > 0)
// x = x - delta.end.character;
// else if (delta.start.line === delta.end.line + delta.linesDelta && delta.linesDelta < 0)
// x = x + delta.start.character;
// return Position.create(pos.line + delta.linesDelta, x);
// }
// else // if(pos.line > delta.end.line)
// return Position.create(pos.line + delta.linesDelta, pos.character);
}
export function rangeDeltaTranslate(range: Range, delta: RangeDelta) {
return Range.create(
positionRangeDeltaTranslate(range.start, delta),
positionRangeDeltaTranslateEnd(range.end, delta)
)
}
/** Sums the two positions. In effect, gets the absolute position of `relPos`.
* @param absPos -- position at which `relPos` is relative to
* @param relPos -- a relative position
*/
export function positionTranslateRelative(absPos: Position, relPos: Position) {
if(relPos.line === 0)
return Position.create(absPos.line, absPos.character+relPos.character);
else
return Position.create(absPos.line+relPos.line, relPos.character);
}
/** Converts `relRange` from a relative range w.r.t. `absPos` to an absolute range.
* @param absPos -- position at which `relRange` is relative to
* @param relRange -- a range, relative to absPos
*/
export function rangeTranslateRelative(absPos: Position, relRange: Range) {
return Range.create(positionTranslateRelative(absPos, relRange.start), positionTranslateRelative(absPos, relRange.end))
} | the_stack |
import { Canvas } from "./Canvas";
import { join, basename } from "path";
import { promise as glob } from "glob-promise";
import { URL } from "url";
import {
cloneJson,
compare,
fileExists,
formatMetadata,
getLabel,
getThumbnail,
hasManifestsYml,
log,
readYml,
warn,
writeJson,
} from "./Utils";
// import urljoin from "url-join";
const urljoin = require("url-join");
// boilerplate json
import canvasBoilerplate from "./boilerplate/canvas.json";
import collectionBoilerplate from "./boilerplate/collection.json";
import collectionItemBoilerplate from "./boilerplate/collectionitem.json";
import manifestBoilerplate from "./boilerplate/manifest.json";
import manifestItemBoilerplate from "./boilerplate/manifestitem.json";
import thumbnailBoilerplate from "./boilerplate/thumbnail.json";
export class Directory {
public directories: Directory[] = [];
public directoryFilePath: string;
public generateThumbs: boolean;
public indexJson: any;
public infoYml: any;
public isCanvas: boolean = false;
public isCollection: boolean = false;
public isManifest: boolean = false;
public items: Canvas[] = [];
public name: string;
public parentDirectory: Directory | undefined;
public url: URL;
public virtualName: string | undefined; // used when root directories are dat/ipfs keys
constructor(
directoryFilePath: string,
url: string,
virtualName?: string,
parentDirectory?: Directory
) {
this.directoryFilePath = directoryFilePath;
this.url = new URL(url);
this.parentDirectory = parentDirectory;
this.virtualName = virtualName;
}
public async read(): Promise<void> {
// canvases are directories starting with an underscore
const canvasesPattern: string = this.directoryFilePath + "/_*";
const canvases: string[] = await glob(canvasesPattern, {
ignore: ["**/*.yml", "**/thumb.*", "**/!*"],
});
// sort canvases
canvases.sort((a, b) => {
return compare(a, b);
});
await Promise.all(
canvases.map(async (canvas: string) => {
log(`creating canvas for: ${canvas}`);
this.items.push(new Canvas(canvas, this));
})
);
// directories not starting with an underscore
// these can be child manifests or child collections
const directoriesPattern: string = this.directoryFilePath + "/*";
const directories: string[] = await glob(directoriesPattern, {
ignore: [
"**/*.{crt,drc,epub,glb,gltf,gz,stl,jpg,jpeg,json,md,mp3,mp4,nii,obj,opf,pdf,ply,png,toml,usdz,vtt,yml}", // ignore files (must include file extensions explicitly, otherwise directories with a . are matched)
"**/_*", // ignore canvas folders
"**/+*", // ignore generated folders
"**/!*", // ignore folders starting with a !
],
});
// sort
directories.sort((a, b) => {
return compare(a, b);
});
if (canvases.length) {
this.isManifest = true;
} else if (directories.length > 0 ||
(await hasManifestsYml(this.directoryFilePath))) {
this.isCollection = true;
}
await Promise.all(
directories.map(async (directory: string) => {
log(`creating directory for: ${directory}`);
const name: string = basename(directory);
const url: string = urljoin(this.url.href, name);
const newDirectory: Directory = new Directory(
directory,
url,
undefined,
this
);
await newDirectory.read();
this.directories.push(newDirectory);
})
);
// if there are no canvas, manifest, or collection directories to read,
// but there are paintable files in the current directory,
// create a canvas for each.
if (!this.directories.length && !canvases.length) {
const paintableFiles: string[] = await glob(this.directoryFilePath + "/*.*", {
ignore: ["**/*.yml", "**/thumb.*", "**/index.json"],
});
// sort files
paintableFiles.sort((a, b) => {
return compare(a, b);
});
paintableFiles.forEach((file: string) => {
log(`creating canvas for: ${file}`);
this.items.push(new Canvas(file, this));
});
}
await this._getInfo();
await this._createIndexJson();
if (this.isCollection) {
log(`created collection: ${this.directoryFilePath}`);
// if there are canvases, warn that they are being ignored
if (this.items.length) {
warn(
`${this.items.length} unused canvas directories (starting with an underscore) found in the ${this.directoryFilePath} collection. Remove directories not starting with an underscore to convert into a manifest.`
);
}
} else {
log(`created manifest: ${this.directoryFilePath}`);
// if there aren't any canvases, warn that there should be
if (!this.items.length) {
warn(
`${this.directoryFilePath} is a manifest, but no canvases (directories starting with an underscore) were found. Therefore it will not have any content.`
);
}
}
}
private async _getInfo(): Promise<void> {
this.infoYml = {};
// if there's an info.yml
const ymlPath: string = join(this.directoryFilePath, "info.yml");
const exists: boolean = await fileExists(ymlPath);
if (exists) {
this.infoYml = await readYml(ymlPath);
log(`got metadata for: ${this.directoryFilePath}`);
} else {
log(`no metadata found for: ${this.directoryFilePath}`);
}
if (!this.infoYml.label) {
// default to the directory name
this.infoYml.label = basename(this.directoryFilePath);
}
}
private async _createIndexJson(): Promise<void> {
if (this.isCollection) {
this.indexJson = cloneJson(collectionBoilerplate);
// for each child directory, add a collectionitem or manifestitem json boilerplate to items.
await Promise.all(
this.directories.map(async (directory: Directory) => {
let itemJson: any;
if (directory.isCollection) {
itemJson = cloneJson(collectionItemBoilerplate);
} else {
itemJson = cloneJson(manifestItemBoilerplate);
}
itemJson.id = urljoin(directory.url.href, "index.json");
itemJson.label = getLabel(directory.infoYml.label);
await getThumbnail(itemJson, directory);
this.indexJson.items.push(itemJson);
})
);
// check for manifests.yml. if it exists, parse and add to items
const hasYml: boolean = await hasManifestsYml(this.directoryFilePath);
if (hasYml) {
const manifestsPath: string = join(this.directoryFilePath, "manifests.yml");
const manifestsYml: any = await readYml(manifestsPath);
manifestsYml.manifests.forEach((manifest: any) => {
const itemJson: any = cloneJson(collectionItemBoilerplate);
itemJson.id = manifest.id;
if (manifest.label) {
itemJson.label = getLabel(manifest.label);
} else {
// no label supplied, use the last fragment of the url
const url: URL = new URL(itemJson.id);
const pathname: string[] = url.pathname.split("/");
if (pathname.length > 1) {
itemJson.label = getLabel(pathname[pathname.length - 2]);
}
}
if (manifest.thumbnail) {
if (typeof manifest.thumbnail === "string") {
const thumbnail: any[] = cloneJson(thumbnailBoilerplate);
thumbnail[0].id = manifest.thumbnail;
itemJson.thumbnail = thumbnail;
} else {
itemJson.thumbnail = manifest.thumbnail;
}
}
this.indexJson.items.push(itemJson);
});
log(`parsed manifests.yml for ${this.directoryFilePath}`);
} else {
log(`no manifests.yml found for: ${this.directoryFilePath}`);
}
// sort items
this.indexJson.items.sort((a, b) => {
return compare(
a.label["@none"][0].toLowerCase(),
b.label["@none"][0].toLowerCase()
);
});
} else {
this.indexJson = cloneJson(manifestBoilerplate);
// for each canvas, add canvas json
let index: number = 0;
for (const canvas of this.items) {
const canvasJson: any = cloneJson(canvasBoilerplate);
canvasJson.id = urljoin(this.url.href, "index.json/canvas", index);
canvasJson.items[0].id = urljoin(
this.url.href,
"index.json/canvas",
index,
"annotationpage/0"
);
await canvas.read(canvasJson);
// add canvas to items
this.indexJson.items.push(canvasJson);
index++;
}
this.indexJson.items.sort((a, b) => {
return compare(a.id, b.id);
});
}
this.indexJson.id = urljoin(this.url.href, "index.json");
this._applyInfo();
await getThumbnail(this.indexJson, this);
// write index.json
const path: string = join(this.directoryFilePath, "index.json");
const json: string = JSON.stringify(this.indexJson, null, " ");
log(`creating index.json for: ${this.directoryFilePath}`);
await writeJson(path, json);
}
private _applyInfo(): void {
this.indexJson.label = getLabel(this.infoYml.label); // defaults to directory name
if (this.infoYml.metadata) {
this.indexJson.metadata = formatMetadata(this.infoYml.metadata);
}
// add manifest-specific properties
if (!this.isCollection) {
if (this.infoYml.attribution) {
this.indexJson.attribution = this.infoYml.attribution;
}
if (this.infoYml.description) {
this.indexJson.description = this.infoYml.description;
}
if (this.infoYml.behavior) {
this.indexJson.behavior = [];
if (Array.isArray(this.infoYml.behavior)) {
this.infoYml.behavior.forEach((behavior) => {
this.indexJson.behavior.push(behavior);
});
} else {
this.indexJson.behavior.push(this.infoYml.behavior);
}
}
}
}
} | the_stack |
// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace OneAuth {
/// Levels of logging. Defines the priority of the logged message
export enum LogLevel {
/// Available to fully disable logging
LogLevelNoLog = 1,
/// Default
LogLevelError = 2,
LogLevelWarning = 3,
LogLevelInfo = 4,
LogLevelVerbose = 5,
}
/// Flights reflecting the values from OneAuthFlight.hpp
export enum Flight {
UseMsalforMsa = 2,
// Windows Only Flights
UseWamforMSA = 1002,
UseWamforAAD = 1003,
}
export enum AccountType {
/// Microsoft personal accounts
Msa = 1,
/// Microsoft work or school accounts
Aad = 2,
/// On-premises accounts
OnPremises = 3,
}
export enum CredentialType {
/// Access token - short-lived, used to access one resource
AccessToken = 1,
/// An opaque reference to account password. Can be used to retrieve cleartext password
PasswordReference = 2,
/// Opaque Kerberos credential reference. This is the indication that Kerberos is being used for auhentication.
KerberosReference = 3,
}
export enum Status {
/// This indicates a bug in our code, in one of our dependencies, or on the server.
/// It may be caused by an unexpected error, exception, or bad data.
/// This may also indicate an API attempting to return an invalid status, in which case the attempted return
/// will be appended to the context.
/// Retrying this request will have undefined behavior. You can still call other APIs, which may succeed. Do so at
/// your own risk.
Unexpected = 0,
/// This status is reserved for future use.
Reserved = 1,
/// Authentication is possible, but it requires direct user interaction.
/// Please find an appropriate time to show a dialogue to the user by calling SignIn() or
/// AcquireTokenInteractively(). Retrying this request may return the same error, unless another application has
/// already done the above.
InteractionRequired = 2,
/// There is no network available on the host machine. This status indicates that a network request was attempted.
/// Retrying this request may return the same error, if the network state has not been fixed.
/// You can retry this request as soon as you believe the network has changed.
/// Please inform the user that their network is unavailable, and that they cannot be signed in because of it.
NoNetwork = 3,
/// The network is temporarily unavailable on the host machine. This status indicates that a network request was
/// attempted. Retrying this request may succeed without any additional effort by the user.
NetworkTemporarilyUnavailable = 4,
/// The authentication server is unavailable. This status indicates that a network request was attempted.
/// Retrying this request must be handled at exponential backoff to avoid further stressing the server.
ServerTemporarilyUnavailable = 5,
/// This request violates our API contract. This includes invalid parameters, calling a UI method on a non-UI
/// std::thread, or attempting to authenticate with an unregistered application. See the result context for
/// additional information. Retrying this request will return the same error.
ApiContractViolation = 6,
/// The request was cancelled by the user.
UserCanceled = 7,
/// The request was cancelled by the application.
ApplicationCanceled = 8,
/// The application is not able to complete this request.
/// The user should contact their IT administrator for help resolving this issue.
IncorrectConfiguration = 9,
/// The passed in buffer is too small.
InsufficientBuffer = 10,
/// The provided authority is not trusted to authenticate against.
AuthorityUntrusted = 11,
}
export enum AuthScheme {
/// HTTP Basic
Basic = 1,
/// OAuth2
Bearer = 2,
/// LiveId authentication using RPS tokens
LiveId = 3,
/// SPNEGO
Negotiate = 4,
/// Windows Challenge/Response (NTLM)
Ntlm = 5,
}
/// AppId for OneDrive and Sharepoint
export const CommonAppIdsODSP = 'com.microsoft.ODSP';
/// AppId for Office Apps: Word, Excel, Powerpoint
export const CommonAppIdsOffice = 'com.microsoft.Office';
/// AppId for Outlook
export const CommonAppIdsOutlook = 'com.microsoft.Outlook';
/// AppId for Bing
export const CommonAppIdsBing = 'com.microsoft.Bing';
/// AppId for Edge
export const CommonAppIdsEdge = 'com.microsoft.Edge';
/// AppId for Microsoft To-Do
export const CommonAppIdsToDo = 'com.microsoft.to-do';
/// AppId for Microsoft Intune Company Portal
export const CommonAppIdsCompanyPortal = 'com.microsoft.CompanyPortal';
export interface AuthResult {
readonly account: Account;
readonly credential: Credential;
readonly error: Error;
readonly correlationId: string;
}
export interface Account {
readonly id: string;
readonly accountType: AccountType;
readonly authority: string;
readonly sovereignty: string;
readonly environment: string;
readonly loginName: string;
readonly displayName: string;
readonly providerId: string;
readonly realm: string;
readonly givenName: string;
readonly middleName: string;
readonly familyName: string;
readonly email: string;
readonly phoneNumber: string;
readonly sid: string;
readonly accountHints: string[];
readonly hosts: string[];
}
export interface Credential {
readonly id: string;
readonly credentialType: CredentialType;
readonly accountId: string;
readonly authority: string;
readonly value: string;
readonly target: string;
readonly expiresOn: number;
}
export interface Error {
readonly status: Status;
readonly diagnostics: {
readonly errorCode: string | undefined;
readonly tag: string | undefined;
readonly description: string | undefined;
};
readonly toString: string | undefined;
}
export class AuthParameters {
constructor(authScheme: AuthScheme, authority: string, target: string, realm: string, accessTokenToRenew: string);
readonly authScheme: AuthScheme;
readonly authority: string;
readonly realm: string;
readonly target: string;
readonly accessTokenToRenew: string;
SetAdditionalParameter(key: string, value: string): void;
}
export class AppConfiguration {
constructor(
appId: string,
appName: string,
appVersion: string,
languageCode: string,
signInWindowTitle: string | undefined,
parentWindow: any | undefined
);
readonly appId: string;
readonly appName: string;
readonly appVersion: string;
readonly languageCode: string | undefined;
readonly signInWindowTitle: string | undefined; // Windows only
readonly parentWindow: any | undefined; // Windows only
}
export class MsaConfiguration {
/// Constructor for MsaConfiguration
/// @param clientId
/// @param redirectUri
/// @param defaultSignInScope
/// @deprecated @param useMsalFlight no longer used and has no effect @see {@link SetFlights}
constructor(
clientId: string,
redirectUri: string,
defaultSignInScope: string,
useMsalFlight: boolean | undefined // deprecated
);
readonly clientId: string;
readonly redirectUri: string;
readonly defaultSignInScope: string;
}
export class AadConfiguration {
constructor(clientId: string, redirectUri: string, defaultSignInResource: string, preferBroker: boolean);
readonly clientId: string;
readonly redirectUri: string;
readonly defaultSignInResource: string;
}
/// Configures the OneAuth module.
///
/// @param appConfiguration The OneAuth app configuration.
/// @param msaConfiguration The MSA configuration.
/// @param aadConfiguration The AAD configuration.
/// @param telemetryConfiguration The Telemetry configuration to receive telemetry dispatched events.
/// @return false if Startup fails, true otherwise.
export function initialize(
appConfiguration: AppConfiguration,
msaConfiguration: MsaConfiguration | undefined,
aadConfiguration: AadConfiguration | undefined,
telemetryConfiguration: TelemetryConfiguration | undefined
): boolean;
/// Cancels all outstanding tasks, closes the authentication UI if any, and shuts down the OneAuth authenticator.
/// Once called, acquiring authenticator instance(s) is only possible after calling the configuration API.
export function shutdown(): void;
/// Sets the language to be used within dialogs inside of OneAuth so that we may display locale correctly
/// @param code that represents the locale to be used
export function setLanguageCode(code: string): void;
/// Lists the supported locale codes within OneAuth
export function supportedLanguageCodes(): string[];
/// Returns the current language code being used
export function getLanguageCode(): string;
/// Sets Logging level for OneAuth and ADAL
/// @param level Desired logging level.
/// @return Previous logging level. If unable to return the previous logging value, will return "error" level by default.
export function setLogLevel(level: LogLevel): LogLevel;
/// The OneAuth Log Callback
/// @param level The level of the log message
/// @param message A log message describing the event that occurred
/// @param containsPii If the message might contain Personally Identifiable Information (PII) this will be true. Log messages possibly containing PII will not be sent to the callback unless piiEnabled is set to YES on the logger.
export type LogCallback = (level: LogLevel, message: string, containsPii: boolean) => void;
/// OneAuth provides a logging callback to assist diagnostics. If piiEnabled is set to NO, the callback will not be triggered for log messages that contain any user information. By default this is NO for release builds and YES for debug builds.
/// @param enabled PII on/off flag.
/// @return Previous PII on/off flag value.
export function setLogPiiEnabled(enabled: boolean): boolean;
/// Sets OneAuth Log Callback which will be called on every tracing event that meets log level and PII settings.
/// Callback implementers must ensure its performance and reliability (e.g. do not throw exceptions, do handle concurrent calls, etc).
/// @param callback Callback that is called by OneAuth logging facility.
export function setLogCallback(callback: LogCallback): void;
/// Present the sign-in UI and signs in a user to the application.
///
/// A successful sign-in returns an account. A new account is created unless there is already a matching one in the
/// local account store. Additionally, an account profile and image are read from a profile endpoint if one is
/// available and the credentials are sufficient for the operation.
///
/// **Threading:** calls from a thread other than the main thread, as well as concurrent calls, will result in a
/// {@link Status::ApiContractViolation} error.
///
/// @param accountHint Initial account hint, if you already know what account the user wants to sign in to. If this
/// argument is empty, the user will be able to supply the account hint via account collection UI.
/// @param authParameters What authentication scheme, authority, etc. should be used for authentication. This can
/// either be created from an HTTP authentication challenge (using the CreateAuthParameters API), or manually.
/// AuthParameters implicitly define the credential type. If this argument is nullptr, then modern
/// authentication is implied (e.g. AAD, MSA), and the authentication parameters are inferred from the account hint
/// provided.
/// @param correlationId An identifier that correlates other telemetry events to this event.
/// @param completion Completion (callback) that will be called once this sign in operation has been completed, for
/// both success and failure. It receives an AuthResult instance that contains either an error or contains
/// an account and a credential.
///
/// **Error statuses returned via completion**
/// - Status::ApiContractViolation
/// - Status::ApplicationCanceled
/// - Status::IncorrectConfiguration
/// - Status::NetworkTemporarilyUnavailable
/// - Status::NoNetwork
/// - Status::ServerTemporarilyUnavailable
/// - Status::UserCanceled
/// - Status::Unexpected
///
/// @see {@link AuthCompletion}
/// @see {@link AuthParameters}
/// @see {@link AuthResult}
export function signInInteractively(
accountHint: string | undefined,
authParameters: AuthParameters | undefined,
correlationId: string
): Promise<AuthResult>;
/// Sign in a user to the app silently with an account inferred from the underlying OS infrastructure, if such
/// an inference is possible.
///
/// A successful sign-in produces a new account unless the account already exists in the local account store.
/// Additionally, an account profile and image are read from a profile endpoint if one is available and the
/// credentials are sufficient.
///
/// At this moment, SignInSilently API is of limited use as it only supports Kerberos scenarios on macOS. Support for
/// other scenarios will be added soon.
///
/// @param authParameters What authentication scheme, authority, etc. should be used for authentication. This can
/// either be created from an HTTP authentication challenge (using the CreateAuthParameters API), or manually.
/// AuthParameters implicitly define the credential type. If this argument is nullptr, then default parameters will
/// be used based on the information inferred from the account hint provided, unless the sign-in is intended for an
/// on-premises resource. On-premises resources cannot be inferred automatically. The developer must specify
/// authentication parameters explicitly for on-premises sign-in scenarios.
/// @param correlationId An idetifier that correlates other telemetry events to this event.
/// @param completion Completion (callback) that will be called once this sign in operation has been completed, for
/// both success and failure. It receives an AuthResult instance that contains either an error or contains
/// an account and a credential.
///
/// **Error statuses returned via completion**
/// - Status::ApiContractViolation
/// - Status::ApplicationCanceled
/// - Status::NetworkTemporarilyUnavailable
/// - Status::NoNetwork
/// - Status::ServerTemporarilyUnavailable
/// - Status::Unexpected
///
/// @see {@link AuthCompletion}
/// @see {@link AuthParameters}
/// @see {@link AuthResult}
export function signInSilently(
authParameters: AuthParameters | undefined,
correlationId: string
): Promise<AuthResult>;
/// Show a prompt for the given account and parameters.
///
/// If credential acquisition is successful, an account profile and image are read from a profile endpoint if one
/// is available and the credentials are sufficient.
///
/// **Threading:** calls from a thread other than the main thread, as well as concurrent calls, will result in a
/// {@link Status::ApiContractViolation} error.
///
/// @param accountId The account id to acquire credentials for.
/// @param authParameters What authentication scheme, authority, etc. should be used for authentication. This can
/// either be created from an HTTP authentication challenge (using the CreateAuthParameters API), or manually.
/// AuthParameters implicitly define the credential type. If this argument is nullptr, then modern
/// authentication is implied (e.g. AAD, MSA), and the authentication parameters are inferred from the account hint
/// provided.
/// @param correlationId An idetifier that correlates other telemetry events to this event.
/// @param completion Completion (callback) that will be called once this sign in operation has been completed, for
/// both success and failure. It receives an AuthResult instance that contains either an error or contains
/// an account and a credential.
///
/// **Error statuses returned via completion**
/// - Status::ApiContractViolation
/// - Status::ApplicationCanceled
/// - Status::IncorrectConfiguration
/// - Status::NetworkTemporarilyUnavailable
/// - Status::NoNetwork
/// - Status::ServerTemporarilyUnavailable
/// - Status::UserCanceled
/// - Status::Unexpected
///
/// @see {@link AuthCompletion}
/// @see {@link AuthParameters}
/// @see {@link AuthResult}
export function acquireCredentialInteractively(
accountId: string,
authParameters: AuthParameters,
correlationId: string
): Promise<AuthResult>;
/// Acquire a credential silently for the given account and parameters.
///
/// This method will never prompt, but may fail if it cannot silently acquire a credential. If it does fail, the
/// error status may suggest resorting to interactive credential aquisition (see {@link
/// Status::InteractionRequired}).
///
/// @param accountId The account id to acquire credentials for.
/// @param authParameters What authentication scheme, authority, etc. should be used for authentication. This can
/// either be created from an HTTP authentication challenge (using the CreateAuthParameters API), or manually.
/// AuthParameters implicitly define the credential type. If this argument is nullptr, then modern
/// authentication is implied (e.g. AAD, MSA), and the authentication parameters are inferred from the account hint
/// provided.
/// @param correlationId An idetifier that correlates other telemetry events to this event.
/// @param completion Completion (callback) that will be called once this sign in operation has been completed, for
/// both success and failure. It receives an AuthResult instance that contains either an error or contains
/// an account and a credential.
///
/// **Error statuses returned via completion**
/// - Status::ApiContractViolation
/// - Status::ApplicationCanceled
/// - Status::IncorrectConfiguration
/// - Status::InteractionRequired
/// - Status::NetworkTemporarilyUnavailable
/// - Status::NoNetwork
/// - Status::ServerTemporarilyUnavailable
/// - Status::Unexpected
///
/// @see {@link AuthCompletion}
/// @see {@link AuthParameters}
/// @see {@link AuthResult}
export function acquireCredentialSilently(
accountId: string,
authParameters: AuthParameters,
correlationId: string
): Promise<AuthResult>;
/// Cancels all ongoing tasks and dismisses the UI (if any).
/// Completions for all ongoing tasks are called synchronously, i.e. before ```CancelAllTasks``` returns.
/// Completions for tasks scheduled after ```CancelAllTasks``` was called will not be executed until
/// CancelAllTasks returns control to the caller.
export function cancelAllTasks(): void;
/// Get an account for a given account id.
///
/// This API is likely to result in a blocking read from a local persistent store.
///
/// @param accountId The account id for the desired account
/// @return A shared pointer to the account.
/// @see {@link Account}
export function readAccountById(accountId: string): Promise<Account>;
/// Get all accounts known to OneAuth from local persistent store(s).
///
/// This API will get accounts from the OneAuth store and any "external" account stores, e.g. the Office or ODSP
/// identity cache. The accounts from "external" stores are de-duplicated against the OneAuth account store. Multiple
/// blocking reads from local persistent stores are likely to result from this call.
///
/// @return All accounts that OneAuth knows about.
/// @see {@link Account}
/// @see {@link GetAssociatedAccounts}
export function readAllAccounts(): Promise<Account[]>;
/// Associate an account with a specified application group.
///
/// Accounts can be associated with applications via application group identifiers. Application group identifiers are
/// arbitrary strings, each associated with a set of applications that choose to help each other identify accounts
/// that they use.
///
/// This call may result in multiple blocking local I/O operations.
///
/// @param accountId The account id belonging to the account to associate.
/// @see {@link Account}
/// @see {@link DisassociateAccount}
export function associateAccount(accountId: string): Promise<boolean>;
/// Disassociate an account from a specified application group.
///
/// This call may result in multiple blocking local I/O operations.
///
/// @param accountId The account id belonging to the account to disassociate.
/// @see {@link Account}
/// @see {@link AssociateAccount}
export function disassociateAccount(accountId: string): Promise<boolean>;
/// Get all accounts associated with the specified application groups.
///
/// This will read accounts from local OneAuth as well as "external" (e.g. Office or ODSP) stores, if any. The
/// accounts from "external" stores are de-duplicated against the OneAuth account store. This call may result in
/// multiple blocking reads from local persistent stores.
///
/// @param appGroup A list of application groups identifiers.
/// @return An array of account objects. An empty array is returned if no known accounts associated with the
/// specified app groups could be read.
/// @see {@link Account}
/// @see {@link AssociateAccount}
/// @see {@link DisassociateAccount}
/// @see {@link GetAllAccounts}
export function readAssociatedAccounts(appGroup: string[]): Promise<Account[]>;
/// Get a profile image associated with the specified account.
///
/// This API does not perform network calls to retrieve the image; the image, if any, is read from a local cache
/// only. This API may result in multiple blocking local I/O operations.
///
/// @param accountId The account id belonging to the account to get the profile image for.
/// @return An image blob as it was returned by the profile endpoint. If no image associated with the account is
/// locally available, the returned blob is empty.
/// @see {@link Account}
export function readProfileImage(accountId: string): Promise<Uint8Array>;
/// Delete all the accounts that OneAuth knows about
///
/// This is a TEST API and should not be used in production scenarios
/// This is due to the API deleting data that is not exclusive to the calling application.
/// There are no network calls involved in deleting all accounts and as such should not be blocking, allthough
/// given a lot of accounts, it may hang a few milliseconds before returning.
export function testDeleteAllAccounts(): void;
/// Set the current flights for OneAuth
/// This API needs to be called before initializing OneAuth
/// Once OneAuth has been initialized this will have no effect on the flights that are set till it is
/// shut down and started again.
/// This will override anything that has already been set.
///
/// This call should not be blocking and should return instantly
/// @param should be an array containing the corresponding @see {@link Flights} to be activated based on the enum defined here
export function setFlights(flights: Array<Flight>): void;
/// Get the current flights that have been set on OneAuth
///
/// This call should not be blocking and should return instantly
/// @return will be an array of flights corresponding to the correct enum of Flights defined here
export function getFlights(): Promise<Array<Flight>>;
export enum AudienceType {
Automation = 0,
Preproduction = 1,
Production = 2,
}
/// Callback function that receives data from OneAuth library that is meant to be sent using Aria SDK.
/// https://authtelemetry.visualstudio.com/Microsoft%20Auth%20Telemetry%20System/_wiki/wikis/Microsoft%20Auth%20Telemetry%20System.wiki/28/Win32?anchor=setting-up-your-telemetry-dispatcher
///
/// @param data The data that needs to be sent to the telemetry server.
export type TelemetryDispatcher = (data: Data) => void;
export interface TelemetryConfigurationConstructor {
new (
audienceType: AudienceType,
sessionId: string,
dispatcher: TelemetryDispatcher | undefined,
allowedResources: string[]
): TelemetryConfiguration;
}
export interface TelemetryConfiguration extends TelemetryConfigurationConstructor {
readonly audienceType: AudienceType;
readonly sessionId: string;
readonly telemetryDispatcher: TelemetryDispatcher | undefined;
readonly allowedResources: string[];
}
export interface StringMap {
readonly [key: string]: string;
}
export interface IntMap {
readonly [property: string]: number;
}
export interface BooleanMap {
readonly [property: string]: boolean;
}
export interface Data {
readonly name: string;
readonly isInstrumentationError: boolean;
readonly stringMap: StringMap;
readonly intMap: IntMap;
readonly int64Map: IntMap;
readonly boolMap: BooleanMap;
}
} | the_stack |
import { FirebaseFunctionsRateLimiterConfiguration } from "./FirebaseFunctionsRateLimiterConfiguration";
import { GenericRateLimiter } from "./GenericRateLimiter";
import { PersistenceProviderMock } from "./persistence/PersistenceProviderMock";
import { TimestampProviderMock } from "./timestamp/TimestampProviderMock.test";
import { expect, sinon, _ } from "./_test/test_environment";
const sampleConfiguration: FirebaseFunctionsRateLimiterConfiguration.ConfigurationFull = {
name: "rate_limiter_1",
periodSeconds: 5 * 60,
maxCalls: 1,
debug: false,
};
const sampleQualifier = "samplequalifier";
describe("GenericRateLimiter", () => {
function mock(configChanges: object) {
const persistenceProviderMock: PersistenceProviderMock = new PersistenceProviderMock();
persistenceProviderMock.persistenceObject = {};
const timestampProviderMock = new TimestampProviderMock();
const genericRateLimiter = new GenericRateLimiter(
{ ...sampleConfiguration, ...configChanges },
persistenceProviderMock,
timestampProviderMock,
);
return { genericRateLimiter, timestampProviderMock, persistenceProviderMock };
}
describe("#isQuotaAlreadyExceededDoNotRecordCall", () => {
it("Calls get on PersistenceProvider", async () => {
const { genericRateLimiter, persistenceProviderMock } = mock({});
persistenceProviderMock.get = sinon.spy(persistenceProviderMock.get);
await genericRateLimiter.isQuotaAlreadyExceededDoNotRecordCall(sampleQualifier);
expect((persistenceProviderMock.get as sinon.SinonSpy).callCount, "get call count").to.be.equal(1);
});
});
describe("#isQuotaExceededOrRecordCall", () => {
it("Quota is not exceeded on first call when maxCalls=1", async () => {
const { genericRateLimiter } = mock({ maxCalls: 1 });
expect(await genericRateLimiter.isQuotaExceededOrRecordCall(sampleQualifier)).to.be.equal(false);
});
it("Does not fail on empty collection", async () => {
const { genericRateLimiter } = mock({});
await genericRateLimiter.isQuotaExceededOrRecordCall(sampleQualifier);
});
it("Calls updateAndGet on PersistenceProvider", async () => {
const { genericRateLimiter, persistenceProviderMock } = mock({});
persistenceProviderMock.updateAndGet = sinon.spy(persistenceProviderMock.updateAndGet);
await genericRateLimiter.isQuotaExceededOrRecordCall(sampleQualifier);
expect(
(persistenceProviderMock.updateAndGet as sinon.SinonSpy).callCount,
"updateAndGet call count",
).to.be.equal(1);
});
it("Puts new current timestamp when quota was not exceeded", async () => {
const { genericRateLimiter, persistenceProviderMock, timestampProviderMock } = mock({});
const sampleTimestamp = _.random(10, 5000);
timestampProviderMock.setTimestampSeconds(sampleTimestamp);
await genericRateLimiter.isQuotaExceededOrRecordCall(sampleQualifier);
expect(_.values(persistenceProviderMock.persistenceObject)[0].u).to.contain(sampleTimestamp);
});
it("does not put current timestamp when quota was exceeded", async () => {
const { genericRateLimiter, persistenceProviderMock, timestampProviderMock } = mock({
maxCalls: 1,
periodSeconds: 20,
});
const sampleTimestamp = _.random(10, 5000);
timestampProviderMock.setTimestampSeconds(sampleTimestamp);
const quotaExceeded1 = await genericRateLimiter.isQuotaExceededOrRecordCall(sampleQualifier);
expect(quotaExceeded1).to.be.equal(false);
timestampProviderMock.setTimestampSeconds(sampleTimestamp + 1);
const quotaExceeded2 = await genericRateLimiter.isQuotaExceededOrRecordCall(sampleQualifier);
expect(quotaExceeded2).to.be.equal(true);
expect(_.values(persistenceProviderMock.persistenceObject)[0].u)
.to.be.an("array")
.with.length(1);
});
describe("threshold tests", () => {
const savedTimestamps: number[] = [];
const persistenceProviderMock: PersistenceProviderMock = new PersistenceProviderMock();
before(async () => {
const timestampProviderMock = new TimestampProviderMock();
const periodSeconds = 5;
const maxCalls = 10;
const genericRateLimiter = new GenericRateLimiter(
{ ...sampleConfiguration, periodSeconds, maxCalls },
persistenceProviderMock,
timestampProviderMock,
);
let timestamp = _.random(10, 5000);
for (let i = 0; i < 6; i++) {
timestampProviderMock.setTimestampSeconds(timestamp);
savedTimestamps.push(timestamp);
await genericRateLimiter.isQuotaExceededOrRecordCall(sampleQualifier);
timestamp += periodSeconds / 3 + 0.1; // remember: never push floats to the edges ;)
}
});
it("saved record does not contain timestamps below threshold", () => {
expect(_.values(persistenceProviderMock.persistenceObject)[0].u)
.to.be.an("array")
.with.length(3)
.that.contains(savedTimestamps[savedTimestamps.length - 1])
.and.contains(savedTimestamps[savedTimestamps.length - 2])
.and.contains(savedTimestamps[savedTimestamps.length - 3]);
});
it("saved record contains all timestamps above or equal threshold", () => {
expect(_.values(persistenceProviderMock.persistenceObject)[0].u)
.to.be.an("array")
.with.length(3)
.that.does.not.contain(savedTimestamps[0])
.and.does.not.contains(savedTimestamps[1])
.and.does.not.contains(savedTimestamps[2]);
});
});
it("updates or reads only single qualifier", async () => {
const periodSeconds = 30;
const maxCalls = 3;
const { genericRateLimiter, timestampProviderMock } = mock({
maxCalls,
periodSeconds,
});
let timestamp = _.random(10, 5000);
for (let i = 0; i < 5; i++) {
timestampProviderMock.setTimestampSeconds(timestamp);
await genericRateLimiter.isQuotaExceededOrRecordCall(sampleQualifier);
timestamp += 1;
}
timestampProviderMock.setTimestampSeconds(timestamp);
expect(await genericRateLimiter.isQuotaExceededOrRecordCall("another_qualifier")).to.be.equal(false);
});
});
describe("check tests", function() {
[
{
name: "isQuotaExceededOrRecordCall",
methodFactory(genericRateLimiter: GenericRateLimiter) {
return genericRateLimiter.isQuotaExceededOrRecordCall.bind(genericRateLimiter);
},
},
{
name: "isQuotaAlreadyExceededDoNotRecordCall",
methodFactory(genericRateLimiter: GenericRateLimiter) {
return genericRateLimiter.isQuotaAlreadyExceededDoNotRecordCall.bind(genericRateLimiter);
},
},
].forEach(testedMethod =>
describe(`#${testedMethod.name}`, () => {
it("returns true if there are more calls than maxCalls", async () => {
const periodSeconds = 20;
const maxCalls = 3;
const { genericRateLimiter, timestampProviderMock } = mock({
maxCalls,
periodSeconds,
});
let timestamp = _.random(10, 5000);
for (let i = 0; i < 6; i++) {
timestampProviderMock.setTimestampSeconds(timestamp);
await genericRateLimiter.isQuotaExceededOrRecordCall(sampleQualifier);
timestamp += 1;
}
const method = testedMethod.methodFactory(genericRateLimiter);
expect(await method(sampleQualifier)).to.be.equal(true);
});
it("returns false if there are exactly maxCalls calls in the period", async () => {
const periodSeconds = 20;
const maxCalls = 3;
const { genericRateLimiter, timestampProviderMock } = mock({
maxCalls,
periodSeconds,
});
let timestamp = _.random(10, 5000);
for (let i = 0; i < 2; i++) {
timestampProviderMock.setTimestampSeconds(timestamp);
await genericRateLimiter.isQuotaExceededOrRecordCall(sampleQualifier);
timestamp += 1;
}
// the following call is the third, should be passed
const method = testedMethod.methodFactory(genericRateLimiter);
expect(await method(sampleQualifier)).to.be.equal(false);
});
it("returns false if there are no calls, maxCalls=1 ant this is the first call", async () => {
const periodSeconds = 20;
const maxCalls = 1;
const { genericRateLimiter, timestampProviderMock } = mock({
maxCalls,
periodSeconds,
});
const timestamp = _.random(10, 5000);
timestampProviderMock.setTimestampSeconds(timestamp);
const method = testedMethod.methodFactory(genericRateLimiter);
expect(await method(sampleQualifier)).to.be.equal(false);
});
it("returns false if there are less calls than maxCalls", async () => {
const periodSeconds = 20;
const maxCalls = 10;
const { genericRateLimiter, timestampProviderMock } = mock({
maxCalls,
periodSeconds,
});
let timestamp = _.random(10, 5000);
for (let i = 0; i < 2; i++) {
timestampProviderMock.setTimestampSeconds(timestamp);
await genericRateLimiter.isQuotaExceededOrRecordCall(sampleQualifier);
timestamp += 1;
}
// the following call is the third, should be passed
const method = testedMethod.methodFactory(genericRateLimiter);
expect(await method(sampleQualifier)).to.be.equal(false);
});
it("returns false if exceeding calls are out of the period", async () => {
const periodSeconds = 20;
const maxCalls = 5;
const { genericRateLimiter, timestampProviderMock } = mock({
maxCalls,
periodSeconds,
});
let timestamp = _.random(10, 5000);
for (let i = 0; i < 10; i++) {
timestampProviderMock.setTimestampSeconds(timestamp);
await genericRateLimiter.isQuotaExceededOrRecordCall(sampleQualifier);
timestamp += 1;
}
timestamp += 30;
timestampProviderMock.setTimestampSeconds(timestamp);
const method = testedMethod.methodFactory(genericRateLimiter);
expect(await method(sampleQualifier)).to.be.equal(false);
});
}),
);
});
}); | the_stack |
'use strict'
// tslint:disable:no-var-requires no-require-imports
// This line should always be right on top.
// tslint:disable:no-any
require('reflect-metadata')
// Initialize source maps (this must never be moved up nor further down).
import { Disposable, ExtensionContext, languages, Memento, OutputChannel, Uri, workspace } from 'coc.nvim'
import { Container } from 'inversify'
import { CodeActionKind } from 'vscode-languageserver-protocol'
import { registerTypes as activationRegisterTypes } from './activation/serviceRegistry'
import { IExtensionActivationManager, ILanguageServerExtension } from './activation/types'
import { buildApi, IExtensionApi } from './api'
import { registerTypes as appRegisterTypes } from './application/serviceRegistry'
import { IApplicationDiagnostics } from './application/types'
import { ICommandManager, IWorkspaceService } from './common/application/types'
import { Commands, PYTHON, STANDARD_OUTPUT_CHANNEL } from './common/constants'
import { registerTypes as registerDotNetTypes } from './common/dotnet/serviceRegistry'
import { registerTypes as installerRegisterTypes } from './common/installer/serviceRegistry'
import { registerTypes as platformRegisterTypes } from './common/platform/serviceRegistry'
import { registerTypes as processRegisterTypes } from './common/process/serviceRegistry'
import { registerTypes as commonRegisterTypes } from './common/serviceRegistry'
// import { ITerminalHelper } from './common/terminal/types'
import {
GLOBAL_MEMENTO, IAsyncDisposableRegistry, IConfigurationService, IDisposableRegistry, IExtensionContext, IFeatureDeprecationManager, IMemento, IOutputChannel,
// Resource,
WORKSPACE_MEMENTO
} from './common/types'
import { createDeferred } from './common/utils/async'
import { StopWatch } from './common/utils/stopWatch'
// import { Common } from './common/utils/localize'
import { registerTypes as variableRegisterTypes } from './common/variables/serviceRegistry'
import { registerTypes as formattersRegisterTypes } from './formatters/serviceRegistry'
import { IInterpreterSelector } from './interpreter/configuration/types'
import {
// ICondaService,
IInterpreterLocatorProgressService, IInterpreterService, InterpreterLocatorProgressHandler
} from './interpreter/contracts'
import { registerTypes as interpretersRegisterTypes } from './interpreter/serviceRegistry'
import { ServiceContainer } from './ioc/container'
import { ServiceManager } from './ioc/serviceManager'
import { IServiceContainer, IServiceManager } from './ioc/types'
import { LinterCommands } from './linters/linterCommands'
import { registerTypes as lintersRegisterTypes } from './linters/serviceRegistry'
// import { ILintingEngine } from './linters/types'
import { PythonCodeActionProvider } from './providers/codeActionsProvider'
import { PythonFormattingEditProvider } from './providers/formatProvider'
import { LinterProvider } from './providers/linterProvider'
import { ReplProvider } from './providers/replProvider'
import { registerTypes as providersRegisterTypes } from './providers/serviceRegistry'
import { activateSimplePythonRefactorProvider } from './providers/simpleRefactorProvider'
import { TerminalProvider } from './providers/terminalProvider'
import { ISortImportsEditingProvider } from './providers/types'
import { activateUpdateSparkLibraryProvider } from './providers/updateSparkLibraryProvider'
import { initialize } from './sourceMapSupport'
import { registerTypes as commonRegisterTerminalTypes } from './terminals/serviceRegistry'
import { ICodeExecutionManager, ITerminalAutoActivation } from './terminals/types'
initialize()
const durations: Record<string, number> = {}
// Do not move this line of code (used to measure extension load times).
const stopWatch = new StopWatch()
// import { TEST_OUTPUT_CHANNEL } from './unittests/common/constants'
// import { ITestContextService } from './unittests/common/types'
// import { ITestCodeNavigatorCommandHandler, ITestExplorerCommandHandler } from './unittests/navigation/types'
// import { registerTypes as unitTestsRegisterTypes } from './unittests/serviceRegistry'
durations.codeLoadingTime = stopWatch.elapsedTime
const activationDeferred = createDeferred<void>()
let activatedServiceContainer: ServiceContainer | undefined
export async function activate(context: ExtensionContext): Promise<IExtensionApi> {
let statusItem = workspace.createStatusBarItem(0, { progress: true })
statusItem.text = 'loading python extension.'
statusItem.show()
try {
let res = await activateUnsafe(context)
statusItem.dispose()
return res
} catch (ex) {
statusItem.dispose()
// handleError(ex)
throw ex // re-raise
}
}
// tslint:disable-next-line:max-func-body-length
async function activateUnsafe(context: ExtensionContext): Promise<IExtensionApi> {
// displayProgress(activationDeferred.promise)
durations.startActivateTime = stopWatch.elapsedTime
const cont = new Container()
const serviceManager = new ServiceManager(cont)
const serviceContainer = new ServiceContainer(cont)
activatedServiceContainer = serviceContainer
registerServices(context, serviceManager, serviceContainer)
await initializeServices(context, serviceManager, serviceContainer)
const manager = serviceContainer.get<IExtensionActivationManager>(IExtensionActivationManager)
context.subscriptions.push(manager)
const activationPromise = manager.activate()
serviceManager.get<ITerminalAutoActivation>(ITerminalAutoActivation).register()
const configuration = serviceManager.get<IConfigurationService>(IConfigurationService)
const pythonSettings = configuration.getSettings()
const standardOutputChannel = serviceContainer.get<OutputChannel>(IOutputChannel, STANDARD_OUTPUT_CHANNEL)
activateSimplePythonRefactorProvider(context, standardOutputChannel, serviceContainer)
const sortImports = serviceContainer.get<ISortImportsEditingProvider>(ISortImportsEditingProvider)
sortImports.registerCommands()
serviceManager.get<ICodeExecutionManager>(ICodeExecutionManager).registerCommands()
// tslint:disable-next-line:no-suspicious-comment
// TODO: Move this down to right before durations.endActivateTime is set.
// sendStartupTelemetry(Promise.all([activationDeferred.promise, activationPromise]), serviceContainer).catch(emptyFn)
const workspaceService = serviceContainer.get<IWorkspaceService>(IWorkspaceService)
const interpreterManager = serviceContainer.get<IInterpreterService>(IInterpreterService)
interpreterManager.refresh(Uri.file(workspace.rootPath))
// tslint:disable-next-line: no-console
.catch(ex => console.error('Python Extension: interpreterManager.refresh', ex))
// const jupyterExtension = extensions.getExtension('donjayamanne.jupyter')
// const lintingEngine = serviceManager.get<ILintingEngine>(ILintingEngine)
// lintingEngine.linkJupyterExtension(jupyterExtension).catch(emptyFn)
context.subscriptions.push(new LinterCommands(serviceManager))
const linterProvider = new LinterProvider(context, serviceManager)
context.subscriptions.push(linterProvider)
if (pythonSettings && pythonSettings.formatting && pythonSettings.formatting.provider !== 'none') {
const formatProvider = new PythonFormattingEditProvider(context, serviceContainer)
context.subscriptions.push(languages.registerDocumentFormatProvider(PYTHON, formatProvider))
context.subscriptions.push(languages.registerDocumentRangeFormatProvider(PYTHON, formatProvider))
}
const deprecationMgr = serviceContainer.get<IFeatureDeprecationManager>(IFeatureDeprecationManager)
deprecationMgr.initialize()
context.subscriptions.push(deprecationMgr)
context.subscriptions.push(activateUpdateSparkLibraryProvider())
context.subscriptions.push(new ReplProvider(serviceContainer))
context.subscriptions.push(new TerminalProvider(serviceContainer))
context.subscriptions.push(languages.registerCodeActionProvider(PYTHON, new PythonCodeActionProvider(), 'python', [CodeActionKind.SourceOrganizeImports]))
durations.endActivateTime = stopWatch.elapsedTime
activationDeferred.resolve()
const api = buildApi(Promise.all([activationDeferred.promise, activationPromise]))
// In test environment return the DI Container.
return api as any
}
export function deactivate(): Thenable<void> {
// Make sure to shutdown anybody who needs it.
if (activatedServiceContainer) {
const registry = activatedServiceContainer.get<IAsyncDisposableRegistry>(IAsyncDisposableRegistry)
if (registry) {
return registry.dispose()
}
}
return Promise.resolve()
}
// tslint:disable-next-line:no-any
// function displayProgress(promise: Promise<any>) {
//
// const progressOptions: ProgressOptions = { location: ProgressLocation.Window, title: Common.loadingExtension() }
// window.withProgress(progressOptions, () => promise)
// }
//
function registerServices(context: ExtensionContext, serviceManager: ServiceManager, serviceContainer: ServiceContainer) {
serviceManager.addSingletonInstance<IServiceContainer>(IServiceContainer, serviceContainer)
serviceManager.addSingletonInstance<IServiceManager>(IServiceManager, serviceManager)
serviceManager.addSingletonInstance<Disposable[]>(IDisposableRegistry, context.subscriptions)
serviceManager.addSingletonInstance<Memento>(IMemento, context.globalState, GLOBAL_MEMENTO)
serviceManager.addSingletonInstance<Memento>(IMemento, context.workspaceState, WORKSPACE_MEMENTO)
serviceManager.addSingletonInstance<IExtensionContext>(IExtensionContext, context)
const standardOutputChannel = workspace.createOutputChannel('Python')
// const unitTestOutChannel = window.createOutputChannel('Python Test Log')
serviceManager.addSingletonInstance<OutputChannel>(IOutputChannel, standardOutputChannel, STANDARD_OUTPUT_CHANNEL)
// serviceManager.addSingletonInstance<OutputChannel>(IOutputChannel, unitTestOutChannel, TEST_OUTPUT_CHANNEL)
activationRegisterTypes(serviceManager)
commonRegisterTypes(serviceManager)
registerDotNetTypes(serviceManager)
processRegisterTypes(serviceManager)
variableRegisterTypes(serviceManager)
lintersRegisterTypes(serviceManager)
interpretersRegisterTypes(serviceManager)
formattersRegisterTypes(serviceManager)
platformRegisterTypes(serviceManager)
installerRegisterTypes(serviceManager)
commonRegisterTerminalTypes(serviceManager)
// unitTestsRegisterTypes(serviceManager)
// dataScienceRegisterTypes(serviceManager)
// debugConfigurationRegisterTypes(serviceManager)
appRegisterTypes(serviceManager)
providersRegisterTypes(serviceManager)
}
async function initializeServices(context: ExtensionContext, serviceManager: ServiceManager, serviceContainer: ServiceContainer) {
const selector = serviceContainer.get<IInterpreterSelector>(IInterpreterSelector)
selector.initialize()
context.subscriptions.push(selector)
const interpreterManager = serviceContainer.get<IInterpreterService>(IInterpreterService)
interpreterManager.initialize()
// const handlers = serviceManager.getAll<IDebugSessionEventHandlers>(IDebugSessionEventHandlers)
const disposables = serviceManager.get<IDisposableRegistry>(IDisposableRegistry)
// const dispatcher = new DebugSessionEventDispatcher(handlers, DebugService.instance, disposables)
// dispatcher.registerEventHandlers()
const cmdManager = serviceContainer.get<ICommandManager>(ICommandManager)
const outputChannel = serviceManager.get<OutputChannel>(IOutputChannel, STANDARD_OUTPUT_CHANNEL)
disposables.push(cmdManager.registerCommand(Commands.ViewOutput, () => outputChannel.show()))
// Display progress of interpreter refreshes only after extension has activated.
serviceContainer.get<InterpreterLocatorProgressHandler>(InterpreterLocatorProgressHandler).register()
serviceContainer.get<IInterpreterLocatorProgressService>(IInterpreterLocatorProgressService).register()
serviceContainer.get<IApplicationDiagnostics>(IApplicationDiagnostics).register()
serviceContainer.get<ILanguageServerExtension>(ILanguageServerExtension).register()
// serviceContainer.get<ITestCodeNavigatorCommandHandler>(ITestCodeNavigatorCommandHandler).register()
// serviceContainer.get<ITestExplorerCommandHandler>(ITestExplorerCommandHandler).register()
// serviceContainer.get<ITestContextService>(ITestContextService).register()
}
// tslint:disable-next-line:no-any
// async function sendStartupTelemetry(activatedPromise: Promise<any>, serviceContainer: IServiceContainer) {
// try {
// await activatedPromise
// durations.totalActivateTime = stopWatch.elapsedTime
// const props = await getActivationTelemetryProps(serviceContainer)
// sendTelemetryEvent(EventName.EDITOR_LOAD, durations, props)
// } catch (ex) {
// traceError('sendStartupTelemetry() failed.', ex)
// }
// }
// function isUsingGlobalInterpreterInWorkspace(currentPythonPath: string, serviceContainer: IServiceContainer): boolean {
// const service = serviceContainer.get<IInterpreterAutoSelectionService>(IInterpreterAutoSelectionService)
// const globalInterpreter = service.getAutoSelectedInterpreter(undefined)
// if (!globalInterpreter) {
// return false
// }
// return currentPythonPath === globalInterpreter.path
// }
// function hasUserDefinedPythonPath(resource: Resource, serviceContainer: IServiceContainer) {
// const workspaceService = serviceContainer.get<IWorkspaceService>(IWorkspaceService)
// const pythonPath = workspaceService.getConfiguration('python', resource).get<string>('pythonPath')!
// return pythonPath && pythonPath !== 'python'
// }
//
// function getPreferredWorkspaceInterpreter(resource: Resource, serviceContainer: IServiceContainer) {
// const workspaceInterpreterSelector = serviceContainer.get<IInterpreterAutoSelectionRule>(IInterpreterAutoSelectionRule, AutoSelectionRule.workspaceVirtualEnvs)
// const interpreter = workspaceInterpreterSelector.getPreviouslyAutoSelectedInterpreter(resource)
// return interpreter ? interpreter.path : undefined
// }
/////////////////////////////
// telemetry
// tslint:disable-next-line:no-any
/////////////////////////////
// error handling
interface IAppShell {
showErrorMessage(str: string): Promise<void>
}
function notifyUser(msg: string) {
// tslint:disable-next-line:no-any
workspace.showMessage(msg, 'error')
}
// async function sendErrorTelemetry(ex: Error) {
// try {
// // tslint:disable-next-line:no-any
// let props: any = {}
// if (activatedServiceContainer) {
// try {
// props = await getActivationTelemetryProps(activatedServiceContainer)
// } catch (ex) {
// // ignore
// }
// }
// sendTelemetryEvent(EventName.EDITOR_LOAD, durations, props, ex)
// } catch (exc2) {
// traceError('sendErrorTelemetry() failed.', exc2)
// }
// } | the_stack |
import { ConcreteRequest } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type Shipping_Test_QueryVariables = {};
export type Shipping_Test_QueryResponse = {
readonly me: {
readonly conversation: {
readonly orderConnection: {
readonly edges: ReadonlyArray<{
readonly node: {
readonly " $fragmentRefs": FragmentRefs<"Shipping_order">;
} | null;
} | null> | null;
} | null;
} | null;
} | null;
};
export type Shipping_Test_Query = {
readonly response: Shipping_Test_QueryResponse;
readonly variables: Shipping_Test_QueryVariables;
};
/*
query Shipping_Test_Query {
me {
conversation(id: "test-id") {
orderConnection(first: 10) {
edges {
node {
__typename
...Shipping_order
id
}
}
}
id
}
id
}
}
fragment Shipping_order on CommerceOrder {
__isCommerceOrder: __typename
requestedFulfillment {
__typename
... on CommerceShip {
name
addressLine1
city
country
postalCode
}
... on CommerceShipArta {
name
addressLine1
city
country
postalCode
}
}
lineItems {
edges {
node {
artwork {
shippingOrigin
id
}
id
}
}
}
}
*/
const node: ConcreteRequest = (function(){
var v0 = [
{
"kind": "Literal",
"name": "id",
"value": "test-id"
}
],
v1 = [
{
"kind": "Literal",
"name": "first",
"value": 10
}
],
v2 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
},
v3 = [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "name",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "addressLine1",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "city",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "country",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "postalCode",
"storageKey": null
}
],
v4 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
};
return {
"fragment": {
"argumentDefinitions": [],
"kind": "Fragment",
"metadata": null,
"name": "Shipping_Test_Query",
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Me",
"kind": "LinkedField",
"name": "me",
"plural": false,
"selections": [
{
"alias": null,
"args": (v0/*: any*/),
"concreteType": "Conversation",
"kind": "LinkedField",
"name": "conversation",
"plural": false,
"selections": [
{
"alias": null,
"args": (v1/*: any*/),
"concreteType": "CommerceOrderConnectionWithTotalCount",
"kind": "LinkedField",
"name": "orderConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceOrderEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
{
"args": null,
"kind": "FragmentSpread",
"name": "Shipping_order"
}
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": "orderConnection(first:10)"
}
],
"storageKey": "conversation(id:\"test-id\")"
}
],
"storageKey": null
}
],
"type": "Query",
"abstractKey": null
},
"kind": "Request",
"operation": {
"argumentDefinitions": [],
"kind": "Operation",
"name": "Shipping_Test_Query",
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Me",
"kind": "LinkedField",
"name": "me",
"plural": false,
"selections": [
{
"alias": null,
"args": (v0/*: any*/),
"concreteType": "Conversation",
"kind": "LinkedField",
"name": "conversation",
"plural": false,
"selections": [
{
"alias": null,
"args": (v1/*: any*/),
"concreteType": "CommerceOrderConnectionWithTotalCount",
"kind": "LinkedField",
"name": "orderConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceOrderEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v2/*: any*/),
{
"kind": "TypeDiscriminator",
"abstractKey": "__isCommerceOrder"
},
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "requestedFulfillment",
"plural": false,
"selections": [
(v2/*: any*/),
{
"kind": "InlineFragment",
"selections": (v3/*: any*/),
"type": "CommerceShip",
"abstractKey": null
},
{
"kind": "InlineFragment",
"selections": (v3/*: any*/),
"type": "CommerceShipArta",
"abstractKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "CommerceLineItemConnection",
"kind": "LinkedField",
"name": "lineItems",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceLineItemEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceLineItem",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Artwork",
"kind": "LinkedField",
"name": "artwork",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "shippingOrigin",
"storageKey": null
},
(v4/*: any*/)
],
"storageKey": null
},
(v4/*: any*/)
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": null
},
(v4/*: any*/)
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": "orderConnection(first:10)"
},
(v4/*: any*/)
],
"storageKey": "conversation(id:\"test-id\")"
},
(v4/*: any*/)
],
"storageKey": null
}
]
},
"params": {
"id": "50264d8be7e5cd27ec69547e17747930",
"metadata": {},
"name": "Shipping_Test_Query",
"operationKind": "query",
"text": null
}
};
})();
(node as any).hash = '305484a456f4b3e4e4a7c961cf7d337d';
export default node; | the_stack |
import { AnimationNode } from "../types";
import { getReducedInterpolationTree } from "../getInterpolationTree";
import { Metrics } from "../../../Types";
import * as Constants from "../../../Types/Constants";
import { DefaultTime } from "../../../Utilities";
describe("getInterpolationTree / duration", () => {
it("should return the correct child duration for staggered interpolations", () => {
const tree = createSimpleTree({
id: 1,
childAnimation: "staggered",
stagger: 100,
children: [
{ id: 2, duration: 100 },
{ id: 3, duration: 300 },
{ id: 4, duration: 100 },
],
});
const valueToTest = getReducedInterpolationTree(tree, {
[2]: true,
[3]: true,
[4]: true,
});
expect(valueToTest).toBeDefined();
if (valueToTest) {
expect(valueToTest.subtreeDuration).toEqual(400);
}
});
it("should return the correct child duration for parallel interpolations", () => {
const tree = createSimpleTree({
id: 1,
childAnimation: "parallel",
children: [{ id: 2, duration: 100 }, { id: 3, duration: 100 }],
});
const valueToTest = getReducedInterpolationTree(tree, {
[2]: true,
[3]: true,
});
expect(valueToTest).toBeDefined();
if (valueToTest) {
expect(valueToTest.subtreeDuration).toEqual(100);
}
});
it("should return the correct child duration for sequential interpolations", () => {
const tree = createSimpleTree({
id: 1,
childAnimation: "sequential",
children: [{ id: 2, duration: 100 }, { id: 3, duration: 100 }],
});
const valueToTest = getReducedInterpolationTree(tree, {
[2]: true,
[3]: true,
});
expect(valueToTest).toBeDefined();
if (valueToTest) {
expect(valueToTest.subtreeDuration).toEqual(200);
}
});
it("should not include parent node's duration when calculating child duration", () => {
const tree = createSimpleTree({
id: 1,
duration: 100,
childAnimation: "sequential",
children: [{ id: 2, duration: 100 }, { id: 3, duration: 100 }],
});
const valueToTest = getReducedInterpolationTree(tree, {
[1]: true,
[2]: true,
[3]: true,
});
expect(valueToTest).toBeDefined();
if (valueToTest) {
expect(valueToTest.subtreeDuration).toEqual(200);
}
});
it("should return parent node's duration when larger than child duration", () => {
const tree = createSimpleTree({
id: 1,
duration: 400,
childAnimation: "sequential",
children: [{ id: 2, duration: 100 }, { id: 3, duration: 100 }],
});
const valueToTest = getReducedInterpolationTree(tree, {
[1]: true,
[2]: true,
[3]: true,
});
expect(valueToTest).toBeDefined();
if (valueToTest) {
expect(valueToTest.subtreeDuration).toEqual(400);
}
});
it("should include delay when calculating child duration", () => {
const tree = createSimpleTree({
id: 1,
childAnimation: "sequential",
children: [
{ id: 2, duration: 100, delay: 100 },
{ id: 3, duration: 100, delay: 100 },
],
});
const valueToTest = getReducedInterpolationTree(tree, {
[2]: true,
[3]: true,
});
expect(valueToTest).toBeDefined();
if (valueToTest) {
expect(valueToTest.subtreeDuration).toEqual(400);
}
});
it("should include delay when returning root node's duration", () => {
const tree = createSimpleTree({
id: 1,
childAnimation: "sequential",
duration: 300,
delay: 200,
children: [
{ id: 2, duration: 100, delay: 100 },
{ id: 3, duration: 100, delay: 100 },
],
});
const valueToTest = getReducedInterpolationTree(tree, {
[1]: true,
[2]: true,
[3]: true,
});
expect(valueToTest).toBeDefined();
if (valueToTest) {
expect(valueToTest.subtreeDuration).toEqual(500);
}
});
it("should return 300 when AsGroup is set for a child", () => {
const tree = createSimpleTree({
id: 1,
children: [
{ id: 2, duration: 300 },
{ id: 3, duration: Constants.AsGroup },
],
});
const valueToTest = getReducedInterpolationTree(tree, {
[2]: true,
[3]: true,
});
expect(valueToTest).toBeDefined();
if (valueToTest) {
expect(valueToTest.children[1].duration).toBe(300);
}
});
it("should return 500 when AsGroup is set for a child in a complex nested tree", () => {
const tree = createSimpleTree({
id: 1,
children: [
{ id: 3, duration: Constants.AsGroup },
{
id: 2,
duration: 300,
children: [{ id: 4, duration: 500 }, { id: 5, duration: 300 }],
},
],
});
const valueToTest = getReducedInterpolationTree(tree, {
[2]: true,
[3]: true,
[4]: true,
[5]: true,
});
expect(valueToTest).toBeDefined();
if (valueToTest) {
expect(valueToTest.children[0].duration).toBe(500);
}
});
it("should return default duration when AsGroup is set for a tree without any duration", () => {
const tree = createSimpleTree({
id: 0,
children: [
{ id: 1, duration: Constants.AsGroup },
{ id: 2, duration: Constants.AsGroup },
],
});
const valueToTest = getReducedInterpolationTree(tree, {
[1]: true,
[2]: true,
});
expect(valueToTest).toBeDefined();
if (valueToTest) {
expect(valueToTest.children[0].duration).toBe(DefaultTime);
expect(valueToTest.children[1].duration).toBe(DefaultTime);
}
});
it("should return 600 when AsChildren is set in complex tree", () => {
const tree = createSimpleTree({
id: 1,
children: [
{
id: 2,
duration: 100,
children: [
{ id: 4, duration: 600 },
{ id: 5, duration: 300 },
{ id: 3, duration: Constants.AsGroup },
],
},
{
id: 6,
duration: 800,
},
],
});
const valueToTest = getReducedInterpolationTree(tree, {
[3]: true,
[4]: true,
[5]: true,
[6]: true,
});
expect(valueToTest).toBeDefined();
if (valueToTest) {
expect(valueToTest.children[0].children[2].duration).toBe(600);
}
});
it("should return 600 when AsContext is set in complex tree", () => {
const tree = createSimpleTree({
id: 1,
children: [
{
id: 2,
duration: 100,
children: [
{ id: 4, duration: 600 },
{ id: 5, duration: 300 },
{ id: 3, duration: Constants.AsContext },
],
},
{
id: 6,
duration: 800,
},
],
});
const valueToTest = getReducedInterpolationTree(tree, {
[3]: true,
[4]: true,
[5]: true,
[6]: true,
});
expect(valueToTest).toBeDefined();
if (valueToTest) {
expect(valueToTest.children[0].children[2].duration).toBe(800);
}
});
});
describe("getInterpolationTree / offset / root node", () => {
it("should return the node's delay as offset for the root node", () => {
const tree = createSimpleTree({
id: 1,
delay: 100,
children: [],
});
const valueToTest = getReducedInterpolationTree(tree, { [1]: true });
expect(valueToTest).toBeDefined();
if (valueToTest) {
expect(valueToTest.offset).toEqual(100);
}
});
it("should return delay as offset for the root node when it is not part of an interpolation", () => {
const tree = createSimpleTree({
id: 1,
delay: 100,
children: [{ id: 2 }],
});
const valueToTest = getReducedInterpolationTree(tree, { [2]: true });
expect(valueToTest).toBeDefined();
if (valueToTest) {
expect(valueToTest.offset).toEqual(100);
}
});
});
describe("getInterpolationTree / offset / parallel", () => {
it("should include parent offset for a child node", () => {
const tree = createSimpleTree({
id: 1,
delay: 100,
childAnimation: "parallel",
children: [{ id: 2, delay: 100 }],
});
const valueToTest = getReducedInterpolationTree(tree, { [2]: true });
expect(valueToTest).toBeDefined();
if (valueToTest) {
expect(valueToTest.children[0].offset).toEqual(200);
}
});
it("should include parent offset for the second child node", () => {
const tree = createSimpleTree({
id: 1,
delay: 100,
childAnimation: "parallel",
children: [{ id: 2, delay: 100 }, { id: 3, delay: 50 }],
});
const valueToTest = getReducedInterpolationTree(tree, {
[2]: true,
[3]: true,
});
expect(valueToTest).toBeDefined();
if (valueToTest) {
expect(valueToTest.children[1].offset).toEqual(150);
}
});
});
describe("getInterpolationTree / offset / sequential", () => {
it("should include previous node offset for second child node", () => {
const tree = createSimpleTree({
id: 1,
delay: 0,
childAnimation: "sequential",
children: [{ id: 2, duration: 100 }, { id: 2, duration: 100 }],
});
const valueToTest = getReducedInterpolationTree(tree, {
[2]: true,
[3]: true,
});
expect(valueToTest).toBeDefined();
if (valueToTest) {
expect(valueToTest.children[1].offset).toEqual(100);
}
});
});
describe("getInterpolationTree / offset / stagger", () => {
it("should include previous node's offset", () => {
const tree = createSimpleTree({
id: 1,
delay: 0,
childAnimation: "staggered",
stagger: 100,
children: [{ id: 2, duration: 100 }, { id: 2, duration: 100 }],
});
const valueToTest = getReducedInterpolationTree(tree, {
[2]: true,
[3]: true,
});
expect(valueToTest).toBeDefined();
if (valueToTest) {
expect(valueToTest.children[1].offset).toEqual(100);
}
});
it("should not render hidden elements", () => {
const tree = createSimpleTree({
id: 1,
delay: 0,
childAnimation: "staggered",
stagger: 100,
children: [
{ id: 2, duration: 100, isHidden: true },
{ id: 3, duration: 100 },
{ id: 4, duration: 100 },
],
});
const valueToTest = getReducedInterpolationTree(tree, {
[2]: true,
[3]: true,
[4]: false,
});
expect(valueToTest).toBeDefined();
if (valueToTest) {
expect(valueToTest.subtreeDuration).toEqual(200);
}
});
});
/****************************************************************
HELPERS
****************************************************************/
export type MockNode = {
id: number;
children?: Array<MockNode>;
duration?: number;
delay?: number;
stagger?: number;
isHidden?: boolean;
childAnimation?: "staggered" | "parallel" | "sequential";
};
export const createSimpleTree = (
mockNode: MockNode,
parent?: AnimationNode,
): AnimationNode => {
const node: AnimationNode = {
id: mockNode.id,
parent,
offset: -1,
stagger: mockNode.stagger || 1.0,
duration: mockNode.duration || 330,
delay: mockNode.delay || 0,
childAnimation: mockNode.childAnimation || "parallel",
childDirection: "forward",
metrics: new Metrics(-1, -1, -1, -1),
children: [],
interpolationId: 0,
isHidden: mockNode.isHidden || false,
};
node.children = mockNode.children
? mockNode.children.map(c => createSimpleTree(c, node))
: [];
node.children.forEach(s => (s.stagger = node.stagger));
return node;
}; | the_stack |
import { Map } from 'immutable';
import { LinkRecord } from '../../constants/flowdesigner.model';
import * as Link from './link';
const isNotLinkException = `Linkrecord should be a Linkrecord, was given
"""
object
"""
Map {}
"""
you should use Link module functions to create and transform Link`;
const protectedValueException =
'linkType is a protected value of the Link, please use getLinkType setLinkType from this module to make change on those values';
describe('isLinkElseThrow', () => {
it('return true if parameter link is a LinkRecord', () => {
// given
const testLink = new LinkRecord();
// when
const test = Link.isLinkElseThrow(testLink);
// expect
expect(test).toEqual(true);
});
it('thow an error if parameter is not a LinkRecord', () => {
// given
const testLink = Map();
// when
// expect
expect(() => Link.isLinkElseThrow(testLink)).toThrow(isNotLinkException);
});
});
describe('Link', () => {
const id = 'ID';
const sourceId = 'SOURCE_ID';
const targetId = 'TARGET_ID';
const linkType = 'LinkType';
const testLink = Link.create(id, sourceId, targetId, linkType);
const key = 'KEY';
const value = { whatever: 'whatever' };
const improperId = 34;
const improperSourceId = 42;
const improperTargetId = 64;
const improperLinkType = {};
const improperLink = Map();
describe('create', () => {
it('given proper id, sourceId, targetid and componentType return a Link', () => {
// given
// when
const test = Link.create(id, sourceId, targetId, linkType);
// expect
expect(Link.isLink(test)).toEqual(true);
});
it('throw if given an improper id', () => {
// given
// when
// expect
expect(() => Link.create(improperId as any, sourceId, targetId, linkType)).toThrow(
'id should be a string, was given 34',
);
});
it('throw if given an improper sourceId', () => {
// given
// when
// expect
expect(() => Link.create(id, improperSourceId as any, targetId, linkType)).toThrow(
'id should be a string, was given 42',
);
});
it('throw if given an improper targetId', () => {
// given
// when
// expect
expect(() => Link.create(id, sourceId, improperTargetId as any, linkType)).toThrow(
'id should be a string, was given 64',
);
});
it('throw if given an improper componentType', () => {
// given
// when
// expect
expect(() => Link.create(id, sourceId, targetId, improperLinkType as any)).toThrow(
'linkType should be a string, was given [object Object]',
);
});
});
describe('isLink', () => {
it('return true if parameter link is a LinkRecord', () => {
// given
// when
const test = Link.isLink(testLink);
// expect
expect(test).toEqual(true);
});
it('thow an error if parameter is not a LinkRecord', () => {
// given
// when
const test = Link.isLink(improperLink);
// expect
expect(test).toEqual(false);
});
});
describe('getId', () => {
it('given a proper Link return an Id', () => {
// given
// when
const test = Link.getId(testLink);
// expect
expect(test).toEqual(id);
});
it('throw given an improper link', () => {
expect(() => Link.getId(improperLink)).toThrow(isNotLinkException);
});
});
describe('getSourceId', () => {
it('given a proper Link return a SourceId', () => {
// given
// when
const test = Link.getSourceId(testLink);
// expect
expect(test).toEqual(sourceId);
});
it('throw given an improper link', () => {
expect(() => Link.getSourceId(improperLink)).toThrow(isNotLinkException);
});
});
describe('setSourceId', () => {
it('given a proper Link and SourceId return a Link with updated SourceId', () => {
// given
const newSourceId = 'newSourceId';
// when
const test = Link.setSourceId(newSourceId, testLink);
// expect
expect(Link.getSourceId(test)).toEqual(newSourceId);
});
it('throw given an improper SourceId', () => {
// given
// when
// expect
expect(() => Link.setSourceId(improperSourceId as any, testLink)).toThrow(
'id should be a string, was given 42',
);
});
it('throw given an improper Link', () => {
// given
// when
// expect
expect(() => Link.setSourceId(sourceId, improperLink)).toThrow(isNotLinkException);
});
});
describe('getTargetId', () => {
it('given a proper Link return a TargetId', () => {
// given
// when
const test = Link.getTargetId(testLink);
// expect
expect(test).toEqual(targetId);
});
it('throw given an improper link', () => {
expect(() => Link.getTargetId(improperLink)).toThrow(isNotLinkException);
});
});
describe('setTargetId', () => {
it('given a proper Link and TargetId return a Link with updated TargetId', () => {
// given
const newTargetId = 'newTargetId';
// when
const test = Link.setTargetId(newTargetId, testLink);
// expect
expect(Link.getTargetId(test)).toEqual(newTargetId);
});
it('throw given an improper TargetId', () => {
// given
// when
// expect
expect(() => Link.setTargetId(improperTargetId as any, testLink)).toThrow(
'id should be a string, was given 64',
);
});
it('throw given an improper Link', () => {
// given
// when
// expect
expect(() => Link.setTargetId(targetId, improperLink)).toThrow(isNotLinkException);
});
});
describe('getComponentType', () => {
it('given a proper Link return a ComponentType', () => {
// given
// when
const test = Link.getComponentType(testLink);
// expect
expect(test).toEqual(linkType);
});
it('throw given an improper Link', () => {
// given
// when
// expect
expect(() => Link.getComponentType(improperLink)).toThrow(isNotLinkException);
});
});
describe('setComponentType', () => {
it('given a proper Link and ComponentType return a Link with updated ComponentType', () => {
// given
const newComponentType = 'monotoneLink';
// when
const test = Link.setComponentType(newComponentType, testLink);
// expect
expect(Link.getComponentType(test)).toEqual(newComponentType);
});
it('throw given an improper ComponentType', () => {
// given
const newComponentType = { type: 'squareOne' };
// when
// expect
expect(() => Link.setComponentType(newComponentType as any, testLink)).toThrow(
'linkType should be a string, was given [object Object]',
);
});
it('throw given an improper Link', () => {
// given
// when
// expect
expect(() => Link.setComponentType(linkType, improperLink)).toThrow(isNotLinkException);
});
});
describe('setData', () => {
it('given a proper key, value and link return said link with the new key/value', () => {
// given
const newKey = 'newKey';
const newValue = 'newValue';
// when
const test = Link.setData(newKey, newValue, testLink);
// expect
expect(Link.getData(newKey, test)).toEqual(newValue);
});
it('throw given an improper key', () => {
// given
const improperKey = 8;
// when
// expect
expect(() => Link.setData(improperKey as any, value, testLink)).toThrow(
`key should be a string, was given ${
improperKey && improperKey.toString()
} of type ${typeof improperKey}`,
);
});
it('throw given an improper link', () => {
// given
// when
// expect
expect(() => Link.setData(key, value, improperLink)).toThrow(isNotLinkException);
});
});
describe('getData', () => {
it('given a proper key and link return value associated with the key', () => {
// given
const newKey = 'newKey';
const newValue = 'newValue';
const preparedLink = Link.setData(newKey, newValue, testLink);
// when
const test = Link.getData(newKey, preparedLink);
// expect
expect(test).toEqual(newValue);
});
it('throw given an improper key', () => {
// given
const improperKey = 8;
// when
// expect
expect(() => Link.getData(improperKey as any, testLink)).toThrow(
`key should be a string, was given ${
improperKey && improperKey.toString()
} of type ${typeof improperKey}`,
);
});
it('throw given an improper link', () => {
// given
// when
// expect
expect(() => Link.getData(key, improperLink)).toThrow(isNotLinkException);
});
});
describe('hasData', () => {
it('given a proper key and link return true if key exist', () => {
// given
const newKey = 'newKey';
const newValue = 'newValue';
const preparedLink = Link.setData(newKey, newValue, testLink);
// when
const test = Link.hasData(newKey, preparedLink);
// expect
expect(test).toEqual(true);
});
it('throw given an improper key', () => {
// given
const improperKey = 8;
// when
// expect
expect(() => Link.hasData(improperKey as any, testLink)).toThrow(
`key should be a string, was given ${
improperKey && improperKey.toString()
} of type ${typeof improperKey}`,
);
});
it('throw given an improper link', () => {
// given
// when
// expect
expect(() => Link.hasData(key, improperLink)).toThrow(isNotLinkException);
});
});
describe('deleteData', () => {
it('given a proper key and link return link without the key in data property if key exist', () => {
// given
const newKey = 'newKey';
const newValue = 'newValue';
const preparedLink = Link.setData(newKey, newValue, testLink);
// when
const test = Link.deleteData(newKey, preparedLink);
// expect
expect(Link.hasData(newKey, test)).toEqual(false);
});
it('throw given an improper key', () => {
// given
const improperKey = 8;
// when
// expect
expect(() => Link.deleteData(improperKey as any, testLink)).toThrow(
`key should be a string, was given ${
improperKey && improperKey.toString()
} of type ${typeof improperKey}`,
);
});
it('throw given an improper link', () => {
// given
// when
// expect
expect(() => Link.deleteData(key, improperLink)).toThrow(isNotLinkException);
});
});
describe('setGraphicalAttribute', () => {
it('given a proper key, value and link return said link with the new key/value', () => {
// given
const newKey = 'newKey';
const newValue = 'newValue';
// when
const test = Link.setGraphicalAttribute(newKey, newValue, testLink);
// expect
expect(Link.getGraphicalAttribute(newKey, test)).toEqual(newValue);
});
it('throw given a key being part of FORBIDEN_GRAPHICAL_ATTRIBUTES', () => {
// given
const improperNewKey = 'linkType';
const newValue = 'newValue';
// when
// expect
expect(() => Link.setGraphicalAttribute(improperNewKey, newValue, testLink)).toThrow(
protectedValueException,
);
});
it('throw given an improper key', () => {
// given
const improperKey = 8;
// when
// expect
expect(() => Link.setGraphicalAttribute(improperKey as any, value, testLink)).toThrow(
`key should be a string, was given ${
improperKey && improperKey.toString()
} of type ${typeof improperKey}`,
);
});
it('throw given an improper link', () => {
// given
// when
// expect
expect(() => Link.setGraphicalAttribute(key, value, improperLink)).toThrow(
isNotLinkException,
);
});
});
describe('getGraphicalAttribute', () => {
it('given a proper key and link return value associated with the key', () => {
// given
const newKey = 'newKey';
const newValue = 'newValue';
const preparedLink = Link.setGraphicalAttribute(newKey, newValue, testLink);
// when
const test = Link.getGraphicalAttribute(newKey, preparedLink);
// expect
expect(test).toEqual(newValue);
});
it('throw given a key being part of FORBIDEN_GRAPHICAL_ATTRIBUTES', () => {
// given
const improperNewKey = 'linkType';
// when
// expect
expect(() => Link.getGraphicalAttribute(improperNewKey, testLink)).toThrow(
protectedValueException,
);
});
it('throw given an improper key', () => {
// given
const improperKey = 8;
// when
// expect
expect(() => Link.getGraphicalAttribute(improperKey as any, testLink)).toThrow(
`key should be a string, was given ${
improperKey && improperKey.toString()
} of type ${typeof improperKey}`,
);
});
it('throw given an improper link', () => {
// given
// when
// expect
expect(() => Link.getGraphicalAttribute(key, improperLink)).toThrow(isNotLinkException);
});
});
describe('hasGraphicalAttribute', () => {
it('given a proper key and link return true if key exist', () => {
// given
const newKey = 'newKey';
const newValue = 'newValue';
const preparedLink = Link.setGraphicalAttribute(newKey, newValue, testLink);
// when
const test = Link.hasGraphicalAttribute(newKey, preparedLink);
// expect
expect(test).toEqual(true);
});
it('throw given a key being part of FORBIDEN_GRAPHICAL_ATTRIBUTES', () => {
// given
const improperKey = 'linkType';
// when
// expect
expect(() => Link.hasGraphicalAttribute(improperKey, testLink)).toThrow(
protectedValueException,
);
});
it('throw given an improper key', () => {
// given
const improperKey = 8;
// when
// expect
expect(() => Link.hasGraphicalAttribute(improperKey as any, testLink)).toThrow(
`key should be a string, was given ${
improperKey && improperKey.toString()
} of type ${typeof improperKey}`,
);
});
it('throw given an improper link', () => {
// given
// when
// expect
expect(() => Link.hasGraphicalAttribute(key, improperLink)).toThrow(isNotLinkException);
});
});
describe('deleteGraphicalAttribute', () => {
it('given a proper key and link return link without the key in data property if key exist', () => {
// given
const newKey = 'newKey';
const newValue = 'newValue';
const preparedLink = Link.setGraphicalAttribute(newKey, newValue, testLink);
// when
const test = Link.deleteGraphicalAttribute(newKey, preparedLink);
// expect
expect(Link.hasGraphicalAttribute(newKey, test)).toEqual(false);
});
it('throw given a key being part of FORBIDEN_GRAPHICAL_ATTRIBUTES', () => {
// given
const improperKey = 'linkType';
// when
// expect
expect(() => Link.deleteGraphicalAttribute(improperKey, testLink)).toThrow(
protectedValueException,
);
});
it('throw given an improper key', () => {
// given
const improperKey = 8;
// when
// expect
expect(() => Link.deleteGraphicalAttribute(improperKey as any, testLink)).toThrow(
`key should be a string, was given ${
improperKey && improperKey.toString()
} of type ${typeof improperKey}`,
);
});
it('throw given an improper link', () => {
// given
// when
// expect
expect(() => Link.deleteGraphicalAttribute(key, improperLink)).toThrow(
isNotLinkException,
);
});
});
}); | the_stack |
import { assert } from 'chai'
import { Group } from '../src/Group'
import { Test } from '../src/Test'
import { TimeoutException } from '../src/Exceptions'
import { getFn, sleep } from './helpers'
describe('Group', () => {
it('should register the tests to be invoked later', async () => {
const group = new Group('sample', getFn([]), getFn([]), { bail: false, timeout: 2000 })
group.test('sample test', function cb () {})
assert.lengthOf(group['_tests'], 1)
assert.instanceOf(group['_tests'][0], Test)
})
it('should run the test when running the group', async () => {
let invoked = false
const group = new Group('sample', getFn([]), getFn([]), { bail: false, timeout: 2000 })
group.test('sample test', function cb () {
invoked = true
})
await group.run()
assert.isTrue(invoked)
})
it('should run the before hooks when running the group', async () => {
const stack: string[] = []
const group = new Group('sample', getFn([]), getFn([]), { bail: false, timeout: 2000 })
group.test('sample test', function cb () {
stack.push('test')
})
group.before(function cb () {
stack.push('before')
})
await group.run()
assert.deepEqual(stack, ['before', 'test'])
})
it('should run the after hooks when running the group', async () => {
const stack: string[] = []
const group = new Group('sample', getFn([]), getFn([]), { bail: false, timeout: 2000 })
group.test('sample test', function cb () {
stack.push('test')
})
group.before(function cb () {
stack.push('before')
})
group.after(function cb () {
stack.push('after')
})
await group.run()
assert.deepEqual(stack, ['before', 'test', 'after'])
})
it('should not run the test and after hook, when before hook fails', async () => {
const stack: string[] = []
const group = new Group('sample', getFn([]), getFn([]), { bail: false, timeout: 2000 })
group.test('sample test', function cb () {
stack.push('test')
})
group.before(function cb () {
stack.push('before')
throw new Error('stop')
})
group.after(function cb () {
stack.push('after')
})
await group.run()
assert.deepEqual(stack, ['before'])
assert.equal(group.toJSON().status, 'failed')
assert.equal(group.toJSON().error!.message, 'stop')
})
it('should not run the upcoming before hooks, when before hook fails', async () => {
const stack: string[] = []
const group = new Group('sample', getFn([]), getFn([]), { bail: false, timeout: 2000 })
group.test('sample test', function cb () {
stack.push('test')
})
group.before(function cb () {
stack.push('before')
throw new Error('stop')
})
group.before(function cb () {
stack.push('before 2')
})
group.after(function cb () {
stack.push('after')
})
await group.run()
assert.deepEqual(stack, ['before'])
assert.equal(group.toJSON().status, 'failed')
assert.equal(group.toJSON().error!.message, 'stop')
})
it('run beforeEach hooks before each test', async () => {
const stack: string[] = []
const group = new Group('sample', getFn([]), getFn([]), { bail: false, timeout: 2000 })
group.before(function cb () {
stack.push('before')
})
group.beforeEach(function cb () {
stack.push('beforeEach')
})
group.test('sample test', function cb () {
stack.push('test')
})
group.test('sample test 2', function cb () {
stack.push('test 2')
})
await group.run()
assert.deepEqual(stack, ['before', 'beforeEach', 'test', 'beforeEach', 'test 2'])
assert.equal(group.toJSON().status, 'passed')
assert.isNull(group.toJSON().error)
})
it('run afterEach hooks after each test', async () => {
const stack: string[] = []
const group = new Group('sample', getFn([]), getFn([]), { bail: false, timeout: 2000 })
group.before(function cb () {
stack.push('before')
})
group.beforeEach(function cb () {
stack.push('beforeEach')
})
group.afterEach(function cb () {
stack.push('afterEach')
})
group.test('sample test', function cb () {
stack.push('test')
})
group.test('sample test', function cb () {
stack.push('test 2')
})
await group.run()
assert.deepEqual(stack, ['before', 'beforeEach', 'test', 'afterEach', 'beforeEach', 'test 2', 'afterEach'])
assert.equal(group.toJSON().status, 'passed')
assert.isNull(group.toJSON().error)
})
it('do not run test when beforeEach fails', async () => {
const stack: string[] = []
const group = new Group('sample', getFn([]), getFn([]), { bail: false, timeout: 2000 })
group.beforeEach(function cb () {
stack.push('beforeEach')
throw new Error('before each failed')
})
group.test('sample test', function cb () {
stack.push('test')
})
await group.run()
assert.deepEqual(stack, ['beforeEach'])
assert.equal(group.toJSON().status, 'failed')
assert.equal(group.toJSON().error!.message, 'before each failed')
})
it('do not run other beforeEach hooks when beforeEach fails', async () => {
const stack: string[] = []
const group = new Group('sample', getFn([]), getFn([]), { bail: false, timeout: 2000 })
group.beforeEach(function cb () {
stack.push('beforeEach')
throw new Error('before each failed')
})
group.beforeEach(function cb () {
stack.push('beforeEach 2')
})
group.test('sample test', function cb () {
stack.push('test')
})
await group.run()
assert.deepEqual(stack, ['beforeEach'])
assert.equal(group.toJSON().status, 'failed')
assert.equal(group.toJSON().error!.message, 'before each failed')
})
it('do not run other afterEach hooks when beforeEach fails', async () => {
const stack: string[] = []
const group = new Group('sample', getFn([]), getFn([]), { bail: false, timeout: 2000 })
group.beforeEach(function cb () {
stack.push('beforeEach')
throw new Error('before each failed')
})
group.afterEach(function cb () {
stack.push('afterEach')
})
group.test('sample test', function cb () {
stack.push('test')
})
await group.run()
assert.deepEqual(stack, ['beforeEach'])
assert.equal(group.toJSON().status, 'failed')
assert.equal(group.toJSON().error!.message, 'before each failed')
})
it('do not run other tests when beforeEach fails', async () => {
const stack: string[] = []
const group = new Group('sample', getFn([]), getFn([]), { bail: false, timeout: 2000 })
group.beforeEach(function cb () {
stack.push('beforeEach')
throw new Error('before each failed')
})
group.test('sample test', function cb () {
stack.push('test')
})
group.test('sample test 2', function cb () {
stack.push('test')
})
await group.run()
assert.deepEqual(stack, ['beforeEach'])
assert.equal(group.toJSON().status, 'failed')
assert.equal(group.toJSON().error!.message, 'before each failed')
})
it('do not run other tests when afterEach fails', async () => {
const stack: string[] = []
const group = new Group('sample', getFn([]), getFn([]), { bail: false, timeout: 2000 })
group.beforeEach(function cb () {
stack.push('beforeEach')
})
group.afterEach(function cb () {
stack.push('afterEach')
throw new Error('after each failed')
})
group.test('sample test', function cb () {
stack.push('test')
})
group.test('sample test 2', function cb () {
stack.push('test')
})
await group.run()
assert.deepEqual(stack, ['beforeEach', 'test', 'afterEach'])
assert.equal(group.toJSON().status, 'failed')
assert.equal(group.toJSON().error!.message, 'after each failed')
})
it('fail group when after hook fails', async () => {
const stack: string[] = []
const group = new Group('sample', getFn([]), getFn([]), { bail: false, timeout: 2000 })
group.beforeEach(function cb () {
stack.push('beforeEach')
})
group.afterEach(function cb () {
stack.push('afterEach')
})
group.after(function cb () {
throw new Error('after failed')
})
group.test('sample test', function cb () {
stack.push('test')
})
group.test('sample test 2', function cb () {
stack.push('test 2')
})
await group.run()
assert.deepEqual(stack, ['beforeEach', 'test', 'afterEach', 'beforeEach', 'test 2', 'afterEach'])
assert.equal(group.toJSON().status, 'failed')
assert.equal(group.toJSON().error!.message, 'after failed')
})
it('do not run other afterEach hooks when one fails', async () => {
const stack: string[] = []
const group = new Group('sample', getFn([]), getFn([]), { bail: false, timeout: 2000 })
group.beforeEach(function cb () {
stack.push('beforeEach')
})
group.afterEach(function cb () {
stack.push('afterEach')
throw new Error('after each failed')
})
group.afterEach(function cb () {
stack.push('afterEach 2')
throw new Error('after each failed')
})
group.test('sample test', function cb () {
stack.push('test')
})
group.test('sample test 2', function cb () {
stack.push('test')
})
await group.run()
assert.deepEqual(stack, ['beforeEach', 'test', 'afterEach'])
assert.equal(group.toJSON().status, 'failed')
assert.equal(group.toJSON().error!.message, 'after each failed')
})
it('define timeout for the test via group', async () => {
const group = new Group('sample', getFn([]), getFn([]), { bail: false, timeout: 2000 })
group.timeout(300)
const test = group.test('sample test', async function cb () {
await sleep(500)
})
await group.run()
assert.equal(test.toJSON().status, 'failed')
assert.instanceOf(test.toJSON().error, TimeoutException)
})
it('raise error when user try to give timeout to the group after adding tests', async () => {
const group = new Group('sample', getFn([]), getFn([]), { bail: false, timeout: 2000 })
group.test('sample test', async function cb () {
await sleep(500)
})
const fn = () => group.timeout(300)
assert.throw(fn, 'group.timeout must be called before defining the tests')
})
it('should not run before hooks when group has zero tests', async () => {
const stack: string[] = []
const group = new Group('sample', getFn([]), getFn([]), { bail: false, timeout: 2000 })
group.before(function cb () {
stack.push('before')
})
await group.run()
assert.deepEqual(stack, [])
})
it('should not run beforeEach hooks when group has zero tests', async () => {
const stack: string[] = []
const group = new Group('sample', getFn([]), getFn([]), { bail: false, timeout: 2000 })
group.beforeEach(function cb () {
stack.push('beforeEach')
})
await group.run()
assert.deepEqual(stack, [])
})
it('should not run after hooks when group has zero tests', async () => {
const stack: string[] = []
const group = new Group('sample', getFn([]), getFn([]), { bail: false, timeout: 2000 })
group.after(function cb () {
stack.push('after')
})
await group.run()
assert.deepEqual(stack, [])
})
it('should not run afterEach hooks when group has zero tests', async () => {
const stack: string[] = []
const group = new Group('sample', getFn([]), getFn([]), { bail: false, timeout: 2000 })
group.afterEach(function cb () {
stack.push('afterEach')
})
await group.run()
assert.deepEqual(stack, [])
})
it('do not run hooks when tests are removed using grep filter', async () => {
const stack: string[] = []
const group = new Group('sample', getFn([]), getFn([]), {
bail: false,
timeout: 2000,
grep: new RegExp('foo'),
})
group.test('sample', function cb () {
stack.push('test')
})
group.before(function cb () {
stack.push('before')
})
await group.run()
assert.deepEqual(stack, [])
})
it('do not register tests after the .only test', async () => {
const stack: string[] = []
const group = new Group('sample', getFn([]), getFn([]), {
bail: false,
timeout: 2000,
})
group.test('sample', function cb () {
stack.push('sample')
}, { only: true })
group.test('another sample', function cb () {
stack.push('another sample')
})
await group.run()
assert.deepEqual(stack, ['sample'])
})
it('remove tests registered before the .only test', async () => {
const stack: string[] = []
const group = new Group('sample', getFn([]), getFn([]), {
bail: false,
timeout: 2000,
})
group.test('another sample', function cb () {
stack.push('another sample')
})
group.test('sample', function cb () {
stack.push('sample')
}, { only: true })
await group.run()
assert.deepEqual(stack, ['sample'])
})
}) | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/snapshotOperationsMappers";
import * as Parameters from "../models/parameters";
import { FaceClientContext } from "../faceClientContext";
/** Class representing a SnapshotOperations. */
export class SnapshotOperations {
private readonly client: FaceClientContext;
/**
* Create a SnapshotOperations.
* @param {FaceClientContext} client Reference to the service client.
*/
constructor(client: FaceClientContext) {
this.client = client;
}
/**
* Submit an operation to take a snapshot of face list, large face list, person group or large
* person group, with user-specified snapshot type, source object id, apply scope and an optional
* user data.<br />
* The snapshot interfaces are for users to backup and restore their face data from one face
* subscription to another, inside same region or across regions. The workflow contains two phases,
* user first calls Snapshot - Take to create a copy of the source object and store it as a
* snapshot, then calls Snapshot - Apply to paste the snapshot to target subscription. The
* snapshots are stored in a centralized location (per Azure instance), so that they can be applied
* cross accounts and regions.<br />
* Taking snapshot is an asynchronous operation. An operation id can be obtained from the
* "Operation-Location" field in response header, to be used in OperationStatus - Get for tracking
* the progress of creating the snapshot. The snapshot id will be included in the
* "resourceLocation" field in OperationStatus - Get response when the operation status is
* "succeeded".<br />
* Snapshot taking time depends on the number of person and face entries in the source object. It
* could be in seconds, or up to several hours for 1,000,000 persons with multiple faces.<br />
* Snapshots will be automatically expired and cleaned in 48 hours after it is created by Snapshot
* - Take. User can delete the snapshot using Snapshot - Delete by themselves any time before
* expiration.<br />
* Taking snapshot for a certain object will not block any other operations against the object. All
* read-only operations (Get/List and Identify/FindSimilar/Verify) can be conducted as usual. For
* all writable operations, including Add/Update/Delete the source object or its persons/faces and
* Train, they are not blocked but not recommended because writable updates may not be reflected on
* the snapshot during its taking. After snapshot taking is completed, all readable and writable
* operations can work as normal. Snapshot will also include the training results of the source
* object, which means target subscription the snapshot applied to does not need re-train the
* target object before calling Identify/FindSimilar.<br />
* * Free-tier subscription quota: 100 take operations per month.
* * S0-tier subscription quota: 100 take operations per day.
* @param type User specified type for the source object to take snapshot from. Currently FaceList,
* PersonGroup, LargeFaceList and LargePersonGroup are supported. Possible values include:
* 'FaceList', 'LargeFaceList', 'LargePersonGroup', 'PersonGroup'
* @param objectId User specified source object id to take snapshot from.
* @param applyScope User specified array of target Face subscription ids for the snapshot. For
* each snapshot, only subscriptions included in the applyScope of Snapshot - Take can apply it.
* @param [options] The optional parameters
* @returns Promise<Models.SnapshotTakeResponse>
*/
take(type: Models.SnapshotObjectType, objectId: string, applyScope: string[], options?: Models.SnapshotTakeOptionalParams): Promise<Models.SnapshotTakeResponse>;
/**
* @param type User specified type for the source object to take snapshot from. Currently FaceList,
* PersonGroup, LargeFaceList and LargePersonGroup are supported. Possible values include:
* 'FaceList', 'LargeFaceList', 'LargePersonGroup', 'PersonGroup'
* @param objectId User specified source object id to take snapshot from.
* @param applyScope User specified array of target Face subscription ids for the snapshot. For
* each snapshot, only subscriptions included in the applyScope of Snapshot - Take can apply it.
* @param callback The callback
*/
take(type: Models.SnapshotObjectType, objectId: string, applyScope: string[], callback: msRest.ServiceCallback<void>): void;
/**
* @param type User specified type for the source object to take snapshot from. Currently FaceList,
* PersonGroup, LargeFaceList and LargePersonGroup are supported. Possible values include:
* 'FaceList', 'LargeFaceList', 'LargePersonGroup', 'PersonGroup'
* @param objectId User specified source object id to take snapshot from.
* @param applyScope User specified array of target Face subscription ids for the snapshot. For
* each snapshot, only subscriptions included in the applyScope of Snapshot - Take can apply it.
* @param options The optional parameters
* @param callback The callback
*/
take(type: Models.SnapshotObjectType, objectId: string, applyScope: string[], options: Models.SnapshotTakeOptionalParams, callback: msRest.ServiceCallback<void>): void;
take(type: Models.SnapshotObjectType, objectId: string, applyScope: string[], options?: Models.SnapshotTakeOptionalParams | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<Models.SnapshotTakeResponse> {
return this.client.sendOperationRequest(
{
type,
objectId,
applyScope,
options
},
takeOperationSpec,
callback) as Promise<Models.SnapshotTakeResponse>;
}
/**
* List all accessible snapshots with related information, including snapshots that were taken by
* the user, or snapshots to be applied to the user (subscription id was included in the applyScope
* in Snapshot - Take).
* @param [options] The optional parameters
* @returns Promise<Models.SnapshotListResponse>
*/
list(options?: Models.SnapshotListOptionalParams): Promise<Models.SnapshotListResponse>;
/**
* @param callback The callback
*/
list(callback: msRest.ServiceCallback<Models.Snapshot[]>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
list(options: Models.SnapshotListOptionalParams, callback: msRest.ServiceCallback<Models.Snapshot[]>): void;
list(options?: Models.SnapshotListOptionalParams | msRest.ServiceCallback<Models.Snapshot[]>, callback?: msRest.ServiceCallback<Models.Snapshot[]>): Promise<Models.SnapshotListResponse> {
return this.client.sendOperationRequest(
{
options
},
listOperationSpec,
callback) as Promise<Models.SnapshotListResponse>;
}
/**
* Retrieve information about a snapshot. Snapshot is only accessible to the source subscription
* who took it, and target subscriptions included in the applyScope in Snapshot - Take.
* @param snapshotId Id referencing a particular snapshot.
* @param [options] The optional parameters
* @returns Promise<Models.SnapshotGetResponse>
*/
get(snapshotId: string, options?: msRest.RequestOptionsBase): Promise<Models.SnapshotGetResponse>;
/**
* @param snapshotId Id referencing a particular snapshot.
* @param callback The callback
*/
get(snapshotId: string, callback: msRest.ServiceCallback<Models.Snapshot>): void;
/**
* @param snapshotId Id referencing a particular snapshot.
* @param options The optional parameters
* @param callback The callback
*/
get(snapshotId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Snapshot>): void;
get(snapshotId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Snapshot>, callback?: msRest.ServiceCallback<Models.Snapshot>): Promise<Models.SnapshotGetResponse> {
return this.client.sendOperationRequest(
{
snapshotId,
options
},
getOperationSpec,
callback) as Promise<Models.SnapshotGetResponse>;
}
/**
* Update the information of a snapshot. Only the source subscription who took the snapshot can
* update the snapshot.
* @param snapshotId Id referencing a particular snapshot.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
update(snapshotId: string, options?: Models.SnapshotUpdateOptionalParams): Promise<msRest.RestResponse>;
/**
* @param snapshotId Id referencing a particular snapshot.
* @param callback The callback
*/
update(snapshotId: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param snapshotId Id referencing a particular snapshot.
* @param options The optional parameters
* @param callback The callback
*/
update(snapshotId: string, options: Models.SnapshotUpdateOptionalParams, callback: msRest.ServiceCallback<void>): void;
update(snapshotId: string, options?: Models.SnapshotUpdateOptionalParams | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
snapshotId,
options
},
updateOperationSpec,
callback);
}
/**
* Delete an existing snapshot according to the snapshotId. All object data and information in the
* snapshot will also be deleted. Only the source subscription who took the snapshot can delete the
* snapshot. If the user does not delete a snapshot with this API, the snapshot will still be
* automatically deleted in 48 hours after creation.
* @param snapshotId Id referencing a particular snapshot.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(snapshotId: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param snapshotId Id referencing a particular snapshot.
* @param callback The callback
*/
deleteMethod(snapshotId: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param snapshotId Id referencing a particular snapshot.
* @param options The optional parameters
* @param callback The callback
*/
deleteMethod(snapshotId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
deleteMethod(snapshotId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
snapshotId,
options
},
deleteMethodOperationSpec,
callback);
}
/**
* Submit an operation to apply a snapshot to current subscription. For each snapshot, only
* subscriptions included in the applyScope of Snapshot - Take can apply it.<br />
* The snapshot interfaces are for users to backup and restore their face data from one face
* subscription to another, inside same region or across regions. The workflow contains two phases,
* user first calls Snapshot - Take to create a copy of the source object and store it as a
* snapshot, then calls Snapshot - Apply to paste the snapshot to target subscription. The
* snapshots are stored in a centralized location (per Azure instance), so that they can be applied
* cross accounts and regions.<br />
* Applying snapshot is an asynchronous operation. An operation id can be obtained from the
* "Operation-Location" field in response header, to be used in OperationStatus - Get for tracking
* the progress of applying the snapshot. The target object id will be included in the
* "resourceLocation" field in OperationStatus - Get response when the operation status is
* "succeeded".<br />
* Snapshot applying time depends on the number of person and face entries in the snapshot object.
* It could be in seconds, or up to 1 hour for 1,000,000 persons with multiple faces.<br />
* Snapshots will be automatically expired and cleaned in 48 hours after it is created by Snapshot
* - Take. So the target subscription is required to apply the snapshot in 48 hours since its
* creation.<br />
* Applying a snapshot will not block any other operations against the target object, however it is
* not recommended because the correctness cannot be guaranteed during snapshot applying. After
* snapshot applying is completed, all operations towards the target object can work as normal.
* Snapshot also includes the training results of the source object, which means target
* subscription the snapshot applied to does not need re-train the target object before calling
* Identify/FindSimilar.<br />
* One snapshot can be applied multiple times in parallel, while currently only CreateNew apply
* mode is supported, which means the apply operation will fail if target subscription already
* contains an object of same type and using the same objectId. Users can specify the "objectId" in
* request body to avoid such conflicts.<br />
* * Free-tier subscription quota: 100 apply operations per month.
* * S0-tier subscription quota: 100 apply operations per day.
* @param snapshotId Id referencing a particular snapshot.
* @param objectId User specified target object id to be created from the snapshot.
* @param [options] The optional parameters
* @returns Promise<Models.SnapshotApplyResponse>
*/
apply(snapshotId: string, objectId: string, options?: Models.SnapshotApplyOptionalParams): Promise<Models.SnapshotApplyResponse>;
/**
* @param snapshotId Id referencing a particular snapshot.
* @param objectId User specified target object id to be created from the snapshot.
* @param callback The callback
*/
apply(snapshotId: string, objectId: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param snapshotId Id referencing a particular snapshot.
* @param objectId User specified target object id to be created from the snapshot.
* @param options The optional parameters
* @param callback The callback
*/
apply(snapshotId: string, objectId: string, options: Models.SnapshotApplyOptionalParams, callback: msRest.ServiceCallback<void>): void;
apply(snapshotId: string, objectId: string, options?: Models.SnapshotApplyOptionalParams | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<Models.SnapshotApplyResponse> {
return this.client.sendOperationRequest(
{
snapshotId,
objectId,
options
},
applyOperationSpec,
callback) as Promise<Models.SnapshotApplyResponse>;
}
/**
* Retrieve the status of a take/apply snapshot operation.
* @param operationId Id referencing a particular take/apply snapshot operation.
* @param [options] The optional parameters
* @returns Promise<Models.SnapshotGetOperationStatusResponse>
*/
getOperationStatus(operationId: string, options?: msRest.RequestOptionsBase): Promise<Models.SnapshotGetOperationStatusResponse>;
/**
* @param operationId Id referencing a particular take/apply snapshot operation.
* @param callback The callback
*/
getOperationStatus(operationId: string, callback: msRest.ServiceCallback<Models.OperationStatus>): void;
/**
* @param operationId Id referencing a particular take/apply snapshot operation.
* @param options The optional parameters
* @param callback The callback
*/
getOperationStatus(operationId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.OperationStatus>): void;
getOperationStatus(operationId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.OperationStatus>, callback?: msRest.ServiceCallback<Models.OperationStatus>): Promise<Models.SnapshotGetOperationStatusResponse> {
return this.client.sendOperationRequest(
{
operationId,
options
},
getOperationStatusOperationSpec,
callback) as Promise<Models.SnapshotGetOperationStatusResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const takeOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "snapshots",
urlParameters: [
Parameters.endpoint
],
requestBody: {
parameterPath: {
type: "type",
objectId: "objectId",
applyScope: "applyScope",
userData: [
"options",
"userData"
]
},
mapper: {
...Mappers.TakeSnapshotRequest,
required: true
}
},
responses: {
202: {
headersMapper: Mappers.SnapshotTakeHeaders
},
default: {
bodyMapper: Mappers.APIError
}
},
serializer
};
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "snapshots",
urlParameters: [
Parameters.endpoint
],
queryParameters: [
Parameters.type,
Parameters.applyScope
],
responses: {
200: {
bodyMapper: {
serializedName: "parsedResponse",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "Snapshot"
}
}
}
}
},
default: {
bodyMapper: Mappers.APIError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "snapshots/{snapshotId}",
urlParameters: [
Parameters.endpoint,
Parameters.snapshotId
],
responses: {
200: {
bodyMapper: Mappers.Snapshot
},
default: {
bodyMapper: Mappers.APIError
}
},
serializer
};
const updateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "snapshots/{snapshotId}",
urlParameters: [
Parameters.endpoint,
Parameters.snapshotId
],
requestBody: {
parameterPath: {
applyScope: [
"options",
"applyScope"
],
userData: [
"options",
"userData"
]
},
mapper: {
...Mappers.UpdateSnapshotRequest,
required: true
}
},
responses: {
200: {},
default: {
bodyMapper: Mappers.APIError
}
},
serializer
};
const deleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "snapshots/{snapshotId}",
urlParameters: [
Parameters.endpoint,
Parameters.snapshotId
],
responses: {
200: {},
default: {
bodyMapper: Mappers.APIError
}
},
serializer
};
const applyOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "snapshots/{snapshotId}/apply",
urlParameters: [
Parameters.endpoint,
Parameters.snapshotId
],
requestBody: {
parameterPath: {
objectId: "objectId",
mode: [
"options",
"mode"
]
},
mapper: {
...Mappers.ApplySnapshotRequest,
required: true
}
},
responses: {
202: {
headersMapper: Mappers.SnapshotApplyHeaders
},
default: {
bodyMapper: Mappers.APIError
}
},
serializer
};
const getOperationStatusOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "operations/{operationId}",
urlParameters: [
Parameters.endpoint,
Parameters.operationId
],
responses: {
200: {
bodyMapper: Mappers.OperationStatus
},
default: {
bodyMapper: Mappers.APIError
}
},
serializer
}; | the_stack |
import * as React from "react"
import * as ReactDOM from "react-dom"
import * as tconf from './BlocklyToolbox/ToolboxUtils'
import 'semantic-ui-css/semantic.min.css'
import './BlocklyToolbox/toolbox.less'
import {CreateFunctionDialog} from "./CreateFunction";
import {ToolboxCategorySpecial} from "./BlocklyToolbox/Toolbox/Common";
// this is a supertype of pxtc.SymbolInfo (see partitionBlocks)
export interface BlockDefinition {
name: string;
xml: string;
group?: string;
description?: string;
}
export interface ToolboxProps {
editorname: string;
blockly: any;
categories: ToolboxCategory[];
//parent: editor.ToolboxEditor;
}
export interface SearchInfo {
id: string;
name: string;
qName?: string;
block?: string;
namespace?: string;
jsdoc?: string;
field?: [string, string];
localizedCategory?: string;
builtinBlock?: boolean;
}
export interface ToolboxState {
showAdvanced?: boolean;
selectedItem: number;
expandedItem?: number;
height?: number;
showSearchBox?: boolean;
hasSearch?: boolean;
focusSearch?: boolean;
searchBlocks?: SearchInfo[]; // block ids
hasError?: boolean;
}
export class Toolbox extends React.Component<ToolboxProps, ToolboxState> {
private selectedItem: CategoryItem | undefined;
private selectedIndex: number;
private items: ToolboxCategory[];
private rootElement: HTMLElement | undefined;
private categories: ToolboxCategory[];
private Blockly: any;
private workspace: any;
private variablesCat: ToolboxCategory | undefined;
private functionsCat: ToolboxCategory | undefined;
private functionsDialog: CreateFunctionDialog | null = null;
private searchFlyout: any;
constructor(props: ToolboxProps) {
super(props);
this.state = {
showAdvanced: false,
selectedItem: -1
};
this.setSelection = this.setSelection.bind(this);
this.advancedClicked = this.advancedClicked.bind(this);
this.recipesClicked = this.recipesClicked.bind(this);
this.recoverToolbox = this.recoverToolbox.bind(this);
this.selectedIndex = -1;
this.items = [];
this.Blockly = props.blockly;
this.workspace = this.Blockly.getMainWorkspace();
this.categories = [];
this.loadToolbox(this.props.categories);
this.Blockly.addChangeListener((e: any) => {
this.rebuildFunctionsFlyout();
if([ "var_create", "var_delete", "var_rename" ].indexOf(e.type) != -1){
this.rebuildVariablesFlyout();
}else if(e.type == "create"){
if(!this.workspace.toolbox_.flyout_.isVisible()) this.clearSelection();
}
});
this.Blockly.Functions.editFunctionExternalHandler = (mutation: Element, cb: any /*Blockly.Functions.ConfirmEditCallback*/) => {
Promise.resolve()
//.delay(10)
.then(() => {
if (!this.functionsDialog) {
const wrapper = document.body.appendChild(document.createElement('div'));
this.functionsDialog = ReactDOM.render(React.createElement(CreateFunctionDialog, { blockly: this.Blockly, functionCreateCallback: () => this.rebuildFunctionsFlyout() }), wrapper) as CreateFunctionDialog;
}
this.functionsDialog.show(mutation, cb, this.workspace);
});
}
}
public loadToolbox(categories: ToolboxCategory[]){
this.categories = categories;
this.categories.forEach(cat => this.buildCategoryFlyout(cat, this));
}
public rebuildVariablesFlyout(){
if(!this.variablesCat) return;
this.variablesCat.flyout = this.buildFlyout(this.variablesCat, this, undefined, true);
}
rebuildFunctionsFlyout(){
if(!this.functionsCat) return;
this.functionsCat.flyout = this.buildFlyout(this.functionsCat, this, undefined, true);
}
buildCategoryFlyout(category: ToolboxCategory, toolbox: Toolbox, parent?: ToolboxCategory){
if(category.special == ToolboxCategorySpecial.VARIABLES){
this.variablesCat = category;
}else if(category.special == ToolboxCategorySpecial.FUNCTIONS){
this.functionsCat = category;
}
category.flyout = toolbox.buildFlyout(category, toolbox, parent);
category.subcategories.forEach(cat => toolbox.buildCategoryFlyout(cat, toolbox, category));
}
constructLabel(text: string){
return this.createFlyoutGroupLabel(text);
}
createFlyoutGroupLabel(name: string, icon?: string, labelLineWidth?: string, helpCallback?: string) {
const groupLabel = this.createFlyoutLabel(name, undefined, icon);
groupLabel.setAttribute('web-class', 'blocklyFlyoutGroup');
groupLabel.setAttribute('web-line', '1.5');
if (labelLineWidth) groupLabel.setAttribute('web-line-width', labelLineWidth);
if (helpCallback) {
groupLabel.setAttribute('web-help-button', 'true');
groupLabel.setAttribute('callbackkey', helpCallback);
}
return groupLabel;
}
createFlyoutHeadingLabel(name: string, color: string, icon?: string, iconClass?: string) {
const headingLabel = this.createFlyoutLabel(name, tconf.convertColor(color), icon, iconClass);
headingLabel.setAttribute('web-class', 'blocklyFlyoutHeading');
return headingLabel;
}
showFlyoutHeadingLabel(name: string, icon: string, color: string) {
const categoryName = name;
const iconClass = `blocklyTreeIcon${icon ? name.toLowerCase() : 'Default'}`.replace(/\s/g, '');
let headingLabel = this.createFlyoutHeadingLabel(categoryName, color, icon, iconClass);
return headingLabel;
}
createFlyoutLabel(name: string, color?: string, icon?: string, iconClass?: string): HTMLElement {
// Add the Heading label
let headingLabel = document.createElement("label") as HTMLElement;
headingLabel.setAttribute('text', name);
if (color) {
headingLabel.setAttribute('web-icon-color', tconf.convertColor(color));
}
if (icon) {
if (icon.length === 1) {
headingLabel.setAttribute('web-icon', icon);
if (iconClass) headingLabel.setAttribute('web-icon-class', iconClass);
}
else {
headingLabel.setAttribute('web-icon-class', `blocklyFlyoutIcon${name}`);
}
}
return headingLabel;
}
search(term: string){
let workspace: any = this.workspace;
let flyout: any = this.searchFlyout ? this.searchFlyout : this.Blockly.Functions.createFlyout(workspace, workspace.toolbox_.flyout_.svgGroup_);
this.searchFlyout = flyout;
this.clear();
if(term == ""){
flyout.setVisible(false);
return;
}
let blocks: any[] = [];
let Blockly = this.Blockly;
function searchCategories(cat: ToolboxCategory){
if(!cat.blocks) return;
cat.blocks.forEach((block: any) => {
if(block.name.replace(/_/g, " ").toLowerCase().includes(term.toLowerCase())){
blocks.push(Blockly.Xml.textToDom(block.xml));
}
});
cat.subcategories.forEach(searchCategories);
}
this.categories.forEach(searchCategories);
if(blocks.length == 0){
blocks.push(this.constructLabel("No results"));
}
flyout.show(blocks);
flyout.setVisible(true);
this.workspace.toolbox_.flyout_ = flyout;
}
buildFlyout(category: ToolboxCategory, toolbox: Toolbox, parent?: ToolboxCategory, visible?: boolean){
let workspace: any = toolbox.workspace;
let flyout: any = category.flyout ? category.flyout : toolbox.Blockly.Functions.createFlyout(workspace, workspace.toolbox_.flyout_.svgGroup_);
let wasVisible = flyout.isVisible();
flyout.setVisible(false);
if(!category.blocks) return flyout;
let blocks: any[] = [];
let color: string = (category.color == "more" && parent) ? parent.color : category.color;
blocks.push(toolbox.showFlyoutHeadingLabel(category.name, category.icon, color));
if(category.special == ToolboxCategorySpecial.VARIABLES) {
toolbox.Blockly.Variables.flyoutCategory(toolbox.workspace).forEach((item: any) => blocks.push(item));
}else if(category.special == ToolboxCategorySpecial.FUNCTIONS){
toolbox.Blockly.Functions.flyoutCategory(toolbox.workspace).forEach((item: any) => blocks.push(item));
}else{
let currentLabel: string = "";
category.blocks.forEach(block => {
let label = block.group;
if(label && label != currentLabel){
currentLabel = label;
blocks.push(toolbox.constructLabel(label));
}
blocks.push(toolbox.Blockly.Xml.textToDom(block.xml));
});
}
flyout.show(blocks);
flyout.setVisible((!!visible) && wasVisible);
return flyout;
}
reflowLayout(cat: ToolboxCategory){
if(cat.flyout) cat.flyout.reflow();
cat.subcategories.forEach((c) => this.reflowLayout(c));
}
setSelectedItem(item: CategoryItem) {
this.selectedItem = item;
}
setPreviousItem() {
if (this.selectedIndex > 0) {
const newIndex = --this.selectedIndex;
// Check if the previous item has a subcategory
let previousItem = this.items[newIndex];
this.setSelection(previousItem, newIndex);
} else if (this.state.showSearchBox) {
// Focus the search box if it exists
const searchBox = this.refs.searchbox as ToolboxSearch;
if (searchBox) searchBox.focus();
}
}
setNextItem() {
if (this.items.length - 1 > this.selectedIndex) {
const newIndex = ++this.selectedIndex;
this.setSelection(this.items[newIndex], newIndex);
}
}
setSearch() {
// Focus the search box if it exists
const searchBox = this.refs.searchbox as ToolboxSearch;
if (searchBox) searchBox.focus();
}
clear() {
this.closeFlyout();
this.clearSelection();
this.selectedIndex = 0;
this.selectedTreeRow = undefined;
}
clearSelection() {
this.setState({ selectedItem: -1, expandedItem: undefined, focusSearch: false })
}
clearSearch() {
this.setState({ hasSearch: false, searchBlocks: undefined, focusSearch: false });
}
setSelection(category: ToolboxCategory, index: number) {
if (this.state.selectedItem == index) {
this.clearSelection();
this.closeFlyout();
} else {
/*if (customClick) {
handled = customClick(parent);
if (handled) return;
}*/
// TODO: custom click. ako je handlan, niš dalje
this.setState({ selectedItem: index, expandedItem: index, focusSearch: false });
this.selectedIndex = index;
this.selectedTreeRow = category;
if (category.advanced && !this.state.showAdvanced) this.showAdvanced();
if (true /*!customClick*/) {
// Show flyout
this.showFlyout(category);
}
}
}
selectFirstItem() {
if (this.items[0]) {
this.setSelection(this.items[0], 0);
}
}
moveFocusToFlyout() {
/*const { parent } = this.props;
parent.moveFocusToFlyout();*/
}
componentDidUpdate(prevProps: ToolboxProps, prevState: ToolboxState) {
if (prevState.showAdvanced != this.state.showAdvanced
|| this.state.expandedItem != prevState.expandedItem) {
//this.props.parent.resize();
}
if (this.state.hasSearch && this.state.searchBlocks != prevState.searchBlocks) {
// Referesh search items
this.refreshSearchItem();
} else if (prevState.hasSearch && !this.state.hasSearch && this.state.selectedItem == 0) {
// No more search
this.closeFlyout();
}
this.categories.forEach((cat) => this.reflowLayout(cat));
}
componentDidCatch(error: any, info: any) {
// Log what happened
const { editorname } = this.props;
// Update error state
this.setState({ hasError: true });
}
recoverToolbox() {
// Recover from above error state
this.setState({ hasError: false });
}
advancedClicked() {
const { editorname } = this.props;
this.showAdvanced();
}
recipesClicked() {
const { editorname } = this.props;
//this.props.parent.parent.showRecipesDialog();
}
showAdvanced() {
//const { parent } = this.props;
if (this.selectedItem && this.selectedItem.props.treeRow
&& this.selectedItem.props.treeRow.advanced) {
this.clear();
this.closeFlyout();
}
this.setState({ showAdvanced: !this.state.showAdvanced });
}
/* getSearchBlocks(): BlockDefinition[] {
const { parent } = this.props;
const { searchBlocks } = this.state;
return searchBlocks.map(searchResult => {
return {
name: searchResult.qName,
attributes: {
blockId: searchResult.id
},
builtinBlock: searchResult.builtinBlock,
builtinField: searchResult.field
}
});
}*/
refreshSelection() {
//const { parent } = this.props;
if (!this.state.selectedItem || !this.selectedTreeRow) return;
if (false /*this.selectedTreeRow.customClick*/) {
//this.selectedTreeRow.customClick(parent);
} else {
this.showFlyout(this.selectedTreeRow);
}
}
refreshSearchItem() {
/*const searchTreeRow = ToolboxSearch.getSearchTreeRow();
this.showFlyout(searchTreeRow);*/
}
private selectedTreeRow: ToolboxCategory | undefined;
private showFlyout(treeRow: ToolboxCategory) {
this.closeFlyout();
this.workspace.toolbox_.flyout_ = treeRow.flyout;
this.workspace.toolbox_.flyout_.setVisible(true);
this.workspace.toolbox_.flyout_.scrollToStart();
this.workspace.toolbox_.flyout_.position();
}
closeFlyout() {
this.workspace.toolbox_.flyout_.setVisible(false);
}
handleRootElementRef = (c: HTMLDivElement) => {
this.rootElement = c;
};
render() {
const { editorname/*, parent*/ } = this.props;
const { showAdvanced, selectedItem, expandedItem, hasError } = this.state;
let visible = true;
let hasSearch = true;
let loading = false;
if (!visible) return <div style={{ display: 'none' }} />
let showSearchBox = true;
const theme = "default"; //pxt.appTarget.appTheme;
//const hasTopBlocks = !!theme.topBlocks && !inTutorial;
if (loading || hasError) return <div>
<div className="blocklyTreeRoot">
<div className="blocklyTreeRow" style={{ opacity: 0 }} />
</div>`
{loading ? <div className="ui active dimmer">
<div className="ui loader indeterminate" />
</div> : undefined}
{hasError ? <div className="ui">
{ "Toolbox crashed.." }
</div> : undefined}
</div>;
const hasAdvanced = false;
const normalCategories: ToolboxCategory[] = this.categories;
const advancedCategories: ToolboxCategory[] = [];
let index = 0;
return <div ref={this.handleRootElementRef} className={ "pxtToolbox" } id={`${editorname}EditorToolbox`}>
<ToolboxStyle categories={normalCategories} />
<ToolboxSearch ref="searchbox" toolbox={this} editorname={editorname} />
<div className="blocklyTreeRoot">
<div role="tree">
{normalCategories.map((treeRow) => { let i = index++;
return <CategoryItem toolbox={this} key={ "catitem_" + i } index={i} treeRow={treeRow}
onCategoryClick={this.setSelection}>
{treeRow.subcategories.map((subTreeRow) => {
let j = index++;
return <CategoryItem key={"catitem_" + j} index={j} toolbox={this} treeRow={subTreeRow}
parentTreeRow={treeRow} onCategoryClick={this.setSelection}/>
})}
</CategoryItem>
})}
{hasAdvanced ? <TreeSeparator key="advancedseparator" /> : undefined}
{hasAdvanced ? <CategoryItem index={ -1 } toolbox={this} treeRow={{ subcategories: [], name: tconf.advancedTitle(), color: tconf.getNamespaceColor('advanced'), icon: tconf.getNamespaceIcon(showAdvanced ? 'advancedexpanded' : 'advancedcollapsed') }} onCategoryClick={this.advancedClicked} /> : undefined}
{showAdvanced ? advancedCategories.map((treeRow) => (
<CategoryItem toolbox={this} index={index++} treeRow={treeRow} onCategoryClick={this.setSelection}>
{treeRow.subcategories ? treeRow.subcategories.map((subTreeRow) => (
<CategoryItem toolbox={this} index={index++} treeRow={subTreeRow} onCategoryClick={this.setSelection} />
)) : undefined}
</CategoryItem>
)) : undefined}
</div>
</div>
</div>
}
}
export interface CategoryItemProps extends TreeRowProps {
toolbox: Toolbox;
onCategoryClick?: (treeRow: ToolboxCategory, index: number) => void;
index: number;
}
export interface CategoryItemState {
selected?: boolean;
}
export class CategoryItem extends React.Component<CategoryItemProps, CategoryItemState> {
private treeRowElement: TreeRow | undefined;
constructor(props: CategoryItemProps) {
super(props);
this.state = {
selected: props.selected
};
this.handleClick = this.handleClick.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
}
getTreeRow() {
return this.treeRowElement;
}
componentWillReceiveProps(nextProps: CategoryItemProps) {
const newState: CategoryItemState = {};
if (nextProps.selected != undefined) {
newState.selected = nextProps.selected;
}
if (Object.keys(newState).length > 0) this.setState(newState)
}
componentDidUpdate(prevProps: CategoryItemProps, prevState: CategoryItemState) {
const { toolbox } = this.props;
if (this.state.selected) {
this.props.toolbox.setSelectedItem(this);
if (!toolbox.state.focusSearch) this.focusElement();
}
}
focusElement() {
this.treeRowElement && this.treeRowElement.focus();
}
handleClick(e: React.MouseEvent<any>) {
const { treeRow, onCategoryClick, index } = this.props;
if(onCategoryClick) onCategoryClick(treeRow, index);
e.preventDefault();
e.stopPropagation();
}
TAB_KEY = 9;
ESC_KEY = 27;
ENTER_KEY = 13;
SPACE_KEY = 32;
keyCodeFromEvent(e: any) {
return (typeof e.which == "number") ? e.which : e.keyCode;
}
handleKeyDown(e: React.KeyboardEvent<HTMLElement>) {
const { toolbox } = this.props;
const isRtl = false;
const charCode = this.keyCodeFromEvent(e);
if (charCode == 40) { // DOWN
this.nextItem();
} else if (charCode == 38) { // UP
this.previousItem();
} else if ((charCode == 39 && !isRtl) || (charCode == 37 && isRtl)) { // (LEFT & LTR) || (RIGHT & RTL)
// Focus inside flyout
toolbox.moveFocusToFlyout();
} else if (charCode == 27) { // ESCAPE
// Close the flyout
toolbox.closeFlyout();
} else if (charCode == this.ENTER_KEY || charCode == this.SPACE_KEY) {
//sui.fireClickOnEnter.call(this, e);
} else if (charCode == this.TAB_KEY
|| charCode == 37 /* Left arrow key */
|| charCode == 39 /* Left arrow key */
|| charCode == 17 /* Ctrl Key */
|| charCode == 16 /* Shift Key */
|| charCode == 91 /* Cmd Key */) {
// Escape tab and shift key
} else {
toolbox.setSearch();
}
}
previousItem() {
const { toolbox } = this.props;
toolbox.setPreviousItem();
}
nextItem() {
const { toolbox } = this.props;
toolbox.setNextItem();
}
handleTreeRowRef = (c: TreeRow) => {
this.treeRowElement = c;
}
render() {
let selectedIndex: number = this.props.toolbox.state.selectedItem;
let selected: boolean = selectedIndex == this.props.index;
let childSelected: boolean = selectedIndex > this.props.index && selectedIndex <= this.props.index + this.props.treeRow.subcategories.length;
return <TreeItem>
<TreeRow ref={this.handleTreeRowRef} isRtl={ false } {...this.props} selected={ selected }
onClick={this.handleClick} onKeyDown={this.handleKeyDown} index={this.props.index} />
<TreeGroup visible={ selected || childSelected }>
{this.props.children}
</TreeGroup>
</TreeItem>
}
}
export interface ToolboxCategory {
name: string;
color: string;
icon: string;
blocks?: BlockDefinition[];
subcategories: ToolboxCategory[];
customClick?: () => boolean;
advanced?: boolean;
flyout?: any;
special?: ToolboxCategorySpecial;
}
export interface TreeRowProps {
treeRow: ToolboxCategory;
parentTreeRow?: ToolboxCategory;
onClick?: (e: React.MouseEvent<any>) => void;
onKeyDown?: (e: React.KeyboardEvent<any>) => void;
selected?: boolean;
isRtl?: boolean;
index: number;
}
export class TreeRow extends React.Component<TreeRowProps, {}> {
private treeRow: HTMLElement | undefined;
constructor(props: TreeRowProps) {
super(props);
this.state = {
}
this.onmouseenter = this.onmouseenter.bind(this);
this.onmouseleave = this.onmouseleave.bind(this);
}
focus() {
if (this.treeRow) this.treeRow.focus();
}
getProperties() {
const { treeRow } = this.props;
return treeRow;
}
onmouseenter() {
const appTheme = "default"; //pxt.appTarget.appTheme;
const metaColor = this.getMetaColor();
const invertedMultipler = /*appTheme.blocklyOptions
&& appTheme.blocklyOptions.toolboxOptions
&& appTheme.blocklyOptions.toolboxOptions.invertedMultiplier || */ 0.3;
//if (appTheme.invertedToolbox) {
if (false) {
//this.treeRow.style.backgroundColor = "#333"; /*pxt.toolbox.fadeColor(metaColor || '#ddd', invertedMultipler, false);*/
}
}
onmouseleave() {
const appTheme = "default"; //pxt.appTarget.appTheme;
const metaColor = this.getMetaColor();
//if (appTheme.invertedToolbox) {
if (false) {
//this.treeRow.style.backgroundColor = (metaColor || '#ddd');
}
}
getMetaColor() {
let color = (this.props.treeRow.color == "more" && this.props.parentTreeRow) ? this.props.parentTreeRow.color : this.props.treeRow.color;
return tconf.convertColor(color ? color : "black") || tconf.getNamespaceColor('default');
}
handleTreeRowRef = (c: HTMLDivElement) => {
this.treeRow = c;
}
render() {
const { selected, onClick, onKeyDown, isRtl, index } = this.props;
const { name, icon } = this.props.treeRow;
const metaColor = this.getMetaColor();
const invertedMultipler = /*appTheme.blocklyOptions
&& appTheme.blocklyOptions.toolboxOptions
&& appTheme.blocklyOptions.toolboxOptions.invertedMultiplier ||*/ 0.3;
let treeRowStyle: React.CSSProperties = {
paddingLeft: '0px',
borderLeft: `8px solid ${metaColor}`
};
let treeRowClass = 'blocklyTreeRow';
// Selected
if (selected) {
treeRowClass += ' blocklyTreeSelected';
treeRowStyle.backgroundColor = (metaColor || '#ddd');
treeRowStyle.color = '#fff';
}
// Icon
const iconClass = `blocklyTreeIcon${name == "More" ? 'more' : icon }`.replace(/\s/g, '');
let iconContent = name == "More" ? tconf.getNamespaceIcon('more') : icon || tconf.getNamespaceIcon('default');
let iconImageStyle: JSX.Element = <style></style>;
if (iconContent.length > 1) {
// It's probably an image icon, and not an icon code
iconImageStyle = <style>
{`.blocklyTreeIcon.${iconClass} {
background-image: url("${ "" /* pxt.webConfig.commitCdnUrl + "/" + encodeURI(icon) */ }")!important;
width: 30px;
height: 100%;
background-size: 20px !important;
background-repeat: no-repeat !important;
background-position: 50% 50% !important;
}`}
</style>;
iconContent = ""; // undefined;
}
return <div role="button" ref={this.handleTreeRowRef} className={treeRowClass}
style={treeRowStyle} tabIndex={0}
onMouseEnter={this.onmouseenter} onMouseLeave={this.onmouseleave}
onClick={onClick} onContextMenu={onClick} onKeyDown={onKeyDown /*? onKeyDown : sui.fireClickOnEnter*/}>
<span className="blocklyTreeIcon" role="presentation"></span>
{iconImageStyle}
<span style={{ display: 'inline-block' }} className={`blocklyTreeIcon ${iconClass}`} role="presentation">{iconContent}</span>
<span className="blocklyTreeLabel">{name}</span>
</div>
}
}
export class TreeSeparator extends React.Component<{}, {}> {
render() {
return <TreeItem>
<div className="blocklyTreeSeparator">
<span style={{ display: 'inline-block' }} role="presentation"></span>
</div>
</TreeItem>
}
}
export interface TreeItemProps {
selected?: boolean;
children?: any;
}
export class TreeItem extends React.Component<TreeItemProps, {}> {
render() {
const { selected } = this.props;
return <div role="treeitem" aria-selected={selected}>
{this.props.children}
</div>
}
}
export interface TreeGroupProps {
visible?: boolean;
children?: any;
}
export class TreeGroup extends React.Component<TreeGroupProps, {}> {
render() {
const { visible } = this.props;
return <div role="group" style={{ backgroundPosition: '0px 0px', 'display': visible ? 'block' : 'none' }}>
{this.props.children}
</div>
}
}
export interface ToolboxSearchProps {
//parent: editor.ToolboxEditor;
editorname: string;
toolbox: Toolbox;
}
export interface ToolboxSearchState {
searchAccessibilityLabel?: string;
}
export class ToolboxSearch extends React.Component<ToolboxSearchProps, ToolboxSearchState> {
constructor(props: ToolboxSearchProps) {
super(props);
this.state = {
};
this.searchImmediate = this.searchImmediate.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
this.handleChange = this.handleChange.bind(this);
}
private search = () => setTimeout(() => this.searchImmediate(), 300);
handleChange() {
this.search();
}
handleKeyDown(e: React.KeyboardEvent<any>) {
const { toolbox } = this.props;
let charCode = (typeof e.which == "number") ? e.which : e.keyCode
if (charCode === 40 /* Down Key */) {
// Select first item in the toolbox
toolbox.selectFirstItem();
}
}
focus() {
(this.refs.searchInput as HTMLInputElement).focus();
}
searchImmediate() {
const { /*parent,*/ toolbox, editorname } = this.props;
const searchTerm = (this.refs.searchInput as HTMLInputElement).value;
let searchAccessibilityLabel = '';
let hasSearch = false;
toolbox.search(searchTerm);
// Execute search
/*parent.searchAsync(searchTerm)
.done((blocks) => {
if (blocks.length == 0) {
searchAccessibilityLabel = lf("No search results...");
} else {
searchAccessibilityLabel = lf("{0} result matching '{1}'", blocks.length, searchTerm.toLowerCase());
}
hasSearch = searchTerm != '';
const newState: ToolboxState = {};
newState.hasSearch = hasSearch;
newState.searchBlocks = blocks;
newState.focusSearch = true;
if (hasSearch) newState.selectedItem = 'search';
toolbox.setState(newState);
this.setState({ searchAccessibilityLabel: searchAccessibilityLabel });
});*/
}
render() {
const { searchAccessibilityLabel } = this.state;
return <div id="blocklySearchArea">
<div id="blocklySearchInput" className="ui fluid icon input" role="search">
<input ref="searchInput" type="text" placeholder={ "Search..." }
onFocus={this.searchImmediate} onKeyDown={this.handleKeyDown} onChange={this.handleChange}
id="blocklySearchInputField" className="blocklySearchInputField"
aria-label={ "Search" }
autoComplete="off" autoCorrect="off" autoCapitalize="off" spellCheck={false} />
<i className="search icon" role="presentation" aria-hidden="true"></i>
<div className="accessible-hidden" id="blocklySearchLabel" aria-live="polite"> {searchAccessibilityLabel} </div>
</div>
</div>
}
}
export class ToolboxTrashIcon extends React.Component<{}, {}> {
render() {
return <div id="blocklyTrashIcon" style={{ opacity: 0, display: 'none' }}>
<i className="trash icon" aria-hidden="true"></i>
</div>
}
}
interface ToolboxStyleProps {
categories: ToolboxCategory[];
}
export class ToolboxStyle extends React.Component<ToolboxStyleProps, {}> {
addCategoryStyle(category: ToolboxCategory, parent?: ToolboxCategory){
let color: string = (category.color == "more" && parent) ? parent.color : category.color;
this.style +=
`span.docs.inlineblock.cat_${this.index} {
background-color: ${color};
border-color: ${tconf.fadeColor(color, 0.1, false)};
}\n`;
this.index++;
category.subcategories.forEach(subcat => this.addCategoryStyle(subcat, category));
}
private index: number = 0;
private style: string = "";
render() {
const { categories } = this.props;
let styles: string = "";
this.index = 0;
this.style = "";
categories.forEach(category => this.addCategoryStyle(category));
return <style>
{this.style}
</style>
}
}
export default Toolbox; | the_stack |
import {
Service,
ServiceConfig,
ServiceOptions,
util,
} from '@google-cloud/common';
import * as promisify from '@google-cloud/promisify';
import arrify = require('arrify');
import * as assert from 'assert';
import {describe, it, before, beforeEach} from 'mocha';
import * as proxyquire from 'proxyquire';
import {CoreOptions, OptionsWithUri, Response} from 'request';
import {Zone} from '../src';
let extended = false;
const fakePaginator = {
paginator: {
extend(esClass: Function, methods: string[]) {
if (esClass.name !== 'DNS') {
return;
}
extended = true;
methods = arrify(methods);
assert.strictEqual(esClass.name, 'DNS');
assert.deepStrictEqual(methods, ['getZones']);
},
streamify(methodName: string) {
return methodName;
},
},
};
class FakeService extends Service {
calledWith_: IArguments;
constructor(config: ServiceConfig, options?: ServiceOptions) {
super(config, options);
// eslint-disable-next-line prefer-rest-params
this.calledWith_ = arguments;
}
}
const fakeUtil = Object.assign({}, util, {
makeAuthenticatedRequestFactory() {},
});
const originalFakeUtil = Object.assign({}, fakeUtil);
let promisified = false;
const fakePromisify = Object.assign({}, promisify, {
// tslint:disable-next-line:variable-name
promisifyAll(esClass: Function, options: promisify.PromisifyAllOptions) {
if (esClass.name !== 'DNS') {
return;
}
promisified = true;
assert.deepStrictEqual(options.exclude, ['zone']);
},
});
class FakeZone {
calledWith_: IArguments;
constructor() {
// eslint-disable-next-line prefer-rest-params
this.calledWith_ = arguments;
}
}
describe('DNS', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let DNS: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let dns: any;
const PROJECT_ID = 'project-id';
before(() => {
DNS = proxyquire('../src', {
'@google-cloud/common': {
Service: FakeService,
},
'@google-cloud/paginator': fakePaginator,
'@google-cloud/promisify': fakePromisify,
'./zone': {
Zone: FakeZone,
},
}).DNS;
});
beforeEach(() => {
Object.assign(fakeUtil, originalFakeUtil);
dns = new DNS({
projectId: PROJECT_ID,
});
});
describe('instantiation', () => {
it('should extend the correct methods', () => {
assert(extended); // See `fakePaginator.extend`
});
it('should streamify the correct methods', () => {
assert.strictEqual(dns.getZonesStream, 'getZones');
});
it('should promisify all the things', () => {
assert(promisified);
});
it('should inherit from Service', () => {
assert(dns instanceof Service);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const calledWith = (dns as any).calledWith_[0];
const baseUrl = 'https://dns.googleapis.com/dns/v1';
assert.strictEqual(calledWith.baseUrl, baseUrl);
assert.deepStrictEqual(calledWith.scopes, [
'https://www.googleapis.com/auth/ndev.clouddns.readwrite',
'https://www.googleapis.com/auth/cloud-platform',
]);
assert.deepStrictEqual(
calledWith.packageJson,
// eslint-disable-next-line @typescript-eslint/no-var-requires
require('../../package.json')
);
});
it('should enable apiEndpoint override', () => {
const apiEndpoint = 'fake.endpoint';
dns = new DNS({
projectId: PROJECT_ID,
apiEndpoint,
});
const calledWith = dns.calledWith_[0];
assert.strictEqual(calledWith.apiEndpoint, apiEndpoint);
assert.strictEqual(calledWith.baseUrl, `https://${apiEndpoint}/dns/v1`);
});
});
describe('createZone', () => {
const zoneName = 'zone-name';
const config = {dnsName: 'dns-name'};
it('should throw if a zone name is not provided', () => {
assert.throws(() => {
dns.createZone();
}, /A zone name is required/);
});
it('should throw if a zone dnsname is not provided', () => {
assert.throws(() => {
dns.createZone(zoneName);
}, /A zone dnsName is required/);
assert.throws(() => {
dns.createZone(zoneName, {});
}, /A zone dnsName is required/);
});
it('should use a provided description', done => {
const cfg = Object.assign({}, config, {description: 'description'});
dns.request = (reqOpts: CoreOptions) => {
assert.strictEqual(reqOpts.json.description, cfg.description);
done();
};
dns.createZone(zoneName, cfg, assert.ifError);
});
it('should default a description to ""', done => {
dns.request = (reqOpts: CoreOptions) => {
assert.strictEqual(reqOpts.json.description, '');
done();
};
dns.createZone(zoneName, config, assert.ifError);
});
it('should make the correct API request', done => {
dns.request = (reqOpts: OptionsWithUri) => {
assert.strictEqual(reqOpts.method, 'POST');
assert.strictEqual(reqOpts.uri, '/managedZones');
const expectedBody = Object.assign({}, config, {
name: zoneName,
description: '',
});
assert.deepStrictEqual(reqOpts.json, expectedBody);
done();
};
dns.createZone(zoneName, config, assert.ifError);
});
describe('error', () => {
const error = new Error('Error.');
const apiResponse = {a: 'b', c: 'd'};
beforeEach(() => {
dns.request = (reqOpts: {}, callback: Function) => {
callback(error, apiResponse);
};
});
it('should execute callback with error and API response', done => {
dns.createZone(
zoneName,
config,
(err: Error, zone: Zone, apiResponse_: Response) => {
assert.strictEqual(err, error);
assert.strictEqual(zone, null);
assert.strictEqual(apiResponse_, apiResponse);
done();
}
);
});
});
describe('success', () => {
const apiResponse = {name: zoneName};
const zone = {};
beforeEach(() => {
dns.request = (reqOpts: {}, callback: Function) => {
callback(null, apiResponse);
};
dns.zone = () => {
return zone;
};
});
it('should create a zone from the response', done => {
dns.zone = (name: string) => {
assert.strictEqual(name, apiResponse.name);
setImmediate(done);
return zone;
};
dns.createZone(zoneName, config, assert.ifError);
});
it('should execute callback with zone and API response', done => {
dns.createZone(
zoneName,
config,
(err: Error, zone_: Zone, apiResponse_: Response) => {
assert.ifError(err);
assert.strictEqual(zone_, zone);
assert.strictEqual(apiResponse_, apiResponse);
done();
}
);
});
it('should set the metadata to the response', done => {
dns.createZone(zoneName, config, (err: Error, zone: Zone) => {
assert.strictEqual(zone.metadata, apiResponse);
done();
});
});
});
});
describe('getZones', () => {
it('should make the correct request', done => {
const query = {a: 'b', c: 'd'};
dns.request = (reqOpts: OptionsWithUri) => {
assert.strictEqual(reqOpts.uri, '/managedZones');
assert.strictEqual(reqOpts.qs, query);
done();
};
dns.getZones(query, assert.ifError);
});
it('should use an empty query if one was not provided', done => {
dns.request = (reqOpts: CoreOptions) => {
assert.strictEqual(Object.keys(reqOpts.qs).length, 0);
done();
};
dns.getZones(assert.ifError);
});
describe('error', () => {
const error = new Error('Error.');
const apiResponse = {a: 'b', c: 'd'};
beforeEach(() => {
dns.request = (reqOpts: {}, callback: Function) => {
callback(error, apiResponse);
};
});
it('should execute callback with error and API response', done => {
dns.getZones(
{},
(
err: Error,
zones: Zone[],
nextQuery: {},
apiResponse_: Response
) => {
assert.strictEqual(err, error);
assert.strictEqual(zones, null);
assert.strictEqual(nextQuery, null);
assert.strictEqual(apiResponse_, apiResponse);
done();
}
);
});
});
describe('success', () => {
const zone = {name: 'zone-1', a: 'b', c: 'd'};
const apiResponse = {managedZones: [zone]};
beforeEach(() => {
dns.request = (reqOpts: {}, callback: Function) => {
callback(null, apiResponse);
};
dns.zone = () => {
return zone;
};
});
it('should create zones from the response', done => {
dns.zone = (zoneName: string) => {
assert.strictEqual(zoneName, zone.name);
setImmediate(done);
return zone;
};
dns.getZones({}, assert.ifError);
});
it('should set a nextQuery if necessary', done => {
const apiResponseWithNextPageToken = Object.assign({}, apiResponse, {
nextPageToken: 'next-page-token',
});
const query = {a: 'b', c: 'd'};
const originalQuery = Object.assign({}, query);
dns.request = (reqOpts: {}, callback: Function) => {
callback(null, apiResponseWithNextPageToken);
};
dns.getZones(query, (err: Error, zones: Zone[], nextQuery: {}) => {
assert.ifError(err);
// Check the original query wasn't modified.
assert.deepStrictEqual(query, originalQuery);
assert.deepStrictEqual(
nextQuery,
Object.assign({}, query, {
pageToken: apiResponseWithNextPageToken.nextPageToken,
})
);
done();
});
});
it('should execute callback with zones and API response', done => {
dns.getZones(
{},
(
err: Error,
zones: Zone[],
nextQuery: {},
apiResponse_: Response
) => {
assert.ifError(err);
assert.strictEqual(zones[0], zone);
assert.strictEqual(nextQuery, null);
assert.strictEqual(apiResponse_, apiResponse);
done();
}
);
});
it('should assign metadata to zones', done => {
dns.getZones({}, (err: Error, zones: Zone[]) => {
assert.ifError(err);
assert.strictEqual(zones[0].metadata, zone);
done();
});
});
});
});
describe('zone', () => {
it('should throw if a name is not provided', () => {
assert.throws(() => {
dns.zone();
}, /A zone name is required/);
});
it('should return a Zone', () => {
const newZoneName = 'new-zone-name';
const newZone = dns.zone(newZoneName);
assert(newZone instanceof FakeZone);
assert.strictEqual(newZone.calledWith_[0], dns);
assert.strictEqual(newZone.calledWith_[1], newZoneName);
});
});
}); | the_stack |
import { expect, test } from 'vitest'
import { transformWithEsbuild } from '../../plugins/esbuild'
import { traverseHtml } from '../../plugins/html'
import { ssrTransform } from '../ssrTransform'
test('default import', async () => {
expect(
(
await ssrTransform(
`import foo from 'vue';console.log(foo.bar)`,
null,
null
)
).code
).toMatchInlineSnapshot(`
"const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\");
console.log(__vite_ssr_import_0__.default.bar)"
`)
})
test('named import', async () => {
expect(
(
await ssrTransform(
`import { ref } from 'vue';function foo() { return ref(0) }`,
null,
null
)
).code
).toMatchInlineSnapshot(`
"const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\");
function foo() { return __vite_ssr_import_0__.ref(0) }"
`)
})
test('namespace import', async () => {
expect(
(
await ssrTransform(
`import * as vue from 'vue';function foo() { return vue.ref(0) }`,
null,
null
)
).code
).toMatchInlineSnapshot(`
"const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\");
function foo() { return __vite_ssr_import_0__.ref(0) }"
`)
})
test('export function declaration', async () => {
expect((await ssrTransform(`export function foo() {}`, null, null)).code)
.toMatchInlineSnapshot(`
"function foo() {}
Object.defineProperty(__vite_ssr_exports__, \\"foo\\", { enumerable: true, configurable: true, get(){ return foo }});"
`)
})
test('export class declaration', async () => {
expect((await ssrTransform(`export class foo {}`, null, null)).code)
.toMatchInlineSnapshot(`
"class foo {}
Object.defineProperty(__vite_ssr_exports__, \\"foo\\", { enumerable: true, configurable: true, get(){ return foo }});"
`)
})
test('export var declaration', async () => {
expect((await ssrTransform(`export const a = 1, b = 2`, null, null)).code)
.toMatchInlineSnapshot(`
"const a = 1, b = 2
Object.defineProperty(__vite_ssr_exports__, \\"a\\", { enumerable: true, configurable: true, get(){ return a }});
Object.defineProperty(__vite_ssr_exports__, \\"b\\", { enumerable: true, configurable: true, get(){ return b }});"
`)
})
test('export named', async () => {
expect(
(await ssrTransform(`const a = 1, b = 2; export { a, b as c }`, null, null))
.code
).toMatchInlineSnapshot(`
"const a = 1, b = 2;
Object.defineProperty(__vite_ssr_exports__, \\"a\\", { enumerable: true, configurable: true, get(){ return a }});
Object.defineProperty(__vite_ssr_exports__, \\"c\\", { enumerable: true, configurable: true, get(){ return b }});"
`)
})
test('export named from', async () => {
expect(
(await ssrTransform(`export { ref, computed as c } from 'vue'`, null, null))
.code
).toMatchInlineSnapshot(`
"const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\");
Object.defineProperty(__vite_ssr_exports__, \\"ref\\", { enumerable: true, configurable: true, get(){ return __vite_ssr_import_0__.ref }});
Object.defineProperty(__vite_ssr_exports__, \\"c\\", { enumerable: true, configurable: true, get(){ return __vite_ssr_import_0__.computed }});"
`)
})
test('named exports of imported binding', async () => {
expect(
(
await ssrTransform(
`import {createApp} from 'vue';export {createApp}`,
null,
null
)
).code
).toMatchInlineSnapshot(`
"const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\");
Object.defineProperty(__vite_ssr_exports__, \\"createApp\\", { enumerable: true, configurable: true, get(){ return __vite_ssr_import_0__.createApp }});"
`)
})
test('export * from', async () => {
expect(
(
await ssrTransform(
`export * from 'vue'\n` + `export * from 'react'`,
null,
null
)
).code
).toMatchInlineSnapshot(`
"const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\");
__vite_ssr_exportAll__(__vite_ssr_import_0__);
const __vite_ssr_import_1__ = await __vite_ssr_import__(\\"react\\");
__vite_ssr_exportAll__(__vite_ssr_import_1__);"
`)
})
test('export * as from', async () => {
expect((await ssrTransform(`export * as foo from 'vue'`, null, null)).code)
.toMatchInlineSnapshot(`
"const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\");
Object.defineProperty(__vite_ssr_exports__, \\"foo\\", { enumerable: true, configurable: true, get(){ return __vite_ssr_import_0__ }});"
`)
})
test('export default', async () => {
expect(
(await ssrTransform(`export default {}`, null, null)).code
).toMatchInlineSnapshot(`"__vite_ssr_exports__.default = {}"`)
})
test('import.meta', async () => {
expect(
(await ssrTransform(`console.log(import.meta.url)`, null, null)).code
).toMatchInlineSnapshot(`"console.log(__vite_ssr_import_meta__.url)"`)
})
test('dynamic import', async () => {
const result = await ssrTransform(
`export const i = () => import('./foo')`,
null,
null
)
expect(result.code).toMatchInlineSnapshot(`
"const i = () => __vite_ssr_dynamic_import__('./foo')
Object.defineProperty(__vite_ssr_exports__, \\"i\\", { enumerable: true, configurable: true, get(){ return i }});"
`)
expect(result.deps).toEqual([])
expect(result.dynamicDeps).toEqual(['./foo'])
})
test('do not rewrite method definition', async () => {
const result = await ssrTransform(
`import { fn } from 'vue';class A { fn() { fn() } }`,
null,
null
)
expect(result.code).toMatchInlineSnapshot(`
"const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\");
class A { fn() { __vite_ssr_import_0__.fn() } }"
`)
expect(result.deps).toEqual(['vue'])
})
test('do not rewrite when variable is in scope', async () => {
const result = await ssrTransform(
`import { fn } from 'vue';function A(){ const fn = () => {}; return { fn }; }`,
null,
null
)
expect(result.code).toMatchInlineSnapshot(`
"const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\");
function A(){ const fn = () => {}; return { fn }; }"
`)
expect(result.deps).toEqual(['vue'])
})
// #5472
test('do not rewrite when variable is in scope with object destructuring', async () => {
const result = await ssrTransform(
`import { fn } from 'vue';function A(){ let {fn, test} = {fn: 'foo', test: 'bar'}; return { fn }; }`,
null,
null
)
expect(result.code).toMatchInlineSnapshot(`
"const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\");
function A(){ let {fn, test} = {fn: 'foo', test: 'bar'}; return { fn }; }"
`)
expect(result.deps).toEqual(['vue'])
})
// #5472
test('do not rewrite when variable is in scope with array destructuring', async () => {
const result = await ssrTransform(
`import { fn } from 'vue';function A(){ let [fn, test] = ['foo', 'bar']; return { fn }; }`,
null,
null
)
expect(result.code).toMatchInlineSnapshot(`
"const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\");
function A(){ let [fn, test] = ['foo', 'bar']; return { fn }; }"
`)
expect(result.deps).toEqual(['vue'])
})
// #5727
test('rewrite variable in string interpolation in function nested arguments', async () => {
const result = await ssrTransform(
`import { fn } from 'vue';function A({foo = \`test\${fn}\`} = {}){ return {}; }`,
null,
null
)
expect(result.code).toMatchInlineSnapshot(`
"const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\");
function A({foo = \`test\${__vite_ssr_import_0__.fn}\`} = {}){ return {}; }"
`)
expect(result.deps).toEqual(['vue'])
})
// #6520
test('rewrite variables in default value of destructuring params', async () => {
const result = await ssrTransform(
`import { fn } from 'vue';function A({foo = fn}){ return {}; }`,
null,
null
)
expect(result.code).toMatchInlineSnapshot(`
"const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\");
function A({foo = __vite_ssr_import_0__.fn}){ return {}; }"
`)
expect(result.deps).toEqual(['vue'])
})
test('do not rewrite when function declaration is in scope', async () => {
const result = await ssrTransform(
`import { fn } from 'vue';function A(){ function fn() {}; return { fn }; }`,
null,
null
)
expect(result.code).toMatchInlineSnapshot(`
"const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\");
function A(){ function fn() {}; return { fn }; }"
`)
expect(result.deps).toEqual(['vue'])
})
test('do not rewrite catch clause', async () => {
const result = await ssrTransform(
`import {error} from './dependency';try {} catch(error) {}`,
null,
null
)
expect(result.code).toMatchInlineSnapshot(`
"const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"./dependency\\");
try {} catch(error) {}"
`)
expect(result.deps).toEqual(['./dependency'])
})
// #2221
test('should declare variable for imported super class', async () => {
expect(
(
await ssrTransform(
`import { Foo } from './dependency';` + `class A extends Foo {}`,
null,
null
)
).code
).toMatchInlineSnapshot(`
"const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"./dependency\\");
const Foo = __vite_ssr_import_0__.Foo;
class A extends Foo {}"
`)
// exported classes: should prepend the declaration at root level, before the
// first class that uses the binding
expect(
(
await ssrTransform(
`import { Foo } from './dependency';` +
`export default class A extends Foo {}\n` +
`export class B extends Foo {}`,
null,
null
)
).code
).toMatchInlineSnapshot(`
"const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"./dependency\\");
const Foo = __vite_ssr_import_0__.Foo;
class A extends Foo {}
class B extends Foo {}
Object.defineProperty(__vite_ssr_exports__, \\"B\\", { enumerable: true, configurable: true, get(){ return B }});
Object.defineProperty(__vite_ssr_exports__, \\"default\\", { enumerable: true, value: A });"
`)
})
// #4049
test('should handle default export variants', async () => {
// default anonymous functions
expect(
(await ssrTransform(`export default function() {}\n`, null, null)).code
).toMatchInlineSnapshot(`
"__vite_ssr_exports__.default = function() {}
"
`)
// default anonymous class
expect((await ssrTransform(`export default class {}\n`, null, null)).code)
.toMatchInlineSnapshot(`
"__vite_ssr_exports__.default = class {}
"
`)
// default named functions
expect(
(
await ssrTransform(
`export default function foo() {}\n` +
`foo.prototype = Object.prototype;`,
null,
null
)
).code
).toMatchInlineSnapshot(`
"function foo() {}
foo.prototype = Object.prototype;
Object.defineProperty(__vite_ssr_exports__, \\"default\\", { enumerable: true, value: foo });"
`)
// default named classes
expect(
(
await ssrTransform(
`export default class A {}\n` + `export class B extends A {}`,
null,
null
)
).code
).toMatchInlineSnapshot(`
"class A {}
class B extends A {}
Object.defineProperty(__vite_ssr_exports__, \\"B\\", { enumerable: true, configurable: true, get(){ return B }});
Object.defineProperty(__vite_ssr_exports__, \\"default\\", { enumerable: true, value: A });"
`)
})
test('sourcemap source', async () => {
expect(
(await ssrTransform(`export const a = 1`, null, 'input.js')).map.sources
).toStrictEqual(['input.js'])
})
test('overwrite bindings', async () => {
expect(
(
await ssrTransform(
`import { inject } from 'vue';` +
`const a = { inject }\n` +
`const b = { test: inject }\n` +
`function c() { const { test: inject } = { test: true }; console.log(inject) }\n` +
`const d = inject\n` +
`function f() { console.log(inject) }\n` +
`function e() { const { inject } = { inject: true } }\n` +
`function g() { const f = () => { const inject = true }; console.log(inject) }\n`,
null,
null
)
).code
).toMatchInlineSnapshot(`
"const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\");
const a = { inject: __vite_ssr_import_0__.inject }
const b = { test: __vite_ssr_import_0__.inject }
function c() { const { test: inject } = { test: true }; console.log(inject) }
const d = __vite_ssr_import_0__.inject
function f() { console.log(__vite_ssr_import_0__.inject) }
function e() { const { inject } = { inject: true } }
function g() { const f = () => { const inject = true }; console.log(__vite_ssr_import_0__.inject) }
"
`)
})
test('Empty array pattern', async () => {
expect(
(await ssrTransform(`const [, LHS, RHS] = inMatch;`, null, null)).code
).toMatchInlineSnapshot(`"const [, LHS, RHS] = inMatch;"`)
})
test('function argument destructure', async () => {
expect(
(
await ssrTransform(
`
import { foo, bar } from 'foo'
const a = ({ _ = foo() }) => {}
function b({ _ = bar() }) {}
function c({ _ = bar() + foo() }) {}
`,
null,
null
)
).code
).toMatchInlineSnapshot(`
"
const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"foo\\");
const a = ({ _ = __vite_ssr_import_0__.foo() }) => {}
function b({ _ = __vite_ssr_import_0__.bar() }) {}
function c({ _ = __vite_ssr_import_0__.bar() + __vite_ssr_import_0__.foo() }) {}
"
`)
})
test('object destructure alias', async () => {
expect(
(
await ssrTransform(
`
import { n } from 'foo'
const a = () => {
const { type: n = 'bar' } = {}
console.log(n)
}
`,
null,
null
)
).code
).toMatchInlineSnapshot(`
"
const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"foo\\");
const a = () => {
const { type: n = 'bar' } = {}
console.log(n)
}
"
`)
})
test('nested object destructure alias', async () => {
expect(
(
await ssrTransform(
`
import { remove, add, get, set, rest, objRest } from 'vue'
function a() {
const {
o: { remove },
a: { b: { c: [ add ] }},
d: [{ get }, set, ...rest],
...objRest
} = foo
remove()
add()
get()
set()
rest()
objRest()
}
remove()
add()
get()
set()
rest()
objRest()
`,
null,
null
)
).code
).toMatchInlineSnapshot(`
"
const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\");
function a() {
const {
o: { remove },
a: { b: { c: [ add ] }},
d: [{ get }, set, ...rest],
...objRest
} = foo
remove()
add()
get()
set()
rest()
objRest()
}
__vite_ssr_import_0__.remove()
__vite_ssr_import_0__.add()
__vite_ssr_import_0__.get()
__vite_ssr_import_0__.set()
__vite_ssr_import_0__.rest()
__vite_ssr_import_0__.objRest()
"
`)
})
test('class props', async () => {
expect(
(
await ssrTransform(
`
import { remove, add } from 'vue'
class A {
remove = 1
add = null
}
`,
null,
null
)
).code
).toMatchInlineSnapshot(`
"
const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\");
const add = __vite_ssr_import_0__.add;
const remove = __vite_ssr_import_0__.remove;
class A {
remove = 1
add = null
}
"
`)
})
test('class methods', async () => {
expect(
(
await ssrTransform(
`
import foo from 'foo'
const bar = 'bar'
class A {
foo() {}
[foo]() {}
[bar]() {}
#foo() {}
bar(foo) {}
}
`,
null,
null
)
).code
).toMatchInlineSnapshot(`
"
const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"foo\\");
const bar = 'bar'
class A {
foo() {}
[__vite_ssr_import_0__.default]() {}
[bar]() {}
#foo() {}
bar(foo) {}
}
"
`)
})
test('declare scope', async () => {
expect(
(
await ssrTransform(
`
import { aaa, bbb, ccc, ddd } from 'vue'
function foobar() {
ddd()
const aaa = () => {
bbb(ccc)
ddd()
}
const bbb = () => {
console.log('hi')
}
const ccc = 1
function ddd() {}
aaa()
bbb()
ccc()
}
aaa()
bbb()
`,
null,
null
)
).code
).toMatchInlineSnapshot(`
"
const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"vue\\");
function foobar() {
ddd()
const aaa = () => {
bbb(ccc)
ddd()
}
const bbb = () => {
console.log('hi')
}
const ccc = 1
function ddd() {}
aaa()
bbb()
ccc()
}
__vite_ssr_import_0__.aaa()
__vite_ssr_import_0__.bbb()
"
`)
})
test('jsx', async () => {
const code = `
import React from 'react'
import { Foo, Slot } from 'foo'
function Bar({ Slot = <Foo /> }) {
return (
<>
<Slot />
</>
)
}
`
const id = '/foo.jsx'
const result = await transformWithEsbuild(code, id)
expect((await ssrTransform(result.code, null, '/foo.jsx')).code)
.toMatchInlineSnapshot(`
"const __vite_ssr_import_0__ = await __vite_ssr_import__(\\"react\\");
const __vite_ssr_import_1__ = await __vite_ssr_import__(\\"foo\\");
function Bar({ Slot: Slot2 = /* @__PURE__ */ __vite_ssr_import_0__.default.createElement(__vite_ssr_import_1__.Foo, null) }) {
return /* @__PURE__ */ __vite_ssr_import_0__.default.createElement(__vite_ssr_import_0__.default.Fragment, null, /* @__PURE__ */ __vite_ssr_import_0__.default.createElement(Slot2, null));
}
"
`)
})
test('continuous exports', async () => {
expect(
(
await ssrTransform(
`
export function fn1() {
}export function fn2() {
}
`,
null,
null
)
).code
).toMatchInlineSnapshot(`
"
function fn1() {
}
Object.defineProperty(__vite_ssr_exports__, \\"fn1\\", { enumerable: true, configurable: true, get(){ return fn1 }});function fn2() {
}
Object.defineProperty(__vite_ssr_exports__, \\"fn2\\", { enumerable: true, configurable: true, get(){ return fn2 }});
"
`)
})
// https://github.com/vitest-dev/vitest/issues/1141
test('export default expression', async () => {
// esbuild transform result of following TS code
// export default <MyFn> function getRandom() {
// return Math.random()
// }
const code = `
export default (function getRandom() {
return Math.random();
});
`.trim()
expect((await ssrTransform(code, null, null)).code).toMatchInlineSnapshot(`
"__vite_ssr_exports__.default = (function getRandom() {
return Math.random();
});"
`)
expect(
(await ssrTransform(`export default (class A {});`, null, null)).code
).toMatchInlineSnapshot(`"__vite_ssr_exports__.default = (class A {});"`)
})
// #8002
test('with hashbang', async () => {
expect(
(
await ssrTransform(
`#!/usr/bin/env node
console.log("it can parse the hashbang")`,
null,
null
)
).code
).toMatchInlineSnapshot(`
"#!/usr/bin/env node
console.log(\\"it can parse the hashbang\\")"
`)
}) | the_stack |
import {
Fragment,
ReactNode,
forwardRef,
useState,
HTMLAttributes,
useMemo,
useContext,
} from 'react';
import { Editor, Transforms } from 'slate';
import { applyRefs } from 'apply-ref';
import { jsx, useTheme } from '@keystone-ui/core';
import { useControlledPopover } from '@keystone-ui/popover';
import { Tooltip } from '@keystone-ui/tooltip';
import { BoldIcon } from '@keystone-ui/icons/icons/BoldIcon';
import { ItalicIcon } from '@keystone-ui/icons/icons/ItalicIcon';
import { PlusIcon } from '@keystone-ui/icons/icons/PlusIcon';
import { ChevronDownIcon } from '@keystone-ui/icons/icons/ChevronDownIcon';
import { Maximize2Icon } from '@keystone-ui/icons/icons/Maximize2Icon';
import { Minimize2Icon } from '@keystone-ui/icons/icons/Minimize2Icon';
import { MoreHorizontalIcon } from '@keystone-ui/icons/icons/MoreHorizontalIcon';
import { DocumentFeatures } from '../views';
import {
InlineDialog,
KeyboardInTooltip,
ToolbarButton,
ToolbarGroup,
ToolbarSeparator,
} from './primitives';
import { linkButton } from './link';
import { BlockComponentsButtons, ComponentBlockContext } from './component-blocks';
import { clearFormatting, Mark, modifierKeyText } from './utils';
import { LayoutsButton } from './layouts';
import { ListButton } from './lists';
import { blockquoteButton } from './blockquote';
import { DocumentFieldRelationshipsContext, RelationshipButton } from './relationship';
import { codeButton } from './code-block';
import { TextAlignMenu } from './alignment';
import { dividerButton } from './divider';
import { useToolbarState } from './toolbar-state';
export function Toolbar({
documentFeatures,
viewState,
}: {
documentFeatures: DocumentFeatures;
viewState?: { expanded: boolean; toggle: () => void };
}) {
const relationship = useContext(DocumentFieldRelationshipsContext);
const blockComponent = useContext(ComponentBlockContext);
const hasBlockItems = Object.entries(relationship).length || Object.keys(blockComponent).length;
return (
<ToolbarContainer>
{!!documentFeatures.formatting.headingLevels.length && (
<Fragment>
<HeadingMenu headingLevels={documentFeatures.formatting.headingLevels} />
<ToolbarSeparator />
</Fragment>
)}
{Object.values(documentFeatures.formatting.inlineMarks).some(x => x) && (
<Fragment>
<InlineMarks marks={documentFeatures.formatting.inlineMarks} />
<ToolbarSeparator />
</Fragment>
)}
{(documentFeatures.formatting.alignment.center ||
documentFeatures.formatting.alignment.end) && (
<TextAlignMenu alignment={documentFeatures.formatting.alignment} />
)}
{documentFeatures.formatting.listTypes.unordered && (
<Tooltip
content={
<Fragment>
Bullet List <KeyboardInTooltip>- </KeyboardInTooltip>
</Fragment>
}
weight="subtle"
>
{attrs => (
<ListButton type="unordered-list" {...attrs}>
<BulletListIcon />
</ListButton>
)}
</Tooltip>
)}
{documentFeatures.formatting.listTypes.ordered && (
<Tooltip
content={
<Fragment>
Numbered List <KeyboardInTooltip>1. </KeyboardInTooltip>
</Fragment>
}
weight="subtle"
>
{attrs => (
<ListButton type="ordered-list" {...attrs}>
<NumberedListIcon />
</ListButton>
)}
</Tooltip>
)}
{(documentFeatures.formatting.alignment.center ||
documentFeatures.formatting.alignment.end ||
documentFeatures.formatting.listTypes.unordered ||
documentFeatures.formatting.listTypes.ordered) && <ToolbarSeparator />}
{documentFeatures.dividers && dividerButton}
{documentFeatures.links && linkButton}
{documentFeatures.formatting.blockTypes.blockquote && blockquoteButton}
{!!documentFeatures.layouts.length && <LayoutsButton layouts={documentFeatures.layouts} />}
{documentFeatures.formatting.blockTypes.code && codeButton}
{!!hasBlockItems && <InsertBlockMenu />}
<ToolbarSeparator />
{useMemo(() => {
const ExpandIcon = viewState?.expanded ? Minimize2Icon : Maximize2Icon;
return (
viewState && (
<Tooltip content={viewState.expanded ? 'Collapse' : 'Expand'} weight="subtle">
{attrs => (
<ToolbarButton
onMouseDown={event => {
event.preventDefault();
viewState.toggle();
}}
{...attrs}
>
<ExpandIcon size="small" />
</ToolbarButton>
)}
</Tooltip>
)
);
}, [viewState])}
</ToolbarContainer>
);
}
/* UI Components */
const MarkButton = forwardRef<any, { children: ReactNode; type: Mark }>(function MarkButton(
props,
ref
) {
const {
editor,
marks: {
[props.type]: { isDisabled, isSelected },
},
} = useToolbarState();
return useMemo(() => {
const { type, ...restProps } = props;
return (
<ToolbarButton
ref={ref}
isDisabled={isDisabled}
isSelected={isSelected}
onMouseDown={event => {
event.preventDefault();
if (isSelected) {
Editor.removeMark(editor, props.type);
} else {
Editor.addMark(editor, props.type, true);
}
}}
{...restProps}
/>
);
}, [editor, isDisabled, isSelected, props, ref]);
});
const ToolbarContainer = ({ children }: { children: ReactNode }) => {
const { colors, spacing } = useTheme();
return (
<div
css={{
backgroundColor: colors.background,
boxShadow: `0 1px ${colors.border}, 0 -1px ${colors.border}`,
paddingBottom: spacing.small,
paddingTop: spacing.small,
position: 'sticky',
top: 0,
zIndex: 2,
}}
>
<ToolbarGroup>{children}</ToolbarGroup>
</div>
);
};
const downIcon = <ChevronDownIcon size="small" />;
function HeadingButton({
trigger,
onToggleShowMenu,
showMenu,
}: {
trigger: ReturnType<typeof useControlledPopover>['trigger'];
showMenu: boolean;
onToggleShowMenu: () => void;
}) {
const { textStyles } = useToolbarState();
let buttonLabel =
textStyles.selected === 'normal' ? 'Normal text' : 'Heading ' + textStyles.selected;
const isDisabled = textStyles.allowedHeadingLevels.length === 0;
return useMemo(
() => (
<ToolbarButton
ref={trigger.ref}
isPressed={showMenu}
isDisabled={isDisabled}
onMouseDown={event => {
event.preventDefault();
onToggleShowMenu();
}}
style={{ textAlign: 'left', width: 116 }}
{...trigger.props}
>
<span css={{ flex: 1 }}>{buttonLabel}</span>
{downIcon}
</ToolbarButton>
),
[buttonLabel, trigger, showMenu, onToggleShowMenu, isDisabled]
);
}
const HeadingMenu = ({
headingLevels,
}: {
headingLevels: DocumentFeatures['formatting']['headingLevels'];
}) => {
const [showMenu, setShowMenu] = useState(false);
const { dialog, trigger } = useControlledPopover(
{
isOpen: showMenu,
onClose: () => setShowMenu(false),
},
{
placement: 'bottom-start',
modifiers: [
{
name: 'offset',
options: {
offset: [0, 8],
},
},
],
}
);
return (
<div
css={{
display: 'inline-block',
position: 'relative',
}}
>
<HeadingButton
showMenu={showMenu}
trigger={trigger}
onToggleShowMenu={() => {
setShowMenu(x => !x);
}}
/>
{showMenu ? (
<InlineDialog ref={dialog.ref} {...dialog.props}>
<HeadingDialog
headingLevels={headingLevels}
onCloseMenu={() => {
setShowMenu(false);
}}
/>
</InlineDialog>
) : null}
</div>
);
};
function HeadingDialog({
headingLevels,
onCloseMenu,
}: {
headingLevels: DocumentFeatures['formatting']['headingLevels'];
onCloseMenu: () => void;
}) {
const { editor, textStyles } = useToolbarState();
return (
<ToolbarGroup direction="column">
{headingLevels.map(hNum => {
let Tag = `h${hNum}` as const;
const isSelected = textStyles.selected === hNum;
return (
<ToolbarButton
key={hNum}
isSelected={isSelected}
onMouseDown={event => {
event.preventDefault();
if (isSelected) {
Transforms.unwrapNodes(editor, { match: n => n.type === 'heading' });
} else {
Transforms.setNodes(
editor,
{ type: 'heading', level: hNum },
{ match: node => node.type === 'paragraph' || node.type === 'heading' }
);
}
onCloseMenu();
}}
>
<Tag>Heading {hNum}</Tag>
</ToolbarButton>
);
})}
</ToolbarGroup>
);
}
function InsertBlockMenu() {
const [showMenu, setShowMenu] = useState(false);
const { dialog, trigger } = useControlledPopover(
{
isOpen: showMenu,
onClose: () => setShowMenu(false),
},
{
placement: 'bottom-start',
modifiers: [
{
name: 'offset',
options: {
offset: [0, 8],
},
},
],
}
);
return (
<div
css={{
display: 'inline-block',
position: 'relative',
}}
>
<Tooltip
content={
<Fragment>
Insert <KeyboardInTooltip>/</KeyboardInTooltip>
</Fragment>
}
weight="subtle"
>
{({ ref, ...attrs }) => (
<ToolbarButton
ref={applyRefs(ref, trigger.ref)}
isPressed={showMenu}
onMouseDown={event => {
event.preventDefault();
setShowMenu(v => !v);
}}
{...trigger.props}
{...attrs}
>
<PlusIcon size="small" style={{ strokeWidth: 3 }} />
<ChevronDownIcon size="small" />
</ToolbarButton>
)}
</Tooltip>
{showMenu ? (
<InlineDialog ref={dialog.ref} {...dialog.props}>
<ToolbarGroup direction="column">
<RelationshipButton onClose={() => setShowMenu(false)} />
<BlockComponentsButtons onClose={() => setShowMenu(false)} />
</ToolbarGroup>
</InlineDialog>
) : null}
</div>
);
}
function InlineMarks({ marks }: { marks: DocumentFeatures['formatting']['inlineMarks'] }) {
const [showMenu, setShowMenu] = useState(false);
const { dialog, trigger } = useControlledPopover(
{
isOpen: showMenu,
onClose: () => setShowMenu(false),
},
{
placement: 'bottom-start',
modifiers: [
{
name: 'offset',
options: {
offset: [0, 8],
},
},
],
}
);
return (
<Fragment>
{marks.bold && (
<Tooltip
content={
<Fragment>
Bold
<KeyboardInTooltip>{modifierKeyText}B</KeyboardInTooltip>
</Fragment>
}
weight="subtle"
>
{attrs => (
<MarkButton type="bold" {...attrs}>
<BoldIcon size="small" style={{ strokeWidth: 3 }} />
</MarkButton>
)}
</Tooltip>
)}
{marks.italic && (
<Tooltip
content={
<Fragment>
Italic
<KeyboardInTooltip>{modifierKeyText}I</KeyboardInTooltip>
</Fragment>
}
weight="subtle"
>
{attrs => (
<MarkButton type="italic" {...attrs}>
<ItalicIcon size="small" />
</MarkButton>
)}
</Tooltip>
)}
<Tooltip content="More formatting" weight="subtle">
{attrs => (
<MoreFormattingButton
isOpen={showMenu}
onToggle={() => {
setShowMenu(v => !v);
}}
trigger={trigger}
attrs={attrs}
/>
)}
</Tooltip>
{showMenu && (
<MoreFormattingDialog
onCloseMenu={() => {
setShowMenu(false);
}}
dialog={dialog}
marks={marks}
/>
)}
</Fragment>
);
}
function MoreFormattingDialog({
dialog,
marks,
onCloseMenu,
}: {
dialog: ReturnType<typeof useControlledPopover>['dialog'];
marks: DocumentFeatures['formatting']['inlineMarks'];
onCloseMenu: () => void;
}) {
// not doing optimisations in here because this will only render when it's open
// which will be rare and you won't be typing while it's open
const {
editor,
clearFormatting: { isDisabled },
} = useToolbarState();
return (
<InlineDialog
onMouseDown={event => {
if ((event.target as any).nodeName === 'BUTTON') {
onCloseMenu();
}
}}
ref={dialog.ref}
{...dialog.props}
>
<ToolbarGroup direction="column">
{marks.underline && (
<MarkButton type="underline">
<ContentInButtonWithShortcut content="Underline" shortcut={`${modifierKeyText}U`} />
</MarkButton>
)}
{marks.strikethrough && <MarkButton type="strikethrough">Strikethrough</MarkButton>}
{marks.code && <MarkButton type="code">Code</MarkButton>}
{marks.keyboard && <MarkButton type="keyboard">Keyboard</MarkButton>}
{marks.subscript && <MarkButton type="subscript">Subscript</MarkButton>}
{marks.superscript && <MarkButton type="superscript">Superscript</MarkButton>}
<ToolbarButton
isDisabled={isDisabled}
onMouseDown={event => {
event.preventDefault();
clearFormatting(editor);
}}
>
<ContentInButtonWithShortcut
content="Clear Formatting"
shortcut={`${modifierKeyText}\\`}
/>
</ToolbarButton>
</ToolbarGroup>
</InlineDialog>
);
}
function ContentInButtonWithShortcut({ content, shortcut }: { content: string; shortcut: string }) {
const theme = useTheme();
return (
<span
css={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
width: '100%',
}}
>
<span>{content}</span>
<kbd
css={{
fontFamily: 'inherit',
marginLeft: theme.spacing.small,
padding: theme.spacing.xxsmall,
paddingLeft: theme.spacing.xsmall,
paddingRight: theme.spacing.xsmall,
backgroundColor: theme.palette.neutral400,
borderRadius: theme.radii.xsmall,
color: theme.colors.foregroundDim,
whiteSpace: 'pre',
}}
>
{shortcut}
</kbd>
</span>
);
}
function MoreFormattingButton({
onToggle,
isOpen,
trigger,
attrs,
}: {
onToggle: () => void;
isOpen: boolean;
trigger: ReturnType<typeof useControlledPopover>['trigger'];
attrs: { ref: any };
}) {
const { marks } = useToolbarState();
const isActive =
marks.strikethrough.isSelected ||
marks.underline.isSelected ||
marks.code.isSelected ||
marks.keyboard.isSelected ||
marks.subscript.isSelected ||
marks.superscript.isSelected;
return useMemo(
() => (
<ToolbarButton
isPressed={isOpen}
isSelected={isActive}
onMouseDown={event => {
event.preventDefault();
onToggle();
}}
{...trigger.props}
{...attrs}
ref={applyRefs(attrs.ref, trigger.ref)}
>
<MoreHorizontalIcon size="small" />
</ToolbarButton>
),
[isActive, onToggle, isOpen, trigger, attrs]
);
}
// Custom (non-feather) Icons
// ------------------------------
export const IconBase = (props: HTMLAttributes<HTMLOrSVGElement>) => (
<svg
aria-hidden="true"
fill="currentColor"
focusable="false"
height="16"
role="presentation"
viewBox="0 0 16 16"
width="16"
{...props}
/>
);
const BulletListIcon = () => (
<IconBase>
<path d="M2 4a1 1 0 100-2 1 1 0 000 2zm3.75-1.5a.75.75 0 000 1.5h8.5a.75.75 0 000-1.5h-8.5zm0 5a.75.75 0 000 1.5h8.5a.75.75 0 000-1.5h-8.5zm0 5a.75.75 0 000 1.5h8.5a.75.75 0 000-1.5h-8.5zM3 8a1 1 0 11-2 0 1 1 0 012 0zm-1 6a1 1 0 100-2 1 1 0 000 2z" />
</IconBase>
);
const NumberedListIcon = () => (
<IconBase>
<path d="M2.003 2.5a.5.5 0 00-.723-.447l-1.003.5a.5.5 0 00.446.895l.28-.14V6H.5a.5.5 0 000 1h2.006a.5.5 0 100-1h-.503V2.5zM5 3.25a.75.75 0 01.75-.75h8.5a.75.75 0 010 1.5h-8.5A.75.75 0 015 3.25zm0 5a.75.75 0 01.75-.75h8.5a.75.75 0 010 1.5h-8.5A.75.75 0 015 8.25zm0 5a.75.75 0 01.75-.75h8.5a.75.75 0 010 1.5h-8.5a.75.75 0 01-.75-.75zM.924 10.32l.003-.004a.851.851 0 01.144-.153A.66.66 0 011.5 10c.195 0 .306.068.374.146a.57.57 0 01.128.376c0 .453-.269.682-.8 1.078l-.035.025C.692 11.98 0 12.495 0 13.5a.5.5 0 00.5.5h2.003a.5.5 0 000-1H1.146c.132-.197.351-.372.654-.597l.047-.035c.47-.35 1.156-.858 1.156-1.845 0-.365-.118-.744-.377-1.038-.268-.303-.658-.484-1.126-.484-.48 0-.84.202-1.068.392a1.858 1.858 0 00-.348.384l-.007.011-.002.004-.001.002-.001.001a.5.5 0 00.851.525zM.5 10.055l-.427-.26.427.26z" />
</IconBase>
); | the_stack |
import ReactReconciler from "react-reconciler";
import Reconciler, { OpaqueHandle } from "react-reconciler";
import { Action } from "./interfaces";
import { SearchOptions } from "./components";
type Type = any;
type Props = JSX.ComponentProps & {
[key: string]: any;
};
type Container = any;
type Instance = any;
type TextInstance = any;
type HydratableInstance = any;
type PublicInstance = any;
type HostContext = any;
type UpdatePayload = any;
type ChildSet = any;
type TimeoutHandle = any;
type NoTimeout = any;
/** A function to help debug errors */
const debug = (...args: any[]) => {
// console.log(args);
};
/** Reconciler config */
class HostConfig
implements
ReactReconciler.HostConfig<
Type,
Props,
Container,
Instance,
TextInstance,
HydratableInstance,
PublicInstance,
HostContext,
UpdatePayload,
ChildSet,
TimeoutHandle,
NoTimeout
> {
getPublicInstance(_instance: Instance | TextInstance) {
// throw new Error("Method not implemented.");
}
getRootHostContext(_rootContainerInstance: Container): HostContext {
return { type: "root" };
}
getChildHostContext(
_parentHostContext: HostContext,
type: Type,
_rootContainerInstance: Container
): HostContext {
return { type };
}
prepareForCommit(_containerInfo: Container): void {
return;
}
resetAfterCommit(_containerInfo: Container): void {
return;
}
createInstance(
type: Type,
props: Props,
rootContainerInstance: Container,
_hostContext: HostContext,
_internalInstanceHandle: OpaqueHandle
): Instance {
if (props.toSlackElement) {
return props.toSlackElement(
props,
(e) => {
const [nodes, promises, onSearchOptions] = reconcile(
e,
rootContainerInstance.action,
rootContainerInstance.getOnSearchOptions
);
if (
nodes &&
rootContainerInstance.action &&
nodes.action_id === rootContainerInstance.action.value &&
rootContainerInstance.getOnSearchOptions &&
onSearchOptions
) {
rootContainerInstance.onSearchOptions = onSearchOptions;
}
return [nodes, promises];
},
rootContainerInstance.promises
);
}
throw Error("Unknown Component type " + JSON.stringify({ props, type }));
}
appendInitialChild(
parentInstance: Instance,
child: Instance | TextInstance
): void {
debug("appendInitialChild");
if (Array.isArray(parentInstance.blocks)) {
parentInstance.blocks.push(child);
return;
}
if (parentInstance.type === "overflow") {
parentInstance.options.push(child);
return;
}
if (
parentInstance.type === "static_select" ||
parentInstance.type === "multi_static_select"
) {
if (child.isOptionGroup) {
if (!Array.isArray(parentInstance.option_groups)) {
parentInstance.option_groups = [];
}
parentInstance.option_groups.push(child);
return;
}
if (!Array.isArray(parentInstance.options)) {
parentInstance.options = [];
}
parentInstance.options.push({ ...child, url: undefined });
return;
}
if (
parentInstance.type === "checkboxes" ||
parentInstance.type === "radio_buttons" ||
parentInstance.isOptionGroup
) {
parentInstance.options.push({ ...child, url: undefined });
return;
}
if (parentInstance.type === "input") {
parentInstance.element = child;
return;
}
if (parentInstance.type === "actions") {
parentInstance.elements.push(child);
return;
}
if (parentInstance.type === "context") {
parentInstance.elements.push(child);
return;
}
if (parentInstance.isConfirm || parentInstance.isOption) {
parentInstance.text = child;
if (parentInstance.text.type === "text") {
parentInstance.text.type = "plain_text";
}
return;
}
if (parentInstance.type === "button") {
parentInstance.text.text += child.text;
return;
}
if (parentInstance.type === "section") {
if (!parentInstance.fields) {
parentInstance.fields = [];
}
parentInstance.fields.push(child);
return;
}
if (
parentInstance.type === "mrkdwn" ||
parentInstance.type === "plain_text"
) {
parentInstance.text += child.text;
return;
}
if (parentInstance.type === child.type) {
parentInstance.text += child.text;
return;
}
throw new Error(
"appendInitialChild::" + JSON.stringify({ parentInstance, child })
);
}
finalizeInitialChildren(
_parentInstance: Instance,
_type: Type,
props: Props,
rootContainerInstance: Container,
_hostContext: HostContext
): boolean {
if (rootContainerInstance.action?.type === "onload" && props.onLoad) {
rootContainerInstance.promises.push(
props.onLoad(rootContainerInstance.action.event)
);
return true;
}
if (rootContainerInstance.action?.type === "onupdate" && props.onUpdate) {
rootContainerInstance.promises.push(
props.onUpdate(rootContainerInstance.action.event)
);
return true;
}
if (rootContainerInstance.action?.type === "onsubmit" && props.onSubmit) {
rootContainerInstance.promises.push(
props.onSubmit(rootContainerInstance.action.event)
);
return true;
}
if (rootContainerInstance.action?.type === "oncancel" && props.onCancel) {
rootContainerInstance.promises.push(
props.onCancel(rootContainerInstance.action.event)
);
return true;
}
if (
rootContainerInstance.action &&
props.action === rootContainerInstance.action.value
) {
if (rootContainerInstance.getOnSearchOptions && props.onSearchOptions) {
rootContainerInstance.onSearchOptions = props.onSearchOptions;
return true;
}
if (props.onClick) {
rootContainerInstance.promises.push(
props.onClick(rootContainerInstance.action.event)
);
}
if (props.onSubmit) {
rootContainerInstance.promises.push(
props.onSubmit(rootContainerInstance.action.event)
);
}
if (props.onSelect) {
rootContainerInstance.promises.push(
props.onSelect(rootContainerInstance.action.event)
);
}
return true;
}
return false;
}
prepareUpdate(
_instance: Instance,
_type: Type,
_oldProps: Props,
_newProps: Props,
_rootContainerInstance: Container,
_hostContext: HostContext
) {
debug("prepareUpdate");
return true;
}
shouldSetTextContent(_type: Type, _props: Props): boolean {
return false;
}
shouldDeprioritizeSubtree(_type: Type, _props: Props): boolean {
return false;
}
createTextInstance(
text: string,
_rootContainerInstance: Container,
_hostContext: HostContext,
_internalInstanceHandle: OpaqueHandle
) {
debug("createTextInstance");
return {
type: "text",
text,
};
}
scheduleDeferredCallback(
_callback: () => any,
_options?: {
/** How long the timeout is */
timeout: number;
}
): any {}
cancelDeferredCallback(callbackID: any): void {}
setTimeout(
_handler: (...args: any[]) => void,
_timeout: number
): TimeoutHandle | NoTimeout {}
clearTimeout(handle: TimeoutHandle | NoTimeout): void {}
noTimeout: NoTimeout;
now(): number {
return Date.now();
}
isPrimaryRenderer: boolean;
supportsMutation: boolean = true;
supportsPersistence: boolean = false;
supportsHydration: boolean = true;
appendChildToContainer(
container: Container,
child: Instance | TextInstance
): void {
if (container.isRoot) {
container.node = child;
return;
}
debug("appendChildToContainer");
throw new Error("container is not an array");
}
appendChild(
_parentInstance: Instance,
_child: Instance | TextInstance
): void {
debug("appendChild");
}
commitTextUpdate(
textInstance: TextInstance,
_oldText: string,
newText: string
): void {
debug("commitTextUpdate");
textInstance.text = newText;
}
commitMount?(
_instance: Instance,
_type: Type,
_newProps: Props,
_internalInstanceHandle: Reconciler.Fiber
): void {
debug("commitMount");
}
replaceContainerChildren?(container: Container, newChildren: ChildSet): void {
debug("replaceContainerChildren", { container, newChildren });
}
resetTextContent(_instance: Instance) {
debug("resetTextContent");
}
commitUpdate?(
_instance: Instance,
_updatePayload: UpdatePayload,
_type: Type,
_oldProps: Props,
_newProps: Props,
_internalInstanceHandle: OpaqueHandle
): void {}
insertBefore?(
parentInstance: Instance,
child: Instance | TextInstance,
beforeChild: Instance | TextInstance
): void {
debug("insertBefore", { parentInstance, child, beforeChild });
}
insertInContainerBefore?(
container: Container,
child: Instance | TextInstance,
beforeChild: Instance | TextInstance
): void {
debug("insertInContainerBefore", { container, child, beforeChild });
}
removeChild?(parentInstance: Instance, child: Instance | TextInstance): void {
debug("removeChild", parentInstance, child);
}
removeChildFromContainer?(
container: Container,
child: Instance | TextInstance
): void {
debug("removeChildFromContainer", {
container,
child,
});
}
}
/** Reconcile the reaction components */
function reconcile(
element:
| React.FunctionComponentElement<any>
| React.ComponentElement<any, any>,
action?: Action,
getOnSearchOptions?: boolean
): [any, Promise<any>[], SearchOptions] {
const reconcilerInstance = Reconciler(new HostConfig());
const root: any = {
isRoot: true,
action,
promises: new Array<Promise<any>>(),
getOnSearchOptions,
};
const container = reconcilerInstance.createContainer(root, false, false);
reconcilerInstance.updateContainer(element, container, null, null);
return [root.node, root.promises, root.onSearchOptions];
}
/** Render the reaction components */
export async function render(
element:
| React.FunctionComponentElement<any>
| React.ComponentElement<any, any>,
action?: Action
) {
const [blocks, promises] = reconcile(element, action);
await Promise.all(promises);
return blocks;
}
/** Search filter options */
export async function getOnSearchOptions(
element:
| React.FunctionComponentElement<any>
| React.ComponentElement<any, any>,
action: Action
) {
const [_, promises, onSearchOptions] = reconcile(element, action, true);
await Promise.all(promises);
return onSearchOptions;
} | the_stack |
import { mean, cross, histogram, quantile } from 'd3-array';
import { scaleLinear } from 'd3-scale';
import { confidenceInterval } from './confidence-interval';
import { toNearestHundreth } from './utils';
export interface Bucket {
min: number;
max: number;
count: {
control: number;
experiment: number;
};
}
export type ISevenFigureSummary = {
[key in string | number]: number;
} & {
min: number;
max: number;
10: number;
25: number;
50: number;
75: number;
90: number;
};
export interface IOutliers {
IQR: number;
outliers: number[];
lowerOutlier: number;
upperOutlier: number;
}
export interface IStatsOptions {
control: number[];
experiment: number[];
name: string;
confidenceLevel?: 0.8 | 0.85 | 0.9 | 0.95 | 0.99 | 0.995 | 0.999;
}
export type IAsPercentage = {
percentMin: number;
percentMedian: number;
percentMax: number;
};
export type IConfidenceInterval = {
min: number;
median: number;
max: number;
zScore: number;
isSig: boolean;
pValue: number;
U: number;
asPercent: IAsPercentage;
};
/**
* Statistics class which powers the TracerBench statistical reporter
*
*
* @param options - IStatsOptions
* @param unitConverterFn - Optional unit converter function which takes a number and returns a number
*/
export class Stats {
public readonly name: string;
public estimator: number;
public readonly sparkLine: { control: string; experiment: string };
public confidenceIntervals: { [key: number]: IConfidenceInterval };
public confidenceInterval: IConfidenceInterval;
public sevenFigureSummary: {
control: ISevenFigureSummary;
experiment: ISevenFigureSummary;
};
public outliers: {
control: IOutliers;
experiment: IOutliers;
};
public readonly sampleCount: { control: number; experiment: number };
public experimentSorted: number[];
public controlSorted: number[];
public buckets: Bucket[];
public range: { min: number; max: number };
public populationVariance: { control: number; experiment: number };
public control: number[];
public experiment: number[];
constructor(options: IStatsOptions, unitConverterFn?: (n: number) => number) {
const { name, control, experiment, confidenceLevel } = options;
this.control = control;
this.experiment = experiment;
const controlSorted = control;
const experimentSorted = experiment;
this.controlSorted = controlSorted.sort((a, b) => a - b);
this.experimentSorted = experimentSorted.sort((a, b) => a - b);
this.name = name;
this.sampleCount = {
control: this.controlSorted.length,
experiment: this.experimentSorted.length
};
this.range = this.getRange(this.controlSorted, this.experimentSorted);
this.sparkLine = {
control: this.getSparkline(
this.getHistogram(this.range, this.controlSorted)
),
experiment: this.getSparkline(
this.getHistogram(this.range, this.experimentSorted)
)
};
this.confidenceIntervals = {
80: this.getConfidenceInterval(
this.controlSorted,
this.experimentSorted,
0.8
),
85: this.getConfidenceInterval(
this.controlSorted,
this.experimentSorted,
0.85
),
90: this.getConfidenceInterval(
this.controlSorted,
this.experimentSorted,
0.9
),
95: this.getConfidenceInterval(
this.controlSorted,
this.experimentSorted,
0.95
),
99: this.getConfidenceInterval(
this.controlSorted,
this.experimentSorted,
0.99
),
995: this.getConfidenceInterval(
this.controlSorted,
this.experimentSorted,
0.995
),
999: this.getConfidenceInterval(
this.controlSorted,
this.experimentSorted,
0.999
)
};
this.confidenceInterval = this.getConfidenceInterval(
this.controlSorted,
this.experimentSorted,
confidenceLevel
);
this.estimator = toNearestHundreth(
this.getHodgesLehmann(this.controlSorted, this.experimentSorted) as number
);
this.sevenFigureSummary = {
control: this.getSevenFigureSummary(this.controlSorted),
experiment: this.getSevenFigureSummary(this.experimentSorted)
};
this.outliers = {
control: this.getOutliers(
this.controlSorted,
this.sevenFigureSummary.control
),
experiment: this.getOutliers(
this.experimentSorted,
this.sevenFigureSummary.experiment
)
};
this.buckets = this.getBuckets(this.controlSorted, this.experimentSorted);
this.populationVariance = {
control: this.getPopulationVariance(this.controlSorted),
experiment: this.getPopulationVariance(this.experimentSorted)
};
// when passed will convert all units **after** statistical computation
// its critical this happens after computation since we need to correctly handle ties
if (unitConverterFn) {
this.convertAllUnits(unitConverterFn);
}
}
private convertAllUnits(unitConverterFn: (n: number) => number): void {
this.estimator = unitConverterFn(this.estimator);
this.experiment = this.experiment.map((n) => {
return unitConverterFn(n);
});
this.experimentSorted = this.experimentSorted.map((n) => {
return unitConverterFn(n);
});
this.control = this.control.map((n) => {
return unitConverterFn(n);
});
this.controlSorted = this.controlSorted.map((n) => {
return unitConverterFn(n);
});
this.range.min = unitConverterFn(this.range.min);
this.range.max = unitConverterFn(this.range.max);
this.populationVariance.control = unitConverterFn(
this.populationVariance.control
);
this.populationVariance.experiment = unitConverterFn(
this.populationVariance.experiment
);
this.outliers.control.IQR = unitConverterFn(this.outliers.control.IQR);
this.outliers.control.lowerOutlier = unitConverterFn(
this.outliers.control.lowerOutlier
);
this.outliers.control.upperOutlier = unitConverterFn(
this.outliers.control.upperOutlier
);
this.outliers.control.outliers = this.outliers.control.outliers.map((n) => {
return unitConverterFn(n);
});
this.outliers.experiment.IQR = unitConverterFn(
this.outliers.experiment.IQR
);
this.outliers.experiment.lowerOutlier = unitConverterFn(
this.outliers.experiment.lowerOutlier
);
this.outliers.experiment.upperOutlier = unitConverterFn(
this.outliers.experiment.upperOutlier
);
this.outliers.experiment.outliers = this.outliers.experiment.outliers.map(
(n) => {
return unitConverterFn(n);
}
);
for (const k in this.confidenceInterval) {
if (k === 'min' || k === 'max' || k === 'median') {
this.confidenceInterval[k] = unitConverterFn(
this.confidenceInterval[k]
);
}
}
for (const k in this.sevenFigureSummary.control) {
this.sevenFigureSummary.control[k] = unitConverterFn(
this.sevenFigureSummary.control[k]
);
}
for (const k in this.sevenFigureSummary.experiment) {
this.sevenFigureSummary.experiment[k] = unitConverterFn(
this.sevenFigureSummary.experiment[k]
);
}
for (const k in this.confidenceIntervals) {
for (const kk in this.confidenceIntervals[k]) {
if (kk === 'min' || kk === 'max' || kk === 'median') {
this.confidenceIntervals[k][kk] = unitConverterFn(
this.confidenceIntervals[k][kk]
);
}
}
}
this.buckets = this.buckets.map((o) => {
o.min = unitConverterFn(o.min);
o.max = unitConverterFn(o.max);
return o;
});
}
private getOutliers(
a: number[],
sevenFigSum: ISevenFigureSummary
): IOutliers {
const IQR = sevenFigSum[75] - sevenFigSum[25];
const obj: IOutliers = {
IQR,
lowerOutlier: Math.floor(sevenFigSum[25] - 1.5 * IQR),
upperOutlier: Math.round(sevenFigSum[75] + 1.5 * IQR),
outliers: []
};
a.forEach((n) => {
const roundedN: number = Math.round(n);
if (roundedN < obj.lowerOutlier || roundedN > obj.upperOutlier) {
obj.outliers.push(roundedN);
}
});
return obj;
}
private getSevenFigureSummary(a: number[]): ISevenFigureSummary {
return {
min: Math.round(Math.min.apply(null, a)),
max: Math.round(Math.max.apply(null, a)),
10: Math.round(quantile(a, 0.1) as number),
25: Math.round(quantile(a, 0.25) as number),
50: Math.round(quantile(a, 0.5) as number),
75: Math.round(quantile(a, 0.75) as number),
90: Math.round(quantile(a, 0.9) as number)
};
}
private getConfidenceInterval(
control: number[],
experiment: number[],
confidenceLevel: IStatsOptions['confidenceLevel'] = 0.95
): IConfidenceInterval {
const ci = confidenceInterval(control, experiment, confidenceLevel);
const isCISig =
(ci.min < 0 && 0 < ci.max) ||
(ci.min > 0 && 0 > ci.max) ||
(ci.min === 0 && ci.max === 0)
? false
: true;
const sigLevel: number = 1 - confidenceLevel;
// ci sign must match on lower and upper bounds and pValue < 5%
const isSig = isCISig && ci.pValue < sigLevel;
return {
min: Math.round(Math.ceil(ci.min * 100) / 100),
max: Math.round(Math.ceil(ci.max * 100) / 100),
isSig,
median: ci.median,
zScore: ci.zScore,
pValue: ci.pValue,
U: ci.U,
asPercent: ci.asPercent
};
}
private getHodgesLehmann(
control: number[],
experiment: number[]
): number | undefined {
const crossProduct = cross(control, experiment, (a, b) => a - b).sort(
(a, b) => a - b
);
return quantile(crossProduct, 0.5);
}
private getRange(
control: number[],
experiment: number[]
): { min: number; max: number } {
const a = control.concat(experiment);
return { min: Math.min(...a), max: Math.max(...a) };
}
private getHistogram(
range: { min: number; max: number },
a: number[]
): number[] {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const x: any = scaleLinear()
.domain([range.min, range.max])
.range([range.min, range.max]);
const h = histogram()
.value((d) => {
return d;
})
.domain(x.domain())
.thresholds(x.ticks());
return h(a).map((i) => {
return i.length;
});
}
private getSparkline(
numbers: number[],
min: number = Math.min.apply(null, numbers),
max: number = Math.max.apply(null, numbers)
): string {
function lshift(n: number, bits: number): number {
return Math.floor(n) * Math.pow(2, bits);
}
const ticks: string[] = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
const results: string[] = [];
let f: number = Math.floor(lshift(max - min, 8) / (ticks.length - 1));
if (f < 1) {
f = 1;
}
numbers.forEach((n: number) => {
const value: string = ticks[Math.floor(lshift(n - min, 8) / f)];
results.push(value);
});
return `${results.join('')}`;
}
private getBuckets(
controlSorted: number[],
experimentSorted: number[],
bucketCount = 12
): Bucket[] {
const { min, max } = this.range;
const buffer = 1;
const minBuffer = min - buffer;
const maxBuffer = max + buffer;
const bucketIncrementor = (maxBuffer - minBuffer) / bucketCount;
const buckets = [];
let count = minBuffer;
while (count < maxBuffer) {
buckets.push({
min: Math.floor(count),
max: Math.floor(count + bucketIncrementor),
count: {
control: 0,
experiment: 0
}
});
count += bucketIncrementor;
}
// since we use a buffer all samples will be caught
// within each bucket regardless of comparator
// and without overlap
buckets.map((bucket) => {
controlSorted.map((sample) => {
if (sample >= bucket.min && sample < bucket.max) {
bucket.count.control++;
}
});
experimentSorted.map((sample) => {
if (sample >= bucket.min && sample < bucket.max) {
bucket.count.experiment++;
}
});
});
return buckets;
}
private getPopulationVariance(a: number[]): number {
const _mean = mean(a);
let sum = 0;
if (_mean) {
a.map((n) => {
sum = sum + Math.pow(n - _mean, 2);
});
}
return toNearestHundreth(sum / a.length);
}
} | the_stack |
import '../../plugins/gr-endpoint-decorator/gr-endpoint-decorator';
import '../../plugins/gr-endpoint-param/gr-endpoint-param';
import '../../shared/gr-button/gr-button';
import '../../shared/gr-editable-label/gr-editable-label';
import '../gr-default-editor/gr-default-editor';
import '../../../styles/shared-styles';
import {PolymerElement} from '@polymer/polymer/polymer-element';
import {htmlTemplate} from './gr-editor-view_html';
import {
GerritNav,
GenerateUrlEditViewParameters,
} from '../../core/gr-navigation/gr-navigation';
import {computeTruncatedPath} from '../../../utils/path-list-util';
import {customElement, observe, property} from '@polymer/decorators';
import {
PatchSetNum,
EditPreferencesInfo,
Base64FileContent,
NumericChangeId,
EditPatchSetNum,
} from '../../../types/common';
import {ParsedChangeInfo} from '../../../types/types';
import {HttpMethod, NotifyType} from '../../../constants/constants';
import {fireAlert, fireTitleChange} from '../../../utils/event-util';
import {getAppContext} from '../../../services/app-context';
import {ErrorCallback} from '../../../api/rest';
import {assertIsDefined} from '../../../utils/common-util';
import {debounce, DelayedTask} from '../../../utils/async-util';
import {changeIsMerged, changeIsAbandoned} from '../../../utils/change-util';
import {GrButton} from '../../shared/gr-button/gr-button';
import {GrDefaultEditor} from '../gr-default-editor/gr-default-editor';
import {GrEndpointDecorator} from '../../plugins/gr-endpoint-decorator/gr-endpoint-decorator';
import {addShortcut, Modifier} from '../../../utils/dom-util';
const RESTORED_MESSAGE = 'Content restored from a previous edit.';
const SAVING_MESSAGE = 'Saving changes...';
const SAVED_MESSAGE = 'All changes saved';
const SAVE_FAILED_MSG = 'Failed to save changes';
const PUBLISHING_EDIT_MSG = 'Publishing edit...';
const PUBLISH_FAILED_MSG = 'Failed to publish edit';
const STORAGE_DEBOUNCE_INTERVAL_MS = 100;
// Used within the tests
export interface GrEditorView {
$: {
close: GrButton;
editorEndpoint: GrEndpointDecorator;
file: GrDefaultEditor;
publish: GrButton;
save: GrButton;
};
}
@customElement('gr-editor-view')
export class GrEditorView extends PolymerElement {
static get template() {
return htmlTemplate;
}
/**
* Fired when the title of the page should change.
*
* @event title-change
*/
/**
* Fired to notify the user of
*
* @event show-alert
*/
@property({type: Object, observer: '_paramsChanged'})
params?: GenerateUrlEditViewParameters;
@property({type: Object, observer: '_editChange'})
_change?: ParsedChangeInfo;
@property({type: Number})
_changeNum?: NumericChangeId;
@property({type: String})
_patchNum?: PatchSetNum;
@property({type: String})
_path?: string;
@property({type: String})
_type?: string;
@property({type: String})
_content?: string;
@property({type: String})
_newContent = '';
@property({type: Boolean})
_saving = false;
@property({type: Boolean})
_successfulSave = false;
@property({
type: Boolean,
computed: '_computeSaveDisabled(_content, _newContent, _saving)',
})
_saveDisabled = true;
@property({type: Object})
_prefs?: EditPreferencesInfo;
@property({type: Number})
_lineNum?: number;
private readonly restApiService = getAppContext().restApiService;
private readonly storage = getAppContext().storageService;
private readonly reporting = getAppContext().reportingService;
// Tests use this so needs to be non private
storeTask?: DelayedTask;
/** Called in disconnectedCallback. */
private cleanups: (() => void)[] = [];
constructor() {
super();
this.addEventListener('content-change', e => {
this._handleContentChange(e as CustomEvent<{value: string}>);
});
}
override connectedCallback() {
super.connectedCallback();
this._getEditPrefs().then(prefs => {
this._prefs = prefs;
});
this.cleanups.push(
addShortcut(this, {key: 's', modifiers: [Modifier.CTRL_KEY]}, () =>
this._handleSaveShortcut()
)
);
this.cleanups.push(
addShortcut(this, {key: 's', modifiers: [Modifier.META_KEY]}, () =>
this._handleSaveShortcut()
)
);
}
override disconnectedCallback() {
this.storeTask?.cancel();
for (const cleanup of this.cleanups) cleanup();
this.cleanups = [];
super.disconnectedCallback();
}
get storageKey() {
return `c${this._changeNum}_ps${this._patchNum}_${this._path}`;
}
_getLoggedIn() {
return this.restApiService.getLoggedIn();
}
_getEditPrefs() {
return this.restApiService.getEditPreferences();
}
_paramsChanged(value: GenerateUrlEditViewParameters) {
if (value.view !== GerritNav.View.EDIT) {
return;
}
this._changeNum = value.changeNum;
this._path = value.path;
this._patchNum = value.patchNum || (EditPatchSetNum as PatchSetNum);
this._lineNum =
typeof value.lineNum === 'string' ? Number(value.lineNum) : value.lineNum;
// NOTE: This may be called before attachment (e.g. while parentElement is
// null). Fire title-change in an async so that, if attachment to the DOM
// has been queued, the event can bubble up to the handler in gr-app.
setTimeout(() => {
const title = `Editing ${computeTruncatedPath(value.path)}`;
fireTitleChange(this, title);
});
const promises = [];
promises.push(this._getChangeDetail(this._changeNum));
promises.push(
this._getFileData(this._changeNum, this._path, this._patchNum)
);
return Promise.all(promises);
}
async _getChangeDetail(changeNum: NumericChangeId) {
this._change = await this.restApiService.getChangeDetail(changeNum);
}
_editChange(value?: ParsedChangeInfo | null) {
if (!value) return;
if (!changeIsMerged(value) && !changeIsAbandoned(value)) return;
fireAlert(
this,
'Change edits cannot be created if change is merged or abandoned. Redirected to non edit mode.'
);
GerritNav.navigateToChange(value);
}
@observe('_change', '_type')
_editType(change?: ParsedChangeInfo | null, type?: string) {
if (!change || !type || !type.startsWith('image/')) return;
// Prevent editing binary files
fireAlert(this, 'You cannot edit binary files within the inline editor.');
GerritNav.navigateToChange(change);
}
_handlePathChanged(e: CustomEvent<string>) {
// TODO(TS) could be cleaned up, it was added for type requirements
if (this._changeNum === undefined || !this._path) {
return Promise.reject(new Error('changeNum or path undefined'));
}
const path = e.detail;
if (path === this._path) {
return Promise.resolve();
}
return this.restApiService
.renameFileInChangeEdit(this._changeNum, this._path, path)
.then(res => {
if (!res || !res.ok) {
return;
}
this._successfulSave = true;
this._viewEditInChangeView();
});
}
_viewEditInChangeView() {
if (this._change)
GerritNav.navigateToChange(this._change, {
isEdit: true,
forceReload: true,
});
}
_getFileData(
changeNum: NumericChangeId,
path: string,
patchNum?: PatchSetNum
) {
if (patchNum === undefined) {
return Promise.reject(new Error('patchNum undefined'));
}
const storedContent = this.storage.getEditableContentItem(this.storageKey);
return this.restApiService
.getFileContent(changeNum, path, patchNum)
.then(res => {
const content = (res && (res as Base64FileContent).content) || '';
if (
storedContent &&
storedContent.message &&
storedContent.message !== content
) {
fireAlert(this, RESTORED_MESSAGE);
this._newContent = storedContent.message;
} else {
this._newContent = content;
}
this._content = content;
// A non-ok response may result if the file does not yet exist.
// The `type` field of the response is only valid when the file
// already exists.
if (res && res.ok && res.type) {
this._type = res.type;
} else {
this._type = '';
}
});
}
_saveEdit() {
if (this._changeNum === undefined || !this._path) {
return Promise.reject(new Error('changeNum or path undefined'));
}
this._saving = true;
this._showAlert(SAVING_MESSAGE);
this.storage.eraseEditableContentItem(this.storageKey);
if (!this._newContent)
return Promise.reject(new Error('new content undefined'));
return this.restApiService
.saveChangeEdit(this._changeNum, this._path, this._newContent)
.then(res => {
this._saving = false;
this._showAlert(res.ok ? SAVED_MESSAGE : SAVE_FAILED_MSG);
if (!res.ok) {
return res;
}
this._content = this._newContent;
this._successfulSave = true;
return res;
});
}
_showAlert(message: string) {
fireAlert(this, message);
}
_computeSaveDisabled(
content?: string,
newContent?: string,
saving?: boolean
) {
// Polymer 2: check for undefined
if ([content, newContent, saving].includes(undefined)) {
return true;
}
if (saving) {
return true;
}
return content === newContent;
}
_handleCloseTap() {
// TODO(kaspern): Add a confirm dialog if there are unsaved changes.
this._viewEditInChangeView();
}
_handleSaveTap() {
this._saveEdit().then(res => {
if (res.ok) this._viewEditInChangeView();
});
}
_handlePublishTap() {
assertIsDefined(this._changeNum, '_changeNum');
const changeNum = this._changeNum;
this._saveEdit().then(() => {
const handleError: ErrorCallback = response => {
this._showAlert(PUBLISH_FAILED_MSG);
this.reporting.error(new Error(response?.statusText));
};
this._showAlert(PUBLISHING_EDIT_MSG);
this.restApiService
.executeChangeAction(
changeNum,
HttpMethod.POST,
'/edit:publish',
undefined,
{notify: NotifyType.NONE},
handleError
)
.then(() => {
assertIsDefined(this._change, '_change');
GerritNav.navigateToChange(this._change, {forceReload: true});
});
});
}
_handleContentChange(e: CustomEvent<{value: string}>) {
this.storeTask = debounce(
this.storeTask,
() => {
const content = e.detail.value;
if (content) {
this.set('_newContent', e.detail.value);
this.storage.setEditableContentItem(this.storageKey, content);
} else {
this.storage.eraseEditableContentItem(this.storageKey);
}
},
STORAGE_DEBOUNCE_INTERVAL_MS
);
}
_handleSaveShortcut() {
if (!this._saveDisabled) {
this._saveEdit();
}
}
}
declare global {
interface HTMLElementTagNameMap {
'gr-editor-view': GrEditorView;
}
} | the_stack |
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js';
import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js';
import 'chrome://resources/cr_elements/cr_icons_css.m.js';
import 'chrome://resources/cr_elements/cr_link_row/cr_link_row.js';
import 'chrome://resources/cr_elements/cr_toggle/cr_toggle.m.js';
import 'chrome://resources/cr_elements/icons.m.js';
import 'chrome://resources/cr_elements/policy/cr_tooltip_icon.m.js';
import 'chrome://resources/cr_elements/shared_style_css.m.js';
import 'chrome://resources/cr_elements/shared_vars_css.m.js';
import 'chrome://resources/js/action_link.js';
import 'chrome://resources/cr_elements/action_link_css.m.js';
import 'chrome://resources/polymer/v3_0/iron-flex-layout/iron-flex-layout-classes.js';
import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js';
import 'chrome://resources/polymer/v3_0/paper-spinner/paper-spinner-lite.js';
import 'chrome://resources/polymer/v3_0/paper-styles/color.js';
import './host_permissions_toggle_list.js';
import './runtime_host_permissions.js';
import './shared_style.js';
import './shared_vars.js';
import './strings.m.js';
import './toggle_row.js';
import {CrContainerShadowMixin} from 'chrome://resources/cr_elements/cr_container_shadow_mixin.js';
import {CrToggleElement} from 'chrome://resources/cr_elements/cr_toggle/cr_toggle.m.js';
import {focusWithoutInk} from 'chrome://resources/js/cr/ui/focus_without_ink.m.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {afterNextRender, html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {ItemDelegate} from './item.js';
import {ItemMixin} from './item_mixin.js';
import {computeInspectableViewLabel, EnableControl, getEnableControl, getItemSource, getItemSourceString, isEnabled, userCanChangeEnablement} from './item_util.js';
import {navigation, Page} from './navigation_helper.js';
import {ExtensionsToggleRowElement} from './toggle_row.js';
export interface ExtensionsDetailViewElement {
$: {
closeButton: HTMLElement,
enableToggle: CrToggleElement,
extensionsActivityLogLink: HTMLElement,
};
}
/** Event interface for dom-repeat. */
interface RepeaterEvent extends CustomEvent {
model: {
item: chrome.developerPrivate.ExtensionView,
};
}
const ExtensionsDetailViewElementBase =
CrContainerShadowMixin(ItemMixin(PolymerElement));
export class ExtensionsDetailViewElement extends
ExtensionsDetailViewElementBase {
static get is() {
return 'extensions-detail-view';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
/**
* The underlying ExtensionInfo for the details being displayed.
*/
data: Object,
size_: String,
delegate: Object,
/** Whether the user has enabled the UI's developer mode. */
inDevMode: Boolean,
/** Whether "allow in incognito" option should be shown. */
incognitoAvailable: Boolean,
/** Whether "View Activity Log" link should be shown. */
showActivityLog: Boolean,
/** Whether the user navigated to this page from the activity log page. */
fromActivityLog: Boolean,
};
}
static get observers() {
return ['onItemIdChanged_(data.id, delegate)'];
}
data: chrome.developerPrivate.ExtensionInfo;
delegate: ItemDelegate;
inDevMode: boolean;
incognitoAvailable: boolean;
showActivityLog: boolean;
fromActivityLog: boolean;
private size_: string;
connectedCallback() {
super.connectedCallback();
if (document.documentElement.hasAttribute('enable-branding-update')) {
// Always show the top shadow, regardless of scroll position.
// TODO(crbug.com/1177509): Remove CrContainerShadowMixin completely and
// add a fixed shadow after feature is launched.
this.enableShadowBehavior(false);
this.showDropShadows();
}
}
ready() {
super.ready();
this.addEventListener('view-enter-start', this.onViewEnterStart_);
}
/**
* Focuses the extensions options button. This should be used after the
* dialog closes.
*/
focusOptionsButton() {
this.shadowRoot!.querySelector<HTMLElement>('#extensions-options')!.focus();
}
/**
* Focuses the back button when page is loaded.
*/
private onViewEnterStart_() {
const elementToFocus = this.fromActivityLog ?
this.$.extensionsActivityLogLink :
this.$.closeButton;
afterNextRender(this, () => focusWithoutInk(elementToFocus));
}
private onItemIdChanged_() {
// Clear the size, since this view is reused, such that no obsolete size
// is displayed.:
this.size_ = '';
this.delegate.getExtensionSize(this.data.id).then(size => {
this.size_ = size;
});
}
private onActivityLogTap_() {
navigation.navigateTo({page: Page.ACTIVITY_LOG, extensionId: this.data.id});
}
private getDescription_(description: string, fallback: string): string {
return description || fallback;
}
private onCloseButtonTap_() {
navigation.navigateTo({page: Page.LIST});
}
private isEnabled_(): boolean {
return isEnabled(this.data.state);
}
private isEnableToggleEnabled_(): boolean {
return userCanChangeEnablement(this.data);
}
private hasDependentExtensions_(): boolean {
return this.data.dependentExtensions.length > 0;
}
private hasSevereWarnings_(): boolean {
return this.data.disableReasons.corruptInstall ||
this.data.disableReasons.suspiciousInstall ||
this.data.disableReasons.updateRequired || !!this.data.blacklistText ||
this.data.runtimeWarnings.length > 0;
}
private computeEnabledStyle_(): string {
return this.isEnabled_() ? 'enabled-text' : '';
}
private computeEnabledText_(
state: chrome.developerPrivate.ExtensionState, onText: string,
offText: string): string {
// TODO(devlin): Get the full spectrum of these strings from bettes.
return isEnabled(state) ? onText : offText;
}
private computeInspectLabel_(view: chrome.developerPrivate.ExtensionView):
string {
return computeInspectableViewLabel(view);
}
private shouldShowOptionsLink_(): boolean {
return !!this.data.optionsPage;
}
private shouldShowOptionsSection_(): boolean {
return this.data.incognitoAccess.isEnabled ||
this.data.fileAccess.isEnabled || this.data.errorCollection.isEnabled;
}
private shouldShowIncognitoOption_(): boolean {
return this.data.incognitoAccess.isEnabled && this.incognitoAvailable;
}
private onEnableToggleChange_() {
this.delegate.setItemEnabled(this.data.id, this.$.enableToggle.checked);
this.$.enableToggle.checked = this.isEnabled_();
}
private onInspectTap_(e: RepeaterEvent) {
this.delegate.inspectItemView(this.data.id, e.model.item);
}
private onExtensionOptionsTap_() {
this.delegate.showItemOptionsPage(this.data);
}
private onReloadTap_() {
this.delegate.reloadItem(this.data.id).catch(loadError => {
this.dispatchEvent(new CustomEvent(
'load-error', {bubbles: true, composed: true, detail: loadError}));
});
}
private onRemoveTap_() {
this.delegate.deleteItem(this.data.id);
}
private onRepairTap_() {
this.delegate.repairItem(this.data.id);
}
private onLoadPathTap_() {
this.delegate.showInFolder(this.data.id);
}
private onAllowIncognitoChange_() {
this.delegate.setItemAllowedIncognito(
this.data.id,
this.shadowRoot!
.querySelector<ExtensionsToggleRowElement>(
'#allow-incognito')!.checked);
}
private onAllowOnFileUrlsChange_() {
this.delegate.setItemAllowedOnFileUrls(
this.data.id,
this.shadowRoot!
.querySelector<ExtensionsToggleRowElement>(
'#allow-on-file-urls')!.checked);
}
private onCollectErrorsChange_() {
this.delegate.setItemCollectsErrors(
this.data.id,
this.shadowRoot!
.querySelector<ExtensionsToggleRowElement>(
'#collect-errors')!.checked);
}
private onExtensionWebSiteTap_() {
this.delegate.openUrl(this.data.manifestHomePageUrl);
}
private onViewInStoreTap_() {
this.delegate.openUrl(this.data.webStoreUrl);
}
private computeDependentEntry_(
item: chrome.developerPrivate.DependentExtension): string {
return loadTimeData.getStringF('itemDependentEntry', item.name, item.id);
}
private computeSourceString_(): string {
return this.data.locationText ||
getItemSourceString(getItemSource(this.data));
}
private hasPermissions_(): boolean {
return this.data.permissions.simplePermissions.length > 0 ||
this.hasRuntimeHostPermissions_();
}
private hasRuntimeHostPermissions_(): boolean {
return !!this.data.permissions.runtimeHostPermissions;
}
private showSiteAccessContent_(): boolean {
return this.showFreeformRuntimeHostPermissions_() ||
this.showHostPermissionsToggleList_();
}
private showFreeformRuntimeHostPermissions_(): boolean {
return this.hasRuntimeHostPermissions_() &&
this.data.permissions.runtimeHostPermissions!.hasAllHosts;
}
private showHostPermissionsToggleList_(): boolean {
return this.hasRuntimeHostPermissions_() &&
!this.data.permissions.runtimeHostPermissions!.hasAllHosts;
}
private showReloadButton_(): boolean {
return getEnableControl(this.data) === EnableControl.RELOAD;
}
private showRepairButton_(): boolean {
return getEnableControl(this.data) === EnableControl.REPAIR;
}
private showEnableToggle_(): boolean {
const enableControl = getEnableControl(this.data);
// We still show the toggle even if we also show the repair button in the
// detail view, because the repair button appears just beneath it.
return enableControl === EnableControl.ENABLE_TOGGLE ||
enableControl === EnableControl.REPAIR;
}
private showAllowlistWarning_(): boolean {
// Only show the allowlist warning if there is no blocklist warning. It
// would be redundant since all blocklisted items are necessarily not
// included in the Safe Browsing allowlist.
return this.data.showSafeBrowsingAllowlistWarning &&
!this.data.blacklistText;
}
}
declare global {
interface HTMLElementTagNameMap {
'extensions-detail-view': ExtensionsDetailViewElement;
}
}
customElements.define(
ExtensionsDetailViewElement.is, ExtensionsDetailViewElement); | the_stack |
import {
Activity,
ActivityTypes,
BotFrameworkAdapter,
RecognizerResult } from 'botbuilder';
import { LuisRecognizer } from 'botbuilder-ai';
import {
DialogContext,
DialogTurnResult,
WaterfallStepContext,
WaterfallDialog,
TextPrompt,
PromptOptions,
ComponentDialog } from 'botbuilder-dialogs';
import { ICognitiveModelSet, LocaleTemplateManager } from 'bot-solutions';
import { TokenStatus } from 'botframework-connector';
import { BotServices } from '../services/botServices';
import { SampleDialog } from './sampleDialog';
import { StateProperties } from '../models';
import { SampleActionInput, SampleAction } from './sampleAction';
import { TurnContextEx } from '../extensions/turnContextEx';
/**
* Dialog providing activity routing and message/event processing.
*/
export class MainDialog extends ComponentDialog {
private stateProperties: StateProperties = new StateProperties();
// Fields
private readonly services: BotServices;
private readonly sampleDialog: SampleDialog;
private readonly sampleAction: SampleAction;
private readonly templateEngine: LocaleTemplateManager;
// Constructor
public constructor(
services: BotServices,
sampleDialog: SampleDialog,
sampleAction: SampleAction,
templateEngine: LocaleTemplateManager
) {
super(MainDialog.name);
this.services = services;
this.templateEngine = templateEngine;
const steps: ((sc: WaterfallStepContext) => Promise<DialogTurnResult>)[] = [
this.introStep.bind(this),
this.routeStep.bind(this),
this.finalStep.bind(this)
];
this.addDialog(new WaterfallDialog (MainDialog.name, steps));
this.addDialog(new TextPrompt(TextPrompt.name));
this.initialDialogId = MainDialog.name;
// Register dialogs
this.sampleDialog = sampleDialog;
this.sampleAction = sampleAction;
this.addDialog(sampleDialog);
this.addDialog(sampleAction);
}
// Runs when the dialog is started.
protected async onBeginDialog(innerDc: DialogContext, options: Object): Promise<DialogTurnResult> {
const activity: Activity = innerDc.context.activity;
if (activity.type === ActivityTypes.Message && activity.text !== undefined && activity.text.trim().length > 0) {
// Get cognitive models for the current locale.
const localizedServices: Partial<ICognitiveModelSet> = this.services.getCognitiveModels(innerDc.context.activity.locale as string);
// Run LUIS recognition on Skill model and store result in turn state.
const skillLuis: LuisRecognizer | undefined = localizedServices.luisServices ? localizedServices.luisServices.get('sampleSkill') : undefined;
if (skillLuis !== undefined) {
const skillResult: RecognizerResult = await skillLuis.recognize(innerDc.context);
innerDc.context.turnState.set(this.stateProperties.skillLuisResult, skillResult);
}
// Run LUIS recognition on General model and store result in turn state.
const generalLuis: LuisRecognizer | undefined = localizedServices.luisServices ? localizedServices.luisServices.get('general') : undefined;
if (generalLuis !== undefined) {
const generalResult: RecognizerResult = await generalLuis.recognize(innerDc.context);
innerDc.context.turnState.set(this.stateProperties.generalLuisResult, generalResult);
}
// Check for any interruptions
const interrupted: DialogTurnResult = await this.interruptDialog(innerDc);
if (Object.keys(interrupted).length > 0) {
// If dialog was interrupted, return interrupted result
return interrupted;
}
}
return await super.onBeginDialog(innerDc, options);
}
// Runs on every turn of the conversation.
protected async onContinueDialog(innerDc: DialogContext): Promise<DialogTurnResult> {
const activity: Activity = innerDc.context.activity;
if (activity.type === ActivityTypes.Message && activity.text !== undefined && activity.text.trim().length > 0) {
// Get cognitive models for the current locale.
const localizedServices: Partial<ICognitiveModelSet> = this.services.getCognitiveModels(innerDc.context.activity.locale as string);
// Run LUIS recognition on Skill model and store result in turn state.
const skillLuis: LuisRecognizer | undefined = localizedServices.luisServices ? localizedServices.luisServices.get('sampleSkill') : undefined;
if (skillLuis !== undefined) {
const skillResult: RecognizerResult = await skillLuis.recognize(innerDc.context);
innerDc.context.turnState.set(this.stateProperties.skillLuisResult, skillResult);
}
// Run LUIS recognition on General model and store result in turn state.
const generalLuis: LuisRecognizer | undefined = localizedServices.luisServices ? localizedServices.luisServices.get('general') : undefined;
if (generalLuis !== undefined) {
const generalResult: RecognizerResult = await generalLuis.recognize(innerDc.context);
innerDc.context.turnState.set(this.stateProperties.generalLuisResult, generalResult);
}
// Check for any interruptions
const interrupted: DialogTurnResult = await this.interruptDialog(innerDc);
if (Object.keys(interrupted).length > 0) {
// If dialog was interrupted, return interrupted result
return interrupted;
}
}
return await super.onContinueDialog(innerDc);
}
// Runs on every turn of the conversation to check if the conversation should be interrupted.
protected async interruptDialog(innerDc: DialogContext): Promise<DialogTurnResult> {
let interrupted: DialogTurnResult = {} as DialogTurnResult;
const activity: Activity = innerDc.context.activity;
if (activity.type === ActivityTypes.Message && activity.text !== undefined && activity.text.trim().length > 0) {
// Get connected LUIS result from turn state.
const generalResult: RecognizerResult = innerDc.context.turnState.get(this.stateProperties.generalLuisResult);
const intent: string = LuisRecognizer.topIntent(generalResult);
if (generalResult.intents[intent].score > 0.5) {
switch(intent) {
case 'Cancel': {
await innerDc.context.sendActivity(this.templateEngine.generateActivityForLocale('CancelledMessage', innerDc.context.activity.locale));
await innerDc.cancelAllDialogs();
if (TurnContextEx.isSkill(innerDc.context)) {
interrupted = await innerDc.endDialog();
}
else {
interrupted = await innerDc.beginDialog(this.initialDialogId);
}
break;
}
case 'Help': {
await innerDc.context.sendActivity(this.templateEngine.generateActivityForLocale('HelpCard', innerDc.context.activity.locale));
await innerDc.repromptDialog();
interrupted = MainDialog.EndOfTurn;
break;
}
case 'Logout': {
// Log user out of all accounts.
await this.logUserOut(innerDc);
await innerDc.context.sendActivity(this.templateEngine.generateActivityForLocale('LogoutMessage', innerDc.context.activity.locale));
await innerDc.cancelAllDialogs();
if (TurnContextEx.isSkill(innerDc.context)) {
interrupted = await innerDc.endDialog();
}
else {
interrupted = await innerDc.beginDialog(this.initialDialogId);
}
break;
}
}
}
}
return interrupted;
}
// Handles introduction/continuation prompt logic.
private async introStep(stepContext: WaterfallStepContext): Promise<DialogTurnResult> {
if (TurnContextEx.isSkill(stepContext.context)) {
// If the bot is in skill mode, skip directly to route and do not prompt
return await stepContext.next();
}
// If bot is in local mode, prompt with intro or continuation message
const promptOptions: PromptOptions = {
prompt: Object.keys(stepContext.options as Activity).length > 0 ? stepContext.options as Activity : this.templateEngine.generateActivityForLocale('FirstPromptMessage', stepContext.context.activity.locale)
};
return await stepContext.prompt(TextPrompt.name, promptOptions);
}
// Handles routing to additional dialogs logic.
protected async routeStep(stepContext: WaterfallStepContext): Promise<DialogTurnResult> {
//PENDING: This should be const activity: IMessageActivity = innerDc.context.activity.asMessageActivity()
// but it's not in botbuilder-js currently
const activity: Activity = stepContext.context.activity;
if (activity.type === ActivityTypes.Message && activity.text !== undefined && activity.text.trim().length > 0) {
// Get current cognitive models for the current locale.
const localizedServices: Partial<ICognitiveModelSet> = this.services.getCognitiveModels(stepContext.context.activity.locale as string);
// Get skill LUIS model from configuration.
const luisService: LuisRecognizer | undefined = localizedServices.luisServices? localizedServices.luisServices.get('sampleSkill') : undefined;
if (luisService !== undefined){
const result = stepContext.context.turnState.get(this.stateProperties.skillLuisResult);
const intent: string = LuisRecognizer.topIntent(result);
switch(intent) {
case 'Sample': {
return await stepContext.beginDialog(this.sampleDialog.id);
}
case 'None':
default: {
// intent was identified but not yet implemented
await stepContext.context.sendActivity(this.templateEngine.generateActivityForLocale('UnsupportedMessage', stepContext.context.activity.locale));
return await stepContext.next();
}
}
} else {
throw new Error('The specified LUIS Model could not be found in your Bot Services configuration.');
}
} else if (activity.type === ActivityTypes.Event) {
// PENDING const ev = activity.AsEventActivity();
const ev = activity;
if (ev.name !== undefined && ev.name.trim().length > 0 ) {
switch (ev.name) {
case 'SampleAction': {
let actionData: Object = {};
if (ev.value !== undefined) {
actionData = ev.value as SampleActionInput;
}
// Invoke the SampleAction dialog passing input data if available
return await stepContext.beginDialog(SampleAction.name, actionData);
}
default: {
await stepContext.context.sendActivity({
type: ActivityTypes.Trace,
text: `Unknown Event ${ ev.name ? ev.name : 'undefined' } was received but not processed.`
});
break;
}
}
} else {
await stepContext.context.sendActivity({
type: ActivityTypes.Trace,
text: 'An event with no name was received but not processed.'
});
}
}
// If activity was unhandled, flow should continue to next step
return await stepContext.next();
}
// Handles conversation cleanup.
private async finalStep(stepContext: WaterfallStepContext): Promise<DialogTurnResult> {
if (TurnContextEx.isSkill(stepContext.context)) {
const result = stepContext.result;
return await stepContext.endDialog(result);
} else {
return await stepContext.replaceDialog(this.id, this.templateEngine.generateActivityForLocale('CompletedMessage', stepContext.context.activity.locale));
}
}
private async logUserOut(dc: DialogContext): Promise<void> {
const supported: BotFrameworkAdapter = dc.context.adapter as BotFrameworkAdapter;
if (supported !== undefined){
// Sign out user
const tokens: TokenStatus[] = await supported.getTokenStatus(dc.context, dc.context.activity.from.id);
tokens.forEach(async (token: TokenStatus): Promise<void> => {
if (token.connectionName !== undefined) {
await supported.signOutUser(dc.context, token.connectionName);
}
});
// Cancel all active dialogs
await dc.cancelAllDialogs();
} else {
throw new Error('OAuthPrompt.SignOutUser(): not supported by the current adapter');
}
}
} | the_stack |
import { Vector3, Box3, Matrix3, Matrix4 } from 'three'
import { WorkerRegistry, ColormakerRegistry } from '../globals'
import { defaults } from '../utils'
import WorkerPool from '../worker/worker-pool'
import { VolumePicker } from '../utils/picker'
import {
uniformArray, serialArray,
arrayMin, arrayMax, arraySum, arrayMean, arrayRms
} from '../math/array-utils'
import MarchingCubes from './marching-cubes'
import { laplacianSmooth, computeVertexNormals } from './surface-utils'
import {
applyMatrix4toVector3array, applyMatrix3toVector3array
} from '../math/vector-utils'
import { m3new, m3makeNormal } from '../math/matrix-utils'
import Surface from './surface'
import { NumberArray } from '../types';
import { ColormakerParameters } from '../color/colormaker';
export interface VolumeSurface {
new (data: NumberArray, nx: number, ny: number, nz: number, atomindex: NumberArray): void
getSurface: (isolevel: number, smooth: boolean|number, box: number[][]|undefined, matrix: Float32Array, contour: boolean, wrap?: boolean) => {
position: Float32Array
normal: undefined|Float32Array
index: Uint32Array|Uint16Array
atomindex: Int32Array|undefined
contour: boolean
}
}
export function VolumeSurface (this: VolumeSurface,data: NumberArray, nx: number, ny: number, nz: number, atomindex: NumberArray) {
var mc = new (MarchingCubes as any)(data, nx, ny, nz, atomindex) as MarchingCubes
function getSurface (isolevel: number, smooth: boolean|number, box: number[][]|undefined, matrix: Float32Array, contour: boolean, wrap: boolean = false) {
const sd = mc.triangulate(isolevel, smooth as boolean, box, contour, wrap)
if (smooth && !contour) {
laplacianSmooth(sd.position, sd.index as any, smooth as number, true)
sd.normal = computeVertexNormals(sd.position, sd.index as any)
}
if (matrix) {
applyMatrix4toVector3array(matrix, sd.position)
if (sd.normal) {
const normalMatrix = m3new()
m3makeNormal(normalMatrix, matrix)
applyMatrix3toVector3array(normalMatrix, sd.normal)
}
}
return sd
}
this.getSurface = getSurface
}
Object.assign(VolumeSurface, {__deps: [
laplacianSmooth, computeVertexNormals, MarchingCubes,
applyMatrix4toVector3array, applyMatrix3toVector3array,
m3new, m3makeNormal
]})
WorkerRegistry.add('surf', function func (e: any, callback: (data: any, transferList: any) => void) {
const a = e.data.args
const p = e.data.params
if (a) {
/* global self */
(self as any).volsurf = new (VolumeSurface as any)(a[0], a[1], a[2], a[3], a[4]) as VolumeSurface
}
if (p) {
const sd = ((self as any).volsurf as VolumeSurface).getSurface(
p.isolevel, p.smooth, p.box, p.matrix, p.contour, p.wrap
)
const transferList = [ sd.position.buffer, sd.index.buffer ]
if (sd.normal) transferList.push(sd.normal.buffer)
if (sd.atomindex) transferList.push(sd.atomindex.buffer)
const data = {
sd: sd,
p: p
}
callback(data, transferList)
}
}, [ VolumeSurface ])
export type VolumeSize = 'value'|'abs-value'|'value-min'|'deviation'
/**
* Volume
*/
class Volume {
name: string
path: string
matrix: Matrix4
normalMatrix: Matrix3
inverseMatrix: Matrix4
center: Vector3
boundingBox: Box3
nx: number
ny: number
nz: number
data: Float32Array
worker: Worker
workerPool: WorkerPool
_position: Float32Array
_min: number|undefined
_max: number|undefined
_mean: number|undefined
_rms: number|undefined
_sum: number|undefined
__box: Box3|undefined
atomindex: Int32Array|undefined
volsurf: VolumeSurface|undefined
header: any
/**
* Make Volume instance
* @param {String} name - volume name
* @param {String} path - source path
* @param {Float32array} data - volume 3d grid
* @param {Integer} nx - x dimension of the 3d volume
* @param {Integer} ny - y dimension of the 3d volume
* @param {Integer} nz - z dimension of the 3d volume
* @param {Int32Array} atomindex - atom indices corresponding to the cells in the 3d grid
*/
constructor (name: string, path: string, data?: Float32Array, nx?: number, ny?: number, nz?: number, atomindex?: Int32Array) {
this.name = name
this.path = path
this.matrix = new Matrix4()
this.normalMatrix = new Matrix3()
this.inverseMatrix = new Matrix4()
this.center = new Vector3()
this.boundingBox = new Box3()
this.setData(data, nx, ny, nz, atomindex)
}
get type () { return 'Volume' }
/**
* set volume data
* @param {Float32array} data - volume 3d grid
* @param {Integer} nx - x dimension of the 3d volume
* @param {Integer} ny - y dimension of the 3d volume
* @param {Integer} nz - z dimension of the 3d volume
* @param {Int32Array} atomindex - atom indices corresponding to the cells in the 3d grid
* @return {undefined}
*/
setData (data?: Float32Array, nx?: number, ny?: number, nz?: number, atomindex?: Int32Array) {
this.nx = nx || 1
this.ny = ny || 1
this.nz = nz || 1
this.data = data || new Float32Array(1)
this.setAtomindex(atomindex)
this._position = new Float32Array()
delete this._min
delete this._max
delete this._mean
delete this._rms
if (this.worker) this.worker.terminate()
}
/**
* Set statistics, which can be different from the data in this volume,
* if this volume is a slice of a bigger volume
* @param {Number|undefined} min - minimum value of the whole data set
* @param {Number|undefined} max - maximum value of the whole data set
* @param {Number|undefined} mean - average value of the whole data set
* @param {Number|undefined} rms - sigma value of the whole data set
*/
setStats (min: number|undefined, max: number|undefined, mean: number|undefined, rms: number|undefined) {
this._min = min
this._max = max
this._mean = mean
this._rms = rms
}
/**
* set transformation matrix
* @param {Matrix4} matrix - 4x4 transformation matrix
* @return {undefined}
*/
setMatrix (matrix: Matrix4) {
this.matrix.copy(matrix)
const bb = this.boundingBox
const v = this.center // temporary re-purposing
const x = this.nx - 1
const y = this.ny - 1
const z = this.nz - 1
bb.makeEmpty()
bb.expandByPoint(v.set(x, y, z))
bb.expandByPoint(v.set(x, y, 0))
bb.expandByPoint(v.set(x, 0, z))
bb.expandByPoint(v.set(x, 0, 0))
bb.expandByPoint(v.set(0, y, z))
bb.expandByPoint(v.set(0, 0, z))
bb.expandByPoint(v.set(0, y, 0))
bb.expandByPoint(v.set(0, 0, 0))
bb.applyMatrix4(this.matrix)
bb.getCenter(this.center)
// make normal matrix
const me = this.matrix.elements
const r0 = new Vector3(me[0], me[1], me[2])
const r1 = new Vector3(me[4], me[5], me[6])
const r2 = new Vector3(me[8], me[9], me[10])
const cp = new Vector3()
// [ r0 ] [ r1 x r2 ]
// M3x3 = [ r1 ] N = [ r2 x r0 ]
// [ r2 ] [ r0 x r1 ]
const ne = this.normalMatrix.elements
cp.crossVectors(r1, r2)
ne[ 0 ] = cp.x
ne[ 1 ] = cp.y
ne[ 2 ] = cp.z
cp.crossVectors(r2, r0)
ne[ 3 ] = cp.x
ne[ 4 ] = cp.y
ne[ 5 ] = cp.z
cp.crossVectors(r0, r1)
ne[ 6 ] = cp.x
ne[ 7 ] = cp.y
ne[ 8 ] = cp.z
this.inverseMatrix.getInverse(this.matrix)
}
/**
* set atom indices
* @param {Int32Array} atomindex - atom indices corresponding to the cells in the 3d grid
* @return {undefined}
*/
setAtomindex (atomindex?: Int32Array) {
this.atomindex = atomindex
}
getBox (center: Vector3, size: number, target: Box3) {
if (!target) target = new Box3()
target.set(center, center)
target.expandByScalar(size)
target.applyMatrix4(this.inverseMatrix)
target.min.round()
target.max.round()
return target
}
_getBox (center: Vector3|undefined, size: number) {
if (!center || !size) return
if (!this.__box) this.__box = new Box3()
const box = this.getBox(center, size, this.__box)
return [ box.min.toArray(), box.max.toArray() ]
}
_makeSurface (sd: any, isolevel: number, smooth: number) {
const name = this.name + '@' + isolevel.toPrecision(2)
const surface = new Surface(name, '', sd)
surface.info.isolevel = isolevel
surface.info.smooth = smooth
surface.info.volume = this
return surface
}
getSurface (isolevel: number, smooth: number, center: Vector3, size: number, contour: boolean, wrap: boolean = false) {
isolevel = isNaN(isolevel) ? this.getValueForSigma(2) : isolevel
smooth = defaults(smooth, 0)
//
if (this.volsurf === undefined) {
this.volsurf = new (VolumeSurface as any)(
this.data, this.nx, this.ny, this.nz, this.atomindex
) as VolumeSurface
}
const box = this._getBox(center, size)
const sd = this.volsurf.getSurface(
isolevel, smooth, box!, this.matrix.elements as unknown as Float32Array, contour, wrap
)
return this._makeSurface(sd, isolevel, smooth)
}
getSurfaceWorker (isolevel: number, smooth: number, center: Vector3, size: number, contour: boolean, wrap: boolean, callback: (s: Surface) => void) {
isolevel = isNaN(isolevel) ? this.getValueForSigma(2) : isolevel
smooth = smooth || 0
//
if (window.hasOwnProperty('Worker')) {
if (this.workerPool === undefined) {
this.workerPool = new WorkerPool('surf', 2)
}
const msg = {}
const worker = this.workerPool.getNextWorker()
if (worker!.postCount === 0) {
Object.assign(msg, {
args: [
this.data, this.nx, this.ny, this.nz, this.atomindex
]
})
}
Object.assign(msg, {
params: {
isolevel: isolevel,
smooth: smooth,
box: this._getBox(center, size),
matrix: this.matrix.elements,
contour: contour,
wrap: wrap
}
})
worker!.post(msg, undefined,
(e: any) => {
const sd = e.data.sd
const p = e.data.p
callback(this._makeSurface(sd, p.isolevel, p.smooth))
},
(e : string) => {
console.warn(
'Volume.getSurfaceWorker error - trying without worker', e
)
const surface = this.getSurface(isolevel, smooth, center, size, contour, wrap)
callback(surface)
}
)
} else {
const surface = this.getSurface(isolevel, smooth, center, size, contour, wrap)
callback(surface)
}
}
getValueForSigma (sigma: number) {
return this.mean + defaults(sigma, 2) * this.rms
}
getSigmaForValue (value: number) {
return (defaults(value, 0) - this.mean) / this.rms
}
get position () {
if (!this._position) {
const nz = this.nz
const ny = this.ny
const nx = this.nx
const position = new Float32Array(nx * ny * nz * 3)
let p = 0
for (let z = 0; z < nz; ++z) {
for (let y = 0; y < ny; ++y) {
for (let x = 0; x < nx; ++x) {
position[ p + 0 ] = x
position[ p + 1 ] = y
position[ p + 2 ] = z
p += 3
}
}
}
applyMatrix4toVector3array(this.matrix.elements as unknown as Float32Array, position)
this._position = position
}
return this._position
}
getDataAtomindex () {
return this.atomindex
}
getDataPosition () {
return this.position
}
getDataColor (params: ColormakerParameters & {scheme: string}) {
const p = params || {}
p.volume = this
p.scale = p.scale || 'Spectral'
p.domain = p.domain || [ this.min, this.max ]
const colormaker = ColormakerRegistry.getScheme(p)
const n = this.position.length / 3
const array = new Float32Array(n * 3)
// var atoms = p.structure.atoms;
// var atomindex = this.atomindex;
for (let i = 0; i < n; ++i) {
colormaker.volumeColorToArray(i, array, i * 3)
// a = atoms[ atomindex[ i ] ];
// if( a ) colormaker.atomColorToArray( a, array, i * 3 );
}
return array
}
getDataPicking () {
const picking = serialArray(this.position.length / 3)
return new VolumePicker(picking, this)
}
getDataSize (size: VolumeSize|number, scale: number) {
const data = this.data
const n = this.position.length / 3
let array
switch (size) {
case 'value':
array = new Float32Array(data)
break
case 'abs-value':
array = new Float32Array(data)
for (let i = 0; i < n; ++i) {
array[ i ] = Math.abs(array[ i ])
}
break
case 'value-min': {
array = new Float32Array(data)
const min = this.min
for (let i = 0; i < n; ++i) {
array[ i ] -= min
}
break
}
case 'deviation':
array = new Float32Array(data)
break
default:
array = uniformArray(n, size)
break
}
if (scale !== 1.0) {
for (let i = 0; i < n; ++i) {
array[ i ] *= scale
}
}
return array
}
get min () {
if (this._min === undefined) {
this._min = arrayMin(this.data)
}
return this._min
}
get max () {
if (this._max === undefined) {
this._max = arrayMax(this.data)
}
return this._max
}
get sum () {
if (this._sum === undefined) {
this._sum = arraySum(this.data)
}
return this._sum
}
get mean () {
if (this._mean === undefined) {
this._mean = arrayMean(this.data)
}
return this._mean
}
get rms () {
if (this._rms === undefined) {
this._rms = arrayRms(this.data)
}
return this._rms
}
clone () {
const vol = new Volume(
this.name,
this.path,
this.data,
this.nx,
this.ny,
this.nz,
this.atomindex
)
vol.matrix.copy(this.matrix)
vol.header = Object.assign({}, this.header)
return vol
}
dispose () {
if (this.workerPool) this.workerPool.terminate()
}
}
export default Volume | the_stack |
import 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js';
import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js';
import 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.m.js';
import 'chrome://resources/cr_elements/shared_style_css.m.js';
import 'chrome://resources/polymer/v3_0/iron-collapse/iron-collapse.js';
import '../settings_shared_css.js';
import '../site_favicon.js';
import {CrIconButtonElement} from 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js';
import {CrLazyRenderElement} from 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.m.js';
import {assert, assertNotReached} from 'chrome://resources/js/assert.m.js';
import {FocusRowBehavior} from 'chrome://resources/js/cr/ui/focus_row_behavior.m.js';
import {EventTracker} from 'chrome://resources/js/event_tracker.m.js';
import {I18nMixin, I18nMixinInterface} from 'chrome://resources/js/i18n_mixin.js';
import {IronCollapseElement} from 'chrome://resources/polymer/v3_0/iron-collapse/iron-collapse.js';
import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {BaseMixin, BaseMixinInterface} from '../base_mixin.js';
import {loadTimeData} from '../i18n_setup.js';
import {routes} from '../route.js';
import {Router} from '../router.js';
import {AllSitesAction2, SortMethod} from './constants.js';
import {LocalDataBrowserProxy, LocalDataBrowserProxyImpl} from './local_data_browser_proxy.js';
import {SiteSettingsMixin, SiteSettingsMixinInterface} from './site_settings_mixin.js';
import {OriginInfo, SiteGroup} from './site_settings_prefs_browser_proxy.js';
interface RepeaterEvent {
model: {
index: number,
},
}
export interface SiteEntryElement {
$: {
expandIcon: CrIconButtonElement,
collapseParent: HTMLElement,
cookies: HTMLElement,
displayName: HTMLElement,
originList: CrLazyRenderElement<IronCollapseElement>,
toggleButton: HTMLElement,
};
// Declaring here because TypeScript default types seem to lack that method.
scrollIntoViewIfNeeded(): void;
}
const SiteEntryElementBase =
mixinBehaviors(
[FocusRowBehavior],
BaseMixin(SiteSettingsMixin(I18nMixin(PolymerElement)))) as {
new (): PolymerElement & I18nMixinInterface & SiteSettingsMixinInterface &
BaseMixinInterface
};
export class SiteEntryElement extends SiteEntryElementBase {
static get is() {
return 'site-entry';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
/**
* An object representing a group of sites with the same eTLD+1.
*/
siteGroup: {
type: Object,
observer: 'onSiteGroupChanged_',
},
/**
* The name to display beside the icon. If grouped_() is true, it will be
* the eTLD+1 for all the origins, otherwise, it will return the host.
*/
displayName_: String,
/**
* The string to display when there is a non-zero number of cookies.
*/
cookieString_: String,
/**
* The position of this site-entry in its parent list.
*/
listIndex: {
type: Number,
value: -1,
},
/**
* The string to display showing the overall usage of this site-entry.
*/
overallUsageString_: String,
/**
* An array containing the strings to display showing the individual disk
* usage for each origin in |siteGroup|.
*/
originUsages_: {
type: Array,
value() {
return [];
},
},
/**
* An array containing the strings to display showing the individual
* cookies number for each origin in |siteGroup|.
*/
cookiesNum_: {
type: Array,
value() {
return [];
},
},
/**
* The selected sort method.
*/
sortMethod: {type: String, observer: 'updateOrigins_'},
enableConsolidatedSiteStorageControls_: {
type: Boolean,
value: () =>
loadTimeData.getBoolean('consolidatedSiteStorageControlsEnabled'),
},
};
}
siteGroup: SiteGroup;
private displayName_: string;
private cookieString_: string;
listIndex: number;
private overallUsageString_: string;
private originUsages_: Array<string>;
private cookiesNum_: Array<string>;
sortMethod?: SortMethod;
private enableConsolidatedSiteStorageControls_: boolean;
private button_: Element|null = null;
private localDataBrowserProxy_: LocalDataBrowserProxy =
LocalDataBrowserProxyImpl.getInstance();
private eventTracker_: EventTracker = new EventTracker();
disconnectedCallback() {
super.disconnectedCallback();
if (this.button_) {
this.eventTracker_.remove(this.button_, 'keydown');
}
}
private onButtonKeydown_(e: KeyboardEvent) {
if (e.shiftKey && e.key === 'Tab') {
this.focus();
}
}
/**
* Whether the list of origins displayed in this site-entry is a group of
* eTLD+1 origins or not.
* @param siteGroup The eTLD+1 group of origins.
*/
private grouped_(siteGroup: SiteGroup): boolean {
if (!siteGroup) {
return false;
}
if (siteGroup.origins.length > 1 ||
siteGroup.numCookies > siteGroup.origins[0].numCookies ||
siteGroup.origins.some(o => o.isPartitioned)) {
return true;
}
return false;
}
/**
* Returns a user-friendly name for the siteGroup.
* If grouped_() is true and eTLD+1 is available, returns the eTLD+1,
* otherwise return the origin representation for the first origin.
* @param siteGroup The eTLD+1 group of origins.
* @return The user-friendly name.
*/
private siteGroupRepresentation_(siteGroup: SiteGroup): string {
if (!siteGroup) {
return '';
}
if (this.grouped_(siteGroup)) {
if (siteGroup.etldPlus1 !== '') {
return siteGroup.etldPlus1;
}
// Fall back onto using the host of the first origin, if no eTLD+1 name
// was computed.
}
return this.originRepresentation(siteGroup.origins[0].origin);
}
/**
* @param siteGroup The eTLD+1 group of origins.
*/
private onSiteGroupChanged_(siteGroup: SiteGroup) {
// Update the button listener.
if (this.button_) {
this.eventTracker_.remove(this.button_, 'keydown');
}
this.button_ =
this.shadowRoot!.querySelector('#toggleButton *:not([hidden])');
this.eventTracker_.add(
assert(this.button_!), 'keydown',
(e: KeyboardEvent) => this.onButtonKeydown_(e));
if (!this.grouped_(siteGroup)) {
// Ensure ungrouped |siteGroup|s do not get stuck in an opened state.
const collapseChild = this.$.originList.getIfExists();
if (collapseChild && collapseChild.opened) {
this.toggleCollapsible_();
}
}
if (!siteGroup) {
return;
}
this.calculateUsageInfo_(siteGroup);
this.getCookieNumString_(siteGroup.numCookies).then(string => {
this.cookieString_ = string;
});
this.updateOrigins_(this.sortMethod);
this.displayName_ = this.siteGroupRepresentation_(siteGroup);
}
/**
* Returns any non-HTTPS scheme/protocol for the siteGroup that only contains
* one origin. Otherwise, returns a empty string.
* @param siteGroup The eTLD+1 group of origins.
* @return The scheme if non-HTTPS, or empty string if HTTPS.
*/
private siteGroupScheme_(siteGroup: SiteGroup): string {
if (!siteGroup || (this.grouped_(siteGroup))) {
return '';
}
return this.originScheme_(siteGroup.origins[0]);
}
/**
* Returns any non-HTTPS scheme/protocol for the origin. Otherwise, returns
* an empty string.
* @return The scheme if non-HTTPS, or empty string if HTTPS.
*/
private originScheme_(origin: OriginInfo): string {
const url = this.toUrl(origin.origin)!;
const scheme = url.protocol.replace(new RegExp(':*$'), '');
const HTTPS_SCHEME = 'https';
if (scheme === HTTPS_SCHEME) {
return '';
}
return scheme;
}
/**
* Get an appropriate favicon that represents this group of eTLD+1 sites as a
* whole.
* @param siteGroup The eTLD+1 group of origins.
* @return URL that is used for fetching the favicon
*/
private getSiteGroupIcon_(siteGroup: SiteGroup): string {
const origins = siteGroup.origins;
assert(origins);
assert(origins.length >= 1);
if (origins.length === 1) {
return origins[0].origin;
}
// If we can find a origin with format "www.etld+1", use the favicon of this
// origin. Otherwise find the origin with largest storage, and use the
// number of cookies as a tie breaker.
for (const originInfo of origins) {
if (this.toUrl(originInfo.origin)!.host ===
'www.' + siteGroup.etldPlus1) {
return originInfo.origin;
}
}
const getMaxStorage = (max: OriginInfo, originInfo: OriginInfo) => {
return (
max.usage > originInfo.usage ||
(max.usage === originInfo.usage &&
max.numCookies > originInfo.numCookies) ?
max :
originInfo);
};
return origins.reduce(getMaxStorage, origins[0]).origin;
}
/**
* Calculates the amount of disk storage used by the given eTLD+1.
* Also updates the corresponding display strings.
* @param siteGroup The eTLD+1 group of origins.
*/
private calculateUsageInfo_(siteGroup: SiteGroup) {
let overallUsage = 0;
siteGroup.origins.forEach(originInfo => {
overallUsage += originInfo.usage;
});
this.browserProxy.getFormattedBytes(overallUsage).then(string => {
this.overallUsageString_ = string;
});
}
/**
* Get display string for number of cookies.
*/
private getCookieNumString_(numCookies: number): Promise<string> {
if (numCookies === 0) {
return Promise.resolve('');
}
return this.localDataBrowserProxy_.getNumCookiesString(numCookies);
}
/**
* Array binding for the |originUsages_| array for use in the HTML.
* @param change The change record for the array.
* @param index The index of the array item.
*/
private originUsagesItem_(change: {base: Array<string>}, index: number):
string {
return change.base[index];
}
/**
* Array binding for the |cookiesNum_| array for use in the HTML.
* @param change The change record for the array.
* @param index The index of the array item.
*/
private originCookiesItem_(change: {base: Array<string>}, index: number):
string {
return change.base[index];
}
/**
* Navigates to the corresponding Site Details page for the given origin.
* @param origin The origin to navigate to the Site Details page for it.
*/
private navigateToSiteDetails_(origin: string) {
this.fire(
'site-entry-selected', {item: this.siteGroup, index: this.listIndex});
Router.getInstance().navigateTo(
routes.SITE_SETTINGS_SITE_DETAILS,
new URLSearchParams('site=' + origin));
}
/**
* A handler for selecting a site (by clicking on the origin).
*/
private onOriginTap_(e: RepeaterEvent) {
if (this.siteGroup.origins[e.model.index].isPartitioned) {
return;
}
this.navigateToSiteDetails_(this.siteGroup.origins[e.model.index].origin);
this.browserProxy.recordAction(AllSitesAction2.ENTER_SITE_DETAILS);
chrome.metricsPrivate.recordUserAction('AllSites_EnterSiteDetails');
}
/**
* A handler for clicking on a site-entry heading. This will either show a
* list of origins or directly navigates to Site Details if there is only one.
*/
private onSiteEntryTap_() {
// Individual origins don't expand - just go straight to Site Details.
if (!this.grouped_(this.siteGroup)) {
this.navigateToSiteDetails_(this.siteGroup.origins[0].origin);
this.browserProxy.recordAction(AllSitesAction2.ENTER_SITE_DETAILS);
chrome.metricsPrivate.recordUserAction('AllSites_EnterSiteDetails');
return;
}
this.toggleCollapsible_();
// Make sure the expanded origins can be viewed without further scrolling
// (in case |this| is already at the bottom of the viewport).
this.scrollIntoViewIfNeeded();
}
/**
* Toggles open and closed the list of origins if there is more than one.
*/
private toggleCollapsible_() {
const collapseChild = this.$.originList.get();
collapseChild.toggle();
this.$.toggleButton.setAttribute(
'aria-expanded', collapseChild.opened ? 'true' : 'false');
this.$.expandIcon.toggleClass('icon-expand-more');
this.$.expandIcon.toggleClass('icon-expand-less');
this.fire('iron-resize');
}
/**
* Fires a custom event when the menu button is clicked. Sends the details
* of the site entry item and where the menu should appear.
*/
private showOverflowMenu_(e: Event) {
this.fire('open-menu', {
target: e.target,
index: this.listIndex,
item: this.siteGroup,
origin: (e.target as HTMLElement).dataset['origin'],
isPartitioned: (e.target as HTMLElement).dataset['partitioned'],
actionScope: (e.target as HTMLElement).dataset['context'],
});
}
private onRemove_(e: Event) {
this.fire('remove-site', {
target: e.target,
index: this.listIndex,
item: this.siteGroup,
origin: (e.target as HTMLElement).dataset['origin'],
isPartitioned:
(e.target as HTMLElement).dataset['partitioned'] !== undefined,
actionScope: (e.target as HTMLElement).dataset['context'],
});
}
/**
* Returns the correct class to apply depending on this site-entry's position
* in a list.
*/
private getClassForIndex_(index: number): string {
return index > 0 ? 'hr' : '';
}
private getRemoveOriginButtonTitle_(origin: string): string {
return this.i18n(
'siteSettingsCookieRemoveSite', this.originRepresentation(origin));
}
/**
* Update the order and data display text for origins.
*/
private updateOrigins_(sortMethod?: SortMethod) {
if (!sortMethod || !this.siteGroup || !this.grouped_(this.siteGroup)) {
return;
}
const origins = this.siteGroup.origins.slice();
origins.sort(this.sortFunction_(sortMethod));
this.set('siteGroup.origins', origins);
this.originUsages_ = new Array(origins.length);
origins.forEach((originInfo, i) => {
this.browserProxy.getFormattedBytes(originInfo.usage).then((string) => {
this.set(`originUsages_.${i}`, string);
});
});
this.cookiesNum_ = new Array(this.siteGroup.origins.length);
origins.forEach((originInfo, i) => {
this.getCookieNumString_(originInfo.numCookies).then((string) => {
this.set(`cookiesNum_.${i}`, string);
});
});
}
/**
* Sort functions for sorting origins based on selected method.
*/
private sortFunction_(sortMethod: SortMethod):
(o1: OriginInfo, o2: OriginInfo) => number {
if (sortMethod === SortMethod.MOST_VISITED) {
return (origin1, origin2) => {
return (origin1.isPartitioned ? 1 : 0) -
(origin2.isPartitioned ? 1 : 0) ||
origin2.engagement - origin1.engagement;
};
} else if (sortMethod === SortMethod.STORAGE) {
return (origin1, origin2) => {
return (origin1.isPartitioned ? 1 : 0) -
(origin2.isPartitioned ? 1 : 0) ||
origin2.usage - origin1.usage ||
origin2.numCookies - origin1.numCookies;
};
} else if (sortMethod === SortMethod.NAME) {
return (origin1, origin2) => {
return (origin1.isPartitioned ? 1 : 0) -
(origin2.isPartitioned ? 1 : 0) ||
origin1.origin.localeCompare(origin2.origin);
};
}
assertNotReached();
return (_origin1, _origin2) => 0;
}
}
declare global {
interface HTMLElementTagNameMap {
'site-entry': SiteEntryElement;
}
}
customElements.define(SiteEntryElement.is, SiteEntryElement); | the_stack |
import * as vscode from "vscode";
import { glo, TyInLineInDepthInQueueInfo, TyDepthDecInfo } from "./extension";
import { ISingleLineBox } from "./renderingTools";
import { notYetDisposedDecsObject } from "./utils2";
// old renderer function
// eslint-disable-next-line @typescript-eslint/naming-convention
export const renderSingleLineBoxV1 = ({
editorInfo,
depth,
inDepthBlockIndex,
lineBlockType,
isfirstFromTopToDown,
isFirstFromBottomToUp,
lineZero,
boxHeight,
boxLeftEdge,
boxRightEdge,
optimalLeftOfRangePx,
optimalRightOfRangePx,
legitFirstLineZero,
legitLastLineZero,
isFocusedBlock,
firstLineHasVisibleChar,
lastLineHasVisibleChar,
}: ISingleLineBox): void => {
// console.log("lineZero:", lineZero);
const upEdge = editorInfo.upToDateLines.upEdge;
const lowEdge = editorInfo.upToDateLines.lowEdge;
if (
// !isFocusedBlock &&
upEdge >= 0 &&
lowEdge >= 1 &&
upEdge <= lowEdge &&
lineZero >= upEdge &&
lineZero <= lowEdge
) {
return;
}
// console.log("ai laiiiinnn:::", lineZero, upEdge, lowEdge);
if (
lineBlockType === "onlyLine" &&
!glo.renderInSingleLineAreas &&
!isFocusedBlock
) {
return;
}
// console.log(
// "Rendering:",
// "line:",
// lineZero + 1,
// "depthIndex",
// depth,
// "inDepthBlockIndex",
// inDepthBlockIndex,
// );
let borderSize = glo.borderSize;
const borderRadius = glo.borderRadius;
// let borderColor: string = `rgba(152, 108, 255, 1)`;
// let borderColor: string = `rgba(255, 255, 255, 0.150)`;
let borderColor: string = glo.coloring.border;
let zIndex = -1000 + depth * 10;
let borderCss: string;
let borderRadiusCss: string;
let top = 0;
let specificHeight = boxHeight;
let backgroundCSS: string = "red";
switch (depth) {
case 0:
backgroundCSS = glo.coloring.onEachDepth[0];
borderColor = glo.coloring.borderOfDepth0;
// zIndex = -100 + 10;
break;
case 1:
backgroundCSS = glo.coloring.onEachDepth[1];
break;
case 2:
backgroundCSS = glo.coloring.onEachDepth[2];
break;
case 3:
backgroundCSS = glo.coloring.onEachDepth[3];
break;
case 4:
backgroundCSS = glo.coloring.onEachDepth[4];
break;
case 5:
backgroundCSS = glo.coloring.onEachDepth[5];
break;
case 6:
backgroundCSS = glo.coloring.onEachDepth[6];
break;
case 7:
backgroundCSS = glo.coloring.onEachDepth[7];
break;
case 8:
backgroundCSS = glo.coloring.onEachDepth[8];
break;
case 9:
backgroundCSS = glo.coloring.onEachDepth[9];
break;
case 10:
backgroundCSS = glo.coloring.onEachDepth[10];
break;
default:
backgroundCSS = glo.coloring.onEachDepth[10];
}
if (glo.enableFocus && isFocusedBlock) {
// backgroundCSS = "rgb(21, 5, 64)";
// backgroundCSS = "rgb(13, 2, 41)";
// backgroundCSS = "rgb(27, 12, 48)";
if (glo.coloring.focusedBlock !== "same") {
backgroundCSS = glo.coloring.focusedBlock;
// backgroundCSS = "rgba(154, 10, 80, 0)";
}
if (glo.coloring.borderOfFocusedBlock !== "same") {
borderColor = glo.coloring.borderOfFocusedBlock;
}
borderSize = 2;
// zIndex = -3;
}
// const boxLeftEdgeFixedShift = boxLeftEdge - borderSize;
if (lineBlockType === "opening") {
borderCss = `
border-left: ${borderSize}px solid ${borderColor};
border-top: ${borderSize}px solid ${borderColor};
border-right: ${borderSize}px solid ${borderColor};
`;
borderRadiusCss = `${borderRadius}px ${borderRadius}px 0px 0px`;
top += 2 - borderSize;
specificHeight -= isFirstFromBottomToUp ? 2 : 0;
if (isFirstFromBottomToUp) {
if (firstLineHasVisibleChar) {
// top += 2; // 0
// specificHeight -= 2; // boxHeight
} else {
// top = 0 + 2; // 0
specificHeight -= 2; // boxHeight
}
}
// specificHeight = isFirstFromBottomToUp
// ? boxHeight - generalBorderSize / 2
// : undefined;
} else if (lineBlockType === "middle") {
borderCss = `
border-left: ${borderSize}px solid ${borderColor};
border-right: ${borderSize}px solid ${borderColor};
`;
// top -= isfirstFromTopToDown ? generalBorderSize : 0;
borderRadiusCss = `0px`;
// zIndex -= 1;
if (isfirstFromTopToDown) {
// return;
top += 2;
specificHeight -= 2;
// backgroundCSS = "red";
}
if (isFirstFromBottomToUp) {
specificHeight -= 2;
}
} else if (lineBlockType === "closing") {
// console.log("isfirstFromTopToDown:", isfirstFromTopToDown);
borderCss = `
border-left: ${borderSize}px solid ${borderColor};
border-right: ${borderSize}px solid ${borderColor};
border-bottom: ${borderSize}px solid ${borderColor};
`;
// top += isfirstFromTopToDown ? generalBorderSize : 0;
// top += 8;
borderRadiusCss = `0px 0px ${borderRadius}px ${borderRadius}px;`;
// specificHeight = isfirstFromTopToDown
// ? boxHeight - generalBorderSize / 2
// : undefined;
// top -= 1;
top -= 2;
// specificHeight -= 2;
if (isfirstFromTopToDown) {
if (lastLineHasVisibleChar) {
top += 2; // 0
specificHeight -= 2; // boxHeight
} else {
top = 0 + 2; // 0
specificHeight -= 4; // boxHeight
}
}
} else {
// lineBlockType === "onlyLine"
borderCss = `
border-left: ${borderSize}px solid ${borderColor};
border-right: ${borderSize}px solid ${borderColor};
border-bottom: ${borderSize}px solid ${borderColor};
border-top: ${borderSize}px solid ${borderColor};
`;
borderRadiusCss = `${borderRadius}px ${borderRadius}px ${borderRadius}px ${borderRadius}px;`;
top -= borderSize - 2;
specificHeight -= 4;
}
const currVsRange = new vscode.Range(lineZero, 0, lineZero, 0); // must be ZERO! IMPORTANT! otherwise may be dimmer when text is dimmer
if (lineZero === 0) {
top += 1;
}
// =======================
const newQueueInfo: TyInLineInDepthInQueueInfo = {
lineZero,
depthIndex: depth,
inDepthBlockIndex,
decorsRefs: {
mainBody: null, // temporal. It will not remain as null, it will be decor
leftLineOfOpening: "f", // may remain as "f", may change
rightLineOfClosing: "f", // may remain as "f", may change
},
};
const thisLineObjectBefore = editorInfo.decors[lineZero];
if (!thisLineObjectBefore) {
editorInfo.decors[lineZero] = [];
}
const thisLineObjectAfter = editorInfo.decors[lineZero] as TyDepthDecInfo[];
const thisLineDepthObjectBefore = thisLineObjectAfter[depth];
if (!thisLineDepthObjectBefore) {
thisLineObjectAfter[depth] = [newQueueInfo];
} else {
thisLineObjectAfter[depth]?.push(newQueueInfo);
}
const thisLineDepthObjectAfter = thisLineObjectAfter[
depth
] as TyInLineInDepthInQueueInfo[];
// thisLineDepthObjectAfter.depth = depth; // maybe no need
// thisLineDepthObjectAfter.inDepthBlockIndex = inDepthBlockIndex; // maybe no need
// console.log("editorInfo.decors:", editorInfo.decors);
// ========================
// const doc = editorInfo.editorRef.document;
// const thisLineData = doc.lineAt(lineZero);
// here the heavy heeeaaaavy job begins:
// return;
const isAtVeryLeft = boxLeftEdge === 0;
const leftInc = isAtVeryLeft ? 2 : 0;
const lineDecoration = vscode.window.createTextEditorDecorationType({
before: {
// rangeBehavior: 1,
// contentText,
contentText: ``,
// margin: "500px",
// border: '1px solid yellow',
// backgroundColor: backgroundCSS, // -------------
// width: "0px",
// height: "0px",
textDecoration: `;box-sizing: content-box !important;
${borderCss}
border-radius: ${borderRadiusCss};
width: calc((${
boxRightEdge - boxLeftEdge
} * (1ch + ${
glo.letterSpacing
}px)) - ${leftInc}px);
height: ${specificHeight}px;
position: absolute;
z-index: ${zIndex};
top: ${top}px;
left: calc((${boxLeftEdge} * (1ch + ${
glo.letterSpacing
}px)) + ${leftInc - borderSize}px);
background: ${backgroundCSS};
`,
// padding: 100px;
},
// rangeBehavior: vscode.DecorationRangeBehavior.OpenOpen,
// border: "1px solid blue",
// backgroundColor: `rgba(24, 230, 168, 0)`,
// textDecoration: `;border-radius: 10px;
// width: 500px;
// z-index: -500;
// `,
// border: "5px solid black",
// borderRadius: "5px",
// isWholeLine : wholeLine
// rangeBehavior: 1,
} as vscode.DecorationRenderOptions);
if (lineBlockType === "opening") {
// isFirstFromBottomToUp
let b = -2;
if (isFirstFromBottomToUp) {
b += 2;
}
const isAtVeryLeft = optimalLeftOfRangePx === 0;
const leftInc = isAtVeryLeft ? 2 : 0;
const width = boxLeftEdge - optimalLeftOfRangePx;
if (width > 0) {
const leftLineOfOpening =
vscode.window.createTextEditorDecorationType({
before: {
// rangeBehavior: 1,
// contentText,
contentText: ``,
// margin: "500px",
// border: '1px solid yellow',
backgroundColor: "rgba(0, 0, 0, 0)", // transparent
// width: "0px",
// height: "0px",
textDecoration: `;box-sizing: content-box !important;
border-bottom: ${borderSize}px solid ${borderColor};
width: calc((${width} * (1ch + ${
glo.letterSpacing
}px)) - ${leftInc - 1}px);
bottom: ${b}px;
height: ${5}px;
position: absolute;
z-index: ${zIndex + 300};
left: calc((${optimalLeftOfRangePx} * (1ch + ${
glo.letterSpacing
}px)) -
${borderSize - leftInc}px);
`,
// padding: 100px;
},
} as vscode.DecorationRenderOptions);
// thisLineDepthObjectAfter.decorsRefs.leftLineOfOpening = leftLineOfOpening;
thisLineDepthObjectAfter[
thisLineDepthObjectAfter.length - 1
]!.decorsRefs.leftLineOfOpening = leftLineOfOpening;
// if (lineZero === 103) {
notYetDisposedDecsObject.decs.push({
dRef: leftLineOfOpening,
lineZero,
});
editorInfo.editorRef.setDecorations(leftLineOfOpening, [
currVsRange,
]);
// console.log("openingiiiisss - leftLineOfOpening");
// }
}
}
if (lineBlockType === "closing") {
let t = -2;
if (isfirstFromTopToDown) {
t += 2;
}
const isAtVeryLeft = boxRightEdge === 0;
const leftInc = isAtVeryLeft ? 2 : 0;
const width = optimalRightOfRangePx - boxRightEdge;
if (width > 0) {
const rightLineOfClosing =
vscode.window.createTextEditorDecorationType({
before: {
// rangeBehavior: 1,
// contentText,
contentText: ``,
// margin: "500px",
// border: '1px solid yellow',
backgroundColor: "rgba(0, 0, 0, 0)", // transparent
// width: "0px",
// height: "0px",
textDecoration: `;box-sizing: content-box !important;
border-top: ${borderSize}px solid ${borderColor};
width: calc((${
optimalRightOfRangePx - boxRightEdge
} * (1ch + ${glo.letterSpacing}px)) - ${
leftInc - borderSize
}px);
top: ${t}px;
height: ${5}px;
position: absolute;
z-index: ${zIndex + 300};
left: calc((${boxRightEdge} * (1ch + ${
glo.letterSpacing
}px)) + ${leftInc}px);
`,
// padding: 100px;
},
} as vscode.DecorationRenderOptions);
thisLineDepthObjectAfter[
thisLineDepthObjectAfter.length - 1
]!.decorsRefs.rightLineOfClosing = rightLineOfClosing;
// if (lineZero === 103) {
notYetDisposedDecsObject.decs.push({
dRef: rightLineOfClosing,
lineZero,
});
editorInfo.editorRef.setDecorations(rightLineOfClosing, [
currVsRange,
]);
// console.log("openingiiiisss - rightLineOfClosing");
// }
}
}
thisLineDepthObjectAfter[
thisLineDepthObjectAfter.length - 1
]!.decorsRefs.mainBody = lineDecoration;
// if (lineZero === 103) {
notYetDisposedDecsObject.decs.push({
dRef: lineDecoration,
lineZero,
});
editorInfo.editorRef.setDecorations(lineDecoration, [currVsRange]);
// }
}; | the_stack |
import { Graph, Rbac, Model } from "../../types";
import * as R from "ramda";
import memoize from "../../lib/utils/memoize";
import { getConnectedAppsForBlock } from "./app_blocks";
import {
getEnvironmentsByEnvParentId,
getAppRoleEnvironmentRolesByComposite,
getAppUserGrantsByComposite,
getAppUserGroupsByComposite,
getGroupMembershipsByObjectId,
getAppGroupUserGroupsByComposite,
} from "./indexed_graph";
import { graphTypes } from "./base";
import { getAppUserGroupAssoc } from "./app_users";
const allEnvironmentReadPermissions = Object.keys(
Rbac.environmentReadPermissions
) as Rbac.EnvironmentReadPermission[],
allEnvironmentWritePermissions = Object.keys(
Rbac.environmentWritePermissions
) as Rbac.EnvironmentWritePermission[],
allEnvironmentPermissions = Object.keys(
Rbac.environmentPermissions
) as Rbac.EnvironmentPermission[];
export const getOrgPermissions = memoize(
(graph: Graph.Graph, orgRoleId: string): Set<Rbac.OrgPermission> => {
const orgRole = graph[orgRoleId];
if (!orgRole || orgRole.type != "orgRole") {
return new Set();
}
if (orgRole.isDefault) {
return new Set(
Rbac.ORG_PERMISSIONS_BY_DEFAULT_ROLE[orgRole.defaultName]
);
} else if (orgRole.extendsRoleId) {
return new Set(
R.union(
orgRole.addPermissions,
R.difference(
Array.from(getOrgPermissions(graph, orgRole.extendsRoleId)),
orgRole.removePermissions
)
)
);
} else if (orgRole.extendsRoleId === undefined) {
return new Set(orgRole.permissions);
}
return new Set();
}
),
getAppPermissions = memoize(
(graph: Graph.Graph, appRoleId: string): Set<Rbac.AppPermission> => {
const appRole = graph[appRoleId];
if (!appRole || appRole.type != "appRole") {
return new Set();
}
if (appRole.isDefault) {
return new Set(
Rbac.APP_PERMISSIONS_BY_DEFAULT_ROLE[appRole.defaultName]
);
} else if (appRole.extendsRoleId) {
return new Set(
R.union(
appRole.addPermissions,
R.difference(
Array.from(getAppPermissions(graph, appRole.extendsRoleId)),
appRole.removePermissions
)
)
);
} else if (appRole.extendsRoleId === undefined) {
return new Set(appRole.permissions);
}
return new Set();
}
),
getEnvironmentPermissions = memoize(
(
graph: Graph.Graph,
environmentId: string,
userId?: string,
accessParams?: Model.AccessParams
): Set<Rbac.EnvironmentPermission> => {
// const start = process.hrtime.bigint(),
// elapsedNs = (msg: string) =>
// console.log(
// "environment permissions",
// msg,
// "-",
// process.hrtime.bigint() - start,
// "ns elapsed"
// );
const environment = graph[environmentId] as Model.Environment;
if (!environment) {
return new Set();
}
let orgRoleId: string,
permissions: Rbac.EnvironmentPermission[] = [];
if (userId) {
const user = graph[userId] as Model.OrgUser | Model.CliUser;
orgRoleId = user.orgRoleId;
} else {
orgRoleId = accessParams!.orgRoleId;
}
const envParent = graph[environment.envParentId] as Model.EnvParent,
orgPermissions = getOrgPermissions(graph, orgRoleId);
if (envParent.type == "app") {
const appRole = getAppRoleForUserOrInvitee(
graph,
envParent.id,
userId,
accessParams
);
if (!appRole) {
return new Set();
}
permissions = getAppRoleEnvironmentRolePermissions(
graph,
appRole.id,
environment.environmentRoleId
);
// elapsedNs("got app environment permissions");
} else if (envParent.type == "block") {
if (orgPermissions.has("blocks_write_envs_all")) {
permissions = allEnvironmentPermissions;
} else {
if (orgPermissions.has("blocks_read_all")) {
permissions = allEnvironmentReadPermissions;
} else if (orgPermissions.has("blocks_write_envs_permitted")) {
const connectedApps = getConnectedAppsForBlock(graph, envParent.id);
if (connectedApps.length > 0) {
const environmentsByEnvParentId =
getEnvironmentsByEnvParentId(graph);
permissions = permissions.concat(
connectedApps.reduce<Rbac.EnvironmentPermission[]>(
(agg, app) => {
const matchEnvironment = R.find(
({ environmentRoleId, isSub }) =>
!isSub &&
environmentRoleId == environment.environmentRoleId,
environmentsByEnvParentId[app.id] ?? []
);
if (!matchEnvironment) {
return agg;
}
const appPermissions = Array.from(
getEnvironmentPermissions(
graph,
matchEnvironment.id,
userId,
accessParams
)
);
const res = [
...R.intersection(
R.intersection(agg, allEnvironmentWritePermissions),
R.intersection(
appPermissions,
allEnvironmentWritePermissions
)
),
...R.union(
R.intersection(agg, allEnvironmentReadPermissions),
R.intersection(
appPermissions,
allEnvironmentReadPermissions
)
),
] as Rbac.EnvironmentPermission[];
return res;
},
/* R.intersection will filter out any write permissions not granted on all connected app environments
(read permissions use union - i.e. if you can read *any* connected app environment, you can read
block environment) */
allEnvironmentWritePermissions
)
);
}
}
}
// elapsedNs("got block environment permissions");
}
// for sub-environments filter out permissions granted by the role if
// corresponding _subenvs scoped permission is missing
const permissionSet = new Set(permissions);
if (environment.isSub) {
if (
permissionSet.has("write") &&
!permissionSet.has("write_branches")
) {
permissionSet.delete("write");
}
if (permissionSet.has("read") && !permissionSet.has("read_branches")) {
permissionSet.delete("read");
}
if (
permissionSet.has("read_meta") &&
!permissionSet.has("read_branches_meta")
) {
permissionSet.delete("read_meta");
}
if (
permissionSet.has("read_inherits") &&
!permissionSet.has("read_branches_inherits")
) {
permissionSet.delete("read_inherits");
}
if (
permissionSet.has("read_history") &&
!permissionSet.has("read_branches_history")
) {
permissionSet.delete("read_history");
}
}
const res = new Set<Rbac.EnvironmentPermission>();
// map subenv-specific permissions to generic environment permissions
for (let permission of permissionSet) {
let v: Rbac.EnvironmentPermission | undefined;
if (environment.isSub) {
if (permission == "read_branches") v = "read";
if (permission == "read_branches_history") v = "read_history";
if (permission == "write_branches") v = "write";
if (permission == "read_branches_inherits") v = "read_inherits";
if (permission == "read_branches_meta") v = "read_meta";
}
if (!v) {
v = permission;
}
res.add(v);
}
// elapsedNs("got res");
return res;
}
),
getAppRoleEnvironmentRolePermissions = (
graph: Graph.Graph,
appRoleId: string,
environmentRoleId: string
): Rbac.EnvironmentPermission[] => {
const appRole = graph[appRoleId],
environmentRole = graph[environmentRoleId];
if (
!appRole ||
appRole.type != "appRole" ||
!environmentRole ||
environmentRole.type != "environmentRole"
) {
return [];
}
if (appRole.hasFullEnvironmentPermissions) {
return Rbac.ENVIRONMENT_FULL_PERMISSIONS;
}
if (appRole.isDefault && environmentRole.isDefault) {
return Rbac.ENVIRONMENT_PERMISSIONS_BY_DEFAULT_ROLE[appRole.defaultName][
environmentRole.defaultName
];
} else {
const appRoleEnvironmentRole =
getAppRoleEnvironmentRolesByComposite(graph)[
appRoleId + "|" + environmentRoleId
];
return [...appRoleEnvironmentRole.permissions, "read_inherits"];
}
},
getUserAppRolesByAppId = (graph: Graph.Graph, userId: string) =>
graphTypes(graph)
.apps.map(({ id: appId }) => {
const appRole = getAppRoleForUserOrInvitee(graph, appId, userId);
return appRole ? { [appId]: appRole! } : undefined;
})
.filter(Boolean)
.reduce<{ [appId: string]: Rbac.AppRole }>(R.merge, {}),
getAppRoleForUserOrInvitee = memoize(
(
graph: Graph.Graph,
appId: string,
userId?: string,
accessParams?: Model.AccessParams
) => {
let orgRoleId: string;
if (userId) {
const user = graph[userId] as Model.OrgUser | Model.CliUser | undefined;
if (!user) {
return undefined;
}
({ orgRoleId } = user);
} else {
orgRoleId = accessParams!.orgRoleId;
}
const orgRole = graph[orgRoleId] as Rbac.OrgRole;
let appRoleId: string | undefined;
if (orgRole.autoAppRoleId) {
appRoleId = orgRole.autoAppRoleId;
} else if (userId) {
const appUserGrant =
getAppUserGrantsByComposite(graph)[userId + "|" + appId];
if (appUserGrant && !appUserGrant.deletedAt) {
appRoleId = appUserGrant.appRoleId;
} else {
const appUserGroupAssoc = getAppUserGroupAssoc(graph, appId, userId);
if (appUserGroupAssoc && !appUserGroupAssoc.deletedAt) {
appRoleId = appUserGroupAssoc.appRoleId;
}
}
} else if (accessParams && accessParams.appUserGrants) {
const inviteAppUserGrant = R.find(
R.propEq("appId", appId),
accessParams.appUserGrants
);
if (inviteAppUserGrant) {
appRoleId = inviteAppUserGrant.appRoleId;
}
} else if (accessParams && accessParams.userGroupIds) {
for (let userGroupId of accessParams.userGroupIds) {
let currentAppRole: Rbac.AppRole | undefined;
const appUserGroup =
getAppUserGroupsByComposite(graph)[appId + "|" + userGroupId];
if (appUserGroup) {
const appRole = graph[appUserGroup.appRoleId] as Rbac.AppRole;
if (
!currentAppRole ||
appRole.orderIndex < currentAppRole.orderIndex
) {
currentAppRole = appRole;
appRoleId = appUserGroup.appRoleId;
}
}
}
}
if (!appRoleId) {
return undefined;
}
return graph[appRoleId] as Rbac.AppRole;
}
),
getAppRoleForUserGroup = memoize(
(graph: Graph.Graph, appId: string, userGroupId: string) => {
const appUserGroup =
getAppUserGroupsByComposite(graph)[appId + "|" + userGroupId];
if (appUserGroup) {
return graph[appUserGroup.appRoleId] as Rbac.AppRole;
}
// groups this app belongs to
const appGroupIds = (
getGroupMembershipsByObjectId(graph)[appId] ?? []
).map(R.prop("groupId"));
const appGroupUserGroupsByComposite =
getAppGroupUserGroupsByComposite(graph);
for (let appGroupId of appGroupIds) {
const appGroupUserGroup =
appGroupUserGroupsByComposite[appGroupId + "|" + userGroupId];
if (appGroupUserGroup) {
return graph[appGroupUserGroup.appRoleId] as Rbac.AppRole;
}
}
return undefined;
}
),
getConnectedAppPermissionsIntersectionForBlock = memoize(
(
graph: Graph.Graph,
blockId: string,
userId?: string,
accessParams?: Model.AccessParams
) => {
const connectedApps = getConnectedAppsForBlock(graph, blockId);
let intersection: Rbac.AppPermission[] | undefined;
for (let { id: appId } of connectedApps) {
const appRole = getAppRoleForUserOrInvitee(
graph,
appId,
userId,
accessParams
),
permissions = appRole
? Array.from(getAppPermissions(graph, appRole.id))
: [];
if (intersection) {
intersection = R.intersection(intersection, permissions);
} else {
intersection = permissions;
}
}
return new Set(intersection);
}
),
getConnectedAppPermissionsUnionForBlock = memoize(
(
graph: Graph.Graph,
blockId: string,
userId?: string,
accessParams?: Model.AccessParams
) => {
const connectedApps = getConnectedAppsForBlock(graph, blockId);
let union: Rbac.AppPermission[] = [];
for (let { id: appId } of connectedApps) {
const appRole = getAppRoleForUserOrInvitee(
graph,
appId,
userId,
accessParams
);
if (appRole) {
union = union.concat(
Array.from(getAppPermissions(graph, appRole.id))
);
}
}
return new Set(union);
}
),
getEnvParentPermissions = memoize(
(
graph: Graph.Graph,
envParentId: string,
userId?: string,
accessParams?: Model.AccessParams
): Set<Rbac.AppPermission> => {
const envParent = graph[envParentId] as Model.EnvParent | undefined;
if (!envParent) {
return new Set();
}
if (envParent.type == "app") {
let appRole: Rbac.AppRole | undefined;
appRole = getAppRoleForUserOrInvitee(
graph,
envParentId,
userId,
accessParams
);
// return new Set(Rbac.DEFAULT_APP_ADMIN_PERMISSIONS);
return appRole ? getAppPermissions(graph, appRole.id) : new Set();
} else {
// return new Set(Rbac.DEFAULT_APP_ADMIN_PERMISSIONS);
return getConnectedAppPermissionsIntersectionForBlock(
graph,
envParentId,
userId,
accessParams
);
}
}
); | the_stack |
import * as React from 'react';
import { render, fireEvent, act, screen } from '@testing-library/react';
import { ToastContainer } from '../../src/components/ToastContainer';
import { toast, eventManager, Event } from '../../src/core';
import { ToastOptions } from '../../src/types';
import { triggerAnimationEnd } from '../helpers';
jest.useFakeTimers();
beforeEach(() => {
jest.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => {
callback(1);
return 1;
});
});
afterEach(() => {
(window.requestAnimationFrame as jest.Mock).mockRestore();
});
describe('ToastContainer', () => {
it('Should bind events when mounted and unbind them when unmounted', () => {
const { unmount } = render(<ToastContainer />);
expect(eventManager.list.has(Event.Show)).toBe(true);
expect(eventManager.list.has(Event.Clear)).toBe(true);
unmount();
jest.runAllTimers();
expect(eventManager.list.has(Event.Show)).toBe(false);
expect(eventManager.list.has(Event.Clear)).toBe(false);
});
it('Should use the containerId as node id', () => {
render(<ToastContainer containerId="foo" />);
expect(document.getElementById('foo')).not.toBe(null);
});
it('Should bind event when re-mounted', () => {
const { unmount } = render(<ToastContainer />);
expect(eventManager.list.has(Event.Show)).toBe(true);
expect(eventManager.list.has(Event.Clear)).toBe(true);
unmount();
render(<ToastContainer />);
jest.runAllTimers();
expect(eventManager.list.has(Event.Show)).toBe(true);
expect(eventManager.list.has(Event.Clear)).toBe(true);
});
it('Should clear all toast when clear is called without id', () => {
render(<ToastContainer />);
act(() => {
toast('coucou1');
toast('coucou2');
jest.runAllTimers();
});
const toasts = screen.queryAllByText(/coucou/);
expect(toasts.length).toBe(2);
act(() => {
toast.dismiss();
jest.runAllTimers();
triggerAnimationEnd(toasts);
});
expect(screen.queryAllByText(/coucou/).length).toBe(0);
});
it('Should dismiss toast with id == 0 only', () => {
render(<ToastContainer />);
act(() => {
toast('toast id 0', {
toastId: 0
});
toast('toast id 1', {
toastId: 1
});
jest.runAllTimers();
});
expect(screen.getAllByText(/toast id/).length).toBe(2);
act(() => {
toast.dismiss(0);
jest.runAllTimers();
triggerAnimationEnd(screen.getByText('toast id 0'));
});
expect(screen.getAllByText(/toast id/).length).toBe(1);
});
it('Should prevent duplicate toast when same id is used', () => {
render(<ToastContainer />);
act(() => {
toast('REAL_TOAST', {
toastId: 'foo'
});
jest.runAllTimers();
});
act(() => {
toast('DUPLICATE_TOAST', {
toastId: 'foo'
});
jest.runAllTimers();
});
expect(screen.queryByText('REAL_TOAST')).not.toBe(null);
expect(screen.queryByText('DUPLICATE_TOAST')).toBe(null);
});
it('Should be able to render a react element, a string, a number, a render props without crashing', () => {
render(<ToastContainer />);
act(() => {
toast('coucou');
toast(123);
toast(<div>foo</div>);
toast(() => <div>bar</div>);
jest.runAllTimers();
});
expect(screen.getByText('coucou')).not.toBe(null);
expect(screen.getByText('123')).not.toBe(null);
expect(screen.getByText('foo')).not.toBe(null);
expect(screen.getByText('bar')).not.toBe(null);
});
it('Should be able to display new toast on top', () => {
render(<ToastContainer newestOnTop />);
const toastValues = ['t 1', 't 2', 't 3'];
act(() => {
for (const value of toastValues) {
toast(value);
}
jest.runAllTimers();
});
expect(screen.getAllByText(/t [1,2,3]/).map(el => el.textContent)).toEqual(
toastValues.reverse()
);
});
// this test could be improved by checking all the options
it('Toast options should supersede ToastContainer props', () => {
const { container } = render(<ToastContainer />);
const CloseBtn = () => <div>Close</div>;
const fn = () => {};
const desiredProps: ToastOptions = {
pauseOnHover: false,
closeOnClick: false,
onOpen: fn,
onClose: fn,
autoClose: false,
hideProgressBar: true,
position: 'top-left',
closeButton: <CloseBtn />
};
act(() => {
toast('hello', desiredProps);
jest.runAllTimers();
});
expect(screen.getByText('Close')).not.toBe(null);
expect(container.innerHTML).toMatch(/top-left/);
});
it('Should pass closeToast function and type when using a custom CloseButton', done => {
render(<ToastContainer />);
const CloseBtn = (props: any) => {
expect('closeToast' in props).toBe(true);
expect('type' in props).toBe(true);
done();
return <div>x</div>;
};
const Msg = () => <div>Plop</div>;
act(() => {
toast(<Msg />, {
closeButton: CloseBtn
});
jest.runAllTimers();
});
});
it('Should be able to disable the close button', () => {
render(<ToastContainer />);
act(() => {
toast('hello');
jest.runAllTimers();
});
// ensure that close button is present by default
expect(screen.getByLabelText('close')).not.toBe(null);
act(() => {
toast.dismiss();
jest.runAllTimers();
triggerAnimationEnd(screen.getByText('hello'));
});
act(() => {
toast('hello', {
closeButton: false
});
jest.runAllTimers();
});
expect(screen.getByText('hello')).not.toBe(null);
expect(screen.queryByLabelText('close')).toBe(null);
});
it('Should be able to delay toast rendering', () => {
render(<ToastContainer />);
act(() => {
toast('hello', { delay: 1000 });
jest.runOnlyPendingTimers();
});
expect(screen.queryByText('hello')).toBe(null);
act(() => {
jest.runAllTimers();
});
expect(screen.getByText('hello')).not.toBe(null);
});
it('Should use default CloseButton when toast option set to true and ToastContainer options is false', () => {
// set closeButton to false to remove it by default
render(<ToastContainer closeButton={false} />);
act(() => {
toast('hello');
jest.runAllTimers();
});
// ensure that close button is NOT present by default
expect(screen.queryByLabelText('close')).toBe(null);
act(() => {
toast('hello', { closeButton: true });
jest.runAllTimers();
});
// now the close button should be present
expect(screen.queryByLabelText('close')).not.toBe(null);
});
it('Should use custom CloseButton when toast option set to true and ToastContainer options is custom', () => {
const CloseBtn = () => <div aria-label="close">CUSTOM_BUTTON</div>;
render(<ToastContainer closeButton={CloseBtn} />);
act(() => {
toast('hello', { closeButton: true });
jest.runAllTimers();
});
// now the close button should be present
expect(screen.getByText('CUSTOM_BUTTON')).not.toBe(null);
});
it('Should merge className and style', () => {
const { container } = render(
<ToastContainer className="foo" style={{ background: 'red' }} />
);
act(() => {
toast('hello');
jest.runAllTimers();
});
expect(container.innerHTML).toMatch(/foo/);
expect(container.innerHTML).toMatch(/style="background: red;"/);
});
it('Should merge className and style when className is functional', () => {
const { container } = render(
<ToastContainer className={() => 'foo'} style={{ background: 'red' }} />
);
act(() => {
toast('hello');
jest.runAllTimers();
});
expect(container.innerHTML).toMatch(/foo/);
expect(container.innerHTML).toMatch(/style="background: red;"/);
});
it('Should pass a closeToast function when displaying a react component', done => {
render(<ToastContainer />);
const Msg = (props: any) => {
expect('closeToast' in props).toBe(true);
done();
return <div>Plop</div>;
};
act(() => {
toast(<Msg />);
jest.runAllTimers();
});
});
it('Should remove toast when closeToast is called', () => {
render(<ToastContainer />);
act(() => {
toast('hello');
jest.runAllTimers();
});
expect(screen.getByText('hello')).not.toBe(null);
act(() => {
fireEvent.click(screen.getByLabelText('close'));
jest.runAllTimers();
triggerAnimationEnd(screen.getByText('hello'));
});
expect(screen.queryByText('hello')).toBe(null);
});
describe('Multiple container support', () => {
it('Should render toasts in all container if enableMultiContainer is not set/false', () => {
render(
<>
<ToastContainer enableMultiContainer={false} />
<ToastContainer />
<ToastContainer containerId={1} />
</>
);
act(() => {
toast('Toast 1');
toast('Toast 2', { containerId: 1 });
jest.runAllTimers();
});
expect(screen.getAllByText('Toast 1').length).toBe(3);
expect(screen.getAllByText('Toast 2').length).toBe(3);
});
it('Should show only related toasts aka- same containerId and containerId', () => {
render(
<>
<ToastContainer containerId={1} enableMultiContainer />
<ToastContainer containerId={2} enableMultiContainer />
</>
);
act(() => {
toast('containerId 1', { containerId: 1 });
toast('containerId 2', { containerId: 2 });
jest.runAllTimers();
});
expect(screen.getAllByText('containerId 1').length).toBe(1);
expect(screen.getAllByText('containerId 2').length).toBe(1);
});
it('Should not display unrelated toasts', () => {
render(<ToastContainer containerId={1} enableMultiContainer />);
act(() => {
toast('hello', { containerId: 2 });
jest.runAllTimers();
});
expect(screen.queryByText('hello')).toBe(null);
});
it('Should display toasts when no containerId is set on the container', () => {
render(<ToastContainer enableMultiContainer />);
act(() => {
toast('hello');
jest.runAllTimers();
});
expect(screen.getByText('hello')).not.toBe(null);
});
it('Should not display any toasts with containerId', () => {
render(<ToastContainer enableMultiContainer />);
act(() => {
toast('hello', { containerId: 1 });
jest.runAllTimers();
});
expect(screen.queryByText('hello')).toBe(null);
});
});
describe('Limit number of toast displayed', () => {
it('Should not crash when using limit', () => {
render(<ToastContainer limit={2} />);
act(() => {
toast('Hello');
jest.runAllTimers();
});
expect(screen.queryByText('Hello')).not.toBe(null);
});
it('Should be possible to limit the number of toast visible', () => {
render(<ToastContainer limit={2} />);
act(() => {
toast('toast-1');
toast('toast-2');
jest.runAllTimers();
});
act(() => {
toast('toast-3');
jest.runAllTimers();
});
expect(screen.queryByText('toast-1')).not.toBe(null);
expect(screen.queryByText('toast-2')).not.toBe(null);
expect(screen.queryByText('toast-3')).toBe(null);
});
it('Should handle only limit that are > 0', () => {
render(<ToastContainer limit={0} />);
act(() => {
toast('toast-1');
toast('toast-2');
jest.runAllTimers();
});
act(() => {
toast('toast-3');
jest.runAllTimers();
});
expect(screen.queryByText('toast-1')).not.toBe(null);
expect(screen.queryByText('toast-2')).not.toBe(null);
expect(screen.queryByText('toast-3')).not.toBe(null);
});
it('Should display a new toast as soon as a slot is available', () => {
render(<ToastContainer limit={2} />);
const toastId = 'id';
act(() => {
toast('toast-1', { toastId });
toast('toast-2');
jest.runAllTimers();
});
act(() => {
toast('toast-3');
jest.runAllTimers();
});
expect(screen.queryByText('toast-1')).not.toBe(null);
expect(screen.queryByText('toast-2')).not.toBe(null);
expect(screen.queryByText('toast-3')).toBe(null);
act(() => {
toast.dismiss(toastId);
jest.runAllTimers();
triggerAnimationEnd(screen.getByText('toast-1'));
});
expect(screen.queryByText('toast-1')).toBe(null);
expect(screen.queryByText('toast-2')).not.toBe(null);
expect(screen.queryByText('toast-3')).not.toBe(null);
});
it('Should be possible to clear limit queue', () => {
render(<ToastContainer limit={2} />);
const toastId = 'id';
act(() => {
toast('toast-1', { toastId });
toast('toast-2');
jest.runAllTimers();
});
act(() => {
toast('toast-3');
jest.runAllTimers();
});
expect(screen.queryByText('toast-1')).not.toBe(null);
expect(screen.queryByText('toast-2')).not.toBe(null);
expect(screen.queryByText('toast-3')).toBe(null);
act(() => {
toast.clearWaitingQueue();
jest.runAllTimers();
});
act(() => {
toast.dismiss(toastId);
jest.runAllTimers();
triggerAnimationEnd(screen.getByText('toast-1'));
});
expect(screen.queryByText('toast-1')).toBe(null);
expect(screen.queryByText('toast-2')).not.toBe(null);
expect(screen.queryByText('toast-3')).toBe(null);
});
});
}); | the_stack |
import Web3 from 'web3';
import ERC20ABI from '../contracts/abi/erc-20';
import { AbiItem } from 'web3-utils';
import { ContractOptions } from 'web3-eth-contract';
import { gasEstimate, executeTransaction, getNextNonceFromEstimate, Operation, gasInToken } from './utils/safe-utils';
import { signSafeTx } from './utils/signing-utils';
import BN from 'bn.js';
import { query } from './utils/graphql';
import { TransactionReceipt } from 'web3-core';
import { TransactionOptions, waitForSubgraphIndexWithTxnReceipt, isTransactionHash } from './utils/general-utils';
const { fromWei } = Web3.utils;
export interface ISafes {
viewSafe(safeAddress: string): Promise<ViewSafeResult>;
view(options?: Partial<Options>): Promise<ViewSafesResult>;
view(owner?: string): Promise<ViewSafesResult>;
view(owner?: string, options?: Partial<Options>): Promise<ViewSafesResult>;
sendTokensGasEstimate(safeAddress: string, tokenAddress: string, recipient: string, amount: string): Promise<string>;
sendTokens(txnHash: string): Promise<TransactionReceipt>;
sendTokens(
safeAddress: string,
tokenAddress: string,
recipient: string,
amount: string,
txnOptions?: TransactionOptions,
contractOptions?: ContractOptions
): Promise<TransactionReceipt>;
}
export type Safe = DepotSafe | PrepaidCardSafe | MerchantSafe | RewardSafe | ExternalSafe;
interface BaseSafe {
address: string;
createdAt: number;
tokens: TokenInfo[];
owners: string[];
}
export interface DepotSafe extends BaseSafe {
type: 'depot';
infoDID?: string;
}
export interface MerchantSafe extends BaseSafe {
type: 'merchant';
accumulatedSpendValue: number;
merchant: string;
infoDID?: string;
}
export interface RewardSafe extends BaseSafe {
type: 'reward';
rewardProgramId: string;
}
export interface ExternalSafe extends BaseSafe {
type: 'external';
}
export interface PrepaidCardSafe extends BaseSafe {
type: 'prepaid-card';
issuingToken: string;
spendFaceValue: number;
prepaidCardOwner: string;
hasBeenUsed: boolean;
issuer: string;
reloadable: boolean;
transferrable: boolean;
customizationDID?: string;
}
export interface TokenInfo {
tokenAddress: string;
token: {
name: string;
symbol: string;
decimals: number;
};
balance: string; // balance is in wei
}
export interface Options {
viewAll: boolean;
type?: Safe['type'];
}
const defaultOptions: Options = { viewAll: false };
export interface ViewSafeResult {
safe: Safe | undefined;
blockNumber: number;
}
export interface ViewSafesResult {
safes: Safe[];
blockNumber: number;
}
const safeQueryFields = `
id
createdAt
owners {
owner {
id
}
}
tokens {
balance
token {
id
name
symbol
}
}
depot {
id
infoDid
}
prepaidCard {
id
customizationDID
issuingToken {
symbol
id
}
faceValue
payments {
id
}
issuer {
id
}
owner {
id
}
reloadable
}
merchant {
id
spendBalance
infoDid
merchant {
id
}
}
reward {
id
rewardee {
id
}
}
`;
const safeQuery = `
query ($id: ID!) {
safe(id: $id) {
${safeQueryFields}
}
_meta {
block {
number
}
}
}
`;
const safesQuery = `
query($account: ID!) {
account(id: $account) {
safes(orderBy:ownershipChangedAt orderDirection:desc) {
safe {
${safeQueryFields}
}
}
}
_meta {
block {
number
}
}
}
`;
const safesFilteredQuery = `
query($account: ID!, $type: String) {
account(id: $account) {
safes(orderBy:ownershipChangedAt orderDirection:desc, where: {type: $type}) {
safe {
${safeQueryFields}
}
}
}
_meta {
block {
number
}
}
}
`;
export async function viewSafe(network: 'xdai' | 'sokol', safeAddress: string): Promise<ViewSafeResult> {
let {
data: { safe, _meta },
} = await query(network, safeQuery, { id: safeAddress });
return {
safe: processSafeResult(safe as GraphQLSafeResult),
blockNumber: _meta.block.number,
};
}
export default class Safes implements ISafes {
constructor(private layer2Web3: Web3) {}
async viewSafe(safeAddress: string): Promise<ViewSafeResult> {
let {
data: { safe, _meta },
} = await query(this.layer2Web3, safeQuery, { id: safeAddress });
return {
safe: processSafeResult(safe as GraphQLSafeResult),
blockNumber: _meta.block.number,
};
}
async view(options?: Partial<Options>): Promise<ViewSafesResult>;
async view(owner?: string): Promise<ViewSafesResult>;
async view(owner?: string, options?: Partial<Options>): Promise<ViewSafesResult>;
async view(ownerOrOptions?: string | Partial<Options>, options?: Partial<Options>): Promise<ViewSafesResult> {
let owner: string;
let _options: Options | undefined;
if (typeof ownerOrOptions === 'string') {
owner = ownerOrOptions;
} else {
owner = (await this.layer2Web3.eth.getAccounts())[0];
_options = { ...defaultOptions, ...(ownerOrOptions ?? {}) };
}
_options = { ...defaultOptions, ...(options ?? _options ?? {}) };
let account, _meta;
if (options?.type) {
let type = options.type === 'external' ? null : options.type;
({
data: { account, _meta },
} = await query(this.layer2Web3, safesFilteredQuery, { account: owner, type }));
} else {
({
data: { account, _meta },
} = await query(this.layer2Web3, safesQuery, { account: owner }));
}
if (account == null) {
return {
safes: [],
blockNumber: _meta.block.number,
};
}
let { safes } = account;
let result: Safe[] = [];
for (let { safe } of safes as { safe: GraphQLSafeResult }[]) {
let safeResult = processSafeResult(safe);
if (safeResult) {
if (_options.viewAll) {
result.push(safeResult);
} else if (safeResult.type === 'prepaid-card' && safeResult.spendFaceValue > 0) {
result.push(safeResult);
} else if (safeResult.type === 'merchant' || safeResult.type === 'depot' || safeResult.type === 'reward') {
result.push(safeResult);
}
}
}
return {
safes: result,
blockNumber: _meta.block.number,
};
}
// Note that the returned amount is in units of the token specified in the
// function params, tokenAddress
async sendTokensGasEstimate(
safeAddress: string,
tokenAddress: string,
recipient: string,
amount: string
): Promise<string> {
let token = new this.layer2Web3.eth.Contract(ERC20ABI as AbiItem[], tokenAddress);
let safeBalance = new BN(await token.methods.balanceOf(safeAddress).call());
if (safeBalance.lt(new BN(amount))) {
throw new Error(
`Safe does not have enough balance to transfer tokens. The token ${tokenAddress} balance of safe ${safeAddress} is ${fromWei(
safeBalance.toString()
)}, amount to transfer ${fromWei(amount)}`
);
}
let payload = this.transferTokenPayload(tokenAddress, recipient, amount);
let estimate = await gasEstimate(
this.layer2Web3,
safeAddress,
tokenAddress,
'0',
payload,
Operation.CALL,
tokenAddress
);
return gasInToken(estimate).toString();
}
async sendTokens(txnHash: string): Promise<TransactionReceipt>;
async sendTokens(
safeAddress: string,
tokenAddress: string,
recipient: string,
amount: string,
txnOptions?: TransactionOptions,
contractOptions?: ContractOptions
): Promise<TransactionReceipt>;
async sendTokens(
safeAddressOrTxnHash: string,
tokenAddress?: string,
recipient?: string,
amount?: string,
txnOptions?: TransactionOptions,
contractOptions?: ContractOptions
): Promise<TransactionReceipt> {
if (isTransactionHash(safeAddressOrTxnHash)) {
let txnHash = safeAddressOrTxnHash;
return waitForSubgraphIndexWithTxnReceipt(this.layer2Web3, txnHash);
}
let safeAddress = safeAddressOrTxnHash;
if (!tokenAddress) {
throw new Error('tokenAddress must be specified');
}
if (!recipient) {
throw new Error('recipient must be specified');
}
if (!amount) {
throw new Error('amount must be specified');
}
let { nonce, onNonce, onTxnHash } = txnOptions ?? {};
let from = contractOptions?.from ?? (await this.layer2Web3.eth.getAccounts())[0];
let token = new this.layer2Web3.eth.Contract(ERC20ABI as AbiItem[], tokenAddress);
let symbol = await token.methods.symbol().call();
let safeBalance = new BN(await token.methods.balanceOf(safeAddress).call());
if (safeBalance.lt(new BN(amount))) {
throw new Error(
`Safe does not have enough balance to transfer tokens. The token ${tokenAddress} balance of safe ${safeAddress} is ${fromWei(
safeBalance.toString()
)}, amount to transfer ${fromWei(amount)}`
);
}
let payload = this.transferTokenPayload(tokenAddress, recipient, amount);
let estimate = await gasEstimate(
this.layer2Web3,
safeAddress,
tokenAddress,
'0',
payload,
Operation.CALL,
tokenAddress
);
let gasCost = gasInToken(estimate);
if (safeBalance.lt(new BN(amount).add(gasCost))) {
throw new Error(
`Safe does not have enough balance to pay for gas when transfer tokens. The token ${tokenAddress} balance of safe ${safeAddress} is ${fromWei(
safeBalance.toString()
)} ${symbol}, amount to transfer ${fromWei(amount)} ${symbol}, the gas cost is ${fromWei(gasCost)} ${symbol}`
);
}
if (nonce == null) {
nonce = getNextNonceFromEstimate(estimate);
if (typeof onNonce === 'function') {
onNonce(nonce);
}
}
let result = await executeTransaction(
this.layer2Web3,
safeAddress,
tokenAddress,
payload,
Operation.CALL,
estimate,
nonce,
await signSafeTx(this.layer2Web3, safeAddress, tokenAddress, payload, estimate, nonce, from)
);
let txnHash = result.ethereumTx.txHash;
if (typeof onTxnHash === 'function') {
await onTxnHash(txnHash);
}
return await waitForSubgraphIndexWithTxnReceipt(this.layer2Web3, txnHash);
}
private transferTokenPayload(tokenAddress: string, recipient: string, amount: string): string {
let token = new this.layer2Web3.eth.Contract(ERC20ABI as AbiItem[], tokenAddress);
return token.methods.transfer(recipient, amount).encodeABI();
}
}
interface GraphQLSafeResult {
id: string;
createdAt: string;
owners: {
owner: {
id: string;
};
}[];
tokens: {
balance: string;
token: {
id: string;
name: string;
symbol: string;
};
}[];
depot: {
id: string;
infoDid: string | null;
} | null;
prepaidCard: {
id: string;
customizationDID: string | null;
issuingToken: {
symbol: string;
id: string;
};
owner: {
id: string;
};
payments: {
id: string;
}[];
faceValue: string;
issuer: { id: string };
reloadable: boolean;
} | null;
merchant: {
id: string;
spendBalance: string;
infoDid: string | null;
merchant: {
id: string;
};
};
reward: {
id: string;
rewardProgramId: string;
rewardee: {
id: string;
};
};
}
function processSafeResult(safe: GraphQLSafeResult): Safe | undefined {
if (!safe) {
return;
}
let tokens: TokenInfo[] = [];
let createdAt = parseInt(safe.createdAt);
for (let tokenDetail of safe.tokens) {
tokens.push({
tokenAddress: tokenDetail.token.id,
balance: tokenDetail.balance,
token: {
name: tokenDetail.token.name,
symbol: tokenDetail.token.symbol,
// we should really get this from teh subgraph--but honestly having
// a non-decimal 18 token messes so many other things up on-chain
// that likely we'll never support a non-decimal 18 token
decimals: 18,
},
});
}
let owners: string[] = [];
for (let ownerInfo of safe.owners) {
let {
owner: { id: owner },
} = ownerInfo;
owners.push(owner);
}
if (safe.depot) {
let depot: DepotSafe = {
type: 'depot',
address: safe.depot.id,
infoDID: safe.depot.infoDid ? safe.depot.infoDid : undefined,
tokens,
createdAt,
owners,
};
return depot;
} else if (safe.merchant) {
let merchant: MerchantSafe = {
type: 'merchant',
address: safe.merchant.id,
infoDID: safe.merchant.infoDid ? safe.merchant.infoDid : undefined,
accumulatedSpendValue: parseInt(safe.merchant.spendBalance),
merchant: safe.merchant.merchant.id,
tokens,
createdAt,
owners,
};
return merchant;
} else if (safe.prepaidCard) {
let prepaidCard: PrepaidCardSafe = {
type: 'prepaid-card',
address: safe.prepaidCard.id,
customizationDID: safe.prepaidCard.customizationDID ? safe.prepaidCard.customizationDID : undefined,
issuingToken: safe.prepaidCard.issuingToken.id,
spendFaceValue: parseInt(safe.prepaidCard.faceValue),
issuer: safe.prepaidCard.issuer.id,
hasBeenUsed: safe.prepaidCard.payments.length > 0,
reloadable: safe.prepaidCard.reloadable,
transferrable: safe.prepaidCard.payments.length === 0 && safe.prepaidCard.issuer.id === safe.prepaidCard.owner.id,
prepaidCardOwner: safe.prepaidCard.owner.id,
tokens,
createdAt,
owners,
};
return prepaidCard;
} else if (safe.reward) {
let reward: RewardSafe = {
type: 'reward',
address: safe.reward.id,
rewardProgramId: safe.reward.rewardProgramId,
tokens,
createdAt,
owners,
};
return reward;
} else {
let externalSafe: ExternalSafe = {
type: 'external',
address: safe.id,
tokens,
createdAt,
owners,
};
return externalSafe;
}
} | the_stack |
import { useCallback, useContext, useEffect, useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import { useNavigationHook } from '../../hooks/Navigation';
import { ALL_ROUTER_TYPES } from '../../router/Types';
import MilvusGrid from '../../components/grid/Grid';
import CustomToolBar from '../../components/grid/ToolBar';
import {
CollectionCreateParam,
CollectionView,
DataTypeEnum,
InsertDataParam,
} from './Types';
import { ColDefinitionsType, ToolBarConfig } from '../../components/grid/Types';
import { usePaginationHook } from '../../hooks/Pagination';
import icons from '../../components/icons/Icons';
import EmptyCard from '../../components/cards/EmptyCard';
import Status from '../../components/status/Status';
import { useTranslation } from 'react-i18next';
import { ChildrenStatusType } from '../../components/status/Types';
import { makeStyles, Theme } from '@material-ui/core';
import StatusIcon from '../../components/status/StatusIcon';
import CustomToolTip from '../../components/customToolTip/CustomToolTip';
import { rootContext } from '../../context/Root';
import CreateCollection from './Create';
import DeleteTemplate from '../../components/customDialog/DeleteDialogTemplate';
import { CollectionHttp } from '../../http/Collection';
import {
useInsertDialogHook,
useLoadAndReleaseDialogHook,
} from '../../hooks/Dialog';
import Highlighter from 'react-highlight-words';
import { parseLocationSearch } from '../../utils/Format';
import InsertContainer from '../../components/insert/Container';
import { MilvusHttp } from '../../http/Milvus';
import { LOADING_STATE } from '../../consts/Milvus';
import { webSokcetContext } from '../../context/WebSocket';
import { WS_EVENTS, WS_EVENTS_TYPE } from '../../consts/Http';
import { checkIndexBuilding, checkLoading } from '../../utils/Validation';
// import CreateAlias from './CreateAlias';
const useStyles = makeStyles((theme: Theme) => ({
emptyWrapper: {
marginTop: theme.spacing(2),
},
icon: {
fontSize: '20px',
marginLeft: theme.spacing(0.5),
},
dialogContent: {
lineHeight: '24px',
fontSize: '16px',
},
link: {
color: theme.palette.common.black,
},
highlight: {
color: theme.palette.primary.main,
backgroundColor: 'transparent',
},
}));
let timer: NodeJS.Timeout | null = null;
// get init search value from url
const { urlSearch = '' } = parseLocationSearch(window.location.search);
const Collections = () => {
useNavigationHook(ALL_ROUTER_TYPES.COLLECTIONS);
const { handleAction } = useLoadAndReleaseDialogHook({ type: 'collection' });
const { handleInsertDialog } = useInsertDialogHook();
const [search, setSearch] = useState<string>(urlSearch);
const [loading, setLoading] = useState<boolean>(false);
const [selectedCollections, setSelectedCollections] = useState<
CollectionView[]
>([]);
const { setDialog, handleCloseDialog, openSnackBar } =
useContext(rootContext);
const { collections, setCollections } = useContext(webSokcetContext);
const { t: collectionTrans } = useTranslation('collection');
const { t: btnTrans } = useTranslation('btn');
const { t: dialogTrans } = useTranslation('dialog');
const { t: successTrans } = useTranslation('success');
const classes = useStyles();
const LoadIcon = icons.load;
const ReleaseIcon = icons.release;
const InfoIcon = icons.info;
const searchedCollections = useMemo(
() => collections.filter(collection => collection._name.includes(search)),
[collections, search]
);
const formatCollections = useMemo(() => {
const data = searchedCollections.map(v => {
// const indexStatus = statusRes.find(item => item._name === v._name);
Object.assign(v, {
nameElement: (
<Link to={`/collections/${v._name}`} className={classes.link}>
<Highlighter
textToHighlight={v._name}
searchWords={[search]}
highlightClassName={classes.highlight}
/>
</Link>
),
statusElement: (
<Status status={v._status} percentage={v._loadedPercentage} />
),
indexCreatingElement: (
<StatusIcon type={v._indexState || ChildrenStatusType.FINISH} />
),
});
return v;
});
return data;
}, [classes.highlight, classes.link, search, searchedCollections]);
const {
pageSize,
handlePageSize,
currentPage,
handleCurrentPage,
total,
data: collectionList,
handleGridSort,
order,
orderBy,
} = usePaginationHook(formatCollections);
const fetchData = useCallback(async () => {
try {
setLoading(true);
const res = await CollectionHttp.getCollections();
const hasLoadingOrBuildingCollection = res.some(
v => checkLoading(v) || checkIndexBuilding(v)
);
// if some collection is building index or loading, start pulling data
if (hasLoadingOrBuildingCollection) {
MilvusHttp.triggerCron({
name: WS_EVENTS.COLLECTION,
type: WS_EVENTS_TYPE.START,
});
}
setCollections(res);
} finally {
setLoading(false);
}
}, [setCollections]);
useEffect(() => {
fetchData();
}, [fetchData]);
const handleInsert = async (
collectionName: string,
partitionName: string,
fieldData: any[]
): Promise<{ result: boolean; msg: string }> => {
const param: InsertDataParam = {
partition_names: [partitionName],
fields_data: fieldData,
};
try {
await CollectionHttp.insertData(collectionName, param);
await MilvusHttp.flush(collectionName);
// update collections
fetchData();
return { result: true, msg: '' };
} catch (err: any) {
const {
response: {
data: { message },
},
} = err;
return { result: false, msg: message || '' };
}
};
const handleCreateCollection = async (param: CollectionCreateParam) => {
const data: CollectionCreateParam = JSON.parse(JSON.stringify(param));
const vectorType = [DataTypeEnum.BinaryVector, DataTypeEnum.FloatVector];
data.fields = data.fields.map(v =>
vectorType.includes(v.data_type)
? {
...v,
type_params: {
// if data type is vector, dimension must exist.
dim: v.dimension!,
},
}
: v
);
await CollectionHttp.createCollection(data);
handleCloseDialog();
openSnackBar(
successTrans('create', { name: collectionTrans('collection') })
);
fetchData();
};
const handleRelease = async (data: CollectionView) => {
const res = await CollectionHttp.releaseCollection(data._name);
openSnackBar(
successTrans('release', { name: collectionTrans('collection') })
);
fetchData();
return res;
};
const handleLoad = async (data: CollectionView) => {
const res = await CollectionHttp.loadCollection(data._name);
openSnackBar(successTrans('load', { name: collectionTrans('collection') }));
fetchData();
return res;
};
const handleDelete = async () => {
for (const item of selectedCollections) {
await CollectionHttp.deleteCollection(item._name);
}
openSnackBar(
successTrans('delete', { name: collectionTrans('collection') })
);
fetchData();
handleCloseDialog();
setSelectedCollections([]);
};
const handleSearch = (value: string) => {
if (timer) {
clearTimeout(timer);
}
setSearch(value);
};
const toolbarConfigs: ToolBarConfig[] = [
{
label: collectionTrans('create'),
onClick: () => {
setDialog({
open: true,
type: 'custom',
params: {
component: (
<CreateCollection handleCreate={handleCreateCollection} />
),
},
});
},
icon: 'add',
},
{
label: btnTrans('insert'),
onClick: () => {
handleInsertDialog(
<InsertContainer
collections={formatCollections}
defaultSelectedCollection={
selectedCollections.length === 1
? selectedCollections[0]._name
: ''
}
// user can't select partition on collection page, so default value is ''
defaultSelectedPartition={''}
handleInsert={handleInsert}
/>
);
},
/**
* insert validation:
* 1. At least 1 available collection
* 2. selected collections quantity shouldn't over 1
*/
disabled: () =>
collectionList.length === 0 || selectedCollections.length > 1,
btnVariant: 'outlined',
},
{
type: 'iconBtn',
onClick: () => {
setDialog({
open: true,
type: 'custom',
params: {
component: (
<DeleteTemplate
label={btnTrans('delete')}
title={dialogTrans('deleteTitle', {
type: collectionTrans('collection'),
})}
text={collectionTrans('deleteWarning')}
handleDelete={handleDelete}
/>
),
},
});
},
label: collectionTrans('delete'),
icon: 'delete',
// tooltip: collectionTrans('deleteTooltip'),
disabledTooltip: collectionTrans('deleteTooltip'),
disabled: data => data.length === 0,
},
// Todo: hide alias after we can get all alias from milvus.
// {
// type: 'iconBtn',
// onClick: () => {
// setDialog({
// open: true,
// type: 'custom',
// params: {
// component: (
// <CreateAlias
// collectionName={selectedCollections[0]._name}
// cb={() => {
// setSelectedCollections([]);
// }}
// />
// ),
// },
// });
// },
// label: collectionTrans('alias'),
// icon: 'alias',
// disabledTooltip: collectionTrans('aliasTooltip'),
// disabled: data => data.length !== 1,
// },
{
label: 'Search',
icon: 'search',
searchText: search,
onSearch: (value: string) => {
handleSearch(value);
},
},
];
const colDefinitions: ColDefinitionsType[] = [
{
id: 'nameElement',
align: 'left',
disablePadding: true,
sortBy: '_name',
label: collectionTrans('name'),
},
{
id: 'statusElement',
align: 'left',
disablePadding: false,
sortBy: '_status',
label: collectionTrans('status'),
},
{
id: '_rowCount',
align: 'left',
disablePadding: false,
label: (
<span className="flex-center">
{collectionTrans('rowCount')}
<CustomToolTip title={collectionTrans('tooltip')}>
<InfoIcon classes={{ root: classes.icon }} />
</CustomToolTip>
</span>
),
},
{
id: '_desc',
align: 'left',
disablePadding: false,
label: collectionTrans('desc'),
},
{
id: '_createdTime',
align: 'left',
disablePadding: false,
label: collectionTrans('createdTime'),
},
{
id: 'indexCreatingElement',
align: 'left',
disablePadding: false,
label: '',
},
{
id: 'action',
align: 'center',
disablePadding: false,
label: '',
showActionCell: true,
isHoverAction: true,
actionBarConfigs: [
{
onClick: (e: React.MouseEvent, row: CollectionView) => {
const cb =
row._status === LOADING_STATE.UNLOADED
? handleLoad
: handleRelease;
handleAction(row, cb);
},
icon: 'load',
label: 'load',
showIconMethod: 'renderFn',
getLabel: (row: CollectionView) =>
row._status === LOADING_STATE.UNLOADED ? 'load' : 'release',
renderIconFn: (row: CollectionView) =>
row._status === LOADING_STATE.UNLOADED ? (
<LoadIcon />
) : (
<ReleaseIcon />
),
},
],
},
];
const handleSelectChange = (value: any) => {
setSelectedCollections(value);
};
const handlePageChange = (e: any, page: number) => {
handleCurrentPage(page);
setSelectedCollections([]);
};
const CollectionIcon = icons.navCollection;
return (
<section className="page-wrapper">
{collections.length > 0 || loading ? (
<MilvusGrid
toolbarConfigs={toolbarConfigs}
colDefinitions={colDefinitions}
rows={collectionList}
rowCount={total}
primaryKey="_name"
selected={selectedCollections}
setSelected={handleSelectChange}
page={currentPage}
onChangePage={handlePageChange}
rowsPerPage={pageSize}
setRowsPerPage={handlePageSize}
isLoading={loading}
handleSort={handleGridSort}
order={order}
orderBy={orderBy}
/>
) : (
<>
<CustomToolBar toolbarConfigs={toolbarConfigs} />
<EmptyCard
wrapperClass={`page-empty-card ${classes.emptyWrapper}`}
icon={<CollectionIcon />}
text={collectionTrans('noData')}
/>
</>
)}
</section>
);
};
export default Collections; | the_stack |
import {Authorized, CurrentUser, ForbiddenError, Get, JsonController, Param, UseBefore} from 'routing-controllers';
import passportJwtMiddleware from '../security/passportJwtMiddleware';
import {Progress} from '../models/progress/Progress';
import {IProgress} from '../../../shared/models/progress/IProgress';
import {IUser} from '../../../shared/models/IUser';
import * as mongoose from 'mongoose';
import ObjectId = mongoose.Types.ObjectId;
import {Course, ICourseModel} from '../models/Course';
import {ILecture} from '../../../shared/models/ILecture';
import {IUnit} from '../../../shared/models/units/IUnit';
import {ICourse} from '../../../shared/models/ICourse';
import {Unit} from '../models/units/Unit';
@JsonController('/report')
@UseBefore(passportJwtMiddleware)
export class ReportController {
/**
* @api {get} /api/report/overview/courses/:id Request course overview
* @apiName GetCourseOverview
* @apiGroup Report
* @apiPermission teacher
* @apiPermission admin
*
* @apiParam {String} id Course ID.
* @apiParam {IUser} currentUser Currently logged in user.
*
* @apiSuccess {Object} course Course with progress stats.
*
* @apiSuccessExample {json} Success-Response:
* {
* "_id": "5a53c474a347af01b84e54b7",
* "name": "Test 101",
* "lectures": [{
* "_id": "5ab18d7defbc191b10dad856",
* "name": "Lecture One",
* "units": [{
* "_id": "5ab2b80a6fab4a3ae0cd672d",
* "updatedAt": "2018-03-21T19:56:13.326Z",
* "createdAt": "2018-03-21T19:52:42.716Z",
* "_course": "5a53c474a347af01b84e54b7",
* "progressable": true,
* "weight": 0,
* "name": "Progressable unit",
* "description": null,
* "deadline": "2018-03-21T22:59:00.000Z",
* "__v": 1,
* "__t": "task",
* "tasks": [...],
* "progressData": [{
* "name": "nothing",
* "value": -1
* }, {
* "name": "tried",
* "value": 1
* }, {
* "name": "done",
* "value": 0
* }]
* }]
* }],
* "students": [],
* "hasAccessKey": false
* }
*
* @apiError ForbiddenError You are no admin or teacher for this course.
*/
@Get('/overview/courses/:id')
@Authorized(['teacher', 'admin'])
async getCourseOverview(@Param('id') id: string, @CurrentUser() currentUser: IUser) {
const coursePromise = this.createCoursePromise(id);
const progressPromise = Progress.aggregate([
{$match: { course: new ObjectId(id) }},
{$group: { _id: '$unit', progresses: { $push: '$$ROOT' }}}
]).exec();
const [course, unitProgressData] = await Promise.all([coursePromise, progressPromise]);
this.checkAccess(course, currentUser);
const courseObjUnfiltered: ICourse = <ICourse>course.toObject();
const courseObj = this.countUnitsAndRemoveEmptyLectures(courseObjUnfiltered, currentUser).courseObj;
courseObj.lectures.map((lecture: ILecture) => {
lecture.units.map((unit) => {
const progressStats = this.calculateProgress(unitProgressData, courseObj.students.length, unit);
unit.progressData = [
{ name: 'nothing', value: progressStats.nothing },
{ name: 'tried', value: progressStats.tried },
{ name: 'done', value: progressStats.done }
];
});
});
return courseObj;
}
/**
* @api {get} /api/report/result/courses/:id Request course results
* @apiName GetCourseResult
* @apiGroup Report
* @apiPermission teacher
* @apiPermission admin
*
* @apiParam {String} id Course ID.
* @apiParam {IUser} currentUser Currently logged in user.
*
* @apiSuccess {Object[]} students Students with units and progress stats.
*
* @apiSuccessExample {json} Success-Response:
* [{
* "_id": "5954c62923de070007fad047",
* "updatedAt": "2017-06-29T09:19:54.227Z",
* "createdAt": "2017-06-29T09:19:37.436Z",
* "email": "geli.hda@gmail.com",
* "uid": "744961",
* "__v": 0,
* "isActive": true,
* "lastVisitedCourses": [],
* "role": "student",
* "profile": {
* "lastName": "Gerhard Paule",
* "firstName": "Von Schröder"
* },
* "id": "5954c62923de070007fad047",
* "progress": {
* "units": [],
* "stats": [{
* "name": "Progress",
* "series": [{
* "name": "nothing",
* "value": 4
* }, {
* "name": "tried",
* "value": 0
* }, {
* "name": "done",
* "value": 0
* }]
* }]
* }
* }, {
* "_id": "59fc9fbc6405b400085564c6",
* "updatedAt": "2018-01-25T10:02:48.569Z",
* "createdAt": "2017-11-03T16:56:28.167Z",
* "email": "mueller.dav+test@gmail.com",
* "__v": 0,
* "isActive": true,
* "lastVisitedCourses": ["597df6d5b7a9c0000616637f", "5a5f3b70b5cbe70006f9befc", "5953e5b868f8c80007898785"],
* "role": "admin",
* "profile": {
* "firstName": "Test12",
* "lastName": "Schmidt",
* "theme": "default"
* },
* "id": "59fc9fbc6405b400085564c6",
* "progress": {
* "units": [],
* "stats": [{
* "name": "Progress",
* "series": [{
* "name": "nothing",
* "value": 4
* }, {
* "name": "tried",
* "value": 0
* }, {
* "name": "done",
* "value": 0
* }]
* }]
* }
* }, {
* "_id": "597dfde2b7a9c0000616639d",
* "updatedAt": "2018-01-25T10:48:21.987Z",
* "createdAt": "2017-07-30T15:40:18.912Z",
* "email": "mueller.dav+gelistudent@gmail.com",
* "uid": "123456",
* "__v": 0,
* "isActive": true,
* "lastVisitedCourses": ["5a5f3b70b5cbe70006f9befc", "597df6d5b7a9c0000616637f", "5a134dcc104f7700067562c0"],
* "role": "student",
* "profile": {
* "firstName": "Davidstudent1",
* "lastName": "Müllerstudent2"
* },
* "id": "597dfde2b7a9c0000616639d",
* "progress": {
* "units": [],
* "stats": [{
* "name": "Progress",
* "series": [{
* "name": "nothing",
* "value": 4
* }, {
* "name": "tried",
* "value": 0
* }, {
* "name": "done",
* "value": 0
* }]
* }]
* }
* }]
*
* @apiError ForbiddenError You are no admin or teacher for this course.
*/
@Get('/result/courses/:id')
@Authorized(['teacher', 'admin'])
async getCourseResults(@Param('id') id: string, @CurrentUser() currentUser: IUser) {
const coursePromise = this.createCoursePromise(id);
const progressPromise = Progress.aggregate([
{$match: { course: new ObjectId(id) }},
{$lookup: { from: 'units', localField: 'unit', foreignField: '_id', as: 'unit' }},
{$group: { _id: '$user', progresses: { $push: '$$ROOT' }}}
]).exec();
const [course, userProgressDataRaw] = await Promise.all([coursePromise, progressPromise]);
this.checkAccess(course, currentUser);
const courseObj: ICourse = <ICourse>course.toObject();
const students = courseObj.students;
const progressableUnits: IUnit[] = [];
courseObj.lectures.forEach((lecture: ILecture) => {
lecture.units.forEach((unit) => {
if (unit.progressable) {
progressableUnits.push(unit);
}
});
});
const userProgressData = await userProgressDataRaw.map((userProgress: any) => {
const remappedProgresses = userProgress.progresses.map((progress: IProgress) => {
// Hydrate and toObject are neccessary to transform all ObjectIds to strings
let unit = Unit.hydrate(progress.unit.pop()).toObject();
unit = {
...unit,
progressData: progress
};
return unit;
});
return {
...userProgress,
progresses: remappedProgresses
};
});
const studentsWithUnitsAndProgress = await students.map((student: IUser) => {
const studentWithUnits: any = student;
studentWithUnits.progress = {
units: []
};
const progressStats = {
nothing: 0,
tried: 0,
done: 0
};
const userProgressIndex = userProgressData.findIndex((userProgress: any) => {
return userProgress._id.toString() === student._id;
});
if (userProgressIndex > -1) {
const userProgressObjects = userProgressData[userProgressIndex];
studentWithUnits.progress.units = userProgressObjects.progresses;
userProgressData.splice(userProgressIndex, 1);
studentWithUnits.progress.units.forEach((studentUnit: IUnit) => {
if (studentUnit.hasOwnProperty('progressData')) {
if (studentUnit.progressData.done) {
progressStats.done++;
} else {
progressStats.tried++;
}
}
});
}
progressStats.nothing = progressableUnits.length - progressStats.done - progressStats.tried;
studentWithUnits.progress.stats = [
{
name: 'Progress',
series: [
{ name: 'nothing', value: progressStats.nothing },
{ name: 'tried', value: progressStats.tried },
{ name: 'done', value: progressStats.done }
]
},
];
return studentWithUnits;
});
return studentsWithUnitsAndProgress;
}
private createCoursePromise(courseId: string) {
return Course.findOne({_id: courseId})
.select({
name: 1,
lectures: 1,
students: 1
})
.populate({
path: 'lectures',
populate: {
path: 'units'
},
select: {
name: 1,
units: 1
}
})
.populate('students')
.populate('teachers')
.populate('courseAdmin')
.exec();
}
/**
* @api {get} /api/report/details/courses/:courseId/units/:unitId Request unit progress
* @apiName GetUnitDetails
* @apiGroup Report
* @apiPermission teacher
* @apiPermission admin
*
* @apiParam {String} courseId Course ID.
* @apiParam {String} unitId Unit ID.
* @apiParam {IUser} currentUser Currently logged in user.
*
* @apiSuccess {Object} report Unit and students with progress stats.
*
* @apiSuccessExample {json} Success-Response:
* "summary": {
* "_id": "5ab2b80a6fab4a3ae0cd672d",
* "updatedAt": "2018-03-21T19:56:13.326Z",
* "createdAt": "2018-03-21T19:52:42.716Z",
* "_course": "5a53c474a347af01b84e54b7",
* "progressable": true,
* "weight": 0,
* "name": "Progressable unit",
* "description": null,
* "deadline": "2018-03-21T22:59:00.000Z",
* "__v": 1,
* "__t": "task",
* "tasks": [...],
* "progressData": [{
* "name": "What's the answer to life and everything?",
* "series": [{
* "name": "correct",
* "value": 1
* }, {
* "name": "wrong",
* "value": 0
* }, {
* "name": "no data",
* "value": 5
* }]
* }, {
* "name": "How are you?",
* "series": [{
* "name": "correct",
* "value": 0
* }, {
* "name": "wrong",
* "value": 1
* }, {
* "name": "no data",
* "value": 5
* }]
* }, {
* "name": "Best questions ever, huh?",
* "series": [{
* "name": "correct",
* "value": 1
* }, {
* "name": "wrong",
* "value": 0
* }, {
* "name": "no data",
* "value": 5
* }]
* }]
* },
* "details": [{
* "_id": "5954bc9e23de070007fad033",
* "updatedAt": "2018-01-25T10:54:35.326Z",
* "createdAt": "2017-06-29T08:38:54.864Z",
* "email": "max@mustermann.me",
* "uid": "12345",
* "__v": 0,
* "isActive": true,
* "lastVisitedCourses": ["597df6d5b7a9c0000616637f", "5a5f3b70b5cbe70006f9befc", "59faf40c772e1300067d2ae6"],
* "role": "admin",
* "profile": {
* "theme": "default",
* "lastName": "Mustermann",
* "firstName": "Max"
* },
* "id": "5954bc9e23de070007fad033",
* "progress": {
* "_id": "5a69b7680146c60006249626",
* "done": false,
* "updatedAt": "2018-01-25T10:54:32.698Z",
* "createdAt": "2018-01-25T10:54:32.698Z",
* "unit": "5a460967302ddd0006331075",
* "course": "597df6d5b7a9c0000616637f",
* "answers": {
* "5a460967302ddd000633106e": {
* "5a460967302ddd0006331070": false,
* "5a460967302ddd000633106f": true
* },
* "5a460967302ddd0006331071": {
* "5a460967302ddd0006331074": false,
* "5a460967302ddd0006331073": false,
* "5a460967302ddd0006331072": true
* }
* },
* "type": "task-unit-progress",
* "user": "5954bc9e23de070007fad033",
* "__v": 0,
* "__t": "task-unit-progress"
* }
* }, {
* "_id": "5954c62923de070007fad047",
* "updatedAt": "2017-06-29T09:19:54.227Z",
* "createdAt": "2017-06-29T09:19:37.436Z",
* "email": "geli.hda@gmail.com",
* "uid": "744961",
* "__v": 0,
* "isActive": true,
* "lastVisitedCourses": [],
* "role": "student",
* "profile": {
* "lastName": "Gerhard Paule",
* "firstName": "Von Schröder"
* },
* "id": "5954c62923de070007fad047"
* }]
*
* @apiError ForbiddenError You are no admin or teacher for this course.
*/
@Get('/details/courses/:courseId/units/:unitId')
@Authorized(['teacher', 'admin'])
async getUnitProgress(@Param('courseId') courseId: string, @Param('unitId') unitId: string, @CurrentUser() currentUser: IUser) {
const coursePromise = Course.findOne({_id: courseId})
.select({ students: 1 })
.populate('students')
.exec();
const unitPromise = Unit.findOne({_id: unitId}).exec();
const progressPromise = Progress.find({'unit': unitId}).exec();
const [course, unit, progresses] = await Promise.all([coursePromise, unitPromise, progressPromise]);
this.checkAccess(course, currentUser);
const courseObj: ICourse = <ICourse>course.toObject();
const students = courseObj.students;
const progressObjects: IProgress[] = <IProgress[]>progresses.map((progress) => progress.toObject());
const unitObjWithProgressStats = await unit.calculateProgress(students, progressObjects);
const studentsWithProgress = students.map((student: IUser) => {
const studentWithProgress: IUser = student;
const progressIndex = progressObjects.findIndex((progressObj: any) => {
return progressObj.user === student._id;
});
if (progressIndex > -1) {
const progressObjForStudent = progressObjects[progressIndex];
studentWithProgress.progress = progressObjForStudent;
progressObjects.splice(progressIndex, 1);
}
return studentWithProgress;
});
const report = {
summary: unitObjWithProgressStats,
details: studentsWithProgress
};
return report;
}
/**
* @api {get} /api/report/overview/users/:id Request user overview
* @apiName GetUserOverview
* @apiGroup Report
*
* @apiParam {String} id User ID.
* @apiParam {IUser} currentUser Currently logged in user.
*
* @apiSuccess {Object[]} courses List of courses with progress stats.
*
* @apiSuccessExample {json} Success-Response:
* [{
* "_id": "5a134dcc104f7700067562c0",
* "name": "katacourse",
* "lectures": [{...}],
* "hasAccessKey": false,
* "progressData": [{
* "name": "nothing",
* "value": 1
* }, {
* "name": "tried",
* "value": 0
* }, {
* "name": "done",
* "value": 0
* }]
* }, {
* "_id": "5a1dc725a61d110008f0f69d",
* "name": "Am I hidden?",
* "lectures": [{...}, {...}],
* "hasAccessKey": false,
* "progressData": [{
* "name": "nothing",
* "value": 1
* }, {
* "name": "tried",
* "value": 1
* }, {
* "name": "done",
* "value": 1
* }]
* }, {
* "_id": "5a5f3b70b5cbe70006f9befc",
* "name": "Video-Test",
* "lectures": [{...}],
* "hasAccessKey": false,
* "progressData": [{
* "name": "nothing",
* "value": 0
* }, {
* "name": "tried",
* "value": 1
* }, {
* "name": "done",
* "value": 0
* }]
* }]
*
* @apiError ForbiddenError
*/
@Get('/overview/users/:id')
async getUserProgress(@Param('id') id: string, @CurrentUser() currentUser: IUser) {
if (id !== currentUser._id.toString()) {
throw new ForbiddenError();
}
const coursesPromise = Course.find({ students: new ObjectId(id) })
.select({
name: 1
})
.populate({
path: 'lectures',
populate: {
path: 'units'
},
select: {
name: 1,
units: 1
}
})
.exec();
const courses = await coursesPromise;
const courseObjects: any = courses.map((course: ICourseModel) => <ICourse>course.toObject());
const aggregatedProgressPromise = courseObjects
.map((courseObj: ICourse) => { return this.countUnitsAndRemoveEmptyLectures(courseObj, currentUser); })
.map(async ({courseObj, progressableUnitCount, invisibleUnits}: any) => {
const userProgressData = await Progress.aggregate([
{$match: { user: new ObjectId(id), unit: { $nin: invisibleUnits } }},
{$group: { _id: '$course', progresses: { $push: '$$ROOT' }}}
]).exec();
const progressStats = await this.calculateProgress(userProgressData, progressableUnitCount, courseObj);
courseObj.progressData = [
{ name: 'not tried', value: progressStats.nothing },
{ name: 'tried', value: progressStats.tried },
{ name: 'solved', value: progressStats.done }
];
return await courseObj;
});
const courseObjectsBeforeFilter = await Promise.all(aggregatedProgressPromise);
const courseObjectsWithProgress = await courseObjectsBeforeFilter.filter((courseObj: any) => {
return courseObj.lectures.length > 0;
});
return courseObjectsWithProgress;
}
private checkAccess(course: ICourse, user: IUser) {
let teacherIndex = -2;
if (course.teachers) {
teacherIndex = course.teachers.findIndex((teacher: any) => {
return teacher.toString() === user._id;
});
}
if (user.role !== 'admin' && course.courseAdmin._id.toString() !== user._id.toString() && teacherIndex < 0) {
throw new ForbiddenError('You are no admin or teacher for this course.');
}
}
private countUnitsAndRemoveEmptyLectures(courseObj: ICourse, currentUser: IUser) {
let progressableUnitCount = 0;
const invisibleUnits: ObjectId[] = [];
courseObj.lectures = courseObj.lectures.filter((lecture: ILecture) => {
lecture.units = lecture.units.filter((unit) => {
if (unit.visible === false && currentUser.role === 'student') {
invisibleUnits.push(new ObjectId(unit._id));
}
if (currentUser.role === 'student') {
return unit.progressable && unit.visible;
} else {
return unit.progressable;
}
});
progressableUnitCount += lecture.units.length;
return lecture.units.length > 0;
});
return {courseObj, progressableUnitCount, invisibleUnits};
}
private calculateProgress(progressData: any, totalCount: number, doc: any) {
const progressStats = {
nothing: 0,
tried: 0,
done: 0
};
const progressIndex = progressData.findIndex((progress: any) => {
return progress._id.toString() === doc._id.toString();
});
if (progressIndex > -1) {
const unitProgressObj = progressData[progressIndex];
unitProgressObj.progresses.forEach((progressObj: IProgress) => {
if (progressObj.done) {
progressStats.done++;
} else {
progressStats.tried++;
}
});
progressData.splice(progressIndex, 1);
}
progressStats.nothing = totalCount - progressStats.done - progressStats.tried;
return progressStats;
}
} | the_stack |
import React, { ClipboardEvent, createRef, KeyboardEvent } from 'react';
import EMOJI_REGEX from 'emojibase-regex';
import { IContent, MatrixEvent, IEventRelation } from 'matrix-js-sdk/src/models/event';
import { DebouncedFunc, throttle } from 'lodash';
import { EventType, RelationType } from "matrix-js-sdk/src/@types/event";
import { logger } from "matrix-js-sdk/src/logger";
import { Room } from 'matrix-js-sdk/src/models/room';
import dis from '../../../dispatcher/dispatcher';
import EditorModel from '../../../editor/model';
import {
containsEmote,
htmlSerializeIfNeeded,
startsWith,
stripEmoteCommand,
stripPrefix,
textSerialize,
unescapeMessage,
} from '../../../editor/serialize';
import BasicMessageComposer, { REGEX_EMOTICON } from "./BasicMessageComposer";
import { CommandPartCreator, Part, PartCreator, SerializedPart, Type } from '../../../editor/parts';
import ReplyChain from "../elements/ReplyChain";
import { findEditableEvent } from '../../../utils/EventUtils';
import SendHistoryManager from "../../../SendHistoryManager";
import { Command, CommandCategories, getCommand } from '../../../SlashCommands';
import Modal from '../../../Modal';
import { _t, _td } from '../../../languageHandler';
import ContentMessages from '../../../ContentMessages';
import { withMatrixClientHOC, MatrixClientProps } from "../../../contexts/MatrixClientContext";
import { Action } from "../../../dispatcher/actions";
import { containsEmoji } from "../../../effects/utils";
import { CHAT_EFFECTS } from '../../../effects';
import CountlyAnalytics from "../../../CountlyAnalytics";
import { MatrixClientPeg } from "../../../MatrixClientPeg";
import { getKeyBindingsManager, MessageComposerAction } from '../../../KeyBindingsManager';
import { replaceableComponent } from "../../../utils/replaceableComponent";
import SettingsStore from '../../../settings/SettingsStore';
import { RoomPermalinkCreator } from "../../../utils/permalinks/Permalinks";
import ErrorDialog from "../dialogs/ErrorDialog";
import QuestionDialog from "../dialogs/QuestionDialog";
import { ActionPayload } from "../../../dispatcher/payloads";
import { decorateStartSendingTime, sendRoundTripMetric } from "../../../sendTimePerformanceMetrics";
import RoomContext, { TimelineRenderingType } from '../../../contexts/RoomContext';
import DocumentPosition from "../../../editor/position";
import { ComposerType } from "../../../dispatcher/payloads/ComposerInsertPayload";
function addReplyToMessageContent(
content: IContent,
replyToEvent: MatrixEvent,
permalinkCreator: RoomPermalinkCreator,
): void {
const replyContent = ReplyChain.makeReplyMixIn(replyToEvent);
Object.assign(content, replyContent);
// Part of Replies fallback support - prepend the text we're sending
// with the text we're replying to
const nestedReply = ReplyChain.getNestedReplyText(replyToEvent, permalinkCreator);
if (nestedReply) {
if (content.formatted_body) {
content.formatted_body = nestedReply.html + content.formatted_body;
}
content.body = nestedReply.body + content.body;
}
}
export function attachRelation(
content: IContent,
relation?: IEventRelation,
): void {
if (relation) {
content['m.relates_to'] = {
...relation, // the composer can have a default
...content['m.relates_to'],
};
}
}
// exported for tests
export function createMessageContent(
model: EditorModel,
replyToEvent: MatrixEvent,
relation: IEventRelation,
permalinkCreator: RoomPermalinkCreator,
): IContent {
const isEmote = containsEmote(model);
if (isEmote) {
model = stripEmoteCommand(model);
}
if (startsWith(model, "//")) {
model = stripPrefix(model, "/");
}
model = unescapeMessage(model);
const body = textSerialize(model);
const content: IContent = {
msgtype: isEmote ? "m.emote" : "m.text",
body: body,
};
const formattedBody = htmlSerializeIfNeeded(model, { forceHTML: !!replyToEvent });
if (formattedBody) {
content.format = "org.matrix.custom.html";
content.formatted_body = formattedBody;
}
if (replyToEvent) {
addReplyToMessageContent(content, replyToEvent, permalinkCreator);
}
if (relation) {
content['m.relates_to'] = {
...relation,
...content['m.relates_to'],
};
}
return content;
}
// exported for tests
export function isQuickReaction(model: EditorModel): boolean {
const parts = model.parts;
if (parts.length == 0) return false;
const text = textSerialize(model);
// shortcut takes the form "+:emoji:" or "+ :emoji:""
// can be in 1 or 2 parts
if (parts.length <= 2) {
const hasShortcut = text.startsWith("+") || text.startsWith("+ ");
const emojiMatch = text.match(EMOJI_REGEX);
if (hasShortcut && emojiMatch && emojiMatch.length == 1) {
return emojiMatch[0] === text.substring(1) ||
emojiMatch[0] === text.substring(2);
}
}
return false;
}
interface ISendMessageComposerProps extends MatrixClientProps {
room: Room;
placeholder?: string;
permalinkCreator: RoomPermalinkCreator;
relation?: IEventRelation;
replyToEvent?: MatrixEvent;
disabled?: boolean;
onChange?(model: EditorModel): void;
}
@replaceableComponent("views.rooms.SendMessageComposer")
export class SendMessageComposer extends React.Component<ISendMessageComposerProps> {
static contextType = RoomContext;
public context!: React.ContextType<typeof RoomContext>;
private readonly prepareToEncrypt?: DebouncedFunc<() => void>;
private readonly editorRef = createRef<BasicMessageComposer>();
private model: EditorModel = null;
private currentlyComposedEditorState: SerializedPart[] = null;
private dispatcherRef: string;
private sendHistoryManager: SendHistoryManager;
constructor(props: ISendMessageComposerProps, context: React.ContextType<typeof RoomContext>) {
super(props);
if (this.props.mxClient.isCryptoEnabled() && this.props.mxClient.isRoomEncrypted(this.props.room.roomId)) {
this.prepareToEncrypt = throttle(() => {
this.props.mxClient.prepareToEncrypt(this.props.room);
}, 60000, { leading: true, trailing: false });
}
window.addEventListener("beforeunload", this.saveStoredEditorState);
}
public componentDidUpdate(prevProps: ISendMessageComposerProps): void {
const replyingToThread = this.props.relation?.key === RelationType.Thread;
const differentEventTarget = this.props.relation?.event_id !== prevProps.relation?.event_id;
const threadChanged = replyingToThread && (differentEventTarget);
if (threadChanged) {
const partCreator = new CommandPartCreator(this.props.room, this.props.mxClient);
const parts = this.restoreStoredEditorState(partCreator) || [];
this.model.reset(parts);
this.editorRef.current?.focus();
}
}
private onKeyDown = (event: KeyboardEvent): void => {
// ignore any keypress while doing IME compositions
if (this.editorRef.current?.isComposing(event)) {
return;
}
const replyingToThread = this.props.relation?.key === RelationType.Thread;
const action = getKeyBindingsManager().getMessageComposerAction(event);
switch (action) {
case MessageComposerAction.Send:
this.sendMessage();
event.preventDefault();
break;
case MessageComposerAction.SelectPrevSendHistory:
case MessageComposerAction.SelectNextSendHistory: {
// Try select composer history
const selected = this.selectSendHistory(action === MessageComposerAction.SelectPrevSendHistory);
if (selected) {
// We're selecting history, so prevent the key event from doing anything else
event.preventDefault();
}
break;
}
case MessageComposerAction.EditPrevMessage:
// selection must be collapsed and caret at start
if (this.editorRef.current?.isSelectionCollapsed() && this.editorRef.current?.isCaretAtStart()) {
const events =
this.context.liveTimeline.getEvents()
.concat(replyingToThread ? [] : this.props.room.getPendingEvents());
const editEvent = findEditableEvent({
events,
isForward: false,
});
if (editEvent) {
// We're selecting history, so prevent the key event from doing anything else
event.preventDefault();
dis.dispatch({
action: Action.EditEvent,
event: editEvent,
timelineRenderingType: this.context.timelineRenderingType,
});
}
}
break;
case MessageComposerAction.CancelEditing:
dis.dispatch({
action: 'reply_to_event',
event: null,
context: this.context.timelineRenderingType,
});
break;
default:
if (this.prepareToEncrypt) {
// This needs to be last!
this.prepareToEncrypt();
}
}
};
// we keep sent messages/commands in a separate history (separate from undo history)
// so you can alt+up/down in them
private selectSendHistory(up: boolean): boolean {
const delta = up ? -1 : 1;
// True if we are not currently selecting history, but composing a message
if (this.sendHistoryManager.currentIndex === this.sendHistoryManager.history.length) {
// We can't go any further - there isn't any more history, so nop.
if (!up) {
return false;
}
this.currentlyComposedEditorState = this.model.serializeParts();
} else if (this.sendHistoryManager.currentIndex + delta === this.sendHistoryManager.history.length) {
// True when we return to the message being composed currently
this.model.reset(this.currentlyComposedEditorState);
this.sendHistoryManager.currentIndex = this.sendHistoryManager.history.length;
return true;
}
const { parts, replyEventId } = this.sendHistoryManager.getItem(delta);
dis.dispatch({
action: 'reply_to_event',
event: replyEventId ? this.props.room.findEventById(replyEventId) : null,
context: this.context.timelineRenderingType,
});
if (parts) {
this.model.reset(parts);
this.editorRef.current?.focus();
}
return true;
}
private isSlashCommand(): boolean {
const parts = this.model.parts;
const firstPart = parts[0];
if (firstPart) {
if (firstPart.type === Type.Command && firstPart.text.startsWith("/") && !firstPart.text.startsWith("//")) {
return true;
}
// be extra resilient when somehow the AutocompleteWrapperModel or
// CommandPartCreator fails to insert a command part, so we don't send
// a command as a message
if (firstPart.text.startsWith("/") && !firstPart.text.startsWith("//")
&& (firstPart.type === Type.Plain || firstPart.type === Type.PillCandidate)) {
return true;
}
}
return false;
}
private sendQuickReaction(): void {
const timeline = this.context.liveTimeline;
const events = timeline.getEvents();
const reaction = this.model.parts[1].text;
for (let i = events.length - 1; i >= 0; i--) {
if (events[i].getType() === EventType.RoomMessage) {
let shouldReact = true;
const lastMessage = events[i];
const userId = MatrixClientPeg.get().getUserId();
const messageReactions = this.props.room.getUnfilteredTimelineSet()
.getRelationsForEvent(lastMessage.getId(), RelationType.Annotation, EventType.Reaction);
// if we have already sent this reaction, don't redact but don't re-send
if (messageReactions) {
const myReactionEvents = messageReactions.getAnnotationsBySender()[userId] || [];
const myReactionKeys = [...myReactionEvents]
.filter(event => !event.isRedacted())
.map(event => event.getRelation().key);
shouldReact = !myReactionKeys.includes(reaction);
}
if (shouldReact) {
MatrixClientPeg.get().sendEvent(lastMessage.getRoomId(), EventType.Reaction, {
"m.relates_to": {
"rel_type": RelationType.Annotation,
"event_id": lastMessage.getId(),
"key": reaction,
},
});
dis.dispatch({ action: "message_sent" });
}
break;
}
}
}
private getSlashCommand(): [Command, string, string] {
const commandText = this.model.parts.reduce((text, part) => {
// use mxid to textify user pills in a command
if (part.type === "user-pill") {
return text + part.resourceId;
}
return text + part.text;
}, "");
const { cmd, args } = getCommand(commandText);
return [cmd, args, commandText];
}
private async runSlashCommand(cmd: Command, args: string): Promise<void> {
const threadId = this.props.relation?.rel_type === RelationType.Thread
? this.props.relation?.event_id
: null;
const result = cmd.run(this.props.room.roomId, threadId, args);
let messageContent;
let error = result.error;
if (result.promise) {
try {
if (cmd.category === CommandCategories.messages) {
// The command returns a modified message that we need to pass on
messageContent = await result.promise;
} else {
await result.promise;
}
} catch (err) {
error = err;
}
}
if (error) {
logger.error("Command failure: %s", error);
// assume the error is a server error when the command is async
const isServerError = !!result.promise;
const title = isServerError ? _td("Server error") : _td("Command error");
let errText;
if (typeof error === 'string') {
errText = error;
} else if (error.message) {
errText = error.message;
} else {
errText = _t("Server unavailable, overloaded, or something else went wrong.");
}
Modal.createTrackedDialog(title, '', ErrorDialog, {
title: _t(title),
description: errText,
});
} else {
logger.log("Command success.");
if (messageContent) return messageContent;
}
}
public async sendMessage(): Promise<void> {
const model = this.model;
if (model.isEmpty) {
return;
}
// Replace emoticon at the end of the message
if (SettingsStore.getValue('MessageComposerInput.autoReplaceEmoji')) {
const indexOfLastPart = model.parts.length - 1;
const positionInLastPart = model.parts[indexOfLastPart].text.length;
this.editorRef.current?.replaceEmoticon(
new DocumentPosition(indexOfLastPart, positionInLastPart),
REGEX_EMOTICON,
);
}
const replyToEvent = this.props.replyToEvent;
let shouldSend = true;
let content;
if (!containsEmote(model) && this.isSlashCommand()) {
const [cmd, args, commandText] = this.getSlashCommand();
if (cmd) {
if (cmd.category === CommandCategories.messages) {
content = await this.runSlashCommand(cmd, args);
if (replyToEvent) {
addReplyToMessageContent(
content,
replyToEvent,
this.props.permalinkCreator,
);
}
attachRelation(content, this.props.relation);
} else {
this.runSlashCommand(cmd, args);
shouldSend = false;
}
} else {
// ask the user if their unknown command should be sent as a message
const { finished } = Modal.createTrackedDialog("Unknown command", "", QuestionDialog, {
title: _t("Unknown Command"),
description: <div>
<p>
{ _t("Unrecognised command: %(commandText)s", { commandText }) }
</p>
<p>
{ _t("You can use <code>/help</code> to list available commands. " +
"Did you mean to send this as a message?", {}, {
code: t => <code>{ t }</code>,
}) }
</p>
<p>
{ _t("Hint: Begin your message with <code>//</code> to start it with a slash.", {}, {
code: t => <code>{ t }</code>,
}) }
</p>
</div>,
button: _t('Send as message'),
});
const [sendAnyway] = await finished;
// if !sendAnyway bail to let the user edit the composer and try again
if (!sendAnyway) return;
}
}
if (isQuickReaction(model)) {
shouldSend = false;
this.sendQuickReaction();
}
if (shouldSend) {
const startTime = CountlyAnalytics.getTimestamp();
const { roomId } = this.props.room;
if (!content) {
content = createMessageContent(
model,
replyToEvent,
this.props.relation,
this.props.permalinkCreator,
);
}
// don't bother sending an empty message
if (!content.body.trim()) return;
if (SettingsStore.getValue("Performance.addSendMessageTimingMetadata")) {
decorateStartSendingTime(content);
}
const threadId = this.props.relation?.rel_type === RelationType.Thread
? this.props.relation.event_id
: null;
const prom = this.props.mxClient.sendMessage(roomId, threadId, content);
if (replyToEvent) {
// Clear reply_to_event as we put the message into the queue
// if the send fails, retry will handle resending.
dis.dispatch({
action: 'reply_to_event',
event: null,
context: this.context.timelineRenderingType,
});
}
dis.dispatch({ action: "message_sent" });
CHAT_EFFECTS.forEach((effect) => {
if (containsEmoji(content, effect.emojis)) {
// For initial threads launch, chat effects are disabled
// see #19731
const isNotThread = this.props.relation?.rel_type !== RelationType.Thread;
if (!SettingsStore.getValue("feature_thread") || isNotThread) {
dis.dispatch({ action: `effects.${effect.command}` });
}
}
});
if (SettingsStore.getValue("Performance.addSendMessageTimingMetadata")) {
prom.then(resp => {
sendRoundTripMetric(this.props.mxClient, roomId, resp.event_id);
});
}
CountlyAnalytics.instance.trackSendMessage(startTime, prom, roomId, false, !!replyToEvent, content);
}
this.sendHistoryManager.save(model, replyToEvent);
// clear composer
model.reset([]);
this.editorRef.current?.clearUndoHistory();
this.editorRef.current?.focus();
this.clearStoredEditorState();
if (SettingsStore.getValue("scrollToBottomOnMessageSent")) {
dis.dispatch({
action: "scroll_to_bottom",
timelineRenderingType: this.context.timelineRenderingType,
});
}
}
componentWillUnmount() {
dis.unregister(this.dispatcherRef);
window.removeEventListener("beforeunload", this.saveStoredEditorState);
this.saveStoredEditorState();
}
// TODO: [REACT-WARNING] Move this to constructor
UNSAFE_componentWillMount() { // eslint-disable-line
const partCreator = new CommandPartCreator(this.props.room, this.props.mxClient);
const parts = this.restoreStoredEditorState(partCreator) || [];
this.model = new EditorModel(parts, partCreator);
this.dispatcherRef = dis.register(this.onAction);
this.sendHistoryManager = new SendHistoryManager(this.props.room.roomId, 'mx_cider_history_');
}
private get editorStateKey() {
let key = `mx_cider_state_${this.props.room.roomId}`;
const thread = this.props.replyToEvent?.getThread();
if (thread) {
key += `_${thread.id}`;
}
return key;
}
private clearStoredEditorState(): void {
localStorage.removeItem(this.editorStateKey);
}
private restoreStoredEditorState(partCreator: PartCreator): Part[] {
const replyingToThread = this.props.relation?.key === RelationType.Thread;
if (replyingToThread) {
return null;
}
const json = localStorage.getItem(this.editorStateKey);
if (json) {
try {
const { parts: serializedParts, replyEventId } = JSON.parse(json);
const parts: Part[] = serializedParts.map(p => partCreator.deserializePart(p));
if (replyEventId) {
dis.dispatch({
action: 'reply_to_event',
event: this.props.room.findEventById(replyEventId),
context: this.context.timelineRenderingType,
});
}
return parts;
} catch (e) {
logger.error(e);
}
}
}
// should save state when editor has contents or reply is open
private shouldSaveStoredEditorState = (): boolean => {
return !this.model.isEmpty || !!this.props.replyToEvent;
};
private saveStoredEditorState = (): void => {
if (this.shouldSaveStoredEditorState()) {
const item = SendHistoryManager.createItem(this.model, this.props.replyToEvent);
localStorage.setItem(this.editorStateKey, JSON.stringify(item));
} else {
this.clearStoredEditorState();
}
};
private onAction = (payload: ActionPayload): void => {
// don't let the user into the composer if it is disabled - all of these branches lead
// to the cursor being in the composer
if (this.props.disabled) return;
switch (payload.action) {
case 'reply_to_event':
case Action.FocusSendMessageComposer:
if ((payload.context ?? TimelineRenderingType.Room) === this.context.timelineRenderingType) {
this.editorRef.current?.focus();
}
break;
case Action.ComposerInsert:
if (payload.timelineRenderingType !== this.context.timelineRenderingType) break;
if (payload.composerType !== ComposerType.Send) break;
if (payload.userId) {
this.editorRef.current?.insertMention(payload.userId);
} else if (payload.event) {
this.editorRef.current?.insertQuotedMessage(payload.event);
} else if (payload.text) {
this.editorRef.current?.insertPlaintext(payload.text);
}
break;
}
};
private onPaste = (event: ClipboardEvent<HTMLDivElement>): boolean => {
const { clipboardData } = event;
// Prioritize text on the clipboard over files if RTF is present as Office on macOS puts a bitmap
// in the clipboard as well as the content being copied. Modern versions of Office seem to not do this anymore.
// We check text/rtf instead of text/plain as when copy+pasting a file from Finder or Gnome Image Viewer
// it puts the filename in as text/plain which we want to ignore.
if (clipboardData.files.length && !clipboardData.types.includes("text/rtf")) {
ContentMessages.sharedInstance().sendContentListToRoom(
Array.from(clipboardData.files), this.props.room.roomId, this.props.relation, this.props.mxClient,
);
return true; // to skip internal onPaste handler
}
};
private onChange = (): void => {
if (this.props.onChange) this.props.onChange(this.model);
};
private focusComposer = (): void => {
this.editorRef.current?.focus();
};
render() {
const threadId = this.props.relation?.rel_type === RelationType.Thread
? this.props.relation.event_id
: null;
return (
<div className="mx_SendMessageComposer" onClick={this.focusComposer} onKeyDown={this.onKeyDown}>
<BasicMessageComposer
onChange={this.onChange}
ref={this.editorRef}
model={this.model}
room={this.props.room}
threadId={threadId}
label={this.props.placeholder}
placeholder={this.props.placeholder}
onPaste={this.onPaste}
disabled={this.props.disabled}
/>
</div>
);
}
}
const SendMessageComposerWithMatrixClient = withMatrixClientHOC(SendMessageComposer);
export default SendMessageComposerWithMatrixClient; | the_stack |
import {
bench,
BenchmarkRunError,
BenchmarkRunProgress,
clearBenchmarks,
ProgressState,
runBenchmarks,
} from "./bench.ts";
import {
assert,
assertEquals,
assertRejects,
assertThrows,
} from "./asserts.ts";
Deno.test({
name: "benching",
fn: async function () {
bench(function forIncrementX1e3(b): void {
b.start();
for (let i = 0; i < 1e3; i++);
b.stop();
});
bench(function forDecrementX1e3(b): void {
b.start();
for (let i = 1e3; i > 0; i--);
b.stop();
});
bench(async function forAwaitFetchDenolandX10(b) {
b.start();
for (let i = 0; i < 10; i++) {
const r = await fetch("https://deno.land/");
await r.text();
}
b.stop();
});
bench(async function promiseAllFetchDenolandX10(b) {
const urls = new Array(10).fill("https://deno.land/");
b.start();
await Promise.all(
urls.map(
async (denoland: string) => {
const r = await fetch(denoland);
await r.text();
},
),
);
b.stop();
});
bench({
name: "runs100ForIncrementX1e6",
runs: 100,
func(b): void {
b.start();
for (let i = 0; i < 1e6; i++);
b.stop();
},
});
bench(function throwing(b): void {
b.start();
// Throws bc the timer's stop method is never called
});
const benchResult = await runBenchmarks({ skip: /throw/ });
assertEquals(benchResult.filtered, 1);
assertEquals(benchResult.results.length, 5);
const resultWithSingleRunsFiltered = benchResult.results.filter(
({ name }) => name === "forDecrementX1e3",
);
assertEquals(resultWithSingleRunsFiltered.length, 1);
const resultWithSingleRuns = resultWithSingleRunsFiltered[0];
assert(!!resultWithSingleRuns.runsCount);
assert(!!resultWithSingleRuns.measuredRunsAvgMs);
assert(!!resultWithSingleRuns.measuredRunsMs);
assertEquals(resultWithSingleRuns.runsCount, 1);
assertEquals(resultWithSingleRuns.measuredRunsMs.length, 1);
const resultWithMultipleRunsFiltered = benchResult.results.filter(
({ name }) => name === "runs100ForIncrementX1e6",
);
assertEquals(resultWithMultipleRunsFiltered.length, 1);
const resultWithMultipleRuns = resultWithMultipleRunsFiltered[0];
assert(!!resultWithMultipleRuns.runsCount);
assert(!!resultWithMultipleRuns.measuredRunsAvgMs);
assert(!!resultWithMultipleRuns.measuredRunsMs);
assertEquals(resultWithMultipleRuns.runsCount, 100);
assertEquals(resultWithMultipleRuns.measuredRunsMs.length, 100);
clearBenchmarks();
},
});
Deno.test({
name: "Bench without name should throw",
fn() {
assertThrows(
(): void => {
bench(() => {});
},
Error,
"The benchmark function must not be anonymous",
);
},
});
Deno.test({
name: "Bench without stop should throw",
fn: async function () {
await assertRejects(
async () => {
bench(function benchWithoutStop(b): void {
b.start();
// Throws bc the timer's stop method is never called
});
await runBenchmarks({ only: /benchWithoutStop/, silent: true });
},
BenchmarkRunError,
"The benchmark timer's stop method must be called",
);
},
});
Deno.test({
name: "Bench without start should throw",
fn: async function () {
await assertRejects(
async () => {
bench(function benchWithoutStart(b): void {
b.stop();
// Throws bc the timer's start method is never called
});
await runBenchmarks({ only: /benchWithoutStart/, silent: true });
},
BenchmarkRunError,
"The benchmark timer's start method must be called",
);
},
});
Deno.test({
name: "Bench with stop before start should throw",
fn: async function () {
await assertRejects(
async () => {
bench(function benchStopBeforeStart(b): void {
b.stop();
b.start();
// Throws bc the timer's stop is called before start
});
await runBenchmarks({ only: /benchStopBeforeStart/, silent: true });
},
BenchmarkRunError,
"The benchmark timer's start method must be called before its stop method",
);
},
});
Deno.test({
name: "clearBenchmarks should clear all candidates",
fn: async function () {
dummyBench("test");
clearBenchmarks();
const benchingResults = await runBenchmarks({ silent: true });
assertEquals(benchingResults.filtered, 0);
assertEquals(benchingResults.results.length, 0);
},
});
Deno.test({
name: "clearBenchmarks with only as option",
fn: async function () {
// to reset candidates
clearBenchmarks();
dummyBench("test");
dummyBench("onlyclear");
clearBenchmarks({ only: /only/ });
const benchingResults = await runBenchmarks({ silent: true });
assertEquals(benchingResults.filtered, 0);
assertEquals(benchingResults.results.length, 1);
assertEquals(benchingResults.results[0].name, "test");
},
});
Deno.test({
name: "clearBenchmarks with skip as option",
fn: async function () {
// to reset candidates
clearBenchmarks();
dummyBench("test");
dummyBench("skipclear");
clearBenchmarks({ skip: /skip/ });
const benchingResults = await runBenchmarks({ silent: true });
assertEquals(benchingResults.filtered, 0);
assertEquals(benchingResults.results.length, 1);
assertEquals(benchingResults.results[0].name, "skipclear");
},
});
Deno.test({
name: "clearBenchmarks with only and skip as option",
fn: async function () {
// to reset candidates
clearBenchmarks();
dummyBench("test");
dummyBench("clearonly");
dummyBench("clearskip");
dummyBench("clearonly");
clearBenchmarks({ only: /clear/, skip: /skip/ });
const benchingResults = await runBenchmarks({ silent: true });
assertEquals(benchingResults.filtered, 0);
assertEquals(benchingResults.results.length, 2);
assert(!!benchingResults.results.find(({ name }) => name === "test"));
assert(!!benchingResults.results.find(({ name }) => name === "clearskip"));
},
});
Deno.test({
name: "progressCallback of runBenchmarks",
fn: async function () {
clearBenchmarks();
dummyBench("skip");
dummyBench("single");
dummyBench("multiple", 2);
const progressCallbacks: BenchmarkRunProgress[] = [];
const benchingResults = await runBenchmarks(
{ skip: /skip/, silent: true },
(progress) => {
progressCallbacks.push(progress);
},
);
let pc = 0;
// Assert initial progress before running
let progress = progressCallbacks[pc++];
assert(progress.queued);
assertEquals(progress.state, ProgressState.BenchmarkingStart);
assertEquals(progress.filtered, 1);
assertEquals(progress.queued.length, 2);
assertEquals(progress.running, undefined);
assertEquals(progress.results, []);
// Assert start of bench "single"
progress = progressCallbacks[pc++];
assertEquals(progress.state, ProgressState.BenchStart);
assertEquals(progress.filtered, 1);
assert(progress.queued);
assertEquals(progress.queued.length, 1);
assert(!!progress.queued.find(({ name }) => name == "multiple"));
assertEquals(progress.running, {
name: "single",
runsCount: 1,
measuredRunsMs: [],
});
assertEquals(progress.results, []);
// Assert running result of bench "single"
progress = progressCallbacks[pc++];
assertEquals(progress.state, ProgressState.BenchPartialResult);
assert(progress.queued);
assertEquals(progress.queued.length, 1);
assertEquals(progress.running!.measuredRunsMs.length, 1);
assertEquals(progress.results.length, 0);
// Assert result of bench "single"
progress = progressCallbacks[pc++];
assertEquals(progress.state, ProgressState.BenchResult);
assert(progress.queued);
assertEquals(progress.queued.length, 1);
assertEquals(progress.running, undefined);
assertEquals(progress.results.length, 1);
assert(!!progress.results.find(({ name }) => name == "single"));
// Assert start of bench "multiple"
progress = progressCallbacks[pc++];
assertEquals(progress.state, ProgressState.BenchStart);
assert(progress.queued);
assertEquals(progress.queued.length, 0);
assertEquals(progress.running, {
name: "multiple",
runsCount: 2,
measuredRunsMs: [],
});
assertEquals(progress.results.length, 1);
// Assert first result of bench "multiple"
progress = progressCallbacks[pc++];
assertEquals(progress.state, ProgressState.BenchPartialResult);
assert(progress.queued);
assertEquals(progress.queued.length, 0);
assertEquals(progress.running!.measuredRunsMs.length, 1);
assertEquals(progress.results.length, 1);
// Assert second result of bench "multiple"
progress = progressCallbacks[pc++];
assertEquals(progress.state, ProgressState.BenchPartialResult);
assert(progress.queued);
assertEquals(progress.queued.length, 0);
assertEquals(progress.running!.measuredRunsMs.length, 2);
assertEquals(progress.results.length, 1);
// Assert finish of bench "multiple"
progress = progressCallbacks[pc++];
assertEquals(progress.state, ProgressState.BenchResult);
assert(progress.queued);
assertEquals(progress.queued.length, 0);
assertEquals(progress.running, undefined);
assertEquals(progress.results.length, 2);
assert(!!progress.results.find(({ name }) => name == "single"));
const resultOfMultiple = progress.results.filter(
({ name }) => name == "multiple",
);
assertEquals(resultOfMultiple.length, 1);
assert(!!resultOfMultiple[0].measuredRunsMs);
assert(!isNaN(resultOfMultiple[0].measuredRunsAvgMs));
assertEquals(resultOfMultiple[0].measuredRunsMs.length, 2);
// The last progress should equal the final result from promise except the state property
progress = progressCallbacks[pc++];
assertEquals(progress.state, ProgressState.BenchmarkingEnd);
delete progress.state;
assertEquals(progress, benchingResults);
},
});
Deno.test({
name: "async progressCallback",
fn: async function () {
clearBenchmarks();
dummyBench("single");
const asyncCallbacks = [];
await runBenchmarks({ silent: true }, (progress) => {
return new Promise((resolve) => {
queueMicrotask(() => {
asyncCallbacks.push(progress);
resolve();
});
});
});
assertEquals(asyncCallbacks.length, 5);
},
});
function dummyBench(name: string, runs = 1): void {
bench({
name,
runs,
func(b) {
b.start();
b.stop();
},
});
} | the_stack |
import { FocusMonitor } from '@angular/cdk/a11y';
import { coerceBooleanProperty } from '@angular/cdk/coercion';
import { SelectionModel } from '@angular/cdk/collections';
import {
AfterContentInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChildren,
Directive,
ElementRef,
EventEmitter,
forwardRef,
Input,
OnDestroy,
OnInit,
Optional,
Output,
QueryList,
ViewChild,
ViewEncapsulation,
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
let _uniqueIdCounter = 0;
export const BUTTON_TOGGLE_GROUP_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => ButtonToggleGroupDirective),
multi: true,
};
export class ButtonToggleChange {
constructor(
public source: ButtonToggleComponent,
public value: any,
) {
}
}
@Directive({
selector: 'gd-button-toggle-group',
providers: [
BUTTON_TOGGLE_GROUP_VALUE_ACCESSOR,
],
host: {
'class': 'ButtonToggleGroup',
'[class.ButtonToggleGroup--vertical]': '_vertical',
'role': 'group',
},
})
export class ButtonToggleGroupDirective implements ControlValueAccessor, OnInit, AfterContentInit {
_controlValueAccessorChangeFn: (value: any) => void = () => {};
/** onTouch function registered via registerOnTouch (ControlValueAccessor). */
_onTouched: () => any = () => {};
/** Child button toggle buttons. */
@ContentChildren(forwardRef(() => ButtonToggleComponent))
_buttonToggles: QueryList<ButtonToggleComponent>;
@Input() disabled: boolean;
@Output() readonly valueChange = new EventEmitter<any>();
/** Event emitted when the group's value changes. */
@Output() readonly change: EventEmitter<ButtonToggleChange> = new EventEmitter<ButtonToggleChange>();
private _selectionModel: SelectionModel<ButtonToggleComponent>;
private _rawValue: any;
constructor(private _changeDetector: ChangeDetectorRef) {
}
private _vertical = false;
/** Whether the toggle group is vertical. */
@Input()
get vertical(): boolean {
return this._vertical;
}
set vertical(value: boolean) {
this._vertical = coerceBooleanProperty(value);
}
private _multiple = false;
/** Whether multiple button toggles can be selected. */
@Input()
get multiple(): boolean {
return this._multiple;
}
set multiple(value: boolean) {
this._multiple = coerceBooleanProperty(value);
}
private _name = `gd-button-toggle-group-${_uniqueIdCounter++}`;
/** `name` attribute for the underlying `input` element. */
@Input()
get name(): string {
return this._name;
}
set name(value: string) {
this._name = value;
if (this._buttonToggles) {
this._buttonToggles.forEach(toggle => toggle.name = this._name);
}
}
/** Value of the toggle group. */
@Input()
get value(): any {
const selected = this._selectionModel ? this._selectionModel.selected : [];
if (this.multiple) {
return selected.map(toggle => toggle.value);
}
return selected[0] ? selected[0].value : undefined;
}
set value(newValue: any) {
this._setSelectionByValue(newValue);
this.valueChange.emit(this.value);
}
/** Selected button toggles in the group. */
get selected() {
const selected = this._selectionModel.selected;
return this.multiple ? selected : (selected[0] || null);
}
ngOnInit(): void {
this._selectionModel = new SelectionModel<ButtonToggleComponent>(
this.multiple, undefined, false);
}
ngAfterContentInit(): void {
this._selectionModel.select(...this._buttonToggles.filter(toggle => toggle.checked));
}
/**
* Sets the model value. Implemented as part of ControlValueAccessor.
* @param value Value to be set to the model.
*/
writeValue(value: any): void {
this.value = value;
this._changeDetector.markForCheck();
}
// Implemented as part of ControlValueAccessor.
registerOnChange(fn: (value: any) => void): void {
this._controlValueAccessorChangeFn = fn;
}
// Implemented as part of ControlValueAccessor.
registerOnTouched(fn: any): void {
this._onTouched = fn;
}
// Implemented as part of ControlValueAccessor.
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
if (this._buttonToggles) {
this._buttonToggles.forEach(toggle => toggle._markForCheck());
}
}
/** Dispatch change event with current selection and group value. */
_emitChangeEvent(): void {
const selected = this.selected;
const source = Array.isArray(selected) ? selected[selected.length - 1] : selected;
const event = new ButtonToggleChange(source, this.value);
this._controlValueAccessorChangeFn(event.value);
this.change.emit(event);
}
/**
* Syncs a button toggle's selected state with the model value.
* @param toggle Toggle to be synced.
* @param select Whether the toggle should be selected.
* @param isUserInput Whether the change was a result of a user interaction.
*/
_syncButtonToggle(toggle: ButtonToggleComponent, select: boolean, isUserInput = false): void {
// Deselect the currently-selected toggle, if we're in single-selection
// mode and the button being toggled isn't selected at the moment.
if (!this.multiple && this.selected && !toggle.checked) {
(this.selected as ButtonToggleComponent).checked = false;
}
if (select) {
this._selectionModel.select(toggle);
} else {
this._selectionModel.deselect(toggle);
}
// Only emit the change event for user input.
if (isUserInput) {
this._emitChangeEvent();
}
// Note: we emit this one no matter whether it was a user interaction, because
// it is used by Angular to sync up the two-way data binding.
this.valueChange.emit(this.value);
}
/** Checks whether a button toggle is selected. */
_isSelected(toggle: ButtonToggleComponent): boolean {
return this._selectionModel.isSelected(toggle);
}
/** Determines whether a button toggle should be checked on init. */
_isPrechecked(toggle: ButtonToggleComponent): boolean {
if (typeof this._rawValue === 'undefined') {
return false;
}
if (this.multiple && Array.isArray(this._rawValue)) {
return this._rawValue.some(value => toggle.value != null && value === toggle.value);
}
return toggle.value === this._rawValue;
}
/** Updates the selection state of the toggles in the group based on a value. */
private _setSelectionByValue(value: any | any[]): void {
this._rawValue = value;
if (!this._buttonToggles) {
return;
}
if (this.multiple && value) {
if (!Array.isArray(value)) {
throw Error('Value must be an array in multiple-selection mode.');
}
this._clearSelection();
value.forEach((currentValue: any) => this._selectValue(currentValue));
} else {
this._clearSelection();
this._selectValue(value);
}
}
/** Clears the selected toggles. */
private _clearSelection(): void {
this._selectionModel.clear();
this._buttonToggles.forEach(toggle => toggle.checked = false);
}
/** Selects a value if there's a toggle that corresponds to it. */
private _selectValue(value: any): void {
const correspondingOption = this._buttonToggles.find(toggle => {
return toggle.value != null && toggle.value === value;
});
if (correspondingOption) {
correspondingOption.checked = true;
this._selectionModel.select(correspondingOption);
}
}
}
@Component({
selector: 'gd-button-toggle',
templateUrl: './button-toggle.html',
styleUrls: ['./button-toggle.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
host: {
'class': 'ButtonToggle',
'[class.ButtonToggle--standalone]': '!buttonToggleGroup',
'[class.ButtonToggle--checked]': 'checked',
'[class.ButtonToggle--disabled]': 'disabled',
'[attr.id]': 'id',
},
})
export class ButtonToggleComponent implements OnInit, OnDestroy {
@Input() id: string;
@Input() value: any;
@Input() name: string;
@Input() ariaLabel: string;
@Input() ariaLabelledby: string | null = null;
@ViewChild('button') _buttonEl: ElementRef<HTMLButtonElement>;
buttonToggleGroup: ButtonToggleGroupDirective;
/** Event emitted when the group value changes. */
@Output() readonly change: EventEmitter<ButtonToggleChange> = new EventEmitter<ButtonToggleChange>();
private _isSingleSelector = false;
constructor(
@Optional() toggleGroup: ButtonToggleGroupDirective,
private _changeDetectorRef: ChangeDetectorRef,
private _elementRef: ElementRef<HTMLElement>,
private _focusMonitor: FocusMonitor,
) {
this.buttonToggleGroup = toggleGroup;
}
private _checked = false;
@Input()
get checked(): boolean {
return this.buttonToggleGroup ? this.buttonToggleGroup._isSelected(this) : this._checked;
}
set checked(value: boolean) {
const newValue = coerceBooleanProperty(value);
if (newValue !== this._checked) {
this._checked = newValue;
if (this.buttonToggleGroup) {
this.buttonToggleGroup._syncButtonToggle(this, this._checked);
}
this._changeDetectorRef.markForCheck();
}
}
get buttonId(): string {
return `${this.id}-button`;
}
private _disabled: boolean = false;
/** Whether the button is disabled. */
@Input()
get disabled(): boolean {
return this._disabled || (this.buttonToggleGroup && this.buttonToggleGroup.disabled);
}
set disabled(value: boolean) {
this._disabled = coerceBooleanProperty(value);
}
ngOnInit(): void {
this._isSingleSelector = this.buttonToggleGroup && !this.buttonToggleGroup.multiple;
this.id = this.id || `gd-button-toggle-${_uniqueIdCounter++}`;
if (this._isSingleSelector) {
this.name = this.buttonToggleGroup.name;
}
if (this.buttonToggleGroup && this.buttonToggleGroup._isPrechecked(this)) {
this.checked = true;
}
this._focusMonitor.monitor(this._elementRef.nativeElement, true);
}
ngOnDestroy(): void {
this._focusMonitor.stopMonitoring(this._elementRef.nativeElement);
}
/** Focuses the button. */
focus(): void {
this._buttonEl.nativeElement.focus();
}
/** Checks the button toggle due to an interaction with the underlying native button. */
_onButtonClick() {
const newChecked = this._isSingleSelector ? true : !this._checked;
if (newChecked !== this._checked) {
this._checked = newChecked;
if (this.buttonToggleGroup) {
this.buttonToggleGroup._syncButtonToggle(this, this._checked, true);
this.buttonToggleGroup._onTouched();
}
}
// Emit a change event when it's the single selector
this.change.emit(new ButtonToggleChange(this, this.value));
}
/**
* Marks the button toggle as needing checking for change detection.
* This method is exposed because the parent button toggle group will directly
* update bound properties of the radio button.
*/
_markForCheck(): void {
// When the group value changes, the button will not be notified.
// Use `markForCheck` to explicit update button toggle's status.
this._changeDetectorRef.markForCheck();
}
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* Manages a Container Registry Task.
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as azure from "@pulumi/azure";
*
* const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"});
* const exampleRegistry = new azure.containerservice.Registry("exampleRegistry", {
* resourceGroupName: exampleResourceGroup.name,
* location: exampleResourceGroup.location,
* sku: "Basic",
* });
* const exampleRegistryTask = new azure.containerservice.RegistryTask("exampleRegistryTask", {
* containerRegistryId: exampleRegistry.id,
* platform: {
* os: "Linux",
* },
* dockerStep: {
* dockerfilePath: "Dockerfile",
* contextPath: "https://github.com/<user name>/acr-build-helloworld-node#main",
* contextAccessToken: "<github personal access token>",
* imageNames: ["helloworld:{{.Run.ID}}"],
* },
* });
* ```
*
* ## Import
*
* Container Registry Tasks can be imported using the `resource id`, e.g.
*
* ```sh
* $ pulumi import azure:containerservice/registryTask:RegistryTask example /subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/group1/providers/Microsoft.ContainerRegistry/registries/registry1/tasks/task1
* ```
*/
export class RegistryTask extends pulumi.CustomResource {
/**
* Get an existing RegistryTask resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: RegistryTaskState, opts?: pulumi.CustomResourceOptions): RegistryTask {
return new RegistryTask(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'azure:containerservice/registryTask:RegistryTask';
/**
* Returns true if the given object is an instance of RegistryTask. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is RegistryTask {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === RegistryTask.__pulumiType;
}
/**
* The name of the dedicated Container Registry Agent Pool for this Container Registry Task.
*/
public readonly agentPoolName!: pulumi.Output<string | undefined>;
/**
* A `agentSetting` block as defined below.
*/
public readonly agentSetting!: pulumi.Output<outputs.containerservice.RegistryTaskAgentSetting | undefined>;
/**
* A `baseImageTrigger` block as defined below.
*/
public readonly baseImageTrigger!: pulumi.Output<outputs.containerservice.RegistryTaskBaseImageTrigger | undefined>;
/**
* The ID of the Container Registry that this Container Registry Task resides in. Changing this forces a new Container Registry Task to be created.
*/
public readonly containerRegistryId!: pulumi.Output<string>;
/**
* A `dockerStep` block as defined below.
*/
public readonly dockerStep!: pulumi.Output<outputs.containerservice.RegistryTaskDockerStep | undefined>;
/**
* Should this Container Registry Task be enabled? Defaults to `true`.
*/
public readonly enabled!: pulumi.Output<boolean | undefined>;
/**
* A `encodedStep` block as defined below.
*/
public readonly encodedStep!: pulumi.Output<outputs.containerservice.RegistryTaskEncodedStep | undefined>;
/**
* A `fileStep` block as defined below.
*/
public readonly fileStep!: pulumi.Output<outputs.containerservice.RegistryTaskFileStep | undefined>;
/**
* A `identity` block as defined below.
*/
public readonly identity!: pulumi.Output<outputs.containerservice.RegistryTaskIdentity | undefined>;
/**
* Whether this Container Registry Task is a system task. Changing this forces a new Container Registry Task to be created. Defaults to `false`.
*/
public readonly isSystemTask!: pulumi.Output<boolean | undefined>;
/**
* The template that describes the run log artifact.
*/
public readonly logTemplate!: pulumi.Output<string | undefined>;
/**
* The name which should be used for this Container Registry Task. Changing this forces a new Container Registry Task to be created.
*/
public readonly name!: pulumi.Output<string>;
/**
* A `platform` block as defined below.
*/
public readonly platform!: pulumi.Output<outputs.containerservice.RegistryTaskPlatform | undefined>;
/**
* One `registryCredential` block as defined below.
*/
public readonly registryCredential!: pulumi.Output<outputs.containerservice.RegistryTaskRegistryCredential | undefined>;
/**
* One or more `sourceTrigger` blocks as defined below.
*/
public readonly sourceTriggers!: pulumi.Output<outputs.containerservice.RegistryTaskSourceTrigger[] | undefined>;
/**
* A mapping of tags which should be assigned to the Container Registry Task.
*/
public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* The timeout of this Container Registry Task in seconds. The valid range lies from 300 to 28800. Defaults to 3600.
*/
public readonly timeoutInSeconds!: pulumi.Output<number | undefined>;
/**
* One or more `timerTrigger` blocks as defined below.
*/
public readonly timerTriggers!: pulumi.Output<outputs.containerservice.RegistryTaskTimerTrigger[] | undefined>;
/**
* Create a RegistryTask resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args: RegistryTaskArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: RegistryTaskArgs | RegistryTaskState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as RegistryTaskState | undefined;
inputs["agentPoolName"] = state ? state.agentPoolName : undefined;
inputs["agentSetting"] = state ? state.agentSetting : undefined;
inputs["baseImageTrigger"] = state ? state.baseImageTrigger : undefined;
inputs["containerRegistryId"] = state ? state.containerRegistryId : undefined;
inputs["dockerStep"] = state ? state.dockerStep : undefined;
inputs["enabled"] = state ? state.enabled : undefined;
inputs["encodedStep"] = state ? state.encodedStep : undefined;
inputs["fileStep"] = state ? state.fileStep : undefined;
inputs["identity"] = state ? state.identity : undefined;
inputs["isSystemTask"] = state ? state.isSystemTask : undefined;
inputs["logTemplate"] = state ? state.logTemplate : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["platform"] = state ? state.platform : undefined;
inputs["registryCredential"] = state ? state.registryCredential : undefined;
inputs["sourceTriggers"] = state ? state.sourceTriggers : undefined;
inputs["tags"] = state ? state.tags : undefined;
inputs["timeoutInSeconds"] = state ? state.timeoutInSeconds : undefined;
inputs["timerTriggers"] = state ? state.timerTriggers : undefined;
} else {
const args = argsOrState as RegistryTaskArgs | undefined;
if ((!args || args.containerRegistryId === undefined) && !opts.urn) {
throw new Error("Missing required property 'containerRegistryId'");
}
inputs["agentPoolName"] = args ? args.agentPoolName : undefined;
inputs["agentSetting"] = args ? args.agentSetting : undefined;
inputs["baseImageTrigger"] = args ? args.baseImageTrigger : undefined;
inputs["containerRegistryId"] = args ? args.containerRegistryId : undefined;
inputs["dockerStep"] = args ? args.dockerStep : undefined;
inputs["enabled"] = args ? args.enabled : undefined;
inputs["encodedStep"] = args ? args.encodedStep : undefined;
inputs["fileStep"] = args ? args.fileStep : undefined;
inputs["identity"] = args ? args.identity : undefined;
inputs["isSystemTask"] = args ? args.isSystemTask : undefined;
inputs["logTemplate"] = args ? args.logTemplate : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["platform"] = args ? args.platform : undefined;
inputs["registryCredential"] = args ? args.registryCredential : undefined;
inputs["sourceTriggers"] = args ? args.sourceTriggers : undefined;
inputs["tags"] = args ? args.tags : undefined;
inputs["timeoutInSeconds"] = args ? args.timeoutInSeconds : undefined;
inputs["timerTriggers"] = args ? args.timerTriggers : undefined;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(RegistryTask.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering RegistryTask resources.
*/
export interface RegistryTaskState {
/**
* The name of the dedicated Container Registry Agent Pool for this Container Registry Task.
*/
agentPoolName?: pulumi.Input<string>;
/**
* A `agentSetting` block as defined below.
*/
agentSetting?: pulumi.Input<inputs.containerservice.RegistryTaskAgentSetting>;
/**
* A `baseImageTrigger` block as defined below.
*/
baseImageTrigger?: pulumi.Input<inputs.containerservice.RegistryTaskBaseImageTrigger>;
/**
* The ID of the Container Registry that this Container Registry Task resides in. Changing this forces a new Container Registry Task to be created.
*/
containerRegistryId?: pulumi.Input<string>;
/**
* A `dockerStep` block as defined below.
*/
dockerStep?: pulumi.Input<inputs.containerservice.RegistryTaskDockerStep>;
/**
* Should this Container Registry Task be enabled? Defaults to `true`.
*/
enabled?: pulumi.Input<boolean>;
/**
* A `encodedStep` block as defined below.
*/
encodedStep?: pulumi.Input<inputs.containerservice.RegistryTaskEncodedStep>;
/**
* A `fileStep` block as defined below.
*/
fileStep?: pulumi.Input<inputs.containerservice.RegistryTaskFileStep>;
/**
* A `identity` block as defined below.
*/
identity?: pulumi.Input<inputs.containerservice.RegistryTaskIdentity>;
/**
* Whether this Container Registry Task is a system task. Changing this forces a new Container Registry Task to be created. Defaults to `false`.
*/
isSystemTask?: pulumi.Input<boolean>;
/**
* The template that describes the run log artifact.
*/
logTemplate?: pulumi.Input<string>;
/**
* The name which should be used for this Container Registry Task. Changing this forces a new Container Registry Task to be created.
*/
name?: pulumi.Input<string>;
/**
* A `platform` block as defined below.
*/
platform?: pulumi.Input<inputs.containerservice.RegistryTaskPlatform>;
/**
* One `registryCredential` block as defined below.
*/
registryCredential?: pulumi.Input<inputs.containerservice.RegistryTaskRegistryCredential>;
/**
* One or more `sourceTrigger` blocks as defined below.
*/
sourceTriggers?: pulumi.Input<pulumi.Input<inputs.containerservice.RegistryTaskSourceTrigger>[]>;
/**
* A mapping of tags which should be assigned to the Container Registry Task.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* The timeout of this Container Registry Task in seconds. The valid range lies from 300 to 28800. Defaults to 3600.
*/
timeoutInSeconds?: pulumi.Input<number>;
/**
* One or more `timerTrigger` blocks as defined below.
*/
timerTriggers?: pulumi.Input<pulumi.Input<inputs.containerservice.RegistryTaskTimerTrigger>[]>;
}
/**
* The set of arguments for constructing a RegistryTask resource.
*/
export interface RegistryTaskArgs {
/**
* The name of the dedicated Container Registry Agent Pool for this Container Registry Task.
*/
agentPoolName?: pulumi.Input<string>;
/**
* A `agentSetting` block as defined below.
*/
agentSetting?: pulumi.Input<inputs.containerservice.RegistryTaskAgentSetting>;
/**
* A `baseImageTrigger` block as defined below.
*/
baseImageTrigger?: pulumi.Input<inputs.containerservice.RegistryTaskBaseImageTrigger>;
/**
* The ID of the Container Registry that this Container Registry Task resides in. Changing this forces a new Container Registry Task to be created.
*/
containerRegistryId: pulumi.Input<string>;
/**
* A `dockerStep` block as defined below.
*/
dockerStep?: pulumi.Input<inputs.containerservice.RegistryTaskDockerStep>;
/**
* Should this Container Registry Task be enabled? Defaults to `true`.
*/
enabled?: pulumi.Input<boolean>;
/**
* A `encodedStep` block as defined below.
*/
encodedStep?: pulumi.Input<inputs.containerservice.RegistryTaskEncodedStep>;
/**
* A `fileStep` block as defined below.
*/
fileStep?: pulumi.Input<inputs.containerservice.RegistryTaskFileStep>;
/**
* A `identity` block as defined below.
*/
identity?: pulumi.Input<inputs.containerservice.RegistryTaskIdentity>;
/**
* Whether this Container Registry Task is a system task. Changing this forces a new Container Registry Task to be created. Defaults to `false`.
*/
isSystemTask?: pulumi.Input<boolean>;
/**
* The template that describes the run log artifact.
*/
logTemplate?: pulumi.Input<string>;
/**
* The name which should be used for this Container Registry Task. Changing this forces a new Container Registry Task to be created.
*/
name?: pulumi.Input<string>;
/**
* A `platform` block as defined below.
*/
platform?: pulumi.Input<inputs.containerservice.RegistryTaskPlatform>;
/**
* One `registryCredential` block as defined below.
*/
registryCredential?: pulumi.Input<inputs.containerservice.RegistryTaskRegistryCredential>;
/**
* One or more `sourceTrigger` blocks as defined below.
*/
sourceTriggers?: pulumi.Input<pulumi.Input<inputs.containerservice.RegistryTaskSourceTrigger>[]>;
/**
* A mapping of tags which should be assigned to the Container Registry Task.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* The timeout of this Container Registry Task in seconds. The valid range lies from 300 to 28800. Defaults to 3600.
*/
timeoutInSeconds?: pulumi.Input<number>;
/**
* One or more `timerTrigger` blocks as defined below.
*/
timerTriggers?: pulumi.Input<pulumi.Input<inputs.containerservice.RegistryTaskTimerTrigger>[]>;
} | the_stack |
import {
isPresent,
isBlank,
isFunction,
toObject,
toPath,
isJsObject,
isIndex,
isKey,
isArray,
isArguments
} from './lang';
const INFINITY = 1 / 0;
/**
* Wraps Javascript Objects
*/
export class StringMapWrapper {
static create(): {[k: /*any*/ string]: any} {
// Note: We are not using Object.create(null) here due to
// performance!
// http://jsperf.com/ng2-object-create-null
return {};
}
static contains( map: {[key: string]: any}, key: string ): boolean {
return map.hasOwnProperty( key );
}
/**
* The base implementation of `getValueFromPath` without support for string paths
* and default values.
*
* @private
* @param {Object} object The object to query.
* @param {Array} path The path of the property to get.
* @param {string} [pathKey] The key representation of path.
* @returns {*} Returns the resolved value.
*/
static baseGet( object: Object, path: string[], pathKey?: string ) {
if ( object == null ) {
return;
}
object = toObject( object );
if ( pathKey !== undefined && pathKey in object ) {
path = [ pathKey ];
}
var index = 0,
length = path.length;
while ( object != null && index < length ) {
object = toObject( object )[ path[ index++ ] ];
}
return (index && index == length)
? object
: undefined;
}
/**
* Gets the property value at `path` of `object`. If the resolved value is
* `undefined` the `defaultValue` is used in its place.
*
* @static
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned if the resolved value is `undefined`.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
static getValueFromPath( object: Object, path: string|any[], defaultValue? ) {
var result = object == null
? undefined
: StringMapWrapper.baseGet( object, toPath( path ), (path + '') );
return result === undefined
? defaultValue
: result;
}
/**
* Sets the property value of `path` on `object`. If a portion of `path`
* does not exist it's created.
*
* @static
* @param {Object} object The object to augment.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @returns {Object} Returns `object`.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.set(object, 'a[0].b.c', 4);
* console.log(object.a[0].b.c);
* // => 4
*
* _.set(object, 'x[0].y.z', 5);
* console.log(object.x[0].y.z);
* // => 5
*/
static setValueInPath<O,M>( object: any, path: string|any[], value: any ): M {
if ( object == null ) {
return object;
}
var pathKey = (path + '');
path = (object[ pathKey ] != null || isKey( path, object ))
? [ pathKey ]
: toPath( path );
var index = -1,
length = path.length,
lastIndex = length - 1,
nested = object;
while ( nested != null && ++index < length ) {
var key = path[ index ];
if ( isJsObject( nested ) ) {
if ( index == lastIndex ) {
nested[ key ] = value;
} else if ( nested[ key ] == null ) {
nested[ key ] = isIndex( path[ index + 1 ] )
? []
: {};
}
}
nested = nested[ key ];
}
return object;
}
static get<V>( map: {[key: string]: V}, key: string ): V {
return map.hasOwnProperty( key )
? map[ key ]
: undefined;
}
static set<V>( map: {[key: string]: V}, key: string, value: V ) { map[ key ] = value; }
static keys( map: {[key: string]: any} ): string[] { return Object.keys( map ); }
static size( map: {[key: string]: any} ): number { return StringMapWrapper.keys( map ).length; }
static isEmpty( map: {[key: string]: any} ): boolean {
for ( var prop in map ) {
return false;
}
return true;
}
static delete( map: {[key: string]: any}, key: string ) { delete map[ key ]; }
static forEach<K, V>( map: {[key: string]: V}, callback: /*(V, K) => void*/ Function ) {
for ( var prop in map ) {
if ( map.hasOwnProperty( prop ) ) {
callback( map[ prop ], prop );
}
}
}
static values<T>( map: {[key: string]: T} ): T[] {
return Object.keys( map ).reduce( ( r, a ) => {
r.push( map[ a ] );
return r;
}, [] );
}
static merge<V>( m1: {[key: string]: V}, m2: {[key: string]: V} ): {[key: string]: V} {
var m: {[key: string]: V} = {};
for ( var attr in m1 ) {
if ( m1.hasOwnProperty( attr ) ) {
m[ attr ] = m1[ attr ];
}
}
for ( var attr in m2 ) {
if ( m2.hasOwnProperty( attr ) ) {
m[ attr ] = m2[ attr ];
}
}
return m;
}
static equals<V>( m1: {[key: string]: V}, m2: {[key: string]: V} ): boolean {
var k1 = Object.keys( m1 );
var k2 = Object.keys( m2 );
if ( k1.length != k2.length ) {
return false;
}
var key;
for ( var i = 0; i < k1.length; i++ ) {
key = k1[ i ];
if ( m1[ key ] !== m2[ key ] ) {
return false;
}
}
return true;
}
static assign(target: any, ...sources: any[]): any {
if ( !isPresent( target ) ) {
throw new TypeError( 'Object.assign cannot be called with null or undefined' );
}
const hasOwnProperty = Object.prototype.hasOwnProperty;
if ( (Object as any).assign ) {
return (Object as any).assign( target, ...sources );
}
let from;
const to = Object( target );
for ( var s = 0; s < sources.length; s++ ) {
from = Object( sources[ s ] );
for ( var key in from ) {
if ( hasOwnProperty.call( from, key ) ) {
to[ key ] = from[ key ];
}
}
}
return to;
}
}
/**
* A boolean-valued function over a value, possibly including context information
* regarding that value's position in an array.
*/
export interface Predicate<T> { ( value: T, index?: number, array?: T[] ): boolean; }
export class ListWrapper {
static create(): any[] { return [] }
static size( array: any[] ): number { return array.length }
// JS has no way to express a statically fixed size list, but dart does so we
// keep both methods.
static createFixedSize( size: number ): any[] { return new Array( size ); }
static createGrowableSize( size: number ): any[] { return new Array( size ); }
static clone<T>( array: T[] ): T[] { return array.slice( 0 ); }
static forEachWithIndex<T>( array: T[], fn: ( t: T, n: number ) => void ) {
for ( var i = 0; i < array.length; i++ ) {
fn( array[ i ], i );
}
}
static first<T>( array: T[] ): T {
if ( !array ) return null;
return array[ 0 ];
}
static last<T>( array: T[] ): T {
if ( !array || array.length == 0 ) return null;
return array[ array.length - 1 ];
}
static indexOf<T>( array: T[], value: T, startIndex: number = 0 ): number {
return array.indexOf( value, startIndex );
}
static contains<T>( list: T[], el: T ): boolean { return list.indexOf( el ) !== -1; }
static reversed<T>( array: T[] ): T[] {
var a = ListWrapper.clone( array );
return a.reverse();
}
static concat( a: any[], b: any[] ): any[] { return a.concat( b ); }
static insert<T>( list: T[], index: number, value: T ) { list.splice( index, 0, value ); }
static removeAt<T>( list: T[], index: number ): T {
var res = list[ index ];
list.splice( index, 1 );
return res;
}
static removeAll<T>( list: T[], items: T[] ) {
for ( var i = 0; i < items.length; ++i ) {
var index = list.indexOf( items[ i ] );
list.splice( index, 1 );
}
}
static remove<T>( list: T[], el: T ): boolean {
var index = list.indexOf( el );
if ( index > -1 ) {
list.splice( index, 1 );
return true;
}
return false;
}
static clear( list: any[] ) { list.length = 0; }
static isEmpty( list: any[] ): boolean { return list.length == 0; }
static fill( list: any[], value: any, start: number = 0, end: number = null ) {
if ( !(Array.prototype as any).fill ) {
(Array.prototype as any).fill = function ( value ) {
// Steps 1-2.
if ( this == null ) {
throw new TypeError( 'this is null or not defined' );
}
var O = Object( this );
// Steps 3-5.
var len = O.length >>> 0;
// Steps 6-7.
var start = arguments[ 1 ];
var relativeStart = start >> 0;
// Step 8.
var k = relativeStart < 0
? Math.max( len + relativeStart, 0 )
: Math.min( relativeStart, len );
// Steps 9-10.
var end = arguments[ 2 ];
var relativeEnd = end === undefined
? len
: end >> 0;
// Step 11.
var final = relativeEnd < 0
? Math.max( len + relativeEnd, 0 )
: Math.min( relativeEnd, len );
// Step 12.
while ( k < final ) {
O[ k ] = value;
k++;
}
// Step 13.
return O;
};
}
(list as any).fill(
value,
start,
end === null
? list.length
: end
);
}
static equals( a: any[], b: any[] ): boolean {
if ( a.length != b.length ) return false;
for ( var i = 0; i < a.length; ++i ) {
if ( a[ i ] !== b[ i ] ) return false;
}
return true;
}
static slice<T>( l: T[], from: number = 0, to: number = null ): T[] {
return l.slice( from,
to === null
? undefined
: to );
}
static splice<T>( l: T[], from: number, length: number ): T[] { return l.splice( from, length ); }
static sort<T>( l: T[], compareFn?: ( a: T, b: T ) => number ) {
if ( isPresent( compareFn ) ) {
l.sort( compareFn );
} else {
l.sort();
}
}
static toString<T>( l: T[] ): string { return l.toString(); }
static toJSON<T>( l: T[] ): string { return JSON.stringify( l ); }
static maximum<T>( list: T[], predicate: ( t: T ) => number ): T {
if ( list.length == 0 ) {
return null;
}
var solution = null;
var maxValue = -Infinity;
for ( var index = 0; index < list.length; index++ ) {
var candidate = list[ index ];
if ( isBlank( candidate ) ) {
continue;
}
var candidateValue = predicate( candidate );
if ( candidateValue > maxValue ) {
solution = candidate;
maxValue = candidateValue;
}
}
return solution;
}
static find( arr, predicate, ctx? ): any {
if ( isFunction( Array.prototype[ 'find' ] ) ) {
return arr.find( predicate, ctx );
}
ctx = ctx || this;
var length = arr.length;
var i;
if ( !isFunction( predicate ) ) {
throw new TypeError( `${predicate} is not a function` );
}
for ( i = 0; i < length; i++ ) {
if ( predicate.call( ctx, arr[ i ], i, arr ) ) {
return arr[ i ];
}
}
return undefined;
}
static findIndex( arr, predicate, ctx? ): number {
if ( isFunction( Array.prototype[ 'findIndex' ] ) ) {
return arr.findIndex( predicate, ctx );
}
if ( !isFunction( predicate ) ) {
throw new TypeError( 'predicate must be a function' );
}
var list = Object( arr );
var len = list.length;
if ( len === 0 ) {
return -1;
}
for ( var i = 0; i < len; i++ ) {
if ( predicate.call( ctx, list[ i ], i, list ) ) {
return i;
}
}
return -1;
}
private static isFlattenable(value): boolean {
return isArray(value) || isArguments(value);
}
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
private static arrayPush( array: any[], values: any[] ): any[] {
var index = -1,
length = values.length,
offset = array.length;
while ( ++index < length ) {
array[ offset + index ] = values[ index ];
}
return array;
}
/**
* The base implementation of `_.flatten` with support for restricting flattening.
*
* @private
* @param {Array} array The array to flatten.
* @param {number} depth The maximum recursion depth.
* @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
* @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
* @param {Array} [result=[]] The initial result value.
* @returns {Array} Returns the new flattened array.
*/
private static baseFlatten(
array: any[],
depth: number,
predicate = ListWrapper.isFlattenable,
isStrict = false,
result = []
) {
var index = -1;
var length = array.length;
while ( ++index < length ) {
var value = array[ index ];
if ( depth > 0 && predicate( value ) ) {
if ( depth > 1 ) {
// Recursively flatten arrays (susceptible to call stack limits).
ListWrapper.baseFlatten( value, depth - 1, predicate, isStrict, result );
} else {
ListWrapper.arrayPush( result, value );
}
} else if ( !isStrict ) {
result[ result.length ] = value;
}
}
return result;
}
/**
* Flattens `array` a single level deep.
*
* @static
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flatten([1, [2, [3, [4]], 5]]);
* // => [1, 2, [3, [4]], 5]
*/
static flatten(array: any[]): any[] {
const length = array ? array.length : 0;
return length ? ListWrapper.baseFlatten(array, 1) : [];
}
/**
* Recursively flattens `array`.
*
* @static
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flattenDeep([1, [2, [3, [4]], 5]]);
* // => [1, 2, 3, 4, 5]
*/
static flattenDeep( array: any[] ): any[] {
const length = array
? array.length
: 0;
return length
? ListWrapper.baseFlatten( array, INFINITY )
: [];
}
} | the_stack |
import * as React from 'react';
import { getLayerStyles } from './KeytipLayer.styles';
import { Keytip } from '../../Keytip';
import { Layer } from '../../Layer';
import {
classNamesFunction,
getDocument,
arraysEqual,
warn,
isMac,
EventGroup,
Async,
initializeComponentRef,
KeyCodes,
} from '../../Utilities';
import { KeytipManager } from '../../utilities/keytips/KeytipManager';
import { KeytipTree } from './KeytipTree';
import {
ktpTargetFromId,
ktpTargetFromSequences,
sequencesToID,
mergeOverflows,
} from '../../utilities/keytips/KeytipUtils';
import { transitionKeysContain } from '../../utilities/keytips/IKeytipTransitionKey';
import { KeytipEvents, KTP_LAYER_ID, KTP_ARIA_SEPARATOR } from '../../utilities/keytips/KeytipConstants';
import type { IKeytipLayerProps, IKeytipLayerStyles, IKeytipLayerStyleProps } from './KeytipLayer.types';
import type { IKeytipProps } from '../../Keytip';
import type { IKeytipTreeNode } from './IKeytipTreeNode';
import type { KeytipTransitionModifier, IKeytipTransitionKey } from '../../utilities/keytips/IKeytipTransitionKey';
export interface IKeytipLayerState {
inKeytipMode: boolean;
keytips: IKeytipProps[];
visibleKeytips: IKeytipProps[];
}
// Default sequence is Alt-Windows (Alt-Meta) in Windows, Option-Control (Alt-Control) in Mac
const defaultStartSequence: IKeytipTransitionKey = {
key: isMac() ? 'Control' : 'Meta',
modifierKeys: [KeyCodes.alt],
};
// Default exit sequence is the same as the start sequence
const defaultExitSequence: IKeytipTransitionKey = defaultStartSequence;
// Default return sequence is Escape
const defaultReturnSequence: IKeytipTransitionKey = {
key: 'Escape',
};
const getClassNames = classNamesFunction<IKeytipLayerStyleProps, IKeytipLayerStyles>();
/**
* A layer that holds all keytip items
* {@docCategory Keytips}
*/
export class KeytipLayerBase extends React.Component<IKeytipLayerProps, IKeytipLayerState> {
public static defaultProps: IKeytipLayerProps = {
keytipStartSequences: [defaultStartSequence],
keytipExitSequences: [defaultExitSequence],
keytipReturnSequences: [defaultReturnSequence],
content: '',
};
private _events: EventGroup;
private _async: Async;
private _keytipTree: KeytipTree;
private _keytipManager: KeytipManager = KeytipManager.getInstance();
private _classNames: { [key in keyof IKeytipLayerStyles]: string };
private _currentSequence: string;
private _newCurrentKeytipSequences?: string[];
private _delayedKeytipQueue: string[] = [];
private _delayedQueueTimeout: number;
private _keyHandled = false;
constructor(props: IKeytipLayerProps, context: any) {
super(props, context);
initializeComponentRef(this);
this._events = new EventGroup(this);
this._async = new Async(this);
const keytips = this._keytipManager.getKeytips();
this.state = {
inKeytipMode: false,
keytips,
visibleKeytips: this._getVisibleKeytips(keytips),
};
this._buildTree();
this._currentSequence = '';
// Add keytip listeners
this._events.on(this._keytipManager, KeytipEvents.KEYTIP_ADDED, this._onKeytipAdded);
this._events.on(this._keytipManager, KeytipEvents.KEYTIP_UPDATED, this._onKeytipUpdated);
this._events.on(this._keytipManager, KeytipEvents.KEYTIP_REMOVED, this._onKeytipRemoved);
this._events.on(this._keytipManager, KeytipEvents.PERSISTED_KEYTIP_ADDED, this._onPersistedKeytipAdded);
this._events.on(this._keytipManager, KeytipEvents.PERSISTED_KEYTIP_REMOVED, this._onPersistedKeytipRemoved);
this._events.on(this._keytipManager, KeytipEvents.PERSISTED_KEYTIP_EXECUTE, this._onPersistedKeytipExecute);
}
public render(): JSX.Element {
const { content, styles } = this.props;
const { keytips, visibleKeytips } = this.state;
this._classNames = getClassNames(styles, {});
return (
<Layer styles={getLayerStyles}>
<span id={KTP_LAYER_ID} className={this._classNames.innerContent}>{`${content}${KTP_ARIA_SEPARATOR}`}</span>
{keytips &&
keytips.map((keytipProps: IKeytipProps, index: number) => {
return (
<span key={index} id={sequencesToID(keytipProps.keySequences)} className={this._classNames.innerContent}>
{keytipProps.keySequences.join(KTP_ARIA_SEPARATOR)}
</span>
);
})}
{visibleKeytips &&
visibleKeytips.map((visibleKeytipProps: IKeytipProps) => {
return <Keytip key={sequencesToID(visibleKeytipProps.keySequences)} {...visibleKeytipProps} />;
})}
</Layer>
);
}
public componentDidMount(): void {
// Add window listeners
this._events.on(window, 'mouseup', this._onDismiss, true /* useCapture */);
this._events.on(window, 'pointerup', this._onDismiss, true /* useCapture */);
this._events.on(window, 'resize', this._onDismiss);
this._events.on(window, 'keydown', this._onKeyDown, true /* useCapture */);
this._events.on(window, 'keypress', this._onKeyPress, true /* useCapture */);
this._events.on(window, 'scroll', this._onDismiss, true /* useCapture */);
// Add keytip listeners
this._events.on(this._keytipManager, KeytipEvents.ENTER_KEYTIP_MODE, this._enterKeytipMode);
this._events.on(this._keytipManager, KeytipEvents.EXIT_KEYTIP_MODE, this._exitKeytipMode);
}
public componentWillUnmount(): void {
this._async.dispose();
this._events.dispose();
}
// The below public functions are only public for testing purposes
// They are not intended to be used in app code by using a KeytipLayer reference
public getCurrentSequence(): string {
return this._currentSequence;
}
public getKeytipTree(): KeytipTree {
return this._keytipTree;
}
/**
* Processes an IKeytipTransitionKey entered by the user
*
* @param transitionKey - IKeytipTransitionKey received by the layer to process
*/
public processTransitionInput(transitionKey: IKeytipTransitionKey, ev?: React.KeyboardEvent<HTMLElement>): void {
const currKtp = this._keytipTree.currentKeytip;
if (transitionKeysContain(this.props.keytipExitSequences!, transitionKey) && currKtp) {
// If key sequence is in 'exit sequences', exit keytip mode
this._keyHandled = true;
this._exitKeytipMode(ev);
} else if (transitionKeysContain(this.props.keytipReturnSequences!, transitionKey)) {
// If key sequence is in return sequences, move currentKeytip to parent (or if currentKeytip is the root, exit)
if (currKtp) {
this._keyHandled = true;
if (currKtp.id === this._keytipTree.root.id) {
// We are at the root, exit keytip mode
this._exitKeytipMode(ev);
} else {
// If this keytip has a onReturn prop, we execute the func.
if (currKtp.onReturn) {
currKtp.onReturn(this._getKtpExecuteTarget(currKtp), this._getKtpTarget(currKtp));
}
// Reset currentSequence
this._currentSequence = '';
// Return pointer to its parent
this._keytipTree.currentKeytip = this._keytipTree.getNode(currKtp.parent);
// Show children keytips of the new currentKeytip
this.showKeytips(this._keytipTree.getChildren());
this._warnIfDuplicateKeytips();
}
}
} else if (transitionKeysContain(this.props.keytipStartSequences!, transitionKey) && !currKtp) {
// If key sequence is in 'entry sequences' and currentKeytip is null, we enter keytip mode
this._keyHandled = true;
this._enterKeytipMode(transitionKey);
this._warnIfDuplicateKeytips();
}
}
/**
* Processes inputs from the document listener and traverse the keytip tree
*
* @param key - Key pressed by the user
*/
public processInput(key: string, ev?: React.KeyboardEvent<HTMLElement>): void {
// Concat the input key with the current sequence
const currSequence: string = this._currentSequence + key;
let currKtp = this._keytipTree.currentKeytip;
// currentKeytip must be defined, otherwise we haven't entered keytip mode yet
if (currKtp) {
const node = this._keytipTree.getExactMatchedNode(currSequence, currKtp);
if (node) {
this._keytipTree.currentKeytip = currKtp = node;
const currKtpChildren = this._keytipTree.getChildren();
// Execute this node's onExecute if defined
if (currKtp.onExecute) {
currKtp.onExecute(this._getKtpExecuteTarget(currKtp), this._getKtpTarget(currKtp));
// Reset currKtp, this might have changed from the onExecute
currKtp = this._keytipTree.currentKeytip;
}
// To exit keytipMode after executing the keytip it must not have a menu or have dynamic children
if (currKtpChildren.length === 0 && !(currKtp.hasDynamicChildren || currKtp.hasMenu)) {
this._exitKeytipMode(ev);
} else {
// Show all children keytips
this.showKeytips(currKtpChildren);
this._warnIfDuplicateKeytips();
}
// Clear currentSequence
this._currentSequence = '';
return;
}
const partialNodes = this._keytipTree.getPartiallyMatchedNodes(currSequence, currKtp);
if (partialNodes.length > 0) {
// We found nodes that partially match the sequence, so we show only those
// Omit showing persisted nodes here
const ids = partialNodes
.filter((partialNode: IKeytipTreeNode) => {
return !partialNode.persisted;
})
.map((partialNode: IKeytipTreeNode) => {
return partialNode.id;
});
this.showKeytips(ids);
// Save currentSequence
this._currentSequence = currSequence;
}
}
}
/**
* Show the given keytips and hide all others
*
* @param ids - Keytip IDs to show
*/
public showKeytips(ids: string[]): void {
// Update the visible prop in the manager
for (const keytip of this._keytipManager.getKeytips()) {
let keytipId = sequencesToID(keytip.keySequences);
if (keytip.overflowSetSequence) {
// Check if the ID with the overflow is the keytip we're looking for
keytipId = sequencesToID(mergeOverflows(keytip.keySequences, keytip.overflowSetSequence));
}
if (ids.indexOf(keytipId) >= 0) {
keytip.visible = true;
} else {
keytip.visible = false;
}
}
// Apply the manager changes to the Layer state
this._setKeytips();
}
/**
* Enters keytip mode for this layer
*/
private _enterKeytipMode(transitionKey?: IKeytipTransitionKey): void {
if (this._keytipManager.shouldEnterKeytipMode) {
if (this._keytipManager.delayUpdatingKeytipChange) {
this._buildTree();
this._setKeytips();
}
this._keytipTree.currentKeytip = this._keytipTree.root;
// Show children of root
this.showKeytips(this._keytipTree.getChildren());
this._setInKeytipMode(true /* inKeytipMode */);
if (this.props.onEnterKeytipMode) {
this.props.onEnterKeytipMode(transitionKey);
}
}
}
private _buildTree(): void {
this._keytipTree = new KeytipTree();
// Add regular and persisted keytips to the tree
for (const id of Object.keys(this._keytipManager.keytips)) {
const uniqueKeytip = this._keytipManager.keytips[id];
this._keytipTree.addNode(uniqueKeytip.keytip, uniqueKeytip.uniqueID);
}
for (const id of Object.keys(this._keytipManager.persistedKeytips)) {
const uniqueKeytip = this._keytipManager.persistedKeytips[id];
this._keytipTree.addNode(uniqueKeytip.keytip, uniqueKeytip.uniqueID);
}
}
/**
* Exits keytip mode for this layer
*/
private _exitKeytipMode(ev?: React.KeyboardEvent<HTMLElement> | React.MouseEvent<HTMLElement>): void {
this._keytipTree.currentKeytip = undefined;
this._currentSequence = '';
// Hide all keytips
this.showKeytips([]);
// Reset the delayed keytips if any
this._delayedQueueTimeout && this._async.clearTimeout(this._delayedQueueTimeout);
this._delayedKeytipQueue = [];
this._setInKeytipMode(false /* inKeytipMode */);
if (this.props.onExitKeytipMode) {
this.props.onExitKeytipMode(ev);
}
}
/**
* Sets the keytips state property
*
* @param keytipProps - Keytips to set in this layer
*/
private _setKeytips(keytipProps: IKeytipProps[] = this._keytipManager.getKeytips()) {
this.setState({ keytips: keytipProps, visibleKeytips: this._getVisibleKeytips(keytipProps) });
}
/**
* Callback function to use for persisted keytips
*
* @param overflowButtonSequences - The overflow button sequence to execute
* @param keytipSequences - The keytip that should become the 'currentKeytip' when it is registered
*/
private _persistedKeytipExecute(overflowButtonSequences: string[], keytipSequences: string[]) {
// Save newCurrentKeytip for later
this._newCurrentKeytipSequences = keytipSequences;
// Execute the overflow button's onExecute
const overflowKeytipNode = this._keytipTree.getNode(sequencesToID(overflowButtonSequences));
if (overflowKeytipNode && overflowKeytipNode.onExecute) {
overflowKeytipNode.onExecute(
this._getKtpExecuteTarget(overflowKeytipNode),
this._getKtpTarget(overflowKeytipNode),
);
}
}
private _getVisibleKeytips(keytips: IKeytipProps[]): IKeytipProps[] {
// Filter out non-visible keytips and duplicates
const seenIds: { [childSequence: string]: number } = {};
return keytips.filter(keytip => {
let keytipId = sequencesToID(keytip.keySequences);
if (keytip.overflowSetSequence) {
// Account for overflow set sequences when checking for duplicates
keytipId = sequencesToID(mergeOverflows(keytip.keySequences, keytip.overflowSetSequence));
}
seenIds[keytipId] = seenIds[keytipId] ? seenIds[keytipId] + 1 : 1;
return keytip.visible && seenIds[keytipId] === 1;
});
}
private _onDismiss = (ev?: React.MouseEvent<HTMLElement>): void => {
// if we are in keytip mode, then exit keytip mode
if (this.state.inKeytipMode) {
this._exitKeytipMode(ev);
}
};
private _onKeyDown = (ev: React.KeyboardEvent<HTMLElement>): void => {
this._keyHandled = false;
// using key since which has been deprecated and key is now widely suporrted.
// See: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which
let key = ev.key;
switch (key) {
case 'Tab':
case 'Enter':
case 'Spacebar':
case ' ':
case 'ArrowUp':
case 'Up':
case 'ArrowDown':
case 'Down':
case 'ArrowLeft':
case 'Left':
case 'ArrowRight':
case 'Right':
if (this.state.inKeytipMode) {
this._keyHandled = true;
this._exitKeytipMode(ev);
}
break;
default:
// Special cases for browser-specific keys that are not at standard
// (according to http://www.w3.org/TR/uievents-key/#keys-navigation)
if (key === 'Esc') {
// Edge: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/5290772/
key = 'Escape';
} else if (key === 'OS' || key === 'Win') {
// Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=1232918
// Edge: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/
// and https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/16424492/
key = 'Meta';
}
const transitionKey: IKeytipTransitionKey = { key };
transitionKey.modifierKeys = this._getModifierKey(key, ev);
this.processTransitionInput(transitionKey, ev);
break;
}
};
/**
* Gets the ModifierKeyCodes based on the keyboard event
*
* @param ev - React.KeyboardEvent
* @returns List of ModifierKeyCodes that were pressed
*/
private _getModifierKey(key: string, ev: React.KeyboardEvent<HTMLElement>): KeytipTransitionModifier[] | undefined {
const modifierKeys: KeytipTransitionModifier[] = [];
if (ev.altKey && key !== 'Alt') {
modifierKeys.push(KeyCodes.alt);
}
if (ev.ctrlKey && key !== 'Control') {
modifierKeys.push(KeyCodes.ctrl);
}
if (ev.shiftKey && key !== 'Shift') {
modifierKeys.push(KeyCodes.shift);
}
if (ev.metaKey && key !== 'Meta') {
modifierKeys.push(KeyCodes.leftWindow);
}
return modifierKeys.length ? modifierKeys : undefined;
}
private _onKeyPress = (ev: React.KeyboardEvent<HTMLElement>): void => {
if (this.state.inKeytipMode && !this._keyHandled) {
// Call processInput
this.processInput(ev.key.toLocaleLowerCase(), ev);
ev.preventDefault();
ev.stopPropagation();
}
};
private _onKeytipAdded = (eventArgs: any) => {
const keytipProps = eventArgs.keytip;
const uniqueID = eventArgs.uniqueID;
this._keytipTree.addNode(keytipProps, uniqueID);
this._setKeytips();
// Add the keytip to the queue to show later
if (this._keytipTree.isCurrentKeytipParent(keytipProps)) {
// Ensure existing children are still shown.
this._delayedKeytipQueue = this._delayedKeytipQueue.concat(this._keytipTree.currentKeytip?.children || []);
this._addKeytipToQueue(sequencesToID(keytipProps.keySequences));
// Ensure the child of currentKeytip is successfully added to currentKeytip's children and update it if not.
// Note: Added this condition because KeytipTree.addNode was not always reflecting updates made to a parent node
// in currentKeytip when that parent is the currentKeytip.
if (
this._keytipTree.currentKeytip &&
this._keytipTree.currentKeytip.hasDynamicChildren &&
this._keytipTree.currentKeytip.children.indexOf(keytipProps.id) < 0
) {
const currNode = this._keytipTree.getNode(this._keytipTree.currentKeytip.id);
if (currNode) {
this._keytipTree.currentKeytip = currNode;
}
}
}
this._persistedKeytipChecks(keytipProps);
};
private _onKeytipUpdated = (eventArgs: any) => {
const keytipProps = eventArgs.keytip;
const uniqueID = eventArgs.uniqueID;
this._keytipTree.updateNode(keytipProps, uniqueID);
this._setKeytips();
if (this._keytipTree.isCurrentKeytipParent(keytipProps)) {
// Ensure existing children are still shown.
this._delayedKeytipQueue = this._delayedKeytipQueue.concat(this._keytipTree.currentKeytip?.children || []);
this._addKeytipToQueue(sequencesToID(keytipProps.keySequences));
}
this._persistedKeytipChecks(keytipProps);
};
/**
* Helper function to do checks related to persisted/overflow keytips
* Done on keytip added and keytip updated
*
* @param keytipProps - Keytip props
*/
private _persistedKeytipChecks = (keytipProps: IKeytipProps) => {
if (this._newCurrentKeytipSequences && arraysEqual(keytipProps.keySequences, this._newCurrentKeytipSequences)) {
this._triggerKeytipImmediately(keytipProps);
}
if (this._isCurrentKeytipAnAlias(keytipProps)) {
let keytipSequence = keytipProps.keySequences;
if (keytipProps.overflowSetSequence) {
keytipSequence = mergeOverflows(keytipSequence, keytipProps.overflowSetSequence);
}
this._keytipTree.currentKeytip = this._keytipTree.getNode(sequencesToID(keytipSequence));
}
};
private _onKeytipRemoved = (eventArgs: any) => {
const keytipProps = eventArgs.keytip;
const uniqueID = eventArgs.uniqueID;
// Remove keytip from the delayed queue
this._removeKeytipFromQueue(sequencesToID(keytipProps.keySequences));
// Remove the node from the Tree
this._keytipTree.removeNode(keytipProps, uniqueID);
this._setKeytips();
};
private _onPersistedKeytipAdded = (eventArgs: any) => {
const keytipProps = eventArgs.keytip;
const uniqueID = eventArgs.uniqueID;
this._keytipTree.addNode(keytipProps, uniqueID, true);
};
private _onPersistedKeytipRemoved = (eventArgs: any) => {
const keytipProps = eventArgs.keytip;
const uniqueID = eventArgs.uniqueID;
this._keytipTree.removeNode(keytipProps, uniqueID);
};
private _onPersistedKeytipExecute = (eventArgs: any) => {
this._persistedKeytipExecute(eventArgs.overflowButtonSequences, eventArgs.keytipSequences);
};
/**
* Trigger a keytip immediately and set it as the current keytip
*
* @param keytipProps - Keytip to trigger immediately
*/
private _triggerKeytipImmediately(keytipProps: IKeytipProps) {
// This keytip should become the currentKeytip and should execute right away
let keytipSequence = [...keytipProps.keySequences];
if (keytipProps.overflowSetSequence) {
keytipSequence = mergeOverflows(keytipSequence, keytipProps.overflowSetSequence);
}
// Set currentKeytip
this._keytipTree.currentKeytip = this._keytipTree.getNode(sequencesToID(keytipSequence));
if (this._keytipTree.currentKeytip) {
// Show all children keytips if any
const children = this._keytipTree.getChildren();
if (children.length) {
this.showKeytips(children);
}
if (this._keytipTree.currentKeytip.onExecute) {
this._keytipTree.currentKeytip.onExecute(
this._getKtpExecuteTarget(this._keytipTree.currentKeytip),
this._getKtpTarget(this._keytipTree.currentKeytip),
);
}
}
// Unset _newCurrKtpSequences
this._newCurrentKeytipSequences = undefined;
}
private _addKeytipToQueue(keytipID: string) {
// Add keytip
this._delayedKeytipQueue.push(keytipID);
// Clear timeout
this._delayedQueueTimeout && this._async.clearTimeout(this._delayedQueueTimeout);
// Reset timeout
this._delayedQueueTimeout = this._async.setTimeout(() => {
if (this._delayedKeytipQueue.length) {
this.showKeytips(this._delayedKeytipQueue);
this._delayedKeytipQueue = [];
}
}, 300);
}
private _removeKeytipFromQueue(keytipID: string) {
const index = this._delayedKeytipQueue.indexOf(keytipID);
if (index >= 0) {
// Remove keytip
this._delayedKeytipQueue.splice(index, 1);
// Clear timeout
this._delayedQueueTimeout && this._async.clearTimeout(this._delayedQueueTimeout);
// Reset timeout
this._delayedQueueTimeout = this._async.setTimeout(() => {
if (this._delayedKeytipQueue.length) {
this.showKeytips(this._delayedKeytipQueue);
this._delayedKeytipQueue = [];
}
}, 300);
}
}
private _getKtpExecuteTarget(currKtp: IKeytipTreeNode): HTMLElement | null {
return getDocument()!.querySelector(ktpTargetFromId(currKtp.id));
}
private _getKtpTarget(currKtp: IKeytipTreeNode): HTMLElement | null {
return getDocument()!.querySelector(ktpTargetFromSequences(currKtp.keySequences));
}
/**
* Returns T/F if the keytipProps keySequences match the currentKeytip, and the currentKeytip is in an overflow well
* This will make 'keytipProps' the new currentKeytip
*
* @param keytipProps - Keytip props to check
* @returns - T/F if this keytip should become the currentKeytip
*/
private _isCurrentKeytipAnAlias(keytipProps: IKeytipProps): boolean {
const currKtp = this._keytipTree.currentKeytip;
if (
currKtp &&
(currKtp.overflowSetSequence || currKtp.persisted) &&
arraysEqual(keytipProps.keySequences, currKtp.keySequences)
) {
return true;
}
return false;
}
/**
* Sets if we are in keytip mode.
* Note, this sets both the state for the layer as well as
* the value that the manager will expose externally.
* @param inKeytipMode - Boolean so set whether we are in keytip mode or not
*/
private _setInKeytipMode = (inKeytipMode: boolean): void => {
this.setState({ inKeytipMode: inKeytipMode });
this._keytipManager.inKeytipMode = inKeytipMode;
};
/**
* Emits a warning if duplicate keytips are found for the children of the current keytip
*/
private _warnIfDuplicateKeytips = (): void => {
const duplicateKeytips = this._getDuplicateIds(this._keytipTree.getChildren());
if (duplicateKeytips.length) {
warn('Duplicate keytips found for ' + duplicateKeytips.join(', '));
}
};
/**
* Returns duplicates among keytip IDs.
* If the returned array is empty, no duplicates were found.
*
* @param keytipIds - Array of keytip IDs to find duplicates for
* @returns - Array of duplicates that were found. Each duplicate will only be added once to this array.
*/
private _getDuplicateIds = (keytipIds: string[]): string[] => {
const seenIds: { [id: string]: number } = {};
return keytipIds.filter(keytipId => {
seenIds[keytipId] = seenIds[keytipId] ? seenIds[keytipId] + 1 : 1;
// Only add the first duplicate keytip seen
return seenIds[keytipId] === 2;
});
};
} | the_stack |
import '../../../src';
import G6 from '../../../src';
const div = document.createElement('div');
div.id = 'drag-combo-spec';
document.body.appendChild(div);
G6.registerCombo(
'custom-combo',
{
draw: (cfg, group) => {
const style = cfg.style || {};
const keyShape = group.addShape('circle', {
attrs: style,
className: 'circle-combo',
name: 'circle-combo',
draggable: true,
});
group.addShape('marker', {
attrs: {
x: 0, //keyShape.attr('r') + 5,
y: 0,
r: 5,
stroke: 'blue',
symbol: 'triangle-down',
},
name: 'marker-shape',
});
return keyShape;
},
update: (cfg, item) => {
const group = item.get('group');
if (cfg.markerStyle) {
const marker = group.find((ele) => ele.get('name') === 'marker-shape');
marker.attr(cfg.markerStyle);
}
const keyShape = group.get('children')[0];
keyShape.attr(cfg.style);
},
},
'circle-combo',
);
describe('drag-combo', () => {
it('drag combo', (done) => {
const data = {
nodes: [
{
id: 'node1',
x: 150,
y: 150,
label: 'node1',
comboId: 'A',
},
{
id: 'node2',
x: 200,
y: 250,
label: 'node2',
comboId: 'A',
},
{
id: 'node3',
x: 100,
y: 250,
label: 'node3',
},
{
id: 'node4',
x: 200,
y: 350,
label: 'node4',
comboId: 'B',
},
],
edges: [
{
source: 'node1',
target: 'node4',
},
{
source: 'node1',
target: 'node2',
},
{
source: 'node2',
target: 'node3',
},
],
combos: [
{
id: 'A',
parentId: 'C',
label: 'group A',
type: 'circle',
},
{
id: 'B',
parentId: 'C',
label: 'group B',
},
{
id: 'C',
label: 'group C',
// type: 'rect'
},
{
id: 'F',
label: 'group F',
// type: 'rect'
},
{
id: 'G',
label: 'group G',
// parentId: 'F'
type: 'custom-combo',
},
],
};
const graph = new G6.Graph({
container: 'drag-combo-spec',
width: 1000,
height: 800,
modes: {
default: ['drag-canvas', 'drag-combo'],
},
defaultCombo: {
// size: [100, 100],
// type: 'custom-combo',
style: {
fill: '#b5f5ec',
},
padding: 1
},
comboStateStyles: {
active: {
stroke: 'red',
},
selected: {
'text-shape': {
fill: '#f00',
fontSize: 20,
},
fill: '#36cfc9',
},
state2: {
stroke: '#0f0',
},
},
});
graph.data(data);
graph.render();
graph.on('combo:click', (e) => {
graph.setItemState(e.item, 'selected', true);
});
graph.on('canvas:click', (evt) => {
const combos = graph.findAllByState('combo', 'selected');
combos.map((combo) => {
graph.clearItemStates(combo);
});
});
const combo = graph.findById('A');
const comboC = graph.findById('C');
let comboCBBox = comboC.getKeyShape().getCanvasBBox();
expect(Math.abs(comboCBBox.width - 279) < 2).toBe(true);
graph.emit('combo:dragstart', { item: combo, x: 100, y: 100 });
graph.emit('combo:drag', { item: combo, x: 500, y: 100 });
comboCBBox = comboC.getKeyShape().getCanvasBBox();
expect(Math.abs(comboCBBox.width - 279) < 2).toBe(true);
graph.emit('combo:dragend', { item: combo, x: 500, y: 100 });
setTimeout(() => {
comboCBBox = comboC.getKeyShape().getCanvasBBox();
// setTimeout 有时候未变化完成
// expect(Math.abs(comboCBBox.width - 47) < 2).toBe(true);
graph.destroy();
done();
}, 800);
});
it('drag combo onlyChangeComboSize', (done) => {
const data = {
nodes: [
{
id: 'node1',
x: 150,
y: 150,
label: 'node1',
comboId: 'A',
},
{
id: 'node2',
x: 200,
y: 250,
label: 'node2',
comboId: 'A',
},
{
id: 'node3',
x: 100,
y: 250,
label: 'node3',
},
{
id: 'node4',
x: 200,
y: 350,
label: 'node4',
comboId: 'B',
},
],
edges: [
{
source: 'node1',
target: 'node4',
},
{
source: 'node1',
target: 'node2',
},
{
source: 'node2',
target: 'node3',
},
],
combos: [
{
id: 'A',
parentId: 'C',
label: 'group A',
type: 'circle',
},
{
id: 'B',
parentId: 'C',
label: 'group B',
},
{
id: 'C',
label: 'group C',
// type: 'rect'
},
{
id: 'F',
label: 'group F',
// type: 'rect'
},
{
id: 'G',
label: 'group G',
// parentId: 'F'
type: 'custom-combo',
},
],
};
const graph = new G6.Graph({
container: 'drag-combo-spec',
width: 1000,
height: 800,
modes: {
default: [
'drag-canvas',
{
type: 'drag-combo',
onlyChangeComboSize: true,
},
],
},
defaultCombo: {
// size: [100, 100],
// type: 'custom-combo',
style: {
fill: '#b5f5ec',
},
padding: 5
},
comboStateStyles: {
active: {
stroke: 'red',
},
selected: {
'text-shape': {
fill: '#f00',
fontSize: 20,
},
fill: '#36cfc9',
},
state2: {
stroke: '#0f0',
},
},
});
graph.data(data);
graph.render();
const combo = graph.findById('A');
const comboC = graph.findById('C');
let comboCBBox = comboC.getKeyShape().getCanvasBBox();
expect(Math.abs(comboCBBox.width - 298) < 2).toBe(true);
graph.emit('combo:dragstart', { item: combo, x: 100, y: 100 });
graph.emit('combo:drag', { item: combo, x: 500, y: 100 });
comboCBBox = comboC.getKeyShape().getCanvasBBox();
expect(Math.abs(comboCBBox.width - 298) < 2).toBe(true);
graph.emit('combo:dragend', { item: combo, x: 500, y: 100 });
setTimeout(() => {
comboCBBox = comboC.getKeyShape().getCanvasBBox();
// setTimeout 有时候未变化完成
// expect(Math.abs(comboCBBox.width - 541) < 2).toBe(true);
graph.destroy();
done();
}, 550);
});
it('combo example', () => {
const data = {
nodes: [
{
id: 'node1',
x: 150,
y: 150,
label: 'node1',
comboId: 'A',
},
{
id: 'node2',
x: 200,
y: 250,
label: 'node2',
comboId: 'B',
},
{
id: 'node3',
x: 100,
y: 250,
label: 'node3',
},
{
id: 'node4',
x: 50,
y: 50,
label: 'node4',
comboId: 'D',
},
{
id: 'node5',
x: 100,
y: 100,
label: 'node5',
comboId: 'E',
},
{
id: 'node6',
x: 500,
y: 200,
label: 'node6',
},
{
id: 'node7',
x: 600,
y: 200,
label: 'node7',
},
],
edges: [
{
source: 'node1',
target: 'node2',
},
{
source: 'node2',
target: 'node3',
},
{
source: 'node3',
target: 'node1',
},
{
source: 'A',
target: 'D',
},
],
combos: [
{
id: 'A',
parentId: 'B',
label: 'group A',
padding: [50, 30, 10, 10],
type: 'rect',
// style: {
// stroke: 'red',
// fill: 'green'
// },
// collapsed: true
},
{
id: 'B',
label: 'group B',
padding: [50, 10, 10, 50],
// type: 'custom-combo'
},
{
id: 'D',
label: 'group D',
parentId: 'E',
},
{
id: 'E',
// collapsed: true
},
{
id: 'FF',
label: '空分组',
// type: 'custom-combo',
// style: {
// stroke: 'green',
// lineWidth: 3
// }
},
],
};
const graph = new G6.Graph({
container: 'drag-combo-spec',
width: 1000,
height: 800,
groupByTypes: false,
modes: {
default: [
'drag-canvas',
{
type: 'drag-combo',
activeState: 'active',
},
{
type: 'drag-node',
comboActiveState: 'active',
},
'collapse-expand-combo',
'click-select',
],
},
defaultCombo: {
// size: [100, 100],
type: 'circle',
style: {
fill: '#f0f0f0',
stroke: '#bfbfbf',
},
},
comboStateStyles: {
selected: {
// 'text-shape': {
// fill: '#f00',
// fontSize: 20
// },
stroke: '#8c8c8c',
},
active: {
stroke: '#722ed1',
lineWidth: 2,
},
state2: {
stroke: '#0f0',
},
},
nodeStateStyles: {
selected: {
stroke: 'green',
lineWidth: 2,
},
},
defaultEdge: {
style: {
stroke: '#bfbfbf',
lineWidth: 2,
endArrow: true,
},
},
});
graph.data(data);
graph.render();
graph.on('nodeselectchange', (evt) => {
// console.log(evt);
});
// 删错 combo
// graph.on('combo:click', evt => {
// const { item } = evt
// graph.removeItem(item)
// })
// graph.on('combo:click', evt => {
// const { item } = evt
// graph.uncombo(item)
// })
// setTimeout(() => {
// graph.updateComboTree('D')
// }, 1000)
// graph.on('combo:mouseenter', evt => {
// const { item } = evt
// graph.setItemState(item, 'hover', true)
// })
// graph.on('combo:mouseleave', evt => {
// const { item } = evt
// graph.setItemState(item, 'hover', false)
// })
});
}); | the_stack |
import getValue from 'get-value'
import setValue from 'set-value'
import { objectHash } from '@jbrowse/core/util'
import { isSource, isTrack } from './util'
import { Config, Track, Source, Store, Names } from './types'
export function parseJB1Json(config: Config | string, url: string): Config {
if (typeof config === 'string') {
let parsedConf
try {
parsedConf = JSON.parse(config)
} catch (error) {
throw new Error(`${error} when parsing configuration.`)
}
return regularizeConf(parsedConf, url)
}
return regularizeConf(config, url)
}
export function parseJB1Conf(config: string, url: string): Config {
let parsedConf
try {
parsedConf = parse(config, url)
} catch (error) {
throw new Error(`${error} when parsing configuration.`)
}
return regularizeConf(parsedConf, url)
}
function isAlwaysArray(varName: string): boolean {
if (varName === 'include') {
return true
}
return false
}
function parse(text: string, url: string): Config {
let section: string[] = []
let keyPath: string[] | undefined
let operation: string
let value: string | undefined
const data: Config = { tracks: {} }
let lineNumber: number
function recordVal(): void {
if (value !== undefined) {
let parsedValue:
| string
| number
| boolean
| string[]
| number[]
| boolean[]
try {
// parse json
const match = value.match(/^json:(.+)/i)
if (match) {
parsedValue = JSON.parse(match[1])
}
// parse numbers if it looks numeric
else if (/^[+-]?[\d.,]+([eE][-+]?\d+)?$/.test(value)) {
parsedValue = parseFloat(value.replace(/,/g, ''))
} else {
parsedValue = value
}
if (!keyPath) {
throw new Error(`Error parsing in section ${section.join(' - ')}`)
}
const path = section.concat(keyPath).join('.')
if (operation === '+=') {
let existing = getValue(data, path)
if (existing) {
if (!Array.isArray(existing)) {
existing = [existing]
}
} else {
existing = []
}
existing.push(parsedValue)
parsedValue = existing
}
if (parsedValue === 'true') {
parsedValue = true
}
if (parsedValue === 'false') {
parsedValue = false
}
setValue(data, path, parsedValue)
} catch (e) {
throw new Error(
`syntax error${url ? ` in ${url}` : ''}${
lineNumber ? ` at line ${lineNumber - 1}` : ''
}`,
)
}
}
}
text.split('\n').forEach((textLine, i): void => {
lineNumber = i + 1
const line = textLine.replace(/^\s*#.+/, '')
// new section
let match: RegExpMatchArray | null
if ((match = line.match(/^\s*\[([^\]]+)/))) {
// new section
recordVal()
keyPath = undefined
value = undefined
section = match[1].trim().split(/\s*\.\s*/)
if (section.length === 1 && section[0].toLowerCase() === 'general') {
section = []
}
}
// new value
else if (
(match = line.match(
value === undefined ? /^([^+=]+)(\+?=)(.*)/ : /^(\S[^+=]+)(\+?=)(.*)/,
))
) {
recordVal()
keyPath = match[1].trim().split(/\s*\.\s*/)
;[, , operation] = match
if (isAlwaysArray(section.concat(keyPath).join('.'))) {
operation = '+='
}
value = match[3].trim()
}
// add to existing array value
else if (
keyPath !== undefined &&
(match = line.match(/^\s{0,4}\+\s*(.+)/))
) {
recordVal()
operation = '+='
value = match[1].trim()
}
// add to existing value
else if (value !== undefined && (match = line.match(/^\s+(\S.*)/))) {
value += value.length ? ` ${match[1].trim()}` : match[1].trim()
}
// done with last value
else {
recordVal()
keyPath = undefined
value = undefined
}
})
recordVal()
return data
}
/**
* Applies defaults and any other necessary tweaks to the loaded configuration.
* @param conf - the object containing the configuration, which it modifies
* in-place
* @param url - URL of the config file
* @returns the same object it was passed
*/
export function regularizeConf(conf: Config, url: string): Config {
// if tracks is not an array, convert it to one
if (conf.tracks && !Array.isArray(conf.tracks)) {
// if it's a single track config, wrap it in an arrayref
if (isTrack(conf.tracks)) {
conf.tracks = [conf.tracks]
}
// otherwise, coerce it to an array
else {
const tracks: Track[] = []
for (const label of Object.keys(conf.tracks)) {
const track = conf.tracks[label]
if (isTrack(track)) {
tracks.push(track)
} else {
tracks.push({ label, ...track })
}
}
conf.tracks = tracks
}
}
// regularize trackMetadata.sources
const meta = conf.trackMetadata
if (meta && meta.sources) {
// if it's a single source config, wrap it in an arrayref
if (typeof meta.sources === 'string') {
meta.sources = [meta.sources]
}
if (isSource(meta.sources)) {
meta.sources = [meta.sources]
}
if (!Array.isArray(meta.sources)) {
const sources: Source[] = []
for (const name of Object.keys(meta.sources)) {
const source = meta.sources[name]
if (!('name' in source)) {
source.name = name
}
sources.push(source)
}
meta.sources = sources
}
// coerce any string source defs to be URLs, and try to detect their types
meta.sources = meta.sources.map((sourceDef: string | Source): Source => {
if (typeof sourceDef === 'string') {
const newSourceDef: Source = { url: sourceDef }
const typeMatch = sourceDef.match(/\.(\w+)$/)
if (typeMatch) {
newSourceDef.type = typeMatch[1].toLowerCase()
}
return newSourceDef
}
return sourceDef
})
}
conf.sourceUrl = conf.sourceUrl || url
if (conf.sourceUrl.startsWith('/')) {
conf.sourceUrl = new URL(conf.sourceUrl, window.location.href).href
}
conf.baseUrl = conf.baseUrl || new URL('.', conf.sourceUrl).href
if (conf.baseUrl.length && !conf.baseUrl.endsWith('/')) {
conf.baseUrl += '/'
}
if (conf.sourceUrl) {
// set a default baseUrl in each of the track and store confs, and the names
// conf, if needed
const addBase: (Track | Store | Names)[] = []
if (conf.tracks) {
addBase.push(...conf.tracks)
}
if (conf.stores) {
addBase.push(...Object.values(conf.stores))
}
if (conf.names) {
addBase.push(conf.names)
}
addBase.forEach((t): void => {
if (!t.baseUrl) {
t.baseUrl = conf.baseUrl || '/'
}
})
// resolve the refSeqs and nameUrl if present
if (conf.refSeqs && typeof conf.refSeqs === 'string') {
conf.refSeqs = new URL(conf.refSeqs, conf.sourceUrl).href
}
if (conf.nameUrl) {
conf.nameUrl = new URL(conf.nameUrl, conf.sourceUrl).href
}
}
conf.stores = conf.stores || {}
;(conf.tracks || []).forEach((trackConfig: Track): void => {
// if there is a `config` subpart, just copy its keys in to the top-level
// config
if (trackConfig.config) {
const c = trackConfig.config
delete trackConfig.config
trackConfig = { ...c, ...trackConfig }
}
// skip if it's a new-style track def
if (trackConfig.store) {
return
}
let trackClassName: string
if (trackConfig.type === 'FeatureTrack') {
trackClassName = 'JBrowse/View/Track/HTMLFeatures'
} else if (trackConfig.type === 'ImageTrack') {
trackClassName = 'JBrowse/View/Track/FixedImage'
} else if (trackConfig.type === 'ImageTrack.Wiggle') {
trackClassName = 'JBrowse/View/Track/FixedImage/Wiggle'
} else if (trackConfig.type === 'SequenceTrack') {
trackClassName = 'JBrowse/View/Track/Sequence'
} else {
trackClassName = regularizeClass('JBrowse/View/Track', trackConfig.type)
}
trackConfig.type = trackClassName
synthesizeTrackStoreConfig(conf, trackConfig)
if (trackConfig.histograms) {
if (!trackConfig.histograms.baseUrl) {
trackConfig.histograms.baseUrl = trackConfig.baseUrl
}
synthesizeTrackStoreConfig(conf, trackConfig.histograms)
}
})
return conf
}
/**
* prefix class name with `root` if it contains no slashes
* @param root - Prefix root
* @param className - class name
*/
function regularizeClass(root: string, className: string | undefined): string {
if (!className) {
return ''
}
if (!className.includes('/')) {
className = `${root}/${className}`
}
className = className.replace(/^\//, '')
return className
}
function guessStoreClass(
trackConfig: Track | undefined,
urlTemplate: string,
): string {
if (!trackConfig) {
return ''
}
if (trackConfig.type && trackConfig.type.includes('/FixedImage')) {
return `JBrowse/Store/TiledImage/Fixed${
trackConfig.backendVersion === 0 ? '_v0' : ''
}`
}
if (/\.jsonz?$/i.test(urlTemplate)) {
return `JBrowse/Store/SeqFeature/NCList${
trackConfig.backendVersion === 0 ? '_v0' : ''
}`
}
if (/\.bam$/i.test(urlTemplate)) {
return 'JBrowse/Store/SeqFeature/BAM'
}
if (/\.cram$/i.test(urlTemplate)) {
return 'JBrowse/Store/SeqFeature/CRAM'
}
if (/\.gff3?$/i.test(urlTemplate)) {
return 'JBrowse/Store/SeqFeature/GFF3'
}
if (/\.bed$/i.test(urlTemplate)) {
return 'JBrowse/Store/SeqFeature/BED'
}
if (/\.vcf.b?gz$/i.test(urlTemplate)) {
return 'JBrowse/Store/SeqFeature/VCFTabix'
}
if (/\.gff3?.b?gz$/i.test(urlTemplate)) {
return 'JBrowse/Store/SeqFeature/GFF3Tabix'
}
if (/\.bed.b?gz$/i.test(urlTemplate)) {
return 'JBrowse/Store/SeqFeature/BEDTabix'
}
if (/\.(bw|bigwig)$/i.test(urlTemplate)) {
return 'JBrowse/Store/SeqFeature/BigWig'
}
if (/\.(bb|bigbed)$/i.test(urlTemplate)) {
return 'JBrowse/Store/SeqFeature/BigBed'
}
if (/\.(fa|fasta)$/i.test(urlTemplate)) {
return 'JBrowse/Store/SeqFeature/IndexedFasta'
}
if (/\.(fa|fasta)\.b?gz$/i.test(urlTemplate)) {
return 'JBrowse/Store/SeqFeature/BgzipIndexedFasta'
}
if (/\.2bit$/i.test(urlTemplate)) {
return 'JBrowse/Store/SeqFeature/TwoBit'
}
if (trackConfig.type && trackConfig.type.endsWith('/Sequence')) {
return 'JBrowse/Store/Sequence/StaticChunked'
}
return ''
}
function synthesizeTrackStoreConfig(
mainConf: Config,
trackConfig: Track,
): void {
// figure out what data store class to use with the track, applying some
// defaults if it is not explicit in the configuration
const { urlTemplate = '' } = trackConfig
let storeClass: string
if (trackConfig.storeClass) {
storeClass = regularizeClass('JBrowse/Store', trackConfig.storeClass)
} else {
storeClass = guessStoreClass(trackConfig, urlTemplate)
}
if (!storeClass) {
console.warn(
`Unable to determine an appropriate data store to use with track '${trackConfig.label}', please explicitly specify a storeClass in the configuration.`,
)
return
}
// synthesize a separate store conf
const storeConf: Store = { ...trackConfig, type: storeClass }
// if this is the first sequence store we see, and we have no refseqs store
// defined explicitly, make this the refseqs store.
if (
(storeClass === 'JBrowse/Store/Sequence/StaticChunked' ||
storeClass === 'JBrowse/Store/Sequence/IndexedFasta' ||
storeClass === 'JBrowse/Store/SeqFeature/IndexedFasta' ||
storeClass === 'JBrowse/Store/SeqFeature/BgzipIndexedFasta' ||
storeClass === 'JBrowse/Store/SeqFeature/TwoBit' ||
storeClass === 'JBrowse/Store/Sequence/TwoBit' ||
trackConfig.useAsRefSeqStore) &&
!(mainConf.stores && mainConf.stores.refseqs)
) {
storeConf.name = 'refseqs'
} else {
storeConf.name = `store${objectHash(storeConf)}`
}
// record it
if (!mainConf.stores) {
mainConf.stores = {}
}
mainConf.stores[storeConf.name] = storeConf
// connect it to the track conf
trackConfig.store = storeConf.name
} | the_stack |
import merge from 'lodash/merge';
import Language from './language';
import {
BlockModelInterface,
CardEntry,
CardModelInterface,
ClipboardInterface,
CommandInterface,
ConversionInterface,
EditorInterface,
EditorOptions,
EventInterface,
EventListener,
InlineModelInterface,
LanguageInterface,
MarkModelInterface,
NodeIdInterface,
NodeInterface,
NodeModelInterface,
PluginEntry,
PluginModelInterface,
RangeInterface,
RequestInterface,
SchemaInterface,
Selector,
} from './types';
import { ListModelInterface } from './types/list';
import language from './locales';
import NodeModel, { $, Event } from './node';
import Command from './command';
import Plugin from './plugin';
import Schema from './schema';
import schemaDefaultData from './constants/schema';
import Conversion from './parser/conversion';
import conversionDefault from './constants/conversion';
import CardModel from './card';
import NodeId from './node/id';
import Clipboard from './clipboard';
import Request from './request';
import List from './list';
import Mark from './mark';
import Inline from './inline';
import Block from './block';
import Range from './range';
import {
CARD_ELEMENT_KEY,
CARD_KEY,
DATA_ELEMENT,
DATA_ID,
ROOT,
} from './constants';
import { isEngine } from './utils';
import Parser from './parser';
class Editor<T extends EditorOptions = EditorOptions>
implements EditorInterface<T>
{
readonly kind: 'editor' | 'engine' | 'view' = 'editor';
options: T = {
lang: 'zh-CN',
locale: {},
plugins: [] as PluginEntry[],
cards: [] as CardEntry[],
config: {},
iconFonts:
"url('//at.alicdn.com/t/font_1456030_lnqmc6a6ca.woff2?t=1638071536645') format('woff2'), url('//at.alicdn.com/t/font_1456030_lnqmc6a6ca.woff?t=1638071536645') format('woff'), url('//at.alicdn.com/t/font_1456030_lnqmc6a6ca.ttf?t=1638071536645') format('truetype')",
} as T;
readonly container: NodeInterface;
language: LanguageInterface;
root: NodeInterface;
card: CardModelInterface;
plugin: PluginModelInterface;
node: NodeModelInterface;
nodeId: NodeIdInterface;
list: ListModelInterface;
mark: MarkModelInterface;
inline: InlineModelInterface;
block: BlockModelInterface;
event: EventInterface;
schema: SchemaInterface;
conversion: ConversionInterface;
command: CommandInterface;
clipboard: ClipboardInterface;
request: RequestInterface;
#_scrollNode: NodeInterface | null = null;
get scrollNode(): NodeInterface | null {
if (this.#_scrollNode) return this.#_scrollNode;
const { scrollNode } = this.options;
let sn = scrollNode
? typeof scrollNode === 'function'
? scrollNode()
: scrollNode
: null;
// 查找父级样式 overflow 或者 overflow-y 为 auto 或者 scroll 的节点
const targetValues = ['auto', 'scroll'];
let parent = this.container.parent();
while (!sn && parent && parent.length > 0 && parent.name !== 'body') {
if (
targetValues.includes(parent.css('overflow')) ||
targetValues.includes(parent.css('overflow-y'))
) {
sn = parent.get<HTMLElement>();
break;
} else {
parent = parent.parent();
}
}
if (sn === null) sn = document.documentElement;
this.#_scrollNode = sn ? $(sn) : null;
return this.#_scrollNode;
}
constructor(selector: Selector, options?: EditorOptions) {
this.options = { ...this.options, ...options };
let { iconFonts } = this.options;
let fontElement = document.querySelector('#am-iconfont');
if (!fontElement && iconFonts !== false) {
fontElement = document.createElement('style');
fontElement.setAttribute('type', 'text/css');
fontElement.setAttribute('id', 'am-iconfont');
let fontsStyle = '@font-face { font-family: "data-icon";';
if (Array.isArray(iconFonts)) {
iconFonts = iconFonts
.map(
(font) => `url('${font.url}') format('${font.format}')`,
)
.join(',');
}
fontsStyle += `src: ${iconFonts};}`;
fontElement.innerHTML = fontsStyle;
document.head.appendChild(fontElement);
}
this.container = $(selector);
this.container.attributes(DATA_ELEMENT, ROOT);
// 多语言
this.language = new Language(
this.options.lang || 'zh-CN',
merge(language, options?.locale),
);
// 事件管理
this.event = new Event();
// 命令
this.command = new Command(this);
// 节点规则
this.schema = new Schema();
this.schema.add(schemaDefaultData);
// 节点转换规则
this.conversion = new Conversion(this);
conversionDefault.forEach((rule) =>
this.conversion.add(rule.from, rule.to),
);
// 卡片
this.card = new CardModel(this, this.options.lazyRender);
// 剪贴板
this.clipboard = new Clipboard(this);
// http请求
this.request = new Request();
// 插件
this.plugin = new Plugin(this);
// 节点管理
this.node = new NodeModel(this);
this.nodeId = new NodeId(this.schema);
// 列表
this.list = new List(this);
// 样式标记
this.mark = new Mark(this);
// 行内样式
this.inline = new Inline(this);
// 块级节点
this.block = new Block(this);
// 编辑器父节点
this.root = $(
this.options.root || this.container.parent() || document.body,
);
const rootPosition = this.root.css('position');
if (!rootPosition || rootPosition === 'static')
this.root.css('position', 'relative');
}
init() {
// 实例化插件
this.mark.init();
this.inline.init();
this.block.init();
this.list.init();
this.card.init(this.options.cards || []);
this.plugin.init(this.options.plugins || [], this.options.config || {});
this.nodeId.init();
}
setScrollNode(node?: HTMLElement) {
this.#_scrollNode = node ? $(node) : null;
}
on<R = any, F extends EventListener<R> = EventListener<R>>(
eventType: string,
listener: F,
rewrite?: boolean,
) {
this.event.on(eventType, listener, rewrite);
return this;
}
off(eventType: string, listener: EventListener) {
this.event.off(eventType, listener);
return this;
}
trigger<R = any>(eventType: string, ...args: any): R {
return this.event.trigger<R>(eventType, ...args);
}
messageSuccess(type: string, message: string, ...args: any[]) {
console.log(type, `success:${message}`, ...args);
}
messageError(type: string, error: string, ...args: any[]) {
console.error(type, `error:${error}`, ...args);
}
messageConfirm(
type: string,
message: string,
...args: any[]
): Promise<boolean> {
console.log(type, `confirm:${message}`, ...args);
return Promise.reject(false);
}
getSelectionData(
range?: RangeInterface,
): Record<'html' | 'text', string> | undefined {
if (!range) range = Range.from(this) ?? undefined;
if (!range) return;
range = range.cloneRange(); //.shrinkToElementNode();
let card = range.startNode.closest(`[${CARD_KEY}]`, (node) => {
return $(node).isEditable()
? undefined
: node.parentNode || undefined;
});
if (card.length > 0 && !range.collapsed && range.endOffset === 0) {
if (range.endContainer.previousSibling) {
range.setEndAfter(range.endContainer.previousSibling);
}
if (
!range.collapsed &&
range.endOffset > 0 &&
range.endContainer.childNodes[range.endOffset - 1] === card[0]
) {
const cardCenter = range.startNode.closest(
`[${CARD_ELEMENT_KEY}="center"]`,
(node) => {
return $(node).isEditable()
? undefined
: node.parentNode || undefined;
},
);
if (cardCenter.length > 0) {
range.setEnd(
cardCenter[0],
cardCenter[0].childNodes.length,
);
} else {
range.setEnd(card[0], card[0].childNodes.length);
}
}
}
let root = range.commonAncestorNode;
card = root.closest(`[${CARD_KEY}]`, (node) => {
return $(node).isEditable()
? undefined
: node.parentNode || undefined;
});
if (card.length > 0) {
const cardCenter = root.closest(
`[${CARD_ELEMENT_KEY}="center"]`,
(node) => {
return $(node).isEditable()
? undefined
: node.parentNode || undefined;
},
);
if (cardCenter.length === 0) {
range.select(card);
root = range.commonAncestorNode;
}
}
if (!root.inEditor() && !root.isRoot()) return;
if (range.collapsed) {
return;
}
const setNodes = (nodes: Node[]) => {
if (0 === nodes.length) return {};
for (let i = nodes.length - 1; i > 0; i--) {
const node = nodes[i];
node.appendChild(nodes[i - 1]);
}
return {
inner: nodes[0],
outter: nodes[nodes.length - 1],
};
};
card = root.closest(`[${CARD_KEY}]`, (node) => {
return node.parentNode || undefined;
});
if (card.length > 0) {
const compnoent = this.card.find(card);
if (compnoent && compnoent.getSelectionNodes) {
const nodes = compnoent.getSelectionNodes();
if (nodes.length > 0) {
const { inner, outter } = setNodes(
nodes.map((node) => node[0]),
);
let html = nodes.map((node) => node.html()).join('');
const parser = new Parser(`<div>${html}</div>`, this);
html = parser.toHTML(inner, outter);
const text = new Parser(html, this).toText(
this.schema,
true,
);
return { html, text };
}
} else if (!compnoent?.isEditable) return;
}
const { node, list } = this;
// 修复自定义列表选择范围
let customizeStartItem: NodeInterface | undefined;
const li = range.startNode.closest('li');
if (li && node.isCustomize(li)) {
const endLi = range.endNode.closest('li');
if (
!li.equal(endLi) ||
(list.isLast(range) && list.isFirst(range))
) {
if (list.isFirst(range)) {
const ul = li.parent();
const index = li.getIndex();
if (ul) range.setStart(ul, index < 0 ? 0 : index);
} else {
const ul = li.parent();
// 选在列表项靠后的节点,把剩余节点拼接成完成的列表项
const selection = range.createSelection();
const rightNode = selection.getNode(li, 'center', true);
selection.anchor?.remove();
selection.focus?.remove();
if (isEngine(this)) this.change.combinText();
if (rightNode.length > 0) {
let isRemove = false;
rightNode.each((_, index) => {
const item = rightNode.eq(index);
if (!isRemove && item?.name === 'li') {
isRemove = true;
return;
}
if (isRemove) item?.remove();
});
const card = li.first();
const component = card
? this.card.find(card)
: undefined;
if (component) {
customizeStartItem = rightNode;
this.list.addCardToCustomize(
customizeStartItem,
component.name,
component.getValue(),
);
if (ul) node.wrap(customizeStartItem, ul?.clone());
}
}
}
}
}
const contents = range.enlargeToElementNode(true).cloneContents();
// 复制纯文本,获取外层的样式包裹层
const nodes: Node[] = [];
if (
root.isText() &&
contents.childNodes.length === 1 &&
contents.firstChild?.nodeType === Node.TEXT_NODE
) {
let parent = root.parent();
while (parent && (node.isMark(parent) || node.isInline(parent))) {
nodes.push(parent.clone(false).get<Node>()!);
parent = parent.parent();
}
}
// if (customizeStartItem) {
// contents.removeChild(contents.childNodes[0]);
// contents.prepend(customizeStartItem[0]);
// }
const listMergeBlocks: NodeInterface[] = [];
contents.querySelectorAll('li').forEach((child) => {
const childElement = $(child);
const dataId = childElement.attributes(DATA_ID);
if (!dataId) return;
const curentElement = this.container
.get<HTMLElement>()
?.querySelector(`[${DATA_ID}=${dataId}]`);
// 补充自定义列表丢失的卡片
if (
node.isCustomize(childElement) &&
!childElement.first()?.isCard() &&
curentElement?.firstChild
) {
childElement.prepend(
node.clone($(curentElement.firstChild), true, false),
);
}
let parent: NodeInterface | Node | null | undefined =
curentElement?.parentElement;
parent = parent ? $(parent.cloneNode(false)) : null;
const childParent = child.parentElement;
if (
curentElement &&
parent &&
node.isList(parent) &&
(!childParent || !node.isList(childParent))
) {
if (parent.name === 'ol') {
// 设置复制位置的 start 属性,默认不设置
// let start = parseInt(parent.attributes('start') || '0', 10)
// start = $(curentElement).index() + start
// if(start === 0) start = 1
// parent.attributes('start', start);
parent.removeAttributes('start');
}
node.wrap(child, parent);
listMergeBlocks.push(parent);
}
});
const { inner, outter } = setNodes(nodes);
const listNodes: NodeInterface[] = [];
contents.childNodes.forEach((child) => {
const childNode = $(child);
if (node.isList(childNode) || childNode.name === 'li') {
listNodes.push(childNode);
}
});
this.nodeId.generateAll($(contents), true);
// 合并列表
this.list.merge(listNodes);
const parser = new Parser(contents, this);
let html = parser.toHTML(inner, outter);
const text = new Parser(html, this).toText(this.schema, true);
return { html, text };
}
destroy() {
this.container.removeAttributes(DATA_ELEMENT);
this.event.destroy();
this.plugin.destroy();
this.card.destroy();
this.container.empty();
}
}
export default Editor; | the_stack |
import {Axis, DynamicCstr} from '../rule_engine/dynamic_cstr';
import {MathCompoundStore} from '../rule_engine/math_simple_store';
import {SpeechRuleEngine} from '../rule_engine/speech_rule_engine';
import {ClearspeakPreferences} from '../speech_rules/clearspeak_preferences';
import {Debugger} from './debugger';
import {EngineConst, SREError} from './engine';
import {ProcessorFactory} from './processors';
import * as System from './system';
import SystemExternal from './system_external';
import {Variables} from './variables';
export class Cli {
public process: any = SystemExternal.extRequire('process');
public setup: {[key: string]: string|boolean};
public processors: string[] = [];
public dp: DOMParser;
constructor() {
this.setup = {'mode': EngineConst.Mode.SYNC};
this.dp = new SystemExternal.xmldom.DOMParser({
errorHandler: function(_key: string, _msg: string) {
throw new SREError('XML DOM error!');
}
});
}
/**
* Sets parameters for the speech rule engine.
* @param arg The option to set.
* @param value The cli option value.
* @param def The default for the option.
*/
public set(arg: string, value: string|boolean, _def: string) {
this.setup[arg] = typeof value === 'undefined' ? true : value;
}
/**
* Registers processors for input files.
* @param v Unused parameter.
* @param processor A processor method.
*/
public processor(_v: string, processor: string) {
this.processors.push(processor);
}
/**
* Prints information on axes values.
*/
public enumerate(all: boolean = false) {
System.setupEngine(this.setup);
if (all) {
for (let loc of Variables.LOCALES) {
System.setupEngine({locale: loc});
}
}
let length = DynamicCstr.DEFAULT_ORDER.map(x => x.length);
let maxLength = (obj: any, index: number) => {
length[index] = Math.max.apply(
null,
Object.keys(obj)
.map(function(x) {
return x.length;
})
.concat(length[index]));
};
let compStr = (str: string, length: number) =>
str + (new Array(length - str.length + 1)).join(' ');
// TODO (TS): Sort out the any type.
let dynamic: any = SpeechRuleEngine.getInstance().enumerate();
dynamic = MathCompoundStore.enumerate(dynamic);
let table = [];
maxLength(dynamic, 0);
for (let ax1 in dynamic) {
let clear1 = true;
let dyna1 = dynamic[ax1];
maxLength(dyna1, 1);
for (let ax2 in dyna1) {
let clear2 = true;
let dyna2 = dyna1[ax2];
maxLength(dyna2, 2);
for (let ax3 in dyna2) {
let styles = Object.keys(dyna2[ax3]).sort();
if (ax3 === 'clearspeak') {
let clear3 = true;
let prefs =
ClearspeakPreferences.getLocalePreferences(dynamic)[ax1];
for (let ax4 in prefs) {
table.push([
compStr(clear1 ? ax1 : '', length[0]),
compStr(clear2 ? ax2 : '', length[1]),
compStr(clear3 ? ax3 : '', length[2]), prefs[ax4].join(', ')
]);
clear1 = false;
clear2 = false;
clear3 = false;
}
} else {
table.push([
compStr(clear1 ? ax1 : '', length[0]),
compStr(clear2 ? ax2 : '', length[1]), compStr(ax3, length[2]),
styles.join(', ')
]);
}
clear1 = false;
clear2 = false;
}
}
}
let i = 0;
let output = '';
output += DynamicCstr.DEFAULT_ORDER
.slice(0, // No topics yet.
-1)
.map((x: string) => compStr(x, length[i++]))
.join(' | ');
output += '\n';
length.forEach((x: number) => output += (new Array(x + 3)).join('='));
output += '========================\n';
output += table.map((x) => x.join(' | ')).join('\n');
console.info(output);
}
/**
* Executes all processors on a single file.
* @param input The name of the input file.
*/
public execute(input: string) {
let options = SystemExternal.commander.opts();
this.runProcessors_((proc, file) => {
System.file.processFile(proc, file, options.output);
}, input);
}
/**
* Readline functionality for CLI. Reads an expression from the command line
* and runs the given processors on it. Result is either printed to stdout or
* to the given output file.
*/
public readline() {
let options = SystemExternal.commander.opts();
this.process.stdin.setEncoding('utf8');
let inter = SystemExternal.extRequire('readline').createInterface({
input: this.process.stdin,
output: options.output ?
SystemExternal.fs.createWriteStream(options.output) :
this.process.stdout
});
let input = '';
inter.on('line', ((expr: string) => {
input += expr;
if (this.readExpression_(input)) {
inter.close();
}
}).bind(this));
inter.on('close', (() => {
this.runProcessors_((proc, expr) => {
inter.output.write(ProcessorFactory.output(proc, expr) + '\n');
}, input);
}).bind(this));
}
/**
* Method for the command line interface of the Speech Rule Engine
*/
public commandLine() {
let commander = SystemExternal.commander;
let system = System;
let set = ((key: string) => {
return (val: string, def: string) => this.set(key, val, def);
}).bind(this);
let processor = this.processor.bind(this);
commander.version(system.version)
.usage('[options] <file ...>')
.option('-i, --input [name]', 'Input file [name]. (Deprecated)')
.option(
'-o, --output [name]', 'Output file [name]. Defaults to stdout.')
.option(
'-d, --domain [name]',
'Speech rule set [name]. See --options' +
' for details.',
set(Axis.DOMAIN),
DynamicCstr.DEFAULT_VALUES[Axis.DOMAIN])
.option(
'-t, --style [name]',
'Speech style [name]. See --options' +
' for details.',
set(Axis.STYLE),
DynamicCstr.DEFAULT_VALUES[Axis.STYLE])
.option(
'-c, --locale [code]', 'Locale [code].',
set(Axis.LOCALE),
DynamicCstr.DEFAULT_VALUES[Axis.LOCALE])
.option(
'-b, --modality [name]', 'Modality [name].',
set(Axis.MODALITY),
DynamicCstr.DEFAULT_VALUES[Axis.MODALITY])
.option(
'-k, --markup [name]', 'Generate speech output with markup tags.',
set('markup'), 'none')
.option(
'-r, --rate [value]',
'Base rate [value] for tagged speech' +
' output.',
set('rate'), '100')
.option(
'-p, --speech', 'Generate speech output (default).', processor,
'speech')
.option(
'-a, --audit', 'Generate auditory descriptions (JSON format).',
processor, 'description')
.option(
'-j, --json', 'Generate JSON of semantic tree.', processor, 'json')
.option(
'-x, --xml', 'Generate XML of semantic tree.', processor,
'semantic')
.option(
'-m, --mathml', 'Generate enriched MathML.', processor, 'enriched')
.option(
'-g, --generate <depth>',
'Include generated speech in enriched' +
' MathML (with -m option only).',
set('speech'), 'none')
.option(
'-w, --structure',
'Include structure attribute in enriched' +
' MathML (with -m option only).',
set('structure'))
.option(
'-P, --pprint', 'Pretty print output whenever possible.',
set('pprint'))
.option(
'-f, --rules [name]', 'Loads a local rule file [name].',
set('rules'))
.option(
'-C, --prune [branch]', 'Prune trie [branch] for clean reload.',
set('prune'))
.option('-v, --verbose', 'Verbose mode.')
.option('-l, --log [name]', 'Log file [name].')
.option('--opt', 'List engine setup options.')
.option('--opt-all', 'List engine setup options for all available locales.')
.on('option:opt', () => {
this.enumerate();
System.exit(0);
})
.on('option:opt-all', () => {
this.enumerate(true);
System.exit(0);
})
.parse(this.process.argv);
System.setupEngine(this.setup);
let options = commander.opts();
if (options.verbose) {
Debugger.getInstance().init(options.log);
}
if (options.input) {
this.execute(options.input);
}
if (commander.args.length) {
commander.args.forEach(this.execute.bind(this));
} else {
this.readline();
}
Debugger.getInstance().exit(function() {
System.exit(0);
});
}
/**
* Runs processor methods on the given input.
* @param processor Name of a processor.
* @param input The input expression or file name
*/
private runProcessors_(
processor: (p1: string, p2: string) => any, input: string) {
try {
if (!this.processors.length) {
this.processors.push('speech');
}
if (input) {
this.processors.forEach(function(proc) {
processor(proc, input);
});
}
} catch (err) {
console.error(err.name + ': ' + err.message);
Debugger.getInstance().exit(function() {
this.process.exit(1);
});
}
}
/**
* Checks if the input expression is already complete.
* @param input The current input on the CLI.
* @return True if input is a complete XML expression.
*/
private readExpression_(input: string): boolean {
try {
let testInput = input.replace(/(&|#|;)/g, '');
this.dp.parseFromString(testInput, 'text/xml');
} catch (err) {
return false;
}
return true;
}
} | the_stack |
import type { languages } from '../fillers/monaco-editor-core';
export const conf: languages.LanguageConfiguration = {
comments: {
lineComment: '--',
blockComment: ['/*', '*/']
},
brackets: [
['{', '}'],
['[', ']'],
['(', ')']
],
autoClosingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '"', close: '"' },
{ open: "'", close: "'" }
],
surroundingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '"', close: '"' },
{ open: "'", close: "'" }
]
};
export const language = <languages.IMonarchLanguage>{
defaultToken: '',
tokenPostfix: '.sql',
ignoreCase: true,
brackets: [
{ open: '[', close: ']', token: 'delimiter.square' },
{ open: '(', close: ')', token: 'delimiter.parenthesis' }
],
keywords: [
'AES128',
'AES256',
'ALL',
'ALLOWOVERWRITE',
'ANALYSE',
'ANALYZE',
'AND',
'ANY',
'ARRAY',
'AS',
'ASC',
'AUTHORIZATION',
'BACKUP',
'BETWEEN',
'BINARY',
'BLANKSASNULL',
'BOTH',
'BY',
'BYTEDICT',
'BZIP2',
'CASE',
'CAST',
'CHECK',
'COLLATE',
'COLUMN',
'CONSTRAINT',
'CREATE',
'CREDENTIALS',
'CROSS',
'CURRENT_DATE',
'CURRENT_TIME',
'CURRENT_TIMESTAMP',
'CURRENT_USER',
'CURRENT_USER_ID',
'DEFAULT',
'DEFERRABLE',
'DEFLATE',
'DEFRAG',
'DELTA',
'DELTA32K',
'DESC',
'DISABLE',
'DISTINCT',
'DO',
'ELSE',
'EMPTYASNULL',
'ENABLE',
'ENCODE',
'ENCRYPT',
'ENCRYPTION',
'END',
'EXCEPT',
'EXPLICIT',
'FALSE',
'FOR',
'FOREIGN',
'FREEZE',
'FROM',
'FULL',
'GLOBALDICT256',
'GLOBALDICT64K',
'GRANT',
'GROUP',
'GZIP',
'HAVING',
'IDENTITY',
'IGNORE',
'ILIKE',
'IN',
'INITIALLY',
'INNER',
'INTERSECT',
'INTO',
'IS',
'ISNULL',
'JOIN',
'LEADING',
'LEFT',
'LIKE',
'LIMIT',
'LOCALTIME',
'LOCALTIMESTAMP',
'LUN',
'LUNS',
'LZO',
'LZOP',
'MINUS',
'MOSTLY13',
'MOSTLY32',
'MOSTLY8',
'NATURAL',
'NEW',
'NOT',
'NOTNULL',
'NULL',
'NULLS',
'OFF',
'OFFLINE',
'OFFSET',
'OID',
'OLD',
'ON',
'ONLY',
'OPEN',
'OR',
'ORDER',
'OUTER',
'OVERLAPS',
'PARALLEL',
'PARTITION',
'PERCENT',
'PERMISSIONS',
'PLACING',
'PRIMARY',
'RAW',
'READRATIO',
'RECOVER',
'REFERENCES',
'RESPECT',
'REJECTLOG',
'RESORT',
'RESTORE',
'RIGHT',
'SELECT',
'SESSION_USER',
'SIMILAR',
'SNAPSHOT',
'SOME',
'SYSDATE',
'SYSTEM',
'TABLE',
'TAG',
'TDES',
'TEXT255',
'TEXT32K',
'THEN',
'TIMESTAMP',
'TO',
'TOP',
'TRAILING',
'TRUE',
'TRUNCATECOLUMNS',
'UNION',
'UNIQUE',
'USER',
'USING',
'VERBOSE',
'WALLET',
'WHEN',
'WHERE',
'WITH',
'WITHOUT'
],
operators: [
'AND',
'BETWEEN',
'IN',
'LIKE',
'NOT',
'OR',
'IS',
'NULL',
'INTERSECT',
'UNION',
'INNER',
'JOIN',
'LEFT',
'OUTER',
'RIGHT'
],
builtinFunctions: [
'current_schema',
'current_schemas',
'has_database_privilege',
'has_schema_privilege',
'has_table_privilege',
'age',
'current_time',
'current_timestamp',
'localtime',
'isfinite',
'now',
'ascii',
'get_bit',
'get_byte',
'set_bit',
'set_byte',
'to_ascii',
'approximate percentile_disc',
'avg',
'count',
'listagg',
'max',
'median',
'min',
'percentile_cont',
'stddev_samp',
'stddev_pop',
'sum',
'var_samp',
'var_pop',
'bit_and',
'bit_or',
'bool_and',
'bool_or',
'cume_dist',
'first_value',
'lag',
'last_value',
'lead',
'nth_value',
'ratio_to_report',
'dense_rank',
'ntile',
'percent_rank',
'rank',
'row_number',
'case',
'coalesce',
'decode',
'greatest',
'least',
'nvl',
'nvl2',
'nullif',
'add_months',
'at time zone',
'convert_timezone',
'current_date',
'date_cmp',
'date_cmp_timestamp',
'date_cmp_timestamptz',
'date_part_year',
'dateadd',
'datediff',
'date_part',
'date_trunc',
'extract',
'getdate',
'interval_cmp',
'last_day',
'months_between',
'next_day',
'sysdate',
'timeofday',
'timestamp_cmp',
'timestamp_cmp_date',
'timestamp_cmp_timestamptz',
'timestamptz_cmp',
'timestamptz_cmp_date',
'timestamptz_cmp_timestamp',
'timezone',
'to_timestamp',
'trunc',
'abs',
'acos',
'asin',
'atan',
'atan2',
'cbrt',
'ceil',
'ceiling',
'checksum',
'cos',
'cot',
'degrees',
'dexp',
'dlog1',
'dlog10',
'exp',
'floor',
'ln',
'log',
'mod',
'pi',
'power',
'radians',
'random',
'round',
'sin',
'sign',
'sqrt',
'tan',
'to_hex',
'bpcharcmp',
'btrim',
'bttext_pattern_cmp',
'char_length',
'character_length',
'charindex',
'chr',
'concat',
'crc32',
'func_sha1',
'initcap',
'left and rights',
'len',
'length',
'lower',
'lpad and rpads',
'ltrim',
'md5',
'octet_length',
'position',
'quote_ident',
'quote_literal',
'regexp_count',
'regexp_instr',
'regexp_replace',
'regexp_substr',
'repeat',
'replace',
'replicate',
'reverse',
'rtrim',
'split_part',
'strpos',
'strtol',
'substring',
'textlen',
'translate',
'trim',
'upper',
'cast',
'convert',
'to_char',
'to_date',
'to_number',
'json_array_length',
'json_extract_array_element_text',
'json_extract_path_text',
'current_setting',
'pg_cancel_backend',
'pg_terminate_backend',
'set_config',
'current_database',
'current_user',
'current_user_id',
'pg_backend_pid',
'pg_last_copy_count',
'pg_last_copy_id',
'pg_last_query_id',
'pg_last_unload_count',
'session_user',
'slice_num',
'user',
'version',
'abbrev',
'acosd',
'any',
'area',
'array_agg',
'array_append',
'array_cat',
'array_dims',
'array_fill',
'array_length',
'array_lower',
'array_ndims',
'array_position',
'array_positions',
'array_prepend',
'array_remove',
'array_replace',
'array_to_json',
'array_to_string',
'array_to_tsvector',
'array_upper',
'asind',
'atan2d',
'atand',
'bit',
'bit_length',
'bound_box',
'box',
'brin_summarize_new_values',
'broadcast',
'cardinality',
'center',
'circle',
'clock_timestamp',
'col_description',
'concat_ws',
'convert_from',
'convert_to',
'corr',
'cosd',
'cotd',
'covar_pop',
'covar_samp',
'current_catalog',
'current_query',
'current_role',
'currval',
'cursor_to_xml',
'diameter',
'div',
'encode',
'enum_first',
'enum_last',
'enum_range',
'every',
'family',
'format',
'format_type',
'generate_series',
'generate_subscripts',
'get_current_ts_config',
'gin_clean_pending_list',
'grouping',
'has_any_column_privilege',
'has_column_privilege',
'has_foreign_data_wrapper_privilege',
'has_function_privilege',
'has_language_privilege',
'has_sequence_privilege',
'has_server_privilege',
'has_tablespace_privilege',
'has_type_privilege',
'height',
'host',
'hostmask',
'inet_client_addr',
'inet_client_port',
'inet_merge',
'inet_same_family',
'inet_server_addr',
'inet_server_port',
'isclosed',
'isempty',
'isopen',
'json_agg',
'json_object',
'json_object_agg',
'json_populate_record',
'json_populate_recordset',
'json_to_record',
'json_to_recordset',
'jsonb_agg',
'jsonb_object_agg',
'justify_days',
'justify_hours',
'justify_interval',
'lastval',
'left',
'line',
'localtimestamp',
'lower_inc',
'lower_inf',
'lpad',
'lseg',
'make_date',
'make_interval',
'make_time',
'make_timestamp',
'make_timestamptz',
'masklen',
'mode',
'netmask',
'network',
'nextval',
'npoints',
'num_nonnulls',
'num_nulls',
'numnode',
'obj_description',
'overlay',
'parse_ident',
'path',
'pclose',
'percentile_disc',
'pg_advisory_lock',
'pg_advisory_lock_shared',
'pg_advisory_unlock',
'pg_advisory_unlock_all',
'pg_advisory_unlock_shared',
'pg_advisory_xact_lock',
'pg_advisory_xact_lock_shared',
'pg_backup_start_time',
'pg_blocking_pids',
'pg_client_encoding',
'pg_collation_is_visible',
'pg_column_size',
'pg_conf_load_time',
'pg_control_checkpoint',
'pg_control_init',
'pg_control_recovery',
'pg_control_system',
'pg_conversion_is_visible',
'pg_create_logical_replication_slot',
'pg_create_physical_replication_slot',
'pg_create_restore_point',
'pg_current_xlog_flush_location',
'pg_current_xlog_insert_location',
'pg_current_xlog_location',
'pg_database_size',
'pg_describe_object',
'pg_drop_replication_slot',
'pg_export_snapshot',
'pg_filenode_relation',
'pg_function_is_visible',
'pg_get_constraintdef',
'pg_get_expr',
'pg_get_function_arguments',
'pg_get_function_identity_arguments',
'pg_get_function_result',
'pg_get_functiondef',
'pg_get_indexdef',
'pg_get_keywords',
'pg_get_object_address',
'pg_get_owned_sequence',
'pg_get_ruledef',
'pg_get_serial_sequence',
'pg_get_triggerdef',
'pg_get_userbyid',
'pg_get_viewdef',
'pg_has_role',
'pg_identify_object',
'pg_identify_object_as_address',
'pg_index_column_has_property',
'pg_index_has_property',
'pg_indexam_has_property',
'pg_indexes_size',
'pg_is_in_backup',
'pg_is_in_recovery',
'pg_is_other_temp_schema',
'pg_is_xlog_replay_paused',
'pg_last_committed_xact',
'pg_last_xact_replay_timestamp',
'pg_last_xlog_receive_location',
'pg_last_xlog_replay_location',
'pg_listening_channels',
'pg_logical_emit_message',
'pg_logical_slot_get_binary_changes',
'pg_logical_slot_get_changes',
'pg_logical_slot_peek_binary_changes',
'pg_logical_slot_peek_changes',
'pg_ls_dir',
'pg_my_temp_schema',
'pg_notification_queue_usage',
'pg_opclass_is_visible',
'pg_operator_is_visible',
'pg_opfamily_is_visible',
'pg_options_to_table',
'pg_postmaster_start_time',
'pg_read_binary_file',
'pg_read_file',
'pg_relation_filenode',
'pg_relation_filepath',
'pg_relation_size',
'pg_reload_conf',
'pg_replication_origin_create',
'pg_replication_origin_drop',
'pg_replication_origin_oid',
'pg_replication_origin_progress',
'pg_replication_origin_session_is_setup',
'pg_replication_origin_session_progress',
'pg_replication_origin_session_reset',
'pg_replication_origin_session_setup',
'pg_replication_origin_xact_reset',
'pg_replication_origin_xact_setup',
'pg_rotate_logfile',
'pg_size_bytes',
'pg_size_pretty',
'pg_sleep',
'pg_sleep_for',
'pg_sleep_until',
'pg_start_backup',
'pg_stat_file',
'pg_stop_backup',
'pg_switch_xlog',
'pg_table_is_visible',
'pg_table_size',
'pg_tablespace_databases',
'pg_tablespace_location',
'pg_tablespace_size',
'pg_total_relation_size',
'pg_trigger_depth',
'pg_try_advisory_lock',
'pg_try_advisory_lock_shared',
'pg_try_advisory_xact_lock',
'pg_try_advisory_xact_lock_shared',
'pg_ts_config_is_visible',
'pg_ts_dict_is_visible',
'pg_ts_parser_is_visible',
'pg_ts_template_is_visible',
'pg_type_is_visible',
'pg_typeof',
'pg_xact_commit_timestamp',
'pg_xlog_location_diff',
'pg_xlog_replay_pause',
'pg_xlog_replay_resume',
'pg_xlogfile_name',
'pg_xlogfile_name_offset',
'phraseto_tsquery',
'plainto_tsquery',
'point',
'polygon',
'popen',
'pqserverversion',
'query_to_xml',
'querytree',
'quote_nullable',
'radius',
'range_merge',
'regexp_matches',
'regexp_split_to_array',
'regexp_split_to_table',
'regr_avgx',
'regr_avgy',
'regr_count',
'regr_intercept',
'regr_r2',
'regr_slope',
'regr_sxx',
'regr_sxy',
'regr_syy',
'right',
'row_security_active',
'row_to_json',
'rpad',
'scale',
'set_masklen',
'setseed',
'setval',
'setweight',
'shobj_description',
'sind',
'sprintf',
'statement_timestamp',
'stddev',
'string_agg',
'string_to_array',
'strip',
'substr',
'table_to_xml',
'table_to_xml_and_xmlschema',
'tand',
'text',
'to_json',
'to_regclass',
'to_regnamespace',
'to_regoper',
'to_regoperator',
'to_regproc',
'to_regprocedure',
'to_regrole',
'to_regtype',
'to_tsquery',
'to_tsvector',
'transaction_timestamp',
'ts_debug',
'ts_delete',
'ts_filter',
'ts_headline',
'ts_lexize',
'ts_parse',
'ts_rank',
'ts_rank_cd',
'ts_rewrite',
'ts_stat',
'ts_token_type',
'tsquery_phrase',
'tsvector_to_array',
'tsvector_update_trigger',
'tsvector_update_trigger_column',
'txid_current',
'txid_current_snapshot',
'txid_snapshot_xip',
'txid_snapshot_xmax',
'txid_snapshot_xmin',
'txid_visible_in_snapshot',
'unnest',
'upper_inc',
'upper_inf',
'variance',
'width',
'width_bucket',
'xml_is_well_formed',
'xml_is_well_formed_content',
'xml_is_well_formed_document',
'xmlagg',
'xmlcomment',
'xmlconcat',
'xmlelement',
'xmlexists',
'xmlforest',
'xmlparse',
'xmlpi',
'xmlroot',
'xmlserialize',
'xpath',
'xpath_exists'
],
builtinVariables: [
// NOT SUPPORTED
],
pseudoColumns: [
// NOT SUPPORTED
],
tokenizer: {
root: [
{ include: '@comments' },
{ include: '@whitespace' },
{ include: '@pseudoColumns' },
{ include: '@numbers' },
{ include: '@strings' },
{ include: '@complexIdentifiers' },
{ include: '@scopes' },
[/[;,.]/, 'delimiter'],
[/[()]/, '@brackets'],
[
/[\w@#$]+/,
{
cases: {
'@keywords': 'keyword',
'@operators': 'operator',
'@builtinVariables': 'predefined',
'@builtinFunctions': 'predefined',
'@default': 'identifier'
}
}
],
[/[<>=!%&+\-*/|~^]/, 'operator']
],
whitespace: [[/\s+/, 'white']],
comments: [
[/--+.*/, 'comment'],
[/\/\*/, { token: 'comment.quote', next: '@comment' }]
],
comment: [
[/[^*/]+/, 'comment'],
// Not supporting nested comments, as nested comments seem to not be standard?
// i.e. http://stackoverflow.com/questions/728172/are-there-multiline-comment-delimiters-in-sql-that-are-vendor-agnostic
// [/\/\*/, { token: 'comment.quote', next: '@push' }], // nested comment not allowed :-(
[/\*\//, { token: 'comment.quote', next: '@pop' }],
[/./, 'comment']
],
pseudoColumns: [
[
/[$][A-Za-z_][\w@#$]*/,
{
cases: {
'@pseudoColumns': 'predefined',
'@default': 'identifier'
}
}
]
],
numbers: [
[/0[xX][0-9a-fA-F]*/, 'number'],
[/[$][+-]*\d*(\.\d*)?/, 'number'],
[/((\d+(\.\d*)?)|(\.\d+))([eE][\-+]?\d+)?/, 'number']
],
strings: [[/'/, { token: 'string', next: '@string' }]],
string: [
[/[^']+/, 'string'],
[/''/, 'string'],
[/'/, { token: 'string', next: '@pop' }]
],
complexIdentifiers: [[/"/, { token: 'identifier.quote', next: '@quotedIdentifier' }]],
quotedIdentifier: [
[/[^"]+/, 'identifier'],
[/""/, 'identifier'],
[/"/, { token: 'identifier.quote', next: '@pop' }]
],
scopes: [
// NOT SUPPORTED
]
}
}; | the_stack |
import YAML from 'yaml';
import {
YAMLConfiguration,
YAMLConfigurationPage,
YAMLConfigurationMenuTree,
YAMLConfigurationDependencyMap,
YAMLConfigurationGlobalMap,
YAMLConfigurationGroupMap,
YAMLConfigurationResourceMap,
YAMLConfigurationPageTree,
YAMLConfigurationMeta,
YAMLConfigurationUsageContext,
YAMLConfigurationQuantity,
YAMLConfigurationNarrative,
YAMLConfigurationRange,
YAMLConfigurationReference,
YAMLConfigurationIdentifier
} from './YAMLConfiguration';
import {
Configuration,
ConfigurationGroup,
ConfigurationResource,
ConfigurationMenuItem,
ConfigurationHistory,
ConfigurationHistoryItem,
ConfigurationInstanceOptions
} from '../fshtypes/Configuration';
import { logger } from '../utils/FSHLogger';
import { parseCodeLexeme } from './parseCodeLexeme';
import {
ImplementationGuideGlobal,
ImplementationGuideDefinitionPage,
ImplementationGuideDefinitionParameter,
ContactDetail,
ImplementationGuideDependsOn,
Meta,
Coding,
Narrative,
ContactPoint,
CodeableConcept,
UsageContext,
Quantity,
Range,
Identifier,
Reference,
ImplementationGuideDefinitionTemplate
} from '../fhirtypes';
import { FshCode } from '../fshtypes';
import { YAMLConfigurationInstanceOptions } from '.';
const MINIMAL_CONFIG_PROPERTIES = ['canonical', 'fhirVersion'];
// Properties that are only relevant when an IG is going to be generated from output, and have no informational purpose
const MINIMAL_IG_ONLY_PROPERTIES = ['id', 'name', 'status', 'copyrightYear', 'releaseLabel'];
const IG_ONLY_PROPERTIES = [
'contained',
'extension',
'modifierExtension',
'groups',
'resources',
'pages',
'parameters',
'template',
'templates',
'menu',
'copyrightyear',
'copyrightYear',
'releaseLabel',
'releaselabel'
];
/**
* Imports the YAML Configuration format (as a YAML string or already parsed JSON) and returns
* the normalized FSH Configuration object.
* @param {YAMLConfiguration | string} yaml - the YAML config as a string or JSON document
* @param {string} file - the path to the configuration file (used for logging source info)
* @returns {Configuration} - the FSH configuration representing the parsed config
*/
export function importConfiguration(yaml: YAMLConfiguration | string, file: string): Configuration {
if (typeof yaml === 'string') {
let parsed: YAMLConfiguration;
try {
parsed = YAML.parse(yaml);
} catch (e) {
logger.error(`Error parsing configuration: ${e.message}.`, { file });
throw new Error('Invalid configuration YAML');
}
if (typeof parsed !== 'object' || parsed === null) {
logger.error('Configuration is not a valid YAML object.', { file });
throw new Error('Invalid configuration YAML');
}
return importConfiguration(parsed, file);
}
// There are a few properties that are absolutely required if we are to have *any* success at all
const minimalProperties = yaml.FSHOnly
? MINIMAL_CONFIG_PROPERTIES
: [...MINIMAL_CONFIG_PROPERTIES, ...MINIMAL_IG_ONLY_PROPERTIES];
const missingProperties = minimalProperties.filter(
(p: keyof YAMLConfiguration) =>
yaml[p] == null || (Array.isArray(yaml[p]) && (yaml[p] as any[]).length === 0)
);
// the copyrightYear and releaseLabel properties permit alternate spellings as all lowercase,
// so if only those are missing, check for the lowercase version before logging an error.
if (missingProperties.includes('copyrightYear') && yaml.copyrightyear) {
missingProperties.splice(missingProperties.indexOf('copyrightYear'), 1);
}
if (missingProperties.includes('releaseLabel') && yaml.releaselabel) {
missingProperties.splice(missingProperties.indexOf('releaseLabel'), 1);
}
if (missingProperties.length > 0) {
logger.error(
`SUSHI minimally requires the following configuration properties to ${
yaml.FSHOnly ? 'start processing FSH' : 'generate an IG'
}: ` +
minimalProperties.join(', ') +
'.',
{ file }
);
throw new Error('Minimal config not met');
}
const config: Configuration = {
filePath: file,
canonical: yaml.canonical, // minimum config property
id: yaml.id, // minimum config property
meta: parseMeta(yaml.meta, file),
implicitRules: yaml.implicitRules,
language: parseSimpleCode(yaml.language, 'language', file),
text: parseText(yaml.text, file),
contained: yaml.contained,
extension: yaml.extension,
modifierExtension: yaml.modifierExtension,
url: yaml.url ?? `${yaml.canonical}/ImplementationGuide/${yaml.id}`,
version: normalizeToString(yaml.version), // minimum config property
name: required(yaml.name, 'name', file),
title: yaml.title,
status: parseCodeWithRequiredValues(
required(yaml.status, 'status', file),
['draft', 'active', 'retired', 'unknown'],
'status',
file
),
experimental: yaml.experimental,
date: normalizeToString(yaml.date),
publisher: normalizeToArray(yaml.publisher)?.[0]?.name,
contact: parseContact(yaml, file),
description: yaml.description,
useContext: parseUsageContext(yaml.useContext, file),
jurisdiction: parseJurisdiction(yaml.jurisdiction, file),
copyright: yaml.copyright,
packageId: yaml.packageId ?? yaml.id,
license: parseSimpleCode(yaml.license, 'license', file),
fhirVersion: normalizeToArray(yaml.fhirVersion)?.map(v =>
parseSimpleCode(v, 'fhirVersion', file)
), // minimum config property
dependencies: parseDependencies(yaml.dependencies),
global: parseGlobal(yaml.global),
groups: parseGroups(yaml.groups),
resources: parseResources(yaml.resources, file),
pages: parsePages(yaml.pages, file),
parameters: parseParameters(yaml, yaml.FSHOnly, file),
templates: parseTemplates(yaml.templates, file),
template: yaml.template,
menu: parseMenu(yaml.menu),
history: parseHistory(yaml, file),
indexPageContent: yaml.indexPageContent,
FSHOnly: yaml.FSHOnly ?? false,
applyExtensionMetadataToRoot: yaml.applyExtensionMetadataToRoot ?? true,
instanceOptions: parseInstanceOptions(yaml.instanceOptions, file)
};
// Remove all undefined variables (mainly helpful for test assertions)
removeUndefinedValues(config);
if (yaml.FSHOnly) {
// If no IG is being generated, emit warning when IG specific properties are used in config
const unusedProperties = Object.keys(yaml).filter((p: keyof YAMLConfiguration) =>
IG_ONLY_PROPERTIES.includes(p)
);
if (unusedProperties.length > 0) {
logger.warn(
`The FSHOnly property is set to true, so no output specific to IG creation will be generated. The following properties are unused and only relevant for IG creation: ${unusedProperties.join(
', '
)}.`,
{ file }
);
}
}
return config;
}
function required<T>(value: T, property: string, file: string): T {
if (value == null || (Array.isArray(value) && value.length === 0)) {
logger.error(`Configuration missing required property: ${property}`, { file });
}
return value;
}
function normalizeToString(yamlValue: any): string {
if (yamlValue == null) {
return;
}
return `${yamlValue}`;
}
function normalizeToArray<T>(yamlValue?: T | T[]): T[] | null | undefined {
if (yamlValue == null) {
return;
}
return Array.isArray(yamlValue) ? yamlValue : [yamlValue];
}
function parseSimpleCode(yamlCode: string, property: string, file: string): string {
return yamlCode?.startsWith('#') ? parseFshCode(yamlCode, property, file)?.code : yamlCode;
}
function parseFshCode(yamlCode: string, property: string, file: string): FshCode {
// If it has a display, we need to split it out and handle it separately
const m = yamlCode.match(/^(.*\S)(\s+"(([^"]|\\")*)")$/);
if (m) {
const concept = parseCodeLexeme(m[1]);
concept.display = m[3].replace(/\\"/g, '"');
return concept;
}
const concept = parseCodeLexeme(yamlCode);
if (concept.system == null && concept.code === '') {
logger.error(`Invalid code format for ${property}: ${yamlCode}`, { file });
// don't return an invalid code
return;
}
return concept;
}
function parseCodingArray(codings: (Coding | string)[], property: string, file: string): Coding[] {
if (codings == null) {
return;
}
const result = codings?.map(c => parseCoding(c, property, file)).filter(c => c != null);
if (result.length === 0 && codings.length > 0) {
// in the case that all inputs were invalid, return undefined instead of empty array
return;
}
return result;
}
function parseCoding(coding: Coding | string, property: string, file: string): Coding {
if (coding == null) {
return;
}
if (typeof coding === 'string') {
return parseFshCode(coding, property, file)?.toFHIRCoding();
}
// It's a coding object
const fixed: Coding = {
...coding,
version: normalizeToString(coding.version),
code: parseSimpleCode(coding.code, property, file)
};
return removeUndefinedValues(fixed);
}
function parseCodeableConceptArray(
concepts: (CodeableConcept | string)[],
property: string,
file: string
): CodeableConcept[] {
if (concepts == null) {
return;
}
const result = concepts?.map(c => parseCodeableConcept(c, property, file)).filter(c => c != null);
if (result.length === 0 && concepts.length > 0) {
// in the case that all inputs were invalid, return undefined instead of empty array
return;
}
return result;
}
function parseCodeableConcept(
concept: CodeableConcept | string,
property: string,
file: string
): CodeableConcept {
if (concept == null) {
return;
}
if (typeof concept === 'string') {
const coding = parseCoding(concept, property, file);
if (coding == null) {
// return undefined instead of an empty concept
return;
}
return {
coding: [coding]
};
}
// It's a CodeableConcept object
const fixed: CodeableConcept = {
...concept,
coding: parseCodingArray(concept.coding, property, file)
};
return removeUndefinedValues(fixed);
}
function parseCodeWithRequiredValues<T extends string>(
yamlCode: string,
allowedValues: T[],
property: string,
file: string
): T {
if (yamlCode == null) {
return;
}
const code = parseSimpleCode(yamlCode, property, file);
const match = allowedValues.find(c => c === code);
if (match) {
return match;
}
logger.error(
`Invalid ${property} value: '${code}'. Must be one of: ${allowedValues
.map(c => `'${c}'`)
.join(',')}.`,
{
file
}
);
}
function parseQuantity(
yamlQuantity: YAMLConfigurationQuantity | string,
property: string,
file: string
): Quantity {
if (yamlQuantity == null) {
return;
}
if (typeof yamlQuantity === 'string') {
const m = yamlQuantity.match(/^(\d*(\.\d+)?)(\s+'([^']+)')?$/);
if (m == null) {
logger.error(`Invalid ${property} value: ${yamlQuantity}`, { file });
return;
}
const quantity: Quantity = {
value: parseFloat(m[1])
};
if (m[4] && m[4].length > 0) {
quantity.system = 'http://unitsofmeasure.org';
quantity.code = m[4];
}
return quantity;
}
const quantity: Quantity = {
...yamlQuantity,
code: parseSimpleCode(yamlQuantity.code, `${property}.code`, file),
comparator: parseCodeWithRequiredValues(
yamlQuantity.comparator,
['<', '<=', '>=', '>'],
`${property}.comparator`,
file
)
};
removeUndefinedValues(quantity);
return quantity;
}
function parseRange(yamlRange: YAMLConfigurationRange, property: string, file: string): Range {
if (yamlRange == null) {
return;
}
const range: Range = {
...yamlRange,
low: parseQuantity(yamlRange.low, `${property}.low`, file),
high: parseQuantity(yamlRange.high, `${property}.high`, file)
};
removeUndefinedValues(range);
return range;
}
function parseReference(
yamlReference: YAMLConfigurationReference,
property: string,
file: string
): Reference {
if (yamlReference == null) {
return;
}
const reference: Reference = {
...yamlReference,
identifier: parseIdentifier(yamlReference.identifier, `${property}.identifier`, file)
};
removeUndefinedValues(reference);
return reference;
}
function parseIdentifier(
yamlIdentifier: YAMLConfigurationIdentifier,
property: string,
file: string
): Identifier {
if (yamlIdentifier == null) {
return;
}
const identifier: Identifier = {
...yamlIdentifier,
use: parseCodeWithRequiredValues(
yamlIdentifier.use,
['usual', 'official', 'temp', 'secondary', 'old'],
`${property}.use`,
file
),
type: parseCodeableConcept(yamlIdentifier.type, `${property}.type`, file),
assigner: parseReference(yamlIdentifier.assigner, `${property}.assigner`, file)
};
removeUndefinedValues(identifier);
return identifier;
}
function parseMeta(yamlMeta: YAMLConfigurationMeta, file: string): Meta {
if (yamlMeta == null) {
return;
}
const fixed = {
...yamlMeta,
security: parseCodingArray(yamlMeta.security, 'meta.security', file),
tag: parseCodingArray(yamlMeta.tag, 'meta.tag', file)
};
return removeUndefinedValues(fixed);
}
function parseText(yamlText: YAMLConfigurationNarrative, file: string): Narrative {
if (yamlText == null) {
return;
}
const fixed: Narrative = {
...yamlText,
status: parseCodeWithRequiredValues(
yamlText.status,
['generated', 'extensions', 'additional', 'empty'],
'text.status',
file
)
};
return removeUndefinedValues(fixed);
}
function parseContact(yamlConfig: YAMLConfiguration, file: string): ContactDetail[] {
const contacts: ContactDetail[] = [];
const publishers = normalizeToArray(yamlConfig.publisher);
if (publishers) {
publishers.forEach((p, i) => {
const contact: ContactDetail = { name: p.name };
if (p.url || p.email) {
contact.telecom = [];
if (p.url) {
contact.telecom.push({ system: 'url', value: p.url });
}
if (p.email) {
contact.telecom.push({ system: 'email', value: p.email });
}
} else if (i === 0) {
// This was the first publisher and there was no additional contact detail, so skip it
return;
}
contacts.push(contact);
});
}
if (yamlConfig.contact) {
contacts.push(
...normalizeToArray(yamlConfig.contact).map(yamlContact => {
const contact: ContactDetail = {
...yamlContact,
telecom: normalizeToArray(yamlContact.telecom).map(yamlTelecom => {
const contactPoint: ContactPoint = {
...yamlTelecom,
system: parseCodeWithRequiredValues(
yamlTelecom.system,
['phone', 'fax', 'email', 'pager', 'url', 'sms', 'other'],
'contact.telecom.system',
file
),
use: parseCodeWithRequiredValues(
yamlTelecom.use,
['home', 'work', 'temp', 'old', 'mobile'],
'contact.telecom.use',
file
)
};
removeUndefinedValues(contactPoint);
return contactPoint;
})
};
if (contact.telecom.length === 0) {
delete contact.telecom;
}
return contact;
})
);
}
if (contacts.length === 0) {
return;
}
return contacts;
}
function parseUsageContext(
yamlUsageContext: YAMLConfigurationUsageContext | YAMLConfigurationUsageContext[],
file: string
): UsageContext[] {
return normalizeToArray(yamlUsageContext)?.map(yaml => {
const usageContext: UsageContext = {
code: parseCoding(required(yaml.code, 'useContext.code', file), 'useContext.code', file),
valueCodeableConcept: parseCodeableConcept(
yaml.valueCodeableConcept,
'useContext.valueCodeableConcept',
file
),
valueQuantity: parseQuantity(yaml.valueQuantity, 'useContext.valueQuantity', file),
valueRange: parseRange(yaml.valueRange, 'useContext.valueRange', file),
valueReference: parseReference(yaml.valueReference, 'useContext.valueReference', file)
};
const valueFields = [
'valueCodeableConcept',
'valueQuantity',
'valueRange',
'valueReference'
].filter((v: keyof UsageContext) => yaml[v] != null);
if (valueFields.length === 0) {
// at least one is required, so force the 'required' error
required(undefined, 'useContext.value[x]', file);
} else if (valueFields.length > 1) {
// more than one value is not allowed since it is a value[x] choice
logger.error(
`Only one useContext.value[x] is allowed but found multiple: ${valueFields.join(', ')}`,
{
file
}
);
}
removeUndefinedValues(usageContext);
return usageContext;
});
}
function parseJurisdiction(
yamlJurisdiction: CodeableConcept | string | (CodeableConcept | string)[],
file: string
): CodeableConcept[] {
return parseCodeableConceptArray(normalizeToArray(yamlJurisdiction), 'jurisdiction', file);
}
function parseDependencies(
yamlDependencies: YAMLConfigurationDependencyMap
): ImplementationGuideDependsOn[] {
if (yamlDependencies == null) {
return;
}
return Object.entries(yamlDependencies).map(([packageId, versionOrDetails]) => {
if (/[A-Z]/.test(packageId)) {
logger.warn(
`${packageId} contains uppercase characters, which is discouraged. SUSHI will use ${packageId.toLowerCase()} as the package name.`
);
packageId = packageId.toLowerCase();
}
if (typeof versionOrDetails === 'string' || typeof versionOrDetails === 'number') {
return { packageId, version: `${versionOrDetails}` };
} else if (versionOrDetails == null) {
// this is an error condition, but we'll just make it an incomplete dependency and
// handle the error later
return { packageId };
}
// else it's the complex object
return removeUndefinedValues({
id: versionOrDetails.id,
packageId,
uri: versionOrDetails.uri,
version:
typeof versionOrDetails.version === 'string' || typeof versionOrDetails.version === 'number'
? `${versionOrDetails.version}`
: undefined
});
});
}
function parseGlobal(yamlGlobal: YAMLConfigurationGlobalMap): ImplementationGuideGlobal[] {
if (yamlGlobal == null) {
return;
}
const global: ImplementationGuideGlobal[] = [];
for (const [type, profiles] of Object.entries(yamlGlobal)) {
normalizeToArray(profiles).forEach(profile => global.push({ type, profile }));
}
return global;
}
function parseGroups(yamlGroups: YAMLConfigurationGroupMap): ConfigurationGroup[] {
if (yamlGroups == null) {
return;
}
return Object.entries(yamlGroups).map(([id, groupObj]) => {
if (groupObj.name === undefined) {
groupObj.name = id;
}
return {
id: id,
name: groupObj.name,
description: groupObj.description,
resources: groupObj.resources
};
});
}
function parseResources(
yamlResources: YAMLConfigurationResourceMap,
file: string
): ConfigurationResource[] {
if (yamlResources == null) {
return;
}
return Object.entries(yamlResources).map(([reference, details]) => {
if (details === 'omit' || details === '#omit') {
return { reference: { reference }, omit: true };
}
return {
reference: { reference },
...details,
fhirVersion: normalizeToArray(details.fhirVersion)?.map(v =>
parseSimpleCode(v, `resource[${reference}].fhirVersion`, file)
)
};
});
}
function parsePages(
yamlPages: YAMLConfigurationPageTree,
file: string
): ImplementationGuideDefinitionPage[] {
if (yamlPages == null) {
return;
}
return Object.entries(yamlPages).map(([nameUrl, details]) => {
return parsePage(nameUrl, details, `pages[${nameUrl}]`, file);
});
}
function parsePage(
nameUrl: string,
details: YAMLConfigurationPage,
property: string,
file: string
): ImplementationGuideDefinitionPage {
const page: ImplementationGuideDefinitionPage = { nameUrl };
if (details?.title) {
page.title = details.title;
}
if (details?.generation) {
page.generation = parseCodeWithRequiredValues(
details.generation,
['html', 'markdown', 'xml', 'generated'],
`${property}.generation`,
file
);
}
if (details != null) {
Object.entries(details).forEach(([key, value]) => {
if (key == 'title' || key == 'generation') {
return;
}
if (page.page == null) {
page.page = [];
}
page.page.push(parsePage(key, value as YAMLConfigurationPage, `${property}[${key}]`, file));
});
}
return page;
}
function parseParameters(
yamlConfig: YAMLConfiguration,
FSHOnly: boolean,
file: string
): ImplementationGuideDefinitionParameter[] {
const parameters: ImplementationGuideDefinitionParameter[] = [];
// copyrightYear and releaseLabel are only required when generating an IG
const copyrightYear = FSHOnly
? yamlConfig.copyrightYear ?? yamlConfig.copyrightyear
: required(yamlConfig.copyrightYear ?? yamlConfig.copyrightyear, 'copyrightYear', file);
const releaseLabel = FSHOnly
? yamlConfig.releaseLabel ?? yamlConfig.releaselabel
: required(yamlConfig.releaseLabel ?? yamlConfig.releaselabel, 'releaseLabel', file);
if (copyrightYear) {
parameters.push({
code: 'copyrightyear',
value: copyrightYear.toString()
});
}
if (releaseLabel) {
parameters.push({
code: 'releaselabel',
value: releaseLabel
});
}
if (yamlConfig.parameters) {
for (const [code, values] of Object.entries(yamlConfig.parameters)) {
normalizeToArray(values).forEach(value => parameters.push({ code, value: `${value}` }));
}
} else if (parameters.length === 0) {
return; // return undefined rather than an empty []
}
return parameters;
}
function parseTemplates(
yamlTemplates: ImplementationGuideDefinitionTemplate | ImplementationGuideDefinitionTemplate[],
file: string
): ImplementationGuideDefinitionTemplate[] {
return normalizeToArray(yamlTemplates)?.map(t => {
const template: ImplementationGuideDefinitionTemplate = {
...t,
code: parseSimpleCode(required(t.code, 'templates.code', file), 'templates.code', file),
source: required(t.source, 'templates.source', file)
};
removeUndefinedValues(template);
return template;
});
}
function parseMenu(yamlMenu: YAMLConfigurationMenuTree): ConfigurationMenuItem[] {
if (yamlMenu == null) {
return;
}
return Object.entries(yamlMenu).map(([name, value]) => {
const item: ConfigurationMenuItem = { name };
if (typeof value === 'string') {
// Set menu item attributes based on keywords
if (value.includes('new-tab ')) {
item.openInNewTab = true;
value = value.replace('new-tab', '');
}
if (value.includes('external ')) {
logger.warn(
'The "external" keyword in menu configuration has been deprecated. The IG Publisher' +
' will detect external links and add the external link icon automatically. To resolve' +
` this warning, remove the "external" keyword from the "${name}" menu item.`
);
value = value.replace('external', '');
}
// Trim off any white space left after using keywords. URL is remaining value.
item.url = value.trim();
} else {
item.subMenu = parseMenu(value);
}
return item;
});
}
function parseHistory(yamlConfig: YAMLConfiguration, file: string): ConfigurationHistory {
const yamlHistory = yamlConfig.history;
if (yamlHistory == null) {
return;
}
const history: ConfigurationHistory = {
'package-id': yamlHistory['package-id'] ?? yamlConfig.packageId ?? yamlConfig.id,
canonical: yamlHistory.canonical ?? yamlConfig.canonical,
title: yamlHistory.title ?? yamlConfig.title,
introduction: yamlHistory.introduction ?? yamlConfig.description,
list: []
};
if (yamlHistory.current) {
if (typeof yamlHistory.current === 'string') {
history.list.push({
version: 'current',
desc: 'Continuous Integration Build (latest in version control)',
path: yamlHistory.current,
status: 'ci-build',
current: true
});
} else {
history.list.push({
version: 'current',
date: normalizeToString(yamlHistory.current.date),
desc:
yamlHistory.current.desc ?? 'Continuous Integration Build (latest in version control)',
path: required(yamlHistory.current.path, 'history[current].path', file),
changes: yamlHistory.current.changes,
status: parseCodeWithRequiredValues(
yamlHistory.current.status ?? 'ci-build',
allowedHistoryStatus,
'history[current].status',
file
),
sequence: yamlHistory.current.sequence,
fhirversion: yamlHistory.current.fhirversion,
current: yamlHistory.current.current ?? true
});
}
}
for (const [key, value] of Object.entries(yamlHistory)) {
if (['package-id', 'canonical', 'title', 'introduction', 'current'].indexOf(key) !== -1) {
continue;
}
const item = value as ConfigurationHistoryItem;
history.list.push({
version: key,
date: required(item.date, `history[${key}].date`, file),
desc: required(item.desc, `history[${key}].desc`, file),
path: required(item.path, `history[${key}].path`, file),
changes: item.changes,
status: parseCodeWithRequiredValues(
required(item.status, `history[${key}].status`, file),
allowedHistoryStatus,
`history[${key}].status`,
file
),
sequence: required(item.sequence, `history[${key}].sequence`, file),
fhirversion: required(item.fhirversion, `history[${key}].fhirVersion`, file),
current: item.current
});
}
history.list.forEach(item => removeUndefinedValues(item));
return history;
}
const allowedHistoryStatus: ConfigurationHistoryItem['status'][] = [
'ci-build',
'preview',
'ballot',
'trial-use',
'update',
'normative',
'trial-use+normative'
];
function parseInstanceOptions(
yamlInstanceOptions: YAMLConfigurationInstanceOptions,
file: string
): ConfigurationInstanceOptions {
return {
setMetaProfile:
parseCodeWithRequiredValues(
yamlInstanceOptions?.setMetaProfile,
['always', 'never', 'inline-only', 'standalone-only'],
'instanceOptions.setMetaProfile',
file
) || 'always',
setId:
parseCodeWithRequiredValues(
yamlInstanceOptions?.setId,
['always', 'standalone-only'],
'instanceOptions.setId',
file
) || 'always'
};
}
function removeUndefinedValues<T extends object>(incoming: T): T {
Object.keys(incoming).forEach((k: string) => {
// @ts-ignore Element implicitly has an 'any' type
if (typeof incoming[k] === 'undefined') {
// @ts-ignore Element implicitly has an 'any' type
delete incoming[k];
}
});
return incoming;
} | the_stack |
import './folder_node.js';
import './item.js';
import {assert} from 'chrome://resources/js/assert.m.js';
import {EventTracker} from 'chrome://resources/js/event_tracker.m.js';
import {isTextInputElement} from 'chrome://resources/js/util.m.js';
import {changeFolderOpen, deselectItems, selectItem} from './actions.js';
import {highlightUpdatedItems, trackUpdatedItems} from './api_listener.js';
import {DropPosition, ROOT_NODE_ID} from './constants.js';
import {Debouncer} from './debouncer.js';
import {BookmarksFolderNodeElement} from './folder_node.js';
import {BookmarksItemElement} from './item.js';
import {Store} from './store.js';
import {BookmarkElement, BookmarkNode, DragData, DropDestination, NodeMap, ObjectMap} from './types.js';
import {canEditNode, canReorderChildren, getDisplayedList, hasChildFolders, isShowingSearch, normalizeNode} from './util.js';
type NormalizedDragData = {
elements: BookmarkNode[],
sameProfile: boolean,
};
const DRAG_THRESHOLD: number = 15;
function isBookmarkItem(element: Element): boolean {
return element.tagName === 'BOOKMARKS-ITEM';
}
function isBookmarkFolderNode(element: Element): boolean {
return element.tagName === 'BOOKMARKS-FOLDER-NODE';
}
function isBookmarkList(element: Element): boolean {
return element.tagName === 'BOOKMARKS-LIST';
}
function isClosedBookmarkFolderNode(element: Element): boolean {
return isBookmarkFolderNode(element) &&
!((element as BookmarksFolderNodeElement).isOpen);
}
function getBookmarkElement(path?: EventTarget[]): BookmarkElement|null {
if (!path) {
return null;
}
for (let i = 0; i < path!.length; i++) {
const element = path![i] as Element;
if (isBookmarkItem(element) || isBookmarkFolderNode(element) ||
isBookmarkList(element)) {
return path![i] as BookmarkElement;
}
}
return null;
}
function getDragElement(path: EventTarget[]): BookmarkElement|null {
const dragElement = getBookmarkElement(path);
for (let i = 0; i < path.length; i++) {
if ((path![i] as Element).tagName === 'BUTTON') {
return null;
}
}
return dragElement && dragElement.getAttribute('draggable') ? dragElement :
null;
}
function getBookmarkNode(bookmarkElement: BookmarkElement): BookmarkNode {
return Store.getInstance().data.nodes[bookmarkElement.itemId]!;
}
/**
* Contains and provides utility methods for drag data sent by the
* bookmarkManagerPrivate API.
*/
export class DragInfo {
dragData: NormalizedDragData|null = null;
setNativeDragData(newDragData: DragData) {
this.dragData = {
sameProfile: newDragData.sameProfile,
elements: newDragData.elements!.map((x) => normalizeNode(x))
};
}
clearDragData() {
this.dragData = null;
}
isDragValid(): boolean {
return !!this.dragData;
}
isSameProfile(): boolean {
return !!this.dragData && this.dragData.sameProfile;
}
isDraggingFolders(): boolean {
return !!this.dragData && this.dragData.elements.some(function(node) {
return !node.url;
});
}
isDraggingBookmark(bookmarkId: string): boolean {
return !!this.dragData && this.isSameProfile() &&
this.dragData.elements.some(function(node) {
return node.id === bookmarkId;
});
}
isDraggingChildBookmark(folderId: string): boolean {
return !!this.dragData && this.isSameProfile() &&
this.dragData.elements.some(function(node) {
return node.parentId === folderId;
});
}
isDraggingFolderToDescendant(itemId: string, nodes: NodeMap): boolean {
if (!this.isSameProfile()) {
return false;
}
let parentId = nodes[itemId]!.parentId;
const parents: ObjectMap<boolean> = {};
while (parentId) {
parents[parentId] = true;
parentId = nodes[parentId]!.parentId;
}
return !!this.dragData && this.dragData.elements.some(function(node) {
return parents[node.id];
});
}
}
/**
* Manages auto expanding of sidebar folders on hover while dragging.
*/
class AutoExpander {
EXPAND_FOLDER_DELAY: number = 400;
private lastElement_: BookmarkElement|null = null;
private debouncer_: Debouncer;
constructor() {
this.debouncer_ = new Debouncer(() => {
const store = Store.getInstance();
store.dispatch(changeFolderOpen(this.lastElement_!.itemId, true));
this.reset();
});
}
update(e: Event, overElement: BookmarkElement|null) {
const itemId = overElement ? overElement.itemId : null;
const store = Store.getInstance();
// If dragging over a new closed folder node with children reset the
// expander. Falls through to reset the expander delay.
if (overElement && overElement !== this.lastElement_ &&
isClosedBookmarkFolderNode(overElement) &&
hasChildFolders(itemId as string, store.data.nodes)) {
this.reset();
this.lastElement_ = overElement;
}
// If dragging over the same node, reset the expander delay.
if (overElement && overElement === this.lastElement_) {
this.debouncer_.restartTimeout(this.EXPAND_FOLDER_DELAY);
return;
}
// Otherwise, cancel the expander.
this.reset();
}
reset() {
this.debouncer_.reset();
this.lastElement_ = null;
}
}
/**
* Encapsulates the behavior of the drag and drop indicator which puts a line
* between items or highlights folders which are valid drop targets.
*/
class DropIndicator {
private removeDropIndicatorTimeoutId_: number|null;
private lastIndicatorElement_: BookmarkElement|null;
private lastIndicatorClassName_: string|null;
timerProxy: Window;
constructor() {
this.removeDropIndicatorTimeoutId_ = null;
this.lastIndicatorElement_ = null;
this.lastIndicatorClassName_ = null;
this.timerProxy = window;
}
/**
* Applies the drop indicator style on the target element and stores that
* information to easily remove the style in the future.
*/
addDropIndicatorStyle(indicatorElement: HTMLElement, position: DropPosition) {
const indicatorStyleName = position === DropPosition.ABOVE ?
'drag-above' :
position === DropPosition.BELOW ? 'drag-below' : 'drag-on';
this.lastIndicatorElement_ = indicatorElement as BookmarkElement;
this.lastIndicatorClassName_ = indicatorStyleName;
indicatorElement.classList.add(indicatorStyleName);
}
/**
* Clears the drop indicator style from the last drop target.
*/
removeDropIndicatorStyle() {
if (!this.lastIndicatorElement_ || !this.lastIndicatorClassName_) {
return;
}
this.lastIndicatorElement_.classList.remove(this.lastIndicatorClassName_);
this.lastIndicatorElement_ = null;
this.lastIndicatorClassName_ = null;
}
/**
* Displays the drop indicator on the current drop target to give the
* user feedback on where the drop will occur.
*/
update(dropDest: DropDestination) {
this.timerProxy.clearTimeout(this.removeDropIndicatorTimeoutId_!);
this.removeDropIndicatorTimeoutId_ = null;
const indicatorElement = dropDest.element.getDropTarget()!;
const position = dropDest.position;
this.removeDropIndicatorStyle();
this.addDropIndicatorStyle(indicatorElement, position);
}
/**
* Stop displaying the drop indicator.
*/
finish() {
if (this.removeDropIndicatorTimeoutId_) {
return;
}
// The use of a timeout is in order to reduce flickering as we move
// between valid drop targets.
this.removeDropIndicatorTimeoutId_ = this.timerProxy.setTimeout(() => {
this.removeDropIndicatorStyle();
}, 100);
}
}
/**
* Manages drag and drop events for the bookmarks-app.
*/
export class DNDManager {
private dragInfo_: DragInfo|null;
private dropDestination_: DropDestination|null;
private dropIndicator_: DropIndicator|null;
private eventTracker_: EventTracker = new EventTracker();
private autoExpander_: AutoExpander|null;
private timerProxy_: any;
private lastPointerWasTouch_: boolean;
constructor() {
this.dragInfo_ = null;
this.dropDestination_ = null;
this.dropIndicator_ = null;
this.autoExpander_ = null;
this.timerProxy_ = window;
this.lastPointerWasTouch_ = false;
}
init() {
this.dragInfo_ = new DragInfo();
this.dropIndicator_ = new DropIndicator();
this.autoExpander_ = new AutoExpander();
this.eventTracker_.add(document, 'dragstart', e => this.onDragStart_(e));
this.eventTracker_.add(document, 'dragenter', e => this.onDragEnter_(e));
this.eventTracker_.add(document, 'dragover', e => this.onDragOver_(e));
this.eventTracker_.add(document, 'dragleave', () => this.onDragLeave_());
this.eventTracker_.add(document, 'drop', e => this.onDrop_(e));
this.eventTracker_.add(document, 'dragend', () => this.clearDragData_());
this.eventTracker_.add(document, 'mousedown', () => this.onMouseDown_());
this.eventTracker_.add(document, 'touchstart', () => this.onTouchStart_());
chrome.bookmarkManagerPrivate.onDragEnter.addListener(
this.handleChromeDragEnter_.bind(this));
chrome.bookmarkManagerPrivate.onDragLeave.addListener(
this.clearDragData_.bind(this));
}
destroy() {
this.eventTracker_.removeAll();
}
////////////////////////////////////////////////////////////////////////////
// DragEvent handlers:
private onDragStart_(e: Event) {
const dragElement = getDragElement(e.composedPath());
if (!dragElement) {
return;
}
e.preventDefault();
const dragData = this.calculateDragData_(dragElement);
if (!dragData) {
this.clearDragData_();
return;
}
const state = Store.getInstance().data;
let draggedNodes = [];
if (isBookmarkItem(dragElement)) {
const displayingItems = assert(getDisplayedList(state));
// TODO(crbug.com/980427): Make this search more time efficient to avoid
// delay on large amount of bookmark dragging.
for (const itemId of displayingItems) {
for (const element of dragData.elements) {
if (element!.id === itemId) {
draggedNodes.push(element!.id);
break;
}
}
}
} else {
draggedNodes = dragData.elements.map((item) => item!.id);
}
assert(draggedNodes.length === dragData.elements.length);
const dragNodeIndex = draggedNodes.indexOf(dragElement.itemId);
assert(dragNodeIndex !== -1);
chrome.bookmarkManagerPrivate.startDrag(
draggedNodes, dragNodeIndex, this.lastPointerWasTouch_,
(e as DragEvent).clientX, (e as DragEvent).clientY);
}
private onDragLeave_() {
this.dropIndicator_!.finish();
}
private onDrop_(e: Event) {
// Allow normal DND on text inputs.
if (isTextInputElement((e.composedPath()[0] as HTMLElement))) {
return;
}
e.preventDefault();
if (this.dropDestination_) {
const dropInfo = this.calculateDropInfo_(this.dropDestination_);
const index = dropInfo.index !== -1 ? dropInfo.index : undefined;
const shouldHighlight = this.shouldHighlight_(this.dropDestination_);
if (shouldHighlight) {
trackUpdatedItems();
}
chrome.bookmarkManagerPrivate.drop(
dropInfo.parentId, index,
shouldHighlight ? highlightUpdatedItems : undefined);
}
this.clearDragData_();
}
private onDragEnter_(e: Event) {
e.preventDefault();
}
private onDragOver_(e: Event) {
this.dropDestination_ = null;
// Allow normal DND on text inputs.
if (isTextInputElement(e.composedPath()[0] as HTMLElement)) {
return;
}
// The default operation is to allow dropping links etc to do
// navigation. We never want to do that for the bookmark manager.
e.preventDefault();
if (!this.dragInfo_!.isDragValid()) {
return;
}
const state = Store.getInstance().data;
const items = this.dragInfo_!.dragData!.elements;
const overElement = getBookmarkElement(e.composedPath());
this.autoExpander_!.update(e, overElement);
if (!overElement) {
this.dropIndicator_!.finish();
return;
}
// Now we know that we can drop. Determine if we will drop above, on or
// below based on mouse position etc.
this.dropDestination_ =
this.calculateDropDestination_((e as DragEvent).clientY, overElement);
if (!this.dropDestination_) {
this.dropIndicator_!.finish();
return;
}
this.dropIndicator_!.update(this.dropDestination_);
}
private onMouseDown_() {
this.lastPointerWasTouch_ = false;
}
private onTouchStart_() {
this.lastPointerWasTouch_ = true;
}
private handleChromeDragEnter_(dragData: DragData) {
this.dragInfo_!.setNativeDragData(dragData);
}
////////////////////////////////////////////////////////////////////////////
// Helper methods:
private clearDragData_() {
this.autoExpander_!.reset();
// Defer the clearing of the data so that the bookmark manager API's drop
// event doesn't clear the drop data before the web drop event has a
// chance to execute (on Mac).
this.timerProxy_.setTimeout(() => {
this.dragInfo_!.clearDragData();
this.dropDestination_ = null;
this.dropIndicator_!.finish();
}, 0);
}
private calculateDropInfo_(dropDestination: DropDestination):
{parentId: string, index: number} {
if (isBookmarkList(dropDestination.element)) {
return {
index: 0,
parentId: Store.getInstance().data.selectedFolder,
};
}
const node = getBookmarkNode(dropDestination.element);
const position = dropDestination.position;
let index = -1;
let parentId = node.id;
if (position !== DropPosition.ON) {
const state = Store.getInstance().data;
// Drops between items in the normal list and the sidebar use the drop
// destination node's parent.
parentId = assert(node.parentId!);
index = state.nodes[parentId]!.children!.indexOf(node.id);
if (position === DropPosition.BELOW) {
index++;
}
}
return {
index: index,
parentId: parentId,
};
}
/**
* Calculates which items should be dragged based on the initial drag item
* and the current selection. Dragged items will end up selected.
*/
private calculateDragData_(dragElement: BookmarkElement) {
const dragId = dragElement.itemId;
const store = Store.getInstance();
const state = store.data;
// Determine the selected bookmarks.
let draggedNodes = Array.from(state.selection.items);
// Change selection to the dragged node if the node is not part of the
// existing selection.
if (isBookmarkFolderNode(dragElement) ||
draggedNodes.indexOf(dragId) === -1) {
store.dispatch(deselectItems());
if (!isBookmarkFolderNode(dragElement)) {
store.dispatch(selectItem(dragId, state, {
clear: false,
range: false,
toggle: false,
}));
}
draggedNodes = [dragId];
}
// If any node can't be dragged, end the drag.
const anyUnmodifiable =
draggedNodes.some((itemId) => !canEditNode(state, itemId));
if (anyUnmodifiable) {
return null;
}
return {
elements: draggedNodes.map((id) => state.nodes[id]),
sameProfile: true,
};
}
/**
* This function determines where the drop will occur.
*/
private calculateDropDestination_(
elementClientY: number,
overElement: BookmarkElement): DropDestination|null {
const validDropPositions = this.calculateValidDropPositions_(overElement);
if (validDropPositions === DropPosition.NONE) {
return null;
}
const above = validDropPositions & DropPosition.ABOVE;
const below = validDropPositions & DropPosition.BELOW;
const on = validDropPositions & DropPosition.ON;
const rect = overElement.getDropTarget()!.getBoundingClientRect();
const yRatio = (elementClientY - rect.top) / rect.height;
if (above && (yRatio <= .25 || yRatio <= .5 && (!below || !on))) {
return {element: overElement, position: DropPosition.ABOVE};
}
if (below && (yRatio > .75 || yRatio > .5 && (!above || !on))) {
return {element: overElement, position: DropPosition.BELOW};
}
if (on) {
return {element: overElement, position: DropPosition.ON};
}
return null;
}
/**
* Determines the valid drop positions for the given target element.
*/
private calculateValidDropPositions_(overElement: BookmarkElement): number {
const dragInfo = this.dragInfo_!;
const state = Store.getInstance().data;
let itemId = overElement.itemId;
// Drags aren't allowed onto the search result list.
if ((isBookmarkList(overElement) || isBookmarkItem(overElement)) &&
isShowingSearch(state)) {
return DropPosition.NONE;
}
if (isBookmarkList(overElement)) {
itemId = state.selectedFolder;
}
if (!canReorderChildren(state, itemId)) {
return DropPosition.NONE;
}
// Drags of a bookmark onto itself or of a folder into its children aren't
// allowed.
if (dragInfo.isDraggingBookmark(itemId) ||
dragInfo.isDraggingFolderToDescendant(itemId, state.nodes)) {
return DropPosition.NONE;
}
let validDropPositions = this.calculateDropAboveBelow_(overElement);
if (this.canDropOn_(overElement)) {
validDropPositions |= DropPosition.ON;
}
return validDropPositions;
}
private calculateDropAboveBelow_(overElement: BookmarkElement): number {
const dragInfo = this.dragInfo_!;
const state = Store.getInstance().data;
if (isBookmarkList(overElement)) {
return DropPosition.NONE;
}
// We cannot drop between Bookmarks bar and Other bookmarks.
if (getBookmarkNode(overElement).parentId === ROOT_NODE_ID) {
return DropPosition.NONE;
}
const isOverFolderNode = isBookmarkFolderNode(overElement);
// We can only drop between items in the tree if we have any folders.
if (isOverFolderNode && !dragInfo.isDraggingFolders()) {
return DropPosition.NONE;
}
let validDropPositions = DropPosition.NONE;
// Cannot drop above if the item above is already in the drag source.
const previousElem =
overElement.previousElementSibling as BookmarksFolderNodeElement;
if (!previousElem || !dragInfo.isDraggingBookmark(previousElem.itemId)) {
validDropPositions |= DropPosition.ABOVE;
}
// Don't allow dropping below an expanded sidebar folder item since it is
// confusing to the user anyway.
if (isOverFolderNode && !isClosedBookmarkFolderNode(overElement) &&
hasChildFolders(overElement.itemId, state.nodes)) {
return validDropPositions;
}
const nextElement =
overElement.nextElementSibling as BookmarksFolderNodeElement;
// Cannot drop below if the item below is already in the drag source.
if (!nextElement || !dragInfo.isDraggingBookmark(nextElement.itemId)) {
validDropPositions |= DropPosition.BELOW;
}
return validDropPositions;
}
/**
* Determine whether we can drop the dragged items on the drop target.
*/
private canDropOn_(overElement: BookmarkElement): boolean {
// Allow dragging onto empty bookmark lists.
if (isBookmarkList(overElement)) {
const state = Store.getInstance().data;
return !!state.selectedFolder &&
state.nodes[state.selectedFolder]!.children!.length === 0;
}
// We can only drop on a folder.
if (getBookmarkNode(overElement).url) {
return false;
}
return !this.dragInfo_!.isDraggingChildBookmark(overElement.itemId);
}
private shouldHighlight_(dropDestination: DropDestination): boolean {
return isBookmarkItem(dropDestination.element) ||
isBookmarkList(dropDestination.element);
}
setTimerProxyForTesting(timerProxy: any) {
this.timerProxy_ = timerProxy;
this.dropIndicator_!.timerProxy = timerProxy;
}
} | the_stack |
import { randomIntegerBetween } from '../../math'
export type Size = {
width: number
height: number
}
export type Point = {
x: number
y: number
}
export type Line = {
x0: number
y0: number
x1: number
y1: number
}
export type Circle = {
x: number
y: number
r: number
}
export type Rect = {
x: number
y: number
width: number
height: number
}
export type Position = Point
export const DEG = Math.PI / 180
export const TWO_PI = 2 * Math.PI
export function randomInRange(a: number, b: number): number {
return a + Math.random() * (b - a)
}
export function pointDistance(a: Point, b: Point): number {
return distance(a.x, a.y, b.x, b.y)
}
export function lineIntersect(
x0: number,
y0: number,
x1: number,
y1: number,
x2: number,
y2: number,
x3: number,
y3: number
): boolean {
const d = (x1 - x0) * (y3 - y2) - (x3 - x2) * (y1 - y0) // determinant
if (d === 0) {
return false
} else {
const a = ((y3 - y2) * (x3 - x0) + (x2 - x3) * (y3 - y0)) / d
const b = ((y0 - y1) * (x3 - x0) + (x1 - x0) * (y3 - y0)) / d
return 0 < a && a < 1 && 0 < b && b < 1
}
}
export function polarToCartesian(
centerX: number,
centerY: number,
radius: number,
angleInDegrees: number
) {
const angleInRadians = ((angleInDegrees - 90) * Math.PI) / 180.0
return {
x: centerX + radius * Math.cos(angleInRadians),
y: centerY + radius * Math.sin(angleInRadians),
}
}
export function describeArc(
x: number,
y: number,
radius: number,
startAngle: number,
endAngle: number
) {
const start = polarToCartesian(x, y, radius, endAngle)
const end = polarToCartesian(x, y, radius, startAngle)
const largeArcFlag = endAngle - startAngle <= 180 ? '0' : '1'
const d = `M ${start.x} ${start.y} A ${radius} ${radius} 0 ${largeArcFlag} 0 ${end.x} ${end.y}`
return d
}
export function _describeArc(
x: number,
y: number,
radius: number,
startAngle: number,
endAngle: number
) {
const start = polarToCartesian(x, y, radius, endAngle)
const end = polarToCartesian(x, y, radius, startAngle)
const largeArcFlag = endAngle - startAngle <= 180 ? '0' : '1'
const d = `M ${start.x} ${start.y} A ${radius} ${radius} 0 ${largeArcFlag} 0 ${end.x} ${end.y}`
return d
}
export function describeArrowPolygon(
x0: number,
y0: number,
x1: number,
y1: number,
h: number,
s: number,
th: number,
tl: number
) {
const dx = x1 - x0
const dy = y1 - y0
const d = Math.sqrt(dx * dx + dy * dy)
const c = d - th
const ux = dx / d
const uy = dy / d
let alpha
if (ux === 0) {
alpha = ((uy / Math.abs(uy)) * Math.PI) / 2
} else {
alpha = Math.atan(uy / ux)
}
const px = Math.sin(alpha)
const py = -Math.cos(alpha)
const a = (s + h) / 2
const apx = a * px
const apy = a * py
const atl = a + tl
const atlpx = atl * px
const atlpy = atl * py
const cux = c * ux
const cuy = c * uy
const x0cux = x0 + cux
const y0cuy = y0 + cuy
const P0 = `${x0 + apx},${y0 + apy}`
return `
${P0}
${x0cux + apx},${y0cuy + apy}
${x0cux + atlpx},${y0cuy + atlpy}
${x1},${y1}
${x0cux - atlpx},${y0cuy - atlpy}
${x0cux - apx},${y0cuy - apy}
${x0 - apx},${y0 - apy}
${P0}
`
}
export function describeCircle(x: number, y: number, r: number) {
const d = `M ${x - r} ${y} A ${r} ${r} 0 1 0 ${x - r} ${y - 0.001} z`
return d
}
export function describeRect(
x: number,
y: number,
width: number,
height: number
) {
const d = `M ${x} ${y} H ${x + width} V ${y + height} H ${x} Z`
return d
}
export function eccentricity(rx: number, ry: number, angle: number) {
// flattening factor
const ff = 1 - ry / rx
const e2 = 2 * ff - ff * ff
return e2
}
export const ellipsoidalToCartesian = (
cx: number,
cy: number,
rx: number,
ry: number,
angle: number
): { x: number; y: number } => {
// flattening factor
const ff = 1 - ry / rx
let e2 = 2 * ff
e2 -= ff * ff
const N = rx / Math.sqrt(1 - e2 * Math.pow(Math.sin(angle), 2))
const x = cx - N * Math.cos(angle)
const y = cy - N * Math.sin(angle)
return { x, y }
}
export function describeEllipseArc(
x: number,
y: number,
rx: number,
ry: number,
startAngle: number,
endAngle: number
) {
const start = ellipsoidalToCartesian(x, y, rx, ry, startAngle)
const end = ellipsoidalToCartesian(x, y, rx, ry, endAngle)
const largeArcFlag = endAngle - startAngle <= 180 ? '0' : '1'
const d = `M ${start.x} ${start.y} A ${rx} ${ry} 0 ${largeArcFlag} 0 ${end.x} ${end.y}`
return d
}
export function getRandomXYInArea(
width: number,
height: number,
cX: number = 0,
cY: number = 0
): Point {
return {
x: randomInRange(cX - width / 2, cX + width / 2),
y: randomInRange(cY - height / 2, cY + height / 2),
}
}
export function randomAngle(): number {
return Math.random() * TWO_PI
}
export function angleToRad(angle: number): number {
return ((angle % 360) * Math.PI) / 180
}
export function radToAngle(rad: number): number {
return (rad * 180) / Math.PI
}
export function randomInRadius(cX: number, cY: number, R: number): Point {
const angle = randomAngle()
return {
x: cX + R * Math.cos(angle),
y: cY + R * Math.sin(angle),
}
}
export function randomInAngle(
cX: number,
cY: number,
R: number,
start: number,
end: number
): Point {
const angle = randomIntegerBetween(start, end)
const rad = angleToRad(angle)
return {
x: cX + R * Math.cos(rad),
y: cY + R * Math.sin(rad),
}
}
export function randomInRect(
x0: number,
y0: number,
x1: number,
y1: number
): Point {
return {
x: x0 + Math.random() * (x1 - x0),
y: y0 + Math.random() * (y1 - y0),
}
}
export function randomInCircle(cX: number, cY: number, R: number): Point {
const angle = randomAngle()
return {
x: cX + Math.random() * R * Math.cos(angle),
y: cY + Math.random() * R * Math.sin(angle),
}
}
export function pointInCircle(
x: number,
y: number,
R: number,
u: Point,
padding: number = 0
) {
return {
x: x + u.x * (R - padding),
y: y + u.y * (R - padding),
}
}
export function pointInRectangle(
x: number,
y: number,
width: number,
height: number,
u: Point,
padding: number = 0
) {
const region = rectangleRegion(x, y, width, height, u)
const tan = u.x / u.y
let a = Math.atan2(u.y, u.x)
if (region === 'left' || region === 'right') {
const sx = Math.sign(u.x)
return {
x: x + sx * (width / 2) - padding * Math.cos(a),
y: y + sx * (width / 2 / tan) - padding * Math.sin(a),
}
} else {
const sy = Math.sign(u.y)
return {
x: x + sy * ((height / 2) * tan) - padding * Math.cos(a),
y: y + sy * (height / 2) - padding * Math.sin(a),
}
}
}
export function pointInNode(node: Thing, u: Point, padding: number = 0) {
const { shape } = node
if (shape === 'circle') {
return pointInCircle(node.x, node.y, node.r, u, padding)
} else {
return pointInRectangle(node.x, node.y, node.width, node.height, u, padding)
}
}
export const NULL_VECTOR: Point = { x: 0, y: 0 }
export function unitVector(
x0: number,
y0: number,
x1: number,
y1: number
): Point {
const dx = x1 - x0
const dy = y1 - y0
const d = norm(dx, dy)
if (d === 0) {
return randomUnitVector()
}
return { x: dx / d, y: dy / d }
}
export function pointUnitVector(
{ x: x0, y: y0 }: Point,
{ x: x1, y: y1 }: Point
): Point {
const dx = x1 - x0
const dy = y1 - y0
const d = norm(dx, dy)
if (d === 0) {
return randomUnitVector()
}
return { x: dx / d, y: dy / d }
}
export function oppositeVector(vector: Point): Point {
const { x, y } = vector
return {
x: -x,
y: -y,
}
}
export const applyVector = (point: Point, u: Point, d: number): Point => {
return {
x: point.x + u.x * d,
y: point.y + u.y * d,
}
}
export function vector(x0: number, y0: number, x1: number, y1: number): Point {
return { x: x1 - x0, y: y1 - y0 }
}
export function jigglePoint(point: Point, intensity: number = 1): Point {
const r = randomUnitVector()
const jiggled = {
x: point.x + intensity * r.x,
y: point.y + intensity * r.y,
}
return jiggled
}
export function perpendicular(vector: Point): Point {
return { x: -vector.y, y: vector.x }
}
// return the angle between two vectors in degrees
// [0, 360[
// assumes 0 is the origin
export const angleBetween = (
ax: number,
ay: number,
bx: number,
by: number
): number => {
return radToAngle(radBetween(ax, ay, bx, by))
}
export const radBetween = (
ax: number,
ay: number,
bx: number,
by: number
): number => {
// const d = distance(ax, ay, bx, by)
// if (d === 0) {
// return 0
// }
let a = Math.atan2(by, bx) - Math.atan2(ay, ax)
if (a < 0) {
a += TWO_PI
}
return a
}
export function inRadius(
cX: number,
cY: number,
R: number,
angle: number
): Point {
const rad = angleToRad(angle)
return {
x: cX + R * Math.cos(rad),
y: cY + R * Math.sin(rad),
}
}
export function distance(
ax: number,
ay: number,
bx: number,
by: number
): number {
return norm(ax - bx, ay - by)
}
export function norm(x: number, y: number): number {
return Math.sqrt(x * x + y * y)
}
export function normalize(point: Point): Point {
const { x, y } = point
const d = norm(point.x, point.y)
return { x: x / d, y: y / d }
}
export function mediumPoint(a: Point, b: Point): Point {
return { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }
}
export function randomUnitVector(): Point {
return normalize({ x: 0.5 - Math.random(), y: 0.5 - Math.random() })
}
export function rotateVector(a: Point, rad: number): Point {
const cos = Math.cos(rad)
const sin = Math.sin(rad)
return { x: a.x * cos - a.y * sin, y: a.x * sin + a.y * cos }
}
export function addVector(a: Point, b: Point): Point {
return { x: a.x + b.x, y: a.y + b.y }
}
export function addVector3(a: Point, b: Point, c: Point): Point {
return addVector(addVector(a, b), c)
}
export function addVector4(a: Point, b: Point, c: Point, d: Point): Point {
return addVector(addVector(a, b), addVector(c, d))
}
export function subtractVector(a: Point, b: Point): Point {
return { x: a.x - b.x, y: a.y - b.y }
}
export function boundingRadius(width: number, height: number) {
return Math.sqrt(width * width + height + height) / 2
}
export function rectangleRegion(
x: number,
y: number,
w: number,
h: number,
u: Point
): 'left' | 'top' | 'right' | 'bottom' {
const { x: ux, y: uy } = u
const { x: ax, y: ay } = unitVector(x, y, x - w / 2, y - h / 2)
const { x: bx, y: by } = unitVector(x, y, x + w / 2, y - h / 2)
const alpha = radBetween(ax, ay, bx, by)
const beta = radBetween(ux, uy, bx, by)
if (beta <= alpha) {
return 'top'
} else if (beta <= Math.PI) {
return 'left'
} else if (beta <= Math.PI + alpha) {
return 'bottom'
} else {
return 'right'
}
}
export type Shape = 'circle' | 'rect'
// TODO
export function bezierSpline(): Point[] {
return []
}
export function is_inside(a: Thing, b: Thing): boolean {
const {
x: a_x,
y: a_y,
shape: a_shape,
r: a_r,
width: a_width,
height: a_height,
} = a
const {
x: b_x,
y: b_y,
shape: b_shape,
r: b_r,
width: b_width,
height: b_height,
} = b
if (a_shape === 'circle' && b_shape === 'circle') {
return distance(a_x, a_y, b_x, b_y) <= b_r - a_r
} else if (a_shape === 'circle' && b_shape === 'rect') {
return (
a_x - a.r >= b_x - b_width / 2 &&
a_x + a.r <= b_x + b_width / 2 &&
a_y - a.r >= b_y - b_height / 2 &&
a_y + a.r <= b_y + b_height / 2
)
} else if (a_shape === 'rect' && b_shape === 'circle') {
// https://stackoverflow.com/questions/14097290/check-if-circle-contains-rectangle
const dx = Math.max(b_x - a_x + a_width / 2, a_x + a_width / 2 - b_x)
const dy = Math.max(b_y - a_y + a_height / 2, a_y + a_height / 2 - b_y)
return b_r * b_r >= dx * dx + dy * dy
} else {
return (
a_x - a_width / 2 >= b_x - b_width / 2 &&
a_x + a_width / 2 <= b_x + b_width / 2 &&
a_y - a_height / 2 >= b_y - b_height / 2 &&
a_y + a_height / 2 <= b_y + b_height / 2
)
}
}
export function surfaceDistance(
a: Thing,
b: Thing
): { l: number; d: number; u: Point } {
return _surfaceDistance(
a.shape,
a.x,
a.y,
a.r,
a.width,
a.height,
b.shape,
b.x,
b.y,
b.r,
b.width,
b.height
)
}
export function _surfaceDistance(
a_shape: Shape,
a_x: number,
a_y: number,
a_r: number,
a_width: number,
a_height: number,
b_shape: Shape,
b_x: number,
b_y: number,
b_r: number,
b_width: number,
b_height: number
): { l: number; d: number; u: Point } {
const d = distance(a_x, a_y, b_x, b_y)
const u = unitVector(a_x, a_y, b_x, b_y)
let a_d: number = _centerToSurfaceDistance(
a_shape,
a_x,
a_y,
a_r,
a_width,
a_height,
u
)
let b_d: number = _centerToSurfaceDistance(
b_shape,
b_x,
b_y,
b_r,
b_width,
b_height,
u
)
let l: number
const ds = b_d + a_d
const dd = Math.abs(a_d - b_d)
if (d <= ds && d >= dd - 1) {
l = 0
} else if (d < dd) {
l = d - dd
}
l = d - ds
return {
d,
l,
u,
}
}
export function surfaceDistanceY(
a: Thing,
b: Thing
): { l: number; d: number; u: number } {
const a_y = a.y
const b_y = b.y
const d = Math.abs(a_y - b_y)
const u = Math.sign(a_y - b_y)
let a_d: number = a.height / 2
let b_d: number = b.height / 2
let l: number
const ds = b_d + a_d
const dd = Math.abs(a_d - b_d)
if (d <= ds && d >= dd - 1) {
l = 0
} else if (d < dd) {
l = d - dd
}
l = d - ds
return {
d,
l,
u,
}
}
export type Thing = {
shape: Shape
x: number
y: number
r: number
width: number
height: number
}
export function centerToSurfaceDistance(node: Thing, u: Position): number {
const { shape, x, y, r, width, height } = node
return _centerToSurfaceDistance(shape, x, y, r, width, height, u)
}
export function _centerToSurfaceDistance(
shape: Shape,
x: number,
y: number,
r: number,
width: number,
height: number,
u: Position
): number {
if (shape === 'circle') {
return r
} else {
const tan = u.x / u.y
const region = rectangleRegion(x, y, width, height, u)
if (region === 'left' || region === 'right') {
return norm(width / 2, width / 2 / tan)
} else {
return norm((height / 2) * tan, height / 2)
}
}
}
export function centerOfMass(points: Point[]): Point {
let sum_x = 0
let sum_y = 0
const n = points.length
for (let i = 0; i < points.length; i++) {
const p = points[i]
sum_x += p.x
sum_y += p.y
}
const x = sum_x / n
const y = sum_y / n
return { x, y }
}
export const vectorAngle = (p0: Point, p1: Point): number => {
let a = Math.atan2(p1.y - p0.y, p1.x - p0.x)
if (a < 0) {
a += TWO_PI
}
return a / DEG
} | the_stack |
import axios, { AxiosRequestConfig, AxiosResponse } from "axios"
import {
BlockchainInfoResult,
BlockDetailsResult,
BlockHeaderResult,
ChainTipResult,
MempoolEntryResult,
MempoolInfoResult,
TxOutResult
} from "bitcoin-com-rest"
import { REST_URL } from "./BITBOX"
export class Blockchain {
public restURL: string
constructor(restURL: string = REST_URL) {
this.restURL = restURL
}
public async getBestBlockHash(): Promise<string> {
try {
const response: AxiosResponse = await axios.get(
`${this.restURL}blockchain/getBestBlockHash`
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
}
}
public async getBlock(
blockhash: string,
verbose: boolean = true
): Promise<BlockDetailsResult> {
try {
const response: AxiosResponse = await axios.get(
`${this.restURL}blockchain/getBlock/${blockhash}?verbose=${verbose}`
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
}
}
public async getBlockchainInfo(): Promise<BlockchainInfoResult> {
try {
const response: AxiosResponse = await axios.get(
`${this.restURL}blockchain/getBlockchainInfo`
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
}
}
public async getBlockCount(): Promise<number> {
try {
const response: AxiosResponse = await axios.get(
`${this.restURL}blockchain/getBlockCount`
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
}
}
public async getBlockHash(height: number = 1): Promise<string> {
// if (typeof height !== "string") height = JSON.stringify(height)
try {
const response: AxiosResponse = await axios.get(
`${this.restURL}blockchain/getBlockHash/${height}`
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
}
}
public async getBlockHeader(
hash: string | string[],
verbose: boolean = true
): Promise<BlockHeaderResult | BlockHeaderResult[]> {
try {
// Handle single hash.
if (typeof hash === "string") {
const response: AxiosResponse = await axios.get(
`${this.restURL}blockchain/getBlockHeader/${hash}?verbose=${verbose}`
)
return response.data
// Handle array of hashes.
} else if (Array.isArray(hash)) {
// Dev note: must use axios.post for unit test stubbing.
const response: AxiosResponse = await axios.post(
`${this.restURL}blockchain/getBlockHeader`,
{
hashes: hash,
verbose: verbose
}
)
return response.data
}
throw new Error(`Input hash must be a string or array of strings.`)
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
}
}
public async getChainTips(): Promise<ChainTipResult[]> {
try {
const response: AxiosResponse = await axios.get(
`${this.restURL}blockchain/getChainTips`
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
}
}
public async getDifficulty(): Promise<number> {
try {
const response: AxiosResponse = await axios.get(
`${this.restURL}blockchain/getDifficulty`
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
}
}
// TODO: add back to REST
public async getMempoolAncestors(
txid: string,
verbose: boolean = false
): Promise<string[] | MempoolEntryResult[]> {
if (typeof txid !== "string") txid = JSON.stringify(txid)
try {
const response: AxiosResponse = await axios.get(
`${this.restURL}blockchain/getMempoolAncestors/${txid}?verbose=${verbose}`
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
}
}
// TODO: add back to REST
public async getMempoolDescendants(
txid: string,
verbose: boolean = false
): Promise<string[] | MempoolEntryResult[]> {
if (typeof txid !== "string") txid = JSON.stringify(txid)
try {
const response: AxiosResponse = await axios.get(
`${this.restURL}blockchain/getMempoolDescendants/${txid}?verbose=${verbose}`
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
}
}
public async getMempoolEntry(
txid: string | string[]
): Promise<MempoolEntryResult> {
try {
if (typeof txid === "string") {
const response: AxiosResponse = await axios.get(
`${this.restURL}blockchain/getMempoolEntry/${txid}`
)
return response.data
} else if (Array.isArray(txid)) {
const options: AxiosRequestConfig = {
method: "POST",
url: `${this.restURL}blockchain/getMempoolEntry`,
data: {
txids: txid
}
}
const response: AxiosResponse = await axios(options)
return response.data
}
throw new Error(`Input must be a string or array of strings.`)
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
}
}
public async getMempoolInfo(): Promise<MempoolInfoResult> {
try {
const response: AxiosResponse = await axios.get(
`${this.restURL}blockchain/getMempoolInfo`
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
}
}
public async getRawMempool(verbose: boolean = false): Promise<string[]> {
// TODO fix verbose
try {
const response: AxiosResponse = await axios.get(
`${this.restURL}blockchain/getRawMempool?vebose=${verbose}`
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
}
}
// Returns details about an unspent transaction output.
public async getTxOut(
txid: string,
n: any,
include_mempool: boolean = true
): Promise<TxOutResult | null> {
// Input validation
if (typeof txid !== "string" || txid.length !== 64)
throw new Error(`txid needs to be a proper transaction ID`)
if (isNaN(n)) throw new Error(`n must be an integer`)
if (typeof include_mempool !== "boolean")
throw new Error(`include_mempool input must be of type boolean`)
try {
const path: string = `${this.restURL}blockchain/getTxOut/${txid}/${n}?include_mempool=${include_mempool}`
// console.log(`path: ${path}`)
const response: AxiosResponse = await axios.get(path)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
}
}
public async getTxOutProof(
txids: string | string[]
): Promise<string | string[]> {
try {
// Single txid.
if (typeof txids === "string") {
const path = `${this.restURL}blockchain/getTxOutProof/${txids}`
//if (blockhash) path = `${path}?blockhash=${blockhash}`
const response: AxiosResponse = await axios.get(path)
return response.data
// Array of txids.
} else if (Array.isArray(txids)) {
// Dev note: must use axios.post for unit test stubbing.
const response: AxiosResponse = await axios.post(
`${this.restURL}blockchain/getTxOutProof`,
{
txids: txids
}
)
return response.data
}
throw new Error(`Input must be a string or array of strings.`)
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
}
}
public async preciousBlock(blockhash: string): Promise<any> {
// TODO bring this back to REST
try {
const response: AxiosResponse = await axios.get(
`${this.restURL}blockchain/preciousBlock/${blockhash}`
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
}
}
public async pruneBlockchain(height: number): Promise<number> {
// TODO bring this back to REST
try {
const response: AxiosResponse = await axios.post(
`${this.restURL}blockchain/pruneBlockchain/${height}`
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
}
}
public async verifyChain(
checklevel: number = 3,
nblocks: number = 6
): Promise<boolean> {
try {
const response: AxiosResponse = await axios.get(
`${this.restURL}blockchain/verifyChain?checklevel=${checklevel}&nblocks=${nblocks}`
)
return response.data
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
}
}
public async verifyTxOutProof(proof: string | string[]): Promise<string[]> {
try {
// Single block
if (typeof proof === "string") {
const response: AxiosResponse = await axios.get(
`${this.restURL}blockchain/verifyTxOutProof/${proof}`
)
return response.data
// Array of hashes.
} else if (Array.isArray(proof)) {
// Dev note: must use axios.post for unit test stubbing.
const response: AxiosResponse = await axios.post(
`${this.restURL}blockchain/verifyTxOutProof`,
{
proofs: proof
}
)
return response.data
}
throw new Error(`Input must be a string or array of strings.`)
} catch (error) {
if (error.response && error.response.data) throw error.response.data
else throw error
}
}
} | the_stack |
import { Component, OnDestroy, OnInit } from '@angular/core';
import { HttpErrorResponse, HttpHeaders, HttpResponse } from '@angular/common/http';
import { ActivatedRoute, Router } from '@angular/router';
import { combineLatest, Subject, Subscription } from 'rxjs';
import { onError } from 'app/shared/util/global.utils';
import { User } from 'app/core/user/user.model';
import { UserService } from 'app/core/user/user.service';
import { AccountService } from 'app/core/auth/account.service';
import { AlertService } from 'app/core/util/alert.service';
import { SortingOrder } from 'app/shared/table/pageable-table';
import { debounceTime, switchMap, tap } from 'rxjs/operators';
import { AbstractControl, FormControl, FormGroup } from '@angular/forms';
import { EventManager } from 'app/core/util/event-manager.service';
import { ParseLinks } from 'app/core/util/parse-links.service';
import { ASC, DESC, ITEMS_PER_PAGE, SORT } from 'app/shared/constants/pagination.constants';
import { faEye, faFilter, faPlus, faSort, faTimes, faWrench } from '@fortawesome/free-solid-svg-icons';
import { LocalStorageService } from 'ngx-webstorage';
import { CourseManagementService } from 'app/course/manage/course-management.service';
import { Course } from 'app/entities/course.model';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { TemplateRef, ViewChild } from '@angular/core';
import { HttpParams } from '@angular/common/http';
export class UserFilter {
authorityFilter: Set<AuthorityFilter> = new Set();
originFilter: Set<OriginFilter> = new Set();
statusFilter: Set<StatusFilter> = new Set();
courseFilter: Set<number> = new Set();
noAuthority = false;
noCourse = false;
/**
* Adds the http param options
* @param options request options
*/
adjustOptions(options: HttpParams) {
if (this.noAuthority) {
options = options.append('authorities', 'NO_AUTHORITY');
} else {
options = options.append('authorities', [...this.authorityFilter].join(','));
}
options = options.append('origins', [...this.originFilter].join(','));
options = options.append('status', [...this.statusFilter].join(','));
if (this.noCourse) {
// -1 means that we filter for users without any course
options = options.append('courseIds', -1);
} else {
options = options.append('courseIds', [...this.courseFilter].join(','));
}
return options;
}
/**
* Returns the number of applied filters.
*/
get numberOfAppliedFilters() {
return this.authorityFilter.size + this.originFilter.size + this.statusFilter.size + this.courseFilter.size + (this.noAuthority ? 1 : 0) + (this.noCourse ? 1 : 0);
}
}
export enum AuthorityFilter {
ADMIN = 'ADMIN',
INSTRUCTOR = 'INSTRUCTOR',
EDITOR = 'EDITOR',
TA = 'TA',
USER = 'USER',
}
export enum OriginFilter {
INTERNAL = 'INTERNAL',
EXTERNAL = 'EXTERNAL',
}
export enum StatusFilter {
ACTIVATED = 'ACTIVATED',
DEACTIVATED = 'DEACTIVATED',
}
export enum UserStorageKey {
AUTHORITY = 'artemis.userManagement.authority',
NO_AUTHORITY = 'artemis.userManagement.noAuthority',
ORIGIN = 'artemis.userManagement.origin',
STATUS = 'artemis.userManagement.status',
NO_COURSE = 'artemis.userManagement.noCourse',
}
type Filter = typeof AuthorityFilter | typeof OriginFilter | typeof StatusFilter;
@Component({
selector: 'jhi-user-management',
templateUrl: './user-management.component.html',
styleUrls: ['./user-management.component.scss'],
})
export class UserManagementComponent implements OnInit, OnDestroy {
@ViewChild('filterModal') filterModal: TemplateRef<any>;
search = new Subject<void>();
loadingSearchResult = false;
currentAccount?: User;
users: User[];
userListSubscription?: Subscription;
totalItems = 0;
itemsPerPage = ITEMS_PER_PAGE;
page!: number;
predicate!: string;
ascending!: boolean;
searchTermString = '';
// filters
filters: UserFilter = new UserFilter();
faFilter = faFilter;
courses: Course[] = [];
authorityKey = UserStorageKey.AUTHORITY;
statusKey = UserStorageKey.STATUS;
originKey = UserStorageKey.ORIGIN;
private dialogErrorSource = new Subject<string>();
dialogError = this.dialogErrorSource.asObservable();
userSearchForm: FormGroup;
// Icons
faSort = faSort;
faPlus = faPlus;
faTimes = faTimes;
faEye = faEye;
faWrench = faWrench;
constructor(
private userService: UserService,
private alertService: AlertService,
private accountService: AccountService,
private parseLinks: ParseLinks,
private activatedRoute: ActivatedRoute,
private router: Router,
private eventManager: EventManager,
private localStorage: LocalStorageService,
private curseManagementService: CourseManagementService,
private modalService: NgbModal,
) {}
/**
* Retrieves the current user and calls the {@link loadAll} and {@link registerChangeInUsers} methods on init
*/
ngOnInit(): void {
// Load all courses and create id to title map
this.curseManagementService.getAll().subscribe((courses) => {
if (courses.body) {
this.courses = courses.body.sort((c1, c2) => (c1.title ?? '').localeCompare(c2.title ?? ''));
}
this.initFilters();
});
this.search
.pipe(
tap(() => (this.loadingSearchResult = true)),
debounceTime(1000),
switchMap(() =>
this.userService.query(
{
page: this.page - 1,
pageSize: this.itemsPerPage,
searchTerm: this.searchTermString,
sortingOrder: this.ascending ? SortingOrder.ASCENDING : SortingOrder.DESCENDING,
sortedColumn: this.predicate,
filters: this.filters,
},
this.filters,
),
),
)
.subscribe({
next: (res: HttpResponse<User[]>) => {
this.loadingSearchResult = false;
this.onSuccess(res.body || [], res.headers);
},
error: (res: HttpErrorResponse) => {
this.loadingSearchResult = false;
onError(this.alertService, res);
},
});
this.userSearchForm = new FormGroup({
searchControl: new FormControl('', { validators: [this.validateUserSearch], updateOn: 'blur' }),
});
this.accountService.identity().then((user) => {
this.currentAccount = user!;
this.userListSubscription = this.eventManager.subscribe('userListModification', () => this.loadAll());
this.handleNavigation();
});
}
/**
* clean up the subscriptions
*/
ngOnDestroy(): void {
if (this.userListSubscription) {
this.eventManager.destroy(this.userListSubscription);
}
this.dialogErrorSource.unsubscribe();
}
/**
* Inits the available filter and maps the functions.
*/
initFilters() {
this.filters.authorityFilter = this.initFilter<AuthorityFilter>(UserStorageKey.AUTHORITY, AuthorityFilter);
this.filters.originFilter = this.initFilter<OriginFilter>(UserStorageKey.ORIGIN, OriginFilter);
this.filters.statusFilter = this.initFilter<StatusFilter>(UserStorageKey.STATUS, StatusFilter);
this.filters.noCourse = !!this.localStorage.retrieve(UserStorageKey.NO_COURSE);
this.filters.noAuthority = !!this.localStorage.retrieve(UserStorageKey.NO_AUTHORITY);
}
/**
* Inits a specific filter.
* @param key of the filter in the local storage
* @param type of filter
*/
initFilter<E>(key: UserStorageKey, type: Filter): Set<E> {
const temp = this.localStorage.retrieve(key);
const tempInStorage = temp
? temp
.split(',')
.map((filter: string) => type[filter])
.filter(Boolean)
: new Set();
return new Set(tempInStorage);
}
/**
* Method to add or remove a filter and store the selected filters in the local store if required.
*/
toggleFilter<E>(filter: Set<E>, value: E, key?: UserStorageKey) {
if (filter.has(value)) {
filter.delete(value);
} else {
filter.add(value);
}
if (key) {
this.localStorage.store(key, Array.from(filter).join(','));
}
}
/**
* Method to add or remove a course filter.
*/
toggleCourseFilter(filter: Set<number>, value: number) {
this.filters.noCourse = false;
this.updateNoCourse(false);
this.toggleFilter<number>(filter, value);
}
/**
* Method to add or remove an authority filter and store the selected authority filters in the local store if required.
*/
toggleAuthorityFilter(filter: Set<AuthorityFilter>, value: AuthorityFilter) {
this.filters.noAuthority = false;
this.updateNoAuthority(false);
this.toggleFilter<AuthorityFilter>(filter, value, this.authorityKey);
}
/**
* Method to add or remove an origin filter and store the selected origin filters in the local store if required.
*/
toggleOriginFilter(value?: OriginFilter) {
const filter = this.filters.originFilter;
this.deselectFilter<OriginFilter>(filter, this.originKey);
if (value) {
this.toggleFilter<OriginFilter>(filter, value, this.originKey);
}
}
/**
* Method to add or remove a status filter and store the selected status filters in the local store if required.
*/
toggleStatusFilter(value?: StatusFilter) {
const filter = this.filters.statusFilter;
this.deselectFilter<StatusFilter>(filter, this.statusKey);
if (value) {
this.toggleFilter<StatusFilter>(filter, value, this.statusKey);
}
}
/**
* Deselect filter.
*/
deselectFilter<E>(filter: Set<E>, key: UserStorageKey) {
if (filter.size) {
this.toggleFilter<E>(filter, Array.from(filter).pop()!, key);
}
}
/**
* Generic method to return all possible filter values per category.
*/
getFilter(type: Filter) {
return Object.keys(type).map((value) => type[value]);
}
/**
* Get all filter options for authorities.
*/
get authorityFilters() {
return this.getFilter(AuthorityFilter);
}
/**
* Get all filter options for origin.
*/
get originFilters() {
return this.getFilter(OriginFilter);
}
/**
* Get all filter options for status.
*/
get statusFilters() {
return this.getFilter(StatusFilter);
}
/**
* Get all filter options for course.
*/
get courseFilters() {
return this.courses;
}
/**
* Update the no course selection and the local storage.
* @param value new value
*/
updateNoCourse(value: boolean) {
this.localStorage.store(UserStorageKey.NO_COURSE, value);
this.filters.noCourse = value;
}
/**
* Update the no authority selection and the local storage.
* @param value new value
*/
updateNoAuthority(value: boolean) {
this.localStorage.store(UserStorageKey.NO_AUTHORITY, value);
this.filters.noAuthority = value;
}
/**
* Deselect all courses
*/
deselectAllCourses() {
this.filters.courseFilter.clear();
this.updateNoCourse(false);
}
/**
* Select all users without course
*/
selectEmptyCourses() {
this.filters.courseFilter.clear();
this.updateNoCourse(true);
}
/**
* Select all courses
*/
selectAllCourses() {
this.filters.courseFilter = new Set(this.courses.map((course) => course.id!));
this.updateNoCourse(false);
}
/**
* Deselect all roles
*/
deselectAllRoles() {
this.filters.authorityFilter.clear();
this.localStorage.clear(UserStorageKey.AUTHORITY);
this.updateNoAuthority(false);
}
/**
* Select empty roles
*/
selectEmptyRoles() {
this.filters.authorityFilter.clear();
this.updateNoAuthority(true);
}
/**
* Select all roles
*/
selectAllRoles() {
this.filters.authorityFilter = new Set(this.authorityFilters);
this.updateNoAuthority(false);
}
/**
* Opens the modal.
*/
open(content: any) {
this.modalService.open(content).result.then();
}
/**
* Apply the filter and close the modal.
*/
applyFilter() {
this.loadAll();
this.modalService.dismissAll();
}
/**
* Update the user's activation status
* @param user whose activation status should be changed
* @param isActivated true if user should be activated, otherwise false
*/
setActive(user: User, isActivated: boolean) {
user.activated = isActivated;
this.userService.update(user).subscribe(() => {
this.loadAll();
});
}
/**
* Retrieve the list of users from the user service for a single page in the user management based on the page, size and sort configuration
*/
loadAll() {
if (this.searchTerm.length >= 3 || this.searchTerm.length === 0) {
this.search.next();
}
}
/**
* Returns the unique identifier for items in the collection
* @param index of a user in the collection
* @param item current user
*/
trackIdentity(index: number, item: User) {
return item.id ?? -1;
}
/**
* Transitions to another page and/or sorting order
*/
transition(): void {
this.router.navigate(['/admin/user-management'], {
relativeTo: this.activatedRoute.parent,
queryParams: {
page: this.page,
sort: `${this.predicate},${this.ascending ? ASC : DESC}`,
},
});
}
private handleNavigation(): void {
combineLatest({
data: this.activatedRoute.data,
params: this.activatedRoute.queryParamMap,
}).subscribe(({ data, params }) => {
const page = params.get('page');
this.page = page != undefined ? +page : 1;
const sort = (params.get(SORT) ?? data['defaultSort']).split(',');
this.predicate = sort[0];
this.ascending = sort[1] === ASC;
this.loadAll();
});
}
/**
* Deletes a user
* @param login of the user that should be deleted
*/
deleteUser(login: string) {
this.userService.delete(login).subscribe({
next: () => {
this.eventManager.broadcast({
name: 'userListModification',
content: 'Deleted a user',
});
this.dialogErrorSource.next('');
},
error: (error: HttpErrorResponse) => this.dialogErrorSource.next(error.message),
});
}
private onSuccess(users: User[], headers: HttpHeaders) {
this.totalItems = Number(headers.get('X-Total-Count'));
this.users = users;
}
set searchTerm(searchTerm: string) {
this.searchTermString = searchTerm;
}
get searchTerm(): string {
return this.searchTermString;
}
validateUserSearch(control: AbstractControl) {
if (control.value.length >= 1 && control.value.length <= 2) {
return { searchControl: true };
}
return null;
}
get searchControl() {
return this.userSearchForm.get('searchControl')!;
}
} | the_stack |
import { State, StateTransform, StateTransformer, StateAction, StateObject, StateObjectCell } from '../../mol-state';
import * as React from 'react';
import { PurePluginUIComponent } from '../base';
import { ParameterControls, ParamOnChange } from '../controls/parameters';
import { PluginContext } from '../../mol-plugin/context';
import { ParamDefinition as PD } from '../../mol-util/param-definition';
import { Subject } from 'rxjs';
import { Icon, RefreshSvg, CheckSvg, ArrowRightSvg, ArrowDropDownSvg, TuneSvg } from '../controls/icons';
import { ExpandGroup, ToggleButton, Button, IconButton } from '../controls/common';
export { StateTransformParameters, TransformControlBase };
class StateTransformParameters extends PurePluginUIComponent<StateTransformParameters.Props> {
validate(params: any) {
// TODO
return void 0;
}
areInitial(params: any) {
return PD.areEqual(this.props.info.params, params, this.props.info.initialValues);
}
onChange: ParamOnChange = ({ name, value }) => {
const params = { ...this.props.params, [name]: value };
this.props.events.onChange(params, this.areInitial(params), this.validate(params));
};
render() {
return <ParameterControls params={this.props.info.params} values={this.props.params} onChange={this.onChange} onEnter={this.props.events.onEnter} isDisabled={this.props.isDisabled} />;
}
}
namespace StateTransformParameters {
export interface Props {
info: {
params: PD.Params,
initialValues: any,
isEmpty: boolean
},
events: {
onChange: (params: any, areInitial: boolean, errors?: string[]) => void,
onEnter: () => void,
}
params: any,
isDisabled?: boolean,
a?: StateObject,
b?: StateObject,
bCell?: StateObjectCell
}
export type Class = React.ComponentClass<Props>
function areParamsEmpty(params: PD.Params) {
const keys = Object.keys(params);
for (const k of keys) {
if (!params[k].isHidden) return false;
}
return true;
}
export function infoFromAction(plugin: PluginContext, state: State, action: StateAction, nodeRef: StateTransform.Ref): Props['info'] {
const source = state.cells.get(nodeRef)!.obj!;
const params = action.definition.params ? action.definition.params(source, plugin) : { };
const initialValues = PD.getDefaultValues(params);
return {
initialValues,
params,
isEmpty: areParamsEmpty(params)
};
}
export function infoFromTransform(plugin: PluginContext, state: State, transform: StateTransform): Props['info'] {
const cell = state.cells.get(transform.ref)!;
// const source: StateObjectCell | undefined = (cell.sourceRef && state.cells.get(cell.sourceRef)!) || void 0;
// const create = transform.transformer.definition.params;
// const params = create ? create((source && source.obj) as any, plugin) : { };
const params = (cell.params && cell.params.definition) || { };
const initialValues = (cell.params && cell.params.values) || { };
return {
initialValues,
params,
isEmpty: areParamsEmpty(params)
};
}
}
namespace TransformControlBase {
export interface ComponentState {
params: any,
error?: string,
busy: boolean,
isInitial: boolean,
simpleOnly?: boolean,
isCollapsed?: boolean
}
export interface CommonProps {
simpleApply?: { header: string, icon?: React.FC, title?: string },
noMargin?: boolean,
applyLabel?: string,
onApply?: () => void,
autoHideApply?: boolean,
wrapInExpander?: boolean,
expanderHeaderLeftMargin?: string
}
}
abstract class TransformControlBase<P, S extends TransformControlBase.ComponentState> extends PurePluginUIComponent<P & TransformControlBase.CommonProps, S> {
abstract applyAction(): Promise<void>;
abstract getInfo(): StateTransformParameters.Props['info'];
abstract getHeader(): StateTransformer.Definition['display'] | 'none';
abstract canApply(): boolean;
abstract getTransformerId(): string;
abstract canAutoApply(newParams: any): boolean;
abstract applyText(): string;
abstract isUpdate(): boolean;
abstract getSourceAndTarget(): { a?: StateObject, b?: StateObject, bCell?: StateObjectCell };
abstract state: S;
private busy: Subject<boolean> = new Subject();
private onEnter = () => {
if (this.state.error) return;
this.apply();
}
private autoApplyHandle: number | undefined = void 0;
private clearAutoApply() {
if (this.autoApplyHandle !== void 0) {
clearTimeout(this.autoApplyHandle);
this.autoApplyHandle = void 0;
}
}
events: StateTransformParameters.Props['events'] = {
onEnter: this.onEnter,
onChange: (params, isInitial, errors) => {
this.clearAutoApply();
this.setState({ params, isInitial, error: errors && errors[0] }, () => {
if (!isInitial && !this.state.error && this.canAutoApply(params)) {
this.clearAutoApply();
this.autoApplyHandle = setTimeout(this.apply, 50) as any as number;
}
});
}
}
apply = async () => {
this.clearAutoApply();
this.setState({ busy: true });
try {
await this.applyAction();
} catch {
// eat errors because they should be handled elsewhere
} finally {
this.props.onApply?.();
this.busy.next(false);
}
}
componentDidMount() {
this.subscribe(this.plugin.behaviors.state.isBusy, b => {
if (this.state.busy !== b) this.busy.next(b);
});
this.subscribe(this.busy, busy => {
if (this.state.busy !== busy) this.setState({ busy });
});
}
refresh = () => {
this.setState({ params: this.getInfo().initialValues, isInitial: true, error: void 0 });
}
setDefault = () => {
const info = this.getInfo();
const params = PD.getDefaultValues(info.params);
this.setState({ params, isInitial: PD.areEqual(info.params, params, info.initialValues), error: void 0 });
}
toggleExpanded = () => {
this.setState({ isCollapsed: !this.state.isCollapsed });
}
renderApply() {
const canApply = this.canApply();
if (this.props.autoHideApply && (!canApply || this.canAutoApply(this.state.params))) return null;
return <div className='msp-transform-apply-wrap'>
<IconButton svg={RefreshSvg} className='msp-transform-default-params' onClick={this.setDefault} disabled={this.state.busy} title='Set default params' />
<div className={`msp-transform-apply-wider`}>
<Button icon={canApply ? CheckSvg : void 0} className={`msp-btn-commit msp-btn-commit-${canApply ? 'on' : 'off'}`} onClick={this.apply} disabled={!canApply}>
{this.props.applyLabel || this.applyText()}
</Button>
</div>
</div>;
}
renderDefault() {
const info = this.getInfo();
const isEmpty = info.isEmpty && this.isUpdate();
const display = this.getHeader();
const tId = this.getTransformerId();
const ParamEditor: StateTransformParameters.Class = this.plugin.customParamEditors.has(tId)
? this.plugin.customParamEditors.get(tId)!
: StateTransformParameters;
const wrapClass = this.state.isCollapsed
? 'msp-transform-wrapper msp-transform-wrapper-collapsed'
: 'msp-transform-wrapper';
let params = null;
if (!isEmpty && !this.state.isCollapsed) {
const { a, b, bCell } = this.getSourceAndTarget();
const applyControl = this.renderApply();
params = <>
<ParamEditor info={info} a={a} b={b} bCell={bCell} events={this.events} params={this.state.params} isDisabled={this.state.busy} />
{applyControl}
</>;
}
const ctrl = <div className={wrapClass} style={{ marginBottom: this.props.noMargin ? 0 : void 0 }}>
{display !== 'none' && !this.props.wrapInExpander && <div className='msp-transform-header'>
<Button onClick={this.toggleExpanded} title={display.description}>
{!isEmpty && <Icon svg={this.state.isCollapsed ? ArrowRightSvg : ArrowDropDownSvg} />}
{display.name}
</Button>
</div>}
{params}
</div>;
if (isEmpty || !this.props.wrapInExpander) return ctrl;
return <ExpandGroup header={this.isUpdate() ? `Update ${display === 'none' ? '' : display.name}` : `Apply ${display === 'none' ? '' : display.name}` } headerLeftMargin={this.props.expanderHeaderLeftMargin}>
{ctrl}
</ExpandGroup>;
}
renderSimple() {
const info = this.getInfo();
const canApply = this.canApply();
const apply = <div className='msp-flex-row'>
<Button icon={this.props.simpleApply?.icon} title={this.props.simpleApply?.title} disabled={this.state.busy || !canApply} onClick={this.apply} className='msp-btn-apply-simple'>
{this.props.simpleApply?.header}
</Button>
{!info.isEmpty && <ToggleButton icon={TuneSvg} label='' title='Options' toggle={this.toggleExpanded} isSelected={!this.state.isCollapsed} disabled={this.state.busy} style={{ flex: '0 0 40px', padding: 0 }} />}
</div>;
if (this.state.isCollapsed) return apply;
const tId = this.getTransformerId();
const ParamEditor: StateTransformParameters.Class = this.plugin.customParamEditors.has(tId)
? this.plugin.customParamEditors.get(tId)!
: StateTransformParameters;
const { a, b, bCell } = this.getSourceAndTarget();
return <>
{apply}
<ParamEditor info={info} a={a} b={b} bCell={bCell} events={this.events} params={this.state.params} isDisabled={this.state.busy} />
</>;
}
render() {
// console.log('rendering', ((this.props as any)?.transform?.transformer || (this.props as any)?.action)?.definition.display.name, +new Date)
return this.props.simpleApply ? this.renderSimple() : this.renderDefault();
}
} | the_stack |
import { ConcreteRequest } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type NearbyGalleriesRailRendererQueryVariables = {
near: string;
};
export type NearbyGalleriesRailRendererQueryResponse = {
readonly partnersConnection: {
readonly edges: ReadonlyArray<{
readonly " $fragmentRefs": FragmentRefs<"NearbyGalleriesRail_partners">;
} | null> | null;
} | null;
};
export type NearbyGalleriesRailRendererQuery = {
readonly response: NearbyGalleriesRailRendererQueryResponse;
readonly variables: NearbyGalleriesRailRendererQueryVariables;
};
/*
query NearbyGalleriesRailRendererQuery(
$near: String!
) {
partnersConnection(first: 12, near: $near, eligibleForListing: true, defaultProfilePublic: true, sort: RANDOM_SCORE_DESC) {
edges {
...NearbyGalleriesRail_partners
}
}
}
fragment FollowProfileButton_profile on Profile {
id
slug
name
internalID
is_followed: isFollowed
}
fragment NearbyGalleriesRail_partners on PartnerEdge {
node {
id
slug
...NearbyGalleryCard_partner
}
}
fragment NearbyGalleryCard_partner on Partner {
name
slug
type
profile {
image {
cropped(height: 300, width: 400, version: "wide") {
src
srcSet
}
}
...FollowProfileButton_profile
id
}
locationsConnection(first: 20) {
edges {
node {
city
displayCountry
id
}
}
}
}
*/
const node: ConcreteRequest = (function(){
var v0 = [
{
"defaultValue": null,
"kind": "LocalArgument",
"name": "near",
"type": "String!"
}
],
v1 = [
{
"kind": "Literal",
"name": "defaultProfilePublic",
"value": true
},
{
"kind": "Literal",
"name": "eligibleForListing",
"value": true
},
{
"kind": "Literal",
"name": "first",
"value": 12
},
{
"kind": "Variable",
"name": "near",
"variableName": "near"
},
{
"kind": "Literal",
"name": "sort",
"value": "RANDOM_SCORE_DESC"
}
],
v2 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
},
v3 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "slug",
"storageKey": null
},
v4 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "name",
"storageKey": null
};
return {
"fragment": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Fragment",
"metadata": null,
"name": "NearbyGalleriesRailRendererQuery",
"selections": [
{
"alias": null,
"args": (v1/*: any*/),
"concreteType": "PartnerConnection",
"kind": "LinkedField",
"name": "partnersConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "PartnerEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"args": null,
"kind": "FragmentSpread",
"name": "NearbyGalleriesRail_partners"
}
],
"storageKey": null
}
],
"storageKey": null
}
],
"type": "Query"
},
"kind": "Request",
"operation": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Operation",
"name": "NearbyGalleriesRailRendererQuery",
"selections": [
{
"alias": null,
"args": (v1/*: any*/),
"concreteType": "PartnerConnection",
"kind": "LinkedField",
"name": "partnersConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "PartnerEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Partner",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v2/*: any*/),
(v3/*: any*/),
(v4/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "type",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Profile",
"kind": "LinkedField",
"name": "profile",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "image",
"plural": false,
"selections": [
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "height",
"value": 300
},
{
"kind": "Literal",
"name": "version",
"value": "wide"
},
{
"kind": "Literal",
"name": "width",
"value": 400
}
],
"concreteType": "CroppedImageUrl",
"kind": "LinkedField",
"name": "cropped",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "src",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "srcSet",
"storageKey": null
}
],
"storageKey": "cropped(height:300,version:\"wide\",width:400)"
}
],
"storageKey": null
},
(v2/*: any*/),
(v3/*: any*/),
(v4/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "internalID",
"storageKey": null
},
{
"alias": "is_followed",
"args": null,
"kind": "ScalarField",
"name": "isFollowed",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "first",
"value": 20
}
],
"concreteType": "LocationConnection",
"kind": "LinkedField",
"name": "locationsConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "LocationEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Location",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "city",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "displayCountry",
"storageKey": null
},
(v2/*: any*/)
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": "locationsConnection(first:20)"
}
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": null
}
]
},
"params": {
"id": null,
"metadata": {},
"name": "NearbyGalleriesRailRendererQuery",
"operationKind": "query",
"text": "query NearbyGalleriesRailRendererQuery(\n $near: String!\n) {\n partnersConnection(first: 12, near: $near, eligibleForListing: true, defaultProfilePublic: true, sort: RANDOM_SCORE_DESC) {\n edges {\n ...NearbyGalleriesRail_partners\n }\n }\n}\n\nfragment FollowProfileButton_profile on Profile {\n id\n slug\n name\n internalID\n is_followed: isFollowed\n}\n\nfragment NearbyGalleriesRail_partners on PartnerEdge {\n node {\n id\n slug\n ...NearbyGalleryCard_partner\n }\n}\n\nfragment NearbyGalleryCard_partner on Partner {\n name\n slug\n type\n profile {\n image {\n cropped(height: 300, width: 400, version: \"wide\") {\n src\n srcSet\n }\n }\n ...FollowProfileButton_profile\n id\n }\n locationsConnection(first: 20) {\n edges {\n node {\n city\n displayCountry\n id\n }\n }\n }\n}\n"
}
};
})();
(node as any).hash = 'e1a8202ed2c0aaba45d3bf3481b9ddc3';
export default node; | the_stack |
import timekeeper from 'timekeeper'
import { RequestHandler } from 'express'
import { MiddlewareTestHarness } from '../../../../../../tests/utils'
import { authenticate, fetchAuthDetails, CLOCK_DRIFT_MS, GrantType } from '.'
import { TAuthenticateRequest, EAuthType } from '../../types'
// import { getSetupDetails, getAuth, updateAuthV3 } from '../../../../clients/integrations'
// import { mocked } from 'ts-jest/utils'
import Integration from '../../../../functions/integration'
import { authenticate as authCodeAuthenticate } from './auth-code'
import { authenticate as clientCredentialsAuthenticate } from './client-credentials'
import {
getTokenWithRefreshToken,
getTokenWithClientCredentials,
AuthorizationMethod,
BodyFormat
} from '../../../clients/oauth2'
import { responseToCredentials, getIdTokenJwt } from './common'
// import { expandAuthConfig } from '../../../../api-config/auth-config'
jest.mock('../../../../api-config/auth-config')
jest.mock('../../../../clients/integrations')
jest.mock('../../../../clients/oauth2')
jest.mock('./auth-code')
jest.mock('./client-credentials')
jest.mock('./common')
const requiredIntegrationConfig = {
authType: EAuthType.OAuth2,
authorizationURL: 'https://example.com/auth',
tokenURL: 'https://${authDomain}.example.com/token'
}
describe('authenticate', () => {
const testResponse = { test: 'response' }
const mockAuth = (test: MiddlewareTestHarness<TAuthenticateRequest>, middleware: RequestHandler) => {
// mocked(middleware).mockImplementationOnce((req: TAuthenticateRequest, res: Response, next: NextFunction) => {
// expect(req).toBe(test.req)
// res.json(testResponse).end()
// next()
// })
}
const setup = (grantType: GrantType | undefined) =>
new MiddlewareTestHarness<TAuthenticateRequest>({
configureRequest: req => {
req.integrationConfig = {
...requiredIntegrationConfig,
grantType
}
},
testMiddleware: authenticate
})
describe('when the grantType is not specified', () => {
it('passes through to the auth code authenticate middleware', async () => {
const test = setup(undefined)
mockAuth(test, authCodeAuthenticate)
await test
.get()
.expect(testResponse)
.expect(200)
})
})
describe('when the grantType is AuthCode', () => {
it('passes through to the auth code authenticate middleware', async () => {
const test = setup(GrantType.AuthCode)
mockAuth(test, authCodeAuthenticate)
await test
.get()
.expect(testResponse)
.expect(200)
})
})
describe('when the grantType is ClientCredentials', () => {
it('passes through to the client credentials authenticate middleware', async () => {
const test = setup(GrantType.ClientCredentials)
mockAuth(test, clientCredentialsAuthenticate)
await test
.get()
.expect(testResponse)
.expect(200)
})
})
describe('when the grantType is any other value', () => {
it('throws an InvalidGrantType error', async () => {
const test = setup('invalid' as GrantType)
await test.get().expect(422)
expect(test.err).toMatchSnapshot()
})
})
})
describe('fetchAuthDetails', () => {
const now = new Date(Date.UTC(2019, 0, 1, 0, 0, 30) - CLOCK_DRIFT_MS)
// const updatedAt = new Date(Date.UTC(2019, 0, 1, 0, 0, 0)).valueOf()
const expiresInNever = 0
const expiresInNotExpired = 30
const expiresInExpired = 29
const oAuthClientId = 'test-oauth-cient-id'
const clientSecret = 'test-client-secret'
const accessToken = 'test-access-token'
// const refreshToken = 'test-refresh-token'
// const idToken = 'test-id-token'
const setupId = 'test-setup-id'
// const connectParams = { connect: 'connect-param' }
const callbackParams = { param: 'value' }
const tokenResponse = { body: { hey: 'there' } }
const newAccessToken = 'new-access-token'
// const newRefreshToken = 'new-refresh-token'
// const newIdToken = 'new-id-token'
// const newExpiresIn = 42
const log = jest.fn()
const paramsBase: any = {
buid: 'test-alias',
scopedUserDataTableName: 'test-scoped-data-table',
servicesTableName: 'test-services-table',
environmentIdentifier: 'test-env-id',
integration: new Integration('test-buid'),
authId: 'test-authId',
connectParams: {
authDomain: 'auth22'
},
logger: { log }
}
const params = {
...paramsBase,
setupId
}
const setup = ({}: // expiresIn,
// withCallbackParams = false,
// withCredentials = true,
// withClientCredentials = true,
// withRefreshToken = true,
// withTokenResponse = false,
// idTokenValue = idToken,
// idTokenJwt
{
expiresIn: number
withCallbackParams?: boolean
withCredentials?: boolean
withClientCredentials?: boolean
withRefreshToken?: boolean
withTokenResponse?: boolean
idTokenValue?: string
idTokenJwt?: any
}) => {
// const effectiveRefreshToken = withRefreshToken ? refreshToken : 'non'
// const credentials = {
// setupId,
// connectParams,
// expiresIn,
// updatedAt,
// accessToken,
// idTokenJwt,
// callbackParamsJSON: withCallbackParams ? JSON.stringify(callbackParams) : undefined,
// clientId: withClientCredentials ? oAuthClientId : undefined,
// clientSecret: withClientCredentials ? clientSecret : undefined,
// idToken: idTokenValue,
// refreshToken: effectiveRefreshToken,
// tokenResponseJSON: withTokenResponse ? JSON.stringify(tokenResponse) : undefined
// }
// mocked(getSetupDetails)
// .mockResolvedValueOnce({ clientSecret, clientId: oAuthClientId })
// .mockClear()
// mocked(getAuth)
// .mockResolvedValueOnce(withCredentials ? credentials : undefined)
// .mockClear()
// mocked(updateAuthV3).mockClear()
log.mockClear()
// mocked(getIdTokenJwt).mockClear()
}
beforeAll(() => {
timekeeper.freeze(now)
})
afterAll(() => {
timekeeper.reset()
})
describe('when the token never expires', () => {
it('returns the details from the auth credentials', async () => {
setup({ expiresIn: expiresInNever })
const auth = await fetchAuthDetails(params, requiredIntegrationConfig)
expect(auth).toMatchSnapshot()
// expect(getSetupDetails).not.toHaveBeenCalled()
// expect(getAuth).toMatchSnapshot()
})
it('decodes any token call response JSON data', async () => {
setup({ expiresIn: expiresInNever, withTokenResponse: true })
const auth = await fetchAuthDetails(params, requiredIntegrationConfig)
expect(auth.tokenResponse).toEqual(tokenResponse)
})
it('looks up the clientId and clientSecret if not stored with the credentials', async () => {
setup({ expiresIn: expiresInNever, withClientCredentials: false })
const auth = await fetchAuthDetails(params, requiredIntegrationConfig)
// expect(getSetupDetails).toHaveBeenCalled()
expect(auth).toMatchObject({ clientSecret, clientId: oAuthClientId })
})
})
describe('when the token has NOT expired', () => {
const storedIdTokenJwt = { realmid: '123456789' }
const decodedIdTokenJwt = { realmid: '999666222' }
it('returns the details from the auth credentials', async () => {
setup({ expiresIn: expiresInNotExpired })
const auth = await fetchAuthDetails(params, requiredIntegrationConfig)
expect(auth).toMatchSnapshot()
// expect(getSetupDetails).not.toHaveBeenCalled()
// expect(getAuth).toMatchSnapshot()
})
describe('when there is a JWT Id Token stored', () => {
it('returns it', async () => {
setup({ expiresIn: expiresInNotExpired, idTokenJwt: storedIdTokenJwt })
const auth = await fetchAuthDetails(params, requiredIntegrationConfig)
expect(getIdTokenJwt).not.toHaveBeenCalled()
expect(auth.idTokenJwt).toEqual(storedIdTokenJwt)
})
})
describe('when there is NOT a JWT Id Token stored', () => {
it('attempts to decode the Id Token and returns the result', async () => {
// mocked(getIdTokenJwt).mockReturnValueOnce(decodedIdTokenJwt)
setup({ expiresIn: expiresInNotExpired })
const auth = await fetchAuthDetails(params, requiredIntegrationConfig)
expect(auth.idTokenJwt).toEqual(decodedIdTokenJwt)
})
})
it('decodes any token call response JSON data', async () => {
setup({ expiresIn: expiresInNotExpired, withTokenResponse: true })
const auth = await fetchAuthDetails(params, requiredIntegrationConfig)
expect(auth.tokenResponse).toEqual(tokenResponse)
})
it('returns any callback params data', async () => {
setup({ expiresIn: expiresInNotExpired, withCallbackParams: true })
const auth = await fetchAuthDetails(params, requiredIntegrationConfig)
expect(auth.callbackParams).toEqual(callbackParams)
})
})
describe('when the token has expired', () => {
// const expandedIntegrationConfig = {
// ...requiredIntegrationConfig,
// tokenURL: 'https://auth22.example.com/token'
// }
const refreshURL = 'https://example.com/refresh'
const newTokenResponse = { body: { new: 'data' } }
const refreshResponse = { accessToken: newAccessToken, decodedResponse: newTokenResponse }
// const newCredentials = {
// accessToken: newAccessToken,
// idToken: newIdToken,
// refreshToken: newRefreshToken,
// expiresIn: newExpiresIn
// }
beforeAll(() => {
// mocked(expandAuthConfig).mockReturnValue(expandedIntegrationConfig)
// mocked(getTokenWithClientCredentials).mockReturnValue(refreshResponse)
// mocked(getTokenWithRefreshToken).mockReturnValue(refreshResponse)
// mocked(responseToCredentials).mockReturnValue(newCredentials)
})
beforeEach(() => {
// mocked(expandAuthConfig).mockClear()
// mocked(getTokenWithClientCredentials).mockClear()
// mocked(getTokenWithRefreshToken).mockClear()
// mocked(responseToCredentials).mockClear()
})
it('refreshes the token using the auth credentials and setup details', async () => {
setup({ expiresIn: expiresInExpired })
const auth = await fetchAuthDetails(params, requiredIntegrationConfig)
// expect(getSetupDetails).toMatchSnapshot()
// expect(getAuth).toMatchSnapshot()
expect(responseToCredentials).toHaveBeenCalledWith(refreshResponse)
expect(getTokenWithRefreshToken).toMatchSnapshot()
expect(auth).toMatchSnapshot()
})
it('updates the stored auth credentials with the refreshed values', async () => {
setup({ expiresIn: expiresInExpired })
await fetchAuthDetails(params, requiredIntegrationConfig)
// expect(updateAuthV3).toMatchSnapshot()
})
it('keeps any callback params that were previously stored', async () => {
setup({ expiresIn: expiresInExpired, withCallbackParams: true })
await fetchAuthDetails(params, requiredIntegrationConfig)
// expect(updateAuthV3).toMatchSnapshot()
})
it('uses the refreshURL configuration option when specified', async () => {
const integrationConfig = {
...requiredIntegrationConfig,
refreshURL
}
setup({ expiresIn: expiresInExpired })
// mocked(expandAuthConfig).mockReturnValue(integrationConfig)
await fetchAuthDetails(params, integrationConfig)
expect(getTokenWithRefreshToken).toHaveBeenCalledWith(expect.objectContaining({ tokenURL: refreshURL }))
})
it('returns the token call response JSON data, merged with the previous value', async () => {
setup({ expiresIn: expiresInExpired, withTokenResponse: true })
const auth = await fetchAuthDetails(params, requiredIntegrationConfig)
expect(auth.tokenResponse).toEqual({ body: { hey: 'there', new: 'data' } })
})
it('returns any callback params data', async () => {
setup({ expiresIn: expiresInExpired, withCallbackParams: true })
const auth = await fetchAuthDetails(params, requiredIntegrationConfig)
expect(auth.callbackParams).toEqual(callbackParams)
})
describe('when there is no refresh token', () => {
describe('when the grant type is Client Credentials', () => {
it('gets a new token using the client credentials', async () => {
const integrationConfig = {
...requiredIntegrationConfig,
authorizationMethod: AuthorizationMethod.Header,
bodyFormat: BodyFormat.Form,
grantType: GrantType.ClientCredentials,
config: {
scope: ['read', 'write']
}
}
// const expandedIntegrationConfig = {
// ...integrationConfig,
// tokenURL: 'https://auth22.example.com/token'
// }
setup({ expiresIn: expiresInExpired, withRefreshToken: false })
// mocked(expandAuthConfig).mockReturnValueOnce(expandedIntegrationConfig)
const auth = await fetchAuthDetails(params, integrationConfig)
expect(getTokenWithClientCredentials).toMatchSnapshot()
expect(auth).toMatchSnapshot()
})
})
describe('when the grant type is NOT Client Credentials', () => {
it('raises an AccessTokenExpired error', async () => {
setup({ expiresIn: expiresInExpired, withRefreshToken: false })
await expect(fetchAuthDetails(params, requiredIntegrationConfig)).rejects.toMatchSnapshot()
})
})
})
})
describe("when the setupId used when connecting doesn't match the setupId sent by the user in the request", () => {
it('throws an InconsistentSetupId error', async () => {
setup({ expiresIn: expiresInNever })
const params = { ...paramsBase, setupId: 'other-setup-id', setupIdFromRequest: true }
await expect(fetchAuthDetails(params, requiredIntegrationConfig)).rejects.toMatchSnapshot()
})
})
describe("when the setupId used when connecting doesn't match the default setupId", () => {
it('logs a warning message about inconsistent setupId', async () => {
setup({ expiresIn: expiresInNever })
const params = { ...paramsBase, setupId: 'other-setup-id', setupIdFromRequest: false }
await fetchAuthDetails(params, requiredIntegrationConfig)
expect(log).toHaveBeenCalledWith(
// tslint:disable-next-line:max-line-length
'Warning: setupId inconsistency - setupId used for authorization setup differs from latest setupId stored in API dashboard'
)
})
})
describe('when no setupId parameter is present', () => {
it("doesn't raise an error", async () => {
setup({ expiresIn: expiresInNever })
const auth = await fetchAuthDetails(paramsBase, requiredIntegrationConfig)
expect(auth).toMatchObject({ accessToken })
})
})
describe('when no auth details can be found for the authId', () => {
it('raises an InvalidAuthId error', async () => {
setup({ expiresIn: expiresInNever, withCredentials: false })
await expect(fetchAuthDetails(paramsBase, requiredIntegrationConfig)).rejects.toMatchInlineSnapshot(`
[InvalidAuthId: No auth details were found using authId 'test-authId' for API 'test-alias'
Please try again with a valid authId or connect with this authId]
`)
})
})
}) | the_stack |
import { define } from 'elements-sk/define';
import { html } from 'lit-html';
import { jsonOrThrow } from 'common-sk/modules/jsonOrThrow';
import { stateReflector } from 'common-sk/modules/stateReflector';
import { fromParamSet, fromObject, ParamSet } from 'common-sk/modules/query';
import { HintableObject } from 'common-sk/modules/hintable';
import { sendBeginTask, sendEndTask, sendFetchError } from '../common';
import { ElementSk } from '../../../infra-sk/modules/ElementSk';
import { SearchCriteriaToHintableObject, SearchCriteriaFromHintableObject } from '../search-controls-sk';
import '../cluster-digests-sk';
import '../digest-details-sk';
import '../../../infra-sk/modules/paramset-sk';
import { SearchCriteria } from '../search-controls-sk/search-controls-sk';
import {
ClusterDiffLink, ClusterDiffResult, Digest, DigestComparison, DigestDetails, TestName,
} from '../rpc_types';
import { ClusterDiffNodeWithLabel, ClusterDigestsSk } from '../cluster-digests-sk/cluster-digests-sk';
import { ParamSetSkClickEventDetail } from '../../../infra-sk/modules/paramset-sk/paramset-sk';
function mergeParamsets(base: ParamSet, extra: ParamSet) {
for (const key in extra) {
const values = base[key] || [];
for (const value of extra[key]) {
if (!values.includes(value)) {
values.push(value);
}
}
base[key] = values;
}
}
function sortParamset(ps: ParamSet) {
for (const key in ps) {
ps[key].sort();
}
}
export class ClusterPageSk extends ElementSk {
private static template = (ele: ClusterPageSk) => {
if (!ele.grouping) {
return html`<h1>Need a test to cluster by</h1>`;
}
return html`
<div class=page-container>
<search-controls-sk .corpora=${ele.corpora}
.paramSet=${ele.paramset}
.searchCriteria=${ele.searchCriteria}
@search-controls-sk-change=${ele.searchControlsChanged}>
</search-controls-sk>
<cluster-digests-sk @selection-changed=${ele.selectionChanged}></cluster-digests-sk>
${ClusterPageSk.infoPanel(ele)}
</div>
`;
};
private static infoPanel = (ele: ClusterPageSk) => {
if (!ele.selectedDigests.length) {
return html`
<div>
Click on one digest or shift click multiple digests to see more specific information.
Use A/Z to Zoom In/Out and S/X to increase/decrease node distance.
</div>
<paramset-sk clickable
.paramsets=${[ele.paramsetOfAllDigests]}
@paramset-key-click=${ele.paramKeyClicked}
@paramset-key-value-click=${ele.paramValueClicked}>
</paramset-sk>
`;
}
if (ele.selectedDigests.length === 1) {
if (ele.digestDetails) {
return html`
<digest-details-sk .details=${ele.digestDetails.digest}
.commits=${ele.digestDetails.commits}>
</digest-details-sk>
`;
}
return html`<h2>Loading digest details</h2>`;
}
if (ele.selectedDigests.length === 2) {
if (ele.diffDetails) {
return html`
<digest-details-sk .details=${ele.diffDetails.left}
.right=${ele.diffDetails.right}>
</digest-details-sk>`;
}
return html`<h2>Loading diff details</h2>`;
}
const selectedDigestParamset = {};
for (const digest of ele.selectedDigests) {
mergeParamsets(selectedDigestParamset, ele.paramsetsByDigest[digest]);
}
sortParamset(selectedDigestParamset);
return html`
<div>Summary of ${ele.selectedDigests.length} digests</div>
<paramset-sk clickable
.paramsets=${[selectedDigestParamset]}
@paramset-key-click=${ele.paramKeyClicked}
@paramset-key-value-click=${ele.paramValueClicked}>
</paramset-sk>
`;
};
private corpora: string[] = [];
private paramset: ParamSet = {};
// TODO(kjlubick): Add a specific type for cluster requests.
private searchCriteria: SearchCriteria = {
corpus: '',
leftHandTraceFilter: {},
rightHandTraceFilter: {},
includePositiveDigests: false,
includeNegativeDigests: false,
includeUntriagedDigests: false,
includeDigestsNotAtHead: false,
includeIgnoredDigests: false,
minRGBADelta: 0,
maxRGBADelta: 0,
mustHaveReferenceImage: false,
sortOrder: 'descending',
};
private grouping: TestName = '';
private changeListID: string = '';
private crs: string = '';
// Keeps track of the digests the user has selected.
private selectedDigests: Digest[] = [];
// The combined paramset of all digests we loaded and displayed.
private paramsetOfAllDigests: ParamSet = {};
// A map of digest -> paramset. Useful for showing the params of the selected digests.
private paramsetsByDigest: { [key: string]: ParamSet } = {};
// These are the nodes and links that are drawn in the cluster-digests-sk. Holding onto them
// lets us update them (e.g. their labels) and easily re-layout the diagram.
private renderedNodes: ClusterDiffNodeWithLabel[] = [];
private renderedLinks: ClusterDiffLink[] = [];
private digestDetails: DigestDetails | null = null;
private diffDetails: DigestComparison | null = null;
// Allows us to abort fetches if we fetch again.
private fetchController?: AbortController;
private readonly stateChanged: ()=> void;
private readonly keyEventHandler: (e: KeyboardEvent)=> void;
constructor() {
super(ClusterPageSk.template);
this.stateChanged = stateReflector(
/* getState */() => {
const state = SearchCriteriaToHintableObject(this.searchCriteria) as any;
state.grouping = this.grouping;
state.changeListID = this.changeListID;
state.crs = this.crs;
return state;
},
/* setState */(newState) => {
if (!this._connected) {
return;
}
this.searchCriteria = SearchCriteriaFromHintableObject(newState);
this.grouping = newState.grouping as string;
this.changeListID = newState.changeListID as string;
this.crs = newState.crs as string;
this.fetchClusterData();
this._render();
},
);
this.keyEventHandler = (e: KeyboardEvent) => this.keyPressed(e);
}
connectedCallback() {
super.connectedCallback();
this._render();
// This assumes that there is only one multi-zoom-sk rendered on the page at a time (if there
// are multiple, they may all respond to keypresses at once).
document.addEventListener('keydown', this.keyEventHandler);
}
disconnectedCallback() {
super.disconnectedCallback();
document.removeEventListener('keydown', this.keyEventHandler);
}
/**
* Creates the RPC URL for fetching the data about clustering within this test (aka grouping).
*/
private clusterURL(): string {
if (!this.grouping) {
return '';
}
const sc = this.searchCriteria;
const query: ParamSet = { ...sc.leftHandTraceFilter };
query.name = [this.grouping];
const queryObj: HintableObject = {
source_type: sc.corpus,
query: fromParamSet(query),
pos: sc.includePositiveDigests,
neg: sc.includeNegativeDigests,
unt: sc.includeUntriagedDigests,
head: !sc.includeDigestsNotAtHead,
include: sc.includeIgnoredDigests,
};
const url = '/json/v2/clusterdiff';
return `${url}?${fromObject(queryObj)}`;
}
private fetchClusterData() {
const url = this.clusterURL();
if (!url) {
console.warn('no grouping/test was specified.');
return;
}
const extra = this.prefetch();
sendBeginTask(this);
sendBeginTask(this);
fetch(url, extra)
.then(jsonOrThrow)
.then((clusterDiffResult: ClusterDiffResult) => {
this.renderedNodes = clusterDiffResult.nodes || [];
this.renderedLinks = clusterDiffResult.links || [];
this.layoutCluster();
// TODO(kjlubick) remove json.test from the RPC value ( we have it in this.grouping)
this.paramsetOfAllDigests = clusterDiffResult.paramsetsUnion;
this.paramsetsByDigest = clusterDiffResult.paramsetByDigest;
this._render();
sendEndTask(this);
})
.catch((e) => sendFetchError(this, e, 'clusterdiff'));
const paramsetURL = '/json/v2/paramset';
fetch(paramsetURL, extra)
.then(jsonOrThrow)
.then((paramset: ParamSet) => {
// We split the paramset into a list of corpora...
this.corpora = paramset.source_type || [];
// ...and the rest of the keys. This is to make it so the layout is
// consistent with other pages (e.g. the search page, the by blame page, etc).
delete paramset.source_type;
// This cluster page is locked into the specific grouping (aka test name); We shouldn't
// support clustering across tests unless we absolutely need to. Doing so would probably
// require some backend changes.
delete paramset.name;
this.paramset = paramset;
this._render();
sendEndTask(this);
})
.catch((e) => sendFetchError(this, e, 'paramset'));
}
private fetchDetails(digest: Digest) {
const extra = this.prefetch();
sendBeginTask(this);
const urlObj: HintableObject = {
corpus: [this.searchCriteria.corpus],
test: [this.grouping],
digest: [digest],
};
if (this.changeListID) {
urlObj.changelist_id = [this.changeListID];
urlObj.crs = [this.crs];
}
const base = '/json/v2/details';
const url = `${base}?${fromObject(urlObj)}`;
fetch(url, extra)
.then(jsonOrThrow)
.then((digestDetails: DigestDetails) => {
this.digestDetails = digestDetails;
this._render();
sendEndTask(this);
})
.catch((e) => sendFetchError(this, e, 'digest details'));
}
private fetchDiff(leftDigest: Digest, rightDigest: Digest) {
const extra = this.prefetch();
sendBeginTask(this);
const urlObj: HintableObject = {
corpus: [this.searchCriteria.corpus],
test: [this.grouping],
left: [leftDigest],
right: [rightDigest],
};
if (this.changeListID) {
urlObj.changelist_id = [this.changeListID];
urlObj.crs = [this.crs];
}
const base = '/json/v2/diff';
const url = `${base}?${fromObject(urlObj)}`;
fetch(url, extra)
.then(jsonOrThrow)
.then((digestComparison: DigestComparison) => {
this.diffDetails = digestComparison;
this._render();
sendEndTask(this);
})
.catch((e) => sendFetchError(this, e, 'diff details'));
}
private keyPressed(e: KeyboardEvent) {
// Advice taken from https://medium.com/@uistephen/keyboardevent-key-for-cross-browser-key-press-check-61dbad0a067a
const cluster = this.querySelector<ClusterDigestsSk>('cluster-digests-sk');
if (!cluster) {
return;
}
const key = e.key || e.keyCode;
switch (key) {
case 'z': case 90: // Zoom in (loosen links)
cluster.changeLinkTightness(false);
break;
case 'a': case 65: // Zoom out (tighten links)
cluster.changeLinkTightness(true);
break;
case 's': case 83: // Increase distance between nodes
cluster.changeNodeRepulsion(true);
break;
case 'x': case 88: // Decrease distance between nodes
cluster.changeNodeRepulsion(false);
break;
default:
return;
}
// If we captured the key event, stop it from propagating.
e.stopPropagation();
}
private layoutCluster() {
this.querySelector<ClusterDigestsSk>('cluster-digests-sk')
?.setData(this.renderedNodes, this.renderedLinks);
}
private paramKeyClicked(e: CustomEvent<ParamSetSkClickEventDetail>) {
const keyClicked = e.detail.key;
for (const node of this.renderedNodes) {
const ps = this.paramsetsByDigest[node.name];
node.label = (ps[keyClicked] || '').toString();
}
this.layoutCluster();
}
private paramValueClicked(e: CustomEvent<ParamSetSkClickEventDetail>) {
const keyClicked = e.detail.key;
const valueClicked = e.detail.value!;
for (const node of this.renderedNodes) {
const ps = this.paramsetsByDigest[node.name];
if (ps[keyClicked].includes(valueClicked)) {
node.label = ps[keyClicked].toString();
} else {
node.label = '';
}
}
this.layoutCluster();
}
private prefetch() {
if (this.fetchController) {
// Kill any outstanding requests
this.fetchController.abort();
}
// Make a fresh abort controller for each set of fetches.
// They cannot be re-used once aborted.
this.fetchController = new AbortController();
return {
signal: this.fetchController.signal,
};
}
protected _render() {
super._render();
// Make the cluster draw to the full width.
const cluster = this.querySelector<ClusterDigestsSk>('cluster-digests-sk');
if (cluster) {
cluster.setWidth(cluster.offsetWidth);
}
}
private searchControlsChanged(e: CustomEvent<SearchCriteria>) {
this.searchCriteria = e.detail;
this.stateChanged();
this.fetchClusterData();
// Reset selection
this.digestDetails = null;
this.diffDetails = null;
this.selectedDigests = [];
this._render();
}
private selectionChanged(e: CustomEvent<Digest[]>) {
this.selectedDigests = e.detail;
const numDigests = this.selectedDigests.length;
this.digestDetails = null;
this.diffDetails = null;
if (numDigests === 1) {
this.fetchDetails(this.selectedDigests[0]);
} else if (numDigests === 2) {
this.fetchDiff(this.selectedDigests[0], this.selectedDigests[1]);
}
this._render();
}
}
define('cluster-page-sk', ClusterPageSk); | the_stack |
type Primitive = null | boolean | string | number | symbol
const TAB_CODE = 9
const LF_CODE = 10
const CR_CODE = 13
const SPACE_CODE = 32
const PERIOD_CODE = 46 // "."
const COMMA_CODE = 44 // ","
const SQUOTE_CODE = 39 // single quote
const DQUOTE_CODE = 34 // double quotes
const OPAREN_CODE = 40 // (
const CPAREN_CODE = 41 // )
const OBRACK_CODE = 91 // [
const CBRACK_CODE = 93 // ]
// const QUMARK_CODE = 63 // ?
const SEMCOL_CODE = 59 // ;
// const COLON_CODE = 58 // :
// Node Types
// ----------
// This is the full set of types that any JSEP node can be.
// Store them here to save space when minified
export const COMPOUND = Symbol("Compound")
export const LITERAL = Symbol("Literal")
export const IDENT = Symbol("Identifier")
export const MEMBER = Symbol("MemberExpression")
export const INDEX = Symbol("IndexExpression")
export const CALL = Symbol("CallExpression")
export const UNARY = Symbol("UnaryExpression")
export const BINARY = Symbol("BinaryExpression")
export const SEQUENCE = Symbol("SequenceExpression")
export const ARRAY = Symbol("ArrayExpression")
export const FAILURE = Symbol("Failure")
export type Expression = Identifier | Literal | UnaryExpression | BinaryExpression | CallExpression |
MemberExpression | IndexExpression | SequenceExpression | ArrayExpression | CompoundExpression
export type Identifier = {
type: typeof IDENT
name: string
}
export type Literal = {
type: typeof LITERAL
value: Primitive
}
export type UnaryExpression = {
type: typeof UNARY
operator: string
argument: Expression
prefix: boolean
}
export type BinaryExpression = {
type: typeof BINARY
operator: string
left: Expression
right: Expression
}
export type CallExpression = {
type: typeof CALL
args: Expression[]
callee: Expression
}
export type MemberExpression = {
type: typeof MEMBER
object: Expression
member: Identifier
}
export type IndexExpression = {
type: typeof INDEX
object: Expression
index: Expression
}
export type SequenceExpression = {
type: typeof SEQUENCE
expressions: Expression[]
}
export type ArrayExpression = {
type: typeof ARRAY
elements: Expression[]
}
export type CompoundExpression = {
type: typeof COMPOUND
body: Expression[]
}
export type Failure = {
type: typeof FAILURE
message: string
}
// Operations
// ----------
// Use a quickly-accessible map to store all of the unary operators
// Values are set to `1` (it really doesn't matter)
const unary_ops: {[key: string]: number} = {
"-": 1,
"!": 1,
"~": 1,
"+": 1,
}
// Also use a map for the binary operations but set their values to their
// binary precedence for quick reference (higher number = higher precedence)
// see [Order of operations](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence)
const binary_ops: {[key: string]: number} = {
"||": 1,
"&&": 2,
"|": 3,
"^": 4,
"&": 5,
"==": 6, "!=": 6,
"<": 7, ">": 7, "<=": 7, ">=": 7,
"<<": 8, ">>": 8,
"+": 9, "-": 9,
"*": 10, "/": 10, "%": 10,
"**": 11,
}
// Additional valid identifier chars, apart from a-z, A-Z and 0-9 (except on the starting char)
const additional_identifier_chars = new Set(["$", "_"])
// Literals
// ----------
// Store the values to return for the various literals we may encounter
const literals: {[key: string]: Primitive} = {
true: true,
false: false,
null: null,
}
function max_key_len(obj: object): number {
return Math.max(0, ...Object.keys(obj).map(k => k.length))
}
const max_unop_len = max_key_len(unary_ops)
const max_binop_len = max_key_len(binary_ops)
function binary_precedence(op_val: string): number {
return binary_ops[op_val] ?? 0
}
function is_decimal_digit(ch: number): boolean {
return ch >= 48 && ch <= 57 // 0...9
}
function is_identifier_start(ch: number): boolean {
return (ch >= 65 && ch <= 90) || // A...Z
(ch >= 97 && ch <= 122) || // a...z
(ch >= 128 && !binary_ops[String.fromCharCode(ch)]) || // any non-ASCII that is not an operator
(additional_identifier_chars.has(String.fromCharCode(ch))) // additional characters
}
function is_identifier_part(ch: number): boolean {
return is_identifier_start(ch) || is_decimal_digit(ch)
}
class ParseError extends Error {}
export class Parser {
// `index` stores the character number we are currently at
// All of the gobbles below will modify `index` as we move along
private index: number = 0
constructor(readonly expr: string) {}
get char(): string {
return this.expr.charAt(this.index)
}
get code(): number {
return this.expr.charCodeAt(this.index)
}
/**
* throw error at index of the expression
*/
error(message: string): never {
throw new ParseError(`${message} at character ${this.index}`)
}
/**
* Push `index` up to the next non-space character
*/
gobbleSpaces(): void {
let ch = this.code
while (ch == SPACE_CODE || ch == TAB_CODE || ch == LF_CODE || ch == CR_CODE) {
ch = this.expr.charCodeAt(++this.index)
}
}
/**
* Top-level method to parse all expressions and returns compound or single node
*/
parse(): Expression | Failure {
try {
const nodes = this.gobbleExpressions(undefined)
// If there's only one expression just try returning the expression
const node = nodes.length == 1 ? nodes[0] : {type: COMPOUND, body: nodes} as CompoundExpression
return node
} catch (error) {
if (error instanceof ParseError)
return {type: FAILURE, message: error.message}
else
throw error
}
}
/**
* top-level parser (but can be reused within as well)
*/
gobbleExpressions(until: number | undefined): Expression[] {
const nodes = []
while (this.index < this.expr.length) {
const ch_i = this.code
// Expressions can be separated by semicolons, commas, or just inferred without any
// separators
if (ch_i == SEMCOL_CODE || ch_i == COMMA_CODE) {
this.index++ // ignore separators
} else {
// Try to gobble each expression individually
const node = this.gobbleExpression()
if (node) {
nodes.push(node)
// If we weren't able to find a binary expression and are out of room, then
// the expression passed in probably has too much
} else if (this.index < this.expr.length) {
if (ch_i == until) {
break
}
this.error(`Unexpected '${this.char}'`)
}
}
}
return nodes
}
/**
* The main parsing function.
*/
gobbleExpression(): Expression | false {
const node = this.gobbleBinaryExpression()
this.gobbleSpaces()
return node
}
/**
* Search for the operation portion of the string (e.g. `+`, `===`)
* Start by taking the longest possible binary operations (3 characters: `===`, `!==`, `>>>`)
* and move down from 3 to 2 to 1 character until a matching binary operation is found
* then, return that binary operation
*/
gobbleBinaryOp(): string | false {
this.gobbleSpaces()
let to_check = this.expr.substr(this.index, max_binop_len)
let tc_len = to_check.length
while (tc_len > 0) {
// Don't accept a binary op when it is an identifier.
// Binary ops that start with a identifier-valid character must be followed
// by a non identifier-part valid character
if (binary_ops.hasOwnProperty(to_check) && (
!is_identifier_start(this.code) ||
(this.index + to_check.length < this.expr.length && !is_identifier_part(this.expr.charCodeAt(this.index + to_check.length)))
)) {
this.index += tc_len
return to_check
}
to_check = to_check.substr(0, --tc_len)
}
return false
}
/**
* This function is responsible for gobbling an individual expression,
* e.g. `1`, `1+2`, `a+(b*2)-Math.sqrt(2)`
*/
gobbleBinaryExpression(): Expression | false {
// First, try to get the leftmost thing
// Then, check to see if there's a binary operator operating on that leftmost thing
// Don't gobbleBinaryOp without a left-hand-side
const left = this.gobbleToken()
if (!left) {
return left
}
let biop = this.gobbleBinaryOp()
// If there wasn't a binary operator, just return the leftmost node
if (!biop) {
return left
}
// Otherwise, we need to start a stack to properly place the binary operations in their
// precedence structure
type BiOpInfo = {value: string, prec: number}
let biop_info = {value: biop, prec: binary_precedence(biop)}
const right = this.gobbleToken()
if (!right) {
this.error(`Expected expression after ${biop}`)
}
const stack: (Expression | BiOpInfo)[] = [left, biop_info, right]
// Properly deal with precedence using [recursive descent](http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm)
let cur_biop
while ((biop = this.gobbleBinaryOp())) {
const prec = binary_precedence(biop)
if (prec == 0) {
this.index -= biop.length
break
}
biop_info = {value: biop, prec}
cur_biop = biop
// Reduce: make a binary expression from the three topmost entries.
while ((stack.length > 2) && (prec <= (stack[stack.length - 2] as BiOpInfo).prec)) {
const right = stack.pop() as Expression
const biop = (stack.pop() as BiOpInfo).value
const left = stack.pop() as Expression
const node: Expression = {
type: BINARY,
operator: biop,
left,
right,
}
stack.push(node)
}
const node = this.gobbleToken()
if (!node) {
this.error(`Expected expression after ${cur_biop}`)
}
stack.push(biop_info, node)
}
let i = stack.length - 1
let node = stack[i]
while (i > 1) {
node = {
type: BINARY,
operator: (stack[i - 1] as BiOpInfo).value,
left: stack[i - 2] as Expression,
right: node as Expression,
}
i -= 2
}
return node as Expression
}
/**
* An individual part of a binary expression:
* e.g. `foo.bar(baz)`, `1`, `"abc"`, `(a % 2)` (because it's in parenthesis)
*/
gobbleToken(): Expression | false {
this.gobbleSpaces()
const ch = this.code
if (is_decimal_digit(ch) || ch == PERIOD_CODE) {
// Char code 46 is a dot `.` which can start off a numeric literal
return this.gobbleNumericLiteral()
}
let node: Expression | false = false
if (ch == SQUOTE_CODE || ch == DQUOTE_CODE) {
// Single or double quotes
node = this.gobbleStringLiteral()
} else if (ch == OBRACK_CODE) {
node = this.gobbleArray()
} else {
let to_check = this.expr.substr(this.index, max_unop_len)
let tc_len = to_check.length
while (tc_len > 0) {
// Don't accept an unary op when it is an identifier.
// Unary ops that start with a identifier-valid character must be followed
// by a non identifier-part valid character
if (unary_ops.hasOwnProperty(to_check) && (
!is_identifier_start(this.code) ||
(this.index + to_check.length < this.expr.length && !is_identifier_part(this.expr.charCodeAt(this.index + to_check.length)))
)) {
this.index += tc_len
const argument = this.gobbleToken()
if (!argument) {
this.error("missing unaryOp argument")
}
return {
type: UNARY,
operator: to_check,
argument,
prefix: true,
}
}
to_check = to_check.substr(0, --tc_len)
}
if (is_identifier_start(ch)) {
node = this.gobbleIdentifier()
if (literals.hasOwnProperty(node.name)) {
node = {
type: LITERAL,
value: literals[node.name],
}
}
} else if (ch == OPAREN_CODE) { // open parenthesis
node = this.gobbleGroup()
}
}
if (!node) {
return false
}
node = this.gobbleTokenProperty(node)
return node
}
/**
* Gobble properties of of identifiers/strings/arrays/groups.
* e.g. `foo`, `bar.baz`, `foo['bar'].baz`
* It also gobbles function calls:
* e.g. `Math.acos(obj.angle)`
*/
gobbleTokenProperty(node: Expression): Expression {
this.gobbleSpaces()
let ch = this.code
while (ch == PERIOD_CODE || ch == OBRACK_CODE || ch == OPAREN_CODE) {
this.index++
if (ch == PERIOD_CODE) {
this.gobbleSpaces()
node = {
type: MEMBER,
object: node,
member: this.gobbleIdentifier(),
}
} else if (ch == OBRACK_CODE) {
const expr = this.gobbleExpression()
if (!expr) {
this.error("Expected an expression")
}
node = {
type: INDEX,
object: node,
index: expr,
}
this.gobbleSpaces()
ch = this.code
if (ch !== CBRACK_CODE) {
this.error("Unclosed [")
}
this.index++
} else if (ch == OPAREN_CODE) {
// A function call is being made; gobble all the arguments
node = {
type: CALL,
args: this.gobbleArguments(CPAREN_CODE),
callee: node,
}
}
this.gobbleSpaces()
ch = this.code
}
return node
}
/**
* Parse simple numeric literals: `12`, `3.4`, `.5`. Do this by using a string to
* keep track of everything in the numeric literal and then calling `parseFloat` on that string
*/
gobbleNumericLiteral(): Literal {
let number = ""
while (is_decimal_digit(this.code)) {
number += this.expr.charAt(this.index++)
}
if (this.code == PERIOD_CODE) { // can start with a decimal marker
number += this.expr.charAt(this.index++)
while (is_decimal_digit(this.code)) {
number += this.expr.charAt(this.index++)
}
}
let ch = this.char
if (ch == "e" || ch == "E") { // exponent marker
number += this.expr.charAt(this.index++)
ch = this.char
if (ch == "+" || ch == "-") { // exponent sign
number += this.expr.charAt(this.index++)
}
while (is_decimal_digit(this.code)) { // exponent itself
number += this.expr.charAt(this.index++)
}
if (!is_decimal_digit(this.expr.charCodeAt(this.index - 1))) {
this.error(`Expected exponent (${number + this.char})`)
}
}
const code = this.code
// Check to make sure this isn't a variable name that start with a number (123abc)
if (is_identifier_start(code)) {
this.error(`Variable names cannot start with a number (${number + this.char})`)
} else if (code == PERIOD_CODE || (number.length == 1 && number.charCodeAt(0) == PERIOD_CODE)) {
this.error("Unexpected ','")
}
return {
type: LITERAL,
value: parseFloat(number),
}
}
/**
* Parses a string literal, staring with single or double quotes with basic support for escape codes
* e.g. `"hello world"`, `'this is\nJSEP'`
*/
gobbleStringLiteral(): Literal {
const quote = this.expr.charAt(this.index++)
let str = ""
let closed = false
while (this.index < this.expr.length) {
let ch = this.expr.charAt(this.index++)
if (ch == quote) {
closed = true
break
} else if (ch == "\\") {
// Check for all of the common escape codes
ch = this.expr.charAt(this.index++)
switch (ch) {
case "n": str += "\n"; break
case "r": str += "\r"; break
case "t": str += "\t"; break
case "b": str += "\b"; break
case "f": str += "\f"; break
case "v": str += "\x0B"; break
default : str += ch
}
} else {
str += ch
}
}
if (!closed) {
this.error(`Unclosed quote after "${str}"`)
}
return {
type: LITERAL,
value: str,
}
}
/**
* Gobbles only identifiers
* e.g.: `foo`, `_value`, `$x1`
* Also, this function checks if that identifier is a literal:
* (e.g. `true`, `false`, `null`) or `this`
*/
gobbleIdentifier(): Identifier {
let ch = this.code
const start = this.index
if (is_identifier_start(ch)) {
this.index++
} else {
this.error(`Unexpected '${this.char}'`)
}
while (this.index < this.expr.length) {
ch = this.code
if (is_identifier_part(ch)) {
this.index++
} else {
break
}
}
return {
type: IDENT,
name: this.expr.slice(start, this.index),
}
}
/**
* Gobbles a list of arguments within the context of a function call
* or array literal. This function also assumes that the opening character
* `(` or `[` has already been gobbled, and gobbles expressions and commas
* until the terminator character `)` or `]` is encountered.
* e.g. `foo(bar, baz)`, `my_func()`, or `[bar, baz]`
*/
gobbleArguments(termination: number): Expression[] {
const args: Expression[] = []
let closed = false
let separator_count = 0
while (this.index < this.expr.length) {
this.gobbleSpaces()
const ch_i = this.code
if (ch_i == termination) { // done parsing
closed = true
this.index++
if (termination == CPAREN_CODE && separator_count && separator_count >= args.length) {
this.error(`Unexpected token '${String.fromCharCode(termination)}'`)
}
break
} else if (ch_i == COMMA_CODE) { // between expressions
this.index++
separator_count++
if (separator_count !== args.length) { // missing argument
if (termination == CPAREN_CODE) {
this.error("Unexpected token ','")
} else if (termination == CBRACK_CODE) {
for (let arg = args.length; arg < separator_count; arg++) {
this.error("Expected an expression")
}
}
}
} else if (args.length !== separator_count && separator_count !== 0) {
// NOTE: `&& separator_count !== 0` allows for either all commas, or all spaces as arguments
this.error("Expected comma")
} else {
const node = this.gobbleExpression()
if (!node || node.type == COMPOUND) {
this.error("Expected comma")
}
args.push(node)
}
}
if (!closed) {
this.error(`Expected ${String.fromCharCode(termination)}`)
}
return args
}
/**
* Responsible for parsing a group of things within parentheses `()`
* that have no identifier in front (so not a function call)
* This function assumes that it needs to gobble the opening parenthesis
* and then tries to gobble everything within that parenthesis, assuming
* that the next thing it should see is the close parenthesis. If not,
* then the expression probably doesn't have a `)`
*/
gobbleGroup(): Expression | false {
this.index++
const nodes = this.gobbleExpressions(CPAREN_CODE)
if (this.code == CPAREN_CODE) {
this.index++
if (nodes.length == 1) {
return nodes[0]
} else if (!nodes.length) {
return false
} else {
return {
type: SEQUENCE,
expressions: nodes,
}
}
} else {
this.error("Unclosed (")
}
}
/**
* Responsible for parsing Array literals `[1, 2, 3]`
* This function assumes that it needs to gobble the opening bracket
* and then tries to gobble the expressions as arguments.
*/
gobbleArray(): ArrayExpression {
this.index++
return {
type: ARRAY,
elements: this.gobbleArguments(CBRACK_CODE),
}
}
} | the_stack |
import {ConstantBackoff, LRUBuffer, Websocket, WebsocketBuilder, WebsocketEvents} from "../src";
import {Server} from "ws";
describe("Testsuite for Websocket", () => {
const port = 42421;
const url = `ws://localhost:${port}`;
let ws: Websocket | undefined;
let wss: Server | undefined;
type WsInstanceWithEvent<K extends Event> = { instance: Websocket, event: K };
beforeEach(async () => {
await startServer(port).then(server => {
wss = server;
});
});
afterEach(async () => {
if (ws !== undefined)
await shutdownClientOrTimeout(ws, 100);
if (wss !== undefined)
await shutdownServerOrTimeout(wss, 100);
});
test("Websocket should fire onOpen-event when connection is established", async () => {
await new Promise<WsInstanceWithEvent<Event>>(resolve => {
ws = new WebsocketBuilder(url).onOpen((instance, event) => {
resolve({instance, event});
}).build();
}).then(e => {
expect(e.instance).toBe(ws);
expect(e.event.type).toBe(WebsocketEvents.open);
expect(e.instance.underlyingWebsocket?.readyState).toBe(WebSocket.OPEN);
});
});
test("Websocket should fire onClose-event when the server closes the connection", async () => {
await new Promise<WsInstanceWithEvent<CloseEvent>>(resolve => {
ws = new WebsocketBuilder(url)
.onClose((instance, event) => {
resolve({instance, event});
}).build();
wss?.close(); // close server
}).then(e => {
expect(e.instance).toBe(ws);
expect(e.event.type).toBe(WebsocketEvents.close);
expect(e.instance.underlyingWebsocket?.readyState).toBe(WebSocket.CLOSED);
});
});
test("Websocket should fire onClose-event when the client closes the connection", async () => {
const closeCode = 1000;
const closeReason = "client closed the connection";
await new Promise<WsInstanceWithEvent<CloseEvent>>(resolve => {
ws = new WebsocketBuilder(url)
.onOpen((instance, _) => {
instance.close(closeCode, closeReason); // close client
})
.onClose((instance, event) => {
resolve({instance, event});
}).build();
}).then(e => {
expect(e.instance).toBe(ws);
expect(e.event.type).toBe(WebsocketEvents.close);
expect(e.event.code).toBe(closeCode);
expect(e.event.reason).toBe(closeReason);
expect(e.instance.underlyingWebsocket?.readyState).toBe(WebSocket.CLOSED);
});
});
test("Websocket should fire onError-event when the server refuses the connection", async () => {
await new Promise<WsInstanceWithEvent<Event>>(resolve => {
wss?.close(); // close server
ws = new WebsocketBuilder(url)
.onError((instance, event) => {
resolve({instance, event});
}).build();
}).then(e => {
expect(e.instance).toBe(ws);
expect(e.event.type).toBe(WebsocketEvents.error);
expect(e.instance.underlyingWebsocket?.readyState).toBe(WebSocket.CLOSED);
});
});
test("Websocket should fire onMessage-event when a message is received", async () => {
const testMessage = "this is a test message.";
const onMessagePromise = new Promise<WsInstanceWithEvent<MessageEvent>>(resolve => {
ws = new WebsocketBuilder(url)
.onMessage((instance, event) => {
resolve({instance, event});
}).build();
}).then(e => {
expect(e.instance).toBe(ws);
expect(e.event.type).toBe(WebsocketEvents.message);
expect(e.event.data).toBe(testMessage);
expect(e.instance.underlyingWebsocket?.readyState).toBe(WebSocket.OPEN);
});
// wait for the client to connect to the server and then send a message to the client
if (wss !== undefined) {
await onClientConnected(wss).then(client => {
client.send(testMessage);
})
}
// wait for the client to receive the message, it should fire the 'onMessage'-event
await onMessagePromise;
});
test("Websocket should send messages when connected", async () => {
const testMessage = "this is a test message.";
const onConnectAndSendPromise = new Promise<void>(resolve => {
ws = new WebsocketBuilder(url)
.onOpen((instance, _) => {
instance.send(testMessage); // send message as soon as we are connected
resolve();
}).build();
});
const onReceivePromise = new Promise<string>(resolve => {
wss?.on('connection', socket => {
socket.onmessage = me => {
resolve(me.data.toString());
}
});
});
await onConnectAndSendPromise; // wait for client to connect and send the message
await onReceivePromise.then(actual => { // wait for server to receive the message and compare
expect(actual).toBe(testMessage);
})
});
test("Websocket should ignore send()-calls when the connection was closed by the user", async () => {
const testMessage = "this is a test message.";
await new Promise<void>(resolve => { // connect to server
ws = new WebsocketBuilder(url)
.onOpen((instance, _) => {
resolve();
}).build();
});
// monkey-patch the underlying websockets send()-method, to see if it is still called
let messagesSent = 0;
if (ws !== undefined && ws.underlyingWebsocket !== undefined) {
ws.underlyingWebsocket.send = (_: string | ArrayBufferLike | Blob | ArrayBufferView) => {
messagesSent++;
}
}
ws?.close(); // close connection from client-side
expect(ws!['closedByUser']).toBe(true); // should indicate that the connection was closed by user
ws?.send(testMessage);
expect(messagesSent).toBe(0); // should still be 0 since send() was never really called
});
test("Websocket should send buffered messages when the connection is (re-)established", async () => {
const testMessages = ["one", "two", "three"];
let onOpen: () => void;
let onClose: () => void;
let wsOnOpenPromise = new Promise<void>(resolve => onOpen = resolve);
const wsOnClosePromise = new Promise<void>(resolve => onClose = resolve);
ws = new WebsocketBuilder(url)
.withBuffer(new LRUBuffer<string>(10))
.withBackoff(new ConstantBackoff(100))
.onOpen(() => onOpen())
.onClose(() => onClose())
.build();
await wsOnOpenPromise; // wait for client to be connected
if (wss !== undefined) // shutdown the server
await shutdownServerOrTimeout(wss, 100);
await wsOnClosePromise; // wait for client to register the disconnect
// sending messages while disconnected should be buffered
expect((ws!['buffer'] as LRUBuffer<string>).len()).toBe(0);
testMessages.forEach(msg => ws?.send(msg));
expect((ws!['buffer'] as LRUBuffer<string>).len()).toBe(testMessages.length);
// re-start the server and create promise for when all messages are received
let onMessagesReceived: (msg: string[]) => void;
const onMessagesReceivedPromise = new Promise<string[]>(resolve => onMessagesReceived = resolve);
await startServer(port).then(server => {
wss = server;
wss.on('connection', socket => {
let buf = [] as string[];
socket.onmessage = me => {
buf.push(me.data.toString());
if (buf.length === testMessages.length)
onMessagesReceived(buf);
}
})
});
// wait for the client to re-connect, it should send out all pending messages...
wsOnOpenPromise = new Promise<void>(resolve => onOpen = resolve);
await wsOnOpenPromise;
// ...which are then received by the server in correct order...
await onMessagesReceivedPromise.then(actual => {
expect(actual).toEqual(testMessages);
})
// ...after which the clients message-buffer should be empty again
expect((ws!['buffer'] as LRUBuffer<string>).len()).toBe(0);
});
test("Websocket should remove event-listener correctly when removeEventListener() is called", async () => {
let count = 0;
const openEventListener = () => count++; // increment counter on every connect
let onOpen: () => void;
let onClose: () => void;
let wsOnOpenPromise = new Promise<void>(resolve => onOpen = resolve);
const wsOnClosePromise = new Promise<void>(resolve => onClose = resolve);
ws = new WebsocketBuilder(url)
.withBackoff(new ConstantBackoff(100))
.onOpen(() => onOpen())
.onOpen(openEventListener)
.onClose(() => onClose())
.build();
await wsOnOpenPromise; // wait for initial connection
expect(count).toBe(1); // openEventListener should be called exactly once at this point
ws.removeEventListener(WebsocketEvents.open, openEventListener); // unregister the event-handler
if (wss !== undefined) // shutdown the server
await shutdownServerOrTimeout(wss, 100);
await wsOnClosePromise; // wait for client to register the disconnect
// restart the server and wait for the client to connect
await startServer(port).then(server => wss = server);
wsOnOpenPromise = new Promise<void>(resolve => onOpen = resolve);
await wsOnOpenPromise;
expect(count).toBe(1); // count should still be 1, since the incrementing event-handler was unregistered
});
test("Websocket should remove event-listeners if they declare the 'once'-property as true", async () => {
let count = 0;
const openEventListener = () => count++; // increment counter on every connect
let onOpen: () => void;
let onClose: () => void;
let wsOnOpenPromise = new Promise<void>(resolve => onOpen = resolve);
const wsOnClosePromise = new Promise<void>(resolve => onClose = resolve);
ws = new WebsocketBuilder(url)
.withBackoff(new ConstantBackoff(100))
.onOpen(() => onOpen())
.onOpen(openEventListener, {once: true} as AddEventListenerOptions) // declare 'once'-property
.onClose(() => onClose())
.build();
await wsOnOpenPromise; // wait for initial connection
expect(count).toBe(1); // openEventListener should be called exactly once at this point
if (wss !== undefined) // shutdown the server
await shutdownServerOrTimeout(wss, 100);
await wsOnClosePromise; // wait for client to register the disconnect
// restart the server and wait for the client to connect
await startServer(port).then(server => wss = server);
wsOnOpenPromise = new Promise<void>(resolve => onOpen = resolve);
await wsOnOpenPromise;
expect(count).toBe(1); // count should still be 1, since the incrementing event-handler was unregistered
});
test("Websocket should try to reconnect when the connection is lost", async () => {
});
test("Websocket should fire retryEvent when trying to reconnect", async () => {
let retryCount = 0;
let onOpen: () => void;
let onClose: () => void;
let onRetry: () => void;
let wsOnOpenPromise = new Promise<void>(resolve => onOpen = resolve);
const wsOnClosePromise = new Promise<void>(resolve => onClose = resolve);
let wsOnRetryPromise = new Promise<void>(resolve => onRetry = resolve);
ws = new WebsocketBuilder(url)
.withBackoff(new ConstantBackoff(100)) // 100ms between retries
.onOpen(() => onOpen())
.onClose(() => onClose())
.onRetry(() => retryCount++)
.onRetry(() => onRetry())
.build();
await wsOnOpenPromise;
if (wss !== undefined) // shutdown the server
await shutdownServerOrTimeout(wss, 100);
await wsOnClosePromise; // wait for client to register the disconnect
await wsOnRetryPromise; // it should retry after 100ms and this will trigger the event
await delay(450); // after 450 more ms, it should've triggered another 4 times
expect(retryCount >= 3 || retryCount <= 6).toBeTruthy();
});
});
function delay(ms: number): Promise<void> {
return new Promise<void>(resolve => {
setTimeout(() => {
resolve();
}, ms);
})
}
function startServer(port: number): Promise<Server> {
return new Promise(resolve => {
const wss = new Server({port});
wss.on('listening', () => {
resolve(wss);
});
});
}
function shutdownServerOrTimeout(wss: Server, timeout: number) {
let timeoutPromise = delay(timeout);
let shutdownServerPromise = shutdownServer(wss);
return Promise.race([timeoutPromise, shutdownServerPromise]);
}
function shutdownServer(wss: Server): Promise<void> {
return new Promise<void>(resolve => {
wss.addListener("close", () => resolve());
wss.close();
});
}
function shutdownClientOrTimeout(ws: Websocket, timeout: number) {
let timeoutPromise = delay(timeout);
let shutdownClientPromise = shutdownClient(ws);
return Promise.race([timeoutPromise, shutdownClientPromise]);
}
function shutdownClient(ws: Websocket): Promise<void> {
return new Promise<void>(resolve => {
ws.addEventListener(WebsocketEvents.close, () => resolve());
ws.close();
});
}
function onClientConnected(wss: Server): Promise<WebSocket> {
return new Promise(resolve => {
wss.on('connection', (client: WebSocket) => {
resolve(client);
});
});
} | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement, Operator } from "../shared";
/**
* Statement provider for service [ses-v2](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonsimpleemailservicev2.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class SesV2 extends PolicyStatement {
public servicePrefix = 'ses';
/**
* Statement provider for service [ses-v2](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonsimpleemailservicev2.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Grants permission to create a new configuration set
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_CreateConfigurationSet.html
*/
public toCreateConfigurationSet() {
return this.to('CreateConfigurationSet');
}
/**
* Grants permission to create a configuration set event destination
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_CreateConfigurationSetEventDestination.html
*/
public toCreateConfigurationSetEventDestination() {
return this.to('CreateConfigurationSetEventDestination');
}
/**
* Grants permission to create a contact
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_CreateContact.html
*/
public toCreateContact() {
return this.to('CreateContact');
}
/**
* Grants permission to create a contact list
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_CreateContactList.html
*/
public toCreateContactList() {
return this.to('CreateContactList');
}
/**
* Grants permission to create a new custom verification email template
*
* Access Level: Write
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_CreateCustomVerificationEmailTemplate.html
*/
public toCreateCustomVerificationEmailTemplate() {
return this.to('CreateCustomVerificationEmailTemplate');
}
/**
* Grants permission to create a new pool of dedicated IP addresses
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_CreateDedicatedIpPool.html
*/
public toCreateDedicatedIpPool() {
return this.to('CreateDedicatedIpPool');
}
/**
* Grants permission to create a new predictive inbox placement test
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_CreateDeliverabilityTestReport.html
*/
public toCreateDeliverabilityTestReport() {
return this.to('CreateDeliverabilityTestReport');
}
/**
* Grants permission to start the process of verifying an email identity
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_CreateEmailIdentity.html
*/
public toCreateEmailIdentity() {
return this.to('CreateEmailIdentity');
}
/**
* Grants permission to create the specified sending authorization policy for the given identity
*
* Access Level: Permissions management
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_CreateEmailIdentityPolicy.html
*/
public toCreateEmailIdentityPolicy() {
return this.to('CreateEmailIdentityPolicy');
}
/**
* Grants permission to create an email template
*
* Access Level: Write
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_CreateEmailTemplate.html
*/
public toCreateEmailTemplate() {
return this.to('CreateEmailTemplate');
}
/**
* Grants permission to creates an import job for a data destination
*
* Access Level: Write
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_CreateImportJob.html
*/
public toCreateImportJob() {
return this.to('CreateImportJob');
}
/**
* Grants permission to delete an existing configuration set
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_DeleteConfigurationSet.html
*/
public toDeleteConfigurationSet() {
return this.to('DeleteConfigurationSet');
}
/**
* Grants permission to delete an event destination
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_DeleteConfigurationSetEventDestination.html
*/
public toDeleteConfigurationSetEventDestination() {
return this.to('DeleteConfigurationSetEventDestination');
}
/**
* Grants permission to delete a contact from a contact list
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_DeleteContact.html
*/
public toDeleteContact() {
return this.to('DeleteContact');
}
/**
* Grants permission to delete a contact list with all of its contacts
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_DeleteContactList.html
*/
public toDeleteContactList() {
return this.to('DeleteContactList');
}
/**
* Grants permission to delete an existing custom verification email template
*
* Access Level: Write
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_DeleteCustomVerificationEmailTemplate.html
*/
public toDeleteCustomVerificationEmailTemplate() {
return this.to('DeleteCustomVerificationEmailTemplate');
}
/**
* Grants permission to delete a dedicated IP pool
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_DeleteDedicatedIpPool.html
*/
public toDeleteDedicatedIpPool() {
return this.to('DeleteDedicatedIpPool');
}
/**
* Grants permission to delete an email identity
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_DeleteEmailIdentity.html
*/
public toDeleteEmailIdentity() {
return this.to('DeleteEmailIdentity');
}
/**
* Grants permission to delete the specified sending authorization policy for the given identity (an email address or a domain)
*
* Access Level: Permissions management
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_DeleteEmailIdentityPolicy.html
*/
public toDeleteEmailIdentityPolicy() {
return this.to('DeleteEmailIdentityPolicy');
}
/**
* Grants permission to delete an email template
*
* Access Level: Write
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_DeleteEmailTemplate.html
*/
public toDeleteEmailTemplate() {
return this.to('DeleteEmailTemplate');
}
/**
* Grants permission to remove an email address from the suppression list for your account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_DeleteSuppressedDestination.html
*/
public toDeleteSuppressedDestination() {
return this.to('DeleteSuppressedDestination');
}
/**
* Grants permission to get information about the email-sending status and capabilities for your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_GetAccount.html
*/
public toGetAccount() {
return this.to('GetAccount');
}
/**
* Grants permission to retrieve a list of the deny lists on which your dedicated IP addresses or tracked domains appear
*
* Access Level: Read
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_GetBlacklistReports.html
*/
public toGetBlacklistReports() {
return this.to('GetBlacklistReports');
}
/**
* Grants permission to get information about an existing configuration set
*
* Access Level: Read
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_GetConfigurationSet.html
*/
public toGetConfigurationSet() {
return this.to('GetConfigurationSet');
}
/**
* Grants permission to retrieve a list of event destinations that are associated with a configuration set
*
* Access Level: Read
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_GetConfigurationSetEventDestinations.html
*/
public toGetConfigurationSetEventDestinations() {
return this.to('GetConfigurationSetEventDestinations');
}
/**
* Grants permission to return a contact from a contact list
*
* Access Level: Read
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_GetContact.html
*/
public toGetContact() {
return this.to('GetContact');
}
/**
* Grants permission to return contact list metadata
*
* Access Level: Read
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_GetContactList.html
*/
public toGetContactList() {
return this.to('GetContactList');
}
/**
* Grants permission to return the custom email verification template for the template name you specify
*
* Access Level: Read
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_GetCustomVerificationEmailTemplate.html
*/
public toGetCustomVerificationEmailTemplate() {
return this.to('GetCustomVerificationEmailTemplate');
}
/**
* Grants permission to get information about a dedicated IP address
*
* Access Level: Read
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_GetDedicatedIp.html
*/
public toGetDedicatedIp() {
return this.to('GetDedicatedIp');
}
/**
* Grants permission to list the dedicated IP addresses a dedicated IP pool
*
* Access Level: Read
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_GetDedicatedIps.html
*/
public toGetDedicatedIps() {
return this.to('GetDedicatedIps');
}
/**
* Grants permission to get the status of the Deliverability dashboard
*
* Access Level: Read
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_GetDeliverabilityDashboardOptions.html
*/
public toGetDeliverabilityDashboardOptions() {
return this.to('GetDeliverabilityDashboardOptions');
}
/**
* Grants permission to retrieve the results of a predictive inbox placement test
*
* Access Level: Read
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_GetDeliverabilityTestReport.html
*/
public toGetDeliverabilityTestReport() {
return this.to('GetDeliverabilityTestReport');
}
/**
* Grants permission to retrieve all the deliverability data for a specific campaign
*
* Access Level: Read
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_GetDomainDeliverabilityCampaign.html
*/
public toGetDomainDeliverabilityCampaign() {
return this.to('GetDomainDeliverabilityCampaign');
}
/**
* Grants permission to retrieve inbox placement and engagement rates for the domains that you use to send email
*
* Access Level: Read
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_GetDomainStatisticsReport.html
*/
public toGetDomainStatisticsReport() {
return this.to('GetDomainStatisticsReport');
}
/**
* Grants permission to get information about a specific identity
*
* Access Level: Read
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_GetEmailIdentity.html
*/
public toGetEmailIdentity() {
return this.to('GetEmailIdentity');
}
/**
* Grants permission to return the requested sending authorization policies for the given identity (an email address or a domain)
*
* Access Level: Read
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_GetEmailIdentityPolicies.html
*/
public toGetEmailIdentityPolicies() {
return this.to('GetEmailIdentityPolicies');
}
/**
* Grants permission to return the template object, which includes the subject line, HTML part, and text part for the template you specify
*
* Access Level: Read
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_GetEmailTemplate.html
*/
public toGetEmailTemplate() {
return this.to('GetEmailTemplate');
}
/**
* Grants permission to provide information about an import job
*
* Access Level: Read
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_GetImportJob.html
*/
public toGetImportJob() {
return this.to('GetImportJob');
}
/**
* Grants permission to retrieve information about a specific email address that's on the suppression list for your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_GetSuppressedDestination.html
*/
public toGetSuppressedDestination() {
return this.to('GetSuppressedDestination');
}
/**
* Grants permission to list all of the configuration sets for your account
*
* Access Level: List
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_ListConfigurationSets.html
*/
public toListConfigurationSets() {
return this.to('ListConfigurationSets');
}
/**
* Grants permission to list all of the contact lists available for your account
*
* Access Level: List
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_ListContactLists.html
*/
public toListContactLists() {
return this.to('ListContactLists');
}
/**
* Grants permission to list the contacts present in a specific contact list
*
* Access Level: List
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_ListContacts.html
*/
public toListContacts() {
return this.to('ListContacts');
}
/**
* Grants permission to list all of the existing custom verification email templates for your account
*
* Access Level: List
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_ListCustomVerificationEmailTemplates.html
*/
public toListCustomVerificationEmailTemplates() {
return this.to('ListCustomVerificationEmailTemplates');
}
/**
* Grants permission to list all of the dedicated IP pools for your account
*
* Access Level: List
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_ListDedicatedIpPools.html
*/
public toListDedicatedIpPools() {
return this.to('ListDedicatedIpPools');
}
/**
* Grants permission to retrieve the list of the predictive inbox placement tests that you've performed, regardless of their statuses, for your account
*
* Access Level: List
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_ListDeliverabilityTestReports.html
*/
public toListDeliverabilityTestReports() {
return this.to('ListDeliverabilityTestReports');
}
/**
* Grants permission to list deliverability data for campaigns that used a specific domain to send email during a specified time range
*
* Access Level: Read
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_ListDomainDeliverabilityCampaigns.html
*/
public toListDomainDeliverabilityCampaigns() {
return this.to('ListDomainDeliverabilityCampaigns');
}
/**
* Grants permission to list the email identities for your account
*
* Access Level: List
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_ListEmailIdentities.html
*/
public toListEmailIdentities() {
return this.to('ListEmailIdentities');
}
/**
* Grants permission to list all of the email templates for your account
*
* Access Level: List
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_ListEmailTemplates.html
*/
public toListEmailTemplates() {
return this.to('ListEmailTemplates');
}
/**
* Grants permission to list all of the import jobs for your account
*
* Access Level: List
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_ListImportJobs.html
*/
public toListImportJobs() {
return this.to('ListImportJobs');
}
/**
* Grants permission to list email addresses that are on the suppression list for your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_ListSuppressedDestinations.html
*/
public toListSuppressedDestinations() {
return this.to('ListSuppressedDestinations');
}
/**
* Grants permission to retrieve a list of the tags (keys and values) that are associated with a specific resource for your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_ListTagsForResource.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to enable or disable the automatic warm-up feature for dedicated IP addresses
*
* Access Level: Write
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_PutAccountDedicatedIpWarmupAttributes.html
*/
public toPutAccountDedicatedIpWarmupAttributes() {
return this.to('PutAccountDedicatedIpWarmupAttributes');
}
/**
* Grants permission to update your account details
*
* Access Level: Write
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_PutAccountDetails.html
*/
public toPutAccountDetails() {
return this.to('PutAccountDetails');
}
/**
* Grants permission to enable or disable the ability to send email for your account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_PutAccountSendingAttributes.html
*/
public toPutAccountSendingAttributes() {
return this.to('PutAccountSendingAttributes');
}
/**
* Grants permission to change the settings for the account-level suppression list
*
* Access Level: Write
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_PutAccountSuppressionAttributes.html
*/
public toPutAccountSuppressionAttributes() {
return this.to('PutAccountSuppressionAttributes');
}
/**
* Grants permission to associate a configuration set with a dedicated IP pool
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_PutConfigurationSetDeliveryOptions.html
*/
public toPutConfigurationSetDeliveryOptions() {
return this.to('PutConfigurationSetDeliveryOptions');
}
/**
* Grants permission to enable or disable collection of reputation metrics for emails that you send using a particular configuration set
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_PutConfigurationSetReputationOptions.html
*/
public toPutConfigurationSetReputationOptions() {
return this.to('PutConfigurationSetReputationOptions');
}
/**
* Grants permission to enable or disable email sending for messages that use a particular configuration set
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_PutConfigurationSetSendingOptions.html
*/
public toPutConfigurationSetSendingOptions() {
return this.to('PutConfigurationSetSendingOptions');
}
/**
* Grants permission to specify the account suppression list preferences for a particular configuration set
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_PutConfigurationSetSuppressionOptions.html
*/
public toPutConfigurationSetSuppressionOptions() {
return this.to('PutConfigurationSetSuppressionOptions');
}
/**
* Grants permission to specify a custom domain to use for open and click tracking elements in email that you send for a particular configuration set
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_PutConfigurationSetTrackingOptions.html
*/
public toPutConfigurationSetTrackingOptions() {
return this.to('PutConfigurationSetTrackingOptions');
}
/**
* Grants permission to move a dedicated IP address to an existing dedicated IP pool
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_PutDedicatedIpInPool.html
*/
public toPutDedicatedIpInPool() {
return this.to('PutDedicatedIpInPool');
}
/**
* Grants permission to put Dedicated IP warm up attributes
*
* Access Level: Write
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_PutDedicatedIpWarmupAttributes.html
*/
public toPutDedicatedIpWarmupAttributes() {
return this.to('PutDedicatedIpWarmupAttributes');
}
/**
* Grants permission to enable or disable the Deliverability dashboard
*
* Access Level: Write
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_PutDeliverabilityDashboardOption.html
*/
public toPutDeliverabilityDashboardOption() {
return this.to('PutDeliverabilityDashboardOption');
}
/**
* Grants permission to associate a configuration set with an email identity
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_PutEmailIdentityConfigurationSetAttributes.html
*/
public toPutEmailIdentityConfigurationSetAttributes() {
return this.to('PutEmailIdentityConfigurationSetAttributes');
}
/**
* Grants permission to enable or disable DKIM authentication for an email identity
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_PutEmailIdentityDkimAttributes.html
*/
public toPutEmailIdentityDkimAttributes() {
return this.to('PutEmailIdentityDkimAttributes');
}
/**
* Grants permission to configure or change the DKIM authentication settings for an email domain identity
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_PutEmailIdentityDkimSigningAttributes.html
*/
public toPutEmailIdentityDkimSigningAttributes() {
return this.to('PutEmailIdentityDkimSigningAttributes');
}
/**
* Grants permission to enable or disable feedback forwarding for an email identity
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_PutEmailIdentityFeedbackAttributes.html
*/
public toPutEmailIdentityFeedbackAttributes() {
return this.to('PutEmailIdentityFeedbackAttributes');
}
/**
* Grants permission to enable or disable the custom MAIL FROM domain configuration for an email identity
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_PutEmailIdentityMailFromAttributes.html
*/
public toPutEmailIdentityMailFromAttributes() {
return this.to('PutEmailIdentityMailFromAttributes');
}
/**
* Grants permission to add an email address to the suppression list
*
* Access Level: Write
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_PutSuppressedDestination.html
*/
public toPutSuppressedDestination() {
return this.to('PutSuppressedDestination');
}
/**
* Grants permission to compose an email message to multiple destinations
*
* Access Level: Write
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_SendBulkEmail.html
*/
public toSendBulkEmail() {
return this.to('SendBulkEmail');
}
/**
* Grants permission to add an email address to the list of identities and attempts to verify it
*
* Access Level: Write
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_SendCustomVerificationEmail.html
*/
public toSendCustomVerificationEmail() {
return this.to('SendCustomVerificationEmail');
}
/**
* Grants permission to send an email message
*
* Access Level: Write
*
* Possible conditions:
* - .ifFeedbackAddress()
* - .ifFromAddress()
* - .ifFromDisplayName()
* - .ifRecipients()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_SendEmail.html
*/
public toSendEmail() {
return this.to('SendEmail');
}
/**
* Grants permission to add one or more tags (keys and values) to a specified resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_TagResource.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Grants permission to create a preview of the MIME content of an email when provided with a template and a set of replacement data
*
* Access Level: Write
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_TestRenderEmailTemplate.html
*/
public toTestRenderEmailTemplate() {
return this.to('TestRenderEmailTemplate');
}
/**
* Grants permission to remove one or more tags (keys and values) from a specified resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_UntagResource.html
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Grants permission to update the configuration of an event destination for a configuration set
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_UpdateConfigurationSetEventDestination.html
*/
public toUpdateConfigurationSetEventDestination() {
return this.to('UpdateConfigurationSetEventDestination');
}
/**
* Grants permission to update a contact's preferences for a list
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_UpdateContact.html
*/
public toUpdateContact() {
return this.to('UpdateContact');
}
/**
* Grants permission to update contact list metadata
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_UpdateContactList.html
*/
public toUpdateContactList() {
return this.to('UpdateContactList');
}
/**
* Grants permission to update an existing custom verification email template
*
* Access Level: Write
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_UpdateCustomVerificationEmailTemplate.html
*/
public toUpdateCustomVerificationEmailTemplate() {
return this.to('UpdateCustomVerificationEmailTemplate');
}
/**
* Grants permission to update the specified sending authorization policy for the given identity (an email address or a domain)
*
* Access Level: Permissions management
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_UpdateEmailIdentityPolicy.html
*/
public toUpdateEmailIdentityPolicy() {
return this.to('UpdateEmailIdentityPolicy');
}
/**
* Grants permission to update an email template
*
* Access Level: Write
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_UpdateEmailTemplate.html
*/
public toUpdateEmailTemplate() {
return this.to('UpdateEmailTemplate');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"CreateConfigurationSet",
"CreateConfigurationSetEventDestination",
"CreateContact",
"CreateContactList",
"CreateCustomVerificationEmailTemplate",
"CreateDedicatedIpPool",
"CreateDeliverabilityTestReport",
"CreateEmailIdentity",
"CreateEmailTemplate",
"CreateImportJob",
"DeleteConfigurationSet",
"DeleteConfigurationSetEventDestination",
"DeleteContact",
"DeleteContactList",
"DeleteCustomVerificationEmailTemplate",
"DeleteDedicatedIpPool",
"DeleteEmailIdentity",
"DeleteEmailTemplate",
"DeleteSuppressedDestination",
"PutAccountDedicatedIpWarmupAttributes",
"PutAccountDetails",
"PutAccountSendingAttributes",
"PutAccountSuppressionAttributes",
"PutConfigurationSetDeliveryOptions",
"PutConfigurationSetReputationOptions",
"PutConfigurationSetSendingOptions",
"PutConfigurationSetSuppressionOptions",
"PutConfigurationSetTrackingOptions",
"PutDedicatedIpInPool",
"PutDedicatedIpWarmupAttributes",
"PutDeliverabilityDashboardOption",
"PutEmailIdentityConfigurationSetAttributes",
"PutEmailIdentityDkimAttributes",
"PutEmailIdentityDkimSigningAttributes",
"PutEmailIdentityFeedbackAttributes",
"PutEmailIdentityMailFromAttributes",
"PutSuppressedDestination",
"SendBulkEmail",
"SendCustomVerificationEmail",
"SendEmail",
"TestRenderEmailTemplate",
"UpdateConfigurationSetEventDestination",
"UpdateContact",
"UpdateContactList",
"UpdateCustomVerificationEmailTemplate",
"UpdateEmailTemplate"
],
"Permissions management": [
"CreateEmailIdentityPolicy",
"DeleteEmailIdentityPolicy",
"UpdateEmailIdentityPolicy"
],
"Read": [
"GetAccount",
"GetBlacklistReports",
"GetConfigurationSet",
"GetConfigurationSetEventDestinations",
"GetContact",
"GetContactList",
"GetCustomVerificationEmailTemplate",
"GetDedicatedIp",
"GetDedicatedIps",
"GetDeliverabilityDashboardOptions",
"GetDeliverabilityTestReport",
"GetDomainDeliverabilityCampaign",
"GetDomainStatisticsReport",
"GetEmailIdentity",
"GetEmailIdentityPolicies",
"GetEmailTemplate",
"GetImportJob",
"GetSuppressedDestination",
"ListDomainDeliverabilityCampaigns",
"ListSuppressedDestinations",
"ListTagsForResource"
],
"List": [
"ListConfigurationSets",
"ListContactLists",
"ListContacts",
"ListCustomVerificationEmailTemplates",
"ListDedicatedIpPools",
"ListDeliverabilityTestReports",
"ListEmailIdentities",
"ListEmailTemplates",
"ListImportJobs"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type configuration-set to the statement
*
* https://docs.aws.amazon.com/ses/latest/APIReference/API_ConfigurationSet.html
*
* @param configurationSetName - Identifier for the configurationSetName.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onConfigurationSet(configurationSetName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:ses:${Region}:${Account}:configuration-set/${ConfigurationSetName}';
arn = arn.replace('${ConfigurationSetName}', configurationSetName);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type contact-list to the statement
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_ContactList.html
*
* @param contactListName - Identifier for the contactListName.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onContactList(contactListName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:ses:${Region}:${Account}:contact-list/${ContactListName}';
arn = arn.replace('${ContactListName}', contactListName);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type custom-verification-email-template to the statement
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_CustomVerificationEmailTemplateMetadata.html
*
* @param templateName - Identifier for the templateName.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onCustomVerificationEmailTemplate(templateName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:ses:${Region}:${Account}:custom-verification-email-template/${TemplateName}';
arn = arn.replace('${TemplateName}', templateName);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type dedicated-ip-pool to the statement
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_DedicatedIp.html
*
* @param dedicatedIPPool - Identifier for the dedicatedIPPool.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onDedicatedIpPool(dedicatedIPPool: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:ses:${Region}:${Account}:dedicated-ip-pool/${DedicatedIPPool}';
arn = arn.replace('${DedicatedIPPool}', dedicatedIPPool);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type deliverability-test-report to the statement
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_DeliverabilityTestReport.html
*
* @param reportId - Identifier for the reportId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onDeliverabilityTestReport(reportId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:ses:${Region}:${Account}:deliverability-test-report/${ReportId}';
arn = arn.replace('${ReportId}', reportId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type identity to the statement
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_IdentityInfo.html
*
* @param identityName - Identifier for the identityName.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onIdentity(identityName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:ses:${Region}:${Account}:identity/${IdentityName}';
arn = arn.replace('${IdentityName}', identityName);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type import-job to the statement
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_ImportJobSummary.html
*
* @param importJobId - Identifier for the importJobId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onImportJob(importJobId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:ses:${Region}:${Account}:import-job/${ImportJobId}';
arn = arn.replace('${ImportJobId}', importJobId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type template to the statement
*
* https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_Template.html
*
* @param templateName - Identifier for the templateName.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onTemplate(templateName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:ses:${Region}:${Account}:template/${TemplateName}';
arn = arn.replace('${TemplateName}', templateName);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Filters actions based on the "Return-Path" address, which specifies where bounces and complaints are sent by email feedback forwarding
*
* https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonses.html#amazonses-policy-keys
*
* Applies to actions:
* - .toSendEmail()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifFeedbackAddress(value: string | string[], operator?: Operator | string) {
return this.if(`FeedbackAddress`, value, operator || 'StringLike');
}
/**
* Filters actions based on the "From" address of a message
*
* https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonses.html#amazonses-policy-keys
*
* Applies to actions:
* - .toSendEmail()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifFromAddress(value: string | string[], operator?: Operator | string) {
return this.if(`FromAddress`, value, operator || 'StringLike');
}
/**
* Filters actions based on the "From" address that is used as the display name of a message
*
* https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonses.html#amazonses-policy-keys
*
* Applies to actions:
* - .toSendEmail()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifFromDisplayName(value: string | string[], operator?: Operator | string) {
return this.if(`FromDisplayName`, value, operator || 'StringLike');
}
/**
* Filters actions based on the recipient addresses of a message, which include the "To", "CC", and "BCC" addresses
*
* https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonses.html#amazonses-policy-keys
*
* Applies to actions:
* - .toSendEmail()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifRecipients(value: string | string[], operator?: Operator | string) {
return this.if(`Recipients`, value, operator || 'StringLike');
}
} | the_stack |
import {
API,
APIEvent,
DynamicPlatformPlugin,
HAP,
Logging,
PlatformAccessory,
PlatformConfig
} from "homebridge";
import {
MYQ_ACTIVE_DEVICE_REFRESH_DURATION,
MYQ_ACTIVE_DEVICE_REFRESH_INTERVAL,
MYQ_DEVICE_REFRESH_INTERVAL,
MYQ_MQTT_TOPIC,
PLATFORM_NAME,
PLUGIN_NAME
} from "./settings";
import { myQApi, myQDevice } from "@hjdhjd/myq";
import { myQAccessory } from "./myq-accessory";
import { myQGarageDoor } from "./myq-garagedoor";
import { myQLamp } from "./myq-lamp";
import { myQMqtt } from "./myq-mqtt";
import { myQOptionsInterface } from "./myq-config";
import util from "util";
interface myQPollInterface {
count: number,
maxCount: number,
}
export class myQPlatform implements DynamicPlatformPlugin {
private readonly accessories: PlatformAccessory[];
public readonly api: API;
public config!: myQOptionsInterface;
private readonly configuredAccessories: { [index: string]: myQAccessory };
public readonly hap: HAP;
public readonly log: Logging;
public readonly mqtt!: myQMqtt;
public readonly myQ!: myQApi;
private pollingTimer!: NodeJS.Timeout;
public readonly pollOptions!: myQPollInterface;
private unsupportedDevices: { [index: string]: boolean };
constructor(log: Logging, config: PlatformConfig, api: API) {
this.accessories = [];
this.api = api;
this.configuredAccessories = {};
this.hap = api.hap;
this.log = log;
this.log.debug = this.debug.bind(this);
this.unsupportedDevices = {};
// We can't start without being configured.
if(!config) {
return;
}
this.config = {
activeRefreshDuration: "activeRefreshDuration" in config ? parseInt(config.activeRefreshDuration as string) : MYQ_ACTIVE_DEVICE_REFRESH_DURATION,
activeRefreshInterval: "activeRefreshInterval" in config ? parseInt(config.activeRefreshInterval as string) : MYQ_ACTIVE_DEVICE_REFRESH_INTERVAL,
debug: config.debug === true,
email: config.email as string,
mqttTopic: "mqttTopic" in config ? config.mqttTopic as string : MYQ_MQTT_TOPIC,
mqttUrl: config.mqttUrl as string,
name: config.name as string,
options: config.options as string[],
password: config.password as string,
refreshInterval: "refreshInterval" in config ? parseInt(config.refreshInterval as string) : MYQ_DEVICE_REFRESH_INTERVAL
};
// We need login credentials or we're not starting.
if(!this.config.email || !this.config.password) {
this.log.error("No myQ login credentials configured.");
return;
}
// Make sure the active refresh duration is reasonable.
if((this.config.activeRefreshDuration > 300) || (this.config.activeRefreshDuration !== this.config.activeRefreshDuration)) {
this.log.info("Adjusting myQ API normal refresh duration from %s to %s." +
" Setting too high of a normal refresh duration is strongly discouraged due to myQ occasionally blocking accounts who overtax the myQ API.",
this.config.activeRefreshDuration, MYQ_ACTIVE_DEVICE_REFRESH_DURATION);
this.config.activeRefreshDuration = MYQ_ACTIVE_DEVICE_REFRESH_DURATION;
}
// Make sure the active refresh interval is reasonable.
if((this.config.activeRefreshInterval < 2) || (this.config.activeRefreshInterval !== this.config.activeRefreshInterval)) {
this.log.info("Adjusting myQ API active refresh interval from %s to %s." +
" Setting too short of an active refresh interval is strongly discouraged due to myQ occasionally blocking accounts who overtax the myQ API.",
this.config.activeRefreshInterval, MYQ_ACTIVE_DEVICE_REFRESH_INTERVAL);
this.config.activeRefreshInterval = MYQ_ACTIVE_DEVICE_REFRESH_INTERVAL;
}
// Make sure the refresh interval is reasonable.
if((this.config.refreshInterval < 5) || (this.config.refreshInterval !== this.config.refreshInterval)) {
this.log.info("Adjusting myQ API refresh interval from %s to %s seconds." +
" Even at this value, you are strongly encouraged to increase this to at least 10 seconds due to myQ occasionally blocking accounts who overtax the myQ API.",
this.config.refreshInterval, MYQ_DEVICE_REFRESH_INTERVAL);
this.config.refreshInterval = MYQ_DEVICE_REFRESH_INTERVAL;
}
this.debug("Debug logging on. Expect a lot of data.");
this.pollOptions = {
count: this.config.activeRefreshDuration / this.config.activeRefreshInterval,
maxCount: this.config.activeRefreshDuration / this.config.activeRefreshInterval
};
// Initialize our connection to the myQ API.
this.myQ = new myQApi(this.config.email, this.config.password, this.log);
// Create an MQTT connection, if needed.
if(!this.mqtt && this.config.mqttUrl) {
this.mqtt = new myQMqtt(this);
}
// Avoid a prospective race condition by waiting to begin our polling until Homebridge is done
// loading all the cached accessories it knows about, and calling configureAccessory() on each.
//
// Fire off our polling, with an immediate status refresh to begin with to provide us that responsive feeling.
api.on(APIEvent.DID_FINISH_LAUNCHING, this.poll.bind(this, this.config.refreshInterval * -1));
}
// This gets called when homebridge restores cached accessories at startup. We
// intentionally avoid doing anything significant here, and save all that logic
// for device discovery.
public configureAccessory(accessory: PlatformAccessory): void {
// Zero out the myQ device pointer on startup. This will be set by device discovery.
accessory.context.device = null;
// Add this to the accessory array so we can track it.
this.accessories.push(accessory);
}
// Discover new myQ devices and sync existing ones with the myQ API.
private discoverAndSyncAccessories(): boolean {
// Remove any device objects from now-stale accessories.
for(const accessory of this.accessories) {
// We only need to do this if the device object is set.
if(!accessory.context.device) {
continue;
}
// Check to see if this accessory's device object is still in myQ or not.
if(!this.myQ.devices.some(x => x.serial_number === (accessory.context.device as myQDevice).serial_number)) {
accessory.context.device = null;
}
}
// Iterate through the list of devices that myQ has returned and sync them with what we show HomeKit.
for(const device of this.myQ.devices) {
// If we have no serial number or device family, something is wrong.
if(!device.serial_number || !device.device_family) {
continue;
}
// We are only interested in garage door openers. Perhaps more types in the future.
switch(true) {
case (device.device_family.indexOf("garagedoor") !== -1):
case (device.device_family === "lamp"):
// We have a known device type. One of:
// - garage door.
// - lamp.
break;
default:
// Unless we are debugging device discovery, ignore any gateways.
// These are typically gateways, hubs, etc. that shouldn't be causing us to alert anyway.
if(!this.config.debug && device.device_family === "gateway") {
continue;
}
// If we've already informed the user about this one, we're done.
if(this.unsupportedDevices[device.serial_number]) {
continue;
}
// Notify the user we see this device, but we aren't adding it to HomeKit.
this.unsupportedDevices[device.serial_number] = true;
this.log.info("myQ device family '%s' is not currently supported, ignoring: %s.", device.device_family, this.myQ.getDeviceName(device));
continue;
break;
}
// Exclude or include certain openers based on configuration parameters.
if(!this.optionEnabled(device)) {
continue;
}
// Generate this device's unique identifier.
const uuid = this.hap.uuid.generate(device.serial_number);
// See if we already know about this accessory or if it's truly new. If it is new, add it to HomeKit.
let accessory = this.accessories.find(x => x.UUID === uuid);
if(!accessory) {
accessory = new this.api.platformAccessory(device.name, uuid);
this.log.info("%s: Adding %s device to HomeKit: %s.", device.name, device.device_family, this.myQ.getDeviceName(device));
// Register this accessory with homebridge and add it to the accessory array so we can track it.
this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [accessory]);
this.accessories.push(accessory);
}
// Link the accessory to it's device object.
accessory.context.device = device;
// If we've already configured this accessory, we're done here.
if(this.configuredAccessories[accessory.UUID]) {
continue;
}
// Eventually switch on multiple types of myQ devices. For now, it's garage doors only...
switch(true) {
case (device.device_family.indexOf("garagedoor") !== -1):
// We have a garage door.
this.configuredAccessories[accessory.UUID] = new myQGarageDoor(this, accessory);
break;
case (device.device_family === "lamp"):
// We have a lamp.
this.configuredAccessories[accessory.UUID] = new myQLamp(this, accessory);
break;
default:
// We should never get here.
this.log.error("Unknown device type detected: %s.", device.device_family);
break;
}
// Refresh the accessory cache with these values.
this.api.updatePlatformAccessories([accessory]);
}
// Remove myQ devices that are no longer found in the myQ API, but we still have in HomeKit.
for(const oldAccessory of this.accessories) {
const device = oldAccessory.context.device as myQDevice;
// We found this accessory in myQ. Figure out if we really want to see it in HomeKit.
if(device && this.optionEnabled(device)) {
continue;
}
this.log.info("%s: Removing myQ device from HomeKit.", oldAccessory.displayName);
delete this.configuredAccessories[oldAccessory.UUID];
this.accessories.splice(this.accessories.indexOf(oldAccessory), 1);
this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [oldAccessory]);
}
return true;
}
// Update HomeKit with the latest status from myQ.
private async updateAccessories(): Promise<boolean> {
// Refresh the full device list from the myQ API.
if(!(await this.myQ.refreshDevices())) {
return false;
}
// Sync myQ status and check for any new or removed accessories.
this.discoverAndSyncAccessories();
// Iterate through our accessories and update its status with the corresponding myQ status.
for(const key in this.configuredAccessories) {
this.configuredAccessories[key].updateState();
}
return true;
}
// Periodically poll the myQ API for status.
public poll(delay = 0): void {
let refresh = this.config.refreshInterval + delay;
// Clear the last polling interval out.
clearTimeout(this.pollingTimer);
// Normally, count just increments on each call. However, when we want to increase our
// polling frequency, count is set to 0 (elsewhere in the plugin) to put us in a more
// frequent polling mode. This is determined by the values configured for
// activeRefreshDuration and activeRefreshInterval which specify the maximum length of time
// for this increased polling frequency (activeRefreshDuration) and the actual frequency of
// each update (activeRefreshInterval).
if(this.pollOptions.count < this.pollOptions.maxCount) {
refresh = this.config.activeRefreshInterval + delay;
this.pollOptions.count++;
}
// Setup periodic update with our polling interval.
this.pollingTimer = setTimeout(() => {
void (async (): Promise<void> => {
// Refresh our myQ information and gracefully handle myQ errors.
if(!(await this.updateAccessories())) {
this.pollOptions.count = this.pollOptions.maxCount - 1;
}
// Fire off the next polling interval.
this.poll();
})();
}, refresh * 1000);
}
// Utility function to let us know if a myQ device should be visible in HomeKit or not.
private optionEnabled(device: myQDevice | null, option = "", defaultReturnValue = true): boolean {
// There are a couple of ways to hide and show devices that we support. The rules of the road are:
//
// 1. Explicitly hiding, or showing a gateway device propogates to all the devices that are plugged
// into that gateway. So if you have multiple gateways but only want one exposed in this plugin,
// you may do so by hiding it.
//
// 2. Explicitly hiding, or showing an opener device by its serial number will always override the above.
// This means that it's possible to hide a gateway, and all the openers that are attached to it, and then
// override that behavior on a single opener device that it's connected to.
//
// Nothing configured - we show all myQ devices to HomeKit.
if(!this.config.options) {
return defaultReturnValue;
}
// No device. Sure, we'll show it.
if(!device) {
return true;
}
if(option) {
this.debug("Option: %s", option);
}
// We've explicitly enabled this device.
if(this.config.options.indexOf("Enable." + (device.serial_number)) !== -1) {
return true;
}
// We've explicitly hidden this opener.
if(this.config.options.indexOf("Disable." + device.serial_number) !== -1) {
return false;
}
// If we don't have a gateway device attached to this opener, we're done here.
if(!device.parent_device_id) {
return true;
}
// We've explicitly shown the gateway this opener is attached to.
if(this.config.options.indexOf("Enable." + device.parent_device_id) !== -1) {
return true;
}
// We've explicitly hidden the gateway this opener is attached to.
if(this.config.options.indexOf("Disable." + device.parent_device_id) !== -1) {
return false;
}
// Nothing special to do - make this opener visible.
return defaultReturnValue;
}
// Utility for debug logging.
public debug(message: string, ...parameters: unknown[]): void {
if(this.config.debug) {
this.log.info(util.format(message, ...parameters));
}
}
} | the_stack |
import { expect } from "chai";
import { BezierCurve3d } from "../../bspline/BezierCurve3d";
import { BezierCurveBase } from "../../bspline/BezierCurveBase";
import { BSplineCurve3d } from "../../bspline/BSplineCurve";
import { BSplineCurve3dH } from "../../bspline/BSplineCurve3dH";
import { BSplineWrapMode, KnotVector } from "../../bspline/KnotVector";
// import { prettyPrint } from "./testFunctions";
import { CurveLocationDetail } from "../../curve/CurveLocationDetail";
import { CurvePrimitive } from "../../curve/CurvePrimitive";
import { GeometryQuery } from "../../curve/GeometryQuery";
import { LineSegment3d } from "../../curve/LineSegment3d";
import { LineString3d } from "../../curve/LineString3d";
import { Path } from "../../curve/Path";
import { StrokeOptions } from "../../curve/StrokeOptions";
import { Geometry } from "../../Geometry";
import { Angle } from "../../geometry3d/Angle";
import { AngleSweep } from "../../geometry3d/AngleSweep";
import { GrowableXYZArray } from "../../geometry3d/GrowableXYZArray";
import { Matrix3d } from "../../geometry3d/Matrix3d";
import { Plane3dByOriginAndUnitNormal } from "../../geometry3d/Plane3dByOriginAndUnitNormal";
import { Point3d } from "../../geometry3d/Point3dVector3d";
import { Range3d } from "../../geometry3d/Range";
import { Transform } from "../../geometry3d/Transform";
import { Point4d } from "../../geometry4d/Point4d";
import { Sample } from "../../serialization/GeometrySamples";
import { IModelJson } from "../../serialization/IModelJsonSchema";
import { Checker } from "../Checker";
import { GeometryCoreTestIO } from "../GeometryCoreTestIO";
import { prettyPrint } from "../testFunctions";
/** return knots [0,0,0, step, 2*step, ... N,N,N]
* where there are:
* * (order-1) leading and trailing clamp values.
* * internal knots with given step.
*/
function buildClampedSteppedKnots(numPoints: number, order: number, step: number): number[] {
const knots = [];
const degree = order - 1;
// left clamp always at 0 . . .
for (let i = 0; i < degree; i++) knots.push(0);
let b = step;
// true internal knots
for (let i = 1; i + order <= numPoints; i++) {
b = i * step;
knots.push(b);
}
// right clamp
b = (numPoints - order + 1) * step;
for (let i = 0; i < degree; i++) knots.push(b);
return knots;
}
/** return knots [-K*step, -(K-1)*step, .. 0, step, ....N, N+step, N+2*step]
* where there are:
* * (order-1) leading and trailing values, uniformly stepped
* * internal knots with given step.
* * trailing values wrap with period N
*/
function buildWrappableSteppedKnots(numInterval: number, order: number, step: number): number[] {
const knots = [];
const knot0 = - step * (order - 2);
for (let i = 0; i < numInterval + order - 2; i++)
knots.push(knot0 + i * step);
return knots;
}
function translateAndPush(allGeometry: GeometryQuery[], g: GeometryQuery | undefined, dx: number, dy: number) {
if (g) {
g.tryTranslateInPlace(dx, dy, 0);
allGeometry.push(g);
}
}
function showPlane(allGeometry: GeometryQuery[], plane: Plane3dByOriginAndUnitNormal, a: number, dx: number, dy: number) {
const origin = plane.getOriginRef();
const normal = plane.getNormalRef();
const frame = Transform.createOriginAndMatrix(origin,
Matrix3d.createRigidViewAxesZTowardsEye(normal.x, normal.y, normal.z));
const g = LineString3d.create(
frame.multiplyXYZ(-0.5 * a, 0, 0),
frame.multiplyXYZ(a, 0, 0),
frame.multiplyXYZ(a, a, 0),
frame.multiplyXYZ(0, a, 0),
origin,
frame.multiplyXYZ(0, 0, 2 * a));
if (g) {
g.tryTranslateInPlace(dx, dy, 0);
allGeometry.push(g);
}
}
function showPoint(allGeometry: GeometryQuery[], point: Point3d, a: number, dx: number, dy: number) {
const g = LineString3d.create(
point,
Point3d.create(point.x - a, point.y, point.z),
Point3d.create(point.x + a, point.y, point.z),
Point3d.create(point.x, point.y + a, point.z),
Point3d.create(point.x, point.y, point.z));
if (g) {
g.tryTranslateInPlace(dx, dy, 0);
allGeometry.push(g);
}
}
function ellipsePoints(a: number, b: number, sweep: AngleSweep, numStep: number): Point3d[] {
const points = [];
for (let f = 0.0; f <= 1.00001; f += 1.0 / numStep) {
const radians = sweep.fractionToRadians(f);
const c = Math.cos(radians);
const s = Math.sin(radians);
points.push(Point3d.create(a * c, b * s, 0.0));
}
return points;
}
/** Check if the linestring edgeLengths and angle meet stroke options demands
* @param edgeLengthFactor factor to apply to edgeLength conditions
* @param angleFactor factor to apply to angle conditions
*/
function checkStrokeProperties(ck: Checker, curve: CurvePrimitive, linestring: LineString3d, options: StrokeOptions,
angleFactor: number = 1.1, edgeLengthFactor: number = 1.1): boolean {
const numPoints = linestring.numPoints();
let ok = true;
if (ck.testLE(3, numPoints, "Expect 3 or more strokes")) {
let maxRadians = 0;
const vector0 = linestring.vectorBetween(0, 1)!;
let vector1;
let maxEdgeLength = vector0.magnitude();
for (let i = 1; i + 1 < numPoints; i++) {
vector1 = linestring.vectorBetween(i, i + 1)!;
maxEdgeLength = Geometry.maxXY(maxEdgeLength, vector1.magnitude());
maxRadians = Geometry.maxXY(maxRadians, vector0.angleTo(vector1).radians);
vector0.setFromVector3d(vector1);
}
if (options.maxEdgeLength)
if (!ck.testLE(maxRadians, edgeLengthFactor * options.maxEdgeLength, "strokeProperties edge length", curve))
ok = false;
if (options.angleTol)
if (!ck.testLE(maxRadians, angleFactor * options.angleTol.radians, "stroke properties angle", curve))
ok = false;
}
return ok;
}
/* eslint-disable no-console */
describe("BsplineCurve", () => {
it("HelloWorld", () => {
const ck = new Checker();
for (const rational of [false, true]) {
for (const order of [2, 3, 4, 5]) {
if (Checker.noisy.bsplineEvaluation) console.log("\n\n ************* order ", order);
// const a = 1.0;
const b = 2.0;
const points = [];
const degree = order - 1;
const numPoles = 5;
const knots = KnotVector.createUniformClamped(numPoles, degree, 0.0, 1.0);
// x should exactly match the knot value (even for high order)
for (let i = 0; i < numPoles; i++) {
const x = knots.grevilleKnot(i);
points.push(Point3d.create(x, b, 0));
}
let curve: BSplineCurve3d | BSplineCurve3dH;
if (rational)
curve = BSplineCurve3dH.createUniformKnots(points, order) as BSplineCurve3dH;
else
curve = BSplineCurve3d.createUniformKnots(points, order) as BSplineCurve3d;
const arcLength = curve.curveLength();
ck.testLE(arcLength, curve.quickLength() + Geometry.smallMetricDistance, "order", order);
if (Checker.noisy.bsplineEvaluation) {
console.log("BsplineCurve", curve);
console.log({ numPoles: curve.numPoles, numSpan: curve.numSpan });
console.log("length", arcLength);
}
for (let span = 0; span < curve.numSpan; span++) {
const p0 = curve.evaluatePointInSpan(span, 0.0);
const p1 = curve.evaluatePointInSpan(span, 0.5);
const p2 = curve.evaluatePointInSpan(span, 1.0);
for (const spanFraction of [0.2, 0.3, 0.9]) {
const knot = curve.spanFractionToKnot(span, spanFraction);
const spanPoint = curve.evaluatePointInSpan(span, spanFraction);
const spanTangent = curve.evaluatePointAndDerivativeInSpan(span, spanFraction);
const spanTangent2 = curve.knotToPointAnd2Derivatives(knot);
ck.testPoint3d(spanPoint, spanTangent2.origin, "evaluate == 2 derivative origin");
ck.testVector3d(spanTangent.direction, spanTangent2.vectorU, "evaluate == 2 derivative origin");
ck.testPoint3d(spanPoint, spanTangent.origin, "point and tangent evaluate");
const knotPoint = curve.knotToPoint(knot);
ck.testCoordinate(knot, knotPoint.x, "x == knot");
ck.testPoint3d(spanPoint, knotPoint, "spanPoint, knotPoint", order, span, spanFraction);
}
ck.testCoordinate(b, p1.y, "constant bspline y");
if (Checker.noisy.bsplineEvaluation) console.log("span", span, p0, p1, p2);
if (span + 1 < curve.numSpan) {
const q2 = curve.evaluatePointInSpan(span + 1, 0.0);
ck.testPoint3d(p2, q2, "span match");
}
}
}
}
ck.checkpoint("End BsplineCurve.HelloWorld");
expect(ck.getNumErrors()).equals(0);
});
it("strokes", () => {
const ck = new Checker();
const bcurves = Sample.createMixedBsplineCurves();
const defaultOption = StrokeOptions.createForCurves();
const angleOptions = StrokeOptions.createForCurves();
angleOptions.angleTol = Angle.createDegrees(5.0);
const edgeLengthOptions = StrokeOptions.createForCurves();
edgeLengthOptions.maxEdgeLength = 0.5;
const allOptions = [defaultOption, angleOptions, edgeLengthOptions];
const allGeometry: GeometryQuery[] = [];
let xShift = 0.0;
const dxShift = 10.0;
const dyShift = 10.0;
for (const curve of bcurves) {
translateAndPush(allGeometry, curve.clone(), xShift, 0.0);
let yShift = dyShift;
for (const options of allOptions) {
const linestring = LineString3d.create();
curve.emitStrokes(linestring, options);
const angleFactor = curve.order <= 2 ? 1000 : 1.6; // suppress angle test on linear case. Be fluffy on others.
translateAndPush(allGeometry, linestring, xShift, yShift);
if (!checkStrokeProperties(ck, curve, linestring, options, angleFactor, 1.1)) {
linestring.clear();
curve.emitStrokes(linestring, options);
}
yShift += dyShift;
}
xShift += dxShift;
}
GeometryCoreTestIO.saveGeometry(allGeometry, "BSplineCurve", "strokes");
ck.checkpoint("End BsplineCurve.strokes");
expect(ck.getNumErrors()).equals(0);
});
it("KnotVector", () => {
const ck = new Checker();
const numPoles = 10;
const degree = 3;
const a0 = 1;
const a1 = 22;
const knots = KnotVector.createUniformClamped(numPoles, degree, a0, a1);
const basisValues = knots.createBasisArray();
ck.testExactNumber(basisValues.length, degree + 1);
ck.testExactNumber(knots.knotLength01, a1 - a0, "knot range");
for (let spanIndex = 0; spanIndex < knots.numSpans; spanIndex++) {
const leftKnotFromSpan = knots.spanFractionToKnot(spanIndex, 0);
const rightKnotFromSpan = knots.spanFractionToKnot(spanIndex, 1);
const leftKnotFromArray = knots.knots[spanIndex + knots.leftKnotIndex];
ck.testCoordinate(leftKnotFromArray, leftKnotFromSpan, "left of span reproduces knots");
ck.testCoordinate(knots.spanIndexToSpanLength(spanIndex), rightKnotFromSpan - leftKnotFromSpan, "span length");
}
expect(ck.getNumErrors()).equals(0);
});
it("DoubleKnots", () => {
// stroke a bcurve with double knots .. bug was that the double knot intervals generated 0 or undefined stroke coordinates.
// Be sure the curve is all in one quadrant so 00 is NOT in the stroke range.
const ck = new Checker();
const bcurve = BSplineCurve3d.create(
[Point3d.create(1, 0),
Point3d.create(2, 0, 0),
Point3d.create(2, 1, 0),
Point3d.create(3, 1, 0),
Point3d.create(4, 0, 0),
Point3d.create(5, 1, 0)],
[0, 0, 0.5, 0.5, 0.75, 1, 1], 3)!;
const path = Path.create(bcurve);
const strokes = path.getPackedStrokes()!;
// console.log(prettyPrint(strokes));
const strokeRange = Range3d.create();
strokes.extendRange(strokeRange);
const curveRange = bcurve.range();
curveRange.expandInPlace(0.00001);
ck.testTrue(curveRange.containsRange(strokeRange));
ck.testFalse(strokeRange.containsXYZ(0, 0, 0));
expect(ck.getNumErrors()).equals(0);
});
it("Circles", () => {
// stroke a circular bcurve
const ck = new Checker();
const bcurves = Sample.createBspline3dHArcs();
const options = StrokeOptions.createForCurves();
options.chordTol = 0.02;
const allGeometry: GeometryQuery[] = [];
let dx = 0.0;
for (const bcurve of bcurves) {
const ls = LineString3d.create();
bcurve.emitStrokes(ls, options);
GeometryCoreTestIO.captureGeometry(allGeometry, bcurve, dx, 0, 0);
GeometryCoreTestIO.captureGeometry(allGeometry, ls, dx, 0, 0);
dx += 5.0;
}
GeometryCoreTestIO.saveGeometry(allGeometry, "BsplineCurve", "BCurveCircularArc");
expect(ck.getNumErrors()).equals(0);
});
it("BSplineCircleConversion", () => {
// stroke a circular bcurve
const ck = new Checker();
const microstationStyleArc = {
bcurve: {
closed: true,
knots: [-0.33333333333333337, 0.0, 0.0, 0.0, 0.33333333333333331, 0.33333333333333331, 0.66666666666666663, 0.66666666666666663,
1.0,
1.0,
1.0,
1.3333333333333333],
order: 3,
points: [
[1.0, 0.0, 0.0, 1.0],
[0.50000000000000011, 0.86602540378443860, 0.0, 0.50000000000000011],
[-0.49999999999999978, 0.86602540378443871, 0.0, 1.0], [-0.99999999999999989, 7.2674717409587315e-17, 0.0,
0.50000000000000011],
[-0.50000000000000044, -0.86602540378443849, 0.0, 1.0],
[0.49999999999999922, -0.86602540378443904, 0.0, 0.50000000000000011], [1.0,
-2.4492935982947064e-16, 0.0,
1.0]],
},
};
const g1 = IModelJson.Reader.parse(microstationStyleArc);
GeometryCoreTestIO.saveGeometry([g1], "BsplineCurve", "CircleIMJson");
expect(ck.getNumErrors()).equals(0);
});
it("SaturateBspline", () => {
const ck = new Checker();
const xStep = 120;
let xShift = 0;
const yShift = 60.0;
const allGeometry: GeometryQuery[] = [];
for (const factor of [0.5, 1, 3]) {
const transform = Transform.createScaleAboutPoint(Point3d.create(0, 0, 0), factor);
for (const allPoints of [
[Point3d.create(0, 0, 0),
Point3d.create(0, 10, 0),
Point3d.create(10, 10, 0),
Point3d.create(10, 0, 0),
Point3d.create(20, 0, 0),
Point3d.create(20, 10, 0),
Point3d.create(25, 5, 0),
Point3d.create(30, 5, 0),
Point3d.create(35, 10, 0)],
ellipsePoints(35, 20, AngleSweep.createStartEndDegrees(-45, 110), 9)]) {
transform.multiplyPoint3dArrayInPlace(allPoints);
for (let degree = 1; degree < 6; degree++) {
const bcurve = BSplineCurve3d.createUniformKnots(allPoints, degree + 1)!;
let cp: BezierCurveBase | undefined;
for (let spanIndex = 0; ; spanIndex++) {
cp = bcurve.getSaturatedBezierSpan3d(spanIndex, cp);
if (!cp) break;
const bezier = cp as BezierCurve3d;
const poles = bezier.copyPointsAsLineString();
translateAndPush(allGeometry, poles, xShift, yShift);
let shiftCount = 2;
for (const degrees of [24, 12, 6]) {
const options = StrokeOptions.createForCurves();
options.angleTol = Angle.createDegrees(degrees);
const strokes = LineString3d.create();
bezier.emitStrokes(strokes, options);
translateAndPush(allGeometry, strokes, xShift, (shiftCount++) * yShift);
}
translateAndPush(allGeometry, bezier.clone(), xShift, (shiftCount++) * yShift);
}
translateAndPush(allGeometry, bcurve, xShift, 0);
xShift += xStep;
}
}
}
GeometryCoreTestIO.saveGeometry(allGeometry, "BezierCurve3d", "BsplineSaturation");
expect(ck.getNumErrors()).equals(0);
});
it("IntersectPlane", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const bcurves = Sample.createMixedBsplineCurves();
const markerSize = 0.1;
const planeSize = 0.5;
let xShift = 0.0;
const yShift = 0.0;
for (const curve of bcurves) {
translateAndPush(allGeometry, curve.clone(), xShift, yShift);
for (const fraction of [0.2, 0.5, 0.73]) {
const tangentRay = curve.fractionToPointAndDerivative(fraction);
// Alter the ray z so it is not perpendicular ..
// tangentRay.direction.z += 0.02;
const intersections: CurveLocationDetail[] = [];
const plane = Plane3dByOriginAndUnitNormal.create(tangentRay.origin, tangentRay.direction)!; // This normalizes.
curve.appendPlaneIntersectionPoints(plane, intersections);
if (intersections.length > 1)
curve.appendPlaneIntersectionPoints(plane, intersections);
showPlane(allGeometry, plane, planeSize, xShift, yShift);
for (const detail of intersections) {
if (detail.point.isAlmostEqual(tangentRay.origin))
showPoint(allGeometry, detail.point, markerSize, xShift, yShift);
else
translateAndPush(allGeometry, LineSegment3d.create(tangentRay.origin, detail.point), xShift, yShift);
}
}
xShift += 10.0;
}
GeometryCoreTestIO.saveGeometry(allGeometry, "BSplineCurve", "IntersectPlane");
expect(ck.getNumErrors()).equals(0);
});
it("BsplineCurve3dHCoverage", () => {
const ck = new Checker();
const poleBuffer = new Float64Array([
0, 0, 0, 1,
1, 0, 0, 1,
1, 1, 0, 2, // weights vary !!
0, 1, 1, 1, // non planar
0, 2, 2, 1]);
const myKnots = [0, 0, 0, 1, 2, 2, 2];
const bcurve = BSplineCurve3dH.create(poleBuffer, myKnots, 4)!;
const bcurveB = BSplineCurve3dH.createUniformKnots(poleBuffer, 4);
ck.testFalse(bcurve.isInPlane(Plane3dByOriginAndUnitNormal.createXYPlane()));
ck.testUndefined(BSplineCurve3dH.createUniformKnots(poleBuffer, 10));
ck.testUndefined(BSplineCurve3dH.create(poleBuffer, myKnots, 10));
ck.testPointer(bcurveB);
const poleBufferA = bcurve.copyPointsFloat64Array();
const poleArray = bcurve.copyPoints();
if (ck.testExactNumber(poleArray.length * 4, poleBufferA.length)) {
for (let i = 0, k = 0; i < poleArray.length; i++) {
ck.testExactNumber(poleArray[i][0], poleBufferA[k++]);
ck.testExactNumber(poleArray[i][1], poleBufferA[k++]);
ck.testExactNumber(poleArray[i][2], poleBufferA[k++]);
ck.testExactNumber(poleArray[i][3], poleBufferA[k++]);
}
}
let n = 0;
const myPole = Point3d.create();
const myPoleH = Point4d.create();
ck.testUndefined(bcurve.getPolePoint4d(100));
for (; bcurve.getPolePoint3d(n, myPole) !== undefined; n++) {
const q = bcurve.getPolePoint4d(n, myPoleH);
if (ck.testPointer(q)) {
const w = myPoleH.w;
ck.testTrue(myPoleH.isAlmostEqualXYZW(myPole.x * w, myPole.y * w, myPole.z * w, w));
}
}
expect(ck.getNumErrors()).equals(0);
});
it("BsplineCurve3dCoverage", () => {
const ck = new Checker();
const poleBuffer = new Float64Array([
0, 0, 0,
1, 0, 0,
1, 1, 0,
0, 1, 1,
0, 2, 2]);
const myKnots = [0, 0, 0, 1, 2, 2, 2];
const bcurve = BSplineCurve3d.create(poleBuffer, myKnots, 4)!;
const bcurveB = BSplineCurve3d.createUniformKnots(poleBuffer, 4);
ck.testFalse(bcurve.isInPlane(Plane3dByOriginAndUnitNormal.createXYPlane()));
ck.testUndefined(BSplineCurve3d.createUniformKnots(poleBuffer, 10));
ck.testUndefined(BSplineCurve3d.create(poleBuffer, myKnots, 10));
ck.testPointer(bcurveB);
const poleBufferA = bcurve.copyPointsFloat64Array();
const poleArray = bcurve.copyPoints();
if (ck.testExactNumber(poleArray.length * 3, poleBufferA.length)) {
for (let i = 0, k = 0; i < poleArray.length; i++) {
ck.testExactNumber(poleArray[i][0], poleBufferA[k++]);
ck.testExactNumber(poleArray[i][1], poleBufferA[k++]);
ck.testExactNumber(poleArray[i][2], poleBufferA[k++]);
}
}
let n = 0;
const myPole = Point3d.create();
const myPoleH = Point4d.create();
ck.testUndefined(bcurve.getPolePoint4d(100));
ck.testUndefined(bcurve.getPolePoint3d(100));
for (; bcurve.getPolePoint3d(n, myPole) !== undefined; n++) {
const q = bcurve.getPolePoint4d(n, myPoleH);
if (ck.testPointer(q)) {
const w = myPoleH.w;
ck.testTrue(myPoleH.isAlmostEqualXYZW(myPole.x * w, myPole.y * w, myPole.z * w, w));
}
}
expect(ck.getNumErrors()).equals(0);
});
it("WeightedCurveMatch", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const poleArray = [
Point3d.create(0, 0, 0),
Point3d.create(1, 0, 0),
Point3d.create(1, 1, 0),
Point3d.create(0, 1, 1),
Point3d.create(0, 2, 2)];
for (const order of [3, 4, 5]) {
const myKnots = buildClampedSteppedKnots(poleArray.length, order, 1.0);
const bcurve3d = BSplineCurve3d.create(poleArray, myKnots, order)!;
const bcurve4d = BSplineCurve3dH.create(poleArray, myKnots, order)!;
allGeometry.push(bcurve3d);
allGeometry.push(bcurve4d);
for (const u of [0.2, 0.4, 0.5, 0.65, 1.0]) {
const point3d = bcurve3d.fractionToPoint(u);
const point4d = bcurve4d.fractionToPoint(u);
if (!ck.testPoint3d(point3d, point4d, u)) {
bcurve3d.fractionToPoint(u);
bcurve4d.fractionToPoint(u);
}
}
}
GeometryCoreTestIO.saveGeometry(allGeometry, "BSplineCurve", "WeightedCurveMatch");
expect(ck.getNumErrors()).equals(0);
});
it("WrappedCurves", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const xStep = 10.0;
const poleArray = [
Point3d.create(0, 0, 0),
Point3d.create(1, 0, 0),
Point3d.create(1, 1, 0),
Point3d.create(0, 1, 1),
Point3d.create(0, 2, 2)];
for (const order of [2, 3, 4, 5]) {
// wrap the points
const wrappedPoleArray = [];
for (const p of poleArray) wrappedPoleArray.push(p.clone());
for (let i = 0; i + 1 < order; i++) wrappedPoleArray.push(poleArray[i].clone());
const myKnots = buildWrappableSteppedKnots(poleArray.length, order, 1.0);
const bcurve3d = BSplineCurve3d.create(wrappedPoleArray, myKnots, order)!;
bcurve3d.setWrappable(BSplineWrapMode.OpenByAddingControlPoints);
const bcurve4d = BSplineCurve3dH.create(wrappedPoleArray, myKnots, order)!;
ck.testUndefined(bcurve3d.getSaturatedBezierSpan3d(100));
ck.testUndefined(bcurve4d.getSaturatedBezierSpan3dH(100));
bcurve4d.setWrappable(BSplineWrapMode.OpenByAddingControlPoints);
GeometryCoreTestIO.captureGeometry(allGeometry, bcurve3d.clone(), (order - 2) * xStep, 0, 0);
GeometryCoreTestIO.captureGeometry(allGeometry, bcurve4d.clone(), (order - 2) * xStep, xStep, 0);
ck.testTrue(bcurve3d.isClosable === BSplineWrapMode.OpenByAddingControlPoints);
ck.testTrue(bcurve4d.isClosable);
ck.testFalse(bcurve3d.isAlmostEqual(bcurve4d));
ck.testFalse(bcurve4d.isAlmostEqual(bcurve3d));
for (const u of [0.2, 0.4, 0.5, 0.65, 1.0]) {
const point3d = bcurve3d.fractionToPoint(u);
const point4d = bcurve4d.fractionToPoint(u);
if (!ck.testPoint3d(point3d, point4d, u)) {
bcurve3d.fractionToPoint(u);
bcurve4d.fractionToPoint(u);
}
// mess up poles first, then knots to reach failure branches in closure tests ...
wrappedPoleArray[0].x += 0.1;
const bcurve3dA = BSplineCurve3d.create(wrappedPoleArray, myKnots, order)!;
bcurve3dA.setWrappable(BSplineWrapMode.OpenByAddingControlPoints);
ck.testFalse(bcurve3dA.isClosable === BSplineWrapMode.OpenByAddingControlPoints);
const bcurve4dA = BSplineCurve3dH.create(wrappedPoleArray, myKnots, order)!;
bcurve4dA.setWrappable(BSplineWrapMode.OpenByAddingControlPoints);
ck.testFalse(bcurve4dA.isClosable);
// mess up knots. The knot test precedes the pole test, so this failure gets hit before the poles (which are already altered)
myKnots[order - 2] -= 0.1;
const bcurve3dB = BSplineCurve3d.create(wrappedPoleArray, myKnots, order)!;
bcurve3dB.setWrappable(BSplineWrapMode.OpenByAddingControlPoints);
ck.testFalse(bcurve3dB.isClosable === BSplineWrapMode.OpenByAddingControlPoints);
const bcurve4dB = BSplineCurve3dH.create(wrappedPoleArray, myKnots, order)!;
bcurve4dB.setWrappable(BSplineWrapMode.OpenByAddingControlPoints);
ck.testFalse(bcurve4dB.isClosable);
}
}
GeometryCoreTestIO.saveGeometry(allGeometry, "BSplineCurve", "WeightedCurveMatch");
expect(ck.getNumErrors()).equals(0);
});
it("StrokeWithKnotsA", () => {
const ck = new Checker();
const poles: Point3d[] = [];
for (let i = 0; i < 10; i++)
poles.push(Point3d.create(i, i * i, 0));
const knots = [0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 4];
const bcurve = BSplineCurve3d.create(poles, knots, 4)!;
const path = Path.create(bcurve);
const options = new StrokeOptions();
options.chordTol = 0.01;
const strokes = path.getPackedStrokes(options);
console.log(prettyPrint(strokes!.getPoint3dArray()));
expect(ck.getNumErrors()).equals(0);
});
it("StrokeWithKnotsB", () => {
const ck = new Checker();
const path = IModelJson.Reader.parse({
path: [{
bcurve: {
points: [[562203.9888586091, 4184365.4828894683, 13.075188058999167],
[562203.8776459384, 4184365.258953491, 13.075185855086009],
[562203.7664332676, 4184365.035017514, 13.075183688796626],
[562203.6552205969, 4184364.811081537, 13.07518155809684],
[562203.5440079262, 4184364.58714556, 13.075179427397055],
[562203.4327952556, 4184364.3632095824, 13.07517733228783],
[562203.3215825849, 4184364.1392736053, 13.075175270883584],
[562203.0991924296, 4184363.691472501, 13.075171148727286],
[562202.8768022744, 4184363.2436713967, 13.075167161227737],
[562202.6544121193, 4184362.7958702925, 13.075163294885328]],
knots: [0, 0, 0, 0, 0.2500197756132385, 0.2500197756132385, 0.2500197756132385,
0.500039551226476, 0.500039551226476, 0.500039551226476, 1, 1, 1, 1],
closed: false,
order: 4,
},
}],
});
ck.testTrue(path instanceof Path);
if (path instanceof Path) {
const options = new StrokeOptions();
options.chordTol = 0.01;
const strokes = path.getPackedStrokes(options);
console.log(prettyPrint(strokes!.getPoint3dArray()));
}
});
// problem: concept station observes under-stroked parabolas.
it("StrokeParabola", () => {
const ck = new Checker();
const x2 = 100.0;
const allGeometry: GeometryQuery[] = [];
let x0Out = 0.0;
for (let i = 0; ; i++) {
let options;
if (i === 0) {
options = undefined;
} else if (i === 1)
options = StrokeOptions.createForCurves();
else if (i === 2)
options = StrokeOptions.createForFacets();
else if (i === 3) {
options = StrokeOptions.createForCurves();
options.angleTol = Angle.createDegrees(5.0);
} else if (i === 4) {
options = StrokeOptions.createForCurves();
options.angleTol = Angle.createDegrees(2.5);
} else if (i === 5) {
options = StrokeOptions.createForCurves();
options.chordTol = 0.2;
} else if (i === 6) {
options = StrokeOptions.createForCurves();
options.chordTol = 0.02;
} else if (i === 7) {
options = StrokeOptions.createForCurves();
options.maxEdgeLength = 10.0;
} else
break;
for (const x1 of [30, 50, 80, 95]) {
let y0Out = 0.0;
const shift = 10.0;
for (const y2 of [10, 40, 80]) {
// const poles = [[0, 0, 0], [x1, 0, 0], [x2, y2, 0]];
const poles = [Point3d.create(0, 0, 0), Point3d.create(x1, 0, 0), Point3d.create(x2, y2, 0)];
const bcurve = BSplineCurve3d.createUniformKnots(GrowableXYZArray.create(poles), 3)!;
const bezier = BezierCurve3d.create(poles)!;
const strokes = LineString3d.create();
const bezierStrokes = LineString3d.create();
bcurve.emitStrokes(strokes, options);
bezier.emitStrokes(bezierStrokes, options);
GeometryCoreTestIO.captureGeometry(allGeometry, bcurve, x0Out, y0Out, 0);
GeometryCoreTestIO.captureGeometry(allGeometry, strokes, x0Out, y0Out, 0);
GeometryCoreTestIO.captureGeometry(allGeometry, bezier, x0Out, y0Out + shift, 0);
GeometryCoreTestIO.captureGeometry(allGeometry, bezierStrokes, x0Out, y0Out + shift, 0);
ck.testExactNumber(strokes.numPoints(), bezierStrokes.numPoints(), "bezier stroke counts the same for isolated and bspline");
y0Out += 100;
}
x0Out += 100;
}
x0Out += 200;
}
GeometryCoreTestIO.saveGeometry(allGeometry, "BSpline", "StrokeParabola");
expect(ck.getNumErrors()).equals(0);
});
}); | the_stack |
import { expect } from 'chai'
import { parseError } from '../../src/lib/squirrel-error-parser'
describe('parseError', () => {
it('parses a missing Squirrel error', () => {
// Source:
// https://github.com/electron/electron/blob/ad90de0c822490664bdb3a3d265f4a0fce3f69de/lib/browser/api/auto-updater/auto-updater-win.js#L29
const input = new Error('Can not find Squirrel')
const output = parseError(input)
expect(output).to.not.be.null
})
it('parses a Squirrel network error', () => {
// see https://github.com/desktop/desktop/issues/2288 for context
const input = new Error(`Command failed: 4294967295
System.AggregateException: One or more errors occurred. ---> System.Net.WebException: The remote name could not be resolved: 'central.github.com'
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Squirrel.Utility.<LogIfThrows>d__38\`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Squirrel.FileDownloader.<DownloadUrl>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Squirrel.UpdateManager.CheckForUpdateImpl.<CheckForUpdate>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Squirrel.UpdateManager.<CheckForUpdate>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Squirrel.Update.Program.<Download>d__7.MoveNext()
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task\`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task\`1.get_Result()
at Squirrel.Update.Program.executeCommandLine(String[] args)
at Squirrel.Update.Program.main(String[] args)
at Squirrel.Update.Program.Main(String[] args)
---> (Inner Exception #0) System.Net.WebException: The remote name could not be resolved: 'central.github.com'
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Squirrel.Utility.<LogIfThrows>d__38\`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Squirrel.FileDownloader.<DownloadUrl>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Squirrel.UpdateManager.CheckForUpdateImpl.<CheckForUpdate>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Squirrel.UpdateManager.<CheckForUpdate>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Squirrel.Update.Program.<Download>d__7.MoveNext()<---
`)
const output = parseError(input)
expect(output).to.not.be.null
})
it('parses a timeout error', () => {
const input = new Error(`Command failed: 4294967295
System.AggregateException: One or more errors occurred. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 54.82.67.239:443
at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Squirrel.Utility.<LogIfThrows>d__38\`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Squirrel.FileDownloader.<DownloadUrl>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Squirrel.UpdateManager.CheckForUpdateImpl.<CheckForUpdate>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Squirrel.UpdateManager.<CheckForUpdate>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Squirrel.Update.Program.<Download>d__7.MoveNext()
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task\`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task\`1.get_Result()
at Squirrel.Update.Program.executeCommandLine(String[] args)
at Squirrel.Update.Program.main(String[] args)
at Squirrel.Update.Program.Main(String[] args)
---> (Inner Exception #0) System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 54.82.67.239:443
at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Squirrel.Utility.<LogIfThrows>d__38\`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Squirrel.FileDownloader.<DownloadUrl>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Squirrel.UpdateManager.CheckForUpdateImpl.<CheckForUpdate>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Squirrel.UpdateManager.<CheckForUpdate>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Squirrel.Update.Program.<Download>d__7.MoveNext()<---`)
const output = parseError(input)
expect(output).to.not.be.null
})
it('passes through an empty error', () => {
const input = new Error()
const output = parseError(input)
expect(output).to.be.null
})
}) | the_stack |
import { v4 as guid } from "uuid";
import {
CosmosClient,
Item,
ItemDefinition,
Items,
OperationType,
Resource,
StatusCodes
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
} from "../../dist";
import logger from "./logger";
import lwwSprocDef from "./lwwSprocDef";
export class ConflictWorker {
private readonly clients: Map<string, CosmosClient> = new Map();
constructor(
private readonly databaseName: string,
private readonly basicContainerName: string,
private readonly manualContainerName: string,
private readonly lwwContainerName: string,
private readonly udpContainerName: string
) {}
public addClient(region: string, client: CosmosClient): void {
this.clients.set(region, client);
}
public async init(): Promise<void> {
const createClient = this.clients.values().next().value;
const { database } = await createClient.databases.createIfNotExists({ id: this.databaseName });
await database.containers.createIfNotExists({ id: this.basicContainerName });
await database.containers.createIfNotExists({
id: this.manualContainerName,
conflictResolutionPolicy: {
mode: "Custom"
}
});
await database.containers.createIfNotExists({
id: this.lwwContainerName,
conflictResolutionPolicy: {
mode: "LastWriterWins",
conflictResolutionPath: "/regionId"
}
});
const { container: udpContainer } = await database.containers.createIfNotExists({
id: this.udpContainerName,
conflictResolutionPolicy: {
mode: "Custom",
conflictResolutionProcedure: `dbs/${this.databaseName}/colls/${this.udpContainerName}/sprocs/resolver`
}
});
// See ./lwwSprocDef for the stored procedure definition include the logic
await udpContainer.scripts.storedProcedures.create(lwwSprocDef);
}
public async RunManualConflict(): Promise<void> {
console.log("Insert Conflict");
await this.RunInsertConflictonManual();
console.log("Update Conflict");
await this.RunUpdateConflictOnManual();
console.log("Delete Conflict");
await this.RunDeleteConflictOnManual();
}
public async RunLWWConflict(): Promise<void> {
console.log("Insert Conflict");
await this.RunInsertConflictOnLWW();
console.log("Update Conflict");
await this.RunUpdateConflictOnLWW();
console.log("Delete Conflict");
await this.RunDeleteConflictOnLWW();
}
public async RunUDP(): Promise<void> {
console.log("Insert Conflict");
await this.RunInsertConflictOnUdp();
console.log("Update Conflict");
await this.RunUpdateConflictOnUdp();
console.log("Delete Conflict");
await this.RunDeleteConflictsOnUdp();
}
private async RunInsertConflictonManual(): Promise<void> {
do {
let p = logger(
`Performing conflicting insert across ${this.clients.size} regions on ${this.manualContainerName}`
).start();
try {
const insertTask: Array<Promise<ItemDefinition>> = [];
const itemBase = { id: guid() };
let index = 0;
for (const [clientRegion, client] of this.clients.entries()) {
const container = client.database(this.databaseName).container(this.manualContainerName);
const newDef = { regionId: index++, regionEndpoint: clientRegion, ...itemBase }; // TODO: ReadEndpoint?
insertTask.push(this.tryInsertItem(container.items, newDef));
}
const items = await Promise.all(insertTask);
p.succeed();
const numberOfConflicts = items.reduce<number>(
(prev, curr) => (curr !== null ? ++prev : prev),
0
);
if (numberOfConflicts > 1) {
p = logger(`Caused ${numberOfConflicts}, verifying conflict resolution`).succeed();
for (const item of items) {
if (item !== null) {
await this.validateAllManualConflict(item);
}
}
break;
} else {
console.log("Retrying insert to induce conflicts");
}
} catch (err) {
p.fail();
throw err;
}
} while (true); // eslint-disable-line no-constant-condition
}
private async RunUpdateConflictOnManual(): Promise<void> {
let retryCount = 5;
do {
const itemBase = { id: guid() };
const [initialRegionName, initialClient] = this.clients.entries().next().value;
const container = initialClient
.database(this.databaseName)
.container(this.manualContainerName);
const item = { regionId: 0, regionEndpoint: initialRegionName, ...itemBase }; // TODO: ReadEndpoint?
const { resource: newItemDef } = await container.items.create(item);
await this.sleep(1000); // 1 second for the write to sync
console.log(
`1) Performing conflicting update across ${this.clients.size} regions on ${this.manualContainerName}`
);
const updates: Array<Promise<ItemDefinition>> = [];
let index = 0;
for (const [regionName, client] of this.clients.entries()) {
const newDef = {
regionId: index++,
regionName,
...itemBase,
_etag: newItemDef._etag
};
updates.push(
this.tryUpdateItem(
client
.database(this.databaseName)
.container(this.manualContainerName)
.item(itemBase.id, undefined),
newDef
)
);
}
const updatedItems = await Promise.all(updates);
const numberOfConflicts = updatedItems.reduce(
(p: number, c: ItemDefinition) => (c !== null ? ++p : p),
-1
);
if (numberOfConflicts > 0) {
console.log(
`2) Caused ${numberOfConflicts} update conflicts, verifying conflict resolution`
);
for (const updatedItem of updatedItems) {
if (updatedItem) {
await this.validateAllManualConflict(updatedItem);
}
}
return;
} else {
console.log(`Found ${numberOfConflicts} - retrying to create more conflicts`);
}
} while (retryCount--);
console.error("Could not enduce an update conflict for manual conflict resolution");
}
private async RunDeleteConflictOnManual(): Promise<void> {
do {
const itemBase = { id: guid() };
const [initialRegionName, initialClient] = this.clients.entries().next().value;
const container = initialClient
.database(this.databaseName)
.container(this.manualContainerName);
const item = { regionId: 0, regionEndpoint: initialRegionName, ...itemBase }; // TODO: ReadEndpoint?
const { resource: newItemDef } = await container.items.create(item);
await this.sleep(1000); // 1 second for the write to sync
console.log(
`1) Performing conflicting delete across ${this.clients.size} regions on ${this.manualContainerName}`
);
const deletes: Array<Promise<ItemDefinition>> = [];
let index = 0;
for (const [regionName, client] of this.clients.entries()) {
const newDef = {
regionId: index++,
regionName,
...itemBase,
_etag: newItemDef._etag,
_rid: newItemDef._rid
};
deletes.push(
this.tryDeleteItem(
client
.database(this.databaseName)
.container(this.manualContainerName)
.item(itemBase.id, undefined),
newDef
)
);
}
const deletedItems = await Promise.all(deletes);
const numberOfConflicts = deletedItems.reduce(
(p: number, c: ItemDefinition) => (c !== null ? ++p : p),
-1
);
if (numberOfConflicts > 0) {
console.log(
`2) Caused ${numberOfConflicts} delete conflicts, verifying conflict resolution`
);
await this.validateLWW(deletedItems, true); // LWW deletes and manual deletes are handled the same
break;
} else {
console.warn("Retrying update/delete to induce conflicts");
}
} while (true); // eslint-disable-line no-constant-condition
}
private async validateAllManualConflict(item: ItemDefinition): Promise<void> {
let conflictExists = false;
for (const [conflictRegion, client] of this.clients.entries()) {
conflictExists = await this.validateManualConflict(conflictRegion, client, item);
}
if (conflictExists) {
await this.DeleteConflict(item);
}
}
private async validateManualConflict(
clientRegion: string,
client: CosmosClient,
item: ItemDefinition
): Promise<boolean> {
for (;;) {
const container = client.database(this.databaseName).container(this.manualContainerName);
const { resources: conflicts } = await container.conflicts.readAll().fetchAll();
for (const conflict of conflicts) {
if (conflict.operationType !== OperationType.Delete) {
const content = JSON.parse(conflict.content as any);
if (item.id !== content.id) {
continue;
}
if (item._rid === content._rid && item._etag === content._etag) {
console.log(`Document from region ${item.regionId} lost conflict @ ${clientRegion}`);
return true;
} else {
try {
client.database(this.databaseName).container(this.manualContainerName);
console.log(
`Document from region ${item.regionId} won the conflict @ ${clientRegion}`
);
return false;
} catch (err) {
if (err.code && err.code === StatusCodes.NotFound) {
console.log(`Item from region ${item.regionId} not found @ ${clientRegion}`);
}
}
}
} else {
if (conflict.resourceId === item._rid) {
console.log(`Delete conflict found @ ${clientRegion}`);
return false;
}
}
}
console.warn(`Document ${item.id} is not found in conflict feed @ ${clientRegion}, retrying`);
await this.sleep(500);
}
}
private async RunInsertConflictOnLWW(): Promise<void> {
do {
console.log(
`1) Performing conflicting insert across ${this.clients.size} regions on ${this.lwwContainerName}`
);
const inserts: Array<Promise<ItemDefinition>> = [];
const itemBase = { id: guid() };
let index = 0;
for (const [clientRegion, client] of this.clients.entries()) {
const container = client.database(this.databaseName).container(this.lwwContainerName);
const newDef = { regionId: index++, regionEndpoint: clientRegion, ...itemBase }; // TODO: ReadEndpoint?
inserts.push(this.tryInsertItem(container.items, newDef));
}
const items = (await Promise.all(inserts)).filter((v) => v !== null);
if (items.length > 1) {
console.log(`2) Caused ${items.length} insert conflicts, verifying conflict resolution`);
await this.validateLWW(items);
break;
} else {
console.warn("Retrying insert to induce conflicts");
}
} while (true); // eslint-disable-line no-constant-condition
}
private async RunUpdateConflictOnLWW(): Promise<void> {
let retry = 5;
do {
const itemBase = { id: guid() };
const [initialRegionName, initialClient] = this.clients.entries().next().value;
const container = initialClient.database(this.databaseName).container(this.lwwContainerName);
const item = { regionId: 0, regionEndpoint: initialRegionName, ...itemBase }; // TODO: ReadEndpoint?
const { resource: newItemDef } = await container.items.create(item);
await this.sleep(1000); // 1 second for the write to sync
console.log(
`1) Performing conflicting update across ${this.clients.size} regions on ${this.lwwContainerName}`
);
const updates: Array<Promise<ItemDefinition>> = [];
let index = 0;
for (const [regionName, client] of this.clients.entries()) {
const newDef = { regionId: index++, regionName, ...itemBase, _etag: newItemDef._etag };
updates.push(
this.tryUpdateItem(
client
.database(this.databaseName)
.container(this.lwwContainerName)
.item(itemBase.id, undefined),
newDef
)
);
}
const items = (await Promise.all(updates)).filter((v) => v !== null);
if (items.length > 1) {
console.log(`2) Caused ${items.length} update conflicts, verifying conflict resolution`);
await this.validateLWW(items);
return;
} else {
console.warn("Retrying update to induce conflicts");
}
} while (retry--);
console.error("Could not induce update conflict on LWW");
}
private async RunDeleteConflictOnLWW(): Promise<void> {
do {
const itemBase = { id: guid() };
const [initialRegionName, initialClient] = this.clients.entries().next().value;
const container = initialClient.database(this.databaseName).container(this.lwwContainerName);
const item = { regionId: 0, regionEndpoint: initialRegionName, ...itemBase }; // TODO: ReadEndpoint?
const { resource: newItemDef } = await container.items.create(item);
await this.sleep(1000); // 1 second for the write to sync
console.log(
`1) Performing conflicting delete across ${this.clients.size} regions on ${this.lwwContainerName}`
);
const deletes: Array<Promise<ItemDefinition>> = [];
let index = 0;
for (const [regionName, client] of this.clients.entries()) {
const newDef = { regionId: index++, regionName, ...itemBase, _etag: newItemDef._etag };
if (index % 2 === 1) {
deletes.push(
this.tryDeleteItem(
client
.database(this.databaseName)
.container(this.lwwContainerName)
.item(itemBase.id, undefined),
newDef
)
);
} else {
deletes.push(
this.tryUpdateItem(
client
.database(this.databaseName)
.container(this.lwwContainerName)
.item(itemBase.id, undefined),
newDef
)
);
}
}
const items = (await Promise.all(deletes)).filter((v) => v !== null);
if (items.length > 2) {
console.log(`2) Caused ${items.length} delete conflicts, verifying conflict resolution`);
await this.validateLWW(items, true);
break;
} else {
console.warn("Retrying update/delete to induce conflicts");
}
} while (true); // eslint-disable-line no-constant-condition
}
private async validateLWW(
items: ItemDefinition[],
hasDeleteConflict: boolean = false
): Promise<void> {
for (const [regionName, client] of this.clients.entries()) {
await this.validateLWWPerClient(regionName, client, items, hasDeleteConflict);
}
}
private async validateLWWPerClient(
regionName: string,
client: CosmosClient,
items: ItemDefinition[],
hasDeleteConflict: boolean
): Promise<void> {
const container = client.database(this.databaseName).container(this.lwwContainerName);
const { resources: conflicts } = await container.conflicts.readAll().fetchAll();
if (conflicts.length !== 0) {
console.error(`Found ${conflicts.length} conflicts in the lww container`);
return;
}
if (hasDeleteConflict) {
do {
try {
const response = await container.item(items[0].id, undefined).read();
if (response.statusCode === StatusCodes.NotFound) {
console.log(`Delete conflict won @ ${regionName}`);
return;
}
} catch (err) {
if (err.code === StatusCodes.NotFound) {
console.log(`Delete conflict won @ ${regionName}`);
return;
}
}
console.error(`Delete conflict for item ${items[0].id} didn't win @ ${regionName}`);
await this.sleep(500);
} while (true); // eslint-disable-line no-constant-condition
}
const winner = items.reduce((p, c) => (p.regionId <= c.regionId ? c : p), items[0]);
console.log(`Document from region ${winner.regionId} should be the winner`);
for (;;) {
try {
const { resource: currentItem } = await container.item(winner.id, undefined).read();
if (currentItem.regionId === winner.regionId) {
console.log(`Winner document from region ${currentItem.regionId} found at ${regionName}`);
break;
}
} catch (err) {
/* No op */
}
console.error(
`Winning document version from region ${winner.regionId} is not found @ ${regionName}, retrying...`
);
await this.sleep(500);
}
}
public async RunInsertConflictOnUdp(): Promise<void> {
do {
console.log(
`1) Performing conflicting insert across ${this.clients.size} regions on ${this.udpContainerName}`
);
const inserts: Array<Promise<ItemDefinition>> = [];
const itemBase = { id: guid() };
let index = 0;
for (const [clientRegion, client] of this.clients.entries()) {
const container = client.database(this.databaseName).container(this.udpContainerName);
const newDef = { regionId: index++, regionEndpoint: clientRegion, ...itemBase }; // TODO: ReadEndpoint?
inserts.push(this.tryInsertItem(container.items, newDef));
}
const items = (await Promise.all(inserts)).filter((v) => v !== null);
if (items.length > 1) {
console.log(`2) Caused ${items.length} insert conflicts, verifying conflict resolution`);
await this.validateUDP(items);
break;
} else {
console.warn("Retrying insert to induce conflicts");
}
} while (true); // eslint-disable-line no-constant-condition
}
public async RunUpdateConflictOnUdp(): Promise<void> {
do {
const itemBase = { id: guid() };
const [initialRegionName, initialClient] = this.clients.entries().next().value;
const container = initialClient.database(this.databaseName).container(this.udpContainerName);
const item = { regionId: 0, regionEndpoint: initialRegionName, ...itemBase }; // TODO: ReadEndpoint?
const { resource: newItemDef } = await container.items.create(item);
await this.sleep(1000); // 1 second for the write to sync
console.log(
`1) Performing conflicting update across ${this.clients.size} regions on ${this.udpContainerName}`
);
const updates: Array<Promise<ItemDefinition>> = [];
let index = 0;
for (const [regionName, client] of this.clients.entries()) {
const newDef = { regionId: index++, regionName, ...itemBase, _etag: newItemDef._etag };
updates.push(
this.tryUpdateItem(
client
.database(this.databaseName)
.container(this.udpContainerName)
.item(itemBase.id, undefined),
newDef
)
);
}
const items = (await Promise.all(updates)).filter((v) => v !== null);
if (items.length > 1) {
console.log(`2) Caused ${items.length} update conflicts, verifying conflict resolution`);
await this.validateUDP(items);
break;
} else {
console.warn("Retrying update to induce conflicts");
}
} while (true); // eslint-disable-line no-constant-condition
}
public async RunDeleteConflictsOnUdp(): Promise<void> {
do {
const itemBase = { id: guid() };
const [initialRegionName, initialClient] = this.clients.entries().next().value;
const container = initialClient.database(this.databaseName).container(this.udpContainerName);
const item = { regionId: 0, regionEndpoint: initialRegionName, ...itemBase }; // TODO: ReadEndpoint?
const { resource: newItemDef } = await container.items.create(item);
await this.sleep(1000); // 1 second for the write to sync
console.log(
`1) Performing conflicting delete across ${this.clients.size} regions on ${this.udpContainerName}`
);
const deletes: Array<Promise<ItemDefinition>> = [];
let index = 0;
for (const [regionName, client] of this.clients.entries()) {
const newDef = { regionId: index++, regionName, ...itemBase, _etag: newItemDef._etag };
if (index % 2 === 1) {
deletes.push(
this.tryDeleteItem(
client
.database(this.databaseName)
.container(this.udpContainerName)
.item(itemBase.id, undefined),
newDef
)
);
} else {
deletes.push(
this.tryUpdateItem(
client
.database(this.databaseName)
.container(this.udpContainerName)
.item(itemBase.id, undefined),
newDef
)
);
}
}
const items = (await Promise.all(deletes)).filter((v) => v !== null);
if (items.length > 2) {
console.log(`2) Caused ${items.length} delete conflicts, verifying conflict resolution`);
await this.validateUDP(items, true);
break;
} else {
console.warn("Retrying update/delete to induce conflicts");
}
} while (true); // eslint-disable-line no-constant-condition
}
private async validateUDP(
items: ItemDefinition[],
hasDeleteConflict: boolean = false
): Promise<void> {
for (const [regionName, client] of this.clients.entries()) {
await this.validateUDPPerClient(regionName, client, items, hasDeleteConflict);
}
}
private async validateUDPPerClient(
regionName: string,
client: CosmosClient,
items: ItemDefinition,
hasDeleteConflict: boolean
): Promise<void> {
const container = client.database(this.databaseName).container(this.udpContainerName);
const { resources: conflicts } = await container.conflicts.readAll().fetchAll();
if (conflicts.length !== 0) {
console.error(`Found ${conflicts.length} conflicts in the udp container`);
return;
}
if (hasDeleteConflict) {
do {
try {
const response = await container.item(items[0].id, undefined).read();
if (response.statusCode === StatusCodes.NotFound) {
console.log(`Delete conflict won @ ${regionName}`);
return;
}
} catch (err) {
if (err.code === StatusCodes.NotFound) {
console.log(`Delete conflict won @ ${regionName}`);
return;
}
}
console.error(`Delete conflict for item ${items[0].id} didn't win @ ${regionName}`);
await this.sleep(500);
} while (true); // eslint-disable-line no-constant-condition
}
const winner = items.reduce(
(p: ItemDefinition, c: ItemDefinition) => (p.regionId <= c.regionId ? c : p),
items[0]
);
console.log(`Document from region ${winner.regionId} should be the winner`);
for (;;) {
try {
const { resource: currentItem } = await container.item(winner.id, undefined).read();
if (currentItem.regionId === winner.regionId) {
console.log(`Winner document from region ${currentItem.regionId} found at ${regionName}`);
break;
}
} catch (err) {
/* No op */
}
console.error(
`Winning document version from region ${winner.regionId} is not found @ ${regionName}, retrying...`
);
await this.sleep(500);
}
}
private async tryInsertItem(items: Items, newDef: ItemDefinition): Promise<ItemDefinition> {
try {
return (await items.create(newDef)).resource;
} catch (err) {
// Handle conflict error silently
if (err.code === StatusCodes.Conflict) {
return null;
}
throw err;
}
}
private async tryUpdateItem(
item: Item,
newDef: ItemDefinition
): Promise<ItemDefinition & Resource> {
const time = Date.now();
try {
return (
await item.replace(newDef, {
accessCondition: {
type: "IfMatch",
condition: newDef._etag
}
})
).resource;
} catch (err) {
if (err.code === StatusCodes.PreconditionFailed || err.code === StatusCodes.NotFound) {
console.log(
`${await item.container.database.client.getWriteEndpoint()} hit ${err.code} at ${time}`
);
return null; // Lost synchronously or not document yet. No conflict is induced.
} else {
console.log("tryUpdateItem hit unexpected error");
throw new Error(JSON.stringify(err));
}
}
}
private async tryDeleteItem(item: Item, newDef: ItemDefinition): Promise<ItemDefinition> {
try {
await item.delete({
accessCondition: {
type: "IfMatch",
condition: newDef._etag
}
});
return newDef;
} catch (err) {
if (err.code === StatusCodes.PreconditionFailed || err.code === StatusCodes.NotFound) {
return null; // Lost synchronously or not document yet. No conflict is induced.
} else {
throw new Error(err);
}
}
}
private async DeleteConflict(item: ItemDefinition): Promise<void> {
const client = this.clients.values().next().value;
const container = client.database(this.databaseName).container(this.manualContainerName);
const conflicts = await container.conflicts.readAll().fetchAll();
for (const conflict of conflicts.resources) {
if (conflict.operationType !== OperationType.Delete) {
const content = JSON.parse(conflict.content);
if (
content._rid === item._rid &&
content._etag === item._etag &&
content.regionId === item.regionId
) {
console.log(
`Deleting manual conflict ${conflict.resourceId} from region ${item.regionId}`
);
await container.conflict(conflict.id).delete();
}
} else if (conflict.resourceId === item._rid) {
console.log(`Deleting manual conflict ${conflict.resourceId} from region ${item.regionId}`);
await container.conflict(conflict.id).delete();
}
}
}
private sleep(timeinMS: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, timeinMS);
});
}
} | the_stack |
module TDev.AST
{
var crashOnInvalid = false;
var blockChaining = false;
export interface ProfilingDataCollection {
unitduration: number;
compilerversion: string;
count?: number;
astnodes?: { [id: string]: ProfilingAstNodeData; }; // TD Ast node --> performance
show?: boolean;
minimumEps?: number;
maximumEps?: number;
averageEps?: number;
}
export class StmtIdCollector extends NodeVisitor {
constructor(public ids: string[] = []) {
super();
}
visitAstNode(node: AstNode) {
return this.visitChildren(node);
}
visitDecl(decl: Decl) {
return this.visitChildren(decl);
}
visitStmt(stmt: Stmt) {
this.ids.push(stmt.stableId);
super.visitStmt(stmt);
}
static collect(script: App) {
var self = new StmtIdCollector();
self.dispatch(script);
return self.ids;
}
}
export class QuotingCtx
{
private mapping: any = {};
private nameMapping: any = {};
private usedNames:any = {};
public reservedNames:any = {};
public unUnicode(s:string)
{
s = s.replace(/[^a-zA-Z0-9]+/g, "_");
if (s == "" || /^[0-9]/.test(s)) s = "_" + s;
return s;
}
public isUsed(s:string)
{
return this.usedNames.hasOwnProperty(s) || this.reservedNames.hasOwnProperty(s)
}
public snapshotUsed()
{
var r = {}
Object.keys(this.reservedNames).forEach(k => r[k] = 1)
Object.keys(this.usedNames).forEach(k => r[k] = 1)
return r
}
public quote(s:string, id:number)
{
var si = s + ":" + id;
var name = s;
if (this.mapping.hasOwnProperty(si)) {
return this.mapping[si];
}
s = this.unUnicode(s);
if (this.isUsed(s)) {
var n = 1;
while (this.isUsed(s + n.toString())) {
n++;
}
s = s + n.toString();
}
this.usedNames[s] = 1;
this.mapping[si] = s;
this.nameMapping[name] = s;
return s;
}
public getNameMapping() { return this.nameMapping; }
}
export enum JsNodeCategory
{
Bad,
ExprStmt,
Goto,
If,
Label,
TmpDef,
TmpRef,
LabelRef,
Call,
Infix,
Term,
DeleteStmt,
Lambda,
}
export class JsNode
{
private cost:number;
public category() { return JsNodeCategory.Bad; }
public toString() { return "<???>"; }
public isUsedLabel() { return false; }
public injectEndIfJumps() { }
public dump(wr:(s:string) => void)
{
wr(this.toString());
}
public forEachExpr(f:(e:JsExpr) => void) { Util.die(); }
}
export class JsStmt
extends JsNode
{
constructor() {
super()
}
}
export class JsExpr
extends JsNode
{
constructor() {
super()
}
public _alwaysValid = false;
public alwaysValid() { return this._alwaysValid }
public gets(v:JsExpr) : JsStmt
{
return new JsExprStmt(new JsInfix(this, "=", v));
}
public makeValid()
{
this._alwaysValid = true
return this
}
}
export class JsCall
extends JsExpr
{
constructor(public recv:JsExpr, public method:string, public args:JsExpr[]) {
super()
}
public category() { return JsNodeCategory.Call; }
public forEachExpr(f:(e:JsExpr) => void)
{
f(this);
if (this.recv != null) this.recv.forEachExpr(f);
if (this.args)
this.args.forEach((a) => a.forEachExpr(f));
}
public toString()
{
var isAlwaysValid = (e:JsExpr) =>
{
if (crashOnInvalid) return true;
if (e.alwaysValid()) return true;
if (e instanceof JsTerm) {
var t = <JsTerm>e;
if (t.code == "s") return true;
}
return false;
}
var meth = this.method;
var args2 = this.args;
if (meth == "ok") {
args2 = args2.filter((e) => !isAlwaysValid(e));
if (args2.length == 0)
return "true";
meth += args2.length;
args2.unshift(new JsTerm("s"));
}
var a = meth;
if (args2) a += "(" + args2.map((e) => e.toString()).join(", ") + ")";
if (this.recv == null)
return a;
else {
var r = this.recv.toString();
if (meth == "[")
return r + a + "]";
else if (meth == "")
return r + a;
else
return r + "." + a;
}
}
static direct(meth:string, args:JsExpr[]) { return new JsCall(null, meth, args); }
static directInst(recv:JsExpr, meth:string, args:JsExpr[]) { return new JsCall(recv, meth, args); }
static okAnd(args:JsExpr[], andThen:JsExpr) { return new JsInfix(JsCall.direct("ok", args), "&&", andThen); }
static mk(recv:JsExpr, method:string, args:JsExpr[])
{
return JsCall.okAnd(recv == null ? args : [recv].concat(args), new JsCall(recv, method, args));
}
}
export class JsInfix
extends JsExpr
{
constructor(public left:JsExpr, public op:string, public right:JsExpr) {
super()
}
public category() { return JsNodeCategory.Infix; }
public forEachExpr(f:(e:JsExpr) => void)
{
f(this);
if (this.left != null) this.left.forEachExpr(f);
if (this.right != null) this.right.forEachExpr(f);
}
public toString()
{
if (this.left == null)
return "(" + this.op + this.right.toString() + ")";
var ll = this.left.toString();
if (this.right == null)
return "(" + ll + this.op + ")";
else {
var rr = this.right.toString();
if (this.op == "&&" && ll == "true") return rr;
return "(" + ll + " " + this.op + " " + rr + ")";
}
}
}
export class JsTerm
extends JsExpr
{
constructor(public code:string) {
super()
}
public category() { return JsNodeCategory.Term; }
public forEachExpr(f:(e:JsExpr) => void) { f(this); }
public toString() { return this.code; }
}
export class JsLiteral
extends JsTerm
{
constructor(c:string) {
super(c)
}
public alwaysValid() { return true }
}
export class JsTmpRef
extends JsExpr
{
constructor(public tmp:JsTmpDef) {
super()
}
public category() { return JsNodeCategory.TmpRef; }
public forEachExpr(f:(e:JsExpr) => void) { f(this); }
public toString() { return this.tmp.getRef(); }
}
export class JsLabelRef
extends JsExpr
{
constructor(public label:JsLabel) {
super()
}
public category() { return JsNodeCategory.LabelRef; }
public forEachExpr(f:(e:JsExpr) => void) { f(this); }
public toString() { return this.label.id; }
}
export class JsTmpDef
extends JsStmt
{
constructor(public stem:string, public initial:JsExpr) {
super()
}
public category() { return JsNodeCategory.TmpDef; }
public id:number;
public isLocal:boolean = true;
public definitionPoint:number;
public forEachExpr(f:(e:JsExpr) => void) { this.initial.forEachExpr(f); }
private getName() { return "t_" + this.stem + "_" + this.id.toString(); }
public getRef() { return this.isLocal ? this.getName() : "s." + this.getName(); }
public toString() {
if (this.isLocal)
return "var " + this.getName() + " = " + this.initial.toString() + ";";
else
return this.getRef() + " = " + this.initial.toString() + ";";
}
}
export class JsExprStmt
extends JsStmt
{
constructor(public code:JsExpr) {
super()
Util.assert(!!code)
}
public category() { return JsNodeCategory.ExprStmt; }
public toString() { return this.code.toString() + ";"; }
public forEachExpr(f:(e:JsExpr) => void) { this.code.forEachExpr(f); }
}
export class JsDeleteStmt
extends JsStmt
{
constructor(public target:JsExpr) {
super()
}
public category() { return JsNodeCategory.DeleteStmt; }
public toString() { return "delete " + this.target.toString() + ";"; }
public forEachExpr(f:(e:JsExpr) => void) { this.target.forEachExpr(f); }
}
export class JsLambda
extends JsExpr
{
constructor(public argCount:number, public body:JsExpr) {
super()
}
public alwaysValid() { return true }
public category() { return JsNodeCategory.Lambda; }
public toString() {
return (
"function(" + Util.range(0, this.argCount).map((i) => "la" + i).join(", ") + ") { " +
"return " + this.body.toString() + " }")
}
public forEachExpr(f:(e:JsExpr) => void) { this.body.forEachExpr(f); }
}
export class JsGoto
extends JsStmt
{
public jumpsToOptimizedLoop = false;
constructor(public target:JsExpr, public canChain = blockChaining) {
super()
}
public toString() {
if (!this.canChain)
return "return " + this.target.toString() + ";";
if (!this.jumpsToOptimizedLoop)
return "if (callstackcurdepth++ < 50) return " + this.target.toString() + "(s); else { callstackcurdepth = 0; return "
+ this.target.toString() + ";}";
return "if (callstackcurdepth++ >= 500) { callstackcurdepth = 0; return "
+ this.target.toString() + ";}";
}
public category() { return JsNodeCategory.Goto; }
public forEachExpr(f:(e:JsExpr) => void) { this.target.forEachExpr(f); }
static simple(t:JsLabel, canChain = blockChaining) { return new JsGoto(new JsLabelRef(t), canChain); }
public isSimple(t:JsLabel)
{
return this.target instanceof JsLabelRef && (<JsLabelRef>this.target).label == t;
}
}
export class JsIf
extends JsStmt
{
public condition:JsExpr;
public thenBody:JsStmt[];
public elseBody:JsStmt[];
public isWhile = false;
constructor(public finalLabel:JsLabel) {
super()
}
public category() { return JsNodeCategory.If; }
public injectEndIfJumps()
{
var inject = (lst:JsNode[]) => {
var wasJmp = false;
var hadLbl = false;
for (var i = 0; i < lst.length; ++i) {
wasJmp = lst[i].category() == JsNodeCategory.Goto;
if (wasJmp || lst[i].isUsedLabel())
hadLbl = true;
}
if (hadLbl && !wasJmp) {
var j = JsGoto.simple(this.finalLabel);
this.finalLabel.refs.push(j);
lst.push(j);
}
}
this.thenBody.forEach((t) => t.injectEndIfJumps());
this.elseBody.forEach((t) => t.injectEndIfJumps());
if (this.finalLabel != null) {
inject(this.thenBody);
inject(this.elseBody);
}
}
public forEachExpr(f:(e:JsExpr) => void) {
this.condition.forEachExpr(f);
this.thenBody.concat(this.elseBody).forEach((t) => t.forEachExpr(f));
}
public dump(wr:(s:string) => void):void
{
wr("if (" + this.condition + ") {");
var wri = (s:string) => { wr(" " + s); }
this.thenBody.forEach((n:JsStmt) => { n.dump(wri); });
if (this.elseBody.length > 0) {
wr("} else {");
this.elseBody.forEach((n:JsStmt) => { n.dump(wri); });
}
wr("}");
}
}
export class JsLabel
extends JsStmt
{
public refs:JsNode[] = [];
constructor(public id:string) {
super()
}
public category() { return JsNodeCategory.Label; }
public isUsedLabel() { return this.refs.length > 0; }
public dump(wr:(s:string) => void)
{
wr("LABEL " + this.id + ":");
}
public forEachExpr(f:(e:JsExpr) => void) { }
}
export interface CompilerOptions
{
isTopLevel?: boolean;
coverage?: boolean;
showCoverage?: boolean;
profiling?: boolean;
showProfiling?: boolean;
debugging?: boolean;
packaging?: boolean;
artResolver?: (url: string) => string;
dynamic?: boolean;
rest?: boolean;
cloud?: boolean;
javascript?: boolean;
authorId?: string;
scriptId?: string; // if present, the ids of libraries will be also baked into the script
scriptGuid?: string;
baseScriptId?: string;
logoUrl?: string;
hasCloudData?: boolean;
hasLocalData?: boolean;
hasPartialData?: boolean;
hostCloudData?: boolean;
optimizeLoops?: boolean;
crashOnInvalid?: boolean;
inlining?: boolean;
okElimination?: boolean;
blockChaining?: boolean;
commonSubexprElim?: boolean;
constantPropagation?: boolean;
libStaticPrefix?: string;
artUrlSuffix?: string;
azureSite?: string;
problemCallback?: (prob: string) => void;
usedProperties?:StringMap<boolean>;
}
export class Compiler
extends NodeVisitor
{
private localNameCtx:QuotingCtx;
private stepIdx = 0;
private actionName:string;
private currentAction:Action;
private inlineCurrentAction = false;
private currentReachingDefs: ReachingDefsMgr;
private currentDoms: DominatorsMgr;
private currentUsedSet: UsedSetMgr;
private currentAE: AvailableExpressionsMgr;
private currentCP: ConstantPropagationMgr;
private numInlinedFunctions = 0;
private numInlinedCalls = 0;
private numOkEliminations = 0;
private numActions = 0;
private numStatements = 0;
private termsReused = 0;
private constantsPropagated = 0;
private currentApp:App;
private globalError:string;
private globalErrorId:string;
public output = "";
private steps = 0;
private todo = [];
private innerActions = [];
private aux:JsStmt[] = [];
private needsScriptText = false;
private profilingBlocks: { [blockId: string]: string[]; } = {}; // block --> stmtExprHolder*
private profilingScopes: JsTmpDef[] = [];
private stmtIds: string[];
private unit = new JsTerm("<unit>");
private api = TDev.api;
private tmpIdx = 0;
private blockId = 1;
public missingApis = [];
private maxArgsToCheck = 0;
private initGlobals = "";
private initGlobals2 = "";
private resetGlobals = "";
private cloudstateJsonExport = "";
private cloudstateJsonImport = "";
private persistentvars = [];
public imports: AppImports = new AppImports();
public packageResources: PackageResource[] = [];
private mapExprToVar: { [id: number]: JsTmpRef } = {};
public debuggerLocalCtxs: { [action: string]: { [nameid: string]: string; }; } = {};
public static version = "1";
constructor(private options:CompilerOptions)
{
super()
crashOnInvalid = !!options.crashOnInvalid;
blockChaining = !!options.blockChaining;
}
private wr(s:string)
{
this.output += s;
}
private term(s:string):JsTerm { return new JsTerm(s); }
private outRef(d:LocalDef)
{
var outp = this.currentAction.getOutParameters();
for (var i = 0; i < outp.length; ++i)
if (outp[i].local == d) {
if (outp.length <= 1)
return "result";
else
return "results[" + i + "]";
}
return null;
}
private localVarName(d:LocalDef)
{
var l = this.outRef(d);
if (l) return l;
return (this.inlineCurrentAction? "l_" :"$") + this.localNameCtx.quote(d.getName(), d.nodeId);
}
private localVarRef(d:LocalDef, direct = false) {
var t = this.inlineCurrentAction ? this.localVarName(d) : "s." + this.localVarName(d);
if (!direct && d.isByRef()) t += ".ref";
return this.term(t);
}
private globalVarId(d:Decl) { return "$" + d.getStableName(); }
private comment(s:string)
{ return "/* " + s.replace(/\//g, "") + " */" }
private globalVarRef(d:Decl)
{
return this.term(this.comment(d.getName()) + " s.d." + this.globalVarId(d));
}
private newTmpVarOK(stem:string, initial:JsExpr, astref: Expr = null)
{
var r = this.newTmpVar(stem, initial, astref)
r._alwaysValid = true
return r
}
private newTmpVar(stem:string, initial:JsExpr, astref: Expr = null)
{
// When the compiler is asking to write an expression to a
// temp var, we try to intercept and look for optimized versions
// of this expression. If there is, we change the expression here
// and return the optimized version instead of the original.
if (this.options.constantPropagation && this.currentCP && astref != null) {
var val = this.currentCP.precomputeLiteralExpression(astref);
if (val != null) {
++this.constantsPropagated;
initial = new JsLiteral(val);
}
}
if (this.options.commonSubexprElim && this.currentAE && astref != null) {
var ref: JsTmpRef = null;
var exprs = this.currentAE.checkForIdenticalExpressions(astref);
for (var i = 0; i < exprs.length; ++i) {
var cur = exprs[i];
ref = this.mapExprToVar[cur.nodeId];
if (ref != null)
break;
}
if (ref != null) {
++this.termsReused;
return ref;
}
}
var t = new JsTmpDef(stem, initial);
this.aux.push(t);
var r = new JsTmpRef(t);
// Record this expression in a map to be used later if it is
// repeated in the future
if (this.options.commonSubexprElim && astref != null) {
this.mapExprToVar[astref.nodeId] = r;
}
return r;
}
private newTmpVarOrUnit(rk:Kind, stem:string, initial:JsExpr, astref: Expr = null) : JsExpr
{
if (rk == api.core.Nothing) {
this.aux.push(new JsExprStmt(initial));
return this.unit;
} else {
return this.newTmpVar(stem, initial, astref);
}
}
private allocateLabel()
{
return new JsLabel(this.actionName + "$" + this.stepIdx++);
}
public visitCodeBlock(b:CodeBlock)
{
var blockId = "";
if (this.needsProfiling()) {
blockId = b.stableId.replace(/\./g, "_");
if (!this.profilingBlocks[blockId]) // associate stmt's ExprHolder with enclosing block [CCC]
this.profilingBlocks[blockId] = [];
}
var res = b.stmts.collect((s: Stmt): JsStmt[] => s.isUnreachable ? [] : this.dispatch(s));
if (this.needsProfiling()) {
var blockId = b.stableId.replace(/\./g, "_");
var hits = new JsTerm("profilingExecutions" + blockId);
res.unshift(new JsExprStmt(new JsInfix(hits, "-=", new JsLiteral("1")))); // record block hit in global cntr
var hitsNext = new JsTerm("profilingExecutionsNext" + blockId);
var hitsNextCount = new JsTerm("profilingExecutionsNextCount" + blockId);
var resetHits = this.allocateIf();
resetHits.condition = new JsInfix(hits, "==", new JsLiteral("0"));
resetHits.thenBody = [
hits.gets(hitsNext),
new JsExprStmt(new JsInfix(hitsNextCount, "+=", hitsNext)),
hitsNext.gets(JsCall.direct("s.rt.nextHitCount", [hitsNext])),
];
resetHits.elseBody = [];
res.push(resetHits);
}
if (b.flags & (BlockFlags.IsPageInit|BlockFlags.IsPageRender)) {
var p = this.currentAction.modelParameter;
if (p) {
var rk = <RecordEntryKind>p.local.getKind();
if (rk.record) {
var stored = this.term("s.rt.getCurrentPage().model");
res.unshift(this.localVarRef(p.local).gets(stored))
if (b.flags & BlockFlags.IsPageInit)
res.unshift(stored.gets(this.term("s.d.$" + rk.record.getStableName() + ".create(s)")));
} else {
Util.check(false);
}
}
}
if (b.flags & BlockFlags.IsPageRender) {
res.unshift(new JsExprStmt(JsCall.direct("s.rt.enter_render", [])))
res.push(new JsExprStmt(JsCall.direct("s.rt.leave_render", [])))
}
return res;
}
private flushAux()
{
var r = this.aux;
this.aux = [];
return r;
}
private doExpr(e:Expr):JsExpr
{
return this.dispatch(e);
}
private runmap_variables: string[][] = [];
private topExpr(eHolder: ExprHolder, s: Stmt): JsExpr {
var ai = eHolder.assignmentInfo()
if (ai && ai.definedVars)
ai.definedVars.forEach(l => {
if (l.isByRef())
this.aux.push(this.localVarRef(l, true).gets(this.term("{ref:undefined}")))
})
var nodeId = eHolder.stableId.replace(/\./g, "_");
var blockId = s.parent.stableId.replace(/\./g, "_"); // associate stmt's ExprHolder with enclosing block [CCC]
if (this.needsProfiling()) {
var profilingLastCallTimeStamp = new JsTmpRef(this.profilingScopes.peek());
var sampleThisStmt = this.allocateIf();
sampleThisStmt.condition = new JsInfix(
new JsInfix(new JsTerm("profilingExecutions" + blockId), "==", new JsLiteral("0")),
"&&",
new JsInfix(profilingLastCallTimeStamp, "==", new JsLiteral("0")));
sampleThisStmt.thenBody = [profilingLastCallTimeStamp.gets(JsCall.direct("perfNow", []))];
sampleThisStmt.elseBody = [];
this.aux.push(sampleThisStmt);
}
var res = this.dispatch(eHolder.parsed);
if (!this.needsProfiling())
return res;
this.profilingBlocks[blockId].push(nodeId);
var duration = new JsTerm("tmp");
var durationCallSite = new JsTerm("profilingDuration" + nodeId); // global execution duration of this call site
var durationSamplesCallSite = new JsTerm("profilingDurationSamples" + nodeId);
var profilingLastCallTimeStamp = new JsTmpRef(this.profilingScopes.peek()); // frame-specific last-call timestamp // TODO: make block-specific
var hits = new JsTerm("profilingExecutions" + blockId);
var captureDuration = this.allocateIf();
captureDuration.condition = new JsInfix(hits, "==", new JsLiteral("0"));
captureDuration.thenBody = [
duration.gets(new JsInfix(JsCall.direct("perfNow", []), "-", profilingLastCallTimeStamp)),
new JsExprStmt(new JsInfix(durationCallSite, "+=", duration)),
new JsExprStmt(new JsInfix(durationSamplesCallSite, "+=", new JsLiteral("1"))),
new JsExprStmt(new JsInfix(profilingLastCallTimeStamp, "+=", duration))];
captureDuration.elseBody = [
profilingLastCallTimeStamp.gets(new JsLiteral("0"))
];
this.aux.push(captureDuration);
if (this.needsProfilingDebug())
this.aux.push(new JsExprStmt(JsCall.direct("alert", [JsCall.direct("JSON.stringify", [new JsTerm("cs._getProfilingResults()")])])));
return res;
}
private markLocation(s:Stmt)
{
this.numStatements++;
var currentId = new JsLiteral(this.stringLiteral(s.stableId));
if (this.debugBuild()) this.buildBreakpoint(s.stableId);
this.aux.push(this.term("s.pc").gets(currentId));
if (this.instrumentForCoverage() && (s.isFirstNonComment() || s.isLastNonComment())) {
// each id gets a variable named c$N_id
var lit = "c$" + s.stableId.replace(/\./g, "_");
this.runmap_variables.push([s.stableId, lit]);
this.aux.push(this.term(lit).gets(this.term('1')));
}
}
private instrumentForCoverage() {
return !!this.options.coverage;
}
// When visiting statements that consumes expressions, we need to set
// up "current*" variables to point to the information generated by our
// analysis passes.
private updateAnalysisInfo(e: ExprHolder) {
if (this.options.okElimination) {
this.currentReachingDefs = e.reachingDefs;
this.currentDoms = e.dominators;
this.currentUsedSet = e.usedSet;
if (this.currentReachingDefs && TDev.dbg) {
this.aux.push(this.term(this.comment(this.currentReachingDefs.toString())));
}
if (this.currentUsedSet && TDev.dbg) {
this.aux.push(this.term(this.comment(this.currentUsedSet.toString())));
}
}
if (this.options.commonSubexprElim) {
this.currentAE = e.aeSet;
if (this.currentAE && TDev.dbg) {
this.aux.push(this.term(this.comment(this.currentAE.toString())));
}
}
if (this.options.constantPropagation) {
this.currentCP = e.cpSet;
if (this.currentCP && TDev.dbg) {
this.aux.push(this.term(this.comment(this.currentCP.toString())));
}
}
}
// Cleans "current*" variables, preparing for the next expression.
private resetAnalysisInfo() {
if (this.options.okElimination) {
this.currentReachingDefs = null;
this.currentDoms = null;
this.currentUsedSet = null;
}
if (this.options.commonSubexprElim) {
this.currentAE = null;
}
if (this.options.constantPropagation) {
this.currentCP = null;
}
}
public visitExprStmt(e:ExprStmt)
{
this.updateAnalysisInfo(e.expr);
this.markLocation(e);
var ex = this.topExpr(e.expr, e);
var r = this.flushAux();
if (ex != this.unit)
r.push(new JsExprStmt(ex));
this.resetAnalysisInfo();
return r;
}
public visitInlineActions(n:InlineActions)
{
n.actions.forEach((a) => {
if (a instanceof InlineAction)
this.compileInlineAction(<InlineAction>a)
})
return this.visitExprStmt(n);
}
private allocateIf() { return new JsIf(this.allocateLabel()); }
public visitElseIf(i:If) { return [] }
public visitIf(i:If)
{
if (i.isTopCommentedOut()) return []
var elseMarker:JsTmpRef = i.branches.length > 1 ? this.newTmpVarOK("elseIf", new JsLiteral("true")) : null;
var res = this.flushAux();
i.branches.forEach((b, idx) => {
if (idx == i.branches.length - 1) return;
this.updateAnalysisInfo(b.condition)
var par = b.body.parent // this may be ElseIf stmt
this.markLocation(par);
var cond = this.topExpr(b.condition, par);
this.resetAnalysisInfo();
var body = this.flushAux();
body.push(new JsExprStmt(JsCall.direct("ok", [cond])))
var ifNode = this.allocateIf();
body.push(ifNode);
ifNode.condition = cond;
ifNode.thenBody = this.dispatch(b.body);
if (idx == i.branches.length - 2) {
ifNode.elseBody = this.dispatch(i.branches[idx+1].body)
} else {
if (elseMarker) ifNode.thenBody.unshift(elseMarker.gets(new JsLiteral("false")))
ifNode.elseBody = []
}
if (idx > 0) {
var outer = this.allocateIf()
outer.condition = elseMarker
outer.thenBody = body
outer.elseBody = []
res.push(outer)
} else {
res.pushRange(body)
}
})
return res;
}
public visitWhile(w:While)
{
this.updateAnalysisInfo(w.calcNode());
this.markLocation(w);
var begLabel = this.allocateLabel();
w._compilerContinueLabel = begLabel;
w._compilerBreakLabel = this.allocateLabel()
this.aux.push(begLabel);
var cond = this.topExpr(w.condition, w);
this.resetAnalysisInfo();
var res = this.flushAux();
var ifNode = this.allocateIf();
ifNode.condition = cond;
ifNode.thenBody = this.dispatch(w.body);
ifNode.thenBody.push(JsGoto.simple(begLabel));
ifNode.elseBody = [];
res.push(ifNode);
res.push(w._compilerBreakLabel)
return res;
}
public visitBreak(b:Call)
{
if (b.topAffectedStmt)
this.aux.push(JsGoto.simple(b.topAffectedStmt._compilerBreakLabel))
return this.unit
}
public visitContinue(b:Call)
{
if (b.topAffectedStmt)
this.aux.push(JsGoto.simple(b.topAffectedStmt._compilerContinueLabel))
return this.unit
}
public visitReturn(r:Call)
{
if (r.topRetLocal) {
var val = this.doExpr(r.args[0]);
this.aux.push(this.localVarRef(r.topRetLocal).gets(val))
}
this.aux.push(JsGoto.simple(r.topAffectedStmt._compilerBreakLabel))
return this.unit
}
public visitShow(s:Call)
{
var ex = this.doExpr(s.topPostCall)
if (ex != this.unit)
this.aux.push(new JsExprStmt(ex));
return this.unit
}
private compileInlineAction(inl:InlineAction)
{
var a = new Action();
a._compilerParentAction = this.currentAction;
a._compilerInlineAction = inl;
a.body = inl.body;
a.isLambda = true;
a.setStableName(this.actionName + "$" + this.stepIdx);
a.stableId = inl.stableId;
a.setName(this.actionName + "::lambda::" + this.stepIdx);
a.isPrivate = true;
this.stepIdx++;
inl.inParameters.forEach((p) => a.header.inParameters.push(new ActionParameter(p)))
inl.outParameters.forEach((p) => a.header.outParameters.push(new ActionParameter(p)))
a.allLocals = inl.allLocals;
inl.closure.forEach((p) => a.header.inParameters.push(new ActionParameter(p, false, true)));
this.innerActions.push(a);
this.markLocation(inl);
var refs:JsExpr[] = inl.closure.map((l) => this.newTmpVar("lmbv", this.localVarRef(l, true)));
// -1 for this
// +2 for previous, returnAddr
var n = inl.inParameters.length - 1 + 2;
while (n >= 1)
refs.unshift(this.term("la" + n--));
// push previous
var mkProxy = this.newTmpVarOK("lmbProxy", this.term("s.libs.mkLambdaProxy"));
refs.unshift(JsCall.directInst(mkProxy, "", [this.term("la0")]))
var frame = new JsLambda(inl.inParameters.length + 2, JsCall.direct("a_" + a.getStableName(), refs))
this.aux.push(this.localVarRef(inl.name).gets(frame));
}
public visitBox(b:Box)
{
this.markLocation(b);
var res = this.flushAux();
res.push(new JsExprStmt(JsCall.direct("lib.Box.push_box", [this.term("s")])))
res.pushRange(this.dispatch(b.body))
res.push(new JsExprStmt(JsCall.direct("lib.Box.pop_box", [this.term("s")])))
return res;
}
private mkCall(prop:IProperty, args:Expr[])
{
var call = new Call();
call.propRef = PropertyRef.mkProp(prop);
call.args = args;
return call;
}
public visitForeach(f:Foreach)
{
var collExpr = f.collection.parsed;
var collTmp:JsTmpRef;
var isArray = false;
this.updateAnalysisInfo(f.calcNode());
this.markLocation(f);
if (collExpr.getKind().hasEnumerator()) {
isArray = true;
collTmp = this.newTmpVarOK("collArr", JsCall.mk(this.topExpr(f.collection, f), "get_enumerator", []));
} else {
collTmp = this.newTmpVar("coll", this.topExpr(f.collection, f));
}
this.resetAnalysisInfo();
f._compilerBreakLabel = this.allocateLabel()
var idxTmp = this.newTmpVarOK("idx", this.term("0"));
var begLabel = this.allocateLabel();
f._compilerContinueLabel = begLabel;
this.aux.push(begLabel);
var lenExpr:JsExpr;
if (isArray)
lenExpr = new JsInfix(collTmp, ".length", null);
else {
var countProp = collExpr.getKind().getProperty("count");
lenExpr = this.callProperty(countProp, [collTmp]);
}
var res = this.flushAux();
var ifNode = this.allocateIf();
ifNode.condition = JsCall.okAnd([collTmp], new JsInfix(idxTmp, "<", lenExpr));
var atExpr:JsExpr;
if (isArray) {
atExpr = new JsCall(collTmp, "[", [idxTmp]);
} else {
var atProp = collExpr.getKind().getProperty("at");
atExpr = this.callProperty(atProp, [collTmp, idxTmp]);
}
this.aux.push(this.localVarRef(f.boundLocal).gets(atExpr));
this.aux.push(new JsExprStmt(new JsInfix(idxTmp, "++", null)));
if (f.conditions.stmts.length == 0) {
ifNode.thenBody = this.flushAux();
ifNode.thenBody.pushRange(this.dispatch(f.body))
} else {
var where = (idx:number) => (<Where>f.conditions.stmts[idx]).condition.parsed;
var cond:Expr = where(0);
for (var i = 1; i < f.conditions.stmts.length; ++i) {
cond = this.mkCall(api.core.AndProp, [cond, where(i)]);
}
var innerIf = this.allocateIf();
innerIf.condition = this.doExpr(cond);
this.aux.push(innerIf);
ifNode.thenBody = this.flushAux();
innerIf.thenBody = this.dispatch(f.body);
innerIf.elseBody = [];
}
ifNode.thenBody.push(JsGoto.simple(begLabel));
ifNode.elseBody = [];
res.push(ifNode);
res.push(f._compilerBreakLabel);
return res;
}
public visitFor(f:For)
{
this.updateAnalysisInfo(f.calcNode());
this.markLocation(f);
var bndTmp = this.newTmpVar("bnd", this.topExpr(f.upperBound, f));
this.resetAnalysisInfo();
var idx = this.localVarRef(f.boundLocal);
this.aux.push(idx.gets(this.term("0")));
var begLabel = this.allocateLabel();
f._compilerContinueLabel = this.allocateLabel();
f._compilerBreakLabel = this.allocateLabel()
var res = this.flushAux();
res.push(begLabel);
var ifNode = this.allocateIf();
ifNode.condition = new JsInfix(idx, "<", bndTmp);
ifNode.thenBody = this.dispatch(f.body);
ifNode.thenBody.push(f._compilerContinueLabel);
ifNode.thenBody.push(new JsExprStmt(new JsInfix(idx, "++", null)));
ifNode.thenBody.push(JsGoto.simple(begLabel));
ifNode.elseBody = [];
res.push(ifNode);
res.push(f._compilerBreakLabel);
return res;
}
public visitComment(c:Comment) {
if (this.options.usedProperties.hasOwnProperty("appconsumerenderedcomments")) {
var par = (<CodeBlock>c.parent).stmts
var idx = par.indexOf(c)
if (par[idx - 1] && par[idx - 1].docText() != null)
return []; // not first
var end = idx
while (par[end] && par[end].docText() != null)
end++
var d = Step.renderDocs(par.slice(idx, end))
return [new JsExprStmt(JsCall.direct("s.rt.saveComment", [new JsLiteral(this.stringLiteral(d))]))]
}
return [];
}
static restrictedIntOps:StringMap<string> = {
"add": "Bits.add_int32",
"subtract": "Bits.subtract_int32",
"multiply": "Bits.multiply_int32",
"divide": "Bits.divide_int32",
}
private callString(prop:IProperty, args:JsExpr[], ctxArg:JsExpr, astref: Call) : JsExpr
{
var pk = prop.parentKind;
var propName = prop.runtimeName();
var parName = prop.parentKind.runtimeName();
var rk = prop.getResult().getKind();
var specApply = prop.getSpecialApply();
var robust = prop.getFlags() & PropertyFlags.Robust;
var res:JsExpr;
var doMagic = () => {
if (specApply) {
Util.assertCode(args.length == 2);
if (astref && astref.isSynthetic)
astref = null
var inner:JsExpr = new JsInfix(args[0], specApply, args[1])
if (Cloud.isRestricted() && parName == "Number_" && astref && !astref.isShim) {
var over = Compiler.restrictedIntOps[propName]
if (over) inner = JsCall.direct("lib." + over, [args[0], args[1]])
}
res = this.newTmpVar("infix", JsCall.okAnd([args[0], args[1]], inner), astref);
} else if (propName == "is_invalid") {
//if (!(pk instanceof RecordEntryKind))
res = new JsInfix(args[0], "==", this.term("undefined"));
res._alwaysValid = true;
//else
// res = JsCall.directInst(this.term("lib.RecordEntry"), "check_invalid", [ args[0] ]);
} else if (!prop.isImplemented()) {
var meth = "";
var apiName = parName + "->" + propName;
if ((prop.getCapability() & api.core.currentPlatform) == 0) {
meth = "TDev.Util.notSupported";
} else {
meth = "TDev.Util.notImplementedYet";
apiName += " (yet)";
}
if (this.missingApis.indexOf(apiName) < 0)
this.missingApis.push(apiName);
res = this.newTmpVarOrUnit(rk, "notImpl", JsCall.direct(meth, [this.term("s"), this.term("'" + apiName + "'")]));
} else if (pk == api.core.App && (propName == "javascript" || propName == "javascript_async")) {
this.emitJavascriptEscape(astref, ctxArg)
res = this.unit
} else if (pk.isBuiltin || !pk.isData) {
if (!pk.isData) args.shift();
args.push(ctxArg);
if (astref && astref.compiledTypeArgs)
args.pushRange(astref.compiledTypeArgs)
if (Cloud.isRestricted() && parName == "Bits" && /^(or|and)_uint32$/.test(propName))
propName = propName.replace("uint32", "int32")
res = this.newTmpVarOrUnit(rk, "call", JsCall.mk(null, "lib." + parName + "." + propName, args));
} else {
var th = args.shift();
args.push(ctxArg);
if (astref && astref.compiledTypeArgs)
args.pushRange(astref.compiledTypeArgs)
res = this.newTmpVarOrUnit(rk, "call", JsCall.mk(th, propName, args));
}
}
doMagic();
if (this.options.okElimination && robust) {
this.numOkEliminations++;
res._alwaysValid = true;
}
return res;
}
private markAllocated(prop:IProperty, res:JsExpr)
{
if (!!(prop.getResult().getFlags() & ParameterFlags.WritesMutable)) {
// this property allocates a new object - mark it if in render mode
this.aux.push(new JsExprStmt(JsCall.direct("s.rt.markAllocated", [res])))
}
}
private returnedFrom(numOut:number, idx:number)
{
var name = "result";
if (numOut > 1)
name = "results[" + idx + "]";
return this.term("s.rt.returnedFrom." + name);
}
private isDataRef(e:Expr) { return (e instanceof Call) && !!(<Call>e).referencedData() }
private assignTo(e:Expr, src:JsExpr)
{
if (e.referencedRecordField() || e.referencedData())
this.emitRefOperation(e, "set", null, [src])
else {
var setter = e.getLiftedSetter()
if (setter) {
var c = mkFakeCall(PropertyRef.mkProp(setter))
this.emitNormalCall(c, [this.doExpr((<Call>e).args[0]), src])
} else
this.aux.push(this.doExpr(e).gets(src))
}
}
private doAssignment(c:Call) : JsExpr
{
var targets = c.args[0].flatten(api.core.TupleProp);
var src = this.doExpr(c.args[1]);
if (targets.length == 1) {
if (c.args[1].getKind() != api.core.Nothing)
this.assignTo(targets[0], src);
} else {
var act = (<Call> c.args[1]).anyCalledAction()
Util.assertCode(act != null);
for (var i = 0; i < act.getOutParameters().length; ++i) {
this.assignTo(targets[i], this.returnedFrom(act.getOutParameters().length, i));
}
}
if (targets.some((e) => this.isDataRef(e)))
this.aux.push(new JsExprStmt(JsCall.direct("s.rt.logDataWrite", [])))
return this.unit;
}
private doLazy(c:Call, isAnd:boolean) : JsExpr
{
var arg0 = this.doExpr(c.args[0])
var tmp = this.newTmpVar("lazy", arg0);
var cond = this.allocateIf();
if (this.options.okElimination && arg0.alwaysValid()) {
this.numOkEliminations++;
cond.condition = isAnd ? <JsExpr> tmp : new JsInfix(null, "!", tmp);
} else
cond.condition = JsCall.okAnd([tmp], isAnd ? <JsExpr> tmp : new JsInfix(null, "!", tmp));
this.aux.push(cond);
var tmpAux = this.flushAux();
var arg1 = this.doExpr(c.args[1]);
this.aux.push(tmp.gets(arg1));
if (this.options.okElimination)
tmp._alwaysValid = arg0.alwaysValid() && arg1.alwaysValid();
cond.thenBody = this.flushAux();
cond.elseBody = [];
this.aux = tmpAux;
return tmp;
}
private forceNonRender()
{
this.aux.push(new JsExprStmt(JsCall.direct("s.rt.forceNonRender", [])));
this.aux.push(new JsExprStmt(JsCall.direct("s.rt.forcePageRefresh", [])))
}
private emitRefOperation(fieldRef:Expr, op:string, args:Expr[], compiledArgs:JsExpr[] = null)
{
if (op == "ref" || op == "with notify") return null;
if (fieldRef instanceof Call) {
var rcf = fieldRef.referencedRecordField()
if (rcf)
return this.emitRecordOperation(<Call>fieldRef, op, rcf, args, compiledArgs)
var rd = fieldRef.referencedData()
if (rd)
return this.emitDataOperation(<Call>fieldRef, op, rd, args, compiledArgs)
}
return null;
}
private emitRefCall(c: Call)
{
return this.emitRefOperation(c.args[0], c.prop().getName().slice(1), c.args.slice(1))
}
private emitDataOperation(fieldRef: Call, op: string, rd: GlobalDef, opargs: Expr[], args: JsExpr[]):any {
if (op == "get") {
if (rd.isTransient)
return this.globalVarRef(rd);
else {
if (!args)
args = <JsExpr[]> opargs.map((e) => this.doExpr(e));
args.unshift(new JsLiteral(this.stringLiteral("$"+rd.getStableName())));
args.push(this.term("s"));
return this.newTmpVar("val", JsCall.direct("s.d.$$" + (rd.cloudEnabled ? "cloud" : "local") + "persistentvars.perform_get", args));
}
}
if (op == "set") {
if (!args)
args = <JsExpr[]> opargs.map((e) => this.doExpr(e));
if (rd.isTransient)
this.aux.push(this.globalVarRef(rd).gets(args[0]));
else {
args.unshift(new JsLiteral(this.stringLiteral("$"+rd.getStableName())));
args.push(this.term("s"));
this.aux.push(new JsExprStmt(JsCall.direct("s.d.$$" + (rd.cloudEnabled ? "cloud" : "local") + "persistentvars.perform_set", args)));
}
}
return null;
}
private emitRecordOperation(fieldRef:Call, op:string, rcf:RecordField, opargs:Expr[], args:JsExpr[])
{
var recvRecord = this.doExpr(fieldRef.args[0]);
//var opName = new JsLiteral(this.stringLiteral(c.prop().getName()));
var fieldName = new JsLiteral(this.stringLiteral(rcf.referenceName()));
if (!args)
args = <JsExpr[]> opargs.map((e) => this.doExpr(e));
args.unshift(fieldName);
args.push(this.term("s"));
//args.unshift(opName);
var prevAux = this.flushAux();
var result: JsExpr;
if (op === "get" || op === "confirmed") {
if (rcf.def().recordType === RecordType.Object) {
// fast path: we inline field read of simple objects at compile time
result = JsCall.directInst(recvRecord, "[", [fieldName]);
}
else {
result = JsCall.directInst(recvRecord, "perform_" + op, args);
}
} else {
var name = op
name = "perform_" + ((name === "test and set") ? "test_and_set" : name);
this.aux.push(new JsExprStmt(JsCall.directInst(recvRecord, name, args)));
result = this.unit;
}
if (result != this.unit) {
result = this.newTmpVar("recOp", result);
}
var ifNode = this.allocateIf();
ifNode.condition = recvRecord;
ifNode.thenBody = this.flushAux();
ifNode.elseBody = [];
prevAux.push(ifNode);
this.aux = prevAux;
return result;
}
private needsProfiling(): boolean {
return this.options.profiling;
}
private needsProfilingDebug(): boolean {
return /profilingDebug/.test(document.URL);
}
private debugBuild() : boolean {
return !!this.options.debugging;
}
private buildBreakpoint(s: string) {
var check =
new JsExprStmt(
new JsInfix(
this.term("bp$" + s.replace(/\./g, "_")),
"&&",
JsCall.direct(
"s.rt.hitBreakpoint",
[new JsLiteral(this.stringLiteral(s))]
)
)
);
var l = this.allocateLabel();
var g = JsGoto.simple(l, false);
this.aux.push(check, g, l);
}
private buildActionCall(numOut:number, isAsync:boolean, args:JsExpr[], mkCall:()=>JsExpr):JsExpr
{
var l = this.allocateLabel();
// skip code singleton
args.splice(0, 1, this.term("s"), new JsLabelRef(l));
var call:JsExpr = mkCall();
var rtEnter:JsExpr;
if (isAsync) {
var task = this.newTmpVar("task", JsCall.direct("s.rt.mkActionTask", []))
rtEnter = JsCall.direct("s.rt.enterAsync", [task, call]);
} else {
rtEnter = JsCall.direct("s.rt.enter", [call]);
}
var g = new JsGoto(rtEnter, false);
this.aux.push(g, l);
if (isAsync) return task;
if (numOut == 1)
return this.newTmpVar("actRes", this.returnedFrom(numOut, 0));
else
return this.unit;
}
// build a literal string array
private buildStringArray(strings: string[]): JsExpr {
return this.term("[" + strings.reduce(
(str, current, i) =>
(!current) ? str :
(i == 0) ? this.stringLiteral(current) :
(str + ", " + this.stringLiteral(current)),
"") + "]");
}
private emitJavascriptEscape(c:Call, ctxArg:JsExpr)
{
if (!this.options.javascript)
return
var code = ""
function localName(l:LocalDef) {
var r = Api.runtimeName(l.getName().replace(/[?]/g, ""))
if (r == "s" || r == "lib") return "_" + r
return r
}
function unterm(t:JsExpr)
{
if (t instanceof JsTerm)
return (<JsTerm>t).code
Util.die()
return ""
}
if (c.args[1].getStringLiteral() != "local") {
this.problem(lf("wrong JS calling convention"))
code = "TDev.Util.userError('wrong JS calling convention');"
} else {
var isAsync = c.prop().getName() == "javascript async";
if (isAsync) {
code = "(function(_resumeCtx){\n" +
" var s = _resumeCtx.stackframe;\n" +
" function resume() { _saveResults(); _resumeCtx.resume() }\n" +
" s.localResume = resume;\n" +
""
} else {
code = "(function(s){\n"
}
code += " function _saveResults() {\n"
this.currentAction.getOutParameters().forEach(p => {
code += " " + unterm(this.localVarRef(p.local)) + " = " + localName(p.local) + ";\n"
})
code += " }\n"
var imp = this.currentApp.imports.npmModules
var impKeys = Object.keys(imp);
if (impKeys.length > 0) {
//code += "var __window = window; window = undefined;\ntry {\n"; // window is undefined in node.js
impKeys.forEach(k => {
k = Api.runtimeName(k)
code += " var " + k + " = s.rt.nodeModules." + k + ";\n"
})
//code += "} finally { window = __window }\n";
}
this.currentAction.allLocals.forEach(l => {
code += " var " + localName(l) + " = " + unterm(this.localVarRef(l)) + ";\n"
})
code += " var rt = s.rt;\n"
code += " function _userCode() {\n\n"
var theCode = c.args[2].getStringLiteral()
//if (/resume\s*\(\)/.test(theCode) != isAsync)
// this.problem("javascript async/resume() mismatch, " + theCode)
code += c.args[2].getStringLiteral()
code += "\n\n }\n"
code += " s.rt.runInlineJavascript(_userCode);\n"
if (!isAsync)
code += " _saveResults();\n"
code += "})"
}
try {
//Security risk
//eval(code)
} catch (e) {
this.problem("syntax error in app->javascript, " + e + "\n" + code)
}
this.aux.push(new JsExprStmt(JsCall.direct(code, [ctxArg])))
}
private problem(s:string)
{
Util.log("compiler problem: " + s)
if (this.options.problemCallback)
this.options.problemCallback(s)
}
private doFun(c:Call): JsExpr
{
if (c.funAction) {
this.compileInlineAction(c.funAction)
return this.localVarRef(c.funAction.name)
} else return this.term("null")
}
public visitCall(c:Call) : JsExpr
{
var prop = c.prop();
//if (prop && prop.parentKind === api.core.CloudData)
// this.options.hasCloudData = true;
if (prop == api.core.AssignmentProp) return this.doAssignment(c);
if (prop == api.core.AndProp) return this.doLazy(c, true);
if (prop == api.core.OrProp) return this.doLazy(c, false);
if (prop == api.core.AsyncProp) return this.dispatch(c.args[1]);
if (prop == api.core.FunProp) return this.doFun(c)
if (prop.getCategory() == PropertyCategory.Library)
return this.unit;
if (prop.parentKind.getRoot() == api.core.Ref) {
var tmp = this.emitRefCall(c);
if (tmp) return tmp
}
if (c.autoGet)
return this.emitRefOperation(c, "get", [])
var args = c.args.slice(0)
var typeArgs:JsExpr[] = []
if (prop instanceof MultiplexProperty &&
(<MultiplexProperty>prop).savedArgs)
typeArgs = (<MultiplexProperty>prop).savedArgs.map(p => {
var r = this.term(this.reifyType(p) || "null")
r._alwaysValid = true
return r
})
while (prop instanceof MultiplexProperty) {
var inner = c.args[0]
if (inner instanceof Call) {
c = <Call>inner
prop = c.prop()
} else {
break;
}
}
c.compiledTypeArgs = typeArgs
args[0] = c.args[0]
return this.emitNormalCall(c, args.map((e) => this.doExpr(e)))
}
private reifyType(p:Kind): string
{
if (p.isBuiltin)
return this.stringLiteral(p.getName().toLowerCase())
else if (p.getRecord()) {
if (!p.parentLibrary() || p.parentLibrary().isThis())
return (<JsTerm>this.globalVarRef(p.getRecord())).code
else
return "s.rt.getLibRecordSingleton(" +
this.stringLiteral(p.parentLibrary().getStableName()) + ", " +
this.stringLiteral(p.getName()) + ")"
} else if (p.isData && !p.isUserDefined() && p.getParameterCount() == 0)
return "lib." + p.runtimeName()
else
return null
}
private emitNormalCall(c:Call, args:JsExpr[]) : JsExpr
{
var prop = c.prop();
var dat = c.referencedData();
var act = c.calledAction();
var rcd = <RecordDef>(prop && prop.forwardsTo() instanceof RecordDef && prop.forwardsTo());
var str = (s: string) => this.stringLiteral(s);
if (prop instanceof ExtensionProperty) {
act = (<ExtensionProperty>prop).shortcutTo
args.unshift(null)
}
if (dat) {
if (dat.isTransient)
return JsCall.direct("lib.GlobalVarRef.mk", [this.term("s.d"), new JsLiteral(this.stringLiteral(this.globalVarId(dat)))]).makeValid();
else
return JsCall.direct("lib.PersistedVarRef.mk", [this.term("s.d.$$" + (dat.cloudEnabled ? "cloud" : "local") + "persistentvars"),
new JsLiteral(this.stringLiteral("$" + dat.getStableName()))]).makeValid();
} else if (rcd) {
return this.globalVarRef(rcd);
} else if (act && act.isPage()) {
var par:JsExpr;
if (act instanceof LibraryRefAction)
par = new JsLiteral(str(act.parentLibrary().getStableName()));
else
par = this.term("s.d.libName");
var pageName:JsExpr[] = [par, new JsLiteral(str(act.getName()))];
args.splice(0, 1);
this.forceNonRender();
this.aux.push(new JsExprStmt(JsCall.direct("s.rt.postAutoPage", pageName.concat(args))));
return this.unit;
} else if (act && act.canBeInlined && this.options.inlining) {
var numOut = act.getOutParameters().length;
var call:JsExpr = undefined;
this.numInlinedCalls++;
args.shift();
args.unshift(new JsTerm("s"));
call = JsCall.direct("a_" + act.getStableName(), args);
if (numOut == 1)
return this.newTmpVar("fast_call", call);
else {
this.aux.push(new JsExprStmt(call));
return this.unit;
}
} else if (act) {
if (act.isExtensionAction()) {
act = act.extensionForward();
args.unshift(null);
}
return this.buildActionCall(!act.isAtomic ? 1 : act.getOutParameters().length, c.runAsAsync, args, () => {
if (act instanceof LibraryRefAction) {
var refAct: LibraryRefAction = (<LibraryRefAction>act)
// The library is ran as a web service
if (act.parentLibrary().isCloud()) {
args = [new JsTerm(refAct.template.isQuery ? "true" : "false"), // don't use toString() *Tim
new JsLiteral(this.stringLiteral(this.options.azureSite)),
new JsLiteral(this.stringLiteral(act.parentLibrary().getName())),
new JsLiteral(this.stringLiteral(act.parentLibrary().getStableName())),
new JsLiteral(this.stringLiteral(act.getName())),
this.buildStringArray(act.getInParameters().map((ap) => { return ap.getName(); })),
this.buildStringArray(act.getOutParameters().map((ap) => { return ap.getName(); })),
this.buildStringArray(act.getOutParameters().map((ap) => {
var kind = ap.getKind();
if (kind instanceof LibraryRefAbstractKind) {
var ak = <LibraryRefAbstractKind>kind;
var lb = ak.parentLibrary().getStableName();
return lb + "→" + ak.getName();
} else if (kind instanceof ParametricKind && kind._name === "Collection") {
var pm = (<ParametricKind>kind).parameters[0];
if (pm instanceof LibraryRefAbstractKind) {
var ak = <LibraryRefAbstractKind> pm;
var lb = ak.parentLibrary().getStableName();
var name = lb + "→" + ak.getName();
} else {
var name = pm.getName();
}
return "Collection of " + name;
}
return kind.toString();
}))].concat(args);
return JsCall.direct(refAct.template.isOffline ? "s.rt.callServiceOffline" : "s.rt.callService", args);
// Normal library action call
} else {
var tmp = this.newTmpVar("libcall", this.term("s.libs[" + str(act.parentLibrary().getStableName()) + "][" + str(act.getName()) + "](s)"));
args[0] = tmp;
return JsCall.directInst(tmp, "invoke", args);
}
} else {
return JsCall.direct("a_" + act.getStableName(), args);
}
})
} else if (prop.getName() == "run" && prop.parentKind.isAction) {
var lmb = args[0];
return this.buildActionCall((<ActionKind>prop.parentKind).getOutParameters().length, c.runAsAsync, args, () => {
return JsCall.okAnd([lmb], JsCall.directInst(lmb, "", args));
})
} else {
var rcf = c.referencedRecordField()
if (rcf) {
var keyname = new JsLiteral(this.stringLiteral(rcf.referenceName()));
if (prop.isKey)
return JsCall.mk(args[0], "[", [keyname]);
else
return JsCall.mk(null, "lib.FieldRef.mk", [args[0], keyname]).makeValid()
}
return this.callProperty(prop, args, c, c.runAsAsync)
}
}
private callProperty(prop: IProperty, args: JsExpr[], astref: Call = null, runAsAsync = false) : JsExpr
{
var writes = (p:PropertyParameter) => !!(p.getFlags() & ParameterFlags.WritesMutable);
var parms = prop.getParameters();
for (var i = 0; i < parms.length; i++)
if (writes(parms[i]))
this.aux.push(new JsExprStmt(JsCall.direct("s.rt.logObjectMutation", [args[i]])));
if (prop.shouldPauseInterperter() && prop.isImplemented()) {
if (runAsAsync) {
var rctx = this.newTmpVarOK("resumeCtx", JsCall.direct("s.rt.getAsyncResumeCtx", []));
this.callString(prop, args, rctx, astref); // this pushes the call
return JsCall.directInst(rctx, "task", null)
}
var l = this.allocateLabel();
var r = new JsLabelRef(l);
var fnName = prop.getFlags() & PropertyFlags.Async ? "s.rt.getAwaitResumeCtx" : "s.rt.getBlockingResumeCtx"
var rctx = this.newTmpVarOK("resumeCtx", JsCall.direct(fnName, [r]));
this.callString(prop, args, rctx, astref); // this pushes the call
this.aux.push(new JsGoto(r, false));
this.aux.push(l);
if (prop.getResult().getKind() == api.core.Nothing)
return this.unit;
else {
var res:JsExpr = this.newTmpVar("pauseRes", this.term("s.pauseValue"));
this.markAllocated(prop, res);
return res;
}
} else if (prop == api.core.StringConcatProp) {
// TODO optimize when both arguments are strings?
return this.newTmpVar("concat", JsCall.direct("lib.String_.concatAny", args));
} else {
var res = this.callString(prop, args, this.term("s"), astref);
this.markAllocated(prop, res);
return res;
}
}
private stringLiteral(s:string) { return Util.jsStringLiteral(s) }
public visitLiteral(l:Literal)
{
switch (typeof l.data) {
case "string":
return new JsLiteral(this.stringLiteral(l.data));
case "number":
return new JsLiteral(l.data.toString());
case "boolean":
return new JsLiteral(l.data.toString());
default: Util.die();
}
}
private handlePlaceholder(pdef:PlaceholderDef)
{
var str = (s:string) => new JsLiteral(this.stringLiteral(s));
var data = pdef.escapeDef
var lk:Kind = data.objectToMake
var parentLib = lk.parentLibrary() ? lk.parentLibrary().getStableName() : "this"
var call = JsCall.direct("s.rt.mkLibObject", [str(parentLib), str(lk.getName())])
var res = this.newTmpVarOK("obj", call)
if (data.optionalConstructor) {
data.optionalConstructor.optionalParameters().forEach(p => {
var fieldName = new JsLiteral(this.stringLiteral(p.recordField.referenceName()));
var arg = p instanceof OptionalParameter ?
this.doExpr((<OptionalParameter>p).expr.parsed) :
this.localVarRef((<InlineAction>p).name);
this.aux.push(new JsExprStmt(JsCall.directInst(res, "perform_set", [fieldName, arg, this.term("s")])));
})
}
return res
}
public visitThingRef(t:ThingRef):JsExpr
{
switch (t.def.nodeType()) {
case "singletonDef":
return this.term("null");
//return this.unit;
case "localDef":
var term = this.localVarRef(<LocalDef>t.def);
// If okElimination is turned on, uses all the information
// we have to try to turn off the "ok check" for this local.
if (this.options.okElimination && this.currentReachingDefs) {
if (!this.currentReachingDefs.mayBeInvalid(<LocalDef>t.def)
|| (this.currentUsedSet && this.currentUsedSet.alreadyUsed(<LocalDef>t.def))) {
this.numOkEliminations++;
term._alwaysValid = true;
}
}
return term;
case "placeholderDef":
return this.handlePlaceholder(<PlaceholderDef>t.def)
default: Util.die();
}
}
public visitAstNode(n:AstNode)
{
Util.oops(lf("compilation not implemented for {0}", n.nodeType()));
}
private emitOk(n:number)
{
var a = Util.range(0, n).map((k) => "a" + k);
this.wr("function ok" + n + "(s, " + a.join(", ") + ") {\n");
// note that in JS "null == undefined" is true, see http://es5.github.com/#x11.9.3
this.wr(" return (" + a.map((x) => x + " == undefined").join(" || ") + ") ?\n");
this.wr(" TDev.Util.userError(\"using invalid value\") : true;\n");
this.wr("}\n\n");
}
public visitLibraryRef(l:LibraryRef) {}
public visitRecordDef(r:RecordDef)
{
if (!this.shouldCompile(r)) return
var mkEntry = "Ent_" + r.getStableName();
var mkTable = "Tbl_" + r.getStableName();
if (r.cloudEnabled)
this.options.hasCloudData = true;
if (r.locallypersisted())
this.options.hasLocalData = true;
if (r.cloudPartiallyEnabled)
this.options.hasPartialData = true;
var rt = (r.persistent ? "Cloud" : "") + RecordDef.recordTypeToString(r.recordType);
var wrProto = (target:string, fnName:string, expr:string) =>
{
if (fnName != "") fnName = "." + fnName;
this.wr(target + ".prototype" + fnName + " = " + expr + ";\n");
}
var wrProtoQ = (target:string, fnName:string, expr:string) =>
{
this.wr(target + ".prototype[" + this.stringLiteral(fnName) + "] = " + expr + ";\n");
}
var wrFields = (target:string, id:string, flds:RecordField[]) =>
{
wrProto(target, id, "[" + flds.map((f) => this.stringLiteral(f.referenceName())).join(", ") + "]");
}
// define entry objects
this.wr("\n//" + mkEntry + "\n");
this.wr("function " + mkEntry + "(p) {\n");
this.wr(" this.parent = p;\n");
this.wr("}\n");
wrProto(mkEntry, "", "new lib." + rt + "Entry()");
wrFields(mkEntry, "keys", r.keys.fields());
wrFields(mkEntry, "values", r.values.fields());
wrFields(mkEntry, "fields", r.getFields());
//wrFields(mkEntry, "factories", r.getFields().map((f:RecordField) => f.);
var wrFieldName = (f: RecordField) =>
{
wrProtoQ(mkEntry, f.referenceName() + "_realname", this.stringLiteral(f.getName()));
}
var wrFieldDefaultValue = (f: RecordField) =>
{
var defl = ""
switch (f.dataKind.getName()) {
case "Boolean": defl = 'false'; break;
case "Number": defl = '0'; break;
case "String": defl = '""'; break;
case "DateTime": defl = 'lib.DateTime.defaultValue'; break;
default: break;
}
if (defl)
wrProtoQ(mkEntry, f.referenceName(), defl)
}
r.getFields().forEach(wrFieldName);
if (!r.persistent)
r.getValueFields().forEach(wrFieldDefaultValue);
// define table objects
this.wr("//" + mkTable + "\n");
this.wr("function " + mkTable + "(l) {\n");
this.wr(" this.libName = l;\n");
this.wr(" this.initParent();\n");
this.wr("}\n");
wrProto(mkTable, "", "new lib." + rt + "Singleton()");
wrProto(mkTable, "entryCtor", mkEntry);
this.wr("cs.objectSingletons[" + this.stringLiteral(r.getCoreName()) + "] " +
"= function(d) { return d." + this.globalVarId(r) + " };\n")
wrProto(mkTable, "selfCtor", mkTable);
wrProto(mkTable, "stableName", this.stringLiteral(r.getStableName()));
wrProto(mkTable, "entryKindName", this.stringLiteral(r.entryKind.getName()));
if (r.persistent && !r.hasErrors()) {
wrProto(mkTable, "cloudtype", this.stringLiteral(r.getCloudType()));
wrProto(mkTable, "key_cloudtypes", "[" + r.keys.fields().map((f) => this.stringLiteral(f.getCloudType())).join(", ") + "]");
wrProto(mkTable, "value_cloudtypes", "[" + r.values.fields().map((f) => this.stringLiteral(f.getCloudType())).join(", ") + "]");
if (r.locallypersisted() && !this.options.cloud) {
wrProto(mkTable, "localsession", "true");
} else {
this.cloudstateJsonExport = this.cloudstateJsonExport + " json[" + this.stringLiteral(r.getName())
+ "] = d." + this.globalVarId(r) + ".exportJson(ctx);\n";
this.cloudstateJsonImport = this.cloudstateJsonImport
+ " d." + this.globalVarId(r) + ".importJsonTableOrIndex(ctx,json[" + this.stringLiteral(r.getName()) + "]);\n";
wrProto(mkTable, "replication",
r.cloudPartiallyEnabled ? this.stringLiteral("partial")
: r.cloudEnabled ? this.stringLiteral("full")
: this.stringLiteral("local"));
}
}
// define record jsonimport
this.wr("\n// jsonimport\n");
if ((r.recordType === RecordType.Table || r.recordType === RecordType.Index) && r.keys.fields().length > 0) {
this.wr(mkTable + ".prototype.importJsonKeys = function (ctx, json) {\n");
this.wr(" var s = ctx.s;\n");
this.wr(" var a = [];\n");
r.keys.fields().forEach((f) => {
if (f.dataKind.hasContext(KindContext.Json)) {
var typename = f.dataKind.getName().replace(/ /g, "");
switch (typename) {
case "Boolean":
case "Number":
case "String":
case "DateTime":
case "Color":
case "User":
case "Location":
case "Vector3":
this.wr(" a.push(ctx.import" + typename + "(json, " + this.stringLiteral(f.getName()) + "));\n");
break;
default: // RecordEntry or RecordCollection
if (f.dataKind instanceof RecordEntryKind) {
this.wr(" a.push(ctx.importRecord(json, undefined,"
+ this.stringLiteral(f.getName()) + ", "
+ "s.d." + this.globalVarId((<RecordEntryKind> f.dataKind).record) + "));\n");
} break;
}
}
});
this.wr(" return a;\n");
this.wr("}\n");
}
this.wr(mkEntry + ".prototype.importJsonFields = function (ctx, json) {\n");
this.wr(" var s = ctx.s;\n");
r.values.fields().forEach((f) => {
if (f.dataKind.hasContext(KindContext.Json)) {
var typename = f.dataKind.getName().replace(/ /g, "");
var fieldname = this.stringLiteral(f.referenceName());
switch (typename) {
case "Boolean":
case "Number":
case "String":
case "DateTime":
case "Color":
case "JsonObject":
case "User":
case "Location":
case "Vector3":
this.wr(" this.perform_set(" +
fieldname + ", "
+ "ctx.import" + typename + "(json, " + this.stringLiteral(f.getName()) + "), s);\n");
break;
case "JsonBuilder":
case "Link":
case "OAuthResponse":
case "StringMap":
case "NumberMap":
this.wr(" this.perform_set("
+ fieldname + ", "
+ "ctx.import" + typename + "(json, this.perform_get(" + fieldname + ",s),"
+ this.stringLiteral(f.getName())
+ "), s);\n");
break;
default: // RecordEntry or RecordCollection
if (f.dataKind instanceof RecordEntryKind) {
this.wr(" this.perform_set(" +
fieldname + ", "
+ "ctx.importRecord(json, this.perform_get(" + fieldname + ",s),"
+ this.stringLiteral(f.getName()) + ", "
+ "s.d." + this.globalVarId((<RecordEntryKind> f.dataKind).record)
+ "), s);\n");
} else if (f.dataKind._name === "Collection") {
var containedkind = (<ParametricKind> f.dataKind).parameters[0];
var rt = containedkind.hasContext(KindContext.Json) ? this.reifyType(containedkind) : null
if (rt) {
this.wr(" this.perform_set(" +
fieldname + ", "
+ "ctx.importCollection(json, this.perform_get(" + fieldname + ",s),"
+ this.stringLiteral(f.getName()) + ", "
+ rt + "), s);\n");
}
}
break;
}
}
});
this.wr("}\n");
// define initialization
var id = this.globalVarId(r);
this.initGlobals += " if(!d.hasOwnProperty(" + this.stringLiteral(id) + ") || !d[" + this.stringLiteral(id) + "]) d." + id + " = new " + mkTable + "(d.libName);\n";
this.initGlobals2 += "d." + id + ".name = \"" + r.getCoreName() + "\";";
if (r.persistent) {
this.initGlobals2 += "d." + id + ".linked_cloudtables = ["
+ r.keys.fields().filter((f) => f.dataKind instanceof RecordEntryKind)
.map((ff) => ("d." + this.globalVarId((<RecordEntryKind>ff.dataKind).record)))
.join(", ")
+ "];\n";
}
this.resetGlobals += " d." + id + " = undefined;\n";
this.wr("cs.registerGlobal(" + this.stringLiteral(id) + ");\n");
}
private throwSyntaxError(a:Action)
{
var str = (s:string) => this.stringLiteral(s)
var userErr = (msg:string, id:string) => {
this.wr(" TDev.Util.syntaxError(" + this.stringLiteral(msg) + ", " + this.stringLiteral(id) + ");\n");
}
if (a.hasErrors()) {
userErr(lf("function '{0}' (in '{1}') has errors and will not run", a.getName(), this.currentApp.getName()),
a.getStableName());
return true;
} else if (this.globalError) {
userErr(this.globalError, this.globalErrorId);
return true;
}
return false;
}
// Emit the JavaScript code for an inlined action, as determined by the
// inline analysis. The analysis only selects actions that lacks
// loop statements and calls to non-inlined actions, which makes it
// simpler. Therefore, this code implements a simpler case of
// visitAction and uses native JS locals to map TouchDevelop locals
// instead of using a dedicated stack data structure.
private visitInlinedAction(a:Action) {
this.inlineCurrentAction = true;
this.localNameCtx = new QuotingCtx();
this.actionName = "a_" + a.getStableName();
this.currentAction = a;
this.wr(this.comment("ACTION: " + a.getName() + " (inlined)") + "\n");
this.wr("function " + this.actionName + "(s ");
a.getInParameters().forEach((l) => { this.wr(", " + this.localVarName(l.local)); });
this.wr(") {\n");
a._compilerBreakLabel = this.allocateLabel();
if (this.throwSyntaxError(a)) {
this.wr("\n }\n");
return;
}
Util.assert(a.getOutParameters().length <= 1);
if (a.getOutParameters().length > 0) {
var param = a.getOutParameters()[0];
if (param.local == undefined) {
this.wr(" var " + param.getName() + " = undefined;\n");
}
}
a.allLocals.forEach((l) => {
if (!a.getInParameters().some((p:ActionParameter) => p.local == l)) {
this.wr(" var " + this.localVarName(l) + " = undefined;\n");
}
});
var jsNodes: JsStmt[] = this.dispatch(a.body);
jsNodes.push(a._compilerBreakLabel)
var prevMax = this.maxArgsToCheck + 1;
this.insertFinalLabels(jsNodes);
jsNodes.forEach((n) => n.forEachExpr((e:JsExpr) => {
if (e instanceof JsLabelRef) {
(<JsLabelRef> e).label.refs.push(e);
}
if (e instanceof JsCall) {
var c = <JsCall>e; // look at each JS method call, including those inserted during compilation
if (c.method == "ok" && this.maxArgsToCheck < c.args.length)
this.maxArgsToCheck = c.args.length;
}
Util.assertCode(e !== this.unit);
}));
this.blockId = 1; this.tmpIdx = 0;
this.markBlocks(jsNodes);
jsNodes.forEach((n) => n.injectEndIfJumps());
this.dumpInlinedContents(jsNodes);
if (a.getOutParameters().length > 0) {
var param = a.getOutParameters()[0];
if (param.local == undefined)
this.wr(" return " + param.getName() + ";\n");
else
this.wr(" return " + this.localVarRef(param.local) + ";\n");
}
this.wr("}\n");
while (prevMax <= this.maxArgsToCheck)
this.emitOk(prevMax++);
this.inlineCurrentAction = false;
}
private shouldCompile(d:Decl)
{
return d.visitorState === true;
}
public visitAction(a:Action)
{
if (!this.shouldCompile(a)) return
this.numActions++;
if (this.options.inlining && a.canBeInlined) {
this.numInlinedFunctions++;
return this.visitInlinedAction(a);
}
this.inlineCurrentAction = false;
this.mapExprToVar = {};
this.localNameCtx = new QuotingCtx();
this.stepIdx = 0;
var str = (s:string) => this.stringLiteral(s)
this.actionName = "a_" + a.getStableName();
this.currentAction = a;
this.wr(this.comment("ACTION: " + a.getName()) + "\n");
this.wr("function " + this.actionName + "(previous, returnAddr");
a.getInParameters().forEach((l) => { this.wr(", " + this.localVarName(l.local)); });
var lab0 = this.allocateLabel();
this.wr(") {\n")
a._compilerBreakLabel = this.allocateLabel();
if (a._compilerInlineAction)
a._compilerInlineAction._compilerBreakLabel = a._compilerBreakLabel;
if (!this.throwSyntaxError(a)) {
this.wr(
" var s = TDev.Runtime.mkStackFrame(previous, returnAddr);\n" +
" s.entryAddr = " + lab0.id + ";\n" +
" s.name = " + str((a._compilerParentAction || a).getName()) + ";\n");
if (a.getOutParameters().length > 1)
this.wr(" s.results = [];\n");
a.allLocals.forEach((l) => {
this.wr(" " + this.localVarRef(l, true).toString() + " = ");
var ap = a.getInParameters().filter((p:ActionParameter) => p.local == l)[0]
if (ap) {
if (l.isByRef() && !ap.isClosure)
this.wr("{ref:" + this.localVarName(l) + "}");
else
this.wr(this.localVarName(l));
} else {
this.wr("undefined");
}
this.wr(";\n");
});
this.wr(" return s;\n");
}
this.wr("}\n");
this.wr("cs.register" + (a.isLambda ? "Lambda" : a.isPage() ? "Page" : "Action") + "(" + str(a.getName()) + ", " + str(a.getStableName()) + ", " + this.actionName + (!a.isAtomic ? ", true" : ", false") + ");\n");
if (a.isEvent()) {
var inf = a.eventInfo;
if (!inf.disabled) {
var varId = !inf.onVariable ? "null" : str(this.globalVarId(inf.onVariable));
this.wr("cs.registerEventHandler(" + str(inf.type.category) + ", " + varId + ", " + this.actionName + ");\n");
}
}
this.wr("\n");
if (a.hasErrors() || !!this.globalError) return;
function setFlag(b:CodeBlock, f:BlockFlags) { if (b) b.flags |= f; }
if (a.isPage()) {
setFlag(a.getPageBlock(true), BlockFlags.IsPageInit);
setFlag(a.getPageBlock(false), BlockFlags.IsPageRender);
}
if (this.needsProfiling()) // create local var for profiler [CCC]
this.profilingScopes.push(new JsTmpDef("profilingLastCallTimeStamp", new JsLiteral("0")));
var jsNodes: JsStmt[] = this.dispatch(a.body);
jsNodes.push(a._compilerBreakLabel);
if (this.needsProfiling())
jsNodes.unshift(this.profilingScopes.pop());
// always add 'pickers' in cloud mode
var cloudPicker = this.options.cloud && !a.isPrivate
if (cloudPicker || (a.isRunnable() && a.hasInParameters()))
jsNodes.unshift(this.synthesizePicker(a.getInParameters()));
if (cloudPicker || (a.isRunnable() && a.hasOutParameters()))
jsNodes.push(this.synthesizeOutput(a.getOutParameters()));
jsNodes.unshift(lab0);
lab0.refs.push(lab0);
var prevMax = this.maxArgsToCheck + 1;
this.insertFinalLabels(jsNodes);
jsNodes.forEach((n) => n.forEachExpr((e:JsExpr) => {
if (e instanceof JsLabelRef) {
(<JsLabelRef> e).label.refs.push(e);
}
if (e instanceof JsCall) {
var c = <JsCall>e; // look at each JS method call, including those inserted during compilation
if (c.method == "ok" && this.maxArgsToCheck < c.args.length)
this.maxArgsToCheck = c.args.length;
}
Util.assertCode(e !== this.unit);
}));
while (prevMax <= this.maxArgsToCheck)
this.emitOk(prevMax++);
this.blockId = 1; this.tmpIdx = 0;
this.markBlocks(jsNodes);
jsNodes.forEach((n) => n.injectEndIfJumps());
/*
var dmp = "";
var xwr = (s:string) => { dmp += s + "\n"; }
if (/gameloop/.test(a.getName())) {
jsNodes.forEach((n) => n.dump(xwr));
debugger;
}
*/
jsNodes.push(new JsGoto(this.term("s.rt.leave()"), false));
this.dumpFunction(jsNodes, 0);
while (this.todo.length > 0) {
var f = this.todo.shift();
f();
}
this.debuggerLocalCtxs[a.stableId] = this.localNameCtx.getNameMapping();
// this will actually only ever turn once
while (this.innerActions.length > 0) {
var aa = this.innerActions.shift();
aa.visitorState = true
this.dispatch(aa);
}
}
public recompileAction(a:Action, cs:CompiledScript)
{
this.initGlobals = "";
this.initGlobals2 = "";
this.maxArgsToCheck = 0;
this.output = "";
this.wr("'use strict';\n");
this.wr("(function (cs) {\n");
this.wr("var libs = cs.libs;\n");
this.wr("var lib = TDev.RT;\n");
this.dispatch(a);
this.wr("})");
cs.reinit(this.output);
}
private insertFinalLabels(nodes:JsStmt[]):void
{
for (var i = 0; i < nodes.length; ++i) {
if (nodes[i] instanceof JsIf) {
var s = <JsIf> nodes[i];
nodes.splice(i + 1, 0, s.finalLabel);
this.insertFinalLabels(s.thenBody);
this.insertFinalLabels(s.elseBody);
}
}
}
private markBlocks(nodes:JsStmt[]):void
{
var mark = (e:JsExpr) =>
{
if (e instanceof JsTmpRef) {
var t = <JsTmpRef>e;
if (this.blockId != t.tmp.definitionPoint)
t.tmp.isLocal = false;
}
}
nodes.forEach((s:JsStmt) => {
if (s instanceof JsIf) {
var i = <JsIf>s;
i.condition.forEachExpr(mark);
this.markBlocks(i.thenBody);
this.markBlocks(i.elseBody);
return;
} else if (s instanceof JsTmpDef) {
var t = <JsTmpDef>s;
t.definitionPoint = this.blockId;
t.id = this.tmpIdx++;
} else if (s instanceof JsLabel) {
var l = <JsLabel>s;
if (l.refs.length > 0)
this.blockId++;
}
s.forEachExpr(mark);
});
}
private dumpFunction(nodes:JsStmt[], idx:number) : void
{
var lab = <JsLabel> nodes[idx];
this.wr("function " + lab.id + "(s) {\n");
if (idx == 0) this.libInits(lab.id)
if (this.options.optimizeLoops) {
var head = <JsIf>nodes[idx + 1]
if (head instanceof JsIf && head.elseBody.length == 0) {
var last = <JsGoto>head.thenBody.peek();
if (last instanceof JsGoto && last.isSimple(lab)) {
// ok, we have a loop
(() => {
var hasLabels = (n:JsStmt[]) => {
for (var i = 0; i < n.length; ++i) {
var ifs = <JsIf>n[i]
if (ifs instanceof JsIf)
if (hasLabels(ifs.thenBody) || hasLabels(ifs.elseBody)) return true;
if (n[i].isUsedLabel()) return true;
}
return false;
}
var innerBody = head.thenBody.slice(0, head.thenBody.length - 1);
if (!hasLabels(innerBody)) {
head.thenBody = innerBody;
head.isWhile = true;
}
})()
}
}
} else if (this.options.blockChaining) {
// Block Chaining will transform an inner loop into a native
// JavaScript loop by emitting a "while" construct. It uses
// a counter to return to the interpreter after a few
// iterations.
var head = <JsIf>nodes[idx + 1];
if (head instanceof JsIf && head.elseBody.length == 0) {
var last = <JsGoto>head.thenBody.peek();
if (last instanceof JsGoto && last.isSimple(lab)) {
// ok, we have a loop
(() => {
var hasLabels = (n: JsStmt[]) => {
for (var i = 0; i < n.length; ++i) {
var ifs = <JsIf>n[i]
if (ifs instanceof JsIf)
if (hasLabels(ifs.thenBody) || hasLabels(ifs.elseBody)) return true;
if (n[i].isUsedLabel()) return true;
}
return false;
}
var innerBody = head.thenBody.slice(0, head.thenBody.length - 1);
if (!hasLabels(innerBody)) {
last.jumpsToOptimizedLoop = true;
head.isWhile = true;
}
})()
}
}
}
this.dumpInner(nodes, idx + 1)
this.wr("}\n");
this.wr("cs.registerStep(" + lab.id + ", '" + lab.id + "');\n\n");
}
private dumpSimple(n:JsStmt)
{
this.wr(" " + n.toString() + "\n");
}
private dumpInner(nodes:JsStmt[], idx:number)
{
while (idx < nodes.length) {
var n = nodes[idx];
if (n.isUsedLabel()) {
this.dumpSimple(JsGoto.simple(<JsLabel>n));
this.todo.push(() => { this.dumpFunction(nodes, idx); });
return;
} else if (n.category() == JsNodeCategory.Goto) {
this.dumpSimple(n);
while (++idx < nodes.length) {
if (nodes[idx].category() == JsNodeCategory.Label) {
this.todo.push(() => { this.dumpFunction(nodes, idx); });
return
}
}
return
} else if (n.category() == JsNodeCategory.If) {
var i = <JsIf> n;
this.wr(" " + (i.isWhile ? "while" : "if") + " (" + i.condition.toString() + ") {\n");
this.dumpInner(i.thenBody, 0);
if (i.elseBody.length > 0) {
this.wr(" } else {\n");
this.dumpInner(i.elseBody, 0);
}
this.wr(" }\n");
} else if (n.category() == JsNodeCategory.Label) {
// unused label
} else {
this.dumpSimple(n);
}
idx++;
}
}
// This is a special version of dumpInner to inlined functions
// (flagged by InlineAnalysis). It emits the contents of an inlined
// function, which does not have a separate stack and is closer to
// native JavaScript. On the other hand, it cannot have loops or
// calls to non-inlined actions.
private dumpInlinedContents(nodes:JsStmt[])
{
var idx = 0;
while (idx < nodes.length) {
var n = nodes[idx];
if (n.isUsedLabel()) {
Util.assert(false && !!"Should not have used labels in inlined function!");
return;
} else if (n.category() == JsNodeCategory.Goto) {
Util.assert(false && !!"Should not have Gotos in inlined function!");
return;
} else if (n.category() == JsNodeCategory.If) {
var i = <JsIf> n;
this.wr(" " + (i.isWhile ? "while" : "if") + " (" + i.condition.toString() + ") {\n");
this.dumpInlinedContents(i.thenBody);
if (i.elseBody.length > 0) {
this.wr(" } else {\n");
this.dumpInlinedContents(i.elseBody);
}
this.wr(" }\n");
} else if (n.category() == JsNodeCategory.Label) {
// unused label
} else {
this.dumpSimple(n);
}
idx++;
}
}
private defaultValue(k:Kind, forPicker = false)
{
switch (k.getName()) {
case "Number": return "0";
case "String": return "\"\"";
case "Boolean": return "false";
case "DateTime": return "lib.DateTime.defaultValue";
case "Tile": return "lib.Tile.mkDefaultValue()";
}
if (!forPicker)
return null;
switch (k.getName()) {
case "Collection": return "lib.Collection.fromArray([], " + (this.reifyType(k.getParameter(0)) || "null") + ")";
}
return null
}
private addResourceAsFile(res: PackageResource) {
if (/^([a-z0-9\-_][a-z0-9\-_\.]*\/)*[a-z0-9\-_][a-z0-9\-_\.]*\.[a-z0-9]+$/i.test(res.sourceName)) {
var resFile = Util.clone(res);
resFile.packageUrl = res.sourceName;
resFile.usageLevel = 1;
this.packageResources.push(resFile)
}
}
public visitGlobalDef(d:GlobalDef)
{
if (!this.shouldCompile(d)) return
if (d.isResource && !!d.url) {
var resourceId = this.globalVarId(d)
var resourceUrl = d.url;
// building up the table of 'resource id' -> url for packaging
if (this.options.packaging) {
var kindName = d.getKind().getName();
var qualId = this.options.libStaticPrefix + resourceId.replace(/\$/, "")
var suff = this.options.artUrlSuffix || ""
var resource:PackageResource = {
kind:'art',
id: qualId,
url: resourceUrl,
packageUrl: null,
sourceName: d.getName(),
usageLevel: d.usageLevel,
type: kindName.toLowerCase()
}
if ((kindName === 'Picture' || kindName === 'Sound') && !/^data:\/\//i.test(resourceUrl)) {
resource.packageUrl = encodeURI('./art/' + qualId + suff);
resourceUrl = resource.packageUrl;
this.packageResources.push(resource)
this.addResourceAsFile(resource);
} else if (kindName === 'String') {
if (!TDev.RT.String_.valueFromArtUrl(resourceUrl)) { // this is an url
resource.packageUrl = encodeURI('./art/' + qualId + suff);
resourceUrl = resource.packageUrl;
this.packageResources.push(resource)
}
// save resource as needed
if (resourceUrl) {
var value = TDev.RT.String_.valueFromArtUrl(resourceUrl);
if (value) {
resource.content = value;
resource.url = undefined;
}
this.addResourceAsFile(resource);
}
}
}
if (d.usageLevel > 0 && resourceUrl)
this.wr("cs.registerArtResource(" +
this.stringLiteral(d.getKind().runtimeName()) + ", " +
this.stringLiteral(resourceId) + ", " +
this.stringLiteral(resourceUrl) + ");\n");
}
if (d.cloudEnabled)
this.options.hasCloudData = true;
else if (!d.isTransient)
this.options.hasLocalData = true;
if (!d.isTransient && !d.hasErrors()) {
this.persistentvars.push({
local: !d.cloudEnabled,
name: d.getStableName(),
cloudtype: Revisions.Parser.MakeProperty(d.getStableName(), "global[]", AST.KindToCodomain(d.getKind()))
});
}
// not writing out the id will cause the art resource to be cleared when saving state
if (!d.isResource && !d.isTransient)
this.wr("cs.registerGlobal(" + this.stringLiteral(this.globalVarId(d)) + ");\n");
var initVal = this.defaultValue(d.getKind());
if (!!initVal) {
this.initGlobals += " if(!d.hasOwnProperty(" + this.stringLiteral(this.globalVarId(d)) + ")) d." + this.globalVarId(d) + " = " + initVal + ";\n";
}
if (!d.getKind().isSerializable || d.isTransient) {
this.resetGlobals += " d." + this.globalVarId(d) + " = " + (initVal || "undefined") + ";\n";
}
}
public initPersistentVars(local: boolean): string {
var collect = this.persistentvars.filter((v) => !!v.local === local);
if (collect.length == 0)
return;
var pv = " d.$$" + (local ? "local" : "cloud") + "persistentvars";
this.wr(pv + " = new lib.PersistentVars(rt);\n");
this.wr(pv + ".localsession = " + local.toString() + ";\n");
this.wr(pv + ".libName = d.libName;\n");
this.wr(pv + ".names = [" + collect.map((v) => this.stringLiteral("$" + v.name)).join(", ") + "]; \n");
this.wr(pv + ".cloudtypes = [" + collect.map((v) => this.stringLiteral(v.cloudtype)).join(", ") + "]; \n");
this.resetGlobals += (pv + " = undefined;\n");
}
static compileCore(a: App, cs: CompiledScript, options:CompilerOptions)
{
var comp = new Compiler(options);
a.setStableNames();
var usage = new UsageComputer()
usage.dispatch(a);
comp.dispatch(a);
cs.init(comp.output, comp.missingApis, comp.packageResources, !options.javascript);
cs.localNamesBindings = comp.debuggerLocalCtxs;
if (options.dynamic) {
a.recompiler = comp;
a.recompiledScript = cs;
}
cs.optStatistics.inlinedCalls += comp.numInlinedCalls;
cs.optStatistics.inlinedFunctions += comp.numInlinedFunctions;
cs.optStatistics.eliminatedOks += comp.numOkEliminations;
cs.optStatistics.numActions += comp.numActions;
cs.optStatistics.numStatements += comp.numStatements;
cs.optStatistics.termsReused += comp.termsReused;
cs.optStatistics.constantsPropagated += comp.constantsPropagated;
cs.imports = comp.imports;
}
static annotateWithIds(a: App) {
var compiled = [];
var k = 0;
a.libraries().forEach((l: LibraryRef) => {
var prev = compiled.filter((e) => e.app == l.resolved)[0];
if (!prev && l.resolved) {
Json.setStableId(l.resolved, (++k) + ".");
compiled.push(l.resolved);
}
});
Json.setStableId(a, "0.");
}
static getCompiledCode(that:CompiledScript, options:CompilerOptions)
{
Object.keys(that.libScripts).forEach((name:string) => { that.libScripts[name].primaryName = null })
var res = ""
if (options.cloud) {
res += "require('./noderuntime.js')\n" +
"var TDev = global.TDev;\n" +
"var window = global.TDev.window;\n" +
"var document = global.TDev.window.document;\n"
} else {
res += "var TDev;\n" +
"if (!TDev) TDev = {};\n"
}
res += "\nTDev.precompiledScript = {\n"
var first = true;
Object.keys(that.libScripts).forEach((name:string) => {
if (!first)
res += ",\n\n// **************************************************************\n"
first = false;
res += Util.jsStringLiteral(name) + ": ";
var cs = <CompiledScript>that.libScripts[name];
if (cs.primaryName) res += Util.jsStringLiteral(cs.primaryName);
else {
cs.primaryName = name;
res += cs.code
}
})
res += "}\n"
if (options.cloud) {
res += "\nTDev.RT.Node.runMainAsync().done();\n"
}
return res;
}
static getCompiledScript(a: App, options: CompilerOptions, initialBreakpoints?: Hashtable): CompiledScript // TODO: get rid of Hashtable here
{
var prep = new PreCompiler(options)
prep.run(a)
var cs = new CompiledScript();
cs.getCompiledCode = () => Compiler.getCompiledCode(cs, options);
a.clearRecompiler();
var compiled = [];
a.setStableNames();
var k = 0;
a.libraries().forEach((l:LibraryRef) => {
//if (options.packaging && l.isCloud()) return
var prev = compiled.filter((e) => e.app == l.resolved)[0];
if (!prev) {
prev = { app: l.resolved, cs: new CompiledScript() };
if (prev.app) {
var opts = Util.flatClone(options);
opts.dynamic = false;
opts.isTopLevel = false;
Json.setStableId(prev.app, (++k) + ".");
opts.libStaticPrefix = "l" + k + "_"
if (opts.debugging) prev.cs.initBreakpoints = (initialBreakpoints || Hashtable.forStrings());
Compiler.compileCore(prev.app, prev.cs, opts);
if (opts.hasCloudData) options.hasCloudData = true;
if (opts.hasPartialData) options.hasPartialData = true;
if (opts.hasLocalData) options.hasLocalData = true;
}
cs.missingApis.pushRange(prev.cs.missingApis);
cs.packageResources.pushRange(prev.cs.packageResources);
}
cs.registerLibRef(l.getStableName(), prev.cs);
});
Json.setStableId(a, "0.");
options.libStaticPrefix = "l0_"
// Initialize the analysis pipeline, will call all necessary
// analyses to perform the requested optimizations
var reachingDefsTime = 0;
var usedAnalysisTime = 0;
var availableExpressionsTime = 0;
var constantPropagationTime = 0;
var inlineAnalysisTime = 0;
var compileTime = 0;
if (options.profiling || options.debugging)
options.inlining = false;
if (options.inlining) {
try {
var iaCounter = TDev.RT.Perf.start("inlineanalysis");
var ia = new InlineAnalysis();
ia.dispatch(a);
ia.nestedInlineAnalysis();
inlineAnalysisTime = TDev.RT.Perf.stop(iaCounter);
} catch (err) {
Util.reportError('Inline Analysis failed', err, false);
inlineAnalysisTime = -1;
options.inlining = false;
}
}
if (options.okElimination) {
try {
var rdCounter = TDev.RT.Perf.start("reachingdefs");
var rd = new ReachingDefinitions();
rd.visitApp(a);
reachingDefsTime = TDev.RT.Perf.stop(rdCounter);
var uaCounter = TDev.RT.Perf.start("usedanalysis");
var ua = new UsedAnalysis();
ua.visitApp(a);
usedAnalysisTime = TDev.RT.Perf.stop(uaCounter);
} catch (err) {
Util.reportError('Reaching Definitions failed', err, false);
reachingDefsTime = -1;
options.okElimination = false;
}
}
if (options.commonSubexprElim) {
var aeCounter = TDev.RT.Perf.start("availableexpressions");
var ae = new AvailableExpressions();
ae.visitApp(a);
availableExpressionsTime = TDev.RT.Perf.stop(aeCounter);
try {
} catch (err) {
Util.reportError('CSE failed', err, false);
availableExpressionsTime = -1;
options.commonSubexprElim = false;
}
}
if (options.constantPropagation) {
var cpCounter = TDev.RT.Perf.start("constantpropagation");
var cp = new ConstantPropagation();
cp.visitApp(a);
constantPropagationTime = TDev.RT.Perf.stop(cpCounter);
try {
} catch (err) {
Util.reportError('ConstantPropagation failed', err, false);
constantPropagationTime = -1;
options.constantPropagation = false;
}
}
var opts = Util.flatClone(options);
opts.isTopLevel = true;
if (options.debugging) cs.initBreakpoints = (initialBreakpoints || Hashtable.forStrings());
var beCounter = TDev.RT.Perf.start("backend");
Compiler.compileCore(a, cs, opts);
compileTime = TDev.RT.Perf.stop(beCounter);
// Output optimization statistics
if (options.inlining) {
Util.log(Util.fmt("Inliner: {0} inlined call(s), {1} inlined action(s)",
cs.optStatistics.inlinedCalls, cs.optStatistics.inlinedFunctions));
}
if (options.okElimination) {
Util.log(Util.fmt("Ok elimination: {0} check(s) eliminated (estimated)", cs.optStatistics.eliminatedOks));
}
if (options.commonSubexprElim) {
Util.log(Util.fmt("CSE: {0} term(s) reused (estimated)", cs.optStatistics.termsReused));
}
if (options.constantPropagation) {
Util.log(Util.fmt("CP: {0} constant(s) propagated (estimated)", cs.optStatistics.constantsPropagated));
}
cs.optStatistics.reachingDefsTime = reachingDefsTime;
cs.optStatistics.usedAnalysisTime = usedAnalysisTime;
cs.optStatistics.inlineAnalysisTime = inlineAnalysisTime;
cs.optStatistics.availableExpressionsTime = availableExpressionsTime;
cs.optStatistics.constantPropagationTime = constantPropagationTime;
cs.optStatistics.compileTime = compileTime;
return cs;
}
private compileLibs(a:App)
{
if (this.globalError) {
this.wr("cs.libBindings = {};\n");
return;
}
this.wr("(function () {\n");
this.wr(" var lib, bnd, resolve;\n");
this.wr(" var bnds = cs.libBindings = {};\n");
a.librariesAndThis().forEach((l:LibraryRef) => {
var ln = this.stringLiteral(l.getStableName());
this.wr(" lib = libs[" + ln + "] = {};\n");
this.wr(" bnd = bnds[" + ln + "] = " + (l.getStableName() == "this" ? "libs" : "{}") + ";\n");
this.wr(" bnd.mkLambdaProxy = cs.mkLambdaProxy(bnd, " + ln + ");\n");
if (this.options.scriptId) {
var libid = l.isThis() ? this.options.scriptId : l.pubid ? l.pubid : l.guid
if (l.resolved)
this.wr(" bnd.scriptName = " + this.stringLiteral(l.resolved.getName() + " (" + libid + ")") + ";\n");
this.wr(" bnd.scriptId = " + this.stringLiteral(libid) + ";\n");
this.wr(" bnd.topScriptId = " + this.stringLiteral(this.options.scriptId) + ";\n");
}
//if (this.options.packaging && l.isCloud()) return
l.getPublicActions().forEach((act:Action) => {
if (!this.shouldCompile(act)) return
var an = this.stringLiteral(act.getName());
this.wr(" lib[" + an + "] = cs.mkLibProxyFactory(bnd, " + ln + ", " + an + ");\n");
});
});
a.libraries().forEach((l:LibraryRef) => {
//if (this.options.packaging && l.isCloud()) return
var ln = this.stringLiteral(l.getStableName());
this.wr(" bnd = bnds[" + ln + "];\n");
this.wr(" bnd[\"this$lib\"] = " + ln + ";\n")
l.resolveClauses.forEach((r:ResolveClause) => {
var rn = this.stringLiteral(r.formalLib.getStableName());
this.wr(" resolve = bnd[" + rn + "] = {};\n");
this.wr(" bnd[" + rn + " + \"$lib\"] = " + this.stringLiteral(r.defaultLib.getStableName()) + ";\n");
r.actionBindings.forEach((ab:ActionBinding) => {
var fn = this.stringLiteral(ab.actualLib.getStableName())
var act = "libs[" + fn + "][" + this.stringLiteral(ab.actual.getName()) + "]";
this.wr(" resolve[" + this.stringLiteral(ab.formalName) + "] = " + act + ";\n");
});
});
});
this.wr("}());\n");
}
private libInits = (nm:string) => {};
public visitApp(a:App)
{
this.stmtIds = StmtIdCollector.collect(a);
if (this.options.isTopLevel) {
var libInits = []
a.libraries().forEach(l => {
if (l.getLibInit())
libInits.push(l.getStableName())
})
if (libInits.length > 0) {
this.libInits = nm => {
this.wr(" if (!s.rt._libinitDone) return s.rt.runLibInits(" + JSON.stringify(libInits) + ", " + nm + ");\n")
}
}
}
this.initGlobals = "";
this.initGlobals2 = "";
this.currentApp = a;
this.needsScriptText = false;
var err = this.currentApp.getGlobalErrorDecl(!this.options.isTopLevel);
if (err) {
this.globalError = Util.fmt("'{0}' (in '{1}') has errors; the script will not run", err.getName(), this.currentApp.getName());
this.globalErrorId = err.getStableName();
} else {
this.globalError = null;
this.globalErrorId = null;
}
this.runmap_variables.clear();
this.wr("(function (cs) {\n");
this.wr("'use strict';\n");
this.wr("var libs = cs.libs = {};\n");
this.wr("var lib = TDev.RT;\n");
this.wr("var callstackcurdepth = 0;\n");
if (this.needsProfiling()) {
this.wr("var profilingScriptStart = Date.now();\n");
}
if (this.debugBuild()) {
this.wr("cs.breakpointBindings = {};\n");
this.stmtIds.forEach(v => {
var varname = "bp$" + v.replace(/\./g, "_");
this.wr("var " + varname + " = !!cs.initBreakpoints.get(" + this.stringLiteral(v) +");\n");
this.wr("cs.breakpointBindings[" + this.stringLiteral(v) + "] = { setter : function(smth) { " + varname + " = smth; }, getter: function () { return " + varname + "; } };\n");
});
}
this.wr("cs.scriptTitle = " + this.stringLiteral(a.getName()) + ";\n");
this.wr("cs.scriptColor = " + this.stringLiteral(a.htmlColor()) + ";\n");
this.wr("cs.objectSingletons = {};\n")
if (a.showAd)
this.wr("cs.showAd = true;\n");
a.things.forEach((t) => this.dispatch(t));
if (this.options.isTopLevel) this.compileLibs(a);
this.wr("cs.startFn = function(rt) {\n" + api.rt_start + "};\n\n");
this.wr("cs.stopFn = function(rt) {\n" + api.rt_stop + "};\n\n");
if (this.instrumentForCoverage()) {
this.wr("cs.extractRunMap = function(rt) {\n");
this.runmap_variables.forEach((v) => this.wr(" if(" + v[1] + ") rt.beenHere(" + this.stringLiteral(v[0]) + ");\n"))
this.wr("};\n\n");
}
if (!this.options.cloud && this.options.isTopLevel) {
this.imports.cordovaPlugins = AppImports.combineCordovaPlugins(a);
}
if (this.options.cloud && this.options.isTopLevel) {
this.imports.pipPackages = AppImports.combinePipPackages(a);
if (!a.isCloud) {
this.wr("cs.autoRouting = true;\n")
if (this.options.hasCloudData)
this.options.hostCloudData = true;
}
this.wr("cs.setupRestRoutes = function(rt) {\n")
var host = /^https?:\/\/(.+?)\/?$/i.exec(this.options.azureSite)[1];
a.librariesAndThis()
.stableSorted((l1, l2) => l1.getStableName().localeCompare(l2.getStableName()))
.forEach(l => {
if (!l.isCloud()) return
l.getPublicActions().stableSorted((a1, a2) => a1.getName().localeCompare(a2.getName())).forEach(a => {
var ref = "libs[" + this.stringLiteral(l.getStableName()) + "][" + this.stringLiteral(a.getName()) + "]"
if (a.getName() == "_init") {
this.wr(" rt.addRestInit(" + ref + ");\n")
} else {
var name = (l.isThis() || l.getName() == "*") ? "" : l.getName() + "/"
if (a.getName() != "*")
name += a.getName()
name = name.replace(/\/+$/, "")
this.wr(" rt.addRestRoute(" + this.stringLiteral(name) + ", " + ref + ");\n")
}
if (l.isThis() && a.getName() == "main")
this.wr(" rt.setMainAction(" + ref + ");\n")
})
})
this.wr(" rt.nodeModules = {};\n")
var imports = AppImports.combineNpmModules(a)
var deps = this.imports.npmModules
Object.keys(imports).forEach(k => {
if (imports[k] == "error") {
this.wr(" TDev.Util.syntaxError(" + this.stringLiteral("node.js module version conflict on " + k) + ");\n");
} else {
this.wr(" rt.nodeModules." + Api.runtimeName(k) + " = require(" + this.stringLiteral(k) + ");\n")
var v = imports[k]
if (v)
deps[k] = v
}
})
this.wr("}\n\n")
}
this.wr("cs._compilerVersion = '" + Compiler.version + "';\n");
this.wr("cs._initGlobals = function(d,rt) {\n" + this.initGlobals + "\n");
this.initPersistentVars(true);
this.initPersistentVars(false);
this.wr("};\n\n");
this.wr("cs._initGlobals2 = function(d) {\n" + this.initGlobals2 + "};\n\n");
this.wr("cs._resetGlobals = function(d) {\n" + this.resetGlobals + "};\n\n");
this.wr("cs._importJson = function(d,ctx,json) {\n" + this.cloudstateJsonImport + "};\n\n");
this.wr("cs._exportJson = function(d,ctx) {\n"
+ " var json = {};\n"
+ this.cloudstateJsonExport
+ " return json;\n};\n\n");
if (this.needsProfiling()) { // emit global profiling vars collected during parsing [CCC]
for (var blockId in this.profilingBlocks) {
this.wr("var profilingExecutions" + blockId + " = 1;\n");
this.wr("var profilingExecutionsNext" + blockId + " = 1;\n");
this.wr("var profilingExecutionsNextCount" + blockId + " = 1;\n");
var stmtIds = this.profilingBlocks[blockId];
for (var i = 0; i < stmtIds.length; i++) { // create global vars to store durations per-callsite
this.wr("var profilingDuration" + stmtIds[i] + " = 0;\n");
this.wr("var profilingDurationSamples" + stmtIds[i] + " = 0;\n");
}
}
this.wr("\n");
this.wr("var tmp = 0;\n\n");
this.wr("var perfNow = TDev.Util.perfNow;\n\n");
this.wr("cs._getProfilingResults = function() {\n");
this.wr(" var profilingDataCollection = {\n"); // editor retrieves this object after script execution
this.wr(" unitduration: " + localStorage["perfunit"] +",\n");
this.wr(" compilerversion: '" + Compiler.version + "',\n");
this.wr(" astnodes: {},\n");
this.wr(" show: " + this.options.showProfiling + "\n");
this.wr(" };\n");
this.wr(" var astnodes = profilingDataCollection.astnodes;\n");
this.wr(" astnodes[''] = {count: 1, duration: (Date.now() - profilingScriptStart)};\n");
this.wr(" var hits;\n");
for (var blockId in this.profilingBlocks) { // store global vars in return object
var stmtIds = this.profilingBlocks[blockId];
for (var i = 0; i < stmtIds.length; i++) {
var stmtId = stmtIds[i];
var duration = "profilingDuration" + stmtId;
var samples = "profilingDurationSamples" + stmtId;
this.wr(" hits = profilingExecutionsNextCount" + blockId + "-" + "profilingExecutions" + blockId + ";\n"); // shared by all stmtExprHolder nested directly under same block
// we assume that these n samples were representative of all executions :-)
var d = "Math.ceil(" + duration + "/" + samples + "*hits)";
this.wr(" if (hits) astnodes['" + stmtId + "'] = {count: hits, duration: " + d + "};\n");
}
}
if (this.needsProfilingDebug())
this.wr(" alert(JSON.stringify(profilingDataCollection));\n");
this.wr(" return profilingDataCollection;\n");
this.wr("};\n\n");
}
if (this.options.showCoverage)
this.wr("cs._showCoverage = true;\n");
var main = a.mainAction();
if (main)
this.wr("cs.mainActionName = " + this.stringLiteral(main.getName()) + ";\n");
if (this.options.authorId)
this.wr("cs.authorId = " + this.stringLiteral(this.options.authorId) + ";\n");
if (this.options.scriptId && !/-/.test(this.options.scriptId))
this.wr("cs.scriptId = " + this.stringLiteral(this.options.scriptId) + ";\n");
if (this.options.scriptGuid)
this.wr("cs.scriptGuid = " + this.stringLiteral(this.options.scriptGuid) + ";\n");
if (this.options.baseScriptId && !/-/.test(this.options.baseScriptId))
this.wr("cs.baseScriptId = " + this.stringLiteral(this.options.baseScriptId) + ";\n");
if (this.options.logoUrl)
this.wr("cs.logoUrl = " + this.stringLiteral(this.options.logoUrl) + ";\n");
if (this.options.hasCloudData)
this.wr("cs.hasCloudData = 1;\n");
if (this.options.hasPartialData)
this.wr("cs.hasPartialData = 1;\n");
if (this.options.azureSite)
this.wr("cs.azureSite = " + this.stringLiteral(this.options.azureSite) + ";\n");
if (this.options.hasLocalData)
this.wr("cs.hasLocalData = 1;\n");
if (this.options.hostCloudData)
this.wr("cs.hostCloudData = 1;\n");
if (this.needsScriptText)
this.wr("var scriptText = " + this.stringLiteral(a.serialize()) + ";\n");
if (this.options.isTopLevel && this.options.usedProperties.hasOwnProperty("appreflect"))
this.wr("cs.reflectionInfo = { actions: " + JSON.stringify(Json.reflectionInfo(a)) + " };\n");
if (this.options.packaging && this.options.artResolver) {
if (a.iconArtId)
this.packageResources.push({
kind: 'art',
id: "scripticon",
url: this.options.artResolver(a.iconArtId),
packageUrl: null,
sourceName: "icon",
usageLevel: 1,
type: "picture"
});
if (a.splashArtId)
this.packageResources.push({
kind: 'art',
id: "scriptsplash",
url: this.options.artResolver(a.splashArtId),
packageUrl: null,
sourceName: "splash",
usageLevel: 1,
type: "picture"
});
}
this.runmap_variables.forEach((v) => this.wr("var " + v[1] + ";\n"));
this.wr("})");
}
private synthesizeOutput(params:ActionParameter[])
{
var pickerIf = this.allocateIf();
pickerIf.condition = this.term("s.previous.needsPicker");
params = params.slice(0);
var cloud = this.options.rest || this.options.cloud
if (!cloud)
params.reverse();
pickerIf.thenBody = params.map((p) =>
JsCall.direct((cloud ? "s.response.addRestResult" : "s.rt.displayResult"),
[new JsLiteral(this.stringLiteral(p.getName())), this.localVarRef(p.local)]));
pickerIf.elseBody = [];
return pickerIf;
}
private synthesizePicker(params:ActionParameter[])
{
var pickerIf = this.allocateIf();
pickerIf.condition = this.term("s.previous.needsPicker");
pickerIf.elseBody = [];
var l = this.allocateLabel();
var r = new JsLabelRef(l);
var str = (s:string) => new JsLiteral(this.stringLiteral(s));
if (this.options.rest || this.options.cloud) {
pickerIf.thenBody =
params.map((p) => {
var kind = p.getKind();
var v = JsCall.direct("s.rt.getRestArgument", [str(p.getName()), (kind instanceof RecordEntryKind) ? str((<RecordEntryKind>kind).record.getStableName()) : str(p.getKind().toString()), this.term("s")])
return this.localVarRef(p.local).gets(v);
});
pickerIf.thenBody.push(
this.term("s.response").gets(this.term("s.rt.getRestRequest().response()")))
} else {
var args:JsExpr[] =
params.map((p) =>
!p.getKind().picker ? this.term("undefined") :
JsCall.direct("lib.RTValue.mkPicker",
<JsExpr[]>[ this.term(p.getKind().picker),
this.term(this.defaultValue(p.getKind(), true)),
str(p.getName()),
str(this.localVarName(p.local))]));
args.unshift(r);
pickerIf.thenBody = [new JsExprStmt(JsCall.direct("s.rt.pickParameters", args)), new JsGoto(r, false), l];
}
return pickerIf;
}
static markUsedStuff(a:App)
{
var pre = new PreCompiler(<any>{})
pre.run(a)
}
}
class UsageComputer
extends NodeVisitor
{
public visitApp(a:App)
{
a.variablesAndResources().forEach(v => v.usageLevel = 0)
super.visitChildren(a)
}
public visitDecl(d:Decl) { super.visitChildren(d); }
public visitStmt(s:Stmt) { super.visitChildren(s); }
public visitExprHolder(eh:ExprHolder) { if (eh.parsed) this.dispatch(eh.parsed) }
private doCall(c:Call, outerFlags:PropertyFlags)
{
var p = c.getCalledProperty()
if (p && p.forwardsTo() instanceof GlobalDef) {
var gd = <GlobalDef>p.forwardsTo()
var lev = (outerFlags & PropertyFlags.NoCanvas) ? 1 : 2;
if (gd.usageLevel < lev)
gd.usageLevel = lev
}
var flags = p ? p.getFlags() : PropertyFlags.None
var a = c.args
for (var i = 0; i < a.length; ++i) {
if (a[i] instanceof Call)
this.doCall(<Call>a[i], flags)
else
this.dispatch(a[i])
}
}
public visitCall(c:Call)
{
this.doCall(c, PropertyFlags.None)
}
}
export class PreCompiler
extends DeepVisitor
{
constructor(public options:CompilerOptions)
{
super()
this.options.usedProperties = {}
}
useKind(k:Kind)
{
var r = k.getRecord()
if (r) this.runOnDecl(r)
}
useBuiltinProperty(p:IProperty)
{
this.options.usedProperties[p.usageKey().toLowerCase()] = true
}
secondaryRun(app: App)
{
app.libraries().forEach(l => {
if (l.isTutorial() || l.isCloud()) {
l.getPublicActions().forEach(a => this.runOnDecl(a))
}
var li = l.getLibInit()
if (li) this.runOnDecl(li)
})
}
}
} | the_stack |
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
* @packageDocumentation
* @module tiledmap
*/
import { ccclass } from 'cc.decorator';
import { EDITOR } from 'internal:constants';
import { Renderable2D } from '../2d/framework/renderable-2d';
import { SpriteFrame } from '../2d/assets/sprite-frame';
import { Component } from '../core/components';
import { TMXMapInfo } from './tmx-xml-parser';
import { Color, IVec2Like, Mat4, Size, Texture2D, Vec2, Vec3, Node, warn, logID, CCBoolean, director } from '../core';
import { TiledTile } from './tiled-tile';
import { MeshRenderData } from '../2d/renderer/render-data';
import { IBatcher } from '../2d/renderer/i-batcher.js';
import {
MixedGID, GID, Orientation, TiledTextureGrids, TMXTilesetInfo, RenderOrder, StaggerAxis, StaggerIndex, TileFlag,
GIDFlags, TiledGrid, TiledAnimationType, PropertiesInfo, TMXLayerInfo,
} from './tiled-types';
import { fillTextureGrids } from './tiled-utils';
import { NodeEventType } from '../core/scene-graph/node-event';
const _mat4_temp = new Mat4();
const _vec2_temp = new Vec2();
const _vec3_temp = new Vec3();
const _vec3_temp2 = new Vec3();
const _tempRowCol = { row: 0, col: 0 };
@ccclass('cc.TiledUserNodeData')
export class TiledUserNodeData extends Component {
_index = -1;
_row = -1;
_col = -1;
_tiledLayer: TiledLayer | null = null;
constructor () {
super();
}
}
export interface TiledMeshData {
renderData: MeshRenderData;
texture: Texture2D | null;
}
interface TiledSubNodeData {
subNodes: (null | TiledUserNodeData)[];
}
type TiledMeshDataArray = (TiledMeshData | TiledSubNodeData)[];
/**
* @en Render the TMX layer.
* @zh 渲染 TMX layer。
* @class TiledLayer
* @extends Component
*/
@ccclass('cc.TiledLayer')
export class TiledLayer extends Renderable2D {
// [row][col] = {count: 0, nodesList: []};
protected _userNodeGrid: { [key: number]: { count: number;[key: number]: { count: number, list: (TiledUserNodeData | null)[] } } } = {};
protected _userNodeMap: { [key: string]: TiledUserNodeData } = {};// [id] = node;
protected _userNodeDirty = false;
// store the layer tiles node, index is caculated by 'x + width * y', format likes '[0]=tileNode0,[1]=tileNode1, ...'
public tiledTiles: (TiledTile | null)[] = [];
// // store the layer tilesets index array
// _tilesetIndexArr: number[] = [];
// // tileset index to array index
// _tilesetIndexToArrIndex: { [key: number]: number } = {};
protected _viewPort = { x: -1, y: -1, width: -1, height: -1 };
protected _cullingRect = {
leftDown: { row: -1, col: -1 },
rightTop: { row: -1, col: -1 },
};
get cullingRect () { return this._cullingRect; }
protected _cullingDirty = true;
protected _rightTop = { row: -1, col: -1 };
get rightTop () { return this._rightTop; }
protected _layerInfo: TMXLayerInfo | null = null;
protected _mapInfo: TMXMapInfo | null = null;
// record max or min tile texture offset,
// it will make culling rect more large, which insure culling rect correct.
protected _topOffset = 0;
protected _downOffset = 0;
protected _leftOffset = 0;
protected _rightOffset = 0;
// store the layer tiles, index is caculated by 'x + width * y', format likes '[0]=gid0,[1]=gid1, ...'
public tiles: MixedGID[] = [];
// vertex array
public vertices: { minCol: number, maxCol: number, [key: number]: { left: number, bottom: number, index: number } }[] = [];
// vertices dirty
protected _verticesDirty = true;
protected _layerName = '';
protected _layerSize?: Size;
get layerSize () { return this._layerSize!; }
protected _minGID?: GID;
protected _maxGID?: GID;
protected _layerOrientation: null | Orientation = null;
protected _opacity?: number;
protected _tintColor?: Color;
// store all layer gid corresponding texture info, index is gid, format likes '[gid0]=tex-info,[gid1]=tex-info, ...'
public texGrids: TiledTextureGrids | null = null;
// store all tileset texture, index is tileset index, format likes '[0]=texture0, [1]=texture1, ...'
protected _textures: SpriteFrame[] = [];
protected _tilesets: TMXTilesetInfo[] = [];
protected _leftDownToCenterX = 0;
protected _leftDownToCenterY = 0;
protected _hasTiledNodeGrid = false;
protected _hasAniGrid = false;
protected _animations: TiledAnimationType | null = null;
// switch of culling
protected _enableCulling?: boolean;
public colorChanged = false;
protected _properties?: PropertiesInfo;
public renderOrder?: RenderOrder;
protected _staggerAxis?: StaggerAxis;
protected _staggerIndex?: StaggerIndex;
protected _hexSideLength?: number;
protected _mapTileSize?: Size;
protected _odd_even?: number;
protected _diffX1?: number;
protected _diffY1?: number;
protected _useAutomaticVertexZ?: boolean;
protected _vertexZvalue?: number;
protected _offset?: Vec2;
protected _meshRenderDataArray: TiledMeshDataArray | null = null;
get meshRenderDataArray () { return this._meshRenderDataArray; }
get leftDownToCenterX () { return this._leftDownToCenterX; }
get leftDownToCenterY () { return this._leftDownToCenterY; }
constructor () {
super();
}
public hasTiledNode () {
return this._hasTiledNodeGrid;
}
public hasAnimation () {
return this._hasAniGrid;
}
/**
* @en enable or disable culling
* @zh 开启或关闭裁剪。
* @method enableCulling
* @param value
*/
set enableCulling (value: boolean) {
if (this._enableCulling !== value) {
this._enableCulling = value;
this._cullingDirty = true;
this.markForUpdateRenderData();
}
}
get enableCulling () { return this._enableCulling!; }
/**
* @en Adds user's node into layer.
* @zh 添加用户节点。
* @method addUserNode
* @param {cc.Node} node
* @return {Boolean}
*/
public addUserNode (node: Node) {
let dataComp = node.getComponent(TiledUserNodeData);
if (dataComp) {
warn('CCTiledLayer:addUserNode node has been added');
return false;
}
dataComp = node.addComponent(TiledUserNodeData);
node.parent = this.node;
// node._renderFlag |= RenderFlow.FLAG_BREAK_FLOW;
this._userNodeMap[node.uuid] = dataComp;
dataComp._row = -1;
dataComp._col = -1;
dataComp._tiledLayer = this;
this._nodeLocalPosToLayerPos(node.getPosition(), _vec2_temp);
this._positionToRowCol(_vec2_temp.x, _vec2_temp.y, _tempRowCol);
this._addUserNodeToGrid(dataComp, _tempRowCol);
this._updateCullingOffsetByUserNode(node);
node.on(NodeEventType.TRANSFORM_CHANGED, this._userNodePosChange, dataComp);
node.on(NodeEventType.SIZE_CHANGED, this._userNodeSizeChange, dataComp);
return true;
}
/**
* @en Removes user's node.
* @zh 移除用户节点。
* @method removeUserNode
* @param {cc.Node} node
* @return {Boolean}
*/
public removeUserNode (node: Node) {
const dataComp = node.getComponent(TiledUserNodeData);
if (!dataComp) {
warn('CCTiledLayer:removeUserNode node is not exist');
return false;
}
node.off(NodeEventType.TRANSFORM_CHANGED, this._userNodePosChange, dataComp);
node.off(NodeEventType.SIZE_CHANGED, this._userNodeSizeChange, dataComp);
this._removeUserNodeFromGrid(dataComp);
delete this._userNodeMap[node.uuid];
node._removeComponent(dataComp);
dataComp.destroy();
node.removeFromParent();
// node._renderFlag &= ~RenderFlow.FLAG_BREAK_FLOW;
return true;
}
/**
* @en Destroy user's node.
* @zh 销毁用户节点。
* @method destroyUserNode
* @param {cc.Node} node
*/
public destroyUserNode (node: Node) {
this.removeUserNode(node);
node.destroy();
}
// acording layer anchor point to calculate node layer pos
protected _nodeLocalPosToLayerPos (nodePos: IVec2Like, out: IVec2Like) {
out.x = nodePos.x + this._leftDownToCenterX;
out.y = nodePos.y + this._leftDownToCenterY;
}
public getNodesByRowCol (row: number, col: number) {
const rowData = this._userNodeGrid[row];
if (!rowData) return null;
return rowData[col];
}
public getNodesCountByRow (row) {
const rowData = this._userNodeGrid[row];
if (!rowData) return 0;
return rowData.count;
}
protected _updateAllUserNode () {
this._userNodeGrid = {};
for (const dataId in this._userNodeMap) {
const dataComp = this._userNodeMap[dataId];
this._nodeLocalPosToLayerPos(dataComp.node.getPosition(), _vec2_temp);
this._positionToRowCol(_vec2_temp.x, _vec2_temp.y, _tempRowCol);
this._addUserNodeToGrid(dataComp, _tempRowCol);
this._updateCullingOffsetByUserNode(dataComp.node);
}
}
protected _updateCullingOffsetByUserNode (node_: Node) {
const node = node_._uiProps.uiTransformComp!.contentSize;
if (this._topOffset < node.height) {
this._topOffset = node.height;
}
if (this._downOffset < node.height) {
this._downOffset = node.height;
}
if (this._leftOffset < node.width) {
this._leftOffset = node.width;
}
if (this._rightOffset < node.width) {
this._rightOffset = node.width;
}
}
protected _userNodeSizeChange () {
const dataComp: TiledUserNodeData = this as unknown as any;
const node = dataComp.node;
const self = dataComp._tiledLayer!;
self._updateCullingOffsetByUserNode(node);
self._userNodeDirty = true;
self.markForUpdateRenderData();
}
protected _userNodePosChange () {
const dataComp: TiledUserNodeData = this as unknown as any;
const node = dataComp.node;
const self = dataComp._tiledLayer!;
self._nodeLocalPosToLayerPos(node.getPosition(), _vec2_temp);
self._positionToRowCol(_vec2_temp.x, _vec2_temp.y, _tempRowCol);
self._limitInLayer(_tempRowCol);
// users pos not change
if (_tempRowCol.row === dataComp._row && _tempRowCol.col === dataComp._col) return;
self._removeUserNodeFromGrid(dataComp);
self._addUserNodeToGrid(dataComp, _tempRowCol);
}
protected _removeUserNodeFromGrid (dataComp: TiledUserNodeData) {
const row = dataComp._row;
const col = dataComp._col;
const index = dataComp._index;
const rowData = this._userNodeGrid[row];
const colData = rowData && rowData[col];
if (colData) {
rowData.count--;
colData.count--;
colData.list[index] = null;
if (colData.count <= 0) {
colData.list.length = 0;
colData.count = 0;
}
}
dataComp._row = -1;
dataComp._col = -1;
dataComp._index = -1;
this._userNodeDirty = true;
this.markForUpdateRenderData();
}
protected _limitInLayer (rowCol: { row: number, col: number }) {
const row = rowCol.row;
const col = rowCol.col;
if (row < 0) rowCol.row = 0;
if (row > this._rightTop.row) rowCol.row = this._rightTop.row;
if (col < 0) rowCol.col = 0;
if (col > this._rightTop.col) rowCol.col = this._rightTop.col;
}
protected _addUserNodeToGrid (dataComp: TiledUserNodeData, tempRowCol: { col: number, row: number }) {
const row = tempRowCol.row;
const col = tempRowCol.col;
const rowData = this._userNodeGrid[row] = this._userNodeGrid[row] || { count: 0 };
const colData = rowData[col] = rowData[col] || { count: 0, list: [] };
dataComp._row = row;
dataComp._col = col;
dataComp._index = colData.list.length;
rowData.count++;
colData.count++;
colData.list.push(dataComp);
this._userNodeDirty = true;
}
public isUserNodeDirty () {
return this._userNodeDirty;
}
public setUserNodeDirty (value) {
this._userNodeDirty = value;
}
onEnable () {
super.onEnable();
this.node.on(NodeEventType.ANCHOR_CHANGED, this._syncAnchorPoint, this);
this.node.on(NodeEventType.TRANSFORM_CHANGED, this.updateCulling, this);
this.node.on(NodeEventType.SIZE_CHANGED, this.updateCulling, this);
this.node.parent!.on(NodeEventType.TRANSFORM_CHANGED, this.updateCulling, this);
this.node.parent!.on(NodeEventType.SIZE_CHANGED, this.updateCulling, this);
this.markForUpdateRenderData();
// delay 1 frame, since camera's matrix data is dirty
this.scheduleOnce(this.updateCulling.bind(this));
}
onDisable () {
super.onDisable();
this.node.parent!.off(NodeEventType.SIZE_CHANGED, this.updateCulling, this);
this.node.parent!.off(NodeEventType.TRANSFORM_CHANGED, this.updateCulling, this);
this.node.off(NodeEventType.SIZE_CHANGED, this.updateCulling, this);
this.node.off(NodeEventType.TRANSFORM_CHANGED, this.updateCulling, this);
this.node.off(NodeEventType.ANCHOR_CHANGED, this._syncAnchorPoint, this);
}
protected _syncAnchorPoint () {
const node = this.node;
const trans = node._uiProps.uiTransformComp!;
const scale = node.getScale();
this._leftDownToCenterX = trans.width * trans.anchorX * scale.x;
this._leftDownToCenterY = trans.height * trans.anchorY * scale.y;
this._cullingDirty = true;
this.markForUpdateRenderData();
}
onDestroy () {
super.onDestroy();
}
/**
* @en Gets the layer name.
* @zh 获取层的名称。
* @method getLayerName
* @return {String}
* @example
* let layerName = tiledLayer.getLayerName();
* cc.log(layerName);
*/
public getLayerName (): string {
return this._layerName;
}
/**
* @en Set the layer name.
* @zh 设置层的名称
* @method setLayerName
* @param {String} layerName
* @example
* tiledLayer.setLayerName("New Layer");
*/
public setLayerName (layerName: string) {
this._layerName = layerName;
}
/**
* @en Return the value for the specific property name.
* @zh 获取指定属性名的值。
* @method getProperty
* @param {String} propertyName
* @return {*}
* @example
* let property = tiledLayer.getProperty("info");
* cc.log(property);
*/
public getProperty (propertyName: string) {
return this._properties![propertyName];
}
/**
* @en Returns the position in pixels of a given tile coordinate.
* @zh 获取指定 tile 的像素坐标。
* @method getPositionAt
* @param {Vec2|Number} pos position or x
* @param {Number} [y]
* @return {Vec2}
* @example
* let pos = tiledLayer.getPositionAt(cc.v2(0, 0));
* cc.log("Pos: " + pos);
* let pos = tiledLayer.getPositionAt(0, 0);
* cc.log("Pos: " + pos);
*/
public getPositionAt (pos: IVec2Like | number, y?: number): Vec2 | null {
let x;
if (y !== undefined) {
x = Math.floor(pos as number);
y = Math.floor(y);
} else {
x = Math.floor((pos as IVec2Like).x);
y = Math.floor((pos as IVec2Like).y);
}
switch (this._layerOrientation) {
case Orientation.ORTHO:
return this._positionForOrthoAt(x, y);
case Orientation.ISO:
return this._positionForIsoAt(x, y);
case Orientation.HEX:
return this._positionForHexAt(x, y);
}
return null;
}
public isInvalidPosition (x: number, y: number) {
return x >= this._layerSize!.width || y >= this._layerSize!.height || x < 0 || y < 0;
}
protected _positionForIsoAt (x: number, y: number): Vec2 {
let offsetX = 0;
let offsetY = 0;
const index = Math.floor(x) + Math.floor(y) * this._layerSize!.width;
const gidAndFlags = this.tiles[index];
if (gidAndFlags) {
const gid = (((gidAndFlags as unknown as number) & TileFlag.FLIPPED_MASK) >>> 0);
const tileset = this.texGrids!.get(gid as unknown as GID)!.tileset;
const offset = tileset.tileOffset;
offsetX = offset.x;
offsetY = offset.y;
}
return new Vec2(
this._mapTileSize!.width * 0.5 * (this._layerSize!.height + x - y - 1) + offsetX,
this._mapTileSize!.height * 0.5 * (this._layerSize!.width - x + this._layerSize!.height - y - 2) - offsetY,
);
}
protected _positionForOrthoAt (x: number, y: number): Vec2 {
let offsetX = 0;
let offsetY = 0;
const index = Math.floor(x) + Math.floor(y) * this._layerSize!.width;
const gidAndFlags = this.tiles[index];
if (gidAndFlags) {
const gid = (((gidAndFlags as unknown as number) & TileFlag.FLIPPED_MASK) >>> 0) as unknown as GID;
const tileset = this.texGrids!.get(gid)!.tileset;
const offset = tileset.tileOffset;
offsetX = offset.x;
offsetY = offset.y;
}
return new Vec2(
x * this._mapTileSize!.width + offsetX,
(this._layerSize!.height - y - 1) * this._mapTileSize!.height - offsetY,
);
}
protected _positionForHexAt (col: number, row: number): Vec2 {
const tileWidth = this._mapTileSize!.width;
const tileHeight = this._mapTileSize!.height;
const rows = this._layerSize!.height;
const index = Math.floor(col) + Math.floor(row) * this._layerSize!.width;
const gid = ((this.tiles[index] as unknown as number) & TileFlag.FLIPPED_MASK) >>> 0;
let offset: IVec2Like;
if (this.texGrids!.get(gid as unknown as GID)) {
offset = this.texGrids!.get(gid as unknown as GID)!.tileset.tileOffset;
} else {
offset = { x: 0, y: 0 };
}
const odd_even = (this._staggerIndex === StaggerIndex.STAGGERINDEX_ODD) ? 1 : -1;
let x = 0;
let y = 0;
let diffX = 0;
let diffY = 0;
switch (this._staggerAxis) {
case StaggerAxis.STAGGERAXIS_Y:
diffX = 0;
if (row % 2 === 1) {
diffX = tileWidth / 2 * odd_even;
}
x = col * tileWidth + diffX + offset.x;
y = (rows - row - 1) * (tileHeight - (tileHeight - this._hexSideLength!) / 2) - offset.y;
break;
case StaggerAxis.STAGGERAXIS_X:
diffY = 0;
if (col % 2 === 1) {
diffY = tileHeight / 2 * -odd_even;
}
x = col * (tileWidth - (tileWidth - this._hexSideLength!) / 2) + offset.x;
y = (rows - row - 1) * tileHeight + diffY - offset.y;
break;
}
return new Vec2(x, y);
}
/**
* @en
* Sets the tiles gid (gid = tile global id) at a given tiles rect.
* @zh
* 设置给定区域的 tile 的 gid (gid = tile 全局 id),
* @method setTilesGIDAt
* @param {Array} gids an array contains gid
* @param {Number} beginCol begin col number
* @param {Number} beginRow begin row number
* @param {Number} totalCols count of column
* @example
* tiledLayer.setTilesGIDAt([1, 1, 1, 1], 10, 10, 2)
*/
public setTilesGIDAt (gids: number[], beginCol: number, beginRow: number, totalCols: number) {
if (!gids || gids.length === 0 || totalCols <= 0) return;
if (beginRow < 0) beginRow = 0;
if (beginCol < 0) beginCol = 0;
let gidsIdx = 0;
const endCol = beginCol + totalCols;
for (let row = beginRow; ; row++) {
for (let col = beginCol; col < endCol; col++) {
if (gidsIdx >= gids.length) return;
this._updateTileForGID(gids[gidsIdx] as unknown as MixedGID, col, row);
gidsIdx++;
}
}
}
/**
* @en
* Sets the tile gid (gid = tile global id) at a given tile coordinate.<br />
* The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor . Tileset Mgr +1.<br />
* If a tile is already placed at that position, then it will be removed.
* @zh
* 设置给定坐标的 tile 的 gid (gid = tile 全局 id),
* tile 的 GID 可以使用方法 “tileGIDAt” 来获得。<br />
* 如果一个 tile 已经放在那个位置,那么它将被删除。
* @method setTileGIDAt
* @param {Number} gid
* @param {Vec2|Number} posOrX position or x
* @param {Number} flagsOrY flags or y
* @param {Number} [flags]
* @example
* tiledLayer.setTileGIDAt(1001, 10, 10, 1)
*/
public setTileGIDAt (gid: MixedGID, x: number, y: number, flags?: number) {
const ugid = ((gid as unknown as number) & TileFlag.FLIPPED_MASK) >>> 0;
x = Math.floor(x);
y = Math.floor(y);
if (this.isInvalidPosition(x, y)) {
throw new Error('cc.TiledLayer.setTileGIDAt(): invalid position');
}
if (!this.tiles || !this._tilesets || this._tilesets.length === 0) {
logID(7238);
return;
}
if (ugid !== 0 && ugid < (this._tilesets[0].firstGid as unknown as number)) {
logID(7239, gid);
return;
}
flags = flags || 0;
this._updateTileForGID(((ugid | flags) >>> 0) as unknown as MixedGID, x, y);
}
protected _updateTileForGID (gidAndFlags: MixedGID, x: number, y: number): void {
const idx = 0 | (x + y * this._layerSize!.width);
if (idx >= this.tiles.length) return;
const oldGIDAndFlags = this.tiles[idx];
if (gidAndFlags === oldGIDAndFlags) return;
const gid = (((gidAndFlags as unknown as number) & TileFlag.FLIPPED_MASK) >>> 0);
const grid = this.texGrids!.get(gid as unknown as GID);
if (grid) {
this.tiles[idx] = gidAndFlags;
this._updateVertex(x, y);
} else {
this.tiles[idx] = 0 as unknown as MixedGID;
}
this._cullingDirty = true;
}
/**
* @en
* Returns the tile gid at a given tile coordinate. <br />
* if it returns 0, it means that the tile is empty. <br />
* @zh
* 通过给定的 tile 坐标、flags(可选)返回 tile 的 GID. <br />
* 如果它返回 0,则表示该 tile 为空。<br />
* @method getTileGIDAt
* @param {Vec2} pos
* @return {Number}
* @example
* let tileGid = tiledLayer.getTileGIDAt(0, 0);
*/
public getTileGIDAt (x: number, y: number): number | null {
if (this.isInvalidPosition(x, y)) {
throw new Error('cc.TiledLayer.getTileGIDAt(): invalid position');
}
if (!this.tiles) {
logID(7237);
return null;
}
const index = Math.floor(x) + Math.floor(y) * this._layerSize!.width;
// Bits on the far end of the 32-bit global tile ID are used for tile flags
const tile = this.tiles[index] as unknown as number;
return ((tile & TileFlag.FLIPPED_MASK) >>> 0);
}
/**
* @en
* Returns the tile flags at a given tile coordinate. <br />
* @zh
* 通过给定的 tile 坐标, 返回 tile 的 flags. <br />
* 如果它返回 null,则表示该 tile 为空。<br />
* @method getTileGIDAt
* @param {number}} x
* @param {number}} y
* @return {Number}
* @example
* let tileGid = tiledLayer.getTileGIDAt(0, 0);
*/
public getTileFlagsAt (x: number, y: number) {
if (this.isInvalidPosition(x, y)) {
throw new Error('TiledLayer.getTileFlagsAt: invalid position');
}
if (!this.tiles) {
logID(7240);
return null;
}
const idx = Math.floor(x) + Math.floor(y) * this._layerSize!.width;
// Bits on the far end of the 32-bit global tile ID are used for tile flags
const tile = this.tiles[idx] as unknown as number;
return ((tile & TileFlag.FLIPPED_ALL) >>> 0) as unknown as GIDFlags;
}
public setCullingDirty (value: boolean) {
this._cullingDirty = value;
}
public isCullingDirty (): boolean {
return this._cullingDirty;
}
// 'x, y' is the position of viewPort, which's anchor point is at the center of rect.
// 'width, height' is the size of viewPort.
public updateViewPort (x: number, y: number, width: number, height: number): void {
if (this._viewPort.width === width
&& this._viewPort.height === height
&& this._viewPort.x === x
&& this._viewPort.y === y) {
return;
}
this._viewPort.x = x;
this._viewPort.y = y;
this._viewPort.width = width;
this._viewPort.height = height;
// if map's type is iso, reserve bottom line is 2 to avoid show empty grid because of iso grid arithmetic
let reserveLine = 1;
if (this._layerOrientation === Orientation.ISO) {
reserveLine = 2;
}
const vpx = this._viewPort.x - this._offset!.x + this._leftDownToCenterX;
const vpy = this._viewPort.y - this._offset!.y + this._leftDownToCenterY;
let leftDownX = vpx - this._leftOffset;
let leftDownY = vpy - this._downOffset;
const rightTopX = vpx + width + this._rightOffset;
const rightTopY = vpy + height + this._topOffset;
const leftDown = this._cullingRect.leftDown;
const rightTop = this._cullingRect.rightTop;
if (leftDownX < 0) leftDownX = 0;
if (leftDownY < 0) leftDownY = 0;
// calc left down
this._positionToRowCol(leftDownX, leftDownY, _tempRowCol);
// make range large
_tempRowCol.row -= reserveLine;
_tempRowCol.col -= reserveLine;
// insure left down row col greater than 0
_tempRowCol.row = _tempRowCol.row > 0 ? _tempRowCol.row : 0;
_tempRowCol.col = _tempRowCol.col > 0 ? _tempRowCol.col : 0;
if (_tempRowCol.row !== leftDown.row || _tempRowCol.col !== leftDown.col) {
leftDown.row = _tempRowCol.row;
leftDown.col = _tempRowCol.col;
this._cullingDirty = true;
}
// show nothing
if (rightTopX < 0 || rightTopY < 0) {
_tempRowCol.row = -1;
_tempRowCol.col = -1;
} else {
// calc right top
this._positionToRowCol(rightTopX, rightTopY, _tempRowCol);
// make range large
_tempRowCol.row++;
_tempRowCol.col++;
}
// avoid range out of max rect
if (_tempRowCol.row > this._rightTop.row) _tempRowCol.row = this._rightTop.row;
if (_tempRowCol.col > this._rightTop.col) _tempRowCol.col = this._rightTop.col;
if (_tempRowCol.row !== rightTop.row || _tempRowCol.col !== rightTop.col) {
rightTop.row = _tempRowCol.row;
rightTop.col = _tempRowCol.col;
this._cullingDirty = true;
this.markForUpdateRenderData();
}
}
// the result may not precise, but it dose't matter, it just uses to be got range
protected _positionToRowCol (x: number, y: number, result: { col: number, row: number }): { col: number, row: number } {
const maptw = this._mapTileSize!.width;
const mapth = this._mapTileSize!.height;
const maptw2 = maptw * 0.5;
const mapth2 = mapth * 0.5;
let row = 0;
let col = 0;
let diffX2 = 0;
let diffY2 = 0;
const axis = this._staggerAxis;
switch (this._layerOrientation) {
// left top to right dowm
case Orientation.ORTHO:
col = Math.floor(x / maptw);
row = Math.floor(y / mapth);
break;
// right top to left down
// iso can be treat as special hex whose hex side length is 0
case Orientation.ISO:
col = Math.floor(x / maptw2);
row = Math.floor(y / mapth2);
break;
// left top to right dowm
case Orientation.HEX:
if (axis === StaggerAxis.STAGGERAXIS_Y) {
row = Math.floor(y / (mapth - this._diffY1!));
diffX2 = row % 2 === 1 ? maptw2 * this._odd_even! : 0;
col = Math.floor((x - diffX2) / maptw);
} else {
col = Math.floor(x / (maptw - this._diffX1!));
diffY2 = col % 2 === 1 ? mapth2 * -this._odd_even! : 0;
row = Math.floor((y - diffY2) / mapth);
}
break;
}
result.row = row;
result.col = col;
return result;
}
public updateCulling () {
if (EDITOR) {
this.enableCulling = false;
} else if (this._enableCulling) {
this.node.updateWorldTransform();
Mat4.invert(_mat4_temp, this.node.getWorldMatrix());
const camera = director.root!.batcher2D.getFirstRenderCamera(this.node);
if (camera) {
_vec3_temp.x = 0;
_vec3_temp.y = 0;
_vec3_temp.z = 0;
_vec3_temp2.x = camera.width;
_vec3_temp2.y = camera.height;
_vec3_temp2.z = 0;
camera.screenToWorld(_vec3_temp, _vec3_temp);
camera.screenToWorld(_vec3_temp2, _vec3_temp2);
// camera.getScreenToWorldPoint(_vec2_temp, _vec2_temp);
// camera.getScreenToWorldPoint(_vec2_temp2, _vec2_temp2);
Vec3.transformMat4(_vec3_temp, _vec3_temp, _mat4_temp);
Vec3.transformMat4(_vec3_temp2, _vec3_temp2, _mat4_temp);
this.updateViewPort(_vec3_temp.x, _vec3_temp.y, _vec3_temp2.x - _vec3_temp.x, _vec3_temp2.y - _vec3_temp.y);
}
}
}
/**
* @en Layer orientation, which is the same as the map orientation.
* @zh 获取 Layer 方向(同地图方向)。
* @method getLayerOrientation
* @return {Number}
* @example
* let orientation = tiledLayer.getLayerOrientation();
* cc.log("Layer Orientation: " + orientation);
*/
public getLayerOrientation () {
return this._layerOrientation;
}
/**
* @en properties from the layer. They can be added using Tiled.
* @zh 获取 layer 的属性,可以使用 Tiled 编辑器添加属性。
* @method getProperties
* @return {Object}
* @example
* let properties = tiledLayer.getProperties();
* cc.log("Properties: " + properties);
*/
public getProperties () {
return this._properties;
}
protected _updateVertex (col: number, row: number) {
const FLIPPED_MASK = TileFlag.FLIPPED_MASK;
const vertices = this.vertices;
const layerOrientation = this._layerOrientation;
const tiles = this.tiles;
if (!tiles) {
return;
}
const rightTop = this._rightTop;
const maptw = this._mapTileSize!.width;
const mapth = this._mapTileSize!.height;
const maptw2 = maptw * 0.5;
const mapth2 = mapth * 0.5;
const rows = this._layerSize!.height;
const cols = this._layerSize!.width;
const grids = this.texGrids!;
let left = 0;
let bottom = 0;
let axis: StaggerAxis;
let diffX1: number;
let diffY1: number;
let odd_even: number;
let diffX2: number;
let diffY2: number;
if (layerOrientation === Orientation.HEX) {
axis = this._staggerAxis!;
diffX1 = this._diffX1!;
diffY1 = this._diffY1!;
odd_even = this._odd_even!;
}
let cullingCol = 0;
let cullingRow = 0;
let gridGID: GID = 0 as unknown as GID;
// grid border
let topBorder = 0;
let downBorder = 0; let leftBorder = 0;
let rightBorder = 0;
const index = row * cols + col;
const gid = tiles[index];
gridGID = (((gid as unknown as number) & FLIPPED_MASK) >>> 0) as unknown as GID;
const grid = grids.get(gridGID)!;
if (!grid) {
return;
}
// if has animation, grid must be updated per frame
if (this._animations!.get(gridGID)) {
this._hasAniGrid = this._hasAniGrid || true;
}
switch (layerOrientation) {
// left top to right dowm
case Orientation.ORTHO:
cullingCol = col;
cullingRow = rows - row - 1;
left = cullingCol * maptw;
bottom = cullingRow * mapth;
break;
// right top to left down
case Orientation.ISO:
// if not consider about col, then left is 'w/2 * (rows - row - 1)'
// if consider about col then left must add 'w/2 * col'
// so left is 'w/2 * (rows - row - 1) + w/2 * col'
// combine expression is 'w/2 * (rows - row + col -1)'
cullingCol = rows + col - row - 1;
// if not consider about row, then bottom is 'h/2 * (cols - col -1)'
// if consider about row then bottom must add 'h/2 * (rows - row - 1)'
// so bottom is 'h/2 * (cols - col -1) + h/2 * (rows - row - 1)'
// combine expressionn is 'h/2 * (rows + cols - col - row - 2)'
cullingRow = rows + cols - col - row - 2;
left = maptw2 * cullingCol;
bottom = mapth2 * cullingRow;
break;
// left top to right dowm
case Orientation.HEX:
diffX2 = (axis! === StaggerAxis.STAGGERAXIS_Y && row % 2 === 1) ? maptw2 * odd_even! : 0;
diffY2 = (axis! === StaggerAxis.STAGGERAXIS_X && col % 2 === 1) ? mapth2 * -odd_even! : 0;
left = col * (maptw - diffX1!) + diffX2;
bottom = (rows - row - 1) * (mapth - diffY1!) + diffY2;
cullingCol = col;
cullingRow = rows - row - 1;
break;
}
const rowData = vertices[cullingRow] = vertices[cullingRow] || { minCol: 0, maxCol: 0 };
const colData = rowData[cullingCol] = rowData[cullingCol] || {};
// record each row range, it will faster when culling grid
if (rowData.minCol > cullingCol) {
rowData.minCol = cullingCol;
}
if (rowData.maxCol < cullingCol) {
rowData.maxCol = cullingCol;
}
// record max rect, when viewPort is bigger than layer, can make it smaller
if (rightTop.row < cullingRow) {
rightTop.row = cullingRow;
}
if (rightTop.col < cullingCol) {
rightTop.col = cullingCol;
}
// _offset is whole layer offset
// tileOffset is tileset offset which is related to each grid
// tileOffset coordinate system's y axis is opposite with engine's y axis.
const tileOffset = grid.tileset.tileOffset;
left += this._offset!.x + tileOffset.x + grid.offsetX;
bottom += this._offset!.y - tileOffset.y - grid.offsetY;
topBorder = -tileOffset.y + grid.tileset._tileSize.height - mapth;
topBorder = topBorder < 0 ? 0 : topBorder;
downBorder = tileOffset.y < 0 ? 0 : tileOffset.y;
leftBorder = -tileOffset.x < 0 ? 0 : -tileOffset.x;
rightBorder = tileOffset.x + grid.tileset._tileSize.width - maptw;
rightBorder = rightBorder < 0 ? 0 : rightBorder;
if (this._rightOffset < leftBorder) {
this._rightOffset = leftBorder;
}
if (this._leftOffset < rightBorder) {
this._leftOffset = rightBorder;
}
if (this._topOffset < downBorder) {
this._topOffset = downBorder;
}
if (this._downOffset < topBorder) {
this._downOffset = topBorder;
}
colData.left = left;
colData.bottom = bottom;
// this index is tiledmap grid index
colData.index = index;
this._cullingDirty = true;
}
protected _updateVertices () {
const vertices = this.vertices;
vertices.length = 0;
const tiles = this.tiles;
if (!tiles) {
return;
}
const rightTop = this._rightTop;
rightTop.row = -1;
rightTop.col = -1;
const rows = this._layerSize!.height;
const cols = this._layerSize!.width;
this._topOffset = 0;
this._downOffset = 0;
this._leftOffset = 0;
this._rightOffset = 0;
this._hasAniGrid = false;
for (let row = 0; row < rows; ++row) {
for (let col = 0; col < cols; ++col) {
this._updateVertex(col, row);
}
}
this._verticesDirty = false;
}
/**
* @en
* Get the TiledTile with the tile coordinate.<br/>
* If there is no tile in the specified coordinate and forceCreate parameter is true, <br/>
* then will create a new TiledTile at the coordinate.
* The renderer will render the tile with the rotation, scale, position and color property of the TiledTile.
* @zh
* 通过指定的 tile 坐标获取对应的 TiledTile。 <br/>
* 如果指定的坐标没有 tile,并且设置了 forceCreate 那么将会在指定的坐标创建一个新的 TiledTile 。<br/>
* 在渲染这个 tile 的时候,将会使用 TiledTile 的节点的旋转、缩放、位移、颜色属性。<br/>
* @method getTiledTileAt
* @param {Integer} x
* @param {Integer} y
* @param {Boolean} forceCreate
* @return {cc.TiledTile}
* @example
* let tile = tiledLayer.getTiledTileAt(100, 100, true);
* cc.log(tile);
*/
public getTiledTileAt (x: number, y: number, forceCreate?: boolean) {
if (this.isInvalidPosition(x, y)) {
throw new Error('TiledLayer.getTiledTileAt: invalid position');
}
if (!this.tiles) {
logID(7236);
return null;
}
const index = Math.floor(x) + Math.floor(y) * this._layerSize!.width;
let tile = this.tiledTiles[index];
if (!tile && forceCreate) {
const node = new Node();
tile = node.addComponent(TiledTile);
tile._x = x;
tile._y = y;
tile._layer = this;
tile.updateInfo();
node.parent = this.node;
return tile;
}
return tile;
}
/**
* @en
* Change tile to TiledTile at the specified coordinate.
* @zh
* 将指定的 tile 坐标替换为指定的 TiledTile。
* @method setTiledTileAt
* @param {Integer} x
* @param {Integer} y
* @param {cc.TiledTile} tiledTile
* @return {cc.TiledTile}
*/
public setTiledTileAt (x: number, y: number, tiledTile: TiledTile | null): TiledTile | null {
if (this.isInvalidPosition(x, y)) {
throw new Error('TiledLayer.setTiledTileAt: invalid position');
}
if (!this.tiles) {
logID(7236);
return null;
}
const index = Math.floor(x) + Math.floor(y) * this._layerSize!.width;
this.tiledTiles[index] = tiledTile;
this._cullingDirty = true;
if (tiledTile) {
this._hasTiledNodeGrid = true;
} else {
this._hasTiledNodeGrid = this.tiledTiles.some((tiledNode) => !!tiledNode);
}
return tiledTile;
}
/**
* @en Return texture.
* @zh 获取纹理。
* @method getTexture
* @param index The index of textures
* @return {Texture2D}
*/
public getTexture (index?: number): SpriteFrame | null {
index = index || 0;
if (this._textures && index >= 0 && this._textures.length > index) {
return this._textures[index];
}
return null;
}
/**
* @en Return texture.
* @zh 获取纹理。
* @method getTextures
* @return {Texture2D}
*/
public getTextures () {
return this._textures;
}
/**
* @en Set the texture.
* @zh 设置纹理。
* @method setTexture
* @param {SpriteFrame} texture
*/
public setTexture (texture: SpriteFrame) {
this.setTextures([texture]);
}
/**
* @en Set the texture.
* @zh 设置纹理。
* @method setTexture
* @param {SpriteFrame} textures
*/
public setTextures (textures: SpriteFrame[]) {
this._textures = textures;
this.markForUpdateRenderData();
}
/**
* @en Gets layer size.
* @zh 获得层大小。
* @method getLayerSize
* @return {Size}
* @example
* let size = tiledLayer.getLayerSize();
* cc.log("layer size: " + size);
*/
public getLayerSize (): Size {
return this._layerSize!;
}
/**
* @en Size of the map's tile (could be different from the tile's size).
* @zh 获取 tile 的大小( tile 的大小可能会有所不同)。
* @method getMapTileSize
* @return {Size}
* @example
* let mapTileSize = tiledLayer.getMapTileSize();
* cc.log("MapTile size: " + mapTileSize);
*/
public getMapTileSize (): Size {
return this._mapTileSize!;
}
/**
* @en Gets Tile set first information for the layer.
* @zh 获取 layer 索引位置为0的 Tileset 信息。
* @method getTileSet
* @param index The index of tilesets
* @return {TMXTilesetInfo}
*/
public getTileSet (index: number): TMXTilesetInfo | null {
index = index || 0;
if (this._tilesets && index >= 0 && this._tilesets.length > index) {
return this._tilesets[index];
}
return null;
}
/**
* @en Gets tile set all information for the layer.
* @zh 获取 layer 所有的 Tileset 信息。
* @method getTileSet
* @return {TMXTilesetInfo}
*/
public getTileSets (): TMXTilesetInfo[] {
return this._tilesets;
}
/**
* @en Sets tile set information for the layer.
* @zh 设置 layer 的 tileset 信息。
* @method setTileSet
* @param {TMXTilesetInfo} tileset
*/
public setTileSet (tileset: TMXTilesetInfo) {
this.setTileSets([tileset]);
}
/**
* @en Sets Tile set information for the layer.
* @zh 设置 layer 的 Tileset 信息。
* @method setTileSets
* @param {TMXTilesetInfo} tilesets
*/
public setTileSets (tilesets: TMXTilesetInfo[]) {
this._tilesets = tilesets;
const textures: SpriteFrame[] = this._textures = [];
const texGrids = this.texGrids!;
texGrids.clear();
for (let i = 0; i < tilesets.length; i++) {
const tileset = tilesets[i];
if (tileset) {
textures[i] = tileset.sourceImage!;
}
}
for (let i = 0, l = tilesets.length; i < l; ++i) {
const tilesetInfo = tilesets[i];
if (!tilesetInfo) continue;
fillTextureGrids(tilesetInfo, texGrids, tilesetInfo.sourceImage);
}
this._prepareToRender();
}
public init (layerInfo: TMXLayerInfo, mapInfo: TMXMapInfo, tilesets: TMXTilesetInfo[], textures: SpriteFrame[], texGrids: TiledTextureGrids) {
this._cullingDirty = true;
this._layerInfo = layerInfo;
this._mapInfo = mapInfo;
const size = layerInfo.layerSize!;
// layerInfo
this._layerName = layerInfo.name;
this.tiles = layerInfo.tiles as unknown as any;
this._properties = layerInfo.properties;
this._layerSize = size;
this._minGID = layerInfo.minGID;
this._maxGID = layerInfo.maxGID;
this._opacity = layerInfo.opacity;
if (layerInfo.tintColor) {
this._tintColor = layerInfo.tintColor;
// this.node.color = this._tintColor;
}
this.renderOrder = mapInfo.renderOrder;
this._staggerAxis = mapInfo.getStaggerAxis()!;
this._staggerIndex = mapInfo.getStaggerIndex()!;
this._hexSideLength = mapInfo.getHexSideLength();
this._animations = mapInfo.getTileAnimations();
// tilesets
this._tilesets = tilesets;
// textures
this._textures = textures;
// grid texture
this.texGrids = texGrids;
// mapInfo
this._layerOrientation = mapInfo.orientation;
this._mapTileSize = mapInfo.getTileSize();
const maptw = this._mapTileSize.width;
const mapth = this._mapTileSize.height;
const layerW = this._layerSize.width;
const layerH = this._layerSize.height;
if (this._layerOrientation === Orientation.HEX) {
let width = 0;
let height = 0;
this._odd_even = (this._staggerIndex === StaggerIndex.STAGGERINDEX_ODD) ? 1 : -1;
if (this._staggerAxis === StaggerAxis.STAGGERAXIS_X) {
this._diffX1 = (maptw - this._hexSideLength) / 2;
this._diffY1 = 0;
height = mapth * (layerH + 0.5);
width = (maptw + this._hexSideLength) * Math.floor(layerW / 2) + maptw * (layerW % 2);
} else {
this._diffX1 = 0;
this._diffY1 = (mapth - this._hexSideLength) / 2;
width = maptw * (layerW + 0.5);
height = (mapth + this._hexSideLength) * Math.floor(layerH / 2) + mapth * (layerH % 2);
}
this.node._uiProps.uiTransformComp!.setContentSize(width, height);
} else if (this._layerOrientation === Orientation.ISO) {
const wh = layerW + layerH;
this.node._uiProps.uiTransformComp!.setContentSize(maptw * 0.5 * wh, mapth * 0.5 * wh);
} else {
this.node._uiProps.uiTransformComp!.setContentSize(layerW * maptw, layerH * mapth);
}
// offset (after layer orientation is set);
this._offset = new Vec2(layerInfo.offset.x, -layerInfo.offset.y);
this._useAutomaticVertexZ = false;
this._vertexZvalue = 0;
this._syncAnchorPoint();
this._prepareToRender();
}
protected _prepareToRender () {
this._updateVertices();
this._updateAllUserNode();
}
public requestMeshRenderData () {
if (!this._meshRenderDataArray) {
this._meshRenderDataArray = [];
}
const arr = this._meshRenderDataArray as any[];
while (arr.length > 0 && arr[arr.length - 1].subNodes && arr[arr.length - 1].subNodes.length === 0) {
arr.pop();
}
if (arr.length > 0) {
const last = arr[arr.length - 1];
if (last.renderData && last.renderData.byteCount === 0) {
return last as TiledMeshData;
}
}
const renderData = new MeshRenderData();
const comb = { renderData, texture: null };
Object.defineProperty(renderData, 'material', { get: () => this.getRenderMaterial(0) });
this._meshRenderDataArray.push(comb);
return comb;
}
public requestSubNodesData () {
if (!this._meshRenderDataArray) {
this._meshRenderDataArray = [];
}
const arr = this._meshRenderDataArray as any[];
while (arr.length > 0 && arr[arr.length - 1].renderData && arr[arr.length - 1].renderData.byteCount === 0) {
arr.pop();
}
if (arr.length > 0) {
if (arr[arr.length - 1].subNodes && arr[arr.length - 1].subNodes.length === 0) {
return arr[arr.length - 1] as TiledSubNodeData;
}
}
const renderData: (TiledUserNodeData | null)[] = [];
const comb = { subNodes: renderData };
this._meshRenderDataArray.push(comb);
return comb;
}
public destroyRenderData () {
if (this._meshRenderDataArray) {
this._meshRenderDataArray.forEach((rd) => { if ((rd as TiledMeshData).renderData) (rd as TiledMeshData).renderData.reset(); });
this._meshRenderDataArray.length = 0;
}
}
protected _flushAssembler () {
const assembler = TiledLayer.Assembler!.getAssembler(this);
if (this._assembler !== assembler) {
this._assembler = assembler;
}
if (!this._meshRenderDataArray) {
if (this._assembler && this._assembler.createData) {
this._assembler.createData(this);
this.markForUpdateRenderData();
this._updateColor();
}
}
}
// 当前的 _meshRenderDataArray 的索引, 以便 fillBuffers 选取 RenderData
public _meshRenderDataArrayIdx = 0;
protected _render (ui: IBatcher) {
if (this._meshRenderDataArray) {
for (let i = 0; i < this._meshRenderDataArray.length; i++) {
this._meshRenderDataArrayIdx = i;
const m = this._meshRenderDataArray[i];
if ((m as TiledSubNodeData).subNodes) {
// 提前处理 User Nodes
(m as TiledSubNodeData).subNodes.forEach((c) => {
if (c) ui.walk(c.node);
});
} else if ((m as TiledMeshData).texture) {
// NOTE: 由于 commitComp 只支持单张纹理, 故分多次提交
ui.commitComp(this, (m as TiledMeshData).texture, this._assembler, null);
}
}
this.node._static = true;
}
}
} | the_stack |
import {assertNotNullOrUndefined} from '../../../../../../front_end/core/platform/platform.js';
import type * as Logs from '../../../../../../front_end/models/logs/logs.js';
import type * as SDK from '../../../../../../front_end/core/sdk/sdk.js';
import * as Common from '../../../../../../front_end/core/common/common.js';
import * as RequestLinkIcon from '../../../../../../front_end/ui/components/request_link_icon/request_link_icon.js';
import * as IconButton from '../../../../../../front_end/ui/components/icon_button/icon_button.js';
import {assertElement, assertShadowRoot, renderElementIntoDOM} from '../../../helpers/DOMHelpers.js';
import * as Coordinator from '../../../../../../front_end/ui/components/render_coordinator/render_coordinator.js';
import type * as Protocol from '../../../../../../front_end/generated/protocol.js';
const {assert} = chai;
const coordinator = Coordinator.RenderCoordinator.RenderCoordinator.instance();
const renderRequestLinkIcon = async(data: RequestLinkIcon.RequestLinkIcon.RequestLinkIconData): Promise<{
component: RequestLinkIcon.RequestLinkIcon.RequestLinkIcon,
shadowRoot: ShadowRoot,
}> => {
const component = new RequestLinkIcon.RequestLinkIcon.RequestLinkIcon();
component.data = data;
renderElementIntoDOM(component);
assertShadowRoot(component.shadowRoot);
await coordinator.done();
return {component, shadowRoot: component.shadowRoot};
};
export const extractElements = (shadowRoot: ShadowRoot): {
icon: IconButton.Icon.Icon,
container: HTMLSpanElement,
label?: HTMLSpanElement,
} => {
const icon = shadowRoot.querySelector('devtools-icon');
assertElement(icon, IconButton.Icon.Icon);
const container = shadowRoot.querySelector('span');
assertNotNullOrUndefined(container);
const label = shadowRoot.querySelector('span > span');
if (label !== null) {
assertElement(label, HTMLSpanElement);
return {
icon,
container,
label,
};
}
return {icon, container};
};
export const extractData = (shadowRoot: ShadowRoot): {
iconData: IconButton.Icon.IconData,
label: string|null,
containerClasses: string[],
} => {
const {icon, container, label} = extractElements(shadowRoot);
return {
iconData: icon.data,
label: label ? label.textContent : null,
containerClasses: Array.from(container.classList),
};
};
interface MockRequestResolverEntry {
resolve: (request: SDK.NetworkRequest.NetworkRequest|null) => void;
promise: Promise<SDK.NetworkRequest.NetworkRequest|null>;
}
class MockRequestResolver {
private promiseMap: Map<string, MockRequestResolverEntry> = new Map();
waitFor(requestId?: string) {
if (!requestId) {
if (this.promiseMap.size !== 1) {
throw new Error('more than one request being awaited, specify a request id');
}
requestId = this.promiseMap.keys().next().value;
}
requestId = requestId || '';
const entry = this.promiseMap.get(requestId);
if (entry) {
return entry.promise;
}
let resolve: (request: SDK.NetworkRequest.NetworkRequest|null) => void = () => {};
const promise = new Promise<SDK.NetworkRequest.NetworkRequest|null>(r => {
resolve = r;
});
this.promiseMap.set(requestId, {resolve, promise});
return promise;
}
resolve(result: SDK.NetworkRequest.NetworkRequest|null, requestId?: string): void {
if (!requestId && this.promiseMap.size === 1) {
requestId = this.promiseMap.keys().next().value;
}
requestId = requestId || result?.requestId() || '';
const entry = this.promiseMap.get(requestId);
if (!entry) {
throw new Error('resolve uninitialized');
}
entry.resolve(result);
this.promiseMap.delete(requestId);
}
}
describe('RequestLinkIcon', () => {
const requestId1 = 'r1' as Protocol.Network.RequestId;
const requestId2 = 'r2' as Protocol.Network.RequestId;
describe('with simple requests', () => {
const mockRequest = {
url() {
return 'http://foo.bar/baz';
},
};
const mockRequestWithTrailingSlash = {
url() {
return 'http://foo.bar/baz/';
},
};
const failingRequestResolver = {
async waitFor() {
throw new Error('Couldn\'t resolve');
},
};
it('renders correctly without a request', async () => {
const {shadowRoot} = await renderRequestLinkIcon({
affectedRequest: {requestId: requestId1},
requestResolver: failingRequestResolver as unknown as Logs.RequestResolver.RequestResolver,
});
const {iconData, label} = extractData(shadowRoot);
assert.strictEqual('iconName' in iconData ? iconData.iconName : null, 'network_panel_icon');
assert.strictEqual(iconData.color, 'var(--issue-color-yellow)');
assert.isNull(label, 'Didn\'t expect a label');
});
it('renders correctly with a request', async () => {
const {shadowRoot} = await renderRequestLinkIcon({
request: mockRequest as unknown as SDK.NetworkRequest.NetworkRequest,
});
const {iconData, label} = extractData(shadowRoot);
assert.strictEqual('iconName' in iconData ? iconData.iconName : null, 'network_panel_icon');
assert.strictEqual(iconData.color, 'var(--color-link)');
assert.isNull(label, 'Didn\'t expect a label');
});
it('renders the request label correctly without a trailing slash', async () => {
const {shadowRoot} = await renderRequestLinkIcon({
request: mockRequest as unknown as SDK.NetworkRequest.NetworkRequest,
displayURL: true,
});
const {label} = extractData(shadowRoot);
assert.strictEqual(label, 'baz');
});
it('renders the request label correctly with a trailing slash', async () => {
const {shadowRoot} = await renderRequestLinkIcon({
request: mockRequestWithTrailingSlash as unknown as SDK.NetworkRequest.NetworkRequest,
displayURL: true,
});
const {label} = extractData(shadowRoot);
assert.strictEqual(label, 'baz/');
});
it('renders the request label correctly without a request', async () => {
const {shadowRoot} = await renderRequestLinkIcon({
affectedRequest: {requestId: requestId1, url: 'https://alpha.beta/gamma'},
requestResolver: failingRequestResolver as unknown as Logs.RequestResolver.RequestResolver,
displayURL: true,
});
const {label} = extractData(shadowRoot);
assert.strictEqual(label, 'gamma');
});
it('the style reacts to the presence of a request', async () => {
const {shadowRoot} = await renderRequestLinkIcon({
request: mockRequest as unknown as SDK.NetworkRequest.NetworkRequest,
});
const {containerClasses} = extractData(shadowRoot);
assert.include(containerClasses, 'link');
});
it('the style reacts to the absence of a request', async () => {
const {shadowRoot} = await renderRequestLinkIcon({
affectedRequest: {requestId: requestId1, url: 'https://alpha.beta/gamma'},
requestResolver: failingRequestResolver as unknown as Logs.RequestResolver.RequestResolver,
});
const {containerClasses} = extractData(shadowRoot);
assert.notInclude(containerClasses, 'link');
});
});
describe('transitions upon request resolution', () => {
const mockRequest = {
url() {
return 'http://foo.bar/baz';
},
};
it('to change the style correctly', async () => {
const resolver = new MockRequestResolver();
const {shadowRoot} = await renderRequestLinkIcon({
affectedRequest: {requestId: requestId1, url: 'https://alpha.beta/gamma'},
requestResolver: resolver as unknown as Logs.RequestResolver.RequestResolver,
});
const {containerClasses: containerClassesBefore} = extractData(shadowRoot);
assert.notInclude(containerClassesBefore, 'link');
resolver.resolve(mockRequest as unknown as SDK.NetworkRequest.NetworkRequest);
await new Promise(r => setTimeout(r)); // Drain Microtask queue to get the cooridnator.write posted.
await coordinator.done();
const {containerClasses: containerClassesAfter} = extractData(shadowRoot);
assert.include(containerClassesAfter, 'link');
});
it('to set the label correctly', async () => {
const resolver = new MockRequestResolver();
const {shadowRoot} = await renderRequestLinkIcon({
affectedRequest: {requestId: requestId1, url: 'https://alpha.beta/gamma'},
requestResolver: resolver as unknown as Logs.RequestResolver.RequestResolver,
displayURL: true,
});
const {label: labelBefore} = extractData(shadowRoot);
assert.strictEqual(labelBefore, 'gamma');
resolver.resolve(mockRequest as unknown as SDK.NetworkRequest.NetworkRequest);
await new Promise(r => setTimeout(r)); // Drain Microtask queue to get the cooridnator.write posted.
await coordinator.done();
const {label: labelAfter} = extractData(shadowRoot);
assert.strictEqual(labelAfter, 'baz');
});
it('to set icon color correctly', async () => {
const resolver = new MockRequestResolver();
const {shadowRoot} = await renderRequestLinkIcon({
affectedRequest: {requestId: requestId1, url: 'https://alpha.beta/gamma'},
requestResolver: resolver as unknown as Logs.RequestResolver.RequestResolver,
displayURL: true,
});
const {iconData: iconDataBefore} = extractData(shadowRoot);
assert.strictEqual(iconDataBefore.color, 'var(--issue-color-yellow)');
resolver.resolve(mockRequest as unknown as SDK.NetworkRequest.NetworkRequest);
await new Promise(r => setTimeout(r)); // Drain Microtask queue to get the cooridnator.write posted.
await coordinator.done();
const {iconData: iconDataAfter} = extractData(shadowRoot);
assert.strictEqual(iconDataAfter.color, 'var(--color-link)');
});
it('handles multiple data assignments', async () => {
const resolver = new MockRequestResolver();
const {shadowRoot, component} = await renderRequestLinkIcon({
affectedRequest: {requestId: requestId2, url: 'https://alpha.beta/gamma'},
requestResolver: resolver as unknown as Logs.RequestResolver.RequestResolver,
displayURL: true,
});
const {label: labelBefore} = extractData(shadowRoot);
assert.strictEqual(labelBefore, 'gamma');
const mockRequest2 = {
url() {
return 'http://foo.bar/baz';
},
requestId() {
return requestId1;
},
};
component.data = {
affectedRequest: {requestId: requestId1, url: 'https://alpha.beta/gamma'},
requestResolver: resolver as unknown as Logs.RequestResolver.RequestResolver,
displayURL: true,
};
resolver.resolve(mockRequest2 as unknown as SDK.NetworkRequest.NetworkRequest);
await new Promise(r => setTimeout(r)); // Drain Microtask queue to get the cooridnator.write posted.
await coordinator.done();
const {label: labelAfter} = extractData(shadowRoot);
assert.strictEqual(labelAfter, 'baz');
});
});
describe('handles clicks correctly', () => {
const mockRequest = {
url() {
return 'http://foo.bar/baz';
},
};
it('if the icon is clicked', async () => {
const revealOverride = sinon.fake(Common.Revealer.reveal);
const {shadowRoot} = await renderRequestLinkIcon({
request: mockRequest as unknown as SDK.NetworkRequest.NetworkRequest,
displayURL: true,
revealOverride,
});
const {icon} = extractElements(shadowRoot);
icon.click();
assert.isTrue(revealOverride.called);
});
it('if the container is clicked', async () => {
const revealOverride = sinon.fake(Common.Revealer.reveal);
const {shadowRoot} = await renderRequestLinkIcon({
request: mockRequest as unknown as SDK.NetworkRequest.NetworkRequest,
displayURL: true,
revealOverride,
});
const {container} = extractElements(shadowRoot);
container.click();
assert.isTrue(revealOverride.called);
});
it('if the label is clicked', async () => {
const revealOverride = sinon.fake(Common.Revealer.reveal);
const {shadowRoot} = await renderRequestLinkIcon({
request: mockRequest as unknown as SDK.NetworkRequest.NetworkRequest,
displayURL: true,
revealOverride,
});
const {label} = extractElements(shadowRoot);
label?.click();
assert.isTrue(revealOverride.called);
});
});
}); | the_stack |
import {
ComponentSet,
FileProperties,
MetadataApiRetrieve,
RetrieveResult,
SourceComponent
} from '@salesforce/source-deploy-retrieve';
import {
MetadataApiRetrieveStatus,
RequestStatus
} from '@salesforce/source-deploy-retrieve/lib/src/client/types';
import * as AdmZip from 'adm-zip';
import { expect } from 'chai';
import * as fs from 'fs';
import * as path from 'path';
import * as shell from 'shelljs';
import {
MetadataCacheExecutor,
MetadataCacheResult,
MetadataCacheService,
PathType
} from '../../../src/conflict/metadataCacheService';
import { stubRootWorkspace } from '../util/rootWorkspace.test-util';
import sinon = require('sinon');
import { SfdxPackageDirectories } from '../../../src/sfdxProject';
describe('Metadata Cache', () => {
describe('Metadata Cache Executor', () => {
const PROJ_ROOT = path.join(
__dirname,
'..',
'..',
'..',
'..',
'test',
'vscode-integration',
'diffs'
);
const usernameOrAlias = 'admin@ut-sandbox.org';
const PROJECT_DIR = path.join(PROJ_ROOT, 'meta-proj');
let workspaceStub: sinon.SinonStub;
let executor: MetadataCacheExecutor;
let componentStub: sinon.SinonStub;
let operationStub: sinon.SinonStub;
let processStub: sinon.SinonStub;
beforeEach(() => {
executor = new MetadataCacheExecutor(
usernameOrAlias,
'Source Diff',
'source-diff-loader',
handleCacheResults
);
operationStub = sinon.stub(
MetadataCacheService.prototype,
'createRetrieveOperation'
);
componentStub = sinon.stub(
MetadataCacheService.prototype,
'getSourceComponents'
);
processStub = sinon.stub(
MetadataCacheService.prototype,
'processResults'
);
workspaceStub = stubRootWorkspace(PROJECT_DIR);
});
afterEach(() => {
componentStub.restore();
processStub.restore();
operationStub.restore();
workspaceStub!.restore();
shell.rm('-rf', PROJECT_DIR);
});
it('Should run metadata service', async () => {
componentStub.resolves(new ComponentSet());
const mockOperation = new MetadataApiRetrieve({
usernameOrConnection: usernameOrAlias,
components: new ComponentSet(),
output: ''
});
const pollStatusStub = sinon.stub(mockOperation, 'pollStatus');
pollStatusStub.callsFake(() => {});
operationStub.resolves(mockOperation);
processStub.resolves(undefined);
await executor.run({ data: PROJECT_DIR, type: 'CONTINUE' });
expect(componentStub.callCount).to.equal(1);
expect(operationStub.callCount).to.equal(1);
expect(pollStatusStub.callCount).to.equal(1);
expect(processStub.callCount).to.equal(1);
});
});
describe('Metadata Cache Service', () => {
const PROJ_ROOT = path.join(
__dirname,
'..',
'..',
'..',
'..',
'test',
'vscode-integration',
'diffs'
);
const TEST_ASSETS_FOLDER = path.join(
__dirname,
'..',
'..',
'..',
'..',
'..',
'system-tests',
'assets'
);
const TEST_DATA_FOLDER = path.join(TEST_ASSETS_FOLDER, 'differ-testdata');
const usernameOrAlias = 'admin@ut-sandbox.org';
const PROJECT_DIR = path.join(PROJ_ROOT, 'meta-proj2');
let workspaceStub: sinon.SinonStub;
let packageStub: sinon.SinonStub;
let service: MetadataCacheService;
beforeEach(() => {
service = new MetadataCacheService(usernameOrAlias);
packageStub = sinon
.stub(SfdxPackageDirectories, 'getPackageDirectoryFullPaths')
.resolves([]);
workspaceStub = stubRootWorkspace(PROJECT_DIR);
});
afterEach(() => {
service.clearCache();
packageStub.restore();
workspaceStub!.restore();
shell.rm('-rf', PROJECT_DIR);
});
it('Should clear cache directory', async () => {
const cachePath = service.getCachePath();
const tempFilePath = path.join(cachePath, 'TestFile.xml');
shell.mkdir('-p', cachePath);
shell.touch([tempFilePath]);
expect(
fs.existsSync(tempFilePath),
`folder ${tempFilePath} should exist`
).to.equal(true);
const actualCachePath = service.clearCache();
expect(actualCachePath).to.equal(cachePath);
expect(
fs.existsSync(actualCachePath),
`folder ${actualCachePath} should not exist`
).to.equal(false);
});
it('Should find one component', async () => {
const projectPath = path.join(PROJECT_DIR, 'src');
// populate project metadata
const projectZip = new AdmZip();
projectZip.addLocalFolder(TEST_DATA_FOLDER);
projectZip.extractAllTo(projectPath);
const componentPath = path.join(
projectPath,
'aura',
'PictureGalleryCard',
'PictureGalleryCard.cmp'
);
service.initialize(componentPath, PROJECT_DIR);
const components = await service.getSourceComponents();
expect(components.size).to.equal(1);
});
it('Should find components', async () => {
const projectPath = path.join(PROJECT_DIR, 'src');
// populate project metadata
const projectZip = new AdmZip();
projectZip.addLocalFolder(TEST_DATA_FOLDER);
projectZip.extractAllTo(projectPath);
service.initialize(projectPath, PROJECT_DIR);
const components = await service.getSourceComponents();
expect(components.size).to.equal(14);
});
it('Should find components using a manifest', async () => {
const projectPath = path.join(PROJECT_DIR, 'src');
const manifestPath = path.join(
TEST_ASSETS_FOLDER,
'proj-testdata',
'manifest',
'one-class.xml'
);
// populate project metadata
const projectZip = new AdmZip();
projectZip.addLocalFolder(TEST_DATA_FOLDER);
projectZip.extractAllTo(projectPath);
service.initialize(manifestPath, PROJECT_DIR, true);
const components = await service.getSourceComponents();
expect(components.size).to.equal(1);
});
it('Should return cache results', async () => {
const projectPath = path.join(PROJECT_DIR, 'src');
const cachePath = service.getCachePath();
const retrieveRoot = path.join('main', 'default');
// populate project metadata
const projectZip = new AdmZip();
projectZip.addLocalFolder(TEST_DATA_FOLDER);
projectZip.extractAllTo(projectPath);
projectZip.extractAllTo(path.join(cachePath, retrieveRoot));
service.initialize(projectPath, PROJECT_DIR);
await service.getSourceComponents();
const results = loadMockCache(cachePath);
const cache = await service.processResults(results);
expect(cache).to.not.equal(undefined);
expect(cache?.selectedPath).to.equal(projectPath);
expect(cache?.selectedType).to.equal(PathType.Folder);
expect(cache?.cachePropPath).to.equal(
path.join(cachePath, 'prop', 'file-props.json')
);
expect(cache?.cache.baseDirectory).to.equal(cachePath);
expect(cache?.cache.commonRoot).to.equal(retrieveRoot);
expect(cache?.project.baseDirectory).to.equal(PROJECT_DIR);
expect(cache?.project.commonRoot).to.equal('src');
// verify contents of prop file
if (cache?.cachePropPath) {
const propObj = JSON.parse(
fs.readFileSync(cache?.cachePropPath, {
encoding: 'UTF-8'
})
);
expect(propObj.componentPath).to.equal(projectPath);
expect(propObj.fileProperties.length).to.equal(1);
const prop = propObj.fileProperties[0];
expect(prop.fullName).to.equal('One');
expect(prop.fileName).to.equal('One.cls');
}
});
});
async function handleCacheResults(
username: string,
cache?: MetadataCacheResult
): Promise<void> {}
function loadMockCache(cachePath: string): RetrieveResult {
const props: FileProperties[] = [
{
id: '1',
createdById: '2',
createdByName: 'Me',
createdDate: 'Today',
fileName: 'One.cls',
fullName: 'One',
lastModifiedById: '3',
lastModifiedByName: 'You',
lastModifiedDate: 'Tomorrow',
type: 'ApexClass'
}
];
const response: MetadataApiRetrieveStatus = {
done: true,
status: RequestStatus.Succeeded,
success: true,
id: '',
fileProperties: props,
zipFile: ''
};
const cacheComps = ComponentSet.fromSource(cachePath);
const results = new RetrieveResult(response, cacheComps);
return results;
}
describe('Static Methods', () => {
const compOne = {
fullName: 'HandlerCostCenter',
type: {
name: 'ApexClass'
}
};
const compTwo = {
fullName: 'Account',
type: {
name: 'CustomObject'
}
};
const childComp = {
fullName: 'AccountNumber',
parent: compTwo,
type: {
name: 'CustomField'
}
};
const fileProperties = [{
fullName: 'HandlerCostCenter',
lastModifiedDate: 'Today',
type: 'ApexClass'
},
{
fullName: 'Account',
lastModifiedDate: 'Yesterday',
type: 'CustomObject'
}] as FileProperties[];
it('Should correlate results correctly', () => {
const cacheResults = {
cache: {
baseDirectory: path.normalize('/a/b'),
commonRoot: 'c',
components: [compOne, compTwo, childComp] as SourceComponent[]
},
project: {
baseDirectory: path.normalize('/d'),
commonRoot: path.normalize('e/f'),
components: [compTwo, childComp, compOne] as SourceComponent[]
},
properties: fileProperties
} as MetadataCacheResult;
const components = MetadataCacheService.correlateResults(cacheResults);
expect(components.length).to.equal(2);
expect(components).to.have.deep.members([{
cacheComponent: compOne,
projectComponent: compOne,
lastModifiedDate: 'Today'
},
{
cacheComponent: compTwo,
projectComponent: compTwo,
lastModifiedDate: 'Yesterday'
}]);
});
it('Should correlate results for just a child component', () => {
const cacheResults = {
cache: {
baseDirectory: path.normalize('/a/b'),
commonRoot: 'c',
components: [compOne, childComp] as SourceComponent[]
},
project: {
baseDirectory: path.normalize('/d'),
commonRoot: path.normalize('e/f'),
components: [childComp, compOne] as SourceComponent[]
},
properties: fileProperties
} as MetadataCacheResult;
const components = MetadataCacheService.correlateResults(cacheResults);
expect(components.length).to.equal(2);
expect(components).to.have.deep.members([{
cacheComponent: compOne,
projectComponent: compOne,
lastModifiedDate: 'Today'
},
{
cacheComponent: childComp,
projectComponent: childComp,
lastModifiedDate: 'Yesterday'
}]);
});
});
}); | the_stack |
import {Message, Placeholder, makeMessageIdMap} from '../messages.js';
import {writeLocaleCodesModule} from '../locales.js';
import type {Locale} from '../types/locale.js';
import type {Config} from '../types/config.js';
import type {TransformOutputConfig} from '../types/modes.js';
import ts from 'typescript';
import {
isLitTemplate,
isMsgCall,
extractTemplate,
extractOptions,
generateMsgIdFromAstNode,
} from '../program-analysis.js';
import {KnownError} from '../error.js';
import {
escapeTextContentToEmbedInTemplateLiteral,
stringifyDiagnostics,
parseStringAsTemplateLiteral,
} from '../typescript.js';
import * as pathLib from 'path';
import {LitLocalizer} from '../index.js';
type TypeScriptTransformerFactoryFactory = (
program: ts.Program
) => ts.TransformerFactory<ts.SourceFile>;
/**
* Localizes a Lit project in transform mode.
*/
export class TransformLitLocalizer extends LitLocalizer {
config: Config & {output: TransformOutputConfig};
constructor(config: Config & {output: TransformOutputConfig}) {
super();
if (config.output.mode !== 'transform') {
throw new Error(
`Error: TransformLocalizer requires a localization config with output.mode "transform"`
);
}
this.config = config;
}
/**
* Compile the project for each locale, replacing all templates with their
* localized versions, and write to the configured locale directory structure.
*/
async build() {
this.assertTranslationsAreValid();
const {translations} = this.readTranslationsSync();
await transformOutput(
translations,
this.config,
this.config.output,
this.program
);
}
/**
* Make a map from each locale code to a function that takes a TypeScript
* Program and returns a TypeScript Transformer Factory that replaces all
* `msg` calls with localized templates.
*
* This factory is suitable for inclusion in the `before` array of the
* `customTransformers` parameter of the TypeScript `program.emit` method.
*/
transformers(): Map<Locale, TypeScriptTransformerFactoryFactory> {
const {translations} = this.readTranslationsSync();
const locales = [this.config.sourceLocale, ...this.config.targetLocales];
const factories = new Map<Locale, TypeScriptTransformerFactoryFactory>();
for (const locale of locales) {
factories.set(locale, (program: ts.Program) =>
litLocalizeTransform(
makeMessageIdMap(translations.get(locale) ?? []),
locale,
program
)
);
}
return factories;
}
}
/**
* Compile and emit the given TypeScript program using the lit-localize
* transformer.
*
* TODO(aomarks) Refactor this into the build() method above.
*/
async function transformOutput(
translationsByLocale: Map<Locale, Message[]>,
config: Config,
transformConfig: TransformOutputConfig,
program: ts.Program
) {
if (transformConfig.outputDir === undefined && !config.tsConfig) {
throw new KnownError(
`Either output.outputDir or tsConfig must be specified.`
);
}
if (transformConfig.localeCodesModule) {
await writeLocaleCodesModule(
config.sourceLocale,
config.targetLocales,
transformConfig.localeCodesModule
);
}
// TODO(aomarks) It doesn't seem that it's possible for a TypeScript
// transformer to emit a new file, so we just have to emit for each locale.
// Need to do some more investigation into the best way to integrate this
// transformation into a real project so that the user can still use --watch
// and other tsc flags. It would also be nice to support the language server,
// so that diagnostics will show up immediately in the editor.
const compilerOpts = program.getCompilerOptions();
const outRoot = transformConfig.outputDir ?? compilerOpts.outDir ?? '.';
for (const locale of [config.sourceLocale, ...config.targetLocales]) {
let translations;
if (locale !== config.sourceLocale) {
translations = new Map<string, Message>();
for (const message of translationsByLocale.get(locale) || []) {
translations.set(message.name, message);
}
}
compilerOpts.outDir = pathLib.join(outRoot, '/', locale);
program.emit(undefined, undefined, undefined, undefined, {
before: [litLocalizeTransform(translations, locale, program)],
});
}
}
/**
* Return a TypeScript TransformerFactory for the lit-localize transformer.
*/
export function litLocalizeTransform(
translations: Map<string, Message> | undefined,
locale: string,
program: ts.Program
): ts.TransformerFactory<ts.SourceFile> {
return (context) => {
return (file) => {
const transformer = new Transformer(
context,
translations,
locale,
program,
file
);
return ts.visitNode(file, transformer.boundVisitNode);
};
};
}
/**
* Implementation of the lit-localize TypeScript transformer.
*/
class Transformer {
private context: ts.TransformationContext;
private translations: Map<string, Message> | undefined;
private locale: string;
private typeChecker: ts.TypeChecker;
boundVisitNode = this.visitNode.bind(this);
sourceFile: ts.SourceFile;
constructor(
context: ts.TransformationContext,
translations: Map<string, Message> | undefined,
locale: string,
program: ts.Program,
sourceFile: ts.SourceFile
) {
this.context = context;
this.translations = translations;
this.locale = locale;
this.typeChecker = program.getTypeChecker();
this.sourceFile = sourceFile;
}
/**
* Top-level delegating visitor for all nodes.
*/
visitNode(node: ts.Node): ts.VisitResult<ts.Node> {
// msg('greeting', 'hello') -> 'hola'
if (isMsgCall(node, this.typeChecker)) {
return this.replaceMsgCall(node);
}
// html`<b>${msg('greeting', 'hello')}</b>` -> html`<b>hola</b>`
if (isLitTemplate(node)) {
// If an html-tagged template literal embeds a msg call, we want to
// collapse the result of that msg call into the parent template.
return tagLit(
makeTemplateLiteral(
this.recursivelyFlattenTemplate(node.template, true)
)
);
}
// import ... from '@lit/localize' -> (removed)
if (ts.isImportDeclaration(node)) {
const moduleSymbol = this.typeChecker.getSymbolAtLocation(
node.moduleSpecifier
);
if (moduleSymbol && this.fileNameAppearsToBeLitLocalize(moduleSymbol)) {
return undefined;
}
}
if (ts.isCallExpression(node)) {
// configureTransformLocalization(...) -> {getLocale: () => "es-419"}
if (
this.typeHasProperty(
node.expression,
'_LIT_LOCALIZE_CONFIGURE_TRANSFORM_LOCALIZATION_'
)
) {
return ts.createObjectLiteral(
[
ts.createPropertyAssignment(
ts.createIdentifier('getLocale'),
ts.createArrowFunction(
undefined,
undefined,
[],
undefined,
ts.createToken(ts.SyntaxKind.EqualsGreaterThanToken),
ts.createStringLiteral(this.locale)
)
),
],
false
);
}
// configureLocalization(...) -> Error
if (
this.typeHasProperty(
node.expression,
'_LIT_LOCALIZE_CONFIGURE_LOCALIZATION_'
)
) {
// TODO(aomarks) This error is not surfaced earlier in the analysis phase
// as a nicely formatted diagnostic, but it should be.
throw new KnownError(
'Cannot use configureLocalization in transform mode. ' +
'Use configureTransformLocalization instead.'
);
}
// updateWhenLocaleChanges() -> undefined
if (
this.typeHasProperty(node.expression, '_LIT_LOCALIZE_CONTROLLER_FN_')
) {
return ts.createIdentifier('undefined');
}
}
// @localized -> removed
if (
ts.isDecorator(node) &&
ts.isCallExpression(node.expression) &&
this.typeHasProperty(
node.expression.expression,
'_LIT_LOCALIZE_DECORATOR_'
)
) {
return undefined;
}
// LOCALE_STATUS_EVENT -> "lit-localize-status"
//
// We want to replace this imported string constant with its static value so
// that we can always safely remove the '@lit/localize' module import.
//
// TODO(aomarks) Maybe we should error here instead, since lit-localize
// won't fire any of these events in transform mode? But I'm still thinking
// about the use case of an app that can run in either runtime or transform
// mode without code changes (e.g. runtime for dev, transform for
// production)...
//
// We can't tag this string const with a special property like we do with
// our exported functions, because doing so breaks lookups into
// `WindowEventMap`. So we instead identify the symbol by name, and check
// that it was declared in the lit-localize module.
let eventSymbol = this.typeChecker.getSymbolAtLocation(node);
if (eventSymbol && eventSymbol.name === 'LOCALE_STATUS_EVENT') {
if (eventSymbol.flags & ts.SymbolFlags.Alias) {
// Symbols will be aliased in the case of
// `import {LOCALE_STATUS_EVENT} ...`
// but not in the case of `import * as ...`.
eventSymbol = this.typeChecker.getAliasedSymbol(eventSymbol);
}
for (const decl of eventSymbol.declarations ?? []) {
let sourceFile: ts.Node = decl;
while (!ts.isSourceFile(sourceFile)) {
sourceFile = sourceFile.parent;
}
const sourceFileSymbol =
this.typeChecker.getSymbolAtLocation(sourceFile);
if (
sourceFileSymbol &&
this.fileNameAppearsToBeLitLocalize(sourceFileSymbol)
) {
return ts.createStringLiteral('lit-localize-status');
}
}
}
return ts.visitEachChild(node, this.boundVisitNode, this.context);
}
/**
* Replace a lit-localize `msg` call with the string or template corresponding
* to that message. If translations are present, use the translation.
* Otherwise, use the source template directly from the second argument.
*/
replaceMsgCall(
call: ts.CallExpression
): ts.TemplateLiteral | ts.TaggedTemplateExpression | ts.StringLiteral {
const [templateArg, optionsArg] = call.arguments;
const templateResult = extractTemplate(
templateArg,
this.sourceFile,
this.typeChecker
);
if (templateResult.error) {
throw new Error(stringifyDiagnostics([templateResult.error]));
}
const {tag, contents, template} = templateResult.result;
let newTemplate = template;
const optionsResult = extractOptions(optionsArg, this.sourceFile);
if (optionsResult.error) {
throw new Error(stringifyDiagnostics([optionsResult.error]));
}
const options = optionsResult.result;
const id = options.id ?? generateMsgIdFromAstNode(template, tag === 'html');
if (this.translations !== undefined) {
const translation = this.translations.get(id);
if (translation !== undefined) {
// If translations are available, replace the source template from the
// second argument with the corresponding translation.
// Maps from <translation absolute expression index> to
// <[source placeholder index, placeholder-relative expression index]>.
const transExprToSourcePosition = new Map<number, [number, number]>();
// Maps from <source placeholder index> to <the number of expressions in
// that placeholder>.
const placeholderExpressionCounts = new Map<number, number>();
// The absolute position of each expression within the translated
// message.
let absTransExprIdx = 0;
// Maps source placeholder to their index.
const placeholdersByIndex = new Map<number, Placeholder>();
for (let i = 0, phIdx = 0; i < contents.length; i++) {
const content = contents[i];
if (typeof content === 'object') {
placeholdersByIndex.set(phIdx++, content);
}
}
const templateLiteralBody = translation.contents
.map((content) => {
if (typeof content === 'string') {
return escapeTextContentToEmbedInTemplateLiteral(content);
}
const sourcePlaceholderIdx = content.index;
const matchingPlaceholder =
placeholdersByIndex.get(sourcePlaceholderIdx);
if (matchingPlaceholder === undefined) {
throw new Error(
`Placeholder from translation does not appear in source.` +
`\nLocale: ${this.locale}` +
`\nPlaceholder: ${content.untranslatable}`
);
}
const parsedPlaceholder = parseStringAsTemplateLiteral(
matchingPlaceholder.untranslatable
);
if (ts.isTemplateExpression(parsedPlaceholder)) {
placeholderExpressionCounts.set(
sourcePlaceholderIdx,
parsedPlaceholder.templateSpans.length
);
for (let i = 0; i < parsedPlaceholder.templateSpans.length; i++) {
const placeholderRelativeExprIdx = i;
transExprToSourcePosition.set(absTransExprIdx++, [
sourcePlaceholderIdx,
placeholderRelativeExprIdx,
]);
}
}
return matchingPlaceholder.untranslatable;
})
.join('');
newTemplate = parseStringAsTemplateLiteral(templateLiteralBody);
if (ts.isTemplateExpression(newTemplate)) {
const newParts: Array<string | ts.Expression> = [];
newParts.push(newTemplate.head.text);
for (let i = 0; i < newTemplate.templateSpans.length; i++) {
const span = newTemplate.templateSpans[i];
const srcPos = transExprToSourcePosition.get(i);
if (srcPos === undefined) {
const expressionText = templateLiteralBody.slice(
span.expression.pos - 1,
span.expression.end - 1
);
throw new Error(
`Expression in translation does not appear in source.` +
`\nLocale: ${this.locale}` +
`\nExpression: ${expressionText}`
);
}
const [sourcePlaceholderIdx, placeholderRelativeExprIdx] = srcPos;
let absSourceExprIdx = placeholderRelativeExprIdx;
for (let j = 0; j < sourcePlaceholderIdx; j++) {
// Offset by the length of all preceding placeholder indexes.
absSourceExprIdx += placeholderExpressionCounts.get(j) ?? 0;
}
if (!ts.isTemplateExpression(template)) {
throw new Error('Internal error');
}
const sourceExpression = template.templateSpans[absSourceExprIdx];
newParts.push(sourceExpression.expression);
newParts.push(span.literal.text);
}
newTemplate = makeTemplateLiteral(newParts);
}
}
// TODO(aomarks) Emit a warning that a translation was missing.
}
// Nothing more to do with a simple string.
if (ts.isStringLiteral(newTemplate)) {
if (tag === 'html') {
throw new KnownError(
'Internal error: string literal cannot be html-tagged'
);
}
return newTemplate;
}
// We may have ended up with template expressions that can be represented
// more efficiently by hoisting them directly into the template.
//
// Given: html`Hello <b>${"World"}</b>`
// Generate: html`Hello <b>World</b>`
newTemplate = makeTemplateLiteral(
this.recursivelyFlattenTemplate(newTemplate, tag === 'html')
);
return tag === 'html' ? tagLit(newTemplate) : newTemplate;
}
/**
* For every expression in the given template, assume that it is a simple
* identifier, and substitute it with the corresponding TypeScript node in the
* given map.
*
* Given: html`Hello ${name}` with Map(['name', StringLiteral{"World"}])
* Generate: html`Hello ${"World"}`
*/
substituteIdentsInExpressions(
template: ts.TemplateExpression,
paramValues: Map<string, ts.Expression>
): ts.TemplateLiteral {
return ts.visitEachChild(
template,
(span: ts.Node) => {
if (!ts.isTemplateSpan(span)) {
return span;
}
const expression = span.expression;
if (!ts.isIdentifier(expression)) {
throw new KnownError('Expected expression to be identifier');
}
const ident = expression.text;
const value = paramValues.get(ident);
if (value === undefined) {
throw new KnownError('No value provided');
}
return ts.createTemplateSpan(value, span.literal);
},
this.context
);
}
/**
* Deconstruct the given template literal it into a sequence of strings and
* expressions. Transform each expression using this transformer class,
* deconstruct that result in the same way, and "flatten" the result into
* the parent template wherever possible. Strings are flattened into strings,
* and strings + HTML are flattened into HTML.
*
* Examples:
*
* [1] `foo` => ['foo']
* [2] `foo${name}bar` => ['foo', Expression{name}, 'bar']
* [3] `foo${"bar"}baz` => ['foo', 'bar', 'baz']
* [4] html`<b>${html`<i>foo</i>`}</b>` => ['<b>', '<i>foo</i>', '</b>']
* [5] html`<b>${msg("foo", 'bar')}</b>` => ['<b>', 'bar', '</b>']
*/
recursivelyFlattenTemplate(
template: ts.TemplateLiteral,
isLit: boolean
): Array<string | ts.Expression> {
if (ts.isNoSubstitutionTemplateLiteral(template)) {
return [template.text];
}
const fragments: Array<string | ts.Expression> = [template.head.text];
const subsume = (expression: ts.Expression): boolean => {
if (ts.isStringLiteral(expression)) {
fragments.push(expression.text);
} else if (ts.isTemplateLiteral(expression)) {
fragments.push(...this.recursivelyFlattenTemplate(expression, false));
} else if (isLit && isLitTemplate(expression)) {
fragments.push(
...this.recursivelyFlattenTemplate(expression.template, true)
);
} else {
return false;
}
return true;
};
for (let i = 0; i < template.templateSpans.length; i++) {
const span = template.templateSpans[i];
// A span preceded by `=` can be an attribute so skip subsume and
// keep it as an expression to produce valid lit-html template
// TODO(augustinekim) Consider optimizing to regular quoted string for
// regular html attributes
if (
(i === 0
? template.head.text
: template.templateSpans[i - 1].literal.text
).endsWith('=')
) {
fragments.push(ts.visitNode(span.expression, this.boundVisitNode));
fragments.push(span.literal.text);
continue;
}
let expression = span.expression;
// Can we directly subsume this span?
if (!subsume(expression)) {
// No, but it may still need transformation.
expression = ts.visitNode(expression, this.boundVisitNode);
// Maybe we can subsume it after transformation (e.g a `msg` call which
// is now transformed to a template)?
if (!subsume(expression)) {
// Still no, then keep the expression in a span as it was.
fragments.push(expression);
}
}
fragments.push(span.literal.text);
}
return fragments;
}
/**
* Return whether the given symbol looks like one of the lit-localize modules
* based on its filename. Note when we call this function, we're already
* strongly suspecting a lit-localize call.
*/
fileNameAppearsToBeLitLocalize(moduleSymbol: ts.Symbol): boolean {
// TODO(aomarks) Find a better way to implement this. We could probably just
// check for any file path matching '/@lit/localize/` -- however that will
// fail our tests because we import with a relative path in that case.
for (const decl of moduleSymbol.declarations ?? []) {
if (
ts.isSourceFile(decl) &&
(decl.fileName.endsWith('/localize/lit-localize.d.ts') ||
decl.fileName.endsWith('/localize/internal/locale-status-event.d.ts'))
) {
return true;
}
}
return false;
}
/**
* Return whether the tpe of the given node is "tagged" with the given special
* identifying property (e.g. "_LIT_LOCALIZE_MSG_").
*/
typeHasProperty(
node: ts.Node,
propertyName: string
): node is ts.CallExpression {
const type = this.typeChecker.getTypeAtLocation(node);
const props = this.typeChecker.getPropertiesOfType(type);
return props.some((prop) => prop.escapedName === propertyName);
}
}
/**
* Wrap a TemplateLiteral in the lit `html` tag.
*/
function tagLit(template: ts.TemplateLiteral): ts.TaggedTemplateExpression {
return ts.createTaggedTemplate(ts.createIdentifier('html'), template);
}
/**
* Given an array of strings and template expressions (as generated by
* `recursivelyFlattenTemplate`), create the simplest TemplateLiteral node,
* where contiguous string items are collapsed into a single TemplateHead or
* TemplateSpan.
*/
function makeTemplateLiteral(
fragments: Array<string | ts.Expression>
): ts.TemplateLiteral {
let textBuf: string[] = [];
const spans = [];
for (let i = fragments.length - 1; i >= 0; i--) {
const fragment = fragments[i];
if (typeof fragment === 'string') {
textBuf.unshift(fragment);
} else {
const text = textBuf.join('');
const literal =
spans.length === 0
? ts.createTemplateTail(text)
: ts.createTemplateMiddle(text);
const span = ts.createTemplateSpan(fragment, literal);
spans.unshift(span);
textBuf = [];
}
}
if (spans.length === 0) {
return ts.createNoSubstitutionTemplateLiteral(textBuf.join(''));
}
return ts.createTemplateExpression(
ts.createTemplateHead(textBuf.join('')),
spans
);
} | the_stack |
import { IDisposable } from '@lumino/disposable';
import { ContentType } from './content';
import { StickyCode } from './code';
import { StickyMarkdown } from './markdown';
import { StickyTab, Tab } from './tab';
import { StickyLand } from './stickyland';
import { MyIcons } from './icons';
type Position = {
x: number;
y: number;
width: number;
height: number;
};
type Size = {
width: number;
height: number;
};
const WINDOW_GAP = 5;
/**
* Class that implements the Code cell in StickyLand.
*/
export class FloatingWindow implements IDisposable {
container: HTMLElement | null;
containerSize: Size;
node: HTMLElement;
stickyCell: StickyCode | StickyMarkdown;
stickyTab: StickyTab;
stickyLand: StickyLand;
tab: Tab | null;
header: HTMLElement;
placeholder: HTMLElement;
cellType: ContentType;
isDisposed = false;
lastMousePos = [0, 0];
// Properties for FLIP animation
startPos: Position | null = null;
endPos: Position | null = null;
constructor(cellType: ContentType, stickyCell: StickyCode | StickyMarkdown) {
// Create the floating window element
this.node = document.createElement('div');
this.node.classList.add('floating-window', 'hidden');
// Append the floating window to different elements for notebook/lab
if (document.querySelector('#jp-main-content-panel') !== null) {
this.container = document.querySelector('#jp-main-content-panel');
} else {
this.container = document.querySelector('#main-panel');
}
this.container?.appendChild(this.node);
if (this.container === null) {
console.warn(
'StickyLand: Cannot find container to inject the floating cell!'
);
}
// Set max size to bound the floating window
this.containerSize = {
width: 2000,
height: 1500
};
if (this.container !== null) {
const containerBBox = this.container.getBoundingClientRect();
this.containerSize.width = containerBBox.width;
this.containerSize.height = containerBBox.height;
}
// Add a top header to the window
this.header = document.createElement('div');
this.header.classList.add('floating-header');
this.node.appendChild(this.header);
const headerText = document.createElement('span');
this.cellType = cellType;
this.stickyCell = stickyCell;
this.stickyTab = this.stickyCell.stickyContent.stickyLand.stickyTab;
this.tab = this.stickyTab.activeTab;
this.stickyLand = this.stickyCell.stickyContent.stickyLand;
// We first put the cell on the left edge of the notebook panel
const initLeft =
this.stickyCell.notebook.node.getBoundingClientRect().x + 10;
// Position the node to the inner region and offset it a little bit when
// users create multiple windows
const curLeft = initLeft + this.stickyLand.floatingWindows.length * 20;
const curTop = 100 + this.stickyLand.floatingWindows.length * 20;
this.node.style.left = `${curLeft}px`;
this.node.style.top = `${curTop}px`;
this.node.style.maxWidth = `${
this.containerSize.width - curLeft - WINDOW_GAP
}px`;
this.node.style.maxHeight = `${
this.containerSize.height - curTop - WINDOW_GAP
}px`;
// Query the cell index for this cell
let cellIndex = 1;
if (this.stickyTab.activeTab) {
cellIndex = this.stickyTab.activeTab.cellIndex;
}
if (cellType === ContentType.Code) {
headerText.innerText = `Code-${cellIndex}`;
} else {
headerText.innerText = `Markdown-${cellIndex}`;
}
this.header.appendChild(headerText);
// Add two buttons to the header
const headerIcons = document.createElement('div');
headerIcons.classList.add('button-group');
this.header.appendChild(headerIcons);
const icon1 = document.createElement('div');
icon1.classList.add('header-button');
icon1.setAttribute('title', 'Put pack the cell to StickyLand');
MyIcons.landIcon.element({ container: icon1 });
headerIcons.appendChild(icon1);
const icon2 = document.createElement('div');
icon2.classList.add('header-button');
icon2.setAttribute('title', 'Close the cell');
MyIcons.closeIcon2.element({ container: icon2 });
headerIcons.appendChild(icon2);
// Bind event handlers for those two buttons
icon1.addEventListener('click', this.landButtonClicked);
icon2.addEventListener('click', this.closeButtonClicked);
// Need to cancel mousedown event to avoid header dragging
icon1.addEventListener('mousedown', e => {
e.preventDefault();
e.stopPropagation();
});
icon2.addEventListener('mousedown', e => {
e.preventDefault();
e.stopPropagation();
});
// Allow users to drag the window to change the position
this.header.addEventListener('mousedown', this.headerMousedownHandler);
// Push itself to the floating window array
this.stickyLand.floatingWindows.push(this);
// Hide the launching icon
const launchIcon =
this.stickyCell.stickyContent.headerNode.querySelector(
'.button-launch'
)?.parentElement;
launchIcon?.classList.add('no-display');
// Register the start position
this.startPos = this.registerStartPos();
// Add the content from the cell to the floating window
const floatingContent = this.stickyCell.stickyContent.wrapperNode.cloneNode(
false
) as HTMLElement;
floatingContent.append(
...this.stickyCell.stickyContent.wrapperNode.childNodes
);
this.node.append(floatingContent);
// Set the initial width to fit the codemirror default width
const cmSizer = this.node.querySelector(
'.CodeMirror-sizer'
) as HTMLElement | null;
if (cmSizer !== null) {
this.node.style.width = `${parseInt(cmSizer.style.minWidth) + 20}px`;
}
// Register the end position
this.endPos = this.registerEndPos();
// Override the auto height from code mirror
this.node.style.height = `${this.endPos.height}px`;
// Play the animation
this.node.classList.remove('hidden');
this.playLaunchingAnimation();
// Add a placeholder in the original sticky content
this.placeholder = this.addPlaceholder();
}
/**
* Compute the initial window position + size
*/
registerStartPos = () => {
const bbox =
this.stickyCell.stickyContent.wrapperNode.getBoundingClientRect();
const headerHeight = 28;
return {
x: bbox.x,
y: bbox.y - headerHeight,
width: bbox.width,
height: bbox.height
};
};
/**
* Compute the ending floating window position + size
*/
registerEndPos = () => {
// pass
const bbox = this.node.getBoundingClientRect();
return {
x: bbox.x,
y: bbox.y,
width: bbox.width,
height: bbox.height
};
};
/**
* Animate the launching process of the floating window
*/
playLaunchingAnimation = () => {
if (this.startPos && this.endPos) {
// Compute the transformation from end to the start
const widthScale = this.startPos.width / this.endPos.width;
const heightScale = this.startPos.height / this.endPos.height;
const xTranslate = this.startPos.x - this.endPos.x;
const yTranslate = this.startPos.y - this.endPos.y;
// Apply the transform
this.node.animate(
[
{
transformOrigin: 'top left',
transform: `
translate(${xTranslate}px, ${yTranslate}px)
scale(${widthScale}, ${heightScale})
`
},
{
transformOrigin: 'top left',
transform: 'none'
}
],
{
duration: 200,
easing: 'cubic-bezier(0.4, 0.0, 0.2, 1)'
}
);
}
};
/**
* Animate the landing process of the floating window
*/
playLandingAnimation = (callback: () => void) => {
if (this.startPos && this.endPos) {
this.registerEndPos();
// Compute the transformation from start to the end
const widthScale = this.startPos.width / this.endPos.width;
const heightScale = this.startPos.height / this.endPos.height;
const xTranslate = this.startPos.x - this.endPos.x;
const yTranslate = this.startPos.y - this.endPos.y;
// Apply the transform
const animation = this.node.animate(
[
{
transformOrigin: 'top left',
transform: 'none',
opacity: 1
},
{
transformOrigin: 'top left',
transform: `
translate(${xTranslate}px, ${yTranslate}px)
scale(${widthScale}, ${heightScale})
`,
opacity: 0
}
],
{
duration: 350,
easing: 'cubic-bezier(0.0, 0.0, 0.2, 1)'
}
);
animation.onfinish = e => {
callback();
};
}
};
/**
* Add a place holder in the content node in StickyLand when the cell is floating
* @returns Placeholder node
*/
addPlaceholder = () => {
const placeholder = document.createElement('div');
placeholder.classList.add('floating-placeholder');
this.stickyCell.stickyContent.wrapperNode.appendChild(placeholder);
// Add an icon
const addIconElem = document.createElement('div');
addIconElem.classList.add('svg-icon');
placeholder.append(addIconElem);
MyIcons.launchIcon.element({ container: addIconElem });
// Add a text label
const label = document.createElement('span');
label.classList.add('placeholder-label');
label.innerText = 'This cell is floating';
placeholder.append(label);
// Add bottom container
const bottomContainer = document.createElement('div');
bottomContainer.classList.add('placeholder-bottom-container');
placeholder.append(bottomContainer);
// Create a button to summon the floating window
const button = document.createElement('button') as HTMLButtonElement;
button.classList.add('placeholder-button', 'button');
bottomContainer.append(button);
button.type = 'button';
button.innerText = 'summon';
button.addEventListener('click', this.landButtonClicked);
return placeholder;
};
/**
* Put the cell back to StickyLand.
* @param e Event
*/
landButtonClicked = (e: Event) => {
e.preventDefault();
e.stopPropagation();
this.land();
const callback = () => {
this.dispose();
};
this.playLandingAnimation(callback);
};
/**
* Land the sticky window and close the corresponding tab
* @param e Event
*/
closeButtonClicked = (e: Event) => {
e.preventDefault();
e.stopPropagation();
const callback = () => {
// First put back the cell
this.land();
// Close the tab
if (this.tab) {
this.stickyTab.closeTab(this.tab);
}
this.dispose();
};
// We don't need to play animation if user wants to close the cell
callback();
};
/**
* Put back the elements to the StickyLand.
*/
land = () => {
// Remove the placeholder
this.placeholder.remove();
// Put back the elements to stickyland
const floatingWrapper = this.node.querySelector('.sticky-content');
if (floatingWrapper) {
this.stickyCell.stickyContent.wrapperNode.append(
...floatingWrapper.childNodes
);
}
// Show the launching icon
const launchIcon =
this.stickyCell.stickyContent.headerNode.querySelector(
'.button-launch'
)?.parentElement;
launchIcon?.classList.remove('no-display');
// Remove the FloatingWindow object from the sticky content
const windowIndex =
this.stickyCell.stickyContent.stickyLand.floatingWindows.indexOf(this);
this.stickyCell.stickyContent.stickyLand.floatingWindows.splice(
windowIndex,
1
);
this.stickyCell.isFloating = false;
};
/**
* Event handler for mouse down. It trigger the document to listen to mouse
* move events
* @param e Event
*/
headerMousedownHandler = (e: Event) => {
e.preventDefault();
e.stopPropagation();
const mouseEvent = e as MouseEvent;
// Raise the clicked window
this.node.parentNode?.appendChild(this.node);
// Create a window size mask so that we can override the codemirror cursor
const cursorMask = document.createElement('div');
cursorMask.classList.add('cursor-mask');
cursorMask.style.cursor = 'move';
document.body.appendChild(cursorMask);
// Also need to mask the internal region
const innerCursorMask = document.createElement('div');
innerCursorMask.classList.add('cursor-mask');
innerCursorMask.style.cursor = 'move';
this.node.appendChild(innerCursorMask);
// Register the offset from the initial click position to the div location
this.lastMousePos = [mouseEvent.pageX, mouseEvent.pageY];
const mouseMoveHandler = (e: Event) => {
e.preventDefault();
e.stopPropagation();
const mouseEvent = e as MouseEvent;
let newX = this.node.offsetLeft + mouseEvent.pageX - this.lastMousePos[0];
let newY = this.node.offsetTop + mouseEvent.pageY - this.lastMousePos[1];
this.lastMousePos[0] = mouseEvent.pageX;
this.lastMousePos[1] = mouseEvent.pageY;
const nodeBBox = this.node.getBoundingClientRect();
// Bound x and y so the window is not out of its container
const maxNewX = this.containerSize.width - nodeBBox.width - WINDOW_GAP;
newX = Math.max(0, newX);
newX = Math.min(maxNewX, newX);
const maxNewY = this.containerSize.height - nodeBBox.height - WINDOW_GAP;
newY = Math.max(0, newY);
newY = Math.min(maxNewY, newY);
this.node.style.left = `${newX}px`;
this.node.style.top = `${newY}px`;
// Also bound the max width and max height to avoid resize overflow
if (newX !== maxNewX) {
this.node.style.maxWidth = `${
this.containerSize.width - newX - WINDOW_GAP
}px`;
}
if (newY !== maxNewY) {
this.node.style.maxHeight = `${
this.containerSize.height - newY - WINDOW_GAP
}px`;
}
};
const mouseUpHandler = () => {
document.removeEventListener('mousemove', mouseMoveHandler, true);
document.removeEventListener('mouseup', mouseUpHandler, true);
document.body.style.cursor = 'default';
cursorMask.remove();
innerCursorMask.remove();
};
// Bind the mouse event listener to the document so we can track the movement
// if outside the header region
document.addEventListener('mousemove', mouseMoveHandler, true);
document.addEventListener('mouseup', mouseUpHandler, true);
document.body.style.cursor = 'move';
};
dispose() {
this.header.removeEventListener('mousedown', this.headerMousedownHandler);
this.node.remove();
this.isDisposed = true;
}
} | the_stack |
import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import { FORM_ERROR } from 'final-form';
import FormErrorMessage from '@airbnb/lunar/lib/components/FormErrorMessage';
import Form, { FormProps } from '../../src/components/Form';
describe('<Form />', () => {
let wrapper: Enzyme.ShallowWrapper<FormProps<{}>, unknown, Form>;
let instance: Form;
beforeEach(() => {
wrapper = shallow(<Form onSubmit={(data) => Promise.resolve(data)}>Hello</Form>);
instance = wrapper.instance();
});
it('creates a final-form instance', () => {
expect(instance.form).toBeDefined();
});
it('can customize `initialValues`', () => {
wrapper = shallow(
<Form initialValues={{ foo: 'bar' }} onSubmit={() => Promise.resolve()}>
Hello
</Form>,
);
expect(wrapper.state('initialValues')).toEqual({ foo: 'bar' });
expect((wrapper.state('values') as { foo: string }).foo).toBe('bar');
});
it('can change `initialValues` through props', () => {
const spy = jest.fn();
wrapper = shallow(
<Form initialValues={{ foo: 'bar' }} onSubmit={() => Promise.resolve()}>
Hello
</Form>,
);
(wrapper.instance() as Form).form.initialize = spy;
wrapper.setProps({
initialValues: { foo: 'qux' },
});
expect(spy).toHaveBeenCalledWith({ foo: 'qux' });
});
it('renders children', () => {
expect(wrapper.find('form').prop('children')).toEqual(['Hello', undefined]);
});
it('renders function children', () => {
const spy = jest.fn();
wrapper = shallow(
<Form initialValues={{ foo: 'bar' }} onSubmit={() => Promise.resolve()}>
{spy}
</Form>,
);
expect(spy).toHaveBeenCalledWith(expect.objectContaining({ initialValues: { foo: 'bar' } }));
});
it('shows submit error', () => {
expect(wrapper.find(FormErrorMessage)).toHaveLength(0);
wrapper.setState({
submitError: 'Failed submit.',
});
expect(wrapper.find(FormErrorMessage)).toHaveLength(1);
expect(wrapper.find(FormErrorMessage).prop('error')).toBe('Failed submit.');
});
describe('castValue()', () => {
it('casts to type', () => {
expect(instance.castValue(123, String)).toBe('123');
});
it('supports arrays', () => {
expect(instance.castValue([1, 2, 3], String)).toEqual(['1', '2', '3']);
});
});
describe('changeValue()', () => {
let spy: jest.SpyInstance;
beforeEach(() => {
spy = jest.spyOn(instance.form, 'change');
instance.registerField(
{
name: 'foo',
defaultValue: 'foo',
validator() {},
},
() => {},
);
instance.registerField(
{
name: 'bar',
defaultValue: 'bar',
validator() {},
},
() => {},
);
instance.registerField(
{
name: 'baz',
defaultValue: 'baz',
validator() {},
},
() => {},
);
});
it('changes a single value', () => {
instance.changeValue('foo', 123);
expect(spy).toHaveBeenCalledWith('foo', 123);
});
it('batches multiple values', () => {
instance.changeValue('foo', 123, {
bar: 456,
baz: 789,
});
expect(spy).toHaveBeenCalledWith('bar', 456);
expect(spy).toHaveBeenCalledWith('baz', 789);
expect(spy).toHaveBeenCalledWith('foo', 123);
});
it('batch value cannot overwrite primary value', () => {
instance.changeValue('foo', 123, {
foo: 456,
});
expect(spy).toHaveBeenCalledWith('foo', 123);
});
it('skips unknown fields', () => {
instance.changeValue('wtf', 123, {
qux: 456,
});
expect(spy).not.toHaveBeenCalled();
});
});
describe('handleSubmit()', () => {
it('returns promise from `onSubmit`', () => {
// @ts-ignore Allow private access
const promise = instance.handleSubmit({}, {}, () => {});
expect(promise).toBeInstanceOf(Promise);
});
it('converts to a promise if `onSubmit` does not return one', () => {
wrapper.setProps({
// @ts-ignore Test non-promise
onSubmit: () => 123,
});
// @ts-ignore Allow private access
const promise = instance.handleSubmit({}, {}, () => {});
expect(promise).toBeInstanceOf(Promise);
});
it('converts to a promise if `onSubmit` does not return one, and handles any error', () => {
const spy = jest.fn();
wrapper.setProps({
onSubmit: () => {
throw new Error('Oops');
},
});
const promise = instance
// @ts-ignore Allow private access
.handleSubmit({}, {}, spy)
.then(() => {
expect(spy).toHaveBeenCalled();
})
.catch(() => {});
expect(promise).toBeInstanceOf(Promise);
});
it('passes data through', async () => {
// @ts-ignore Allow private access
const data = await instance.handleSubmit({ foo: 'bar' }, {}, () => {});
expect(data).toEqual({ foo: 'bar' });
});
it('sets error if catch occurs', async () => {
const spy = jest.fn();
const error = new Error('Oops');
wrapper.setProps({
onSubmit: () => Promise.reject(error),
});
try {
// @ts-ignore Allow private access
await instance.handleSubmit({}, {}, spy);
} catch (error_) {
expect(error_).toBe(error);
}
expect(spy).toHaveBeenCalled();
});
it('calls `onFailedSubmit` if catch occurs', async () => {
const spy = jest.fn();
const error = new Error('Oops');
wrapper.setProps({
onSubmit: () => Promise.reject(error),
onFailedSubmit: spy,
});
try {
// @ts-ignore Allow private access
await instance.handleSubmit({ foo: 'bar' }, {}, () => {});
} catch (error_) {
expect(error_).toBe(error);
}
expect(spy).toHaveBeenCalledWith({ foo: 'bar' }, error);
});
});
describe('handleFormReset()', () => {
it('calls reset on form', () => {
const spy = jest.spyOn(instance.form, 'reset');
wrapper.find('form').simulate('reset');
expect(spy).toHaveBeenCalled();
});
it('calls onReset prop', () => {
const spy = jest.fn();
wrapper.setProps({
onReset: spy,
});
wrapper.find('form').simulate('reset');
expect(spy).toHaveBeenCalled();
});
});
describe('handleFormSubmit()', () => {
it('calls submit on form', () => {
const spy = jest.spyOn(instance.form, 'submit');
wrapper.find('form').simulate('submit', { preventDefault() {} });
expect(spy).toHaveBeenCalled();
});
});
describe('handleValidate()', () => {
beforeEach(() => {
instance.registerField(
{
name: 'foo',
defaultValue: 'foo',
parse: String,
validator() {},
},
() => {},
);
instance.registerField(
{
name: 'bar',
defaultValue: 'bar',
parse: Number,
validator: () => {
throw new Error('Failure');
},
},
() => {},
);
instance.registerField(
{
name: 'baz',
defaultValue: 'baz',
parse: Boolean,
validator() {},
},
() => {},
);
});
it('calls `onValidate`', async () => {
const spy = jest.fn(() => true);
wrapper.setProps({
onValidate: spy,
});
// @ts-ignore Allow private access
await instance.handleValidate({ foo: 'foo' });
expect(spy).toHaveBeenCalledWith({ foo: 'foo' }, {}, expect.anything());
});
it('can fail using `onValidate`', async () => {
wrapper.setProps({
onValidate: () => false,
});
// @ts-ignore Allow private access
expect(await instance.handleValidate({ foo: 'foo' })).toEqual({
[FORM_ERROR]: 'Failed to validate form. Please try again.',
});
});
it('calls `onFailedValidate` if `onValidate` fails', async () => {
const spy = jest.fn();
wrapper.setProps({
onValidate: () => false,
onFailedValidate: spy,
});
// @ts-ignore Allow private access
await instance.handleValidate({ foo: 'foo' });
expect(spy).toHaveBeenCalledWith(
{ foo: 'foo' },
{
[FORM_ERROR]: 'Failed to validate form. Please try again.',
},
);
});
it('runs validators', async () => {
// @ts-ignore Allow private access
expect(await instance.handleValidate({ bar: 123 })).toEqual({
bar: 'Failure',
});
});
it('calls `onFailedValidate` if validators fails', async () => {
const spy = jest.fn();
wrapper.setProps({
onFailedValidate: spy,
});
// @ts-ignore Allow private access
await instance.handleValidate({ bar: 123 });
expect(spy).toHaveBeenCalledWith(
{ bar: 123 },
{
bar: 'Failure',
},
);
});
});
describe('prepareData()', () => {
beforeEach(() => {
instance.registerField(
{
name: 'foo',
defaultValue: 'foo',
parse: String,
validator() {},
},
() => {},
);
instance.registerField(
{
name: 'bar',
defaultValue: 'bar',
parse: Number,
validator() {},
},
() => {},
);
instance.registerField(
{
name: 'baz',
defaultValue: 'baz',
parse: Boolean,
validator() {},
},
() => {},
);
});
it('trims strings', () => {
expect(instance.prepareData({ foo: ' foo ' })).toEqual(
expect.objectContaining({ foo: 'foo' }),
);
});
it('parses strings', () => {
expect(instance.prepareData({ foo: 123 })).toEqual(expect.objectContaining({ foo: '123' }));
});
it('parses numbers', () => {
expect(instance.prepareData({ bar: '123' })).toEqual(expect.objectContaining({ bar: 123 }));
});
it('parses booleans', () => {
expect(instance.prepareData({ baz: 0 })).toEqual(expect.objectContaining({ baz: false }));
});
it('parses all', () => {
expect(instance.prepareData({ foo: ' foo ', bar: '123.45', baz: 1 })).toEqual({
foo: 'foo',
bar: 123.45,
baz: true,
});
});
it('passes through unknown fields', () => {
expect(
instance.prepareData({ foo: ' foo ', bar: '123.45', baz: 1, qux: [1, 2, 3] }),
).toEqual({ foo: 'foo', bar: 123.45, baz: true, qux: [1, 2, 3] });
});
});
describe('registerField()', () => {
it('registers a field in the form', () => {
const spy = jest.fn();
const func = () => {};
instance.form.registerField = spy;
instance.registerField(
{
name: 'foo',
isEqual: () => true,
validateFields: ['foo'],
subscriptions: ['dirty'],
validator() {},
},
func,
);
expect(spy).toHaveBeenCalledWith(
'foo',
func,
{ dirty: true },
expect.objectContaining({
validateFields: ['foo'],
}),
);
});
it('registers a field in the component', () => {
const spy = jest.fn();
const func = () => {};
instance.form.registerField = spy;
instance.registerField(
{
name: 'foo',
isEqual: () => true,
validateFields: ['foo'],
subscriptions: ['dirty'],
validator() {},
},
func,
);
expect(instance.registeredFields.foo).toBeDefined();
});
it('unregisters a field', () => {
const spy = jest.fn();
const func = () => {};
instance.form.registerField = () => spy;
const unregister = instance.registerField(
{
name: 'foo',
isEqual: () => true,
validateFields: ['foo'],
subscriptions: ['dirty'],
validator() {},
},
func,
);
expect(instance.registeredFields.foo).toBeDefined();
unregister();
expect(spy).toHaveBeenCalled();
expect(instance.registeredFields.foo).toBeUndefined();
});
it('calls a mutator for config', () => {
const spy = jest.fn();
instance.form.mutators.setFieldConfig = spy;
instance.registerField({ name: 'foo', validator() {} }, () => {});
expect(spy).toHaveBeenCalledWith('foo', expect.objectContaining({ name: 'foo' }));
});
it('only calls mutator once for consecutive registers', () => {
const spy = jest.spyOn(instance.form.mutators, 'setFieldConfig');
instance.registerField({ name: 'foo', validator() {} }, () => {});
instance.registerField({ name: 'foo', validator() {} }, () => {});
instance.registerField({ name: 'foo', validator() {} }, () => {});
expect(spy).toHaveBeenCalledTimes(1);
});
});
describe('setFieldConfig()', () => {
it('sets all the correct values', () => {
const config = {
name: 'foo',
defaultValue: '123',
validateDefaultValue: true,
validator() {},
};
const fields = { foo: { data: {} } };
const formState = { initialValues: {}, values: {} };
// @ts-ignore
instance.setFieldConfig(['foo', config], { fields, formState });
expect(fields).toEqual({
foo: {
data: { config },
initial: '123',
value: '123',
touched: true,
},
});
expect(formState).toEqual({
initialValues: {
foo: '123',
},
values: {
foo: '123',
},
});
});
it('initial value is ignored if a field already has a value', () => {
const config = {
name: 'foo',
validateDefaultValue: true,
validator() {},
};
const fields = { foo: { data: {} } };
const formState = { initialValues: { foo: '123' }, values: { foo: '456' } };
// @ts-ignore
instance.setFieldConfig(['foo', config], { fields, formState });
expect(fields).toEqual({
foo: {
data: { config },
initial: '123',
value: '456',
touched: true,
},
});
expect(formState).toEqual({
initialValues: {
foo: '123',
},
values: {
foo: '456',
},
});
});
});
describe('submitForm()', () => {
it('calls `submit` on the final-form instance', () => {
const spy = jest.spyOn(instance.form, 'submit');
instance.submitForm();
expect(spy).toHaveBeenCalled();
});
});
describe('validate()', () => {
it('returns empty object for unknown fields', async () => {
expect(await instance.validate({ foo: 123 })).toEqual({});
});
it('adds error to object if failed', async () => {
instance.registerField(
{
name: 'foo',
defaultValue: 'foo',
validator: () => {
throw new Error('Failed');
},
},
() => {},
);
expect(await instance.validate({ foo: 123 })).toEqual({ foo: 'Failed' });
});
it('doesnt add error to object if passes', async () => {
instance.registerField(
{
name: 'foo',
defaultValue: 'foo',
validator: () => {},
},
() => {},
);
expect(await instance.validate({ foo: 123 })).toEqual({});
});
it('doesnt add error to object if no validator', async () => {
instance.registerField(
{
name: 'foo',
defaultValue: 'foo',
validator() {},
},
() => {},
);
expect(await instance.validate({ foo: 123 })).toEqual({});
});
it('doesnt add error to object if field not in data', async () => {
instance.registerField(
{
name: 'foo',
defaultValue: 'foo',
validator: () => {
throw new Error('Failed');
},
},
() => {},
);
expect(await instance.validate({ bar: 123 })).toEqual({});
});
it('supports nested names', async () => {
instance.registerField(
{
name: 'foo[bar][baz]',
defaultValue: 'foo',
validator: () => {
throw new Error('Failed');
},
},
() => {},
);
expect(await instance.validate({ foo: { bar: { baz: 123 } } })).toEqual({
foo: { bar: { baz: 'Failed' } },
});
});
it('waits for async validators', async () => {
const spy = jest.fn();
instance.registerField(
{
name: 'foo',
defaultValue: 'foo',
validator: () => Promise.resolve(),
},
() => {},
);
const promise = instance
.validate({ foo: 123 })
.then(spy)
.then(() => {
expect(spy).toHaveBeenCalledWith({});
});
expect(spy).not.toHaveBeenCalled();
// eslint-disable-next-line jest/no-test-return-statement
return promise;
});
it('supports async rejections', async () => {
const spy = jest.fn();
const FAILED = 'FAILED';
instance.registerField(
{
name: 'foo',
defaultValue: 'foo',
validator: () => Promise.reject(new Error(FAILED)),
},
() => {},
);
const promise = instance
.validate({ foo: 123 })
.then(spy)
.then(() => {
expect(spy).toHaveBeenCalledWith({ foo: FAILED });
});
expect(spy).not.toHaveBeenCalled();
// eslint-disable-next-line jest/no-test-return-statement
return promise;
});
});
describe('wrapValidator()', () => {
it('wraps with a closure', async () => {
const func = instance.wrapValidator((value, data) => {
expect(value).toBeDefined();
expect(data).toBeDefined();
if (!value) {
throw new Error('Failure');
}
});
expect(typeof func).toBe('function');
// Returns undefined by default
expect(await func(123, {})).toBeUndefined();
// Throws an error if failed
expect(await func('', {})).toBe('Failure');
});
});
}); | the_stack |
import {
Component,
ViewEncapsulation,
ChangeDetectionStrategy,
AfterContentInit,
Input,
Output,
EventEmitter,
ViewChild,
ChangeDetectorRef,
Optional,
Inject
} from '@angular/core';
import {HcCalendarCellCssClasses, CalendarBodyComponent, HcCalendarCell} from '../calendar-body/calendar-body.component';
import {Directionality} from '@angular/cdk/bidi';
import {createMissingDateImplError} from '../datetime/datepicker-errors';
import {D, HC_DATE_FORMATS, HcDateFormats} from '../datetime/date-formats';
import {DateAdapter} from '../datetime/date-adapter';
const DAYS_PER_WEEK = 7;
/**
* An internal component used to display a single month in the datepicker.
* @docs-private
*/
@Component({
selector: 'hc-month-view',
templateUrl: './month-view.component.html',
exportAs: 'hcMonthView',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MonthViewComponent implements AfterContentInit {
/**
* The date to display in this month view (everything other than the month and year is ignored).
*/
@Input()
get activeDate(): D {
return this._activeDate;
}
set activeDate(value: D) {
const oldActiveDate = this._activeDate;
const validDate = this._getValidDateOrNull(this._dateAdapter.deserialize(value)) || this._dateAdapter.today();
this._activeDate = this._dateAdapter.clampDate(validDate, this.minDate, this.maxDate);
if (!this._hasSameMonthAndYear(oldActiveDate, this._activeDate)) {
this._init();
}
}
private _activeDate: D;
/** The currently selected date. */
@Input()
get selected(): D | null {
return this._selected;
}
set selected(value: D | null) {
this._selected = this._getValidDateOrNull(this._dateAdapter.deserialize(value));
this._selectedDate = this._getDateInCurrentMonth(this._selected);
}
private _selected: D | null;
/** The minimum selectable date. */
@Input()
get minDate(): D | null {
return this._minDate;
}
set minDate(value: D | null) {
this._minDate = this._getValidDateOrNull(this._dateAdapter.deserialize(value));
}
private _minDate: D | null;
/** The maximum selectable date. */
@Input()
get maxDate(): D | null {
return this._maxDate;
}
set maxDate(value: D | null) {
this._maxDate = this._getValidDateOrNull(this._dateAdapter.deserialize(value));
}
private _maxDate: D | null;
/** Function used to filter which dates are selectable. */
@Input()
dateFilter: (date: D) => boolean;
/** Function that can be used to add custom CSS classes to dates. */
@Input()
dateClass: (date: D) => HcCalendarCellCssClasses;
/** Emits when a new date is selected. */
@Output()
readonly selectedChange: EventEmitter<D | null> = new EventEmitter<D | null>();
/** Emits when any date is selected. */
@Output()
readonly _userSelection: EventEmitter<void> = new EventEmitter<void>();
/** Emits when any date is activated. */
@Output()
readonly activeDateChange: EventEmitter<D> = new EventEmitter<D>();
/** The body of calendar table */
@ViewChild(CalendarBodyComponent)
_hcCalendarBody: CalendarBodyComponent;
/** The label for this month (e.g. "January 2017"). */
_monthLabel: string;
/** Grid of calendar cells representing the dates of the month. */
_weeks: HcCalendarCell[][];
/** The number of blank cells in the first row before the 1st of the month. */
_firstWeekOffset: number;
/**
* The date of the month that the currently selected Date falls on.
* Null if the currently selected Date is in another month.
*/
_selectedDate: number | null;
/** The date of the month that today falls on. Null if today is in another month. */
_todayDate: number | null;
/** The names of the weekdays. */
_weekdays: {long: string; narrow: string}[];
constructor(
private _changeDetectorRef: ChangeDetectorRef,
@Optional()
@Inject(HC_DATE_FORMATS)
private _dateFormats: HcDateFormats,
@Optional() public _dateAdapter: DateAdapter<D>,
@Optional() private _dir?: Directionality
) {
if (!this._dateAdapter) {
throw createMissingDateImplError('DateAdapter');
}
if (!this._dateFormats) {
throw createMissingDateImplError('HC_DATE_FORMATS');
}
const firstDayOfWeek = this._dateAdapter.getFirstDayOfWeek();
const narrowWeekdays = this._dateAdapter.getDayOfWeekNames('short');
const longWeekdays = this._dateAdapter.getDayOfWeekNames('long');
// Rotate the labels for days of the week based on the configured first day of the week.
const weekdays = longWeekdays.map((long, i) => {
return {long, narrow: narrowWeekdays[i]};
});
this._weekdays = weekdays.slice(firstDayOfWeek).concat(weekdays.slice(0, firstDayOfWeek));
this._activeDate = this._dateAdapter.today();
}
ngAfterContentInit(): void {
this._init();
}
/** Handles when a new date is selected. */
_dateSelected(date: number): void {
if (this._selectedDate !== date) {
const selectedYear = this._dateAdapter.getYear(this.activeDate);
const selectedMonth = this._dateAdapter.getMonth(this.activeDate);
const selectedDate = this._dateAdapter.createDate(selectedYear, selectedMonth, date);
if (this._selected) {
selectedDate.setHours(this._selected.getHours());
selectedDate.setMinutes(this._selected.getMinutes());
}
this.selectedChange.emit(selectedDate);
}
this._userSelection.emit();
}
/** Handles keydown events on the calendar body when calendar is in month view. */
_handleCalendarBodyKeydown(event: KeyboardEvent): void {
// TODO(mmalerba): We currently allow keyboard navigation to disabled dates, but just prevent
// disabled ones from being selected. This may not be ideal, we should look into whether
// navigation should skip over disabled dates, and if so, how to implement that efficiently.
const oldActiveDate = this._activeDate;
const isRtl = this._isRtl();
switch (event.key) {
case 'ArrowLeft':
this.activeDate = this._dateAdapter.addCalendarDays(this._activeDate, isRtl ? 1 : -1);
break;
case 'ArrowRight':
this.activeDate = this._dateAdapter.addCalendarDays(this._activeDate, isRtl ? -1 : 1);
break;
case 'ArrowUp':
this.activeDate = this._dateAdapter.addCalendarDays(this._activeDate, -7);
break;
case 'ArrowDown':
this.activeDate = this._dateAdapter.addCalendarDays(this._activeDate, 7);
break;
case 'Home':
this.activeDate = this._dateAdapter.addCalendarDays(this._activeDate, 1 - this._dateAdapter.getDate(this._activeDate));
break;
case 'End':
this.activeDate = this._dateAdapter.addCalendarDays(
this._activeDate,
this._dateAdapter.getNumDaysInMonth(this._activeDate) - this._dateAdapter.getDate(this._activeDate)
);
break;
case 'PageUp':
this.activeDate = event.altKey
? this._dateAdapter.addCalendarYears(this._activeDate, -1)
: this._dateAdapter.addCalendarMonths(this._activeDate, -1);
break;
case 'PageDown':
this.activeDate = event.altKey
? this._dateAdapter.addCalendarYears(this._activeDate, 1)
: this._dateAdapter.addCalendarMonths(this._activeDate, 1);
break;
case 'Enter':
case ' ':
if (!this.dateFilter || this.dateFilter(this._activeDate)) {
this._dateSelected(this._dateAdapter.getDate(this._activeDate));
this._userSelection.emit();
// Prevent unexpected default actions such as form submission.
event.preventDefault();
}
return;
default:
// Don't prevent default or focus active cell on keys that we don't explicitly handle.
return;
}
if (this._dateAdapter.compareDate(oldActiveDate, this.activeDate)) {
this.activeDateChange.emit(this.activeDate);
}
this._focusActiveCell();
// Prevent unexpected default actions such as form submission.
event.preventDefault();
}
/** Initializes this month view. */
_init(): void {
this._selectedDate = this._getDateInCurrentMonth(this.selected);
this._todayDate = this._getDateInCurrentMonth(this._dateAdapter.today());
this._monthLabel = this._dateAdapter.getMonthNames('short')[this._dateAdapter.getMonth(this.activeDate)].toLocaleUpperCase();
const firstOfMonth = this._dateAdapter.createDate(
this._dateAdapter.getYear(this.activeDate),
this._dateAdapter.getMonth(this.activeDate),
1
);
this._firstWeekOffset =
(DAYS_PER_WEEK + this._dateAdapter.getDayOfWeek(firstOfMonth) - this._dateAdapter.getFirstDayOfWeek()) % DAYS_PER_WEEK;
this._createWeekCells();
this._changeDetectorRef.markForCheck();
}
/** Focuses the active cell after the microtask queue is empty. */
_focusActiveCell(): void {
this._hcCalendarBody._focusActiveCell();
}
/** Creates hcCalendarCells for the dates in this month. */
private _createWeekCells() {
const daysInMonth = this._dateAdapter.getNumDaysInMonth(this.activeDate);
const dateNames = this._dateAdapter.getDateNames();
this._weeks = [[]];
for (let i = 0, cell = this._firstWeekOffset; i < daysInMonth; i++, cell++) {
if (cell === DAYS_PER_WEEK) {
this._weeks.push([]);
cell = 0;
}
const date = this._dateAdapter.createDate(
this._dateAdapter.getYear(this.activeDate),
this._dateAdapter.getMonth(this.activeDate),
i + 1
);
const enabled = this._shouldEnableDate(date);
const ariaLabel = this._dateAdapter.format(date, this._dateFormats.display.dateA11yLabel);
const cellClasses = this.dateClass ? this.dateClass(date) : undefined;
this._weeks[this._weeks.length - 1].push(new HcCalendarCell(i + 1, dateNames[i], ariaLabel, enabled, cellClasses));
}
}
/** Date filter for the month */
private _shouldEnableDate(date: D): boolean {
return (
!!date &&
(!this.dateFilter || this.dateFilter(date)) &&
(!this.minDate || this._dateAdapter.compareDate(date, this.minDate) >= 0) &&
(!this.maxDate || this._dateAdapter.compareDate(date, this.maxDate) <= 0)
);
}
/**
* Gets the date in this month that the given Date falls on.
* Returns null if the given Date is in another month.
*/
private _getDateInCurrentMonth(date: D | null): number | null {
return date && this._hasSameMonthAndYear(date, this.activeDate) ? this._dateAdapter.getDate(date) : null;
}
/** Checks whether the 2 dates are non-null and fall within the same month of the same year. */
private _hasSameMonthAndYear(d1: D | null, d2: D | null): boolean {
return !!(
d1 &&
d2 &&
this._dateAdapter.getMonth(d1) === this._dateAdapter.getMonth(d2) &&
this._dateAdapter.getYear(d1) === this._dateAdapter.getYear(d2)
);
}
/**
* @param obj The object to check.
* @returns The given object if it is both a date instance and valid, otherwise null.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private _getValidDateOrNull(obj: any): D | null {
return this._dateAdapter.isDateInstance(obj) && this._dateAdapter.isValid(obj) ? obj : null;
}
/** Determines whether the user has the RTL layout direction. */
private _isRtl() {
return this._dir && this._dir.value === 'rtl';
}
} | the_stack |
import { Component, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { delay } from 'rxjs/operators';
import * as dateFns from 'date-fns';
import { Subject, Observable, of } from 'rxjs';
import {
IDataTableColumn,
RemoteDataTableService,
IDataTablePaginationOptions,
IDataTableSearchOptions,
NovoModalService,
IDataTablePreferences,
IDataTableFilter,
Helpers,
} from 'novo-elements';
import { ConfigureColumnsModal, MockData } from '../extras';
/**
* @title Remote Data Table Example
*/
@Component({
selector: 'data-table-remote-example',
templateUrl: 'data-table-remote-example.html',
styleUrls: ['data-table-remote-example.css'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DataTableRemoteExample {
// Table configuration
public dataSetOptions: any[] = [{ label: 'Dataset #1', value: 1 }, { label: 'Dataset #2', value: 2 }, { label: 'Dataset #3', value: 3 }];
public loadedDataSet: number = 1;
public paginationTypeOptions: any[] = [{ label: 'Standard', value: 'standard' }, { label: 'Basic', value: 'basic' }];
public loadedPaginationType: string = 'standard';
public globalSearchOptions: any[] = [{ label: 'Show', value: true }, { label: 'Hide', value: false }];
public loadedGlobalSearch: boolean = false;
// Shared configuration
public sharedColumns: IDataTableColumn<MockData>[] = [
{
id: 'preview',
type: 'action',
enabled: true,
handlers: {
click: this.log.bind(this),
},
action: {
icon: 'preview',
},
},
{
id: 'actions',
type: 'action',
label: 'Actions',
enabled: true,
action: {
options: [
{ label: 'Action 1', handlers: { click: this.log.bind(this) } },
{ label: 'Action 2', handlers: { click: this.log.bind(this) }, disabled: true },
{ label: 'Action 3', handlers: { click: this.log.bind(this) }, disabledFunc: this.checkDisabled.bind(this) },
],
},
},
{
id: 'id',
label: 'ID',
enabled: true,
type: 'text',
filterable: {
type: 'number',
},
sortable: true,
},
{
id: 'telephone',
label: 'Phone',
type: 'link:tel',
attributes: {
target: '_blank',
},
},
{
id: 'email',
label: 'Email',
type: 'link:mailto',
attributes: {
target: '_blank',
},
},
{
id: 'address',
label: 'Address',
type: 'text',
format: ['$city, $state', '$city', '$state'],
},
{
id: 'embeddedObj',
label: 'Embedded (hard)',
enabled: true,
format: ['$another.id', '$firstName $lastName'],
type: 'link',
handlers: {
click: this.log.bind(this),
},
filterable: true,
},
{
id: 'simpleEmbeddedObj',
label: 'Embedded (simple)',
enabled: true,
format: '$id',
type: 'text',
filterable: true,
sortable: true,
},
{
id: 'date',
label: 'Date',
enabled: true,
type: 'date',
filterable: {
type: 'date',
allowCustomRange: true,
},
sortable: true,
},
{
id: 'dateTime',
label: 'DateTime',
enabled: false,
type: 'datetime',
},
{
id: 'time',
label: 'Time',
enabled: false,
type: 'time',
},
{
id: 'money',
label: 'Money',
enabled: false,
type: 'currency',
filterable: true,
sortable: true,
},
{
id: 'percent',
label: 'Percent',
enabled: true,
type: 'percent',
filterable: true,
sortable: true,
},
{
id: 'name',
label: 'Name',
labelIcon: 'bull',
enabled: true,
type: 'text',
template: 'custom',
},
{
id: 'status',
label: 'Status',
enabled: true,
type: 'text',
filterable: true,
sortable: true,
},
{
id: 'priority',
label: 'Priority',
enabled: true,
type: 'text',
filterable: {
type: 'multi-select',
options: this.getPriorityOptions(),
},
sortable: true,
},
{
id: 'enabled',
label: 'Enabled',
enabled: true,
type: 'text',
sortable: true,
filterable: {
type: 'select',
options: [{ value: true, label: 'True' }, { value: false, label: 'False' }],
},
},
{
id: 'edit',
type: 'action',
enabled: true,
disabled: true,
handlers: {
click: this.log.bind(this),
},
action: {
icon: 'edit',
},
},
];
public sharedDisplayColumns = [
'selection',
'expand',
'preview',
'actions',
'id',
'date',
'name',
'telephone',
'email',
'simpleEmbeddedObj',
'status',
'priority',
'percent',
'embeddedObj',
'edit',
];
public sharedPaginationOptions: IDataTablePaginationOptions = {
theme: 'standard',
pageSize: 10,
pageSizeOptions: [10, 50, 100, 250, 500],
};
public widePaginationOptions: IDataTablePaginationOptions = {
theme: 'basic-wide',
pageSize: 10,
pageSizeOptions: [10, 50, 100, 250, 500],
};
public sharedSearchOptions: IDataTableSearchOptions = {
placeholder: 'Search for things...',
tooltip: 'HELLO',
};
public sharedDefaultSort: { id: string; value: string } = {
id: 'id',
value: 'asc',
};
public globalSearchEnabled: boolean = false;
public refreshSubject: Subject<boolean> = new Subject();
// Remote configuration
public remoteService: RemoteDataTableService<MockData>;
private staticDataSet1: MockData[] = [];
constructor(private ref: ChangeDetectorRef, private modalService: NovoModalService) {
for (let i = 0; i < 1000; i++) {
const day = i < 500 ? dateFns.subDays(new Date(), i) : dateFns.addDays(new Date(), i - 500);
this.staticDataSet1.push({
id: i,
embeddedObj: { id: i, test: `HMM ${i}`, another: { id: 777 } },
simpleEmbeddedObj: { id: i },
name: `(1) Name ${i}`,
status: `(1) Status ${i}`,
priority: this.getPriority(),
enabled: i % 2 === 0,
date: day,
dateTime: day,
time: day,
money: i + 10,
percent: i / 100,
telephone: '555-555-5555',
email: 'test@google.com',
address: { city: 'City', state: null },
});
}
this.remoteService = new RemoteMockDataService([...this.staticDataSet1.slice(0, 10)]);
}
public getPriority(): string {
const x = Math.round(Math.random() * 50);
return 'test ' + x.toString();
}
public getPriorityOptions() {
const options = new Array();
let i;
for (i = 0; i < 49; i++) {
options.push('test ' + i.toString());
}
return options;
}
public switchPaginationType(type: 'basic' | 'standard') {
this.sharedPaginationOptions = Object.assign({}, this.sharedPaginationOptions, { theme: type });
this.ref.detectChanges();
}
public toggleGlobalSearch(toggle: boolean): void {
this.globalSearchEnabled = toggle;
this.ref.detectChanges();
}
public log(event: { originalEvent: MouseEvent; row: MockData }): void {
console.log('[DataTable] Event Triggered!', event); // tslint:disable-line
}
public checkDisabled(row: MockData): boolean {
return true;
}
public configureColumns(): void {
this.modalService
.open(ConfigureColumnsModal, { columns: this.sharedColumns })
.onClosed.then((columns: IDataTableColumn<MockData>[]) => {
if (columns) {
const enabledColumns = columns.filter((column: IDataTableColumn<MockData>) => column.enabled);
this.sharedDisplayColumns = ['selection', 'expand', ...enabledColumns.map((column: IDataTableColumn<MockData>) => column.id)];
this.ref.markForCheck();
}
});
}
public onPreferencesChanged(event: IDataTablePreferences): void {
console.log('Preferences changed (persist manually):', event); // tslint:disable-line
}
public refresh(): void {
this.refreshSubject.next();
}
}
class RemoteMockDataService extends RemoteDataTableService<MockData> {
public url: string;
constructor(private data: MockData[]) {
super();
}
public getTableResults(
sort: { id: string; value: string; transform?: Function },
filter: IDataTableFilter | IDataTableFilter[],
page: number,
pageSize: number,
globalSearch?: string,
): Observable<{ results: MockData[]; total: number }> {
const whereQuery: string = this.buildWhereClause(filter);
const sortQuery: string = this.buildSortColumn(sort);
const pageQuery: number = this.buildStart(page, pageSize);
this.url = `http://mock-api.com?where=${whereQuery}&sort=${sortQuery}&pageSize=${pageSize}&page=${pageQuery}`;
return of({ results: this.data, total: this.data.length }).pipe(delay(5000));
}
private buildWhereClause(filter: IDataTableFilter | IDataTableFilter[]): string {
const query: any = {};
if (filter) {
const filters = Helpers.convertToArray(filter);
filters.forEach((aFilter) => {
query[aFilter.id] = aFilter.transform ? aFilter.transform(aFilter.value) : aFilter.value;
});
}
return this.toQuerySyntax(query);
}
private buildSortColumn(sort: { id: string; value: string; transform?: Function }): string {
if (sort) {
let value = sort.id;
if (sort.transform) {
value = sort.transform(value);
}
return sort.value === 'asc' ? value : `-${value}`;
}
return '';
}
private buildStart(page: number, pageSize: number): number {
return (page || 0) * pageSize;
}
private toQuerySyntax(data: any) {
const queries: Array<string> = [];
for (const key in data) {
const value = data[key];
if (key === 'or') {
queries.push(`(${this.toQuerySyntax(value).replace(/ AND /g, ' OR ')})`);
} else {
queries.push(this.parseQueryValue(key, value));
}
}
return queries.join(' AND ');
}
private parseQueryValue(key: string, value: any, isNot: boolean = false) {
const clauses: Array<string> = [],
IN = isNot ? ' NOT IN ' : ' IN ',
EQ = isNot ? '<>' : '=',
GT = isNot ? '<' : '>=',
LT = isNot ? '>=' : '<';
if (Array.isArray(value)) {
clauses.push(`${key}${IN}(${this.writeQueryValues(value)})`);
} else if (value instanceof Object) {
if (typeof value.isNull === 'boolean') {
const query: string = value.isNull ? 'IS NULL' : 'IS NOT NULL';
clauses.push(`${key} ${query}`);
}
if (value.min !== null && value.min !== undefined) {
clauses.push(`${key}${GT}${this.writeQueryValue(value.min)}`);
}
if (value.max !== null && value.max !== undefined) {
clauses.push(`${key}${LT}${this.writeQueryValue(value.max)}`);
}
if (value.any && Array.isArray(value.any)) {
clauses.push(`${key}${IN}(${this.writeQueryValues(value.any)})`);
}
if (value.all && Array.isArray(value.all)) {
clauses.push(`${key}${IN}(${this.writeQueryValues(value.all)})`);
}
if (value.not !== null && value.not !== undefined) {
clauses.push(this.parseQueryValue(key, value.not, true));
}
if (value.like !== null && value.like !== undefined) {
clauses.push(`${key} like '%${value.like}%'`);
}
if (value.lookup !== null && value.lookup !== undefined) {
const obj = {};
obj[key] = value.lookup;
clauses.push(this.toQuerySyntax(obj));
}
if (value.with !== null && value.with !== undefined) {
clauses.push(`${key} IS NOT EMPTY`);
}
if (value.without !== null && value.without !== undefined) {
clauses.push(`${key} IS EMPTY`);
}
if (value.or !== null && value.or !== undefined) {
const obj = {};
obj[key] = value.or;
clauses.push(this.toQuerySyntax(obj).replace('AND', 'OR'));
}
for (const subkey in value) {
if (['min', 'max', 'any', 'all', 'not', 'or', 'like', 'lookup', 'with', 'without', 'isNull'].indexOf(subkey) < 0) {
const subvalue = value[subkey];
clauses.push(this.parseQueryValue(`${key}.${subkey}`, subvalue));
}
}
} else {
clauses.push(`${key}${EQ}${this.writeQueryValue(value)}`);
}
return clauses.join(' AND ');
}
private writeQueryValues(values) {
if (typeof values[0] === 'number' || typeof values[0] === 'boolean') {
return `${values.join(',')}`;
} else {
return `'${values.join(`','`)}'`;
}
}
private writeQueryValue(value) {
if (value instanceof Date) {
return value.getTime();
} else if (typeof value === 'number' || typeof value === 'boolean') {
return `${value}`;
} else {
return `'${value.replace(/\*/g, '')}'`;
}
}
} | the_stack |
declare namespace WebAssembly {
interface Module {}
}
declare namespace Emscripten {
interface FileSystemType {}
type EnvironmentType = 'WEB' | 'NODE' | 'SHELL' | 'WORKER';
type JSType = 'number' | 'string' | 'array' | 'boolean';
type TypeCompatibleWithC = number | string | any[] | boolean;
type CIntType = 'i8' | 'i16' | 'i32' | 'i64';
type CFloatType = 'float' | 'double';
type CPointerType = 'i8*' | 'i16*' | 'i32*' | 'i64*' | 'float*' | 'double*' | '*';
type CType = CIntType | CFloatType | CPointerType;
type WebAssemblyImports = Array<{
name: string;
kind: string;
}>;
type WebAssemblyExports = Array<{
module: string;
name: string;
kind: string;
}>;
interface CCallOpts {
async?: boolean | undefined;
}
}
interface EmscriptenModule {
print(str: string): void;
printErr(str: string): void;
arguments: string[];
environment: Emscripten.EnvironmentType;
preInit: Array<{ (): void }>;
preRun: Array<{ (): void }>;
postRun: Array<{ (): void }>;
onAbort: { (what: any): void };
onRuntimeInitialized: { (): void };
preinitializedWebGLContext: WebGLRenderingContext;
noInitialRun: boolean;
noExitRuntime: boolean;
logReadFiles: boolean;
filePackagePrefixURL: string;
wasmBinary: ArrayBuffer;
destroy(object: object): void;
getPreloadedPackage(remotePackageName: string, remotePackageSize: number): ArrayBuffer;
instantiateWasm(
imports: Emscripten.WebAssemblyImports,
successCallback: (module: WebAssembly.Module) => void,
): Emscripten.WebAssemblyExports;
locateFile(url: string, scriptDirectory: string): string;
onCustomMessage(event: MessageEvent): void;
// USE_TYPED_ARRAYS == 1
HEAP: Int32Array;
IHEAP: Int32Array;
FHEAP: Float64Array;
// USE_TYPED_ARRAYS == 2
HEAP8: Int8Array;
HEAP16: Int16Array;
HEAP32: Int32Array;
HEAPU8: Uint8Array;
HEAPU16: Uint16Array;
HEAPU32: Uint32Array;
HEAPF32: Float32Array;
HEAPF64: Float64Array;
TOTAL_STACK: number;
TOTAL_MEMORY: number;
FAST_MEMORY: number;
addOnPreRun(cb: () => any): void;
addOnInit(cb: () => any): void;
addOnPreMain(cb: () => any): void;
addOnExit(cb: () => any): void;
addOnPostRun(cb: () => any): void;
preloadedImages: any;
preloadedAudios: any;
_malloc(size: number): number;
_free(ptr: number): void;
}
/**
* A factory function is generated when setting the `MODULARIZE` build option
* to `1` in your Emscripten build. It return a Promise that resolves to an
* initialized, ready-to-call `EmscriptenModule` instance.
*
* By default, the factory function will be named `Module`. It's recommended to
* use the `EXPORT_ES6` option, in which the factory function will be the
* default export. If used without `EXPORT_ES6`, the factory function will be a
* global variable. You can rename the variable using the `EXPORT_NAME` build
* option. It's left to you to declare any global variables as needed in your
* application's types.
* @param moduleOverrides Default properties for the initialized module.
*/
type EmscriptenModuleFactory<T extends EmscriptenModule = EmscriptenModule> = (
moduleOverrides?: Partial<T>,
) => Promise<T>;
declare namespace FS {
interface Lookup {
path: string;
node: FSNode;
}
interface FSStream {}
interface FSNode {}
interface ErrnoError {}
let ignorePermissions: boolean;
let trackingDelegate: any;
let tracking: any;
let genericErrors: any;
//
// paths
//
function lookupPath(path: string, opts: any): Lookup;
function getPath(node: FSNode): string;
//
// nodes
//
function isFile(mode: number): boolean;
function isDir(mode: number): boolean;
function isLink(mode: number): boolean;
function isChrdev(mode: number): boolean;
function isBlkdev(mode: number): boolean;
function isFIFO(mode: number): boolean;
function isSocket(mode: number): boolean;
//
// devices
//
function major(dev: number): number;
function minor(dev: number): number;
function makedev(ma: number, mi: number): number;
function registerDevice(dev: number, ops: any): void;
//
// core
//
function syncfs(populate: boolean, callback: (e: any) => any): void;
function syncfs(callback: (e: any) => any, populate?: boolean): void;
function mount(type: Emscripten.FileSystemType, opts: any, mountpoint: string): any;
function unmount(mountpoint: string): void;
function mkdir(path: string, mode?: number): any;
function mkdev(path: string, mode?: number, dev?: number): any;
function symlink(oldpath: string, newpath: string): any;
function rename(old_path: string, new_path: string): void;
function rmdir(path: string): void;
function readdir(path: string): any;
function unlink(path: string): void;
function readlink(path: string): string;
function stat(path: string, dontFollow?: boolean): any;
function lstat(path: string): any;
function chmod(path: string, mode: number, dontFollow?: boolean): void;
function lchmod(path: string, mode: number): void;
function fchmod(fd: number, mode: number): void;
function chown(path: string, uid: number, gid: number, dontFollow?: boolean): void;
function lchown(path: string, uid: number, gid: number): void;
function fchown(fd: number, uid: number, gid: number): void;
function truncate(path: string, len: number): void;
function ftruncate(fd: number, len: number): void;
function utime(path: string, atime: number, mtime: number): void;
function open(path: string, flags: string, mode?: number, fd_start?: number, fd_end?: number): FSStream;
function close(stream: FSStream): void;
function llseek(stream: FSStream, offset: number, whence: number): any;
function read(stream: FSStream, buffer: ArrayBufferView, offset: number, length: number, position?: number): number;
function write(
stream: FSStream,
buffer: ArrayBufferView,
offset: number,
length: number,
position?: number,
canOwn?: boolean,
): number;
function allocate(stream: FSStream, offset: number, length: number): void;
function mmap(
stream: FSStream,
buffer: ArrayBufferView,
offset: number,
length: number,
position: number,
prot: number,
flags: number,
): any;
function ioctl(stream: FSStream, cmd: any, arg: any): any;
function readFile(path: string, opts: { encoding: 'binary'; flags?: string | undefined }): Uint8Array;
function readFile(path: string, opts: { encoding: 'utf8'; flags?: string | undefined }): string;
function readFile(path: string, opts?: { flags?: string | undefined }): Uint8Array;
function writeFile(path: string, data: string | ArrayBufferView, opts?: { flags?: string | undefined }): void;
//
// module-level FS code
//
function cwd(): string;
function chdir(path: string): void;
function init(
input: null | (() => number | null),
output: null | ((c: number) => any),
error: null | ((c: number) => any),
): void;
function createLazyFile(
parent: string | FSNode,
name: string,
url: string,
canRead: boolean,
canWrite: boolean,
): FSNode;
function createPreloadedFile(
parent: string | FSNode,
name: string,
url: string,
canRead: boolean,
canWrite: boolean,
onload?: () => void,
onerror?: () => void,
dontCreateFile?: boolean,
canOwn?: boolean,
): void;
function createDataFile(
parent: string | FSNode,
name: string,
data: ArrayBufferView,
canRead: boolean,
canWrite: boolean,
canOwn: boolean,
): FSNode;
}
declare var MEMFS: Emscripten.FileSystemType;
declare var NODEFS: Emscripten.FileSystemType;
declare var IDBFS: Emscripten.FileSystemType;
// Below runtime function/variable declarations are exportable by
// -s EXTRA_EXPORTED_RUNTIME_METHODS. You can extend or merge
// EmscriptenModule interface to add runtime functions.
//
// For example, by using -s "EXTRA_EXPORTED_RUNTIME_METHODS=['ccall']"
// You can access ccall() via Module["ccall"]. In this case, you should
// extend EmscriptenModule to pass the compiler check like the following:
//
// interface YourOwnEmscriptenModule extends EmscriptenModule {
// ccall: typeof ccall;
// }
//
// See: https://emscripten.org/docs/getting_started/FAQ.html#why-do-i-get-typeerror-module-something-is-not-a-function
declare function ccall(
ident: string,
returnType: Emscripten.JSType | null,
argTypes: Emscripten.JSType[],
args: Emscripten.TypeCompatibleWithC[],
opts?: Emscripten.CCallOpts,
): any;
declare function cwrap(
ident: string,
returnType: Emscripten.JSType | null,
argTypes: Emscripten.JSType[],
opts?: Emscripten.CCallOpts,
): (...args: any[]) => any;
declare function setValue(ptr: number, value: any, type: Emscripten.CType, noSafe?: boolean): void;
declare function getValue(ptr: number, type: Emscripten.CType, noSafe?: boolean): number;
declare function allocate(
slab: number[] | ArrayBufferView | number,
types: Emscripten.CType | Emscripten.CType[],
allocator: number,
ptr?: number,
): number;
declare function stackAlloc(size: number): number;
declare function stackSave(): number;
declare function stackRestore(ptr: number): void;
declare function UTF8ToString(ptr: number, maxBytesToRead?: number): string;
declare function stringToUTF8(str: string, outPtr: number, maxBytesToRead?: number): void;
declare function lengthBytesUTF8(str: string): number;
declare function allocateUTF8(str: string): number;
declare function allocateUTF8OnStack(str: string): number;
declare function UTF16ToString(ptr: number): string;
declare function stringToUTF16(str: string, outPtr: number, maxBytesToRead?: number): void;
declare function lengthBytesUTF16(str: string): number;
declare function UTF32ToString(ptr: number): string;
declare function stringToUTF32(str: string, outPtr: number, maxBytesToRead?: number): void;
declare function lengthBytesUTF32(str: string): number;
declare function intArrayFromString(stringy: string, dontAddNull?: boolean, length?: number): number[];
declare function intArrayToString(array: number[]): string;
declare function writeStringToMemory(str: string, buffer: number, dontAddNull: boolean): void;
declare function writeArrayToMemory(array: number[], buffer: number): void;
declare function writeAsciiToMemory(str: string, buffer: number, dontAddNull: boolean): void;
declare function addRunDependency(id: any): void;
declare function removeRunDependency(id: any): void;
declare function addFunction(func: (...args: any[]) => any, signature?: string): number;
declare function removeFunction(funcPtr: number): void;
declare var ALLOC_NORMAL: number;
declare var ALLOC_STACK: number;
declare var ALLOC_STATIC: number;
declare var ALLOC_DYNAMIC: number;
declare var ALLOC_NONE: number; | the_stack |
import { PublicKey, AccountInfo } from "@solana/web3.js";
import BN from "bn.js";
import { deserializeUnchecked } from "borsh";
import { BinaryReader, BinaryWriter } from "borsh";
const base58: any = require("bs58");
// eslint-disable-next-line
export const METADATA_REPLACE = new RegExp("\u0000", "g");
export const EDITION_MARKER_BIT_SIZE = 248;
export const METADATA_PREFIX = "metadata";
export const EDITION = "edition";
export class LazyAccountInfoProxy<T> {
executable: boolean = false;
owner: StringPublicKey = "";
lamports: number = 0;
get data() {
return undefined as unknown as T;
}
}
export interface LazyAccountInfo {
executable: boolean;
owner: StringPublicKey;
lamports: number;
data: [string, string];
}
const PubKeysInternedMap = new Map<string, PublicKey>();
export const toPublicKey = (key: string | PublicKey) => {
if (typeof key !== "string") {
return key;
}
let result = PubKeysInternedMap.get(key);
if (!result) {
result = new PublicKey(key);
PubKeysInternedMap.set(key, result);
}
return result;
};
export interface PublicKeyStringAndAccount<T> {
pubkey: string;
account: AccountInfo<T>;
}
export const WRAPPED_SOL_MINT = new PublicKey(
"So11111111111111111111111111111111111111112"
);
export const TOKEN_PROGRAM_ID = new PublicKey(
"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
);
export const SPL_ASSOCIATED_TOKEN_ACCOUNT_PROGRAM_ID = new PublicKey(
"ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"
);
export const BPF_UPGRADE_LOADER_ID = new PublicKey(
"BPFLoaderUpgradeab1e11111111111111111111111"
);
export const MEMO_ID = new PublicKey(
"MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"
);
export const METADATA_PROGRAM_ID =
"metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s" as StringPublicKey;
export const VAULT_ID =
"vau1zxA2LbssAUEF7Gpw91zMM1LvXrvpzJtmZ58rPsn" as StringPublicKey;
export const AUCTION_ID =
"auctxRXPeJoc4817jDhf4HbjnhEcr1cCXenosMhK5R8" as StringPublicKey;
export const METAPLEX_ID =
"p1exdMJcjVao65QdewkaZRUnU6VPSXhus9n2GzWfh98" as StringPublicKey;
export const SYSTEM = new PublicKey("11111111111111111111111111111111");
export const getStoreID = async (storeOwnerAddress?: string) => {
if (!storeOwnerAddress) {
return undefined;
}
const programs = await findProgramAddress(
[
Buffer.from("metaplex"),
toPublicKey(METAPLEX_ID).toBuffer(),
toPublicKey(storeOwnerAddress).toBuffer(),
],
toPublicKey(METAPLEX_ID)
);
const storeAddress = programs[0];
return storeAddress;
};
export const setProgramIds = async (store?: string) => {
STORE = store ? toPublicKey(store) : undefined;
};
let STORE: PublicKey | undefined;
export const programIds = () => {
return {
token: TOKEN_PROGRAM_ID,
associatedToken: SPL_ASSOCIATED_TOKEN_ACCOUNT_PROGRAM_ID,
bpf_upgrade_loader: BPF_UPGRADE_LOADER_ID,
system: SYSTEM,
metadata: METADATA_PROGRAM_ID,
memo: MEMO_ID,
vault: VAULT_ID,
auction: AUCTION_ID,
metaplex: METAPLEX_ID,
store: STORE,
};
};
export const findProgramAddress = async (
seeds: (Buffer | Uint8Array)[],
programId: PublicKey
) => {
const key =
"pda-" +
seeds.reduce((agg, item) => agg + item.toString("hex"), "") +
programId.toString();
let cached = localStorage.getItem(key);
if (cached) {
const value = JSON.parse(cached);
return [value.key, parseInt(value.nonce)] as [string, number];
}
const result = await PublicKey.findProgramAddress(seeds, programId);
try {
localStorage.setItem(
key,
JSON.stringify({
key: result[0].toBase58(),
nonce: result[1],
})
);
} catch {
// ignore
}
return [result[0].toBase58(), result[1]] as [string, number];
};
export type StringPublicKey = string;
export enum MetadataKey {
Uninitialized = 0,
MetadataV1 = 4,
EditionV1 = 1,
MasterEditionV1 = 2,
MasterEditionV2 = 6,
EditionMarker = 7,
}
export async function getEdition(
tokenMint: StringPublicKey
): Promise<StringPublicKey> {
const PROGRAM_IDS = programIds();
return (
await findProgramAddress(
[
Buffer.from(METADATA_PREFIX),
toPublicKey(PROGRAM_IDS.metadata).toBuffer(),
toPublicKey(tokenMint).toBuffer(),
Buffer.from(EDITION),
],
toPublicKey(PROGRAM_IDS.metadata)
)
)[0];
}
class CreateMetadataArgs {
instruction: number = 0;
data: Data;
isMutable: boolean;
constructor(args: { data: Data; isMutable: boolean }) {
this.data = args.data;
this.isMutable = args.isMutable;
}
}
class UpdateMetadataArgs {
instruction: number = 1;
data: Data | null;
// Not used by this app, just required for instruction
updateAuthority: StringPublicKey | null;
primarySaleHappened: boolean | null;
constructor(args: {
data?: Data;
updateAuthority?: string;
primarySaleHappened: boolean | null;
}) {
this.data = args.data ? args.data : null;
this.updateAuthority = args.updateAuthority ? args.updateAuthority : null;
this.primarySaleHappened = args.primarySaleHappened;
}
}
export class Creator {
address: StringPublicKey;
verified: boolean;
share: number;
constructor(args: {
address: StringPublicKey;
verified: boolean;
share: number;
}) {
this.address = args.address;
this.verified = args.verified;
this.share = args.share;
}
}
export class Data {
name: string;
symbol: string;
uri: string;
sellerFeeBasisPoints: number;
creators: Creator[] | null;
constructor(args: {
name: string;
symbol: string;
uri: string;
sellerFeeBasisPoints: number;
creators: Creator[] | null;
}) {
this.name = args.name;
this.symbol = args.symbol;
this.uri = args.uri;
this.sellerFeeBasisPoints = args.sellerFeeBasisPoints;
this.creators = args.creators;
}
}
export class Metadata {
key: MetadataKey;
updateAuthority: StringPublicKey;
mint: StringPublicKey;
data: Data;
primarySaleHappened: boolean;
isMutable: boolean;
editionNonce: number | null;
// set lazy
masterEdition?: StringPublicKey;
edition?: StringPublicKey;
constructor(args: {
updateAuthority: StringPublicKey;
mint: StringPublicKey;
data: Data;
primarySaleHappened: boolean;
isMutable: boolean;
editionNonce: number | null;
}) {
this.key = MetadataKey.MetadataV1;
this.updateAuthority = args.updateAuthority;
this.mint = args.mint;
this.data = args.data;
this.primarySaleHappened = args.primarySaleHappened;
this.isMutable = args.isMutable;
this.editionNonce = args.editionNonce;
}
public async init() {
const edition = await getEdition(this.mint);
this.edition = edition;
this.masterEdition = edition;
}
}
export class Edition {
key: MetadataKey;
/// Points at MasterEdition struct
parent: StringPublicKey;
/// Starting at 0 for master record, this is incremented for each edition minted.
edition: BN;
constructor(args: {
key: MetadataKey;
parent: StringPublicKey;
edition: BN;
}) {
this.key = MetadataKey.EditionV1;
this.parent = args.parent;
this.edition = args.edition;
}
}
export class MasterEditionV1 {
key: MetadataKey;
supply: BN;
maxSupply?: BN;
/// Can be used to mint tokens that give one-time permission to mint a single limited edition.
printingMint: StringPublicKey;
/// If you don't know how many printing tokens you are going to need, but you do know
/// you are going to need some amount in the future, you can use a token from this mint.
/// Coming back to token metadata with one of these tokens allows you to mint (one time)
/// any number of printing tokens you want. This is used for instance by Auction Manager
/// with participation NFTs, where we dont know how many people will bid and need participation
/// printing tokens to redeem, so we give it ONE of these tokens to use after the auction is over,
/// because when the auction begins we just dont know how many printing tokens we will need,
/// but at the end we will. At the end it then burns this token with token-metadata to
/// get the printing tokens it needs to give to bidders. Each bidder then redeems a printing token
/// to get their limited editions.
oneTimePrintingAuthorizationMint: StringPublicKey;
constructor(args: {
key: MetadataKey;
supply: BN;
maxSupply?: BN;
printingMint: StringPublicKey;
oneTimePrintingAuthorizationMint: StringPublicKey;
}) {
this.key = MetadataKey.MasterEditionV1;
this.supply = args.supply;
this.maxSupply = args.maxSupply;
this.printingMint = args.printingMint;
this.oneTimePrintingAuthorizationMint =
args.oneTimePrintingAuthorizationMint;
}
}
export class MasterEditionV2 {
key: MetadataKey;
supply: BN;
maxSupply?: BN;
constructor(args: { key: MetadataKey; supply: BN; maxSupply?: BN }) {
this.key = MetadataKey.MasterEditionV2;
this.supply = args.supply;
this.maxSupply = args.maxSupply;
}
}
class CreateMasterEditionArgs {
instruction: number = 10;
maxSupply: BN | null;
constructor(args: { maxSupply: BN | null }) {
this.maxSupply = args.maxSupply;
}
}
class MintPrintingTokensArgs {
instruction: number = 9;
supply: BN;
constructor(args: { supply: BN }) {
this.supply = args.supply;
}
}
export class EditionMarker {
key: MetadataKey;
ledger: number[];
constructor(args: { key: MetadataKey; ledger: number[] }) {
this.key = MetadataKey.EditionMarker;
this.ledger = args.ledger;
}
editionTaken(edition: number) {
const editionOffset = edition % EDITION_MARKER_BIT_SIZE;
const indexOffset = Math.floor(editionOffset / 8);
if (indexOffset > 30) {
throw Error("bad index for edition");
}
const positionInBitsetFromRight = 7 - (editionOffset % 8);
const mask = Math.pow(2, positionInBitsetFromRight);
const appliedMask = this.ledger[indexOffset] & mask;
// eslint-disable-next-line
return appliedMask != 0;
}
}
export const METADATA_SCHEMA = new Map<any, any>([
[
CreateMetadataArgs,
{
kind: "struct",
fields: [
["instruction", "u8"],
["data", Data],
["isMutable", "u8"], // bool
],
},
],
[
UpdateMetadataArgs,
{
kind: "struct",
fields: [
["instruction", "u8"],
["data", { kind: "option", type: Data }],
["updateAuthority", { kind: "option", type: "pubkeyAsString" }],
["primarySaleHappened", { kind: "option", type: "u8" }],
],
},
],
[
CreateMasterEditionArgs,
{
kind: "struct",
fields: [
["instruction", "u8"],
["maxSupply", { kind: "option", type: "u64" }],
],
},
],
[
MintPrintingTokensArgs,
{
kind: "struct",
fields: [
["instruction", "u8"],
["supply", "u64"],
],
},
],
[
MasterEditionV1,
{
kind: "struct",
fields: [
["key", "u8"],
["supply", "u64"],
["maxSupply", { kind: "option", type: "u64" }],
["printingMint", "pubkeyAsString"],
["oneTimePrintingAuthorizationMint", "pubkeyAsString"],
],
},
],
[
MasterEditionV2,
{
kind: "struct",
fields: [
["key", "u8"],
["supply", "u64"],
["maxSupply", { kind: "option", type: "u64" }],
],
},
],
[
Edition,
{
kind: "struct",
fields: [
["key", "u8"],
["parent", "pubkeyAsString"],
["edition", "u64"],
],
},
],
[
Data,
{
kind: "struct",
fields: [
["name", "string"],
["symbol", "string"],
["uri", "string"],
["sellerFeeBasisPoints", "u16"],
["creators", { kind: "option", type: [Creator] }],
],
},
],
[
Creator,
{
kind: "struct",
fields: [
["address", "pubkeyAsString"],
["verified", "u8"],
["share", "u8"],
],
},
],
[
Metadata,
{
kind: "struct",
fields: [
["key", "u8"],
["updateAuthority", "pubkeyAsString"],
["mint", "pubkeyAsString"],
["data", Data],
["primarySaleHappened", "u8"], // bool
["isMutable", "u8"], // bool
],
},
],
[
EditionMarker,
{
kind: "struct",
fields: [
["key", "u8"],
["ledger", [31]],
],
},
],
]);
export const extendBorsh = () => {
(BinaryReader.prototype as any).readPubkey = function () {
const reader = this as unknown as BinaryReader;
const array = reader.readFixedArray(32);
return new PublicKey(array);
};
(BinaryWriter.prototype as any).writePubkey = function (value: PublicKey) {
const writer = this as unknown as BinaryWriter;
writer.writeFixedArray(value.toBuffer());
};
(BinaryReader.prototype as any).readPubkeyAsString = function () {
const reader = this as unknown as BinaryReader;
const array = reader.readFixedArray(32);
return base58.encode(array) as StringPublicKey;
};
(BinaryWriter.prototype as any).writePubkeyAsString = function (
value: StringPublicKey
) {
const writer = this as unknown as BinaryWriter;
writer.writeFixedArray(base58.decode(value));
};
};
extendBorsh();
export const decodeMetadata = (buffer: Buffer): Metadata => {
const metadata = deserializeUnchecked(
METADATA_SCHEMA,
Metadata,
buffer
) as Metadata;
metadata.data.name = metadata.data.name.replace(METADATA_REPLACE, "");
metadata.data.uri = metadata.data.uri.replace(METADATA_REPLACE, "");
metadata.data.symbol = metadata.data.symbol.replace(METADATA_REPLACE, "");
return metadata;
};
export const getMetadataAddress = async (
mintKey: string
): Promise<[PublicKey, number]> => {
const seeds = [
Buffer.from("metadata"),
new PublicKey(METADATA_PROGRAM_ID).toBuffer(),
new PublicKey(mintKey).toBuffer(),
];
return PublicKey.findProgramAddress(
seeds,
new PublicKey(METADATA_PROGRAM_ID)
);
}; | the_stack |
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, NgZone } from '@angular/core';
import { ProxyCmp, proxyOutputs } from './angular-component-lib/utils';
import { Components } from '@ionic/core';
export declare interface IonAccordion extends Components.IonAccordion {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['disabled', 'mode', 'readonly', 'toggleIcon', 'toggleIconSlot', 'value']
})
@Component({
selector: 'ion-accordion',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['disabled', 'mode', 'readonly', 'toggleIcon', 'toggleIconSlot', 'value']
})
export class IonAccordion {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
import type { AccordionGroupChangeEventDetail as IAccordionGroupAccordionGroupChangeEventDetail } from '@ionic/core';
export declare interface IonAccordionGroup extends Components.IonAccordionGroup {
/**
* Emitted when the value property has changed.
*/
ionChange: EventEmitter<CustomEvent<IAccordionGroupAccordionGroupChangeEventDetail>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['animated', 'disabled', 'expand', 'mode', 'multiple', 'readonly', 'value']
})
@Component({
selector: 'ion-accordion-group',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['animated', 'disabled', 'expand', 'mode', 'multiple', 'readonly', 'value']
})
export class IonAccordionGroup {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionChange']);
}
}
export declare interface IonApp extends Components.IonApp {}
@ProxyCmp({
defineCustomElementFn: undefined
})
@Component({
selector: 'ion-app',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>'
})
export class IonApp {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonAvatar extends Components.IonAvatar {}
@ProxyCmp({
defineCustomElementFn: undefined
})
@Component({
selector: 'ion-avatar',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>'
})
export class IonAvatar {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonBackButton extends Components.IonBackButton {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['color', 'defaultHref', 'disabled', 'icon', 'mode', 'routerAnimation', 'text', 'type']
})
@Component({
selector: 'ion-back-button',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['color', 'defaultHref', 'disabled', 'icon', 'mode', 'routerAnimation', 'text', 'type']
})
export class IonBackButton {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonBackdrop extends Components.IonBackdrop {
/**
* Emitted when the backdrop is tapped.
*/
ionBackdropTap: EventEmitter<CustomEvent<void>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['stopPropagation', 'tappable', 'visible']
})
@Component({
selector: 'ion-backdrop',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['stopPropagation', 'tappable', 'visible']
})
export class IonBackdrop {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionBackdropTap']);
}
}
export declare interface IonBadge extends Components.IonBadge {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['color', 'mode']
})
@Component({
selector: 'ion-badge',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['color', 'mode']
})
export class IonBadge {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonBreadcrumb extends Components.IonBreadcrumb {
/**
* Emitted when the breadcrumb has focus.
*/
ionFocus: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the breadcrumb loses focus.
*/
ionBlur: EventEmitter<CustomEvent<void>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['active', 'color', 'disabled', 'download', 'href', 'mode', 'rel', 'routerAnimation', 'routerDirection', 'separator', 'target']
})
@Component({
selector: 'ion-breadcrumb',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['active', 'color', 'disabled', 'download', 'href', 'mode', 'rel', 'routerAnimation', 'routerDirection', 'separator', 'target']
})
export class IonBreadcrumb {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionFocus', 'ionBlur']);
}
}
import type { BreadcrumbCollapsedClickEventDetail as IBreadcrumbsBreadcrumbCollapsedClickEventDetail } from '@ionic/core';
export declare interface IonBreadcrumbs extends Components.IonBreadcrumbs {
/**
* Emitted when the collapsed indicator is clicked on.
*/
ionCollapsedClick: EventEmitter<CustomEvent<IBreadcrumbsBreadcrumbCollapsedClickEventDetail>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['color', 'itemsAfterCollapse', 'itemsBeforeCollapse', 'maxItems', 'mode']
})
@Component({
selector: 'ion-breadcrumbs',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['color', 'itemsAfterCollapse', 'itemsBeforeCollapse', 'maxItems', 'mode']
})
export class IonBreadcrumbs {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionCollapsedClick']);
}
}
export declare interface IonButton extends Components.IonButton {
/**
* Emitted when the button has focus.
*/
ionFocus: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the button loses focus.
*/
ionBlur: EventEmitter<CustomEvent<void>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['buttonType', 'color', 'disabled', 'download', 'expand', 'fill', 'href', 'mode', 'rel', 'routerAnimation', 'routerDirection', 'shape', 'size', 'strong', 'target', 'type']
})
@Component({
selector: 'ion-button',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['buttonType', 'color', 'disabled', 'download', 'expand', 'fill', 'href', 'mode', 'rel', 'routerAnimation', 'routerDirection', 'shape', 'size', 'strong', 'target', 'type']
})
export class IonButton {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionFocus', 'ionBlur']);
}
}
export declare interface IonButtons extends Components.IonButtons {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['collapse']
})
@Component({
selector: 'ion-buttons',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['collapse']
})
export class IonButtons {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonCard extends Components.IonCard {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['button', 'color', 'disabled', 'download', 'href', 'mode', 'rel', 'routerAnimation', 'routerDirection', 'target', 'type']
})
@Component({
selector: 'ion-card',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['button', 'color', 'disabled', 'download', 'href', 'mode', 'rel', 'routerAnimation', 'routerDirection', 'target', 'type']
})
export class IonCard {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonCardContent extends Components.IonCardContent {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['mode']
})
@Component({
selector: 'ion-card-content',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['mode']
})
export class IonCardContent {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonCardHeader extends Components.IonCardHeader {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['color', 'mode', 'translucent']
})
@Component({
selector: 'ion-card-header',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['color', 'mode', 'translucent']
})
export class IonCardHeader {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonCardSubtitle extends Components.IonCardSubtitle {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['color', 'mode']
})
@Component({
selector: 'ion-card-subtitle',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['color', 'mode']
})
export class IonCardSubtitle {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonCardTitle extends Components.IonCardTitle {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['color', 'mode']
})
@Component({
selector: 'ion-card-title',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['color', 'mode']
})
export class IonCardTitle {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
import type { CheckboxChangeEventDetail as ICheckboxCheckboxChangeEventDetail } from '@ionic/core';
export declare interface IonCheckbox extends Components.IonCheckbox {
/**
* Emitted when the checked property has changed.
*/
ionChange: EventEmitter<CustomEvent<ICheckboxCheckboxChangeEventDetail>>;
/**
* Emitted when the checkbox has focus.
*/
ionFocus: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the checkbox loses focus.
*/
ionBlur: EventEmitter<CustomEvent<void>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['checked', 'color', 'disabled', 'indeterminate', 'mode', 'name', 'value']
})
@Component({
selector: 'ion-checkbox',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['checked', 'color', 'disabled', 'indeterminate', 'mode', 'name', 'value']
})
export class IonCheckbox {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionChange', 'ionFocus', 'ionBlur']);
}
}
export declare interface IonChip extends Components.IonChip {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['color', 'disabled', 'mode', 'outline']
})
@Component({
selector: 'ion-chip',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['color', 'disabled', 'mode', 'outline']
})
export class IonChip {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonCol extends Components.IonCol {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['offset', 'offsetLg', 'offsetMd', 'offsetSm', 'offsetXl', 'offsetXs', 'pull', 'pullLg', 'pullMd', 'pullSm', 'pullXl', 'pullXs', 'push', 'pushLg', 'pushMd', 'pushSm', 'pushXl', 'pushXs', 'size', 'sizeLg', 'sizeMd', 'sizeSm', 'sizeXl', 'sizeXs']
})
@Component({
selector: 'ion-col',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['offset', 'offsetLg', 'offsetMd', 'offsetSm', 'offsetXl', 'offsetXs', 'pull', 'pullLg', 'pullMd', 'pullSm', 'pullXl', 'pullXs', 'push', 'pushLg', 'pushMd', 'pushSm', 'pushXl', 'pushXs', 'size', 'sizeLg', 'sizeMd', 'sizeSm', 'sizeXl', 'sizeXs']
})
export class IonCol {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
import type { ScrollBaseDetail as IContentScrollBaseDetail } from '@ionic/core';
import type { ScrollDetail as IContentScrollDetail } from '@ionic/core';
export declare interface IonContent extends Components.IonContent {
/**
* Emitted when the scroll has started. This event is disabled by default.
Set `scrollEvents` to `true` to enable.
*/
ionScrollStart: EventEmitter<CustomEvent<IContentScrollBaseDetail>>;
/**
* Emitted while scrolling. This event is disabled by default.
Set `scrollEvents` to `true` to enable.
*/
ionScroll: EventEmitter<CustomEvent<IContentScrollDetail>>;
/**
* Emitted when the scroll has ended. This event is disabled by default.
Set `scrollEvents` to `true` to enable.
*/
ionScrollEnd: EventEmitter<CustomEvent<IContentScrollBaseDetail>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['color', 'forceOverscroll', 'fullscreen', 'scrollEvents', 'scrollX', 'scrollY'],
methods: ['getScrollElement', 'scrollToTop', 'scrollToBottom', 'scrollByPoint', 'scrollToPoint']
})
@Component({
selector: 'ion-content',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['color', 'forceOverscroll', 'fullscreen', 'scrollEvents', 'scrollX', 'scrollY']
})
export class IonContent {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionScrollStart', 'ionScroll', 'ionScrollEnd']);
}
}
import type { DatetimeChangeEventDetail as IDatetimeDatetimeChangeEventDetail } from '@ionic/core';
export declare interface IonDatetime extends Components.IonDatetime {
/**
* Emitted when the datetime selection was cancelled.
*/
ionCancel: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the value (selected date) has changed.
*/
ionChange: EventEmitter<CustomEvent<IDatetimeDatetimeChangeEventDetail>>;
/**
* Emitted when the datetime has focus.
*/
ionFocus: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the datetime loses focus.
*/
ionBlur: EventEmitter<CustomEvent<void>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['cancelText', 'clearText', 'color', 'dayValues', 'disabled', 'doneText', 'firstDayOfWeek', 'hourCycle', 'hourValues', 'isDateEnabled', 'locale', 'max', 'min', 'minuteValues', 'mode', 'monthValues', 'name', 'presentation', 'readonly', 'showClearButton', 'showDefaultButtons', 'showDefaultTimeLabel', 'showDefaultTitle', 'size', 'value', 'yearValues'],
methods: ['confirm', 'reset', 'cancel']
})
@Component({
selector: 'ion-datetime',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['cancelText', 'clearText', 'color', 'dayValues', 'disabled', 'doneText', 'firstDayOfWeek', 'hourCycle', 'hourValues', 'isDateEnabled', 'locale', 'max', 'min', 'minuteValues', 'mode', 'monthValues', 'name', 'presentation', 'readonly', 'showClearButton', 'showDefaultButtons', 'showDefaultTimeLabel', 'showDefaultTitle', 'size', 'value', 'yearValues']
})
export class IonDatetime {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionCancel', 'ionChange', 'ionFocus', 'ionBlur']);
}
}
export declare interface IonFab extends Components.IonFab {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['activated', 'edge', 'horizontal', 'vertical'],
methods: ['close']
})
@Component({
selector: 'ion-fab',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['activated', 'edge', 'horizontal', 'vertical']
})
export class IonFab {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonFabButton extends Components.IonFabButton {
/**
* Emitted when the button has focus.
*/
ionFocus: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the button loses focus.
*/
ionBlur: EventEmitter<CustomEvent<void>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['activated', 'closeIcon', 'color', 'disabled', 'download', 'href', 'mode', 'rel', 'routerAnimation', 'routerDirection', 'show', 'size', 'target', 'translucent', 'type']
})
@Component({
selector: 'ion-fab-button',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['activated', 'closeIcon', 'color', 'disabled', 'download', 'href', 'mode', 'rel', 'routerAnimation', 'routerDirection', 'show', 'size', 'target', 'translucent', 'type']
})
export class IonFabButton {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionFocus', 'ionBlur']);
}
}
export declare interface IonFabList extends Components.IonFabList {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['activated', 'side']
})
@Component({
selector: 'ion-fab-list',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['activated', 'side']
})
export class IonFabList {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonFooter extends Components.IonFooter {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['collapse', 'mode', 'translucent']
})
@Component({
selector: 'ion-footer',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['collapse', 'mode', 'translucent']
})
export class IonFooter {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonGrid extends Components.IonGrid {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['fixed']
})
@Component({
selector: 'ion-grid',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['fixed']
})
export class IonGrid {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonHeader extends Components.IonHeader {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['collapse', 'mode', 'translucent']
})
@Component({
selector: 'ion-header',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['collapse', 'mode', 'translucent']
})
export class IonHeader {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonIcon extends Components.IonIcon {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['color', 'flipRtl', 'icon', 'ios', 'lazy', 'md', 'mode', 'name', 'sanitize', 'size', 'src']
})
@Component({
selector: 'ion-icon',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['color', 'flipRtl', 'icon', 'ios', 'lazy', 'md', 'mode', 'name', 'sanitize', 'size', 'src']
})
export class IonIcon {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonImg extends Components.IonImg {
/**
* Emitted when the img src has been set
*/
ionImgWillLoad: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the image has finished loading
*/
ionImgDidLoad: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the img fails to load
*/
ionError: EventEmitter<CustomEvent<void>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['alt', 'src']
})
@Component({
selector: 'ion-img',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['alt', 'src']
})
export class IonImg {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionImgWillLoad', 'ionImgDidLoad', 'ionError']);
}
}
export declare interface IonInfiniteScroll extends Components.IonInfiniteScroll {
/**
* Emitted when the scroll reaches
the threshold distance. From within your infinite handler,
you must call the infinite scroll's `complete()` method when
your async operation has completed.
*/
ionInfinite: EventEmitter<CustomEvent<void>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['disabled', 'position', 'threshold'],
methods: ['complete']
})
@Component({
selector: 'ion-infinite-scroll',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['disabled', 'position', 'threshold']
})
export class IonInfiniteScroll {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionInfinite']);
}
}
export declare interface IonInfiniteScrollContent extends Components.IonInfiniteScrollContent {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['loadingSpinner', 'loadingText']
})
@Component({
selector: 'ion-infinite-scroll-content',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['loadingSpinner', 'loadingText']
})
export class IonInfiniteScrollContent {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
import type { InputChangeEventDetail as IInputInputChangeEventDetail } from '@ionic/core';
export declare interface IonInput extends Components.IonInput {
/**
* Emitted when a keyboard input occurred.
*/
ionInput: EventEmitter<CustomEvent<InputEvent>>;
/**
* Emitted when the value has changed.
*/
ionChange: EventEmitter<CustomEvent<IInputInputChangeEventDetail>>;
/**
* Emitted when the input loses focus.
*/
ionBlur: EventEmitter<CustomEvent<FocusEvent>>;
/**
* Emitted when the input has focus.
*/
ionFocus: EventEmitter<CustomEvent<FocusEvent>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['accept', 'autocapitalize', 'autocomplete', 'autocorrect', 'autofocus', 'clearInput', 'clearOnEdit', 'color', 'debounce', 'disabled', 'enterkeyhint', 'inputmode', 'max', 'maxlength', 'min', 'minlength', 'mode', 'multiple', 'name', 'pattern', 'placeholder', 'readonly', 'required', 'size', 'spellcheck', 'step', 'type', 'value'],
methods: ['setFocus', 'getInputElement']
})
@Component({
selector: 'ion-input',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['accept', 'autocapitalize', 'autocomplete', 'autocorrect', 'autofocus', 'clearInput', 'clearOnEdit', 'color', 'debounce', 'disabled', 'enterkeyhint', 'inputmode', 'max', 'maxlength', 'min', 'minlength', 'mode', 'multiple', 'name', 'pattern', 'placeholder', 'readonly', 'required', 'size', 'spellcheck', 'step', 'type', 'value']
})
export class IonInput {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionInput', 'ionChange', 'ionBlur', 'ionFocus']);
}
}
export declare interface IonItem extends Components.IonItem {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['button', 'color', 'counter', 'counterFormatter', 'detail', 'detailIcon', 'disabled', 'download', 'fill', 'href', 'lines', 'mode', 'rel', 'routerAnimation', 'routerDirection', 'shape', 'target', 'type']
})
@Component({
selector: 'ion-item',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['button', 'color', 'counter', 'counterFormatter', 'detail', 'detailIcon', 'disabled', 'download', 'fill', 'href', 'lines', 'mode', 'rel', 'routerAnimation', 'routerDirection', 'shape', 'target', 'type']
})
export class IonItem {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonItemDivider extends Components.IonItemDivider {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['color', 'mode', 'sticky']
})
@Component({
selector: 'ion-item-divider',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['color', 'mode', 'sticky']
})
export class IonItemDivider {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonItemGroup extends Components.IonItemGroup {}
@ProxyCmp({
defineCustomElementFn: undefined
})
@Component({
selector: 'ion-item-group',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>'
})
export class IonItemGroup {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonItemOption extends Components.IonItemOption {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['color', 'disabled', 'download', 'expandable', 'href', 'mode', 'rel', 'target', 'type']
})
@Component({
selector: 'ion-item-option',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['color', 'disabled', 'download', 'expandable', 'href', 'mode', 'rel', 'target', 'type']
})
export class IonItemOption {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonItemOptions extends Components.IonItemOptions {
/**
* Emitted when the item has been fully swiped.
*/
ionSwipe: EventEmitter<CustomEvent<any>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['side']
})
@Component({
selector: 'ion-item-options',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['side']
})
export class IonItemOptions {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionSwipe']);
}
}
export declare interface IonItemSliding extends Components.IonItemSliding {
/**
* Emitted when the sliding position changes.
*/
ionDrag: EventEmitter<CustomEvent<any>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['disabled'],
methods: ['getOpenAmount', 'getSlidingRatio', 'open', 'close', 'closeOpened']
})
@Component({
selector: 'ion-item-sliding',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['disabled']
})
export class IonItemSliding {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionDrag']);
}
}
export declare interface IonLabel extends Components.IonLabel {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['color', 'mode', 'position']
})
@Component({
selector: 'ion-label',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['color', 'mode', 'position']
})
export class IonLabel {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonList extends Components.IonList {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['inset', 'lines', 'mode'],
methods: ['closeSlidingItems']
})
@Component({
selector: 'ion-list',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['inset', 'lines', 'mode']
})
export class IonList {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonListHeader extends Components.IonListHeader {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['color', 'lines', 'mode']
})
@Component({
selector: 'ion-list-header',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['color', 'lines', 'mode']
})
export class IonListHeader {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonMenu extends Components.IonMenu {
/**
* Emitted when the menu is about to be opened.
*/
ionWillOpen: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the menu is about to be closed.
*/
ionWillClose: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the menu is open.
*/
ionDidOpen: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the menu is closed.
*/
ionDidClose: EventEmitter<CustomEvent<void>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['contentId', 'disabled', 'maxEdgeStart', 'menuId', 'side', 'swipeGesture', 'type'],
methods: ['isOpen', 'isActive', 'open', 'close', 'toggle', 'setOpen']
})
@Component({
selector: 'ion-menu',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['contentId', 'disabled', 'maxEdgeStart', 'menuId', 'side', 'swipeGesture', 'type']
})
export class IonMenu {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionWillOpen', 'ionWillClose', 'ionDidOpen', 'ionDidClose']);
}
}
export declare interface IonMenuButton extends Components.IonMenuButton {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['autoHide', 'color', 'disabled', 'menu', 'mode', 'type']
})
@Component({
selector: 'ion-menu-button',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['autoHide', 'color', 'disabled', 'menu', 'mode', 'type']
})
export class IonMenuButton {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonMenuToggle extends Components.IonMenuToggle {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['autoHide', 'menu']
})
@Component({
selector: 'ion-menu-toggle',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['autoHide', 'menu']
})
export class IonMenuToggle {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonNav extends Components.IonNav {
/**
* Event fired when the nav will change components
*/
ionNavWillChange: EventEmitter<CustomEvent<void>>;
/**
* Event fired when the nav has changed components
*/
ionNavDidChange: EventEmitter<CustomEvent<void>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['animated', 'animation', 'root', 'rootParams', 'swipeGesture'],
methods: ['push', 'insert', 'insertPages', 'pop', 'popTo', 'popToRoot', 'removeIndex', 'setRoot', 'setPages', 'getActive', 'getByIndex', 'canGoBack', 'getPrevious']
})
@Component({
selector: 'ion-nav',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['animated', 'animation', 'root', 'rootParams', 'swipeGesture']
})
export class IonNav {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionNavWillChange', 'ionNavDidChange']);
}
}
export declare interface IonNavLink extends Components.IonNavLink {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['component', 'componentProps', 'routerAnimation', 'routerDirection']
})
@Component({
selector: 'ion-nav-link',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['component', 'componentProps', 'routerAnimation', 'routerDirection']
})
export class IonNavLink {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonNote extends Components.IonNote {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['color', 'mode']
})
@Component({
selector: 'ion-note',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['color', 'mode']
})
export class IonNote {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonProgressBar extends Components.IonProgressBar {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['buffer', 'color', 'mode', 'reversed', 'type', 'value']
})
@Component({
selector: 'ion-progress-bar',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['buffer', 'color', 'mode', 'reversed', 'type', 'value']
})
export class IonProgressBar {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonRadio extends Components.IonRadio {
/**
* Emitted when the radio button has focus.
*/
ionFocus: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the radio button loses focus.
*/
ionBlur: EventEmitter<CustomEvent<void>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['color', 'disabled', 'mode', 'name', 'value']
})
@Component({
selector: 'ion-radio',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['color', 'disabled', 'mode', 'name', 'value']
})
export class IonRadio {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionFocus', 'ionBlur']);
}
}
import type { RadioGroupChangeEventDetail as IRadioGroupRadioGroupChangeEventDetail } from '@ionic/core';
export declare interface IonRadioGroup extends Components.IonRadioGroup {
/**
* Emitted when the value has changed.
*/
ionChange: EventEmitter<CustomEvent<IRadioGroupRadioGroupChangeEventDetail>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['allowEmptySelection', 'name', 'value']
})
@Component({
selector: 'ion-radio-group',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['allowEmptySelection', 'name', 'value']
})
export class IonRadioGroup {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionChange']);
}
}
import type { RangeChangeEventDetail as IRangeRangeChangeEventDetail } from '@ionic/core';
import type { RangeKnobMoveStartEventDetail as IRangeRangeKnobMoveStartEventDetail } from '@ionic/core';
import type { RangeKnobMoveEndEventDetail as IRangeRangeKnobMoveEndEventDetail } from '@ionic/core';
export declare interface IonRange extends Components.IonRange {
/**
* Emitted when the value property has changed.
*/
ionChange: EventEmitter<CustomEvent<IRangeRangeChangeEventDetail>>;
/**
* Emitted when the range has focus.
*/
ionFocus: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the range loses focus.
*/
ionBlur: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the user starts moving the range knob, whether through
mouse drag, touch gesture, or keyboard interaction.
*/
ionKnobMoveStart: EventEmitter<CustomEvent<IRangeRangeKnobMoveStartEventDetail>>;
/**
* Emitted when the user finishes moving the range knob, whether through
mouse drag, touch gesture, or keyboard interaction.
*/
ionKnobMoveEnd: EventEmitter<CustomEvent<IRangeRangeKnobMoveEndEventDetail>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['color', 'debounce', 'disabled', 'dualKnobs', 'max', 'min', 'mode', 'name', 'pin', 'pinFormatter', 'snaps', 'step', 'ticks', 'value']
})
@Component({
selector: 'ion-range',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['color', 'debounce', 'disabled', 'dualKnobs', 'max', 'min', 'mode', 'name', 'pin', 'pinFormatter', 'snaps', 'step', 'ticks', 'value']
})
export class IonRange {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionChange', 'ionFocus', 'ionBlur', 'ionKnobMoveStart', 'ionKnobMoveEnd']);
}
}
import type { RefresherEventDetail as IRefresherRefresherEventDetail } from '@ionic/core';
export declare interface IonRefresher extends Components.IonRefresher {
/**
* Emitted when the user lets go of the content and has pulled down
further than the `pullMin` or pulls the content down and exceeds the pullMax.
Updates the refresher state to `refreshing`. The `complete()` method should be
called when the async operation has completed.
*/
ionRefresh: EventEmitter<CustomEvent<IRefresherRefresherEventDetail>>;
/**
* Emitted while the user is pulling down the content and exposing the refresher.
*/
ionPull: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the user begins to start pulling down.
*/
ionStart: EventEmitter<CustomEvent<void>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['closeDuration', 'disabled', 'pullFactor', 'pullMax', 'pullMin', 'snapbackDuration'],
methods: ['complete', 'cancel', 'getProgress']
})
@Component({
selector: 'ion-refresher',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['closeDuration', 'disabled', 'pullFactor', 'pullMax', 'pullMin', 'snapbackDuration']
})
export class IonRefresher {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionRefresh', 'ionPull', 'ionStart']);
}
}
export declare interface IonRefresherContent extends Components.IonRefresherContent {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['pullingIcon', 'pullingText', 'refreshingSpinner', 'refreshingText']
})
@Component({
selector: 'ion-refresher-content',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['pullingIcon', 'pullingText', 'refreshingSpinner', 'refreshingText']
})
export class IonRefresherContent {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonReorder extends Components.IonReorder {}
@ProxyCmp({
defineCustomElementFn: undefined
})
@Component({
selector: 'ion-reorder',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>'
})
export class IonReorder {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
import type { ItemReorderEventDetail as IReorderGroupItemReorderEventDetail } from '@ionic/core';
export declare interface IonReorderGroup extends Components.IonReorderGroup {
/**
* Event that needs to be listened to in order to complete the reorder action.
Once the event has been emitted, the `complete()` method then needs
to be called in order to finalize the reorder action.
*/
ionItemReorder: EventEmitter<CustomEvent<IReorderGroupItemReorderEventDetail>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['disabled'],
methods: ['complete']
})
@Component({
selector: 'ion-reorder-group',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['disabled']
})
export class IonReorderGroup {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionItemReorder']);
}
}
export declare interface IonRippleEffect extends Components.IonRippleEffect {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['type'],
methods: ['addRipple']
})
@Component({
selector: 'ion-ripple-effect',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['type']
})
export class IonRippleEffect {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonRow extends Components.IonRow {}
@ProxyCmp({
defineCustomElementFn: undefined
})
@Component({
selector: 'ion-row',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>'
})
export class IonRow {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
import type { SearchbarChangeEventDetail as ISearchbarSearchbarChangeEventDetail } from '@ionic/core';
export declare interface IonSearchbar extends Components.IonSearchbar {
/**
* Emitted when a keyboard input occurred.
*/
ionInput: EventEmitter<CustomEvent<KeyboardEvent>>;
/**
* Emitted when the value has changed.
*/
ionChange: EventEmitter<CustomEvent<ISearchbarSearchbarChangeEventDetail>>;
/**
* Emitted when the cancel button is clicked.
*/
ionCancel: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the clear input button is clicked.
*/
ionClear: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the input loses focus.
*/
ionBlur: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the input has focus.
*/
ionFocus: EventEmitter<CustomEvent<void>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['animated', 'autocomplete', 'autocorrect', 'cancelButtonIcon', 'cancelButtonText', 'clearIcon', 'color', 'debounce', 'disabled', 'enterkeyhint', 'inputmode', 'mode', 'placeholder', 'searchIcon', 'showCancelButton', 'showClearButton', 'spellcheck', 'type', 'value'],
methods: ['setFocus', 'getInputElement']
})
@Component({
selector: 'ion-searchbar',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['animated', 'autocomplete', 'autocorrect', 'cancelButtonIcon', 'cancelButtonText', 'clearIcon', 'color', 'debounce', 'disabled', 'enterkeyhint', 'inputmode', 'mode', 'placeholder', 'searchIcon', 'showCancelButton', 'showClearButton', 'spellcheck', 'type', 'value']
})
export class IonSearchbar {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionInput', 'ionChange', 'ionCancel', 'ionClear', 'ionBlur', 'ionFocus']);
}
}
import type { SegmentChangeEventDetail as ISegmentSegmentChangeEventDetail } from '@ionic/core';
export declare interface IonSegment extends Components.IonSegment {
/**
* Emitted when the value property has changed and any
dragging pointer has been released from `ion-segment`.
*/
ionChange: EventEmitter<CustomEvent<ISegmentSegmentChangeEventDetail>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['color', 'disabled', 'mode', 'scrollable', 'selectOnFocus', 'swipeGesture', 'value']
})
@Component({
selector: 'ion-segment',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['color', 'disabled', 'mode', 'scrollable', 'selectOnFocus', 'swipeGesture', 'value']
})
export class IonSegment {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionChange']);
}
}
export declare interface IonSegmentButton extends Components.IonSegmentButton {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['disabled', 'layout', 'mode', 'type', 'value']
})
@Component({
selector: 'ion-segment-button',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['disabled', 'layout', 'mode', 'type', 'value']
})
export class IonSegmentButton {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
import type { SelectChangeEventDetail as ISelectSelectChangeEventDetail } from '@ionic/core';
export declare interface IonSelect extends Components.IonSelect {
/**
* Emitted when the value has changed.
*/
ionChange: EventEmitter<CustomEvent<ISelectSelectChangeEventDetail>>;
/**
* Emitted when the selection is cancelled.
*/
ionCancel: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the overlay is dismissed.
*/
ionDismiss: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the select has focus.
*/
ionFocus: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the select loses focus.
*/
ionBlur: EventEmitter<CustomEvent<void>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['cancelText', 'compareWith', 'disabled', 'interface', 'interfaceOptions', 'mode', 'multiple', 'name', 'okText', 'placeholder', 'selectedText', 'value'],
methods: ['open']
})
@Component({
selector: 'ion-select',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['cancelText', 'compareWith', 'disabled', 'interface', 'interfaceOptions', 'mode', 'multiple', 'name', 'okText', 'placeholder', 'selectedText', 'value']
})
export class IonSelect {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionChange', 'ionCancel', 'ionDismiss', 'ionFocus', 'ionBlur']);
}
}
export declare interface IonSelectOption extends Components.IonSelectOption {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['disabled', 'value']
})
@Component({
selector: 'ion-select-option',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['disabled', 'value']
})
export class IonSelectOption {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonSkeletonText extends Components.IonSkeletonText {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['animated']
})
@Component({
selector: 'ion-skeleton-text',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['animated']
})
export class IonSkeletonText {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonSlide extends Components.IonSlide {}
@ProxyCmp({
defineCustomElementFn: undefined
})
@Component({
selector: 'ion-slide',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>'
})
export class IonSlide {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonSlides extends Components.IonSlides {
/**
* Emitted after Swiper initialization
*/
ionSlidesDidLoad: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the user taps/clicks on the slide's container.
*/
ionSlideTap: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the user double taps on the slide's container.
*/
ionSlideDoubleTap: EventEmitter<CustomEvent<void>>;
/**
* Emitted before the active slide has changed.
*/
ionSlideWillChange: EventEmitter<CustomEvent<void>>;
/**
* Emitted after the active slide has changed.
*/
ionSlideDidChange: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the next slide has started.
*/
ionSlideNextStart: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the previous slide has started.
*/
ionSlidePrevStart: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the next slide has ended.
*/
ionSlideNextEnd: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the previous slide has ended.
*/
ionSlidePrevEnd: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the slide transition has started.
*/
ionSlideTransitionStart: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the slide transition has ended.
*/
ionSlideTransitionEnd: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the slider is actively being moved.
*/
ionSlideDrag: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the slider is at its initial position.
*/
ionSlideReachStart: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the slider is at the last slide.
*/
ionSlideReachEnd: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the user first touches the slider.
*/
ionSlideTouchStart: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the user releases the touch.
*/
ionSlideTouchEnd: EventEmitter<CustomEvent<void>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['mode', 'options', 'pager', 'scrollbar'],
methods: ['update', 'updateAutoHeight', 'slideTo', 'slideNext', 'slidePrev', 'getActiveIndex', 'getPreviousIndex', 'length', 'isEnd', 'isBeginning', 'startAutoplay', 'stopAutoplay', 'lockSwipeToNext', 'lockSwipeToPrev', 'lockSwipes', 'getSwiper']
})
@Component({
selector: 'ion-slides',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['mode', 'options', 'pager', 'scrollbar']
})
export class IonSlides {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionSlidesDidLoad', 'ionSlideTap', 'ionSlideDoubleTap', 'ionSlideWillChange', 'ionSlideDidChange', 'ionSlideNextStart', 'ionSlidePrevStart', 'ionSlideNextEnd', 'ionSlidePrevEnd', 'ionSlideTransitionStart', 'ionSlideTransitionEnd', 'ionSlideDrag', 'ionSlideReachStart', 'ionSlideReachEnd', 'ionSlideTouchStart', 'ionSlideTouchEnd']);
}
}
export declare interface IonSpinner extends Components.IonSpinner {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['color', 'duration', 'name', 'paused']
})
@Component({
selector: 'ion-spinner',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['color', 'duration', 'name', 'paused']
})
export class IonSpinner {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonSplitPane extends Components.IonSplitPane {
/**
* Expression to be called when the split-pane visibility has changed
*/
ionSplitPaneVisible: EventEmitter<CustomEvent<{ visible: boolean }>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['contentId', 'disabled', 'when']
})
@Component({
selector: 'ion-split-pane',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['contentId', 'disabled', 'when']
})
export class IonSplitPane {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionSplitPaneVisible']);
}
}
export declare interface IonTabBar extends Components.IonTabBar {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['color', 'mode', 'selectedTab', 'translucent']
})
@Component({
selector: 'ion-tab-bar',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['color', 'mode', 'selectedTab', 'translucent']
})
export class IonTabBar {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonTabButton extends Components.IonTabButton {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['disabled', 'download', 'href', 'layout', 'mode', 'rel', 'selected', 'tab', 'target']
})
@Component({
selector: 'ion-tab-button',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['disabled', 'download', 'href', 'layout', 'mode', 'rel', 'selected', 'tab', 'target']
})
export class IonTabButton {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonText extends Components.IonText {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['color', 'mode']
})
@Component({
selector: 'ion-text',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['color', 'mode']
})
export class IonText {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
import type { TextareaChangeEventDetail as ITextareaTextareaChangeEventDetail } from '@ionic/core';
export declare interface IonTextarea extends Components.IonTextarea {
/**
* Emitted when the input value has changed.
*/
ionChange: EventEmitter<CustomEvent<ITextareaTextareaChangeEventDetail>>;
/**
* Emitted when a keyboard input occurred.
*/
ionInput: EventEmitter<CustomEvent<InputEvent>>;
/**
* Emitted when the input loses focus.
*/
ionBlur: EventEmitter<CustomEvent<FocusEvent>>;
/**
* Emitted when the input has focus.
*/
ionFocus: EventEmitter<CustomEvent<FocusEvent>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['autoGrow', 'autocapitalize', 'autofocus', 'clearOnEdit', 'color', 'cols', 'debounce', 'disabled', 'enterkeyhint', 'inputmode', 'maxlength', 'minlength', 'mode', 'name', 'placeholder', 'readonly', 'required', 'rows', 'spellcheck', 'value', 'wrap'],
methods: ['setFocus', 'getInputElement']
})
@Component({
selector: 'ion-textarea',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['autoGrow', 'autocapitalize', 'autofocus', 'clearOnEdit', 'color', 'cols', 'debounce', 'disabled', 'enterkeyhint', 'inputmode', 'maxlength', 'minlength', 'mode', 'name', 'placeholder', 'readonly', 'required', 'rows', 'spellcheck', 'value', 'wrap']
})
export class IonTextarea {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionChange', 'ionInput', 'ionBlur', 'ionFocus']);
}
}
export declare interface IonThumbnail extends Components.IonThumbnail {}
@ProxyCmp({
defineCustomElementFn: undefined
})
@Component({
selector: 'ion-thumbnail',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>'
})
export class IonThumbnail {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
export declare interface IonTitle extends Components.IonTitle {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['color', 'size']
})
@Component({
selector: 'ion-title',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['color', 'size']
})
export class IonTitle {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
}
import type { ToggleChangeEventDetail as IToggleToggleChangeEventDetail } from '@ionic/core';
export declare interface IonToggle extends Components.IonToggle {
/**
* Emitted when the value property has changed.
*/
ionChange: EventEmitter<CustomEvent<IToggleToggleChangeEventDetail>>;
/**
* Emitted when the toggle has focus.
*/
ionFocus: EventEmitter<CustomEvent<void>>;
/**
* Emitted when the toggle loses focus.
*/
ionBlur: EventEmitter<CustomEvent<void>>;
}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['checked', 'color', 'disabled', 'mode', 'name', 'value']
})
@Component({
selector: 'ion-toggle',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['checked', 'color', 'disabled', 'mode', 'name', 'value']
})
export class IonToggle {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
proxyOutputs(this, this.el, ['ionChange', 'ionFocus', 'ionBlur']);
}
}
export declare interface IonToolbar extends Components.IonToolbar {}
@ProxyCmp({
defineCustomElementFn: undefined,
inputs: ['color', 'mode']
})
@Component({
selector: 'ion-toolbar',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content></ng-content>',
inputs: ['color', 'mode']
})
export class IonToolbar {
protected el: HTMLElement;
constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
c.detach();
this.el = r.nativeElement;
}
} | the_stack |
import { Component, OnInit, OnDestroy, ViewChild, ElementRef } from '@angular/core';
import { FormControl, FormGroup, FormBuilder } from '@angular/forms';
import { CoreError } from '@classes/errors/error';
import { CoreCourse } from '@features/course/services/course';
import { CanLeave } from '@guards/can-leave';
import { CoreNavigator } from '@services/navigator';
import { CoreSites, CoreSitesReadingStrategy } from '@services/sites';
import { CoreSync } from '@services/sync';
import { CoreDomUtils } from '@services/utils/dom';
import { CoreTextUtils } from '@services/utils/text';
import { CoreUtils } from '@services/utils/utils';
import { CoreWSFile } from '@services/ws';
import { Translate } from '@singletons';
import { CoreEvents } from '@singletons/events';
import { CoreForms } from '@singletons/form';
import { AddonModWiki, AddonModWikiProvider } from '../../services/wiki';
import { AddonModWikiOffline } from '../../services/wiki-offline';
import { AddonModWikiSync } from '../../services/wiki-sync';
/**
* Page that allows adding or editing a wiki page.
*/
@Component({
selector: 'page-addon-mod-wiki-edit',
templateUrl: 'edit.html',
})
export class AddonModWikiEditPage implements OnInit, OnDestroy, CanLeave {
@ViewChild('editPageForm') formElement?: ElementRef;
cmId?: number; // Course module ID.
courseId?: number; // Course the wiki belongs to.
title?: string; // Title to display.
pageForm?: FormGroup; // The form group.
contentControl?: FormControl; // The FormControl for the page content.
canEditTitle = false; // Whether title can be edited.
loaded = false; // Whether the data has been loaded.
component = AddonModWikiProvider.COMPONENT; // Component to link the files to.
wrongVersionLock = false; // Whether the page lock doesn't match the initial one.
editorExtraParams: Record<string, unknown> = {};
protected subwikiId?: number; // Subwiki ID the page belongs to.
protected wikiId?: number; // Wiki ID the page belongs to.
protected pageId?: number; // The page ID (if editing a page).
protected section?: string; // The section being edited.
protected groupId?: number; // The group the subwiki belongs to.
protected userId?: number; // The user the subwiki belongs to.
protected blockId?: string; // ID to block the subwiki.
protected editing = false; // Whether the user is editing a page (true) or creating a new one (false).
protected editOffline = false; // Whether the user is editing an offline page.
protected subwikiFiles: CoreWSFile[] = []; // List of files of the subwiki.
protected originalContent?: string; // The original page content.
protected version?: number; // Page version.
protected renewLockInterval?: number; // An interval to renew the lock every certain time.
protected forceLeave = false; // To allow leaving the page without checking for changes.
protected isDestroyed = false; // Whether the page has been destroyed.
constructor(
protected formBuilder: FormBuilder,
) { }
/**
* @inheritdoc
*/
async ngOnInit(): Promise<void> {
this.cmId = CoreNavigator.getRouteNumberParam('cmId') || undefined;
this.courseId = CoreNavigator.getRouteNumberParam('courseId') || undefined;
this.subwikiId = CoreNavigator.getRouteNumberParam('subwikiId');
this.wikiId = CoreNavigator.getRouteNumberParam('wikiId');
this.pageId = CoreNavigator.getRouteNumberParam('pageId');
this.section = CoreNavigator.getRouteParam('section');
this.groupId = CoreNavigator.getRouteNumberParam('groupId');
this.userId = CoreNavigator.getRouteNumberParam('userId');
let pageTitle = CoreNavigator.getRouteParam<string>('pageTitle');
pageTitle = pageTitle ? pageTitle.replace(/\+/g, ' ') : '';
this.canEditTitle = !pageTitle;
this.title = pageTitle ?
Translate.instant('addon.mod_wiki.editingpage', { $a: pageTitle }) :
Translate.instant('addon.mod_wiki.newpagehdr');
this.blockId = AddonModWikiSync.getSubwikiBlockId(this.subwikiId, this.wikiId, this.userId, this.groupId);
// Create the form group and its controls.
this.contentControl = this.formBuilder.control('');
this.pageForm = this.formBuilder.group({
title: pageTitle,
});
this.pageForm.addControl('text', this.contentControl);
// Block the wiki so it cannot be synced.
CoreSync.blockOperation(this.component, this.blockId);
if (this.pageId) {
this.editorExtraParams.pageid = this.pageId;
if (this.section) {
this.editorExtraParams.section = this.section;
}
} else if (pageTitle) {
this.editorExtraParams.pagetitle = pageTitle;
}
try {
const success = await this.fetchWikiPageData();
if (success && !this.isDestroyed) {
// Block the subwiki now that we have blockId for sure.
const newBlockId = AddonModWikiSync.getSubwikiBlockId(this.subwikiId, this.wikiId, this.userId, this.groupId);
if (newBlockId != this.blockId) {
CoreSync.unblockOperation(this.component, this.blockId);
this.blockId = newBlockId;
CoreSync.blockOperation(this.component, this.blockId);
}
}
} finally {
this.loaded = true;
}
}
/**
* Convenience function to get wiki page data.
*
* @return Promise resolved with boolean: whether it was successful.
*/
protected async fetchWikiPageData(): Promise<boolean> {
let canEdit = false;
let fetchFailed = false;
try {
// Wait for sync to be over (if any).
const syncResult = await AddonModWikiSync.waitForSync(this.blockId!);
if (this.pageId) {
// Editing a page that already exists.
this.canEditTitle = false;
this.editing = true;
this.editOffline = false; // Cannot edit pages in offline.
// Get page contents to obtain title and editing permission
const pageContents = await AddonModWiki.getPageContents(this.pageId, { cmId: this.cmId });
this.pageForm!.controls.title.setValue(pageContents.title); // Set the title in the form group.
this.wikiId = pageContents.wikiid;
this.subwikiId = pageContents.subwikiid;
this.title = Translate.instant('addon.mod_wiki.editingpage', { $a: pageContents.title });
this.groupId = pageContents.groupid;
this.userId = pageContents.userid;
canEdit = pageContents.caneditpage;
await this.fetchModuleAndCourseId();
// Get subwiki files, needed to replace URLs for rich text editor.
this.subwikiFiles = await AddonModWiki.getSubwikiFiles(this.wikiId, {
groupId: this.groupId,
userId: this.userId,
cmId: this.cmId,
});
// Get editable text of the page/section.
const editContents = await AddonModWiki.getPageForEditing(this.pageId, this.section);
// Get the original page contents, treating file URLs if needed.
const content = CoreTextUtils.replacePluginfileUrls(editContents.content || '', this.subwikiFiles);
this.contentControl!.setValue(content);
this.originalContent = content;
this.version = editContents.version;
if (canEdit) {
// Renew the lock every certain time.
this.renewLockInterval = window.setInterval(() => {
this.renewLock();
}, AddonModWikiProvider.RENEW_LOCK_TIME);
}
} else {
const pageTitle = this.pageForm!.controls.title.value;
this.editing = false;
canEdit = !!this.blockId; // If no blockId, the user cannot edit the page.
await this.fetchModuleAndCourseId();
// Try to get wikiId.
if (!this.wikiId && this.cmId && this.courseId) {
const module = await CoreCourse.getModule(this.cmId, this.courseId, undefined, true);
this.wikiId = module.instance;
}
if (pageTitle) {
// Title is set, it could be editing an offline page or creating a new page using an edit link.
// First of all, verify if this page was created in the current sync.
if (syncResult) {
const page = syncResult.created.find((page) => page.title == pageTitle);
if (page && page.pageId > 0) {
// Page was created, now it exists in the site.
this.pageId = page.pageId;
return this.fetchWikiPageData();
}
}
// Check if there's already some offline data for this page.
const page = await CoreUtils.ignoreErrors(
AddonModWikiOffline.getNewPage(pageTitle, this.subwikiId, this.wikiId, this.userId, this.groupId),
);
if (page) {
// Load offline content.
this.contentControl!.setValue(page.cachedcontent);
this.originalContent = page.cachedcontent;
this.editOffline = true;
} else {
// No offline data found.
this.editOffline = false;
}
} else {
this.editOffline = false;
}
}
return true;
} catch (error) {
CoreDomUtils.showErrorModalDefault(error, 'Error getting wiki data.');
fetchFailed = true;
// Go back.
this.forceLeavePage();
return false;
} finally {
if (!canEdit && !fetchFailed) {
// Cannot edit, show alert and go back.
CoreDomUtils.showAlert(Translate.instant('core.notice'), Translate.instant('addon.mod_wiki.cannoteditpage'));
this.forceLeavePage();
}
}
}
/**
* Load cmId and courseId if they aren't set.
*
* @return Promise.
*/
protected async fetchModuleAndCourseId(): Promise<void> {
if (!this.wikiId || (this.cmId && this.courseId)) {
return;
}
const module = await CoreCourse.getModuleBasicInfoByInstance(
this.wikiId,
'wiki',
{ readingStrategy: CoreSitesReadingStrategy.PREFER_CACHE },
);
this.cmId = module.id;
this.courseId = module.course;
}
/**
* Force leaving the page, without checking for changes.
*/
protected forceLeavePage(): void {
this.forceLeave = true;
CoreNavigator.back();
}
/**
* Navigate to a page.
*
* @param title Page title.
*/
protected goToPage(title: string): void {
// Not the firstpage.
AddonModWiki.setEditedPageData({
cmId: this.cmId,
courseId: this.courseId,
pageId: this.pageId,
pageTitle: title,
wikiId: this.wikiId!,
subwikiId: this.subwikiId,
userId: this.userId,
groupId: this.groupId,
});
this.forceLeavePage();
}
/**
* Check if data has changed.
*
* @return Whether data has changed.
*/
protected hasDataChanged(): boolean {
const values = this.pageForm!.value;
return !(this.originalContent == values.text || (!this.editing && !values.text && !values.title));
}
/**
* @inheritdoc
*/
async canLeave(): Promise<boolean> {
if (this.forceLeave) {
return true;
}
// Check if data has changed.
if (this.hasDataChanged()) {
await CoreDomUtils.showConfirm(Translate.instant('core.confirmcanceledit'));
}
CoreForms.triggerFormCancelledEvent(this.formElement, CoreSites.getCurrentSiteId());
return true;
}
/**
* @inheritdoc
*/
ionViewDidLeave(): void {
// When going back, the ionViewDidEnter of the previous page should be called before this ionViewDidLeave.
// But just in case, use a timeout to make sure it does.
setTimeout(() => {
// Remove the edited page data (if any) if the previous page isn't a wiki page.
AddonModWiki.consumeEditedPageData();
}, 200);
}
/**
* Save the data.
*/
async save(): Promise<void> {
const values = this.pageForm!.value;
const title = values.title;
let text = values.text;
const modal = await CoreDomUtils.showModalLoading('core.sending', true);
text = CoreTextUtils.restorePluginfileUrls(text, this.subwikiFiles);
text = CoreTextUtils.formatHtmlLines(text);
try {
if (this.editing) {
// Edit existing page.
await AddonModWiki.editPage(this.pageId!, text, this.section);
CoreForms.triggerFormSubmittedEvent(this.formElement, true, CoreSites.getCurrentSiteId());
// Invalidate page since it changed.
await AddonModWiki.invalidatePage(this.pageId!);
return this.goToPage(title);
}
// Creating a new page.
if (!title) {
// Title is mandatory, stop.
modal.dismiss();
CoreDomUtils.showAlert(
Translate.instant('core.notice'),
Translate.instant('addon.mod_wiki.titleshouldnotbeempty'),
);
return;
}
if (!this.editOffline) {
// Check if the user has an offline page with the same title.
const page = await CoreUtils.ignoreErrors(
AddonModWikiOffline.getNewPage(title, this.subwikiId, this.wikiId, this.userId, this.groupId),
);
if (page) {
// There's a page with same title, reject with error message.
throw new CoreError(Translate.instant('addon.mod_wiki.pageexists'));
}
}
// Try to send the page.
const id = await AddonModWiki.newPage(title, text, {
subwikiId: this.subwikiId,
wikiId: this.wikiId,
userId: this.userId,
groupId: this.groupId,
cmId: this.cmId,
});
CoreForms.triggerFormSubmittedEvent(this.formElement, id > 0, CoreSites.getCurrentSiteId());
if (id <= 0) {
// Page stored in offline. Go to see the offline page.
return this.goToPage(title);
}
// Page was created, get its data and go to the page.
CoreEvents.trigger(CoreEvents.ACTIVITY_DATA_SENT, { module: 'wiki' });
this.pageId = id;
const pageContents = await AddonModWiki.getPageContents(this.pageId, { cmId: this.cmId });
const promises: Promise<unknown>[] = [];
this.wikiId = pageContents.wikiid;
// Invalidate subwiki pages since there are new.
promises.push(AddonModWiki.invalidateSubwikiPages(this.wikiId));
if (!this.subwikiId) {
// Subwiki was not created, invalidate subwikis as well.
promises.push(AddonModWiki.invalidateSubwikis(this.wikiId));
}
this.subwikiId = pageContents.subwikiid;
this.userId = pageContents.userid;
this.groupId = pageContents.groupid;
await CoreUtils.ignoreErrors(Promise.all(promises));
// Notify page created.
CoreEvents.trigger(AddonModWikiProvider.PAGE_CREATED_EVENT, {
pageId: this.pageId,
subwikiId: this.subwikiId,
pageTitle: title,
}, CoreSites.getCurrentSiteId());
this.goToPage(title);
} catch (error) {
CoreDomUtils.showErrorModalDefault(error, 'Error saving wiki data.');
} finally {
modal.dismiss();
}
}
/**
* Renew lock and control versions.
*/
protected async renewLock(): Promise<void> {
const response = await AddonModWiki.getPageForEditing(this.pageId!, this.section, true);
if (response.version && this.version != response.version) {
this.wrongVersionLock = true;
}
}
/**
* @inheritdoc
*/
ngOnDestroy(): void {
this.isDestroyed = true;
clearInterval(this.renewLockInterval);
// Unblock the subwiki.
if (this.blockId) {
CoreSync.unblockOperation(this.component, this.blockId);
}
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.