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

414 lines
11 KiB
TypeScript
Raw Normal View History

import { getAppsmithConfigs } from "@appsmith/configs";
import * as Sentry from "@sentry/react";
2019-09-09 09:08:54 +00:00
import AnalyticsUtil from "./AnalyticsUtil";
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";
feat: Migrate design system components import to design-system repo - I (#15562) * Icon component deleted and changed the imports in refrence places * design system package version changed * import changes * Delete TextInput.tsx * Change imports * Change single named import * Update package * Update package * Delete ScrollIndicator.tsx * Change imports * Icon import completed * Event type added * Changed Button component imports * import change button * Button onclick type fix * Label with Tooltip import changes * Changed breadcrumbs import * EmojiPicker and Emoji Reaction import changes * AppIcon import change * import bug fix * Menu Item import chnages * Icon selector imports changed * Delete LabelWithTooltip.tsx * Change imports across the app * Update package version * Update version number for design-system * Delete Checkbox.tsx * Remove the exports * Add lock file for ds package update * Change imports * default import -> named * Update release version * Make arg type explicit * Updated design-system to latest release * Missing file mysteriously comes back and is updated accordingly * changes design-system package version * Add types to arguments in the onChange for text input * onBlur type fix * Search component in property pane * WDS button changes reverted * package version bumped * conflict fix * Remove Dropdown, change imports * Category import fix * fix: table icon size import * Bump version of design system package * Yarn lock Co-authored-by: Tanvi Bhakta <tanvibhakta@gmail.com>
2022-08-22 05:09:39 +00:00
import { AppIconCollection, AppIconName } from "design-system";
import { ERROR_CODES } from "@appsmith/constants/ApiConstants";
refactor: admin settings (#9906) * refactor admin settings feature * separated save-restart bar to separate component * created new CE dir to facilitate code split * created separate ee dir and exporting everything we have in ce file. * little mod * minor fix * splitting settings types config * using object literals for category types instead of enums * CE: support use of component for each category * minor style fix * authentication page UI changes implemented * github signup doc url added back * removed comments * routing updates * made subcategories listing in left pane optional * added muted saml to auth listing * added breadcrumbs and enabled button * created separate component for auth page and auth config * added callout and disconnect components * updated breadcrumbs component * minor updates to common components * updated warning callout and added icon * ce: test cases fixed * updated test file name * warning banner callout added on auth page * updated callout banner for form login * CE: Split config files * CE: moved the window declaration in EE file as its dependency will be updated in EE * CE: Splitting ApiConstants and SocialLogin constants * CE: split login page * CE: moved getSocialLoginButtonProps func to EE file as it's dependencies will be updated in EE * added key icon * CE: created a factory class to share social auths list * Minor style fix for social btns * Updated the third party auth styles * Small fixes to styling * ce: splitting forms constants * breadcrumbs implemented for all pages in admin settings * Settings breadcrumbs separated * splitted settings breadcrumbs between ce and ee * renamed default import * minor style fix * added login form config. * updated login/signup pages to use form login disabled config * removed common functionality outside * implemented breadcrumb component from scratch without using blueprint * removed unwanted code * Small style update * updated breadcrumb categories file name and breadcrumb icon * added cypress tests for admin settings auth page * added comments * update locator for upgrade button * added link for intercom on upgrade button * removed unnecessary file * minor style fix * style fix for auth option cards * split messages constant * fixed imports for message constants splitting. * added message constants * updated unit test cases * fixed messages import in cypress index * fixed messages import again, cypress fails to read re-exported objs. * added OIDC auth method on authentication page * updated import statements from ee to @appsmith * removed dead code * updated read more link UI * PR comments fixes * some UI fixes * used color and fonts from theme * fixed some imports * fixed some imports * removed warning imports * updated OIDC logo and auth method desc copies * css changes * css changes * css changes * updated cypress test for breadcrumb * moved callout component to ads as calloutv2 * UI changes for form fields * updated css for spacing between form fields * added sub-text on auth pages * added active class for breadcrumb item * added config for disable signup toggle and fixed UI issues of restart banner * fixed admin settings page bugs * assigned true as default state for signup * fixed messages import statements * updated code for PR comments related suggestions * reverted file path change in cypress support * updated cypress test * updated cypress test Co-authored-by: Ankita Kinger <ankita@appsmith.com>
2022-02-11 18:08:46 +00:00
import { createMessage, ERROR_500 } from "@appsmith/constants/messages";
import { JSCollectionData } from "reducers/entityReducers/jsActionsReducer";
import { osName } from "react-device-detect";
2019-08-30 10:33:49 +00:00
export const initializeAnalyticsAndTrackers = () => {
const appsmithConfigs = getAppsmithConfigs();
2020-05-28 18:10:26 +00:00
try {
if (appsmithConfigs.sentry.enabled && !window.Sentry) {
window.Sentry = Sentry;
Sentry.init({
...appsmithConfigs.sentry,
beforeBreadcrumb(breadcrumb) {
if (
breadcrumb.category === "console" &&
breadcrumb.level !== "error"
) {
return null;
}
if (breadcrumb.category === "sentry.transaction") {
return null;
}
if (breadcrumb.category === "redux.action") {
if (
breadcrumb.data &&
breadcrumb.data.type === "SET_EVALUATED_TREE"
) {
breadcrumb.data = undefined;
}
}
return breadcrumb;
},
});
}
} catch (e) {
log.error(e);
}
try {
if (appsmithConfigs.smartLook.enabled && !(window as any).smartlook) {
const { id } = appsmithConfigs.smartLook;
AnalyticsUtil.initializeSmartLook(id);
}
if (appsmithConfigs.segment.enabled && !(window as any).analytics) {
if (appsmithConfigs.segment.apiKey) {
// This value is only enabled for Appsmith's cloud hosted version. It is not set in self-hosted environments
AnalyticsUtil.initializeSegment(appsmithConfigs.segment.apiKey);
} else if (appsmithConfigs.segment.ceKey) {
// This value is set in self-hosted environments. But if the analytics are disabled, it's never used.
AnalyticsUtil.initializeSegment(appsmithConfigs.segment.ceKey);
}
2020-11-05 16:51:22 +00:00
}
} catch (e) {
Sentry.captureException(e);
log.error(e);
2019-08-30 10:33:49 +00:00
}
2019-09-09 09:08:54 +00:00
};
export const mapToPropList = (map: Record<string, string>): Property[] => {
return _.map(map, (value, key) => {
return { key: key, value: value };
});
};
export const INTERACTION_ANALYTICS_EVENT = "INTERACTION_ANALYTICS_EVENT";
export type InteractionAnalyticsEventDetail = {
key?: string;
propertyName?: string;
propertyType?: string;
widgetType?: string;
};
export const interactionAnalyticsEvent = (
detail: InteractionAnalyticsEventDetail = {},
) =>
new CustomEvent(INTERACTION_ANALYTICS_EVENT, {
bubbles: true,
detail,
});
export function emitInteractionAnalyticsEvent<T extends HTMLElement>(
element: T | null,
args: Record<string, unknown>,
) {
element?.dispatchEvent(interactionAnalyticsEvent(args));
}
export const DS_EVENT = "DS_EVENT";
export enum DSEventTypes {
KEYPRESS = "KEYPRESS",
}
export type DSEventDetail = {
component: string;
event: DSEventTypes;
meta: Record<string, unknown>;
};
export function createDSEvent(detail: DSEventDetail) {
return new CustomEvent(DS_EVENT, {
bubbles: true,
detail,
});
}
export function emitDSEvent<T extends HTMLElement>(
element: T | null,
args: DSEventDetail,
) {
element?.dispatchEvent(createDSEvent(args));
}
export const getNextEntityName = (
prefix: string,
existingNames: string[],
startWithoutIndex?: boolean,
) => {
const regex = new RegExp(`^${prefix}(\\d+)$`);
2020-12-24 04:32:25 +00:00
const usedIndices: number[] = existingNames.map((name) => {
2020-01-24 09:54:40 +00:00
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]);
if (startWithoutIndex && lastIndex === 0) {
const exactMatchFound = existingNames.some(
(name) => prefix && name.trim() === prefix.trim(),
);
if (!exactMatchFound) {
return prefix.trim();
}
}
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+)$`);
2020-12-24 04:32:25 +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[];
const lastIndex = Math.max(...usedIndices, ...[0]);
return trimmedPrefix + `_${lastIndex + 1}`;
};
export const createNewApiName = (actions: ActionDataState, pageId: string) => {
const pageApiNames = actions
2020-12-24 04:32:25 +00:00
.filter((a) => a.config.pageId === pageId)
.map((a) => a.config.name);
return getNextEntityName("Api", pageApiNames);
};
feat: JS Editor (#6003) * Changes to add js plugin * routes+reducer+create template * added debugger to js editor page * entity explorer changes * create js function * added copy, move and delete action * added js plugin * added existing js functions to data tree * removed actionconfig for js collection * new js function added to data tree and entity as well * parsing flow added * changes to data tree * parse and update js functions * small changes for def creator for js action * create delete modified * small changes for update * update flow change * entity properties added * removed linting errors * small changes in entity explorer * changes for update * move, copy implementation * conflict resolved * changes for dependecy map creation * Only make the variables the binding paths * Basic eval sync working * Minor fixes * removed unwanted code * entity props and autocomplete * saving in progress show * redirection fix after delete js action * removed unnecessary line * Fixing merge conflict * added sample body * removed dummy data and added plugin Type * few PR comments fixed * automplete fix * few more PR comments fix * PR commnets fix * move and copy api change * js colleciton name refactor & 'move to page' changes & search * view changes * autocomplete added for js collections * removing till async is implemented * small changes * separate js pane response view * Executing functions * js collection to js objects * entity explorer issue and resolve action on page switch * removed unused line * small color fix * js file icon added * added js action to property pane * Property pane changes for actions * property pane changes for js functions * showing syntax error for now * actions sorted in response tab * added js objects to slash and recent entitties * enabling this to be used inside of function * eval fix * feature flag changes for entity explorer and property pane * debugger changes * copy bug fix * small changes for eval * debugger bug fix * chnaged any to specific types * error in console fix * icons update * fixed test case * test case fix * non empty check for functions * evaluate test case fix * added new icons * text change * updated time for debounce for trial * after release mereg * changed icon * after merge * PR comments simple * fixed PR comments - redux form, settings remove * js object interface changes * name refactor * export default change * delete resolve actions chnage * after merge * adding execute fn as 3rd option and removed create new js function * issue 7054 fixed - app crash * execute function on response tab changes * refactor function name part 1 * refactor of js function name * try catch added refactor * test fix * not used line removed * test cases locator fixed Co-authored-by: Nidhi <nidhi.nair93@gmail.com> Co-authored-by: hetunandu <hetu@appsmith.com>
2021-09-08 17:32:22 +00:00
export const createNewJSFunctionName = (
jsActions: JSCollectionData[],
feat: JS Editor (#6003) * Changes to add js plugin * routes+reducer+create template * added debugger to js editor page * entity explorer changes * create js function * added copy, move and delete action * added js plugin * added existing js functions to data tree * removed actionconfig for js collection * new js function added to data tree and entity as well * parsing flow added * changes to data tree * parse and update js functions * small changes for def creator for js action * create delete modified * small changes for update * update flow change * entity properties added * removed linting errors * small changes in entity explorer * changes for update * move, copy implementation * conflict resolved * changes for dependecy map creation * Only make the variables the binding paths * Basic eval sync working * Minor fixes * removed unwanted code * entity props and autocomplete * saving in progress show * redirection fix after delete js action * removed unnecessary line * Fixing merge conflict * added sample body * removed dummy data and added plugin Type * few PR comments fixed * automplete fix * few more PR comments fix * PR commnets fix * move and copy api change * js colleciton name refactor & 'move to page' changes & search * view changes * autocomplete added for js collections * removing till async is implemented * small changes * separate js pane response view * Executing functions * js collection to js objects * entity explorer issue and resolve action on page switch * removed unused line * small color fix * js file icon added * added js action to property pane * Property pane changes for actions * property pane changes for js functions * showing syntax error for now * actions sorted in response tab * added js objects to slash and recent entitties * enabling this to be used inside of function * eval fix * feature flag changes for entity explorer and property pane * debugger changes * copy bug fix * small changes for eval * debugger bug fix * chnaged any to specific types * error in console fix * icons update * fixed test case * test case fix * non empty check for functions * evaluate test case fix * added new icons * text change * updated time for debounce for trial * after release mereg * changed icon * after merge * PR comments simple * fixed PR comments - redux form, settings remove * js object interface changes * name refactor * export default change * delete resolve actions chnage * after merge * adding execute fn as 3rd option and removed create new js function * issue 7054 fixed - app crash * execute function on response tab changes * refactor function name part 1 * refactor of js function name * try catch added refactor * test fix * not used line removed * test cases locator fixed Co-authored-by: Nidhi <nidhi.nair93@gmail.com> Co-authored-by: hetunandu <hetu@appsmith.com>
2021-09-08 17:32:22 +00:00
pageId: string,
) => {
const pageJsFunctionNames = jsActions
.filter((a) => a.config.pageId === pageId)
.map((a) => a.config.name);
return getNextEntityName("JSObject", pageJsFunctionNames);
};
2019-12-16 08:49:10 +00:00
export const noop = () => {
log.debug("noop");
2019-12-16 08:49:10 +00:00
};
2020-03-16 07:59:07 +00:00
export const stopEventPropagation = (e: any) => {
e.stopPropagation();
};
export const createNewQueryName = (
queries: ActionDataState,
pageId: string,
) => {
const pageApiNames = queries
2020-12-24 04:32:25 +00:00
.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
Homepage redesign with themes (#482) * Updating homepage body color * WIP: Fixing scrolls and adding anchors * Removing divider from bottom of the page. * Adding hover background color to app card * Changing edit and launch icons. * Fixing app name paddding in card. * Fixing workspaces overflow * Adding right padding to applications view * Adding share icon to share btn * Fixing Application card styles. * Fixing text decoration in button. * Adding new workspace button * Fixing new workspace and new app styles. * Adding icon sizes. * Fixing Org Name and Org settings menu. * Application menu working * Fixing overlay visibility on app card * Fixing settings page content width. * Fixing workspace icon * Changing app card colors. * Removing debugger * Adding app icon. * Fixing the spaces in application card * Adding storybook-static folder to gitignore. * Adding other storybook files. * Adding menu items for app * Removing cypress selector from text. * Menu width issue fixed * Default app icon color added * Removing hardcoded colors * Removing hardcoded colors. * Light Mode on! * Showing correct icon and color in menu * Update color working properly. * Updating appIcon * Editable text working. * Adding validator * Adding edit permissions to menu * Removing box shadow on app card. * Fixing context menu fill color * Fixing Menu hover issues. * Fixing menu open close hover issues. * Fixing settings pages * Changed Workspace to org. * Fix: State management in EditableText Component (#540) * Error state height is fixed as per design * savingState prop condition fixed * Fixing createnew. * Fixing saving state for application card. * Fixed application card editable text error. * Fixing issue caused during merge. * Fixing tests in create org. * Removing commented code. * Removing unwanted vars. * Fixing delete duplicate tests. * Latest color palette. * Fixing form and table widget. * Removing switcher from header * Removing unused files * Fixing app card context dropdown * Show overlay fix * Adding localStorage support to theme. * Making dark mode the default. Co-authored-by: Rohit Kumawat <rohit.kumawat@primathon.in>
2020-09-16 11:50:47 +00:00
export const getInitialsAndColorCode = (
fullName: any,
colorPalette: string[],
): string[] => {
let inits = "";
// if name contains space. eg: "Full Name"
2021-06-16 18:36:34 +00:00
if (fullName && 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
2021-06-16 18:36:34 +00:00
const str = fullName ? 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);
}
Homepage redesign with themes (#482) * Updating homepage body color * WIP: Fixing scrolls and adding anchors * Removing divider from bottom of the page. * Adding hover background color to app card * Changing edit and launch icons. * Fixing app name paddding in card. * Fixing workspaces overflow * Adding right padding to applications view * Adding share icon to share btn * Fixing Application card styles. * Fixing text decoration in button. * Adding new workspace button * Fixing new workspace and new app styles. * Adding icon sizes. * Fixing Org Name and Org settings menu. * Application menu working * Fixing overlay visibility on app card * Fixing settings page content width. * Fixing workspace icon * Changing app card colors. * Removing debugger * Adding app icon. * Fixing the spaces in application card * Adding storybook-static folder to gitignore. * Adding other storybook files. * Adding menu items for app * Removing cypress selector from text. * Menu width issue fixed * Default app icon color added * Removing hardcoded colors * Removing hardcoded colors. * Light Mode on! * Showing correct icon and color in menu * Update color working properly. * Updating appIcon * Editable text working. * Adding validator * Adding edit permissions to menu * Removing box shadow on app card. * Fixing context menu fill color * Fixing Menu hover issues. * Fixing menu open close hover issues. * Fixing settings pages * Changed Workspace to org. * Fix: State management in EditableText Component (#540) * Error state height is fixed as per design * savingState prop condition fixed * Fixing createnew. * Fixing saving state for application card. * Fixed application card editable text error. * Fixing issue caused during merge. * Fixing tests in create org. * Removing commented code. * Removing unwanted vars. * Fixing delete duplicate tests. * Latest color palette. * Fixing form and table widget. * Removing switcher from header * Removing unused files * Fixing app card context dropdown * Show overlay fix * Adding localStorage support to theme. * Making dark mode the default. Co-authored-by: Rohit Kumawat <rohit.kumawat@primathon.in>
2020-09-16 11:50:47 +00:00
const colorCode = getColorCode(inits, colorPalette);
return [inits, colorCode];
};
Homepage redesign with themes (#482) * Updating homepage body color * WIP: Fixing scrolls and adding anchors * Removing divider from bottom of the page. * Adding hover background color to app card * Changing edit and launch icons. * Fixing app name paddding in card. * Fixing workspaces overflow * Adding right padding to applications view * Adding share icon to share btn * Fixing Application card styles. * Fixing text decoration in button. * Adding new workspace button * Fixing new workspace and new app styles. * Adding icon sizes. * Fixing Org Name and Org settings menu. * Application menu working * Fixing overlay visibility on app card * Fixing settings page content width. * Fixing workspace icon * Changing app card colors. * Removing debugger * Adding app icon. * Fixing the spaces in application card * Adding storybook-static folder to gitignore. * Adding other storybook files. * Adding menu items for app * Removing cypress selector from text. * Menu width issue fixed * Default app icon color added * Removing hardcoded colors * Removing hardcoded colors. * Light Mode on! * Showing correct icon and color in menu * Update color working properly. * Updating appIcon * Editable text working. * Adding validator * Adding edit permissions to menu * Removing box shadow on app card. * Fixing context menu fill color * Fixing Menu hover issues. * Fixing menu open close hover issues. * Fixing settings pages * Changed Workspace to org. * Fix: State management in EditableText Component (#540) * Error state height is fixed as per design * savingState prop condition fixed * Fixing createnew. * Fixing saving state for application card. * Fixed application card editable text error. * Fixing issue caused during merge. * Fixing tests in create org. * Removing commented code. * Removing unwanted vars. * Fixing delete duplicate tests. * Latest color palette. * Fixing form and table widget. * Removing switcher from header * Removing unused files * Fixing app card context dropdown * Show overlay fix * Adding localStorage support to theme. * Making dark mode the default. Co-authored-by: Rohit Kumawat <rohit.kumawat@primathon.in>
2020-09-16 11:50:47 +00:00
export const getColorCode = (
initials: string,
colorPalette: string[],
): string => {
let asciiSum = 0;
for (let i = 0; i < initials.length; i++) {
asciiSum += initials[i].charCodeAt(0);
}
Homepage redesign with themes (#482) * Updating homepage body color * WIP: Fixing scrolls and adding anchors * Removing divider from bottom of the page. * Adding hover background color to app card * Changing edit and launch icons. * Fixing app name paddding in card. * Fixing workspaces overflow * Adding right padding to applications view * Adding share icon to share btn * Fixing Application card styles. * Fixing text decoration in button. * Adding new workspace button * Fixing new workspace and new app styles. * Adding icon sizes. * Fixing Org Name and Org settings menu. * Application menu working * Fixing overlay visibility on app card * Fixing settings page content width. * Fixing workspace icon * Changing app card colors. * Removing debugger * Adding app icon. * Fixing the spaces in application card * Adding storybook-static folder to gitignore. * Adding other storybook files. * Adding menu items for app * Removing cypress selector from text. * Menu width issue fixed * Default app icon color added * Removing hardcoded colors * Removing hardcoded colors. * Light Mode on! * Showing correct icon and color in menu * Update color working properly. * Updating appIcon * Editable text working. * Adding validator * Adding edit permissions to menu * Removing box shadow on app card. * Fixing context menu fill color * Fixing Menu hover issues. * Fixing menu open close hover issues. * Fixing settings pages * Changed Workspace to org. * Fix: State management in EditableText Component (#540) * Error state height is fixed as per design * savingState prop condition fixed * Fixing createnew. * Fixing saving state for application card. * Fixed application card editable text error. * Fixing issue caused during merge. * Fixing tests in create org. * Removing commented code. * Removing unwanted vars. * Fixing delete duplicate tests. * Latest color palette. * Fixing form and table widget. * Removing switcher from header * Removing unused files * Fixing app card context dropdown * Show overlay fix * Adding localStorage support to theme. * Making dark mode the default. Co-authored-by: Rohit Kumawat <rohit.kumawat@primathon.in>
2020-09-16 11:50:47 +00:00
return colorPalette[asciiSum % colorPalette.length];
};
export const getApplicationIcon = (initials: string): AppIconName => {
let asciiSum = 0;
for (let i = 0; i < initials.length; i++) {
asciiSum += initials[i].charCodeAt(0);
}
return AppIconCollection[asciiSum % AppIconCollection.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,
};
}
export const retryPromise = (
fn: () => Promise<any>,
retriesLeft = 5,
interval = 1000,
): Promise<any> => {
return new Promise((resolve, reject) => {
fn()
.then(resolve)
.catch(() => {
setTimeout(() => {
if (retriesLeft === 1) {
return Promise.reject({
code: ERROR_CODES.SERVER_ERROR,
message: createMessage(ERROR_500),
show: false,
});
}
// Passing on "reject" is the important part
retryPromise(fn, retriesLeft - 1, interval).then(resolve, reject);
}, interval);
});
});
};
export const getRandomPaletteColor = (colorPalette: string[]) => {
return colorPalette[Math.floor(Math.random() * colorPalette.length)];
};
export const isBlobUrl = (url: string) => {
return typeof url === "string" && url.startsWith("blob:");
};
/**
*
* @param data string file data
* @param type string file type
* @returns string containing blob id and type
*/
export const createBlobUrl = (data: Blob | MediaSource, type: string) => {
let url = URL.createObjectURL(data);
url = url.replace(
`${window.location.protocol}//${window.location.hostname}/`,
"",
);
return `${url}?type=${type}`;
};
/**
*
* @param blobId string blob id along with type.
* @returns [string,string] [blobUrl, type]
*/
export const parseBlobUrl = (blobId: string) => {
const url = `blob:${window.location.protocol}//${
window.location.hostname
}/${blobId.substring(5)}`;
return url.split("?type=");
};
feat: property pane docking (#7361) * add tailwindcss * docked property pane * uncomment a line * make entity explorer as drawer on unpin * remove unused imports * add pin state in reducer * add menu icon in header * fix widget sidebar * fix widgets sidebar * style property pane * update property pane css * update icons in property pane * update property pane header styles * update spacing * fix few ui issues * wip: preview mode * wip:preview mode * remove unused import * comments sidebar in app and edit mode * fix order of import * use selected state for property pane * update scrollbar style * add classes to sidebar and property pane * make widgets editor fluid * make widgets editor fluid and refactor logic * resize the widgets editor if explorer is pinned * add shortcut for preview mode * fix link for tabs in edit mode * zoom in/zoom out for 0.75 * fix chart widget + table widget crashing * allow zooming of canvas * fix weird canvas draw issue + update container for handling zoom * add actions for is panning * allow panning with grab cursor * reset panning + zooming when entering preview mode * add grabbing cursor when grabbing * only prevent default when space key is pressed * dont allow zoom in preview mode * remove unused imports * fix dont allow zoom in preview mode * fix ux of panning on space hit * make fluid as the default app layout * chart spec * fix dropdown_on change spec * fix add widget table and bind spec * remove draggable property pane spec * fix container spec * fix form widget spec * fix jest test * fix the function typo * remove clicking of close button for property pane in cypress tests * remove property pane actions test * fix drag and drop test failing * add cypress selector id to back button in property pane * fix toggle js spec * fix merge conflicts from new design system * editor header * fix product updates styles + widget card * remove all unused imports * fix dynamic layout spec * fix entity explorer tab rename test failing * fix table spec * fix bind tabletextpagination spec * fix js object spec * fix entity explorer rename issue * fix cypress test * fix cypress command wrong commit * fix tab spec * fix property pane copy tests * add zoom header * zoom levels * make property pane sidebar resizable * add multi select property pane * fix widget search bug * update property pane width in state on drag end * fix viewer header * fix editor header * update editor header + remove zooming * update small style * dont allow closing of explorer when resizing * fix jest test * fix dropdown widget jest test * preview test case wip * add entity explorer pinning tests + preview mode tests * add tooltip in layout control + add padding bottom in property pane view * incorporate aakash feedbacks * fix preview mode margin issue * remove panning code * fix cypress failing test * uncomment jest test * remove redundant code * fix maincontainer test * incorporate review feedbacks * incorporate aakash feedbacks * review feedbacks * incorporate review feedbacks * incorporate qa feedbacks * fix dynamic layout spec * updated test based on latest change * dsl updated * Updated dsl * Updated dsl * resize deselects widget issue. * fix canvas height issue * fix typo * incorporate qa feedbacks * incorporate qa feedbacks * incorporate qa feedbacks * update color for setting control for widget name * fix onboarding styles conflicts * Updated tests * fix application overflow issue * updated test method Co-authored-by: root <root@DESKTOP-9GENCK0.localdomain> Co-authored-by: Pawan Kumar <pawankumar@Pawans-MacBook-Pro.local> Co-authored-by: Ashok Kumar M <35134347+marks0351@users.noreply.github.com> Co-authored-by: Apple <nandan@thinkify.io>
2021-11-23 08:01:46 +00:00
/**
feat: Switch Group widget (#7590) * Feat: Switch Group Widget -- The first MVP of the widget * feat: Switch Group Widget -- Follow the same config and implementation as the other group widgets * feat: Switch Group Widget -- Elaborate the help text for defaultSelectedValues * feat: Switch Group Widget -- Add a widget icon * feat: Switch Group Widget -- Remove unnecessary property control at ItemsControl.tsx -- Refactor some code snippets for higher code quality -- Add basic cypress test cases * fix: icon for the widget optimised & replaced * feat: Switch Group Widget -- Add a unit test for defaultSelectedValuesValidation * feat: Switch Group Widget -- Make the validation type for defaultSelectedValues property to ValidationTypes.ARRAY -- Remove original validation function and its unit test * feat: Switch Group Widget -- Fix on typo -- Fix on formatting issue -- Change the help text for isRequired property * feat: Switch Group Widget -- Revert help text for isRequired property to the original one * feat: Switch Group Widget -- Set strict property to true on defaultSelectedValues * feat: Switch group widget -- Refactor utility function, getCamelCaseString -- Add the corresponding test case * feat: Switch group widget -- Implement options property as a plain JS field -- Reimplement update logic for selectedValues when options changes -- Add a new utility function for checking equality of object arrays -- Add a unit test for the above function -- Rewrite the corresponding Cypress test cases * feat: Switch Group Widget -- Remove isArrayEqual utility function and directly use functions from lodash * feat: Swtich Group Widget -- Make selectedValues as a derived property * feat: Switch Group Widget -- Replace the widget icon * feat: Switch Group Widget -- Rewrite a test case for onSelectionChange property * feat: Switch Group Widget -- Remove redundant calls for openPropertyPane * feat: Switch Group Widget -- Remove closePropertyPane call from afterEach hook * feat: Switch Group Widget -- Change the selector for every switch element in onSelectionChange test case * feat: Switch Group Widget -- Fix on failed Cypress test case, adding closePropertyPane command to onSelectionChange * feat: Switch Group Widget -- Remove template literal from a selector * feat: Switch Group Widget -- Make click on onSelectionChange test case forced * feat: Switch Group Widget -- Fix on crash issue when editing on Options property * feat: Switch Group Widget -- Add the widget icon to show in entity explorer * feat: Switch Group Widget -- Fix on blue color on mouse down -- Add a new property for alignment Co-authored-by: somangshu <somangshu.goswami1508@gmail.com>
2021-12-09 12:02:47 +00:00
* Convert a string into camelCase
* @param sourceString input string
* @returns camelCase string
*/
export const getCamelCaseString = (sourceString: string) => {
let out = "";
// Split the input string to separate words using RegEx
const regEx = /[A-Z\xC0-\xD6\xD8-\xDE]?[a-z\xDF-\xF6\xF8-\xFF]+|[A-Z\xC0-\xD6\xD8-\xDE]+(?![a-z\xDF-\xF6\xF8-\xFF])|\d+/g;
const words = sourceString.match(regEx);
if (words) {
words.forEach(function(el, idx) {
const add = el.toLowerCase();
out += idx === 0 ? add : add[0].toUpperCase() + add.slice(1);
});
}
return out;
};
feat: camera widget (#8069) * feat: Camera Widget -- Scaffold the basic structure of the widget * feat: Camera Widget -- Prototype a feature, taking picture * feat: Camera Widget -- Add types for MediaRecorder -- Define media capture status and action types -- Prototype basic video recording, playing features * feat: Camera Widget -- Implement video player -- Add timer for recording and playing video -- Add permission and error handling logic -- Add device selectors * feat: Camera Widget -- Place control buttons above device inputs layer -- Make the widget fully responsive * feat: Camera Widget -- Change the color of caret-down icon to white -- Remove overlaying of web cam and video player -- Add some padding for device inputs * feat: Camera Widget -- Add black background to the container of the widget * feat: Camera Widget -- Change the widget icon * feat: Camera Widget -- Implement the mute feature of a mic or a camera * feat: Camera Widget -- Check media device permissions before getting started * feat: Camera Widget -- Add a fullscreen control * feat: Camera Widget -- Set error text color to white -- Change the layout of control panel * feat: Camera Widget -- Apply layout change for control panel according to app layout change * feat: Camera Widget -- Add a new derived property, videoURL * feat: Switch Group Widget -- Adopt theme changes * feat: Camera Widget -- Make background grey in case of both error and disabled status * feat: Camera Widget -- Update npm dependencies * feat: Camera Widget -- Fix on #8788, using muted property * feat: Camera Widget -- Show off the microphone setting icon only if the current mode is video -- Set isMirrored property to true by default * feat: Camera Widget -- Add photo viewer * feat: Camera Widget -- Add onImageCapture, onRecordingStart, onRecordingStop actions instead of onMediaCapture * feat: Camera Widget -- Expose meta properties for the widget * feat: Camera Widget -- Fix on responsiveness issue * feat: Camera Widget -- Add type definitions for MediaStream recording * feat: Camera Widget -- Hide isMirroed property for video mode * feat: Camera Widget -- Wrap all the controls with TooltipComponent * feat: Camera Widget -- Implement enter, exit full screen feature * feat: Camera Widget -- Add a widget icon for entity explorer * feat: Camera Widget -- Fix on the typo for the label of onRecordingStop property * feat: Camera Widget -- Enable/disable media tracks * feat: Camera Widget -- Set the video's height to 100% in fullscreen mode * feat: Camera Widget -- Add overlayers on Webcam * feat: Camera Widget -- Set position to relative on fullscreen wrapper div -- Set the photo viewer's height to 100% * feat: Camera Widget -- Add image, mediaCaptureStatus, timer meta properties to keep UI states when the widget is dragged * feat: Camera Widget -- Refactor code base, eliminating commented code blocks * feat: Camera Widget -- Revert all the changes needed for keeping status when the widget is dragged -- Set mirroed property to false for video mode
2021-12-24 14:06:59 +00:00
/**
* Convert Base64 string to Blob
* @param base64Data
* @param contentType
* @param sliceSize
* @returns
*/
export const base64ToBlob = (
base64Data: string,
contentType = "",
sliceSize = 512,
) => {
const byteCharacters = atob(base64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, { type: contentType });
return blob;
};
// util function to detect current os is Mac
export const isMacOs = () => {
return osName === "Mac OS";
};
perf: Widget re-rendering refactor (#14485) * initial commit * props hoc * changes * removed ignores and withWidgetProps * added extra props to canvasStructure * widget props changes * list widget changes * reintroduced widget props hook and other refactors * remove warnings * added deepequal for childWidgets selector * fix global hotkeys and tabs widget jest test * fix main container test fix * fixed view mode width * fix form widget values * minor fix * fix skeleton * form widget validity fix * jest test fix * fixed tests: GlobalHotkeys, Tabs, CanvasSelectectionArena and fixed main container rendering * minor fix * minor comments * reverted commented code * simplified structure, selective redux state updates and other inconsistencies * fix junit test cases * stop form widget from force rendering children * fix test case * random commit to re run tests * update isFormValid prop only if it exists * detangling circular dependency * fixing cypress tests * cleaned up code * clean up man cnavas props and fix jest cases * fix rendering order of child widgets for canvas * fix dropdown reset spec * adding comments * cleaning up unwanted code * fix multiselect widget on deploy * adressing review comments * addressing minor review comment changes * destructuring modal widget child and fix test case * fix communityIssues cypress spec * rewrite isVisible logic to match previous behaviour * merging widget props with component props before checking isVisible * adressing review comments for modal widget's isVisible Co-authored-by: rahulramesha <rahul@appsmith.com>
2022-08-19 10:10:36 +00:00
/**
* checks if array of strings are equal regardless of order
* @param arr1
* @param arr2
* @returns
*/
export function areArraysEqual(arr1: string[], arr2: string[]) {
if (arr1.length !== arr2.length) return false;
if (arr1.sort().join(",") === arr2.sort().join(",")) return true;
return false;
}