type
stringclasses 7
values | content
stringlengths 4
9.55k
| repo
stringlengths 7
96
| path
stringlengths 4
178
| language
stringclasses 1
value |
---|---|---|---|---|
FunctionDeclaration |
function constructOrphanErrors() {
const orphanedErrors = new Set();
// Error messages that are already displayed in a field should not be
// displayed in the common area - orphan errors.
const usedMessages = new Set();
Object.values(usedErrors).forEach((errs: IErrorObj[]) => {
errs.forEach((error) => {
usedMessages.add(error.msg);
});
});
if (errors) {
Object.keys(errors).forEach((propName) => {
if (propName === 'orphanErrors') {
errors.orphanErrors.forEach((orphanError: IErrorObj) => {
// Making use the error msg has not been displayed contextually
// elsewhere.
if (!usedMessages.has(orphanError.msg)) {
orphanedErrors.add(orphanError.msg);
}
});
}
// If the error is not used and if the message is not used,
// add it to orphan errors.
else if (!usedErrors.hasOwnProperty(propName)) {
errors[propName].forEach((error: IErrorObj) => {
if (!usedMessages.has(error.msg)) {
// If any error is not displayed contextually, and the error message
// is not used by any other field, mark the error as orphan.
orphanedErrors.add(error.msg);
}
});
}
});
}
return Array.from(orphanedErrors);
} | hsiaoching/cdap | cdap-ui/app/cdap/components/ConfigurationGroup/index.tsx | TypeScript |
FunctionDeclaration |
function ConfigurationGroup(props) {
return (
<ThemeWrapper>
<StyledConfigurationGroup {...props} />
</ThemeWrapper>
);
} | hsiaoching/cdap | cdap-ui/app/cdap/components/ConfigurationGroup/index.tsx | TypeScript |
ArrowFunction |
(theme): StyleRules => {
return {
group: {
marginBottom: '20px',
},
groupTitle: {
marginBottom: '15px',
},
h2Title: {
...h2Styles(theme),
marginBottom: 0,
},
groupSubTitle: {
color: theme.palette.grey[200],
},
};
} | hsiaoching/cdap | cdap-ui/app/cdap/components/ConfigurationGroup/index.tsx | TypeScript |
ArrowFunction |
({
widgetJson,
pluginProperties,
values,
inputSchema,
onChange,
disabled,
classes,
errors,
validateProperties,
}) => {
const [configurationGroups, setConfigurationGroups] = React.useState([]);
const referenceValueForUnMount = React.useRef<{
configurationGroups?: IFilteredConfigurationGroup[];
values?: Record<string, string>;
}>({});
const [filteredConfigurationGroups, setFilteredConfigurationGroups] = React.useState([]);
// Initialize the configurationGroups based on widgetJson and pluginProperties obtained from backend
React.useEffect(() => {
if (!pluginProperties) {
return;
}
const widgetConfigurationGroup = objectQuery(widgetJson, 'configuration-groups');
const widgetOutputs = objectQuery(widgetJson, 'outputs');
const processedConfigurationGroup = processConfigurationGroups(
pluginProperties,
widgetConfigurationGroup,
widgetOutputs
);
setConfigurationGroups(processedConfigurationGroup.configurationGroups);
// set default values
const defaultValues = processedConfigurationGroup.defaultValues;
const newValues = {
...defaultValues,
...values,
};
changeParentHandler(newValues);
}, [widgetJson, pluginProperties]);
// Watch for changes in values to determine dynamic widget
React.useEffect(() => {
let newFilteredConfigurationGroup;
try {
newFilteredConfigurationGroup = filterByCondition(
configurationGroups,
widgetJson,
pluginProperties,
values
);
} catch (e) {
newFilteredConfigurationGroup = configurationGroups;
// tslint:disable:no-console
console.log('Issue with applying filters: ', e);
}
referenceValueForUnMount.current = {
configurationGroups: newFilteredConfigurationGroup,
values,
};
setFilteredConfigurationGroups(newFilteredConfigurationGroup);
}, [values, configurationGroups]);
// This onUnMount is to make sure we clear out all properties that are hidden.
React.useEffect(() => {
return () => {
const newValues = { ...referenceValueForUnMount.current.values };
const configGroups = referenceValueForUnMount.current.configurationGroups;
if (configGroups) {
configGroups.forEach((group) => {
group.properties.forEach((property) => {
if (property.show === false) {
delete newValues[property.name];
}
});
});
}
changeParentHandler(newValues);
};
}, []);
function changeParentHandler(updatedValues) {
if (!onChange || typeof onChange !== 'function') {
return;
}
onChange(removeEmptyJsonValues(updatedValues));
}
const extraConfig = {
namespace: getCurrentNamespace(),
properties: values,
inputSchema,
validateProperties,
};
// Used to keep track of error messages that found a widget
// required to identify errors that did not find a widget,
// they will be marked as orphan errors.
const [usedErrors, setUsedErrors] = React.useState({});
const [groups, setGroups] = React.useState([]);
const [orphanErrors, setOrphanErrors] = React.useState([]);
// TODO: Revisit these hooks for errors. These don't seem to be necessary.
React.useEffect(() => {
setGroups(constructGroups);
}, [filteredConfigurationGroups, errors]);
React.useEffect(() => {
setOrphanErrors(constructOrphanErrors);
}, [usedErrors]);
function constructGroups() {
const newUsedErrors = {};
const newGroups = filteredConfigurationGroups.map((group, i) => {
if (group.show === false) {
return null;
}
return (
<div key={`${group.label}-${i}`} className={classes.group}>
<div className={classes.groupTitle}>
<h2 className={classes.h2Title}>{group.label}</h2>
<If condition={group.description && group.description.length > 0}>
<small className={classes.groupSubTitle}>{group.description}</small>
</If>
</div>
<div>
{group.properties.map((property, j) => {
if (property.show === false) {
return null;
}
// Hiding all plugin functions if pipeline is deployed
if (
disabled &&
property.hasOwnProperty('widget-category') &&
property['widget-category'] === 'plugin'
) {
return null;
}
// Check if a field is present to display the error contextually
const errorObjs =
errors && errors.hasOwnProperty(property.name) ? errors[property.name] : null;
if (errorObjs) {
// Mark error as used
newUsedErrors[property.name] = errors[property.name];
}
return (
<PropertyRow
key={`${property.name}-${j}`}
widgetProperty={property}
pluginProperty={pluginProperties[property.name]}
value={values[property.name]}
onChange={changeParentHandler}
extraConfig={extraConfig}
disabled={disabled}
errors={errorObjs}
/>
);
})}
</div>
</div> | hsiaoching/cdap | cdap-ui/app/cdap/components/ConfigurationGroup/index.tsx | TypeScript |
ArrowFunction |
() => {
if (!pluginProperties) {
return;
}
const widgetConfigurationGroup = objectQuery(widgetJson, 'configuration-groups');
const widgetOutputs = objectQuery(widgetJson, 'outputs');
const processedConfigurationGroup = processConfigurationGroups(
pluginProperties,
widgetConfigurationGroup,
widgetOutputs
);
setConfigurationGroups(processedConfigurationGroup.configurationGroups);
// set default values
const defaultValues = processedConfigurationGroup.defaultValues;
const newValues = {
...defaultValues,
...values,
};
changeParentHandler(newValues);
} | hsiaoching/cdap | cdap-ui/app/cdap/components/ConfigurationGroup/index.tsx | TypeScript |
ArrowFunction |
() => {
let newFilteredConfigurationGroup;
try {
newFilteredConfigurationGroup = filterByCondition(
configurationGroups,
widgetJson,
pluginProperties,
values
);
} catch (e) {
newFilteredConfigurationGroup = configurationGroups;
// tslint:disable:no-console
console.log('Issue with applying filters: ', e);
}
referenceValueForUnMount.current = {
configurationGroups: newFilteredConfigurationGroup,
values,
};
setFilteredConfigurationGroups(newFilteredConfigurationGroup);
} | hsiaoching/cdap | cdap-ui/app/cdap/components/ConfigurationGroup/index.tsx | TypeScript |
ArrowFunction |
() => {
return () => {
const newValues = { ...referenceValueForUnMount.current.values };
const configGroups = referenceValueForUnMount.current.configurationGroups;
if (configGroups) {
configGroups.forEach((group) => {
group.properties.forEach((property) => {
if (property.show === false) {
delete newValues[property.name];
}
});
});
}
changeParentHandler(newValues);
};
} | hsiaoching/cdap | cdap-ui/app/cdap/components/ConfigurationGroup/index.tsx | TypeScript |
ArrowFunction |
() => {
const newValues = { ...referenceValueForUnMount.current.values };
const configGroups = referenceValueForUnMount.current.configurationGroups;
if (configGroups) {
configGroups.forEach((group) => {
group.properties.forEach((property) => {
if (property.show === false) {
delete newValues[property.name];
}
});
});
}
changeParentHandler(newValues);
} | hsiaoching/cdap | cdap-ui/app/cdap/components/ConfigurationGroup/index.tsx | TypeScript |
ArrowFunction |
(group) => {
group.properties.forEach((property) => {
if (property.show === false) {
delete newValues[property.name];
}
});
} | hsiaoching/cdap | cdap-ui/app/cdap/components/ConfigurationGroup/index.tsx | TypeScript |
ArrowFunction |
(property) => {
if (property.show === false) {
delete newValues[property.name];
}
} | hsiaoching/cdap | cdap-ui/app/cdap/components/ConfigurationGroup/index.tsx | TypeScript |
ArrowFunction |
() => {
setGroups(constructGroups);
} | hsiaoching/cdap | cdap-ui/app/cdap/components/ConfigurationGroup/index.tsx | TypeScript |
ArrowFunction |
() => {
setOrphanErrors(constructOrphanErrors);
} | hsiaoching/cdap | cdap-ui/app/cdap/components/ConfigurationGroup/index.tsx | TypeScript |
ArrowFunction |
(group, i) => {
if (group.show === false) {
return null;
}
return (
<div key={`${group.label}-${i}`} | hsiaoching/cdap | cdap-ui/app/cdap/components/ConfigurationGroup/index.tsx | TypeScript |
ArrowFunction |
(property, j) => {
if (property.show === false) {
return null;
}
// Hiding all plugin functions if pipeline is deployed
if (
disabled &&
property.hasOwnProperty('widget-category') &&
property['widget-category'] === 'plugin'
) {
return null;
}
// Check if a field is present to display the error contextually
const errorObjs =
errors && errors.hasOwnProperty(property.name) ? errors[property.name] : null;
if (errorObjs) {
// Mark error as used
newUsedErrors[property.name] = errors[property.name];
}
return (
<PropertyRow
key={`${property.name}-${j}`} | hsiaoching/cdap | cdap-ui/app/cdap/components/ConfigurationGroup/index.tsx | TypeScript |
ArrowFunction |
(errs: IErrorObj[]) => {
errs.forEach((error) => {
usedMessages.add(error.msg);
});
} | hsiaoching/cdap | cdap-ui/app/cdap/components/ConfigurationGroup/index.tsx | TypeScript |
ArrowFunction |
(error) => {
usedMessages.add(error.msg);
} | hsiaoching/cdap | cdap-ui/app/cdap/components/ConfigurationGroup/index.tsx | TypeScript |
ArrowFunction |
(propName) => {
if (propName === 'orphanErrors') {
errors.orphanErrors.forEach((orphanError: IErrorObj) => {
// Making use the error msg has not been displayed contextually
// elsewhere.
if (!usedMessages.has(orphanError.msg)) {
orphanedErrors.add(orphanError.msg);
}
});
}
// If the error is not used and if the message is not used,
// add it to orphan errors.
else if (!usedErrors.hasOwnProperty(propName)) {
errors[propName].forEach((error: IErrorObj) => {
if (!usedMessages.has(error.msg)) {
// If any error is not displayed contextually, and the error message
// is not used by any other field, mark the error as orphan.
orphanedErrors.add(error.msg);
}
});
}
} | hsiaoching/cdap | cdap-ui/app/cdap/components/ConfigurationGroup/index.tsx | TypeScript |
ArrowFunction |
(orphanError: IErrorObj) => {
// Making use the error msg has not been displayed contextually
// elsewhere.
if (!usedMessages.has(orphanError.msg)) {
orphanedErrors.add(orphanError.msg);
}
} | hsiaoching/cdap | cdap-ui/app/cdap/components/ConfigurationGroup/index.tsx | TypeScript |
ArrowFunction |
(error: IErrorObj) => {
if (!usedMessages.has(error.msg)) {
// If any error is not displayed contextually, and the error message
// is not used by any other field, mark the error as orphan.
orphanedErrors.add(error.msg);
}
} | hsiaoching/cdap | cdap-ui/app/cdap/components/ConfigurationGroup/index.tsx | TypeScript |
ArrowFunction |
(error: string) => (
<li>{error}</li>
) | hsiaoching/cdap | cdap-ui/app/cdap/components/ConfigurationGroup/index.tsx | TypeScript |
InterfaceDeclaration |
export interface IConfigurationGroupProps extends WithStyles<typeof styles> {
widgetJson?: IWidgetJson;
pluginProperties: PluginProperties;
values: Record<string, string>;
inputSchema?: any;
disabled?: boolean;
onChange?: (values: Record<string, string>) => void;
errors: {
[property: string]: IErrorObj[];
};
validateProperties?: () => void;
} | hsiaoching/cdap | cdap-ui/app/cdap/components/ConfigurationGroup/index.tsx | TypeScript |
ArrowFunction |
type => Coffee | SandraBayabos/coffee-app-nestjs | src/coffees/entities/flavour.entity.ts | TypeScript |
ArrowFunction |
coffee => coffee.flavours | SandraBayabos/coffee-app-nestjs | src/coffees/entities/flavour.entity.ts | TypeScript |
ClassDeclaration |
@Entity()
export class Flavour {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@ManyToMany(type => Coffee, coffee => coffee.flavours)
coffees: Coffee[]
} | SandraBayabos/coffee-app-nestjs | src/coffees/entities/flavour.entity.ts | TypeScript |
InterfaceDeclaration | // eslint-disable-next-line @typescript-eslint/no-empty-interface,@typescript-eslint/no-unused-vars
export interface AugmentedSubmittables<ApiType extends ApiTypes> { } | AxiaSolar-Js/api | packages/api/src/types/submittable.ts | TypeScript |
InterfaceDeclaration |
export interface SubmittableExtrinsicFunction<ApiType extends ApiTypes, A extends AnyTuple = AnyTuple> extends CallBase<A> {
(...params: any[]): SubmittableExtrinsic<ApiType>;
} | AxiaSolar-Js/api | packages/api/src/types/submittable.ts | TypeScript |
InterfaceDeclaration |
export interface SubmittableModuleExtrinsics<ApiType extends ApiTypes> {
// only with is<Type> augmentation
[index: string]: SubmittableExtrinsicFunction<ApiType>; // | AugmentedIsSubmittable<ApiType, AnyTuple>;
} | AxiaSolar-Js/api | packages/api/src/types/submittable.ts | TypeScript |
TypeAliasDeclaration |
export type AugmentedSubmittable<T extends AnyFunction, A extends AnyTuple = AnyTuple> = T & CallBase<A>; | AxiaSolar-Js/api | packages/api/src/types/submittable.ts | TypeScript |
ArrowFunction |
async ({ where }) => {
// TODO: in multi-tenant app, you must add validation to ensure correct tenant
const intern = await db.intern.findFirst({
where,
select: {
interests: true,
jobApplications: true,
user: true,
id: true,
bio: true,
oneliner: true,
userId: true,
},
})
if (!intern) throw new NotFoundError()
return intern
} | 0xsamrath/internnova | app/interns/queries/getIntern.ts | TypeScript |
ClassDeclaration |
export class ExperimentalAssayViewValidator implements Validator<ExperimentalAssayView> {
static INSTANCE = new ExperimentalAssayViewValidator();
generalV = GeneralDescValidator.INSTANCE;
contribV = ContributionDescValidator.INSTANCE;
bioV = SimpleBioDescValidator.INSTANCE;
protected constructor() {
}
validate(obj: ExperimentalAssayView): string[] {
let err: string[] = [];
err = err.concat(this.generalV.validate(obj.generalDesc),
this.contribV.validate(obj.contributionDesc),
this.bioV.validate(obj));
return err;
}
} | SynthSys/BioDare2-UI | src/app/dom/repo/exp/experimental-assay-view.validator.ts | TypeScript |
MethodDeclaration |
validate(obj: ExperimentalAssayView): string[] {
let err: string[] = [];
err = err.concat(this.generalV.validate(obj.generalDesc),
this.contribV.validate(obj.contributionDesc),
this.bioV.validate(obj));
return err;
} | SynthSys/BioDare2-UI | src/app/dom/repo/exp/experimental-assay-view.validator.ts | TypeScript |
ArrowFunction |
async (): Promise<RepositoryInfo[]> => {
if (process.env.NODE_ENV === 'development') {
return repoMock
}
const info = getUserInfoToLocalStorage()
if (!info) {
return []
}
const { name, token } = info
const query = `query {
user(login: ${name}) {
repositories(last: 100) {
edges {
node {
id
name
url
}
}
}
starredRepositories(last: 100) {
edges {
node {
id
name
url
}
}
}
}
}`
try {
const response = await fetch('https://api.github.com/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({ query }),
})
const json = await response.json()
const userInfo = json.data.user
const userRepositories = userInfo.repositories.edges.map(
({ node }: { node: RepositoryInfo }) => node,
)
const starredRepositories = userInfo.starredRepositories.edges.map(
({ node }: { node: RepositoryInfo }) => node,
)
return userRepositories.concat(starredRepositories)
} catch (e) {
console.error(e)
return []
}
} | JaeYeopHan/octodirect | src/service/github-repository.service.ts | TypeScript |
ArrowFunction |
({ node }: { node: RepositoryInfo }) => node | JaeYeopHan/octodirect | src/service/github-repository.service.ts | TypeScript |
InterfaceDeclaration |
export interface RepositoryInfo {
id: string
name: string
url: string
} | JaeYeopHan/octodirect | src/service/github-repository.service.ts | TypeScript |
ArrowFunction |
details => details.post | a-kalmykov/ionic-typeorm | sample/sample2-one-to-one/entity/Post.ts | TypeScript |
ArrowFunction |
image => image.post | a-kalmykov/ionic-typeorm | sample/sample2-one-to-one/entity/Post.ts | TypeScript |
ArrowFunction |
metadata => metadata.post | a-kalmykov/ionic-typeorm | sample/sample2-one-to-one/entity/Post.ts | TypeScript |
ArrowFunction |
information => information.post | a-kalmykov/ionic-typeorm | sample/sample2-one-to-one/entity/Post.ts | TypeScript |
ArrowFunction |
author => author.post | a-kalmykov/ionic-typeorm | sample/sample2-one-to-one/entity/Post.ts | TypeScript |
ClassDeclaration |
@Entity("sample2_post")
export class Post {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@Column()
text: string;
// post has relation with category, however inverse relation is not set (category does not have relation with post set)
@OneToOne(type => PostCategory, {
cascadeInsert: true,
cascadeUpdate: true,
cascadeRemove: true
})
@JoinColumn()
category: PostCategory;
// post has relation with details. cascade inserts here means if new PostDetails instance will be set to this
// relation it will be inserted automatically to the db when you save this Post entity
@OneToOne(type => PostDetails, details => details.post, {
cascadeInsert: true
})
@JoinColumn()
details: PostDetails;
// post has relation with details. cascade update here means if new PostDetail instance will be set to this relation
// it will be inserted automatically to the db when you save this Post entity
@OneToOne(type => PostImage, image => image.post, {
cascadeUpdate: true
})
@JoinColumn()
image: PostImage;
// post has relation with details. cascade update here means if new PostDetail instance will be set to this relation
// it will be inserted automatically to the db when you save this Post entity
@OneToOne(type => PostMetadata, metadata => metadata.post, {
cascadeRemove: true
})
@JoinColumn()
metadata: PostMetadata|null;
// post has relation with details. full cascades here
@OneToOne(type => PostInformation, information => information.post, {
cascadeInsert: true,
cascadeUpdate: true,
cascadeRemove: true
})
@JoinColumn()
information: PostInformation;
// post has relation with details. not cascades here. means cannot be persisted, updated or removed
@OneToOne(type => PostAuthor, author => author.post)
@JoinColumn()
author: PostAuthor;
} | a-kalmykov/ionic-typeorm | sample/sample2-one-to-one/entity/Post.ts | TypeScript |
MethodDeclaration |
ngOnInit() {
this.model = [
{
label: 'Home',
items:[
{label: 'Dashboard',icon: 'pi pi-fw pi-home', routerLink: ['/']}
]
},
{
label: '管理',
items: [
{label: '使用者', icon: 'pi pi-fw pi-user-edit', routerLink: ['/pages/user']},
]
},
{
label: 'UI Components',
items: [
{label: 'Form Layout', icon: 'pi pi-fw pi-id-card', routerLink: ['/uikit/formlayout']},
{label: 'Input', icon: 'pi pi-fw pi-check-square', routerLink: ['/uikit/input']},
{label: 'Float Label', icon: 'pi pi-fw pi-bookmark', routerLink: ['/uikit/floatlabel']},
{label: 'Invalid State', icon: 'pi pi-fw pi-exclamation-circle', routerLink: ['/uikit/invalidstate']},
{label: 'Button', icon: 'pi pi-fw pi-mobile', routerLink: ['/uikit/button'], class: 'rotated-icon'},
{label: 'Table', icon: 'pi pi-fw pi-table', routerLink: ['/uikit/table']},
{label: 'List', icon: 'pi pi-fw pi-list', routerLink: ['/uikit/list']},
{label: 'Tree', icon: 'pi pi-fw pi-share-alt', routerLink: ['/uikit/tree']},
{label: 'Panel', icon: 'pi pi-fw pi-tablet', routerLink: ['/uikit/panel']},
{label: 'Overlay', icon: 'pi pi-fw pi-clone', routerLink: ['/uikit/overlay']},
{label: 'Media', icon: 'pi pi-fw pi-image', routerLink: ['/uikit/media']},
{label: 'Menu', icon: 'pi pi-fw pi-bars', routerLink: ['/uikit/menu'], preventExact: true},
{label: 'Message', icon: 'pi pi-fw pi-comment', routerLink: ['/uikit/message']},
{label: 'File', icon: 'pi pi-fw pi-file', routerLink: ['/uikit/file']},
{label: 'Chart', icon: 'pi pi-fw pi-chart-bar', routerLink: ['/uikit/charts']},
{label: 'Misc', icon: 'pi pi-fw pi-circle', routerLink: ['/uikit/misc']}
]
},
{
label:'Prime Blocks',
items:[
{label: 'Free Blocks', icon: 'pi pi-fw pi-eye', routerLink: ['/blocks'], badge: 'NEW'},
{label: 'All Blocks', icon: 'pi pi-fw pi-globe', url: ['https://www.primefaces.org/primeblocks-ng'], target: '_blank'},
]
},
{label:'Utilities',
items:[
{label: 'PrimeIcons', icon: 'pi pi-fw pi-prime', routerLink: ['/icons']},
{label: 'PrimeFlex', icon: 'pi pi-fw pi-desktop', url: ['https://www.primefaces.org/primeflex/'], target: '_blank'},
]
},
{
label: 'Pages',
items: [
{label: 'Crud', icon: 'pi pi-fw pi-user-edit', routerLink: ['/pages/crud']},
{label: 'Timeline', icon: 'pi pi-fw pi-calendar', routerLink: ['/pages/timeline']},
{label: 'Landing', icon: 'pi pi-fw pi-globe', routerLink: ['pages/landing']},
{label: 'Login', icon: 'pi pi-fw pi-sign-in', routerLink: ['pages/login']},
{label: 'Error', icon: 'pi pi-fw pi-times-circle', routerLink: ['pages/error']},
{label: 'Not Found', icon: 'pi pi-fw pi-exclamation-circle', routerLink: ['pages/notfound']},
{label: 'Access Denied', icon: 'pi pi-fw pi-lock', routerLink: ['pages/access']},
{label: 'Empty', icon: 'pi pi-fw pi-circle', routerLink: ['/pages/empty']}
]
},
{
label: 'Hierarchy',
items: [
{
label: 'Submenu 1', icon: 'pi pi-fw pi-bookmark',
items: [
{
label: 'Submenu 1.1', icon: 'pi pi-fw pi-bookmark',
items: [
{label: 'Submenu 1.1.1', icon: 'pi pi-fw pi-bookmark'},
{label: 'Submenu 1.1.2', icon: 'pi pi-fw pi-bookmark'},
{label: 'Submenu 1.1.3', icon: 'pi pi-fw pi-bookmark'},
]
},
{
label: 'Submenu 1.2', icon: 'pi pi-fw pi-bookmark',
items: [
{label: 'Submenu 1.2.1', icon: 'pi pi-fw pi-bookmark'}
]
},
]
},
{
label: 'Submenu 2', icon: 'pi pi-fw pi-bookmark',
items: [
{
label: 'Submenu 2.1', icon: 'pi pi-fw pi-bookmark',
items: [
{label: 'Submenu 2.1.1', icon: 'pi pi-fw pi-bookmark'},
{label: 'Submenu 2.1.2', icon: 'pi pi-fw pi-bookmark'},
]
},
{
label: 'Submenu 2.2', icon: 'pi pi-fw pi-bookmark',
items: [
{label: 'Submenu 2.2.1', icon: 'pi pi-fw pi-bookmark'},
]
},
]
}
]
},
{
label:'Get Started',
items:[
{
label: 'Documentation', icon: 'pi pi-fw pi-question', routerLink: ['/documentation']
},
{
label: 'View Source', icon: 'pi pi-fw pi-search', url: ['https://github.com/primefaces/sakai-ng'], target: '_blank'
}
]
}
];
} | primochen/sakai-ng | src/app/app.menu.component.ts | TypeScript |
MethodDeclaration |
onKeydown(event: KeyboardEvent) {
const nodeElement = (<HTMLDivElement> event.target);
if (event.code === 'Enter' || event.code === 'Space') {
nodeElement.click();
event.preventDefault();
}
} | primochen/sakai-ng | src/app/app.menu.component.ts | TypeScript |
InterfaceDeclaration |
export interface GetExifReqBody {
imgUrl: string;
} | latusikl/PhotoExifEditor | frontend/src/app/model/getExifReqBody.ts | TypeScript |
FunctionDeclaration | /**
* slug_cs will take envVar and then :
* - replace any character by `-` except `0-9`, `a-z`, `.`, and `_`
* - remove leading and trailing `-` character
* - limit the string size to 63 characters
* @param envVar to be slugged
*/
export function slug_cs(envVar: string): string {
return trailHyphen(replaceAnyNonAlphanumericCharacter(envVar)).substring(
0,
MAX_SLUG_STRING_SIZE
)
} | jbcpollak/github-slug-action | src/slug.ts | TypeScript |
FunctionDeclaration | /**
* slug will take envVar and then :
* - put the variable content in lower case
* - replace any character by `-` except `0-9`, `a-z`, `.`, and `_`
* - remove leading and trailing `-` character
* - limit the string size to 63 characters
* @param envVar to be slugged
*/
export function slug(envVar: string): string {
return slug_cs(envVar.toLowerCase())
} | jbcpollak/github-slug-action | src/slug.ts | TypeScript |
FunctionDeclaration | /**
* slugref_cs will take envVar and then :
* - remove refs/(heads|tags|pull)/
* - replace any character by `-` except `0-9`, `a-z`, `.`, and `_`
* - remove leading and trailing `-` character
* - limit the string size to 63 characters
* @param envVar to be slugged
*/
export function slugref_cs(envVar: string): string {
return slug_cs(removeRef(envVar))
} | jbcpollak/github-slug-action | src/slug.ts | TypeScript |
FunctionDeclaration | /**
* slugref will take envVar and then :
* - remove refs/(heads|tags|pull)/
* - put the variable content in lower case
* - replace any character by `-` except `0-9`, `a-z`, `.`, and `_`
* - remove leading and trailing `-` character
* - limit the string size to 63 characters
* @param envVar to be slugged
*/
export function slugref(envVar: string): string {
return slugref_cs(envVar.toLowerCase())
} | jbcpollak/github-slug-action | src/slug.ts | TypeScript |
FunctionDeclaration | /**
* slugurl_cs will take envVar and then :
* - replace any character by `-` except `0-9`, `a-z`
* - remove leading and trailing `-` character
* - limit the string size to 63 characters
* @param envVar to be slugged
*/
export function slugurl_cs(envVar: string): string {
return slug_cs(replaceAnyNonUrlCharactersWithHyphen(envVar))
} | jbcpollak/github-slug-action | src/slug.ts | TypeScript |
FunctionDeclaration | /**
* slugurl will take envVar and then :
* - put the variable content in lower case
* - replace any character by `-` except `0-9`, `a-z`
* - remove leading and trailing `-` character
* - limit the string size to 63 characters
* @param envVar to be slugged
*/
export function slugurl(envVar: string): string {
return slug(replaceAnyNonUrlCharactersWithHyphen(envVar))
} | jbcpollak/github-slug-action | src/slug.ts | TypeScript |
FunctionDeclaration | /**
* slugurlref_cs will take envVar and then :
* - remove refs/(heads|tags|pull)/
* - replace any character by `-` except `0-9`, `a-z`
* - remove leading and trailing `-` character
* - limit the string size to 63 characters
* @param envVar to be slugged
*/
export function slugurlref_cs(envVar: string): string {
return slugurl_cs(slugref_cs(envVar))
} | jbcpollak/github-slug-action | src/slug.ts | TypeScript |
FunctionDeclaration | /**
* slugurlref will take envVar and then :
* - remove refs/(heads|tags|pull)/
* - put the variable content in lower case
* - replace any character by `-` except `0-9`, `a-z`
* - remove leading and trailing `-` character
* - limit the string size to 63 characters
* @param envVar to be slugged
*/
export function slugurlref(envVar: string): string {
return slugurl(slugref(envVar))
} | jbcpollak/github-slug-action | src/slug.ts | TypeScript |
FunctionDeclaration |
function trailHyphen(envVar: string): string {
return envVar.replace(RegExp('^-*', 'g'), '').replace(RegExp('-*$', 'g'), '')
} | jbcpollak/github-slug-action | src/slug.ts | TypeScript |
FunctionDeclaration |
function replaceAnyNonAlphanumericCharacter(envVar: string): string {
return envVar.replace(RegExp('[^a-zA-Z0-9._]', 'g'), '-')
} | jbcpollak/github-slug-action | src/slug.ts | TypeScript |
FunctionDeclaration |
function replaceAnyNonUrlCharactersWithHyphen(envVar: string): string {
return envVar.replace(RegExp('[._]', 'g'), '-')
} | jbcpollak/github-slug-action | src/slug.ts | TypeScript |
FunctionDeclaration |
function removeRef(envVar: string): string {
return envVar.replace(RegExp('^refs/(heads|tags|pull)/'), '')
} | jbcpollak/github-slug-action | src/slug.ts | TypeScript |
ArrowFunction |
user => {
if(!user) { return null; }
// Loads the post data
if(id) { return this.db.document<PostData>(`users/${user.uid}/feed/${id}`).get(); }
// Creates a new unique document id
const newId = this.db.col(`users/${user.uid}/feed`).doc().id;
// Returns an empty post
return of({
id: newId,
tags: ['public'],
author: user.uid,
type: 'document', content: [{
type: 'paragraph', content: [{
type: 'text', value: ''
}]}]} as PostData);
} | AndreiYa/wizdm | wizdm/src/app/pages/explore/feed/edit/edit-resolver.service.ts | TypeScript |
ClassDeclaration | /** Resolves the post document */
@Injectable()
export class PostResolver implements Resolve<PostData> {
constructor(private auth: AuthService, private db: DatabaseService) { }
/** Resolves the post content loading the requested id */
public resolve(route: ActivatedRouteSnapshot): Observable<PostData> {
// Resolves the id from the query parameter
const id = route.queryParamMap.get('id');
return this.auth.user$.pipe( take(1), switchMap( user => {
if(!user) { return null; }
// Loads the post data
if(id) { return this.db.document<PostData>(`users/${user.uid}/feed/${id}`).get(); }
// Creates a new unique document id
const newId = this.db.col(`users/${user.uid}/feed`).doc().id;
// Returns an empty post
return of({
id: newId,
tags: ['public'],
author: user.uid,
type: 'document', content: [{
type: 'paragraph', content: [{
type: 'text', value: ''
}]}]} as PostData);
}));
}
} | AndreiYa/wizdm | wizdm/src/app/pages/explore/feed/edit/edit-resolver.service.ts | TypeScript |
MethodDeclaration | /** Resolves the post content loading the requested id */
public resolve(route: ActivatedRouteSnapshot): Observable<PostData> {
// Resolves the id from the query parameter
const id = route.queryParamMap.get('id');
return this.auth.user$.pipe( take(1), switchMap( user => {
if(!user) { return null; }
// Loads the post data
if(id) { return this.db.document<PostData>(`users/${user.uid}/feed/${id}`).get(); }
// Creates a new unique document id
const newId = this.db.col(`users/${user.uid}/feed`).doc().id;
// Returns an empty post
return of({
id: newId,
tags: ['public'],
author: user.uid,
type: 'document', content: [{
type: 'paragraph', content: [{
type: 'text', value: ''
}]}]} as PostData);
}));
} | AndreiYa/wizdm | wizdm/src/app/pages/explore/feed/edit/edit-resolver.service.ts | TypeScript |
ArrowFunction |
options => source =>
source.pipe(
map(data => {
const hasValidConfig = Object.keys(options.fields).find(
name => options.fields[name].operation === GroupByOperationID.groupBy
);
if (!hasValidConfig) {
return data;
}
const processed: DataFrame[] = [];
for (const frame of data) {
const groupByFields: Field[] = [];
for (const field of frame.fields) {
if (shouldGroupOnField(field, options)) {
groupByFields.push(field);
}
}
if (groupByFields.length === 0) {
continue; // No group by field in this frame, ignore the frame
}
// Group the values by fields and groups so we can get all values for a
// group for a given field.
const valuesByGroupKey: Record<string, Record<string, MutableField>> = {};
for (let rowIndex = 0; rowIndex < frame.length; rowIndex++) {
const groupKey = String(groupByFields.map(field => field.values.get(rowIndex)));
const valuesByField = valuesByGroupKey[groupKey] ?? {};
if (!valuesByGroupKey[groupKey]) {
valuesByGroupKey[groupKey] = valuesByField;
}
for (let field of frame.fields) {
const fieldName = getFieldDisplayName(field);
if (!valuesByField[fieldName]) {
valuesByField[fieldName] = {
name: fieldName,
type: field.type,
config: { ...field.config },
values: new ArrayVector(),
};
}
valuesByField[fieldName].values.add(field.values.get(rowIndex));
}
}
const fields: Field[] = [];
const groupKeys = Object.keys(valuesByGroupKey);
for (const field of groupByFields) {
const values = new ArrayVector();
const fieldName = getFieldDisplayName(field);
for (let key of groupKeys) {
const valuesByField = valuesByGroupKey[key];
values.add(valuesByField[fieldName].values.get(0));
}
fields.push({
name: field.name,
type: field.type,
config: {
...field.config,
},
values: values,
});
}
// Then for each calculations configured, compute and add a new field (column)
for (const field of frame.fields) {
if (!shouldCalculateField(field, options)) {
continue;
}
const fieldName = getFieldDisplayName(field);
const aggregations = options.fields[fieldName].aggregations;
const valuesByAggregation: Record<string, any[]> = {};
for (const groupKey of groupKeys) {
const fieldWithValuesForGroup = valuesByGroupKey[groupKey][fieldName];
const results = reduceField({
field: fieldWithValuesForGroup,
reducers: aggregations,
});
for (const aggregation of aggregations) {
if (!Array.isArray(valuesByAggregation[aggregation])) {
valuesByAggregation[aggregation] = [];
}
valuesByAggregation[aggregation].push(results[aggregation]);
}
}
for (const aggregation of aggregations) {
const aggregationField: Field = {
name: `${fieldName} (${aggregation})`,
values: new ArrayVector(valuesByAggregation[aggregation]),
type: FieldType.other,
config: {},
};
aggregationField.type = detectFieldType(aggregation, field, aggregationField);
fields.push(aggregationField);
}
}
processed.push({
fields,
length: groupKeys.length,
});
}
return processed;
})
) | 3wWqj/grafana | packages/grafana-data/src/transformations/transformers/groupBy.ts | TypeScript |
ArrowFunction |
source =>
source.pipe(
map(data => {
const hasValidConfig = Object.keys(options.fields).find(
name => options.fields[name].operation === GroupByOperationID.groupBy
);
if (!hasValidConfig) {
return data;
}
const processed: DataFrame[] = [];
for (const frame of data) {
const groupByFields: Field[] = [];
for (const field of frame.fields) {
if (shouldGroupOnField(field, options)) {
groupByFields.push(field);
}
}
if (groupByFields.length === 0) {
continue; // No group by field in this frame, ignore the frame
}
// Group the values by fields and groups so we can get all values for a
// group for a given field.
const valuesByGroupKey: Record<string, Record<string, MutableField>> = {};
for (let rowIndex = 0; rowIndex < frame.length; rowIndex++) {
const groupKey = String(groupByFields.map(field => field.values.get(rowIndex)));
const valuesByField = valuesByGroupKey[groupKey] ?? {};
if (!valuesByGroupKey[groupKey]) {
valuesByGroupKey[groupKey] = valuesByField;
}
for (let field of frame.fields) {
const fieldName = getFieldDisplayName(field);
if (!valuesByField[fieldName]) {
valuesByField[fieldName] = {
name: fieldName,
type: field.type,
config: { ...field.config },
values: new ArrayVector(),
};
}
valuesByField[fieldName].values.add(field.values.get(rowIndex));
}
}
const fields: Field[] = [];
const groupKeys = Object.keys(valuesByGroupKey);
for (const field of groupByFields) {
const values = new ArrayVector();
const fieldName = getFieldDisplayName(field);
for (let key of groupKeys) {
const valuesByField = valuesByGroupKey[key];
values.add(valuesByField[fieldName].values.get(0));
}
fields.push({
name: field.name,
type: field.type,
config: {
...field.config,
},
values: values,
});
}
// Then for each calculations configured, compute and add a new field (column)
for (const field of frame.fields) {
if (!shouldCalculateField(field, options)) {
continue;
}
const fieldName = getFieldDisplayName(field);
const aggregations = options.fields[fieldName].aggregations;
const valuesByAggregation: Record<string, any[]> = {};
for (const groupKey of groupKeys) {
const fieldWithValuesForGroup = valuesByGroupKey[groupKey][fieldName];
const results = reduceField({
field: fieldWithValuesForGroup,
reducers: aggregations,
});
for (const aggregation of aggregations) {
if (!Array.isArray(valuesByAggregation[aggregation])) {
valuesByAggregation[aggregation] = [];
}
valuesByAggregation[aggregation].push(results[aggregation]);
}
}
for (const aggregation of aggregations) {
const aggregationField: Field = {
name: `${fieldName} (${aggregation})`,
values: new ArrayVector(valuesByAggregation[aggregation]),
type: FieldType.other,
config: {},
};
aggregationField.type = detectFieldType(aggregation, field, aggregationField);
fields.push(aggregationField);
}
}
processed.push({
fields,
length: groupKeys.length,
});
}
return processed;
})
) | 3wWqj/grafana | packages/grafana-data/src/transformations/transformers/groupBy.ts | TypeScript |
ArrowFunction |
data => {
const hasValidConfig = Object.keys(options.fields).find(
name => options.fields[name].operation === GroupByOperationID.groupBy
);
if (!hasValidConfig) {
return data;
}
const processed: DataFrame[] = [];
for (const frame of data) {
const groupByFields: Field[] = [];
for (const field of frame.fields) {
if (shouldGroupOnField(field, options)) {
groupByFields.push(field);
}
}
if (groupByFields.length === 0) {
continue; // No group by field in this frame, ignore the frame
}
// Group the values by fields and groups so we can get all values for a
// group for a given field.
const valuesByGroupKey: Record<string, Record<string, MutableField>> = {};
for (let rowIndex = 0; rowIndex < frame.length; rowIndex++) {
const groupKey = String(groupByFields.map(field => field.values.get(rowIndex)));
const valuesByField = valuesByGroupKey[groupKey] ?? {};
if (!valuesByGroupKey[groupKey]) {
valuesByGroupKey[groupKey] = valuesByField;
}
for (let field of frame.fields) {
const fieldName = getFieldDisplayName(field);
if (!valuesByField[fieldName]) {
valuesByField[fieldName] = {
name: fieldName,
type: field.type,
config: { ...field.config },
values: new ArrayVector(),
};
}
valuesByField[fieldName].values.add(field.values.get(rowIndex));
}
}
const fields: Field[] = [];
const groupKeys = Object.keys(valuesByGroupKey);
for (const field of groupByFields) {
const values = new ArrayVector();
const fieldName = getFieldDisplayName(field);
for (let key of groupKeys) {
const valuesByField = valuesByGroupKey[key];
values.add(valuesByField[fieldName].values.get(0));
}
fields.push({
name: field.name,
type: field.type,
config: {
...field.config,
},
values: values,
});
}
// Then for each calculations configured, compute and add a new field (column)
for (const field of frame.fields) {
if (!shouldCalculateField(field, options)) {
continue;
}
const fieldName = getFieldDisplayName(field);
const aggregations = options.fields[fieldName].aggregations;
const valuesByAggregation: Record<string, any[]> = {};
for (const groupKey of groupKeys) {
const fieldWithValuesForGroup = valuesByGroupKey[groupKey][fieldName];
const results = reduceField({
field: fieldWithValuesForGroup,
reducers: aggregations,
});
for (const aggregation of aggregations) {
if (!Array.isArray(valuesByAggregation[aggregation])) {
valuesByAggregation[aggregation] = [];
}
valuesByAggregation[aggregation].push(results[aggregation]);
}
}
for (const aggregation of aggregations) {
const aggregationField: Field = {
name: `${fieldName} (${aggregation})`,
values: new ArrayVector(valuesByAggregation[aggregation]),
type: FieldType.other,
config: {},
};
aggregationField.type = detectFieldType(aggregation, field, aggregationField);
fields.push(aggregationField);
}
}
processed.push({
fields,
length: groupKeys.length,
});
}
return processed;
} | 3wWqj/grafana | packages/grafana-data/src/transformations/transformers/groupBy.ts | TypeScript |
ArrowFunction |
name => options.fields[name].operation === GroupByOperationID.groupBy | 3wWqj/grafana | packages/grafana-data/src/transformations/transformers/groupBy.ts | TypeScript |
ArrowFunction |
field => field.values.get(rowIndex) | 3wWqj/grafana | packages/grafana-data/src/transformations/transformers/groupBy.ts | TypeScript |
ArrowFunction |
(field: Field, options: GroupByTransformerOptions): boolean => {
const fieldName = getFieldDisplayName(field);
return options?.fields[fieldName]?.operation === GroupByOperationID.groupBy;
} | 3wWqj/grafana | packages/grafana-data/src/transformations/transformers/groupBy.ts | TypeScript |
ArrowFunction |
(field: Field, options: GroupByTransformerOptions): boolean => {
const fieldName = getFieldDisplayName(field);
return (
options?.fields[fieldName]?.operation === GroupByOperationID.aggregate &&
Array.isArray(options?.fields[fieldName].aggregations) &&
options?.fields[fieldName].aggregations.length > 0
);
} | 3wWqj/grafana | packages/grafana-data/src/transformations/transformers/groupBy.ts | TypeScript |
ArrowFunction |
(aggregation: string, sourceField: Field, targetField: Field): FieldType => {
switch (aggregation) {
case ReducerID.allIsNull:
return FieldType.boolean;
case ReducerID.last:
case ReducerID.lastNotNull:
case ReducerID.first:
case ReducerID.firstNotNull:
return sourceField.type;
default:
return guessFieldTypeForField(targetField) ?? FieldType.string;
}
} | 3wWqj/grafana | packages/grafana-data/src/transformations/transformers/groupBy.ts | TypeScript |
InterfaceDeclaration |
export interface GroupByFieldOptions {
aggregations: ReducerID[];
operation: GroupByOperationID | null;
} | 3wWqj/grafana | packages/grafana-data/src/transformations/transformers/groupBy.ts | TypeScript |
InterfaceDeclaration |
export interface GroupByTransformerOptions {
fields: Record<string, GroupByFieldOptions>;
} | 3wWqj/grafana | packages/grafana-data/src/transformations/transformers/groupBy.ts | TypeScript |
EnumDeclaration |
export enum GroupByOperationID {
aggregate = 'aggregate',
groupBy = 'groupby',
} | 3wWqj/grafana | packages/grafana-data/src/transformations/transformers/groupBy.ts | TypeScript |
ClassDeclaration |
class ModifyProperties {
private projectConfig: egret.EgretProperty
constructor() {
}
initProperties() {
var projectPath = file.joinPath(egret.args.projectDir, "egretProperties.json");
this.projectConfig = JSON.parse(file.read(projectPath));
}
save(version?: string) {
if (version) {
this.projectConfig.egret_version = version;
}
var projectPath = file.joinPath(egret.args.projectDir, "egretProperties.json");
var content = JSON.stringify(this.projectConfig, null, "\t");
file.save(projectPath, content);
}
upgradeModulePath() {
let config = this.projectConfig
for (let m of config.modules) {
if (!m.path) {
m.path = '${EGRET_APP_DATA}/' + config.egret_version;
}
}
}
} | taoabc/dragonbones-runtime-build | .cache/egret-core-5.1.0/tools/commands/upgrade/ModifyProperties.ts | TypeScript |
MethodDeclaration |
initProperties() {
var projectPath = file.joinPath(egret.args.projectDir, "egretProperties.json");
this.projectConfig = JSON.parse(file.read(projectPath));
} | taoabc/dragonbones-runtime-build | .cache/egret-core-5.1.0/tools/commands/upgrade/ModifyProperties.ts | TypeScript |
MethodDeclaration |
save(version?: string) {
if (version) {
this.projectConfig.egret_version = version;
}
var projectPath = file.joinPath(egret.args.projectDir, "egretProperties.json");
var content = JSON.stringify(this.projectConfig, null, "\t");
file.save(projectPath, content);
} | taoabc/dragonbones-runtime-build | .cache/egret-core-5.1.0/tools/commands/upgrade/ModifyProperties.ts | TypeScript |
MethodDeclaration |
upgradeModulePath() {
let config = this.projectConfig
for (let m of config.modules) {
if (!m.path) {
m.path = '${EGRET_APP_DATA}/' + config.egret_version;
}
}
} | taoabc/dragonbones-runtime-build | .cache/egret-core-5.1.0/tools/commands/upgrade/ModifyProperties.ts | TypeScript |
InterfaceDeclaration | /**
* <p>Contains the response to a successful <a>CreatePolicy</a> request. </p>
*/
export interface CreatePolicyOutput extends __aws_sdk_types.MetadataBearer {
/**
* <p>A structure containing details about the new policy.</p>
*/
Policy?: _UnmarshalledPolicy;
/**
* Metadata about the response received, including the HTTP status code, HTTP headers, and any request identifiers recognized by the SDK.
*/
$metadata: __aws_sdk_types.ResponseMetadata;
} | Dylan0916/aws-sdk-js-v3 | clients/browser/client-iam-browser/types/CreatePolicyOutput.ts | TypeScript |
ClassDeclaration |
@NgModule({
declarations: [
AppComponent,
FilterComponent,
ScatterplotPatrimonioComponent,
ResumoCandidatoComponent,
JoyplotEstadosComponent,
FactSheetComponent,
AboutComponent,
HomeComponent,
ReadmeComponent,
Top10Component,
NoDataDialogComponent
],
imports: [
BrowserAnimationsModule,
FlexLayoutModule,
BrowserModule,
FormsModule,
ReactiveFormsModule,
MatToolbarModule,
MatTabsModule,
MatButtonModule,
MatIconModule,
MatTooltipModule,
MatCardModule,
MatSidenavModule,
MatCheckboxModule,
MatOptionModule,
MatSelectModule,
MatAutocompleteModule,
MatInputModule,
MatSnackBarModule,
MatSlideToggleModule,
MatListModule,
HttpClientModule,
MatDialogModule,
MatTableModule,
MatSortModule,
MatPaginatorModule,
MatExpansionModule,
AppRoutingModule
],
providers: [
HttpClientModule,
RequestService,
GlobalService,
DataService,
UtilsService,
AlertService,
CandidatoService,
VisPatrimonioService,
PermalinkService
],
bootstrap: [AppComponent],
entryComponents: [AboutComponent, ReadmeComponent, NoDataDialogComponent]
})
export class AppModule {} | analytics-ufcg/empenhados-patrimonio-app | src/app/app.module.ts | TypeScript |
FunctionDeclaration | /**
* Create macro plugin.
*
* For example,
* ```typescript
* // vite.config.ts
*
* export default defineConfig({
* plugins: [
* createMacroPlugin({ ... })
* .use(provideSomeMacros({ ... }))
* ],
* })
* ```
*/
export function createMacroPlugin(
/* istanbul ignore next */
options: MacroPluginOptions = {}
): MacroPlugin {
const {
exclude,
include,
maxTraversals,
typesPath,
dev,
ssr,
watcherOptions,
parserPlugins,
} = options
const uninstantiatedProviders: MacroProvider[] = []
let runtime: Runtime | undefined
const plugin: MacroPlugin = {
use(...sources) {
uninstantiatedProviders.push(...sources)
return plugin
},
name: 'vite-plugin-macro',
enforce: 'pre',
configResolved: async (config) => {
// create env
const env = createEnvContext(
dev ?? !config.isProduction,
ssr ?? !!config.build.ssr,
watcherOptions
)
// init runtime
runtime = createRuntime(env, {
filter: { exclude, include },
transformer: { maxTraversals, parserPlugins },
})
// add providers
uninstantiatedProviders.forEach((provider) => {
runtime!.appendProvider(provider)
})
// call onStart hook and render types
await Promise.all([
runtime!.start(),
runtime!.renderTypes(
/* istanbul ignore next */
typesPath || join(env.projectPath[0], 'macros.d.ts')
),
])
},
configureServer: async (server) => {
;(runtime!.internal.env.modules as InternalModules).__setServer(server)
},
resolveId: (id) => runtime?.resolveId(id),
load: (id) => runtime?.load(id),
transform: async (code, id) => {
if (!(await runtime?.filter(id))) return
const result = await runtime?.transform(code, id)
return result && { code: result, map: null }
},
buildEnd: async () => {
await runtime!.stop()
},
}
return plugin
} | typed-macro/typed-macro | packages/wrapper-vite/src/plugin/plugin.ts | TypeScript |
ArrowFunction |
async (config) => {
// create env
const env = createEnvContext(
dev ?? !config.isProduction,
ssr ?? !!config.build.ssr,
watcherOptions
)
// init runtime
runtime = createRuntime(env, {
filter: { exclude, include },
transformer: { maxTraversals, parserPlugins },
})
// add providers
uninstantiatedProviders.forEach((provider) => {
runtime!.appendProvider(provider)
})
// call onStart hook and render types
await Promise.all([
runtime!.start(),
runtime!.renderTypes(
/* istanbul ignore next */
typesPath || join(env.projectPath[0], 'macros.d.ts')
),
])
} | typed-macro/typed-macro | packages/wrapper-vite/src/plugin/plugin.ts | TypeScript |
ArrowFunction |
(provider) => {
runtime!.appendProvider(provider)
} | typed-macro/typed-macro | packages/wrapper-vite/src/plugin/plugin.ts | TypeScript |
ArrowFunction |
async (server) => {
;(runtime!.internal.env.modules as InternalModules).__setServer(server)
} | typed-macro/typed-macro | packages/wrapper-vite/src/plugin/plugin.ts | TypeScript |
ArrowFunction |
(id) => runtime?.resolveId(id) | typed-macro/typed-macro | packages/wrapper-vite/src/plugin/plugin.ts | TypeScript |
ArrowFunction |
(id) => runtime?.load(id) | typed-macro/typed-macro | packages/wrapper-vite/src/plugin/plugin.ts | TypeScript |
ArrowFunction |
async (code, id) => {
if (!(await runtime?.filter(id))) return
const result = await runtime?.transform(code, id)
return result && { code: result, map: null }
} | typed-macro/typed-macro | packages/wrapper-vite/src/plugin/plugin.ts | TypeScript |
ArrowFunction |
async () => {
await runtime!.stop()
} | typed-macro/typed-macro | packages/wrapper-vite/src/plugin/plugin.ts | TypeScript |
TypeAliasDeclaration |
export type MacroPlugin = Plugin & {
/**
* Register macro providers to this macro manager so that
* all macros in providers and plugins share the same runtime.
*
* For macro plugins:
* > Some options like `maxTraversals` or `typesPath` will be overridden by
* > manager's, `parserPlugins` will be merged with the manager's one.
* >
* > After registered, the original macro plugin will be attached to the manager,
* > which means no need to add the plugin to Vite/Rollup 's plugins array again.
* @param sources macro providers or plugins.
*/
use(...sources: MacroProvider[]): MacroPlugin
} | typed-macro/typed-macro | packages/wrapper-vite/src/plugin/plugin.ts | TypeScript |
TypeAliasDeclaration |
export type MacroPluginOptions = FilterOptions &
TransformerOptions & {
/**
* The path of the automatically generated type declaration file.
*
* @default '<projectDir>/macros.d.ts'
*/
typesPath?: string
/**
* Is in dev mode.
*
* @default mode !== 'production'
* @see https://vitejs.dev/guide/env-and-mode.html#modes
*/
dev?: boolean
/**
* Is in SSR mode.
*
* @default whether there is an SSR configuration
* @see https://vitejs.dev/guide/ssr.html
*/
ssr?: boolean
/**
* Configure chokidar FSWatcher.
*
* @see https://github.com/paulmillr/chokidar#api
*/
watcherOptions?: WatchOptions
} | typed-macro/typed-macro | packages/wrapper-vite/src/plugin/plugin.ts | TypeScript |
MethodDeclaration |
use(...sources) {
uninstantiatedProviders.push(...sources)
return plugin
} | typed-macro/typed-macro | packages/wrapper-vite/src/plugin/plugin.ts | TypeScript |
FunctionDeclaration |
export default function TVSeriesSearch({query, onClick}: TVSeriesSearchProps) {
const classes = useStyles();
const [shows, setShows] = React.useState<Array<TVSeriesPreview>>([]);
React.useEffect(()=> {
if(query) {
fetchShowsSearch(query)
.then(foundShows=> setShows(foundShows));
return;
}
setShows([]);
}, [query]);
return (
<div className={classes.results}>
{shows.map(show=>
<Preview
key={show.id}
onClick={()=> onClick(show.id)}
image={show.image?.medium}
name={show.name}
status={show.status}
network={show.network}/>
)} | Stuff7/react-portfolio-frontend | src/components/TVSM/TVSeriesSearch.tsx | TypeScript |
ArrowFunction |
({palette})=> ({
results: {
margin: "20px 0",
display: "flex",
overflow: "auto",
},
}) | Stuff7/react-portfolio-frontend | src/components/TVSM/TVSeriesSearch.tsx | TypeScript |
ArrowFunction |
()=> {
if(query) {
fetchShowsSearch(query)
.then(foundShows=> setShows(foundShows));
return;
}
setShows([]);
} | Stuff7/react-portfolio-frontend | src/components/TVSM/TVSeriesSearch.tsx | TypeScript |
ArrowFunction |
foundShows=> setShows(foundShows) | Stuff7/react-portfolio-frontend | src/components/TVSM/TVSeriesSearch.tsx | TypeScript |
ArrowFunction |
show=>
<Preview
key | Stuff7/react-portfolio-frontend | src/components/TVSM/TVSeriesSearch.tsx | TypeScript |
InterfaceDeclaration |
interface TVSeriesSearchProps {
query: string;
onClick: (seriesID: number)=> void;
} | Stuff7/react-portfolio-frontend | src/components/TVSM/TVSeriesSearch.tsx | TypeScript |
ArrowFunction |
(first, second) =>
_.date.sortNewToOld(first.expiresDate, second.expiresDate) | levibostian/dollabill-apple | app/parse/common/auto_renewable_subscription/subscription.ts | TypeScript |
ArrowFunction |
(transaction) => transaction.offerCodeRefName | levibostian/dollabill-apple | app/parse/common/auto_renewable_subscription/subscription.ts | TypeScript |
ArrowFunction |
(transaction) => transaction.offerCodeRefName! | levibostian/dollabill-apple | app/parse/common/auto_renewable_subscription/subscription.ts | TypeScript |
ArrowFunction |
(transaction) => transaction.promotionalOfferId | levibostian/dollabill-apple | app/parse/common/auto_renewable_subscription/subscription.ts | TypeScript |
ArrowFunction |
(transaction) => transaction.promotionalOfferId! | levibostian/dollabill-apple | app/parse/common/auto_renewable_subscription/subscription.ts | TypeScript |
ClassDeclaration | /**
* Creates a parsed subscription from a collection of parsed transactions.
*
* @internal
*/
export class ParsedSubscription {
public allTransactions: AutoRenewableSubscriptionTransaction[]
public latestExpireDateTransaction: AutoRenewableSubscriptionTransaction
public renewalInfo?: ApplePendingRenewalInfo
constructor(
public originalTransactionId: string,
public isEligibleIntroductoryOffer: boolean,
transactions: AutoRenewableSubscriptionTransaction[], // the transactions for the originalTransactionId.
renewalInfo?: ApplePendingRenewalInfo
) {
if (transactions.length <= 0)
throw new InternalError(
"PrerequisiteNotMet",
"It's assumed that a subscription is not created if there are no transactions recorded for it."
)
this.allTransactions = transactions.sort((first, second) =>
_.date.sortNewToOld(first.expiresDate, second.expiresDate)
)
this.latestExpireDateTransaction = this.allTransactions[0] // there will be at least 1 transaction or there would not be an entry in the Map<>.
this.renewalInfo = renewalInfo
}
parseSubscription(): AutoRenewableSubscription {
const issues = this.issues()
return {
currentProductId: this.latestExpireDateTransaction.productId,
originalTransactionId: this.originalTransactionId,
subscriptionGroup: this.latestExpireDateTransaction.subscriptionGroupId,
isInFreeTrialPeriod: this.latestExpireDateTransaction.inTrialPeriod,
isEligibleIntroductoryOffer: this.isEligibleIntroductoryOffer,
currentEndDate: this.currentEndDate(),
status: this.status(),
usedOfferCodes: this.usedOfferCodes(),
usedPromotionalOffers: this.usedPromotionalOffers(),
allTransactions: this.allTransactions,
latestExpireDateTransaction: this.latestExpireDateTransaction,
willAutoRenew: this.willAutoRenew(),
willDowngradeToProductId: this.willDowngradeToProductId(),
issuesStrings: this.issuesStrings(issues),
issues,
priceIncreaseAccepted: this.priceIncreaseAccepted(),
gracePeriodExpireDate: this.gracePeriodExpireDate(),
cancelledDate: this.cancelledDate(),
expireDate: this.expireDate(),
isInBillingRetry: this.isInBillingRetry()
}
}
usedOfferCodes(): string[] {
const set = new Set(this.allTransactions
.filter((transaction) => transaction.offerCodeRefName)
.map((transaction) => transaction.offerCodeRefName!))
return [...set]
}
usedPromotionalOffers(): string[] {
const set = new Set(this.allTransactions
.filter((transaction) => transaction.promotionalOfferId)
.map((transaction) => transaction.promotionalOfferId!))
return [...set]
}
priceIncreaseAccepted(): boolean | undefined {
let priceIncreaseAccepted: boolean | undefined
if (this.renewalInfo?.price_consent_status) {
priceIncreaseAccepted = this.renewalInfo.price_consent_status === "1"
}
return priceIncreaseAccepted
}
issues(): AutoRenewableSubscriptionIssues {
return {
notYetAcceptingPriceIncrease: this.priceIncreaseAccepted() === false,
billingIssue: this.renewalInfo?.expiration_intent === "2" || this.gracePeriodExpireDate() !== undefined,
willVoluntaryCancel: this.renewalInfo !== undefined && !this.willAutoRenew()
}
}
issuesStrings(statuses: AutoRenewableSubscriptionIssues): AutoRenewableSubscriptionIssueString[] {
const strings: AutoRenewableSubscriptionIssueString[] = []
if (statuses.notYetAcceptingPriceIncrease) strings.push("not_yet_accepting_price_increase")
if (statuses.billingIssue) strings.push("billing_issue")
if (statuses.willVoluntaryCancel) strings.push("will_voluntary_cancel")
return strings
}
willAutoRenew(): boolean {
return this.renewalInfo?.auto_renew_status === "1" || false
}
gracePeriodExpireDate(): Date | undefined {
if (this.renewalInfo?.grace_period_expires_date_ms) return new Date(parseInt(this.renewalInfo.grace_period_expires_date_ms!))
return undefined
}
expireDate(): Date {
return this.latestExpireDateTransaction.expiresDate
}
currentEndDate(): Date {
return this.cancelledDate() || this.gracePeriodExpireDate() || this.expireDate()
}
willDowngradeToProductId(): string | undefined {
return this.renewalInfo?.auto_renew_product_id
}
isInBillingRetry(): boolean {
return this.renewalInfo?.is_in_billing_retry_period === "1" || false
}
cancelledDate(): Date | undefined {
return this.latestExpireDateTransaction.cancelledDate
}
status(): AutoRenewableSubscriptionStatus {
const inGracePeriod = this.renewalInfo?.grace_period_expires_date !== undefined || false
if (inGracePeriod) return "grace_period"
const isInBillingRetry = this.renewalInfo?.is_in_billing_retry_period === "1" || false
if (isInBillingRetry) return "billing_retry_period"
if (this.renewalInfo?.expiration_intent !== undefined) {
const involuntaryCancelled = this.renewalInfo.expiration_intent === "2" || this.renewalInfo.expiration_intent === "4"
if (involuntaryCancelled) return "involuntary_cancel"
const voluntaryCancelled = this.renewalInfo.expiration_intent === "1" || false
if (voluntaryCancelled) return "voluntary_cancel"
return "other_not_active"
}
if (this.latestExpireDateTransaction.cancelledDate !== undefined || this.latestExpireDateTransaction.refundReason !== undefined) {
const refunded = this.latestExpireDateTransaction.refundReason === "app_issue" || this.latestExpireDateTransaction.refundReason === "other"
if (refunded) return "refunded"
const upgraded = this.latestExpireDateTransaction.refundReason === "upgrade"
if (upgraded) return "upgraded"
return "other_not_active"
}
// Note: this should be caught by the "expiration_intent" of the pending renewal object but just in case, we want to catch when the customer has gone beyond the billing retry period and there is still a billing issue.
if (this.latestExpireDateTransaction.expiresDate.getTime() < new Date().getTime()) {
return "voluntary_cancel"
}
return "active"
}
} | levibostian/dollabill-apple | app/parse/common/auto_renewable_subscription/subscription.ts | TypeScript |
MethodDeclaration |
parseSubscription(): AutoRenewableSubscription {
const issues = this.issues()
return {
currentProductId: this.latestExpireDateTransaction.productId,
originalTransactionId: this.originalTransactionId,
subscriptionGroup: this.latestExpireDateTransaction.subscriptionGroupId,
isInFreeTrialPeriod: this.latestExpireDateTransaction.inTrialPeriod,
isEligibleIntroductoryOffer: this.isEligibleIntroductoryOffer,
currentEndDate: this.currentEndDate(),
status: this.status(),
usedOfferCodes: this.usedOfferCodes(),
usedPromotionalOffers: this.usedPromotionalOffers(),
allTransactions: this.allTransactions,
latestExpireDateTransaction: this.latestExpireDateTransaction,
willAutoRenew: this.willAutoRenew(),
willDowngradeToProductId: this.willDowngradeToProductId(),
issuesStrings: this.issuesStrings(issues),
issues,
priceIncreaseAccepted: this.priceIncreaseAccepted(),
gracePeriodExpireDate: this.gracePeriodExpireDate(),
cancelledDate: this.cancelledDate(),
expireDate: this.expireDate(),
isInBillingRetry: this.isInBillingRetry()
}
} | levibostian/dollabill-apple | app/parse/common/auto_renewable_subscription/subscription.ts | TypeScript |
MethodDeclaration |
usedOfferCodes(): string[] {
const set = new Set(this.allTransactions
.filter((transaction) => transaction.offerCodeRefName)
.map((transaction) => transaction.offerCodeRefName!))
return [...set]
} | levibostian/dollabill-apple | app/parse/common/auto_renewable_subscription/subscription.ts | TypeScript |
Subsets and Splits