repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
datalens-ui | github_2023 | datalens-tech | typescript | generateHeadColumns | function generateHeadColumns() {
let headerId = 0;
function generateHeadColumnLevel(level: any, key?: any) {
return (
headColumn[level]
// eslint-disable-next-line complexity
.map((entry: any, entryIndex: number) => {
const cell: any = {
id: ++headerId,
type: 'text',
};
let mType;
let mItem;
let value = entry;
if (value === null) {
value = '__null';
}
if (typeof value === 'undefined') {
value = '__undefined';
}
const cType = cTypes[level];
if (cType === 'markup') {
value = JSON.stringify(value);
}
if (
!measureNamesInRow &&
(measureNamesLevel === null || measureNamesLevel === level)
) {
if (multimeasure) {
mType = mTypes[entryIndex];
mItem = m[entryIndex];
} else {
mType = mTypes[0];
mItem = m[0];
}
if (isNumericalDataType(mType)) {
cell.type = 'number';
cell.sortable = true;
const mItemFormatting = mItem?.formatting as
| CommonNumberFormattingOptions
| undefined;
if (mItemFormatting) {
cell.formatter = {
format: mItemFormatting.format,
suffix: mItemFormatting.postfix,
prefix: mItemFormatting.prefix,
showRankDelimiter: mItemFormatting.showRankDelimiter,
unit: mItemFormatting.unit,
precision:
mType === DATASET_FIELD_TYPES.FLOAT &&
typeof mItemFormatting.precision !== 'number'
? MINIMUM_FRACTION_DIGITS
: mItemFormatting.precision,
};
} else {
cell.precision =
mType === DATASET_FIELD_TYPES.FLOAT
? MINIMUM_FRACTION_DIGITS
: 0;
}
} else if (isDateField({data_type: mType})) {
cell.type = 'date';
cell.sortable = true;
cell.format = mItem.format;
}
}
if (isDateField({data_type: cType})) {
cell.name = formatDate({
valueType: cType,
value: entry,
format: c[level].format,
});
} else if (isMarkupField({data_type: cType})) {
cell.name = markupToRawString(entry);
cell.markup = entry;
} else if (isNumericalDataType(cType) && c[level]?.formatting) {
cell.name = entry === null ? 'null' : entry;
cell.formattedName = chartKitFormatNumberWrapper(entry, {
lang: 'ru',
...c[level].formatting,
});
} else {
cell.name = entry === null ? 'null' : entry;
}
const currentKey =
typeof key === 'string'
? `${key}${SPECIAL_DELIMITER}${value}`
: `${value}`;
const nextLevel = headColumn[level + 1];
const noValues = !auxHashTableCKeys[currentKey];
if (noValues) {
return null;
} else if (nextLevel) {
cell.sub = generateHeadColumnLevel(level + 1, currentKey);
if (cell.sub.length === 0) {
return null;
}
}
return cell;
})
.filter((entry: any) => entry !== null)
);
}
let result;
if (headColumn[0]) {
result = generateHeadColumnLevel(0);
} else {
result = [
{
name: '',
group: useGroup,
autogroup: false,
sortable: false,
},
];
}
if (!hideHeadRows) {
// How many levels are there in the headRow - so many need to insert an empty cell into the header
headRow.forEach(() => {
result.unshift({
name: '',
group: useGroup,
autogroup: false,
sortable: false,
});
});
}
return result;
} | // Header cap generation function | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/server/modes/charts/plugins/datalens/preparers/old-pivot-table/old-pivot-table.ts#L838-L982 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | getPaths | function getPaths(structure: any, level: any, current: any, target: any, direction: any) {
if (current.length) {
if (direction === 'row' && !auxHashTableRKeys[current.join(SPECIAL_DELIMITER)]) {
return;
} else if (
direction === 'column' &&
!auxHashTableCKeys[current.join(SPECIAL_DELIMITER)]
) {
return;
}
}
if (structure[level + 1]) {
structure[level].forEach((entry: any) => {
let pathPart = entry;
if (entry === null) {
pathPart = '__null';
} else if (typeof entry === 'undefined') {
pathPart = '__undefined';
} else if (typeof entry === 'object') {
pathPart = JSON.stringify(pathPart);
}
getPaths(structure, level + 1, [...current, pathPart], target, direction);
});
} else if (structure[level]) {
structure[level].forEach((entry: any) => {
let pathPart = entry;
if (entry === null) {
pathPart = '__null';
} else if (typeof entry === 'undefined') {
pathPart = '__undefined';
} else if (typeof entry === 'object') {
pathPart = JSON.stringify(pathPart);
}
target.push([...current, pathPart]);
});
}
} | // The function of generating keys of existing data in the correct order | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/server/modes/charts/plugins/datalens/preparers/old-pivot-table/old-pivot-table.ts#L1009-L1050 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | customFormatNumber | function customFormatNumber({
value,
minimumFractionDigits,
locale = 'ru-RU',
}: {
value: number;
minimumFractionDigits: number;
locale: string;
}) {
switch (locale) {
case 'ru-RU':
default: {
const formattedValue = formatNumber(value, minimumFractionDigits);
return formattedValue.replace(/,/g, ' ').replace(/\./g, ',');
}
}
} | // This function is needed in order to format numbers in the Russian locale | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/server/modes/charts/plugins/datalens/utils/misc-helpers.ts#L135-L152 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | DashSchemeConverter.upTo4 | static async upTo4(originalData: any) {
const data = await DashSchemeConverter.upTo3(originalData);
const {salt, pages, schemeVersion, counter} = data;
if (schemeVersion >= 4) {
return data;
}
const [page] = pages;
const {id: pageId, tabs} = page;
const convertedTabs = tabs.map((tab: any) => ({...tab, aliases: {}}));
return {
salt,
counter,
schemeVersion: 4,
pages: [{id: pageId, tabs: convertedTabs}],
};
} | // adding the aliases field for each tab | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/shared/modules/dash-scheme-converter.ts#L115-L136 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | DashSchemeConverter.upTo6 | static async upTo6(originalData: any) {
const data = await DashSchemeConverter.upTo4(originalData);
const {salt, pages, counter, schemeVersion} = data;
if (schemeVersion >= 6) {
return data;
}
const [page] = pages;
const {id: pageId, tabs} = page;
const convertedTabs = tabs.map(({ignores, ...tab}: any) => ({
...tab,
ignores: ignores.reduce((result: any, {who, whom}: any) => {
tab.items
.filter(({id, type}: any) => id === who && type === DashTabItemType.Widget)
.forEach(({data}: any) =>
data.forEach(({id}: any) => {
result.push({who: id, whom});
}),
);
return result;
}, []),
}));
return {
salt,
counter,
schemeVersion: 6,
pages: [{id: pageId, tabs: convertedTabs}],
};
} | // ignors for the WIDGET-elements is translated into ignors for tabs WIDGET-elements | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/shared/modules/dash-scheme-converter.ts#L139-L172 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | Control.getMeta | getMeta() {
if (this.props.data.sourceType === DashTabItemControlSourceType.External) {
return (this.chartKitRef.current as ChartControlRef)?.getMeta();
}
if (this.context?.isNewRelations) {
return this.getCurrentWidgetMetaInfo();
}
if (this.chartKitRef && this.chartKitRef.current) {
this.chartKitRef.current.undeferred();
}
return new Promise((resolve) => {
this.resolve = resolve;
if (this.state.loadedData) {
this.resolveMeta(this.state.loadedData);
}
if (this.state.status === LOAD_STATUS.FAIL) {
this.resolveMeta(null);
}
});
} | // public | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/components/DashKit/plugins/Control/Control.tsx#L267-L286 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | DataTypeIcon | const DataTypeIcon: React.FC<DataTypeIconProps> = (props) => {
const {size, dataType, fieldType, className, ...restIconProps} = props;
if (!Object.values(DATASET_FIELD_TYPES).includes(dataType)) {
return null;
}
let data;
switch (dataType) {
case DATASET_FIELD_TYPES.FLOAT:
case DATASET_FIELD_TYPES.UINTEGER:
case DATASET_FIELD_TYPES.INTEGER:
data = Hashtag;
break;
case DATASET_FIELD_TYPES.BOOLEAN:
data = CopyCheckXmark;
break;
case DATASET_FIELD_TYPES.DATE:
case DATASET_FIELD_TYPES.GENERICDATETIME:
case DATASET_FIELD_TYPES.DATETIMETZ:
data = Calendar;
break;
case DATASET_FIELD_TYPES.GEOPOINT:
data = GeoDots;
break;
case DATASET_FIELD_TYPES.GEOPOLYGON:
data = GeoPolygons;
break;
case DATASET_FIELD_TYPES.UNSUPPORTED:
data = TriangleExclamationFill;
break;
case DATASET_FIELD_TYPES.ARRAY_FLOAT:
case DATASET_FIELD_TYPES.ARRAY_INT:
case DATASET_FIELD_TYPES.ARRAY_STR:
data = SquareBracketsBarsVertical;
break;
case DATASET_FIELD_TYPES.TREE_FLOAT:
case DATASET_FIELD_TYPES.TREE_INT:
case DATASET_FIELD_TYPES.TREE_STR:
data = BranchesDown;
break;
case DATASET_FIELD_TYPES.MARKUP:
data = SquareBracketsLetterA;
break;
case DATASET_FIELD_TYPES.STRING:
default:
data = SquareLetterT;
break;
}
const mods = {
dimension:
fieldType === DatasetFieldType.Dimension ||
(fieldType === DatasetFieldType.Pseudo && dataType === DATASET_FIELD_TYPES.STRING),
measure: fieldType === DatasetFieldType.Measure,
parameter: fieldType === DatasetFieldType.Parameter,
};
return <Icon data={data} size={size} className={b(mods, className)} {...restIconProps} />;
}; | // eslint-disable-next-line complexity | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/components/DataTypeIcon/DataTypeIcon.tsx#L32-L92 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | useNormalizedOpenedDialogData | function useNormalizedOpenedDialogData(props: DialogEditItemProps): DialogEditSpecificProps {
const openedDialog = useSelector(selectOpenedDialogType);
const {
type,
openedItemData,
setItemData,
widgetType,
widgetsCurrentTab,
openedItemDefaults,
selectorsGroupTitlePlaceholder,
} = props;
return {
type: openedDialog || type,
openedItemData,
setItemData,
widgetType,
widgetsCurrentTab,
openedItemDefaults,
selectorsGroupTitlePlaceholder,
};
} | // TypeGuard hook | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/components/DialogEditItem/DialogEditItem.tsx#L105-L127 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | DocumentationTab | const DocumentationTab: React.FC<Props> = ({documentation}: Props) => {
if (!documentation) {
return null;
}
return (
<YfmWrapper
className={b()}
setByInnerHtml={true}
content={replaceRelativeLinksToAbsoluteInHTML(documentation)}
noMagicLinks={true}
/>
);
}; | // To lift styles and listeners from the docks, use a class on a container with markup | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/components/DialogErrorWithTabs/Tabs/DocumentationTab/DocumentationTab.tsx#L18-L31 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | getControlToChartRelations | const getControlToChartRelations = ({
relationType,
widget,
row,
relations,
datasets,
}: {
relationType: string;
widget: DashkitMetaDataItemNoRelations;
row: DashkitMetaDataItemNoRelations;
relations: Omit<RelationsData, 'type' | 'available' | 'byFields' | 'forceAddAlias'>;
datasets: Datasets;
}) => {
let availableRelations = [...OUTPUT_RELATIONS];
let newRelationType = relationType;
const isItemFilteringChart = Boolean(
(row.type as FilteringWidgetType) in DASH_FILTERING_CHARTS_WIDGET_TYPES &&
row.enableFiltering,
);
let hasRelation = false;
let forceAddAlias = false;
let byFields = [] as string[];
if (relations.byAliases.length) {
if (isItemFilteringChart) {
newRelationType = relationType || getDefaultTypeByIgnore(relations);
availableRelations = [...FULL_RELATIONS];
} else {
newRelationType = relationType || RELATION_TYPES.output;
if (!OUTPUT_RELATIONS.includes(newRelationType)) {
newRelationType = RELATION_TYPES.output;
}
availableRelations = [...OUTPUT_RELATIONS];
}
} else if (isExternalControl(widget)) {
hasRelation = hasCommonUsedParamsWithDefaults(
widget.widgetParams || {},
row.usedParams || [],
);
if (hasRelation) {
newRelationType = relationType || RELATION_TYPES.output;
} else if (isEditorChart(row)) {
newRelationType = relationType || RELATION_TYPES.unknown;
forceAddAlias = true;
} else {
newRelationType = RELATION_TYPES.ignore;
}
if (isItemFilteringChart) {
availableRelations = [...FULL_RELATIONS];
} else {
if (!OUTPUT_RELATIONS.includes(newRelationType)) {
newRelationType = RELATION_TYPES.output;
}
availableRelations = [...OUTPUT_RELATIONS];
}
} else {
const commonUsedParamsFields = intersection(widget.usedParams || [], row.usedParams || []);
if (commonUsedParamsFields.length) {
newRelationType = relationType || RELATION_TYPES.output;
if (isDatasetControl(widget)) {
byFields = getMappedConnectedControlField({item: widget, datasets}) || [];
}
if (isItemFilteringChart) {
availableRelations = [...FULL_RELATIONS];
} else {
if (!OUTPUT_RELATIONS.includes(newRelationType)) {
newRelationType = RELATION_TYPES.output;
}
availableRelations = [...OUTPUT_RELATIONS];
}
} else {
newRelationType = relationType || RELATION_TYPES.unknown;
if (isItemFilteringChart) {
availableRelations = [...FULL_RELATIONS];
}
forceAddAlias = true;
}
}
return {
relationType: newRelationType as RelationType,
availableRelations,
forceAddAlias,
byFields,
};
}; | /**
* For current widget == control and widget in line == chart
*/ | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/components/DialogRelations/hooks/helpersChart.ts#L23-L110 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | getChartToControlRelations | const getChartToControlRelations = ({
relationType,
widget,
row,
relations,
datasets,
}: {
relationType: string;
widget: DashkitMetaDataItemNoRelations;
row: DashkitMetaDataItemNoRelations;
relations: Omit<RelationsData, 'type' | 'available' | 'byFields' | 'forceAddAlias'>;
datasets: Datasets;
}) => {
let newRelationType = relationType;
let availableRelations = [...INPUT_RELATIONS];
const isCurrentFilteringChart = Boolean(
(widget.type as FilteringWidgetType) in DASH_FILTERING_CHARTS_WIDGET_TYPES &&
widget.enableFiltering,
);
let forceAddAlias = false;
let hasRelation = false;
let byFields = [] as string[];
if (relations.byAliases.length) {
if (isCurrentFilteringChart) {
newRelationType = relationType || getDefaultTypeByIgnore(relations);
availableRelations = [...FULL_RELATIONS];
} else {
newRelationType = relationType || RELATION_TYPES.input;
if (!INPUT_RELATIONS.includes(newRelationType)) {
newRelationType = RELATION_TYPES.input;
}
availableRelations = [...INPUT_RELATIONS];
}
} else if (isExternalControl(row)) {
hasRelation = hasCommonUsedParamsWithDefaults(
row.widgetParams || {},
widget.usedParams || [],
);
if (hasRelation) {
newRelationType = relationType || RELATION_TYPES.input;
} else if (isEditorChart(widget)) {
newRelationType = relationType || RELATION_TYPES.unknown;
forceAddAlias = true;
} else {
newRelationType = RELATION_TYPES.ignore;
}
if (isCurrentFilteringChart) {
availableRelations = [...FULL_RELATIONS];
} else {
if (!INPUT_RELATIONS.includes(newRelationType)) {
newRelationType = RELATION_TYPES.input;
}
availableRelations = [...INPUT_RELATIONS];
}
} else {
const commonUsedParamsFields = intersection(row.usedParams || [], widget.usedParams || []);
if (commonUsedParamsFields.length) {
newRelationType = relationType || RELATION_TYPES.input;
if (isDatasetControl(row)) {
byFields = getMappedConnectedControlField({item: row, datasets}) || [];
}
if (isCurrentFilteringChart) {
availableRelations = [...FULL_RELATIONS];
} else {
if (!INPUT_RELATIONS.includes(newRelationType)) {
newRelationType = RELATION_TYPES.input;
}
availableRelations = [...INPUT_RELATIONS];
}
} else {
newRelationType = relationType || RELATION_TYPES.unknown;
if (isCurrentFilteringChart) {
availableRelations = [...FULL_RELATIONS];
}
forceAddAlias = true;
}
}
return {
relationType: newRelationType as RelationType,
availableRelations,
forceAddAlias,
byFields,
};
}; | /**
* For current widget == chart and widget in line == control
*/ | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/components/DialogRelations/hooks/helpersChart.ts#L115-L201 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | EntryDialogues.open | open<T extends string, P extends Record<string, any> = any>({
dialog,
dialogProps,
}: MethodOpen<T, P>): Promise<EntryDialogOnCloseArg> {
return new Promise((resolveOpenDialog) => {
this.setState({
dialog,
resolveOpenDialog,
dialogProps,
visible: true,
});
});
} | // Public method via ref | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/components/EntryDialogues/EntryDialogues.tsx#L183-L195 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | withErrorPage | function withErrorPage<T = unknown>(
WrappedComponent: React.ComponentType<T>,
action?: ErrorPageProps['action'],
) {
const componentName = WrappedComponent.displayName || WrappedComponent.name || 'Component';
return class WithErrorPage extends React.Component<T, WithErrorPageState> {
static displayName = `withErrorPage(${componentName})`;
static getDerivedStateFromError(error: Error) {
return {error};
}
state: WithErrorPageState = {
error: null,
};
render() {
if (this.state.error) {
return <ErrorPage error={this.state.error} action={action} />;
}
return <WrappedComponent {...this.props} />;
}
} | // TODO: make ability to insert in compose | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/components/ErrorPage/withErrorPage.tsx | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | Monaco.onResizeWindow | onResizeWindow = () => {
if (this.editor) {
this.editor.layout();
}
} | /*
You can use the automaticLayout flag for the resize, but when it is set to true
an event with an interval of 100ms is set on the window, which checks the state of the viewport.
It seems that it is too expensive for such an operation, so the resize is custom
*/ | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/components/Monaco/Monaco.tsx | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | isChartType | function isChartType(props: ChartWrapperWithProviderProps): props is ChartWithProviderWithRefProps {
return props.usageType === 'chart';
} | /**
* is needed for proper component props typing
* @param props
*/ | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/components/Widgets/Chart/ChartWidgetWithProvider.tsx#L20-L22 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | getUniqDatasetsFields | const getUniqDatasetsFields = (datasets?: Array<DatasetsData>) => {
datasets?.forEach((dataset) => {
if (!dataset.fieldsList) {
return;
}
const guids: Record<string, string> = {};
const newFieldList: DatasetsFieldsListData[] = [];
dataset.fieldsList.forEach((fieldItem) => {
if (!(fieldItem.guid in guids)) {
guids[fieldItem.guid] = '';
newFieldList.push(fieldItem);
}
});
dataset.fieldsList = newFieldList;
});
return datasets;
}; | /**
* We get duplicated from api, need to clear it to prevent problems with doubles
* (in ex. in dash relations)
* @param datasets
*/ | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/components/Widgets/Chart/helpers/helpers.ts#L133-L150 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | Observer.triggerSync | private triggerSync(element: HTMLDivElement, callback: IntersectionCallback) {
const {top, height} = element.getBoundingClientRect();
const bottom = top + height;
const isVisible = top < window.innerHeight + LOADING_VISIBLE_OFFSET && bottom >= 0;
callback(isVisible);
} | /**
* Sync call for priority loading to work as intended
* cause all selectors are added to load queue while first render
* if we will delegate this to IntersectionObserver init call micro-task
* we will be already late by the time when loading will be already started
*/ | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/components/Widgets/Chart/hooks/useIntersectionObserver.ts#L93-L99 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | isNeedToUpdateNode | const isNeedToUpdateNode = (el: Element) => {
return el.children?.length === 0;
}; | /**
* Check latex and mermaid containers
* when containers are first time passed they are empty and all data is stored in data attribute
* if they don't have any child element it's an indicator that we need to update them
*/ | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/components/YfmWrapper/YfmWrapper.tsx#L39-L41 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | ChartKitBase.shouldComponentUpdate | shouldComponentUpdate(
nextProps: ChartKitProps<TProviderProps, TProviderData, TProviderCancellation>,
nextState: ChartKitState<TProviderProps, TProviderData, TProviderCancellation>,
) {
const nextStateWithoutNotChanged = omit(nextState, 'isDataProviderPropsNotChanged');
const stateWithoutNotChanged = omit(this.state, 'isDataProviderPropsNotChanged');
const shouldUpdate =
!isEqual(omit(nextProps, 'menu'), omit(this.props, 'menu')) ||
!isEqual(nextStateWithoutNotChanged, stateWithoutNotChanged);
return shouldUpdate;
} | // and by componentDidUpdate, another getWidget is launched | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/libs/DatalensChartkit/components/ChartKitBase/ChartKitBase.tsx#L270-L281 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | ChartKitBase.onChange | private onChange = (
data: OnChangeData,
state: {forceUpdate: boolean},
callExternalOnChange?: boolean,
callChangeByClick?: boolean,
) => {
if (data.type === 'PARAMS_CHANGED') {
let additionalParams = {};
const oldDrillDownLevel = this.getCurrentDrillDownLevel();
const newDrillDownLevel = data.data.params.drillDownLevel;
const isDrillDownLevelNotEqual =
oldDrillDownLevel && newDrillDownLevel && oldDrillDownLevel !== newDrillDownLevel;
let drillParamsChanged = false;
if (isDrillDownLevelNotEqual) {
drillParamsChanged = true;
additionalParams = {
_page: String(START_PAGE),
};
}
const oldDrillDownFilters = this.getCurrentDrillDownFilters();
const newDrillDownFilters = data.data.params.drillDownFilters;
// check only when not null, not undefined, not ''
const isDrillDownFiltersNotEqual =
Boolean(oldDrillDownFilters) &&
Boolean(newDrillDownFilters) &&
!isEqual(oldDrillDownFilters, newDrillDownFilters);
if (isDrillDownFiltersNotEqual) {
drillParamsChanged = true;
}
const isPageChanged =
String(data.data.params._page) !== String(this.state.runtimeParams?._page);
const isSortingChanged =
data.data.params._columnId !== this.state.runtimeParams?._columnId ||
data.data.params._sortOrder !== this.state.runtimeParams?._sortOrder ||
data.data.params.__sortMeta !== this.state.runtimeParams?.__sortMeta;
const newRuntimeParam = deepAssign(
{},
this.state.runtimeParams,
data.data.params,
additionalParams,
);
const needForceChange =
!callExternalOnChange ||
drillParamsChanged ||
isPageChanged ||
isSortingChanged ||
callChangeByClick;
if (needForceChange) {
this.setState(
{
runtimeParams: newRuntimeParam,
...state,
},
() => {
this.onExternalChangeCallback({
callExternal: Boolean(callExternalOnChange),
onChange: this.props.onChange,
params: newRuntimeParam,
});
},
);
} else {
this.onExternalChangeCallback({
callExternal: Boolean(callExternalOnChange),
onChange: this.props.onChange,
params: newRuntimeParam,
});
}
} else if (callExternalOnChange && this.props.onChange) {
this.props.onChange(data);
}
} | // right now it only for table with onClick in the cell and control-button with onClick | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/libs/DatalensChartkit/components/ChartKitBase/ChartKitBase.tsx | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | handlePageScroll | const handlePageScroll = () => {
const keys: string[] = Object.keys(uninitializedComponents);
keys.forEach((key) => {
const component = uninitializedComponents[key];
component.checkViewportPosition();
});
}; | // Scroll event handler - bypasses all components waiting for initialization and calls a validating method to check | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/libs/DatalensChartkit/components/DeferredInitializer/DeferredInitializer.tsx#L18-L26 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | trackComponentPosition | const trackComponentPosition = (component: DeferredInitializer, key: string) => {
if (!Object.keys(uninitializedComponents).length) {
bindScrollHandler();
}
uninitializedComponents[key] = component;
}; | // Adding a property to the uninitializedComponents object. If, at the same time, initially, the object is empty | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/libs/DatalensChartkit/components/DeferredInitializer/DeferredInitializer.tsx#L40-L46 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | untrackComponentPosition | const untrackComponentPosition = (key: string) => {
delete uninitializedComponents[key];
if (!Object.keys(uninitializedComponents).length) {
unbindScrollHandler();
}
}; | // Deleting a property from an uninitializedComponents object. If, after deletion, the object becomes empty - | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/libs/DatalensChartkit/components/DeferredInitializer/DeferredInitializer.tsx#L50-L56 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | DeferredInitializer.getDerivedStateFromProps | static getDerivedStateFromProps(
nextProps: DeferredInitializerProps,
prevState: DeferredInitializerState,
) {
if (nextProps.deferred && !prevState.initialized) {
return {initialized: true};
}
return null;
} | // but in this case, it is still updated, because props.children are new every time | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/libs/DatalensChartkit/components/DeferredInitializer/DeferredInitializer.tsx#L79-L87 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | ChartsDataProvider.setSettings | setSettings = (newSettings: Partial<Settings>) => {
if ('maxConcurrentRequests' in newSettings) {
initConcurrencyManager(newSettings.maxConcurrentRequests || Infinity);
}
Object.assign(this.settings, newSettings);
if (Array.isArray(this.settings.endpoint)) {
this.settings.endpoint = this.settings.endpoint.map((value) =>
value.replace(/\/$/, ''),
);
} else {
this.settings.endpoint = this.settings.endpoint.replace(/\/$/, '');
}
} | // @ts-ignore Moving to TS 4.9. Improve generics | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/libs/DatalensChartkit/modules/data-provider/charts/index.ts | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | ChartsDataProvider.isEqualProps | isEqualProps(a: ChartsProps, b: ChartsProps) {
return isEqual(a, b);
} | // compare only by fields registered in some static field or take ChartsProps keys | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/libs/DatalensChartkit/modules/data-provider/charts/index.ts#L581-L583 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | ChartsDataProvider.pushStats | pushStats(input: ChartKitLoadSuccess<ChartsData>, externalStats: Partial<ChartsStats> = {}) {
// console.log('CHARTS_DATA_PROVIDER_PUSH_STATS', input);
const stats = Object.assign(
ChartsDataProvider.gatherStats({
...input.data,
requestId: input.requestId,
}),
externalStats,
);
if (this.collectStatsTimerId) {
window.clearTimeout(this.collectStatsTimerId);
}
this.collectStatsTimerId = window.setTimeout(
this.collectStats.bind(this),
STATS_COLLECT_TIMEOUT,
);
this.collectStatsBatchQueue.push(stats);
} | // called when status: 'success' | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/libs/DatalensChartkit/modules/data-provider/charts/index.ts#L734-L754 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | processNode | async function processNode<T extends CurrentResponse, R extends Widget | ControlsOnlyWidget>(
loaded: T,
noJsonFn?: boolean,
): Promise<R & ChartsData> {
const {
type: loadedType,
params,
defaultParams,
id,
key,
usedParams,
unresolvedParams,
sources,
logs_v2,
timings,
extra,
requestId,
traceId,
widgetConfig,
} = loaded;
try {
const showSafeChartInfo =
Utils.getOptionsFromSearch(window.location.search).showSafeChartInfo ||
(params &&
SHARED_URL_OPTIONS.SAFE_CHART in params &&
String(params?.[SHARED_URL_OPTIONS.SAFE_CHART]?.[0]) === '1');
let result: Widget & Optional<WithControls> & ChartsData = {
// @ts-ignore
type: loadedType.match(/^[^_]*/)![0],
params: omit(params, 'name'),
defaultParams,
entryId: id ?? `fake_${getRandomCKId()}`,
key,
usedParams,
sources,
logs_v2,
timings,
extra,
requestId,
traceId,
isNewWizard: loadedType in WIZARD_CHART_NODE,
isOldWizard: false,
isEditor: loadedType in EDITOR_CHART_NODE,
isQL: loadedType in QL_CHART_NODE,
widgetConfig,
};
if ('unresolvedParams' in loaded) {
result.unresolvedParams = unresolvedParams;
}
if ('publicAuthor' in loaded) {
const publicAuthor = loaded.publicAuthor;
(result as GraphWidget).publicAuthor = publicAuthor;
}
if (isNodeResponse(loaded)) {
const parsedConfig = JSON.parse(loaded.config);
const enableJsAndHtml = get(parsedConfig, 'enableJsAndHtml', true);
const jsonParse = noJsonFn || enableJsAndHtml === false ? JSON.parse : JSONfn.parse;
result.data = loaded.data;
result.config = jsonParse(loaded.config);
result.libraryConfig = jsonParse(
loaded.highchartsConfig,
noJsonFn ? replacer : undefined,
);
if (showSafeChartInfo) {
result.safeChartInfo = getSafeChartWarnings(
loadedType,
pick(result, 'config', 'libraryConfig', 'data'),
);
}
if (
shouldUseUISandbox(result.config) ||
shouldUseUISandbox(result.libraryConfig) ||
shouldUseUISandbox(result.data)
) {
const uiSandbox = await getUISandbox();
const uiSandboxOptions: UiSandboxRuntimeOptions = {};
if (!get(loaded.params, SHARED_URL_OPTIONS.WITHOUT_UI_SANDBOX_LIMIT)) {
// creating an object for mutation
// so that we can calculate the total execution time of the sandbox
uiSandboxOptions.totalTimeLimit = UI_SANDBOX_TOTAL_TIME_LIMIT;
}
if (result.type === WidgetKind.BlankChart) {
uiSandboxOptions.fnExecTimeLimit = 1500;
}
const unwrapFnArgs = {
entryId: result.entryId,
entryType: loadedType,
sandbox: uiSandbox,
options: uiSandboxOptions,
};
await unwrapPossibleFunctions({...unwrapFnArgs, target: result.config});
await unwrapPossibleFunctions({...unwrapFnArgs, target: result.libraryConfig});
await unwrapPossibleFunctions({...unwrapFnArgs, target: result.data});
result.uiSandboxOptions = uiSandboxOptions;
}
const isWizardOrQl = result.isNewWizard || result.isQL;
const shouldProcessHtmlFields =
isPotentiallyUnsafeChart(loadedType) ||
(isEnabledFeature(Feature.HtmlInWizard) && result.config?.useHtml);
if (shouldProcessHtmlFields) {
const parseHtml = await getParseHtmlFn();
const ignoreInvalidValues = isWizardOrQl;
const allowHtml =
isWizardOrQl && isEnabledFeature(Feature.EscapeStringInWizard)
? false
: enableJsAndHtml;
processHtmlFields(result.data, {
allowHtml,
parseHtml,
ignoreInvalidValues,
});
processHtmlFields(result.libraryConfig, {
allowHtml,
parseHtml,
ignoreInvalidValues,
});
}
await unwrapMarkdown({config: result.config, data: result.data});
await unwrapMarkup({config: result.config, data: result.data});
applyChartkitHandlers({
config: result.config,
libraryConfig: result.libraryConfig,
});
if ('sideMarkdown' in loaded.extra && loaded.extra.sideMarkdown) {
(result as GraphWidget).sideMarkdown = loaded.extra.sideMarkdown;
}
if ('chartsInsights' in loaded.extra && loaded.extra.chartsInsights) {
const {chartsInsightsLocators = ''} = UserSettings.getInstance().getSettings();
try {
const locators = chartsInsightsLocators
? JSON.parse(chartsInsightsLocators)
: {};
const chartsInsightsData = getChartsInsightsData(
loaded.extra.chartsInsights,
locators,
);
(result as GraphWidget).chartsInsightsData = chartsInsightsData;
} catch (error) {
logger.logError('ChartsInsights: process data failed', error);
}
}
const postProcessRunResult = registry.chart.functions.get('postProcessRunResult');
if (postProcessRunResult) {
result = {...result, ...postProcessRunResult(loaded)};
}
if (result.type === 'metric' && result.config && result.config.metricVersion === 2) {
// @ts-ignore
result.type = 'metric2';
}
if (result.type === 'ymap' && result.libraryConfig) {
result.libraryConfig.apiKey = DL.YAMAP_API_KEY;
}
}
if ('uiScheme' in loaded) {
const uiScheme = (loaded as UI).uiScheme;
if (uiScheme) {
(result as WithControls).controls = Array.isArray(uiScheme)
? {
controls: uiScheme,
lineBreaks: 'nowrap',
}
: uiScheme;
}
}
return result as R & ChartsData;
} catch (error) {
throw DatalensChartkitCustomError.wrap(error, {
code: CHARTS_ERROR_CODE.PROCESSING_ERROR,
message: i18n('chartkit.data-provider', 'error-processing'),
});
}
} | /* eslint-disable complexity */ | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/libs/DatalensChartkit/modules/data-provider/charts/node.ts#L245-L440 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | SDK.makeRequestCancelable | makeRequestCancelable({method = 'custom', requestConfig}: IMakeRequestCancelable) {
const currentCancelableRequest = this._cancelableRequests[method];
if (currentCancelableRequest) {
currentCancelableRequest.cancel(`${method} was cancelled`);
}
const cancellation = this.createCancelSource();
this._cancelableRequests[method] = cancellation;
requestConfig.cancelToken = cancellation.token;
} | // TODO: save not only method, but data and query | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/libs/sdk/index.ts#L111-L122 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | UserSettings.getInstance | static getInstance() {
if (!this.instance) {
this.instance = new this();
}
return this.instance;
} | // Details in technotes/user-settings.md | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/libs/userSettings/index.ts#L12-L17 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | MarkdownProvider.getMarkdown | static async getMarkdown({text}: {text: string}) {
const cached = MarkdownProvider.cache[text];
if (cached) {
return {
result: cached,
meta: MarkdownProvider.cacheMeta[text],
};
}
try {
const fetchRenderedMarkdown = registry.common.functions.get('fetchRenderedMarkdown');
const {result, meta} = await fetchRenderedMarkdown(text);
MarkdownProvider.cache[text] = result;
MarkdownProvider.cacheMeta[text] = meta;
return {result, meta};
} catch (error) {
logger.logError('MarkdownProvider: renderMarkdown failed', error);
console.error('MARKDOWN_PROVIDER_GET_MARKDOWN_FAILED', error);
throw error;
}
} | // we accept {text} and give {result} for compatibility with plugins/Text in dashkit | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/modules/markdownProvider.ts#L50-L73 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | functionDiffFilter | const functionDiffFilter = (context: any) => {
if (typeof context.left === 'function') {
if (typeof context.right === 'function') {
if (context.left === context.right) {
context.setResult(undefined);
} else {
context.setResult([context.left, context.right]);
}
} else {
context.setResult([context.left, context.right]);
}
context.exit();
} else if (typeof context.right === 'function') {
context.setResult([context.left, context.right]).exit();
}
}; | // Plugin for jsondiffpatch to diff functions by its' references | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/store/utils/jdp.ts#L5-L21 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | i18n | const i18n = (_: string, _key: string) => {
return 'Failed to load user';
}; | /* TODO: add title translations */ | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/units/auth/containers/UserProfile/UserProfile.tsx#L20-L22 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | MarkdownProvider.getMarkdown | static async getMarkdown({text}: {text: string}) {
const cached = MarkdownProvider.cache[text];
if (cached) {
return {result: cached};
}
try {
const fetchRenderedMarkdown = registry.common.functions.get('fetchRenderedMarkdown');
const {result} = await fetchRenderedMarkdown(text);
MarkdownProvider.cache[text] = result;
return {result};
} catch (error) {
logger.logError('MarkdownProvider: renderMarkdown failed', error);
console.error('MARKDOWN_PROVIDER_GET_MARKDOWN_FAILED', error);
throw error;
}
} | // we accept {text} and give {result} for compatibility with plugins/Text in dashkit | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/units/dash/modules/markdownProvider.ts#L53-L73 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | hasTabs | const hasTabs = (data: DashTabItem['data']): data is DashTabItemWidget['data'] => {
return 'tabs' in data && data.tabs.length > 1;
}; | /**
* Type guards
*/ | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/units/dash/store/actions/helpers.ts#L20-L22 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | prepareCode | const prepareCode = (rowCode: string) => {
// Such spaces can get into the input when copying a string from another source (for example, from telegram)
return rowCode.replace(/\u00a0/g, ' ');
}; | // TODO: think about highlighting such spaces in the editor | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/units/datasets/components/SourceEditorDialog/components/EditorFormItem.tsx#L24-L27 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | getFieldDocKey | const getFieldDocKey = (options: InputFormItemProps) => {
const {field_doc_key, name, sourceType} = options;
return field_doc_key || (`${sourceType}/${name}` as InputFormItemProps['field_doc_key']);
}; | // In case the key didn't come from the backup, but we must have a transfer | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/units/datasets/components/SourceEditorDialog/components/InputFormItem.tsx#L23-L26 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | getMessageText | function getMessageText() {
return {
CREATE_DATASET_MSGS: {
NOTIFICATION_SUCCESS: i18n('toast_create-dataset-msgs-success'),
NOTIFICATION_FAILURE: i18n('toast_create-dataset-msgs-failure'),
},
FIELD_DUPLICATED_MSGS: {
NOTIFICATION_SUCCESS: i18n('toast_field-duplicated-msgs-success'),
NOTIFICATION_FAILURE: '',
},
FIELD_REMOVE_MSGS: {
NOTIFICATION_SUCCESS: i18n('toast_field-remove-msgs-success'),
NOTIFICATION_FAILURE: '',
},
DATASET_SAVE_MSGS: {
NOTIFICATION_SUCCESS: i18n('toast_dataset-save-msgs-success'),
NOTIFICATION_FAILURE: i18n('toast_dataset-save-msgs-failure'),
},
DATASET_FETCH_PREVIEW_MSGS: {
NOTIFICATION_SUCCESS: '',
NOTIFICATION_FAILURE: i18n('toast_dataset-fetch-preview-msgs-failure'),
},
DATASET_VALIDATION_MSGS: {
NOTIFICATION_SUCCESS: '',
NOTIFICATION_FAILURE: i18n('toast_dataset-validation-msgs-failure'),
},
FETCH_TYPES_MSGS: {
NOTIFICATION_SUCCESS: '',
NOTIFICATION_FAILURE: i18n('toast_fetch-types-msgs-failure'),
},
};
} | // Empty lines are added to preserve the consistency of the object structure | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/units/datasets/helpers/dataset-error-helpers.ts#L7-L38 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | DialogField.componentDidMount | componentDidMount() {
const {item, extra, availableLabelModes = [], visualization, options} = this.props;
if (!item) {
return;
}
const visualizationId = visualization.id;
const {data_type, cast, formatting} = item;
const commonDataType = getCommonDataType(cast || data_type);
if (commonDataType === 'date') {
if (!item.format) {
switch (cast || data_type) {
case DATASET_FIELD_TYPES.DATE:
item.format = AVAILABLE_DATE_FORMATS[2];
break;
case DATASET_FIELD_TYPES.GENERICDATETIME:
item.format = AVAILABLE_DATETIME_FORMATS[5];
break;
case DATASET_FIELD_TYPES.DATETIMETZ:
item.format = AVAILABLE_DATETIMETZ_FORMATS[7];
break;
}
}
if (!item.grouping) {
item.grouping = 'none';
}
}
const defaultFormatting = isPseudoField(item) ? {} : getDefaultFormatting(item);
const preparedFormatting: CommonNumberFormattingOptions = {
...defaultFormatting,
...(formatting || {}),
};
if (extra && extra.label) {
const itemLabelMode =
(item.formatting as CommonNumberFormattingOptions)?.labelMode || '';
preparedFormatting.labelMode =
availableLabelModes.indexOf(itemLabelMode) === -1
? availableLabelModes[0]
: itemLabelMode;
}
this.setState({
item,
extra,
availableLabelModes,
options,
data_type,
cast,
originTitle:
item.fakeTitle && !item.title.startsWith('title-') ? item.title : undefined,
title: item.fakeTitle || item.title,
aggregation: item.aggregation,
format: item.format,
grouping: item.grouping,
hideLabelMode: (item.hideLabelMode as 'hide' | 'show') || HIDE_LABEL_MODES.DEFAULT,
formatting: preparedFormatting,
visualizationId,
});
} | // eslint-disable-next-line complexity | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/units/wizard/components/Dialogs/DialogField/DialogField.tsx#L184-L251 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | Utils.isRetina | static isRetina() {
let devicePixelRatio = 1;
if ('deviceXDPI' in window.screen && 'logicalXDPI' in window.screen) {
devicePixelRatio =
(window.screen as any).deviceXDPI / (window.screen as any).logicalXDPI;
} else if ('devicePixelRatio' in window) {
devicePixelRatio = window.devicePixelRatio;
}
return devicePixelRatio >= 1.3;
} | // TODO@types | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/utils/utils.ts#L122-L131 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | Utils.isEnabledFeature | static isEnabledFeature(featureName: string) {
const featureDynamicStatus = _get(DL.DYNAMIC_FEATURES, featureName);
if (typeof featureDynamicStatus !== 'undefined') {
return featureDynamicStatus;
}
return Boolean(_get(DL.FEATURES, featureName));
} | /** @deprecated use separate function ui/utils/isEnabledFeature */ | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/ui/utils/utils.ts#L215-L223 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | stateChangeListener | const stateChangeListener = (request: Request) => {
if (request.url().endsWith(CommonUrls.PartialCreateDashState)) {
stateUpdatesCount++;
}
}; | // counting state change calls | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/tests/opensource-suites/dash/selectors/groupButtonActions.test.ts#L188-L192 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | ControlActions.editSelectorBySettings | async editSelectorBySettings({
sourceType = DashTabItemControlSourceType.Manual,
...setting
}: SelectorSettings = {}) {
await this.dialogControl.waitForVisible();
if (sourceType) {
await this.dialogControl.sourceTypeSelect.click();
await this.dialogControl.sourceTypeSelect.selectListItemByQa(slct(sourceType));
}
if (sourceType === DashTabItemControlSourceType.Manual) {
if (setting.fieldName) {
await this.dialogControl.fieldName.fill(setting.fieldName);
}
// TODO: remove condition with innerText after removing addSelectorWithDefaultSettings
if (!setting.elementType || setting.elementType === 'list') {
await this.fillSelectSelectorItems({
items: setting.items,
defaultValue: setting.defaultValue,
});
}
} else {
if (setting.dataset?.link) {
await this.addDatasetByLink(setting.dataset?.link);
} else if (setting.dataset?.innerText || typeof setting.dataset?.idx === 'number') {
await this.dialogControl.selectDatasetButton.click();
await this.dialogControl.selectDatasetButton.navigationMinimal.selectListItem(
setting.dataset,
);
}
if (setting.datasetField?.innerText || typeof setting.datasetField?.idx === 'number') {
await this.dialogControl.datasetFieldSelector.click();
await this.dialogControl.datasetFieldSelector.selectListItem(setting.datasetField);
}
}
if (setting.elementType) {
await this.dialogControl.elementType.click();
await this.selectElementType(setting.elementType);
}
if (setting.appearance?.titlePlacement) {
await this.dialogControl.appearanceTitle.radioGroup.selectByName(
setting.appearance.titlePlacement,
);
}
if (setting.appearance?.title) {
await this.dialogControl.appearanceTitle.textInput.fill(setting.appearance.title);
}
if (typeof setting.appearance?.innerTitleEnabled === 'boolean') {
await this.dialogControl.appearanceInnerTitle.checkbox.toggle(
setting.appearance.innerTitleEnabled,
);
}
if (setting.appearance?.innerTitle) {
await this.dialogControl.appearanceInnerTitle.textInput.fill(
setting.appearance.innerTitle,
);
}
if (typeof setting.required === 'boolean') {
await this.dialogControl.requiredCheckbox.toggle(setting.required);
}
if (typeof setting.defaultValue === 'string' && setting.elementType === 'input') {
await this.page
.locator(`${slct(DialogControlQa.valueInput)} input`)
.fill(setting.defaultValue);
}
} | // eslint-disable-next-line complexity | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/tests/page-objects/dashboard/ControlActions.ts#L245-L320 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | ControlActions.addSelectorWithDefaultSettings | async addSelectorWithDefaultSettings(setting: SelectorSettings = {}) {
const defaultSettings: SelectorSettings = {
sourceType: DashTabItemControlSourceType.Dataset,
appearance: {titlePlacement: TitlePlacements.Left},
dataset: {idx: 0},
datasetField: {idx: 0},
};
await this.clickAddSelector();
await this.editSelectorBySettings({...defaultSettings, ...setting});
await this.page.click(slct(ControlQA.dialogControlApplyBtn));
} | /** @deprecated instead use addSelector */ | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/tests/page-objects/dashboard/ControlActions.ts#L323-L335 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | DashboardPage.entryNavigationDialogFillAndSave | async entryNavigationDialogFillAndSave(page: Page, entryName: string) {
// waiting for the save dialog to open
const entryDialog = await page.waitForSelector(slct('entry-dialog-content'));
const entryDialogInput = await entryDialog!.waitForSelector('[data-qa=path-select] input');
// filling in the input
await entryDialogInput!.fill(entryName);
// save
await page.click(slct(EntryDialogQA.Apply));
} | // Fill in the input with the name of the entity being created in the EntryDialog (the dialog that appears when saving entities) and click the "Create" button | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/tests/page-objects/dashboard/DashboardPage.ts#L161-L170 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | DashboardPage.getGridItem | async getGridItem(filter: {byHeader?: string; byEntiryId?: string} & LocatorOptionsType) {
let gridItemFilter: LocatorOptionsType;
if (filter.byHeader) {
gridItemFilter = {
has: this.page.locator(slct('widget-chart-tab', filter.byHeader)),
};
} else if (filter.byEntiryId) {
gridItemFilter = {
has: this.page.locator(slct(`chartkit-body-entry-${filter.byEntiryId}`)),
};
} else {
gridItemFilter = filter;
}
return this.page.locator(`.${DashkitQa.GRID_ITEM}`, gridItemFilter);
} | /**
* Selector for gridItem
*
* @param filter
* filter.byHeader - search by header text in tabs,
* if tab is not shown currently in tabs list then filter will fail
*
* filter.byEntiryId - filters only currently rendered charts entities
* if element is not presented in DOM selector will fail
*
* Otherwise default Locator options can be used: `has`, `hasNot`, `hasText`, `hasNotText`
*
* @return {Locator}
*/ | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/tests/page-objects/dashboard/DashboardPage.ts#L1017-L1033 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | DashboardPage.getGroupSelectorLabels | async getGroupSelectorLabels() {
const controlLabelLocator = this.page.locator(slct(ControlQA.controlLabel));
const firstLabelLocator = controlLabelLocator.first();
// if one of selectors is visible, group selector is loaded
await expect(firstLabelLocator).toBeVisible();
const allLabelsLocators = await controlLabelLocator.all();
const labels = await Promise.all(allLabelsLocators.map((locator) => locator.textContent()));
return labels;
} | // it cannot be used with single selectors as they have different loading times | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/tests/page-objects/dashboard/DashboardPage.ts#L1075-L1085 | c6c62518947d4384167d05e7c686eb880fef00f8 |
datalens-ui | github_2023 | datalens-tech | typescript | subscribeOnParameterUpdate | function subscribeOnParameterUpdate(page: Page) {
const consoleErrors: string[] = [];
page.on('console', (msg) => {
if (msg.type() === 'error') {
consoleErrors.push(msg.text());
}
});
const waitForResponsePromise = page.waitForResponse((response) => {
return response.finished().then(() => response.url().endsWith('/validateDataset'));
});
return {
consoleErrors,
waitForResponsePromise,
};
} | // Subscribe to the validateDataset request and to errors in the console. | https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/tests/suites/wizard/parameters/editParameter.test.ts#L12-L29 | c6c62518947d4384167d05e7c686eb880fef00f8 |
passkeys | github_2023 | teamhanko | typescript | createPasskeyProvider | function createPasskeyProvider({
tenant,
authorize: authorize,
id = DEFAULT_PROVIDER_ID,
}: {
tenant: Tenant;
/**
* Called after the JWT has been verified. The passed-in `userId` is the value of the `sub` claim of the JWT.
*
* The `userId` can safely be used to log the user in, e.g.:
*
* @example
* async function authorize({ userId }) {
* const user = await db.users.find(userId);
*
* if (!user) return null;
*
* return user;
* }
*/
authorize?: (data: { userId: string; token: JWTPayload }) => any;
id?: string;
}) {
const url = new URL(`${tenant.config.tenantId}/.well-known/jwks.json`, tenant.config.baseUrl);
const JWKS = createRemoteJWKSet(url);
// TODO call normally when this is fixed: https://github.com/nextauthjs/next-auth/issues/572
return {
id,
name: "Passkeys",
type: "credentials",
credentials: {
/**
* Token returned by `passkeyApi.login.finalize()`
*/
finalizeJWT: {
label: "JWT returned by /login/finalize",
type: "text",
},
} as any,
async authorize(credentials?: { finalizeJWT?: string }) {
const jwt = credentials?.finalizeJWT;
if (!jwt) throw new Error("No JWT provided");
let token: JWTVerifyResult;
try {
token = await jwtVerify(jwt, JWKS);
} catch (e) {
throw new PasskeyProviderError("JWT verification failed", ErrorCode.JWTVerificationFailed, e);
}
const userId = token.payload.sub;
if (!userId) {
throw new PasskeyProviderError("JWT does not contain a `sub` claim", ErrorCode.JWTSubClaimMissing);
}
// Make sure token is not older than TOKEN_MAX_AGE_SECONDS
// This can be removed in the future, when the JWT issued by the Passkey Server gets an `exp` claim.
// As of now, it only has aud, cred, iat, and sub, so jwtVerify() does not check for expiration.
const now = Date.now() / 1000;
if (token.payload.iat == null || now > token.payload.iat + TOKEN_MAX_AGE_SECONDS) {
throw new PasskeyProviderError("JWT has expired", ErrorCode.JWTExpired);
}
let user = { id: userId };
if (authorize) {
user = await authorize({ userId, token: token.payload });
}
return user;
},
} as const;
} | // TODO in future versions, remove `export const PasskeyProvider/Passkeys` and make this `export default function Passkeys` | https://github.com/teamhanko/passkeys/blob/1d194aba6ea8bd1fc4c293da2eaec96e64b301a2/packages/js/passkeys-next-auth-provider/index.ts#L25-L98 | 1d194aba6ea8bd1fc4c293da2eaec96e64b301a2 |
photography-website | github_2023 | ECarry | typescript | addViewTransition | const addViewTransition = (callback: () => void) => {
if (!document.startViewTransition) {
callback();
return;
}
document.startViewTransition(callback);
}; | // Utility function to handle view transitions | https://github.com/ECarry/photography-website/blob/e264f64e88083ffdcdb18f37c71a42ca45f5c125/src/components/theme/theme-switch.tsx#L8-L15 | e264f64e88083ffdcdb18f37c71a42ca45f5c125 |
photography-website | github_2023 | ECarry | typescript | handleApiError | const handleApiError = (error: unknown): never => {
if (error instanceof Error) {
throw new Error(`API Error: ${error.message}`);
}
throw new Error("An unknown error occurred");
}; | /**
* Helper function to handle API errors
* @param error - The error object caught in the try-catch block
* @throws {Error} - Throws an error with a descriptive message
*/ | https://github.com/ECarry/photography-website/blob/e264f64e88083ffdcdb18f37c71a42ca45f5c125/src/features/photos/api/use-create-photo.ts#L16-L21 | e264f64e88083ffdcdb18f37c71a42ca45f5c125 |
photography-website | github_2023 | ECarry | typescript | handleApiError | const handleApiError = (error: unknown): never => {
if (error instanceof Error) {
throw new Error(`API Error: ${error.message}`);
}
throw new Error("An unknown error occurred");
}; | /**
* Helper function to handle API errors
* @param error - The error object caught in the try-catch block
* @throws {Error} - Throws an error with a descriptive message
*/ | https://github.com/ECarry/photography-website/blob/e264f64e88083ffdcdb18f37c71a42ca45f5c125/src/features/photos/api/use-delete-photo.ts#L19-L24 | e264f64e88083ffdcdb18f37c71a42ca45f5c125 |
photography-website | github_2023 | ECarry | typescript | handleApiError | const handleApiError = (error: unknown): never => {
if (error instanceof Error) {
throw new Error(`API Error: ${error.message}`);
}
throw new Error("An unknown error occurred");
}; | /**
* Helper function to handle API errors
* @param error - The error object caught in the try-catch block
* @throws {Error} - Throws an error with a descriptive message
*/ | https://github.com/ECarry/photography-website/blob/e264f64e88083ffdcdb18f37c71a42ca45f5c125/src/features/photos/api/use-update-photo.ts#L19-L24 | e264f64e88083ffdcdb18f37c71a42ca45f5c125 |
photography-website | github_2023 | ECarry | typescript | NewPhotoSheet | const NewPhotoSheet = () => {
// Get new photo sheet state and handlers
const { isOpen, onClose } = useNewPhotoSheet();
return (
<Sheet open={isOpen} onOpenChange={onClose}>
<SheetContent className="min-w-[100%] lg:min-w-[50%]">
<SheetHeader>
<SheetTitle>New Photo</SheetTitle>
<SheetDescription></SheetDescription>
</SheetHeader>
{/* Form Container */}
<div className="h-[calc(100vh-6rem)] overflow-y-auto p-2">
<NewPhotoForm />
</div>
</SheetContent>
</Sheet>
);
}; | /**
* NewPhotoSheet Component
* A slide-out sheet component for creating new photo.
* Provides a form interface with accessibility features.
* @component
* @returns {JSX.Element} The new photo sheet component
*/ | https://github.com/ECarry/photography-website/blob/e264f64e88083ffdcdb18f37c71a42ca45f5c125/src/features/photos/components/new-photo-sheet.tsx#L23-L42 | e264f64e88083ffdcdb18f37c71a42ca45f5c125 |
photography-website | github_2023 | ECarry | typescript | handleApiError | const handleApiError = (error: unknown): never => {
if (error instanceof Error) {
throw new Error(`API Error: ${error.message}`);
}
throw new Error("An unknown error occurred");
}; | /**
* Helper function to handle API errors
* @param error - The error object caught in the try-catch block
* @throws {Error} - Throws an error with a descriptive message
*/ | https://github.com/ECarry/photography-website/blob/e264f64e88083ffdcdb18f37c71a42ca45f5c125/src/features/posts/api/use-create-post.ts#L14-L19 | e264f64e88083ffdcdb18f37c71a42ca45f5c125 |
photography-website | github_2023 | ECarry | typescript | handleApiError | const handleApiError = (error: unknown): never => {
if (error instanceof Error) {
throw new Error(`API Error: ${error.message}`);
}
throw new Error("An unknown error occurred");
}; | /**
* Helper function to handle API errors
* @param error - The error object caught in the try-catch block
* @throws {Error} - Throws an error with a descriptive message
*/ | https://github.com/ECarry/photography-website/blob/e264f64e88083ffdcdb18f37c71a42ca45f5c125/src/features/posts/api/use-delete-post.ts#L19-L24 | e264f64e88083ffdcdb18f37c71a42ca45f5c125 |
photography-website | github_2023 | ECarry | typescript | handleApiError | const handleApiError = (error: unknown): never => {
if (error instanceof Error) {
throw new Error(`API Error: ${error.message}`);
}
throw new Error("An unknown error occurred");
}; | /**
* Helper function to handle API errors
* @param error - The error object caught in the try-catch block
* @throws {Error} - Throws an error with a descriptive message
*/ | https://github.com/ECarry/photography-website/blob/e264f64e88083ffdcdb18f37c71a42ca45f5c125/src/features/posts/api/use-update-post.ts#L20-L25 | e264f64e88083ffdcdb18f37c71a42ca45f5c125 |
photography-website | github_2023 | ECarry | typescript | NewPostSheet | const NewPostSheet = () => {
// Get new post sheet state and handlers
const { isOpen, onClose } = useNewPostSheet();
return (
<Sheet open={isOpen} onOpenChange={onClose}>
<SheetContent className="min-w-[100%] lg:min-w-[50%]">
<SheetHeader>
<SheetTitle>New Post</SheetTitle>
<SheetDescription></SheetDescription>
</SheetHeader>
{/* Form Container */}
<div className="h-[calc(100vh-6rem)] overflow-y-auto p-2">
<NewPostForm />
</div>
</SheetContent>
</Sheet>
);
}; | /**
* NewPostSheet Component
* A slide-out sheet component for creating new post.
* Provides a form interface with accessibility features.
* @component
* @returns {JSX.Element} The new photo sheet component
*/ | https://github.com/ECarry/photography-website/blob/e264f64e88083ffdcdb18f37c71a42ca45f5c125/src/features/posts/components/new-post-sheet.tsx#L23-L42 | e264f64e88083ffdcdb18f37c71a42ca45f5c125 |
photography-website | github_2023 | ECarry | typescript | handleApiError | const handleApiError = (error: unknown): never => {
if (error instanceof Error) {
throw new Error(`API Error: ${error.message}`);
}
throw new Error("An unknown error occurred");
}; | /**
* Helper function to handle API errors
* @param error - The error object caught in the try-catch block
* @throws {Error} - Throws an error with a descriptive message
*/ | https://github.com/ECarry/photography-website/blob/e264f64e88083ffdcdb18f37c71a42ca45f5c125/src/features/r2/api/use-upload-photo.ts#L19-L24 | e264f64e88083ffdcdb18f37c71a42ca45f5c125 |
Xin-Admin | github_2023 | xinframe | typescript | Guide | const Guide: React.FC<Props> = (props) => {
const { name } = props;
return (
<Layout>
<Row>
<Typography.Title level={3} className={styles.title}>
欢迎使用 <strong>{name}</strong> !
</Typography.Title>
</Row>
</Layout>
);
}; | // 脚手架示例组件 | https://github.com/xinframe/Xin-Admin/blob/31c1276ed37d7b8f3499354b670b7ab7bafa99b0/web/src/components/Guide/Guide.tsx#L10-L21 | 31c1276ed37d7b8f3499354b670b7ab7bafa99b0 |
Xin-Admin | github_2023 | xinframe | typescript | collectKeys | const collectKeys = (data: TableData[]) => {
let keys: any = [];
data.forEach((item) => {
keys.push(item.id);
if (item.children) {
keys = keys.concat(collectKeys(item.children));
}
});
return keys;
}; | /**
* 递归收集所有 Key
* @param data
*/ | https://github.com/xinframe/Xin-Admin/blob/31c1276ed37d7b8f3499354b670b7ab7bafa99b0/web/src/components/XinTable/index.tsx#L65-L74 | 31c1276ed37d7b8f3499354b670b7ab7bafa99b0 |
Xin-Admin | github_2023 | xinframe | typescript | handleRemove | const handleRemove = async (selectedRows: TableData[]) => {
const hide = message.loading('正在删除');
if (!selectedRows || deleteShow === false){
message.warning('请选择需要删除的节点');
return
}
let ids = selectedRows.map(x => x.id)
deleteApi(tableApi+'/delete', { ids: ids.join() || '' }).then( res => {
if (res.success) {
message.success(res.msg);
actionRef.current?.reloadAndRest?.();
}else {
message.warning(res.msg);
}
}).finally(() => hide())
} | /**
* 删除节点
* @param selectedRows
*/ | https://github.com/xinframe/Xin-Admin/blob/31c1276ed37d7b8f3499354b670b7ab7bafa99b0/web/src/components/XinTable/index.tsx#L80-L95 | 31c1276ed37d7b8f3499354b670b7ab7bafa99b0 |
Xin-Admin | github_2023 | xinframe | typescript | deleteButton | const deleteButton = (record: TableData) => {
return (
<Access accessible={ accessName?access.buttonAccess(accessName+'.delete'):true }>
<Popconfirm
title="Delete the task"
description="你确定要删除这条数据吗?"
onConfirm={() => { handleRemove([record]) }}
okText="确认"
cancelText="取消"
>
<a>删除</a>
</Popconfirm>
</Access>
)
} | /**
* 删除按钮
* @param record
*/ | https://github.com/xinframe/Xin-Admin/blob/31c1276ed37d7b8f3499354b670b7ab7bafa99b0/web/src/components/XinTable/index.tsx#L101-L115 | 31c1276ed37d7b8f3499354b670b7ab7bafa99b0 |
Xin-Admin | github_2023 | xinframe | typescript | editButton | const editButton = (record: TableData) => {
return (
<Access accessible={ accessName?access.buttonAccess(accessName+'.edit'):true }>
<UpdateForm<TableData>
values={record}
columns={columns}
id={record.id}
api={tableApi+'/edit'}
tableRef={actionRef}
handleUpdate={handleUpdate}
/>
</Access>
)
} | /**
* 编辑按钮
* @param record
*/ | https://github.com/xinframe/Xin-Admin/blob/31c1276ed37d7b8f3499354b670b7ab7bafa99b0/web/src/components/XinTable/index.tsx#L121-L134 | 31c1276ed37d7b8f3499354b670b7ab7bafa99b0 |
Xin-Admin | github_2023 | xinframe | typescript | addButton | const addButton = () => {
return (
<Access accessible={ accessName?access.buttonAccess(accessName+'.add'):true}>
<CreateForm<TableData>
columns = { columns }
api={tableApi+'/add'}
tableRef={actionRef}
handleAdd={handleAdd}
addBefore={addBefore}
/>
</Access>
)
} | /**
* 新增按钮
*/ | https://github.com/xinframe/Xin-Admin/blob/31c1276ed37d7b8f3499354b670b7ab7bafa99b0/web/src/components/XinTable/index.tsx#L139-L151 | 31c1276ed37d7b8f3499354b670b7ab7bafa99b0 |
Xin-Admin | github_2023 | xinframe | typescript | defaultButton | const defaultButton = () => {
let operate: ProFormColumnsAndProColumns<TableData> = {
title: '操作',
dataIndex: 'option',
valueType: 'option',
render: (_, record) => (
<Space split={<Divider type="vertical" />} size={0}>
{editShow !== false && editButton(record)}
{deleteShow !== false && deleteButton(record)}
{operateRender !== undefined && operateRender(record)}
</Space>
),
} | /**
* 默认操作栏按钮
*/ | https://github.com/xinframe/Xin-Admin/blob/31c1276ed37d7b8f3499354b670b7ab7bafa99b0/web/src/components/XinTable/index.tsx#L156-L168 | 31c1276ed37d7b8f3499354b670b7ab7bafa99b0 |
Xin-Admin | github_2023 | xinframe | typescript | defaultToolBar | const defaultToolBar: ProTableProps<TableData, any>['toolBarRender'] = (action,rows) => {
let bar: ReactNode[] = [addShow !== false ? addButton() : '',];
if(allKeys.length && allKeys.length > dataSource.length) {
bar.push((
<>
<Button onClick={() => setExpandedRowKeys(allKeys)}>
展开全部
</Button>
<Button onClick={() => setExpandedRowKeys([])}>
折叠全部
</Button>
</>
))
}
if(props.toolBarRender) {
bar.push(props.toolBarRender(action,rows))
}
return bar
} | /**
* 工具栏默认渲染
*/ | https://github.com/xinframe/Xin-Admin/blob/31c1276ed37d7b8f3499354b670b7ab7bafa99b0/web/src/components/XinTable/index.tsx#L175-L193 | 31c1276ed37d7b8f3499354b670b7ab7bafa99b0 |
Xin-Admin | github_2023 | xinframe | typescript | footerBar | const footerBar = () => {
return selectedRowsState?.length > 0 && (
<FooterToolbar
extra={
<div>
已选择{' '}
<a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
项
</div>
}
>
<Access accessible={ accessName?access.buttonAccess(accessName+'.delete'):true }>
<Button
danger
onClick={async () => {
await handleRemove(selectedRowsState);
setSelectedRows([]);
actionRef.current?.reloadAndRest?.();
}}
>
批量删除
</Button>
{footerBarButton}
</Access>
</FooterToolbar>
)
} | /**
* 多选底部操作栏
*/ | https://github.com/xinframe/Xin-Admin/blob/31c1276ed37d7b8f3499354b670b7ab7bafa99b0/web/src/components/XinTable/index.tsx#L198-L224 | 31c1276ed37d7b8f3499354b670b7ab7bafa99b0 |
Xin-Admin | github_2023 | xinframe | typescript | setDictJson | const setDictJson = (data: DictDate[]): Map<string, DictItem[]> => {
let dictMap: Map<string, DictItem[]> = new Map();
data.forEach((dict: DictDate) => {
dictMap.set(dict.code, dict.dictItems.map(a => Object.assign(a, { type: dict.type })));
});
return dictMap;
} | /**
* 格式化字典: request
* @param data
*/ | https://github.com/xinframe/Xin-Admin/blob/31c1276ed37d7b8f3499354b670b7ab7bafa99b0/web/src/models/dictModel.ts#L26-L32 | 31c1276ed37d7b8f3499354b670b7ab7bafa99b0 |
Xin-Admin | github_2023 | xinframe | typescript | setDictEnum | const setDictEnum = (data: DictDate[]): Map<string,{[key: string]: ReactNode}> => {
let dictMap: Map<string, {[key: string]: ReactNode}> = new Map();
data.forEach((dict: DictDate) => {
let data: {[key: string]: ReactNode} = {};
dict.dictItems.forEach((a) => {
data[a.value] = a.label;
})
dictMap.set(dict.code, data);
});
return dictMap;
} | /**
* 格式化字典: Enum
* @param data
*/ | https://github.com/xinframe/Xin-Admin/blob/31c1276ed37d7b8f3499354b670b7ab7bafa99b0/web/src/models/dictModel.ts#L38-L48 | 31c1276ed37d7b8f3499354b670b7ab7bafa99b0 |
Xin-Admin | github_2023 | xinframe | typescript | refreshDict | const refreshDict = () => {
localStorage.removeItem('dictMap');
refresh();
} | /**
* 刷新字典
*/ | https://github.com/xinframe/Xin-Admin/blob/31c1276ed37d7b8f3499354b670b7ab7bafa99b0/web/src/models/dictModel.ts#L72-L75 | 31c1276ed37d7b8f3499354b670b7ab7bafa99b0 |
Xin-Admin | github_2023 | xinframe | typescript | getDictionaryData | const getDictionaryData = async (key: string): Promise<DictItem[]> => {
if (!dictData) {
let res = await refreshDictAsync();
return res.dictJson.has(key) ? res.dictJson.get(key)! : [];
}
return dictData.dictJson.has(key) ? dictData.dictJson.get(key)! : [];
}; | /**
* 通过键值获取字典
* @param key
*/ | https://github.com/xinframe/Xin-Admin/blob/31c1276ed37d7b8f3499354b670b7ab7bafa99b0/web/src/models/dictModel.ts#L81-L87 | 31c1276ed37d7b8f3499354b670b7ab7bafa99b0 |
Xin-Admin | github_2023 | xinframe | typescript | onSave | const onSave = async () => {
let data = {
'id': record.id,
'rule_ids': [...checkedKeys, ...halfCheckedKeys],
}
await Api.setGroupRule(data)
message.success('保存成功');
} | /**
* 保存权限规则
*/ | https://github.com/xinframe/Xin-Admin/blob/31c1276ed37d7b8f3499354b670b7ab7bafa99b0/web/src/pages/backend/Admin/Group/components/GroupRule.tsx#L38-L45 | 31c1276ed37d7b8f3499354b670b7ab7bafa99b0 |
Xin-Admin | github_2023 | xinframe | typescript | defaultUpdate | const defaultUpdate = async (fields: any) => {
await editApi('/admin/updatePassword', Object.assign({id:initialState!.currentUser.id},fields))
message.success('更新成功!');
} | /**
* 更新节点
* @param fields
*/ | https://github.com/xinframe/Xin-Admin/blob/31c1276ed37d7b8f3499354b670b7ab7bafa99b0/web/src/pages/backend/Admin/Setting/index.tsx#L134-L137 | 31c1276ed37d7b8f3499354b670b7ab7bafa99b0 |
Xin-Admin | github_2023 | xinframe | typescript | onSave | const onSave = async () => {
let data = {
'id': record.id,
'rule_ids': [...checkedKeys, ...halfCheckedKeys],
}
await Api.setGroupRule(data)
message.success('保存成功');
} | /**
* 保存权限规则
*/ | https://github.com/xinframe/Xin-Admin/blob/31c1276ed37d7b8f3499354b670b7ab7bafa99b0/web/src/pages/backend/User/Group/components/GroupRule.tsx#L38-L45 | 31c1276ed37d7b8f3499354b670b7ab7bafa99b0 |
Xin-Admin | github_2023 | xinframe | typescript | fixMenuItemIcon | const fixMenuItemIcon = (menus: MenuDataItem[]): MenuDataItem[] => {
menus.forEach((item) => {
if(item.icon && typeof item.icon === 'string' && allIcons[item.icon]){
if (item.icon.startsWith('icon-')) {
item.icon = <IconFont type={item.icon} className={item.icon} />;
} else {
item.icon = React.createElement(allIcons[item.icon]);
}
}
// TODO 二级菜单暂时不可通过此方式解决图标无法渲染问题,等待 Umi 官方更新
// if(item.children && item.children.length > 0){
// item.children = fixMenuItemIcon(item.children)
// }
});
return menus;
}; | // 从接口获取菜单时icon为string类型 | https://github.com/xinframe/Xin-Admin/blob/31c1276ed37d7b8f3499354b670b7ab7bafa99b0/web/src/utils/menuDataRender.tsx#L7-L23 | 31c1276ed37d7b8f3499354b670b7ab7bafa99b0 |
Xin-Admin | github_2023 | xinframe | typescript | refreshToken | const refreshToken = async (response: AxiosResponse) => {
try {
// 登录状态过期,刷新令牌并重新发起请求
let app = localStorage.getItem('app');
if( !app || app === 'api'){
let res = await refreshUserToken()
localStorage.setItem('x-user-token', res.data.token);
response.headers!.xUserToken = res.data.token;
// 重新发送请求
return await request(response.config.url!, response.config);
}else {
let res = await refreshAdminToken()
localStorage.setItem('x-token', res.data.token);
response.headers!.xToken = res.data.token;
// 重新发送请求
let data = await request(response.config.url!,response.config);
return Promise.resolve(data);
}
}catch (e) {
return Promise.reject(e);
}
} | /**
* 刷新Token
* @param response
*/ | https://github.com/xinframe/Xin-Admin/blob/31c1276ed37d7b8f3499354b670b7ab7bafa99b0/web/src/utils/request.ts#L24-L45 | 31c1276ed37d7b8f3499354b670b7ab7bafa99b0 |
insomnium | github_2023 | ArchGPT | typescript | checkFeature | function checkFeature(point: { latitude: any; longitude: any }) {
let feature;
// Check if there is already a feature object for the given point
for (let i = 0; i < featureList.length; i++) {
feature = featureList[i];
if (feature.location.latitude === point.latitude &&
feature.location.longitude === point.longitude) {
return feature;
}
}
const name = '';
feature = {
name: name,
location: point,
};
return feature;
} | /**
* Get a feature object at the given point, or creates one if it does not exist.
* @param {point} point The point to check
* @return {feature} The feature object at the point. Note that an empty name
* indicates no feature
*/ | https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia-smoke-test/server/grpc.ts#L36-L52 | 58e1bbe93aa035d248df1dd77dec29f2f4c0a327 |
insomnium | github_2023 | ArchGPT | typescript | getFeature | const getFeature: HandleCall<any, any> = (call: any, callback: any) => {
callback(null, checkFeature(call.request));
}; | /**
* getFeature request handler.
*/ | https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia-smoke-test/server/grpc.ts#L58-L60 | 58e1bbe93aa035d248df1dd77dec29f2f4c0a327 |
insomnium | github_2023 | ArchGPT | typescript | listFeatures | const listFeatures: HandleCall<any, any> = (call: any) => {
const lo = call.request.lo;
const hi = call.request.hi;
const left = Math.min(lo.longitude, hi.longitude);
const right = Math.max(lo.longitude, hi.longitude);
const top = Math.max(lo.latitude, hi.latitude);
const bottom = Math.min(lo.latitude, hi.latitude);
// For each feature, check if it is in the given bounding box
featureList.forEach(function(feature) {
if (feature.name === '') {
return;
}
if (feature.location.longitude >= left &&
feature.location.longitude <= right &&
feature.location.latitude >= bottom &&
feature.location.latitude <= top) {
call.write(feature);
}
});
call.end();
}; | /**
* listFeatures request handler.
*/ | https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia-smoke-test/server/grpc.ts#L66-L86 | 58e1bbe93aa035d248df1dd77dec29f2f4c0a327 |
insomnium | github_2023 | ArchGPT | typescript | getDistance | function getDistance(start: { latitude: number; longitude: number }, end: { latitude: number; longitude: number }) {
function toRadians(num: number) {
return num * Math.PI / 180;
}
const R = 6371000; // earth radius in metres
const lat1 = toRadians(start.latitude / COORD_FACTOR);
const lat2 = toRadians(end.latitude / COORD_FACTOR);
const lon1 = toRadians(start.longitude / COORD_FACTOR);
const lon2 = toRadians(end.longitude / COORD_FACTOR);
const deltalat = lat2 - lat1;
const deltalon = lon2 - lon1;
const a = Math.sin(deltalat / 2) * Math.sin(deltalat / 2) +
Math.cos(lat1) * Math.cos(lat2) *
Math.sin(deltalon / 2) * Math.sin(deltalon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
} | /**
* Calculate the distance between two points using the "haversine" formula.
* The formula is based on http://mathforum.org/library/drmath/view/51879.html.
* @param start The starting point
* @param end The end point
* @return The distance between the points in meters
*/ | https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia-smoke-test/server/grpc.ts#L95-L112 | 58e1bbe93aa035d248df1dd77dec29f2f4c0a327 |
insomnium | github_2023 | ArchGPT | typescript | recordRoute | const recordRoute: HandleCall<any, any> = (call: any, callback: any) => {
let pointCount = 0;
let featureCount = 0;
let distance = 0;
let previous: { latitude: number; longitude: number } | null = null;
// Start a timer
const startTime = process.hrtime();
call.on('data', function(point: any) {
pointCount += 1;
if (checkFeature(point).name !== '') {
featureCount += 1;
}
/* For each point after the first, add the incremental distance from the
* previous point to the total distance value */
if (previous != null) {
distance += getDistance(previous, point);
}
previous = point;
});
call.on('end', function() {
callback(null, {
point_count: pointCount,
feature_count: featureCount,
// Cast the distance to an integer
distance: distance | 0,
// End the timer
elapsed_time: process.hrtime(startTime)[0],
});
});
}; | /**
* recordRoute handler.
*/ | https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia-smoke-test/server/grpc.ts#L117-L146 | 58e1bbe93aa035d248df1dd77dec29f2f4c0a327 |
insomnium | github_2023 | ArchGPT | typescript | pointKey | function pointKey(point: { latitude: string; longitude: string }) {
return point.latitude + ' ' + point.longitude;
} | /**
* Turn the point into a dictionary key.
* @param {point} point The point to use
* @return {string} The key for an object
*/ | https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia-smoke-test/server/grpc.ts#L155-L157 | 58e1bbe93aa035d248df1dd77dec29f2f4c0a327 |
insomnium | github_2023 | ArchGPT | typescript | routeChat | const routeChat: HandleCall<any, any> = (call: any) => {
call.on('data', function(note: any) {
const key = pointKey(note.location);
/* For each note sent, respond with all previous notes that correspond to
* the same point */
if (routeNotes.hasOwnProperty(key)) {
// @ts-expect-error typescript
routeNotes[key].forEach(function(note: any) {
call.write(note);
});
} else {
// @ts-expect-error typescript
routeNotes[key] = [];
}
// Then add the new note to the list
// @ts-expect-error typescript
routeNotes[key].push(JSON.parse(JSON.stringify(note)));
});
call.on('end', function() {
call.end();
});
}; | /**
* routeChat handler. Receives a stream of message/location pairs, and responds
* with a stream of all previous messages at each of those locations.
* @param {Duplex} call The stream for incoming and outgoing messages
*/ | https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia-smoke-test/server/grpc.ts#L164-L185 | 58e1bbe93aa035d248df1dd77dec29f2f4c0a327 |
insomnium | github_2023 | ArchGPT | typescript | allowLocalhostImplicit | function allowLocalhostImplicit(oidc: Provider) {
const { invalidate: orig } = (oidc.Client as any).Schema.prototype;
(oidc.Client as any).Schema.prototype.invalidate = function invalidate(message: any, code: any) {
if (code === 'implicit-force-https' || code === 'implicit-forbid-localhost') {
return;
}
orig.call(this, message);
};
} | // Allow implicit to function despite the redirect address being http and localhost | https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia-smoke-test/server/oauth.ts#L256-L266 | 58e1bbe93aa035d248df1dd77dec29f2f4c0a327 |
insomnium | github_2023 | ArchGPT | typescript | Insomnium.send | async send(reqId: string | null = null) {
// Default to active request if nothing is specified
const requestId = reqId || this.activeRequestId;
if (!requestId) {
throw new Error('No selected request');
}
const result = await this.sendRequest(requestId);
return result;
} | /**
*
* @param reqId - request ID to send. Specifying nothing will send the active request
*/ | https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia-testing/src/run/insomnia.ts#L38-L48 | 58e1bbe93aa035d248df1dd77dec29f2f4c0a327 |
insomnium | github_2023 | ArchGPT | typescript | clean | const clean = (runnable: Runnable): TestResult => {
// @ts-expect-error this is what the source code originally had in mocha so I am not changing it
let err = runnable.err || {};
if (err instanceof Error) {
err = errorJSON(err);
}
return {
title: runnable.title,
fullTitle: runnable.fullTitle(),
file: runnable.file,
duration: runnable.duration,
// @ts-expect-error this is what the source code originally had in mocha so I am not changing it
currentRetry: runnable.currentRetry(),
err: cleanCycles(err),
};
}; | /**
* Return a plain-object representation of `test` free of cyclic properties etc.
*/ | https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia-testing/src/run/javascript-reporter.ts#L57-L73 | 58e1bbe93aa035d248df1dd77dec29f2f4c0a327 |
insomnium | github_2023 | ArchGPT | typescript | cleanCycles | const cleanCycles = (obj: Error) => {
const cache: JSON[] = [];
return JSON.parse(
JSON.stringify(obj, (_, value) => {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
// Instead of going in a circle, we'll print [object Object]
return '' + value;
}
cache.push(value);
}
return value;
}),
);
}; | /**
* Replaces any circular references inside `obj` with '[object Object]'
*/ | https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia-testing/src/run/javascript-reporter.ts#L78-L94 | 58e1bbe93aa035d248df1dd77dec29f2f4c0a327 |
insomnium | github_2023 | ArchGPT | typescript | errorJSON | const errorJSON = (error: Error) => {
return (Object.getOwnPropertyNames(error) as (keyof Error)[]).reduce((accumulator, key) => {
return {
...accumulator,
[key]: error[key],
};
}, {});
}; | /**
* Transform an Error object into a JSON object.
*/ | https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia-testing/src/run/javascript-reporter.ts#L99-L106 | 58e1bbe93aa035d248df1dd77dec29f2f4c0a327 |
insomnium | github_2023 | ArchGPT | typescript | runInternal | const runInternal = async <TReturn, TNetworkResponse>(
testSrc: string | string[],
options: InsomniaOptions<TNetworkResponse>,
reporter: Reporter | ReporterConstructor = 'spec',
extractResult: (runner: Mocha.Runner) => TReturn,
) => new Promise<TReturn>((resolve, reject) => {
const { bail, keepFile, testFilter } = options;
// Add global `insomnia` helper.
// This is the only way to add new globals to the Mocha environment as far as I can tell
// @ts-expect-error -- global hack
global.insomnia = new Insomnium(options);
// @ts-expect-error -- global hack
global.chai = chai;
const mocha: Mocha = new Mocha({
// ms * sec * min
timeout: 1000 * 60 * 1,
globals: ['insomnia', 'chai'],
bail,
reporter,
fgrep: testFilter,
});
const sources = Array.isArray(testSrc) ? testSrc : [testSrc];
sources.forEach(source => {
mocha.addFile(writeTempFile(source));
});
try {
const runner = mocha.run(() => {
resolve(extractResult(runner));
// Remove global since we don't need it anymore
// @ts-expect-error -- global hack
delete global.insomnia;
// @ts-expect-error -- global hack
delete global.chai;
if (keepFile && mocha.files.length) {
console.log(`Test files: ${JSON.stringify(mocha.files)}.`);
return;
}
// Clean up temp files
mocha.files.forEach(file => {
unlink(file, err => {
if (err) {
console.log('Failed to clean up test file', file, err);
}
});
});
});
} catch (err) {
reject(err);
}
}); | // declare var insomnia: Insomnium; | https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia-testing/src/run/run.ts#L13-L69 | 58e1bbe93aa035d248df1dd77dec29f2f4c0a327 |
insomnium | github_2023 | ArchGPT | typescript | writeTempFile | const writeTempFile = (sourceCode: string) => {
const root = join(tmpdir(), 'insomnia-testing');
fs.mkdirSync(root, { recursive: true });
const path = join(root, `${Math.random()}-test.ts`);
writeFileSync(path, sourceCode);
return path;
}; | /**
* Copy test to tmp dir and return the file path
*/ | https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia-testing/src/run/run.ts#L74-L81 | 58e1bbe93aa035d248df1dd77dec29f2f4c0a327 |
insomnium | github_2023 | ArchGPT | typescript | disableSpellcheckerDownload | const disableSpellcheckerDownload = () => {
electron.session.defaultSession.setSpellCheckerDictionaryDownloadURL(
'https://00.00/'
);
}; | /**
* There's no option that prevents Electron from fetching spellcheck dictionaries from Chromium's CDN and passing a non-resolving URL is the only known way to prevent it from fetching.
* see: https://github.com/electron/electron/issues/22995
* On macOS the OS spellchecker is used and therefore we do not download any dictionary files.
* This API is a no-op on macOS.
*/ | https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/main.development.ts#L73-L77 | 58e1bbe93aa035d248df1dd77dec29f2f4c0a327 |
insomnium | github_2023 | ArchGPT | typescript | _createModelInstances | async function _createModelInstances() {
await models.stats.get();
await models.settings.getOrCreate();
} | /*
Only one instance should exist of these models
On rare occasions, race conditions during initialization result in multiple being created
To avoid that, create them explicitly prior to any initialization steps
*/ | https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/main.development.ts#L217-L220 | 58e1bbe93aa035d248df1dd77dec29f2f4c0a327 |
insomnium | github_2023 | ArchGPT | typescript | getTsEnumOnlyWithNamedMembers | const getTsEnumOnlyWithNamedMembers = enumObj => {
let obj = {};
for (const member in enumObj) {
if (typeof enumObj[member] === 'number') {
obj = { ...obj, [member]: member };
}
}
return obj;
}; | /**
* This is just to make it easier to test
* node-libcurl Enum exports (CurlAuth, CurlCode, etc) are TypeScript enums, which are converted to an object with format:
* ```ts
* const myEnum = {
* EnumKey: 0,
* 0: EnumKey,
* }
* ```
* We only want the named members (non-number ones)
*/ | https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/__mocks__/@getinsomnia/node-libcurl.ts#L182-L192 | 58e1bbe93aa035d248df1dd77dec29f2f4c0a327 |
insomnium | github_2023 | ArchGPT | typescript | Metadata.constructor | constructor() {
// Do nothing
} | /**
* Mock Metadata class to avoid TypeError: grpc.Metadata is not a constructor
*/ | https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/__mocks__/@grpc/grpc-js.ts#L96-L98 | 58e1bbe93aa035d248df1dd77dec29f2f4c0a327 |
insomnium | github_2023 | ArchGPT | typescript | allTypes | const allTypes = () => Object.keys(db); | // ~~~~~~~ // | https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/common/database.ts#L668-L668 | 58e1bbe93aa035d248df1dd77dec29f2f4c0a327 |
insomnium | github_2023 | ArchGPT | typescript | _send | async function _send<T>(fnName: string, ...args: any[]) {
return new Promise<T>((resolve, reject) => {
const replyChannel = `db.fn.reply:${uuidv4()}`;
electron.ipcRenderer.send('db.fn', fnName, replyChannel, ...args);
electron.ipcRenderer.once(replyChannel, (_e, err, result: T) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
} | // ~~~~~~~ // | https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/common/database.ts#L713-L725 | 58e1bbe93aa035d248df1dd77dec29f2f4c0a327 |
insomnium | github_2023 | ArchGPT | typescript | _applyApiSpecName | async function _applyApiSpecName(workspace: Workspace) {
const apiSpec = await models.apiSpec.getByParentId(workspace._id);
if (apiSpec === null) {
return;
}
if (!apiSpec.fileName || apiSpec.fileName === models.apiSpec.init().fileName) {
await models.apiSpec.update(apiSpec, {
fileName: workspace.name,
});
}
} | /**
* This function ensures that apiSpec exists for each workspace
* If the filename on the apiSpec is not set or is the default initialized name
* It will apply the workspace name to it
*/ | https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/common/database.ts#L751-L762 | 58e1bbe93aa035d248df1dd77dec29f2f4c0a327 |
insomnium | github_2023 | ArchGPT | typescript | _repairBaseEnvironments | async function _repairBaseEnvironments(workspace: Workspace) {
const baseEnvironments = await database.find<Environment>(models.environment.type, {
parentId: workspace._id,
});
// Nothing to do here
if (baseEnvironments.length <= 1) {
return;
}
const chosenBase = baseEnvironments[0];
for (const baseEnvironment of baseEnvironments) {
if (baseEnvironment._id === chosenBase._id) {
continue;
}
chosenBase.data = Object.assign(baseEnvironment.data, chosenBase.data);
const subEnvironments = await database.find<Environment>(models.environment.type, {
parentId: baseEnvironment._id,
});
for (const subEnvironment of subEnvironments) {
await database.docUpdate(subEnvironment, {
parentId: chosenBase._id,
});
}
// Remove unnecessary base env
await database.remove(baseEnvironment);
}
// Update remaining base env
await database.update(chosenBase);
console.log(`[fix] Merged ${baseEnvironments.length} base environments under ${workspace.name}`);
} | /**
* This function repairs workspaces that have multiple base environments. Since a workspace
* can only have one, this function walks over all base environments, merges the data, and
* moves all children as well.
*/ | https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/common/database.ts#L769-L804 | 58e1bbe93aa035d248df1dd77dec29f2f4c0a327 |
insomnium | github_2023 | ArchGPT | typescript | _fixMultipleCookieJars | async function _fixMultipleCookieJars(workspace: Workspace) {
const cookieJars = await database.find<CookieJar>(models.cookieJar.type, {
parentId: workspace._id,
});
// Nothing to do here
if (cookieJars.length <= 1) {
return;
}
const chosenJar = cookieJars[0];
for (const cookieJar of cookieJars) {
if (cookieJar._id === chosenJar._id) {
continue;
}
for (const cookie of cookieJar.cookies) {
if (chosenJar.cookies.find(c => c.id === cookie.id)) {
continue;
}
chosenJar.cookies.push(cookie);
}
// Remove unnecessary jar
await database.remove(cookieJar);
}
// Update remaining jar
await database.update(chosenJar);
console.log(`[fix] Merged ${cookieJars.length} cookie jars under ${workspace.name}`);
} | /**
* This function repairs workspaces that have multiple cookie jars. Since a workspace
* can only have one, this function walks over all jars and merges them and their cookies
* together.
*/ | https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/common/database.ts#L811-L843 | 58e1bbe93aa035d248df1dd77dec29f2f4c0a327 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.