PromucFlow_constructor/app/client/src/utils/AppsmithUtils.tsx

186 lines
5.3 KiB
TypeScript
Raw Normal View History

2020-03-16 07:59:07 +00:00
import { ReduxAction } from "constants/ReduxActionConstants";
import { getAppsmithConfigs } from "configs";
2019-09-09 09:08:54 +00:00
import * as Sentry from "@sentry/browser";
import AnalyticsUtil from "./AnalyticsUtil";
import FontFaceObserver from "fontfaceobserver";
import FormControlRegistry from "./FormControlRegistry";
2019-11-25 05:07:27 +00:00
import { Property } from "api/ActionAPI";
import _ from "lodash";
import { ActionDataState } from "reducers/entityReducers/actionsReducer";
2020-03-23 12:40:17 +00:00
import * as log from "loglevel";
2020-03-27 12:46:29 +00:00
import { LogLevelDesc } from "loglevel";
import { providerBackgroundColors } from "constants/providerConstants";
2020-05-28 18:10:26 +00:00
import FeatureFlag from "utils/featureFlags";
2019-08-30 10:33:49 +00:00
export const createReducer = (
initialState: any,
2019-09-09 09:08:54 +00:00
handlers: { [type: string]: Function },
2019-08-30 10:33:49 +00:00
) => {
return function reducer(state = initialState, action: ReduxAction<any>) {
if (handlers.hasOwnProperty(action.type)) {
2019-09-09 09:08:54 +00:00
return handlers[action.type](state, action);
2019-08-30 10:33:49 +00:00
} else {
2019-09-09 09:08:54 +00:00
return state;
2019-08-30 10:33:49 +00:00
}
2019-09-09 09:08:54 +00:00
};
};
2019-08-30 10:33:49 +00:00
export const appInitializer = () => {
FormControlRegistry.registerFormControlBuilders();
const appsmithConfigs = getAppsmithConfigs();
2020-05-28 18:10:26 +00:00
FeatureFlag.initialize(appsmithConfigs.featureFlag);
Use injected configuration from Nginx at runtime instead of build time (#30) * Use envsubst and nginx templates to generate nginx configs which can substitute environment variables and inject into the index.html file * Fix path in dockerfile. Add .gitignore and .env.example files. Fix nginx-linux template. * Add all environment variables. Add prefix to all environment variables. Update scripts to attempt to substitute all environment variables with the prefix * Setup dockerfile to execute a bash script. use env.example for fetching environment variables in development * Toggle features based on injected configs. Fix nginx template substitution script. * Update env.example file * Remove debug code from start-nginx.sh * Fix nginx config templates by adding quotes by default. Fix sed regex to include numerals. Toggle social login buttons on Login page based on the config. * Update rapid api environment variable name. Toggle oauth buttons based on config in SignUp page. Update .env.example to be a union of server and client environment variables * Adding a Map disabled message on Map widget * Adding links to Privacy policy and TNC * Use REACT_APP_ env variables with higher priority over injected config variables for toggling features * Update netlify.toml by commenting out the build environment variables * Remove env variables not required by the client * Remove start-storybook entry from package.json * Fix netlify.toml. Fallback algolia configs * Add contexts to netlify.toml for successful deploys. Swith to using APPSMITH_MARKETPLACE_URL as the toggle for RapidAPI feature on the client. Remove comments in nginx config templates. Fix template used in dockerfile. Co-authored-by: Satbir Singh <apple@apples-MacBook-Pro.local> Co-authored-by: Satbir Singh <satbir121@gmail.com>
2020-07-07 10:22:17 +00:00
if (appsmithConfigs.sentry.enabled) {
Sentry.init({ dsn: appsmithConfigs.sentry.apiKey });
}
Use injected configuration from Nginx at runtime instead of build time (#30) * Use envsubst and nginx templates to generate nginx configs which can substitute environment variables and inject into the index.html file * Fix path in dockerfile. Add .gitignore and .env.example files. Fix nginx-linux template. * Add all environment variables. Add prefix to all environment variables. Update scripts to attempt to substitute all environment variables with the prefix * Setup dockerfile to execute a bash script. use env.example for fetching environment variables in development * Toggle features based on injected configs. Fix nginx template substitution script. * Update env.example file * Remove debug code from start-nginx.sh * Fix nginx config templates by adding quotes by default. Fix sed regex to include numerals. Toggle social login buttons on Login page based on the config. * Update rapid api environment variable name. Toggle oauth buttons based on config in SignUp page. Update .env.example to be a union of server and client environment variables * Adding a Map disabled message on Map widget * Adding links to Privacy policy and TNC * Use REACT_APP_ env variables with higher priority over injected config variables for toggling features * Update netlify.toml by commenting out the build environment variables * Remove env variables not required by the client * Remove start-storybook entry from package.json * Fix netlify.toml. Fallback algolia configs * Add contexts to netlify.toml for successful deploys. Swith to using APPSMITH_MARKETPLACE_URL as the toggle for RapidAPI feature on the client. Remove comments in nginx config templates. Fix template used in dockerfile. Co-authored-by: Satbir Singh <apple@apples-MacBook-Pro.local> Co-authored-by: Satbir Singh <satbir121@gmail.com>
2020-07-07 10:22:17 +00:00
if (appsmithConfigs.hotjar.enabled) {
const { id, sv } = appsmithConfigs.hotjar;
AnalyticsUtil.initializeHotjar(id, sv);
}
if (appsmithConfigs.segment.enabled) {
Use injected configuration from Nginx at runtime instead of build time (#30) * Use envsubst and nginx templates to generate nginx configs which can substitute environment variables and inject into the index.html file * Fix path in dockerfile. Add .gitignore and .env.example files. Fix nginx-linux template. * Add all environment variables. Add prefix to all environment variables. Update scripts to attempt to substitute all environment variables with the prefix * Setup dockerfile to execute a bash script. use env.example for fetching environment variables in development * Toggle features based on injected configs. Fix nginx template substitution script. * Update env.example file * Remove debug code from start-nginx.sh * Fix nginx config templates by adding quotes by default. Fix sed regex to include numerals. Toggle social login buttons on Login page based on the config. * Update rapid api environment variable name. Toggle oauth buttons based on config in SignUp page. Update .env.example to be a union of server and client environment variables * Adding a Map disabled message on Map widget * Adding links to Privacy policy and TNC * Use REACT_APP_ env variables with higher priority over injected config variables for toggling features * Update netlify.toml by commenting out the build environment variables * Remove env variables not required by the client * Remove start-storybook entry from package.json * Fix netlify.toml. Fallback algolia configs * Add contexts to netlify.toml for successful deploys. Swith to using APPSMITH_MARKETPLACE_URL as the toggle for RapidAPI feature on the client. Remove comments in nginx config templates. Fix template used in dockerfile. Co-authored-by: Satbir Singh <apple@apples-MacBook-Pro.local> Co-authored-by: Satbir Singh <satbir121@gmail.com>
2020-07-07 10:22:17 +00:00
AnalyticsUtil.initializeSegment(appsmithConfigs.segment.apiKey);
2019-08-30 10:33:49 +00:00
}
2020-05-28 18:10:26 +00:00
2020-03-27 12:46:29 +00:00
log.setLevel(getEnvLogLevel(appsmithConfigs.logLevel));
2020-03-23 12:40:17 +00:00
2019-09-06 11:40:00 +00:00
const textFont = new FontFaceObserver("DM Sans");
2019-09-09 09:08:54 +00:00
textFont
.load()
.then(() => {
document.body.className += "fontLoaded";
})
.catch(err => {
console.log(err);
});
};
export const mapToPropList = (map: Record<string, string>): Property[] => {
return _.map(map, (value, key) => {
return { key: key, value: value };
});
};
2020-01-24 09:54:40 +00:00
export const getNextEntityName = (prefix: string, existingNames: string[]) => {
const regex = new RegExp(`^${prefix}(\\d+)$`);
2020-01-24 09:54:40 +00:00
const usedIndices: number[] = existingNames.map(name => {
if (name && regex.test(name)) {
const matches = name.match(regex);
const ind =
matches && Array.isArray(matches) ? parseInt(matches[1], 10) : 0;
return Number.isNaN(ind) ? 0 : ind;
}
return 0;
}) as number[];
2020-01-24 09:54:40 +00:00
const lastIndex = Math.max(...usedIndices, ...[0]);
return prefix + (lastIndex + 1);
};
2019-11-07 11:17:53 +00:00
export const getDuplicateName = (prefix: string, existingNames: string[]) => {
const trimmedPrefix = prefix.replace(/ /g, "");
const regex = new RegExp(`^${trimmedPrefix}(\\d+)$`);
const usedIndices: number[] = existingNames.map(name => {
if (name && regex.test(name)) {
const matches = name.match(regex);
const ind =
matches && Array.isArray(matches) ? parseInt(matches[1], 10) : 0;
return Number.isNaN(ind) ? 0 : ind;
}
return 0;
}) as number[];
const lastIndex = Math.max(...usedIndices, ...[0]);
return trimmedPrefix + `_${lastIndex + 1}`;
};
export const createNewApiName = (actions: ActionDataState, pageId: string) => {
const pageApiNames = actions
.filter(a => a.config.pageId === pageId)
.map(a => a.config.name);
return getNextEntityName("Api", pageApiNames);
};
2019-12-16 08:49:10 +00:00
export const noop = () => {
console.log("noop");
};
2020-03-16 07:59:07 +00:00
export const createNewQueryName = (
queries: ActionDataState,
pageId: string,
) => {
const pageApiNames = queries
.filter(a => a.config.pageId === pageId)
.map(a => a.config.name);
const newName = getNextEntityName("Query", pageApiNames);
return newName;
};
2020-03-16 07:59:07 +00:00
export const convertToString = (value: any): string => {
if (_.isUndefined(value)) {
return "";
}
if (_.isObject(value)) {
return JSON.stringify(value, null, 2);
}
if (_.isString(value)) return value;
return value.toString();
};
2020-03-27 12:46:29 +00:00
const getEnvLogLevel = (configLevel: LogLevelDesc): LogLevelDesc => {
let logLevel = configLevel;
const localStorageLevel = localStorage.getItem("logLevel") as LogLevelDesc;
if (localStorageLevel) logLevel = localStorageLevel;
return logLevel;
};
export const getInitialsAndColorCode = (fullName: any): string[] => {
let inits = "";
// if name contains space. eg: "Full Name"
if (fullName.includes(" ")) {
const namesArr = fullName.split(" ");
let initials = namesArr.map((name: string) => name.charAt(0));
initials = initials.join("").toUpperCase();
inits = initials.slice(0, 2);
} else {
// handle for camelCase
const str = fullName.replace(/([a-z])([A-Z])/g, "$1 $2");
const namesArr = str.split(" ");
let initials = namesArr.map((name: string) => name.charAt(0));
initials = initials.join("").toUpperCase();
inits = initials.slice(0, 2);
}
const colorCode = getColorCode(inits);
return [inits, colorCode];
};
const getColorCode = (initials: string): string => {
let asciiSum = 0;
for (let i = 0; i < initials.length; i++) {
asciiSum += initials[i].charCodeAt(0);
}
return providerBackgroundColors[asciiSum % providerBackgroundColors.length];
};
2020-05-28 18:10:26 +00:00
export function hexToRgb(
hex: string,
): {
r: number;
g: number;
b: number;
} {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result
? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16),
}
: {
r: -1,
g: -1,
b: -1,
};
}