code
stringlengths
10
343k
docstring
stringlengths
36
21.9k
func_name
stringlengths
1
3.35k
language
stringclasses
1 value
repo
stringlengths
7
58
path
stringlengths
4
131
url
stringlengths
44
195
license
stringclasses
5 values
function handleImportDesign(data) { updateProgress({ showProgress: true }); const { uploadType, name, url, file } = data; let requestBody = null; switch (uploadType) { case 'File Upload': { const fileElement = document.getElementById('root_file'); const fileName = fileElement.files[0].name; requestBody = JSON.stringify({ name, file_name: fileName, file: getUnit8ArrayDecodedFile(file), }); break; } case 'URL Import': requestBody = JSON.stringify({ url, name, }); break; } importPattern({ importBody: requestBody, }) .unwrap() .then(() => { updateProgress({ showProgress: false }); notify({ message: `"${name}" design uploaded`, event_type: EVENT_TYPES.SUCCESS, }); getPatterns(); }) .catch(() => { updateProgress({ showProgress: false }); handleError(ACTION_TYPES.UPLOAD_PATTERN); }); }
Gets the data of Import Filter and handles submit operation @param {{ uploadType: ("File Upload"| "URL Import"); name: string; url: string; file: string; }} data
handleImportDesign ( data )
javascript
meshery/meshery
ui/components/MesheryPatterns.js
https://github.com/meshery/meshery/blob/master/ui/components/MesheryPatterns.js
Apache-2.0
const errorH = (err, prefixMessage, variant) => { console.error('an error occured with severity: ', variant, { err }); return notify({ message: `${prefixMessage}: ${err?.message}`, event_type: EVENT_TYPES.ERROR, details: err.toString(), }); }; return errorH; }
@param {Object} err @param {string} prefixMessage @param {("error"|"warning")} variant
errorH
javascript
meshery/meshery
ui/components/ErrorHandling.js
https://github.com/meshery/meshery/blob/master/ui/components/ErrorHandling.js
Apache-2.0
const EmptyState = ({ icon, message, pointerLabel }) => { return ( <div style={{ textAlign: 'center', display: 'flex', flexDirection: 'column', justifyContent: 'flex-start', alignItems: 'center', minHeight: '50vh', }} > <Grid style={{ display: 'flex', width: '100%', padding: '0 40px' }}> <CurvedArrowIcon /> <Typography style={{ fontSize: 24, color: '#808080', px: 5, py: 2, lineHeight: 1.5, letterSpacing: '0.15px', display: 'flex', alignItems: 'flex-end', marginBottom: -32, }} > {pointerLabel} </Typography> </Grid> <Grid style={{ marginTop: '120px' }}> {icon} <Typography style={{ fontSize: 24, color: '#808080', px: 5, py: 2, lineHeight: 1, }} > {message} </Typography> </Grid> </div> ); };
Wrapper component for flip cards. @param {Object} props - The component props. @param {Object} props.message - The message of the empty state. @param {string} props.icon - The icon of the empty state.
EmptyState
javascript
meshery/meshery
ui/components/Lifecycle/General/empty-state/index.js
https://github.com/meshery/meshery/blob/master/ui/components/Lifecycle/General/empty-state/index.js
Apache-2.0
export function getPatternAttributeName(jsonSchema) { return jsonSchema?._internal?.patternAttributeName || 'NA'; }
getPatternAttributeName will take a json schema and will return a pattern attribute name if it does exists, then it returns "NA" @param {*} jsonSchema json schema of the pattern @returns {string} pattern attribute name
getPatternAttributeName ( jsonSchema )
javascript
meshery/meshery
ui/components/MesheryMeshInterface/helpers.js
https://github.com/meshery/meshery/blob/master/ui/components/MesheryMeshInterface/helpers.js
Apache-2.0
export function recursiveCleanObject(obj) { for (const k in obj) { if (!obj[k] || typeof obj[k] !== 'object') continue; recursiveCleanObject(obj[k]); if (Object.keys(obj[k]).length === 0) delete obj[k]; } return obj; }
recursiveCleanObject will take an object and will remove all of the "falsy" objects @param {*} obj object that needs to be cleaned
recursiveCleanObject ( obj )
javascript
meshery/meshery
ui/components/MesheryMeshInterface/helpers.js
https://github.com/meshery/meshery/blob/master/ui/components/MesheryMeshInterface/helpers.js
Apache-2.0
export function recursiveCleanObjectExceptEmptyArray(obj) { for (const k in obj) { if (!obj[k] || typeof obj[k] !== 'object' || Array.isArray(obj[k])) continue; recursiveCleanObjectExceptEmptyArray(obj[k]); if (Object.keys(obj[k]).length === 0) delete obj[k]; } }
recursiveCleanObjectExceptEmptyArray will take an object and will remove all of the "falsy" objects except empty array @param {*} obj object that needs to be cleaned
recursiveCleanObjectExceptEmptyArray ( obj )
javascript
meshery/meshery
ui/components/MesheryMeshInterface/helpers.js
https://github.com/meshery/meshery/blob/master/ui/components/MesheryMeshInterface/helpers.js
Apache-2.0
export function createPatternFromConfig(config, namespace, partialClean = false) { const pattern = { name: `pattern-${trueRandom().toString(36).substr(2, 5)}`, services: {}, }; partialClean ? recursiveCleanObjectExceptEmptyArray(config) : recursiveCleanObject(config); Object.keys(config).forEach((key) => { // Add it only if the settings are non empty or "true" if (config[key].settings) { // const name = PascalCaseToKebab(key); pattern.services[key] = config[key]; pattern.services[key].namespace = namespace; } }); Object.keys(pattern.services).forEach((key) => { // Delete the settings attribute/field if it is set to "true" if (pattern.services[key].settings === true) delete pattern.services[key].settings; }); return pattern; }
createPatternFromConfig will take in the form data and will create a valid pattern from it It will/may also perform some sanitization on the given inputs @param {*} config
createPatternFromConfig ( config , namespace , partialClean = false )
javascript
meshery/meshery
ui/components/MesheryMeshInterface/helpers.js
https://github.com/meshery/meshery/blob/master/ui/components/MesheryMeshInterface/helpers.js
Apache-2.0
function jsonSchemaBuilder(schema, uiSchema) { if (!schema) return; userPromptKeys.forEach((key) => { if (Object.prototype.hasOwnProperty.call(schema, key)) { schema[key]?.forEach((item) => { jsonSchemaBuilder(item, uiSchema); }); } }); if (schema.type === 'object' || Object.prototype.hasOwnProperty.call(schema, 'properties')) { // to handle objects as well as oneof, anyof and allof fields for (let key in schema.properties) { uiSchema[key] = {}; // handle percentage for range widget if ( (schema.properties?.[key]['type'] === 'number' || schema.properties?.[key].type === 'integer') && key.toLowerCase().includes('percent') ) { uiSchema[key]['ui:widget'] = 'range'; } jsonSchemaBuilder(schema.properties?.[key], uiSchema[key]); } return; } if (schema.type === 'array') { uiSchema['items'] = { 'ui:label': false, }; jsonSchemaBuilder(schema.items, uiSchema['items']); return; } if (uiSchema['ui:widget']) { // if widget is already assigned, don't go over return; } if (schema.type === 'number' || schema.type === 'integer') { schema['maximum'] = 99999; schema['minimum'] = 0; } }
The rjsf json schema builder for the ui inplace builds the obj recursively according to the schema provided @param {Record<string, any>} schema The RJSF schema @param {*} uiSchema uiSchema @returns
jsonSchemaBuilder ( schema , uiSchema )
javascript
meshery/meshery
ui/components/MesheryMeshInterface/helpers.js
https://github.com/meshery/meshery/blob/master/ui/components/MesheryMeshInterface/helpers.js
Apache-2.0
export function buildUiSchema(schema) { const uiSchemaObj = {}; // 1. Build ui schema jsonSchemaBuilder(schema, uiSchemaObj); // 2. Set the ordering of the components uiSchemaObj['ui:order'] = ['metadata', 'name', 'namespace', 'label', 'annotation', '*']; //3. Return the final uiSchema Object return uiSchemaObj; }
Builds ui schema and sets the required rjsf ui properties @param {Record.<string, any>} schema RJSF json Schema @returns
buildUiSchema ( schema )
javascript
meshery/meshery
ui/components/MesheryMeshInterface/helpers.js
https://github.com/meshery/meshery/blob/master/ui/components/MesheryMeshInterface/helpers.js
Apache-2.0
export function getRefinedJsonSchema(jsonSchema, hideTitle = true, handleError) { let refinedSchema; try { refinedSchema = hideTitle ? deleteTitleFromJSONSchema(jsonSchema) : jsonSchema; refinedSchema = deleteDescriptionFromJSONSchema(refinedSchema); refinedSchema.properties = refinedSchema?.properties && sortProperties(refinedSchema.properties); // temporarily commented recursivelyParseJsonAndCheckForNonRJSFCompliantFields(refinedSchema); } catch (e) { console.trace(e); handleError(e, 'schema parsing problem'); } return refinedSchema; }
remove top-level title, top-level description and handle non-RJSF compliant fields @param {Object.<String, Object>} jsonSchema @returns
getRefinedJsonSchema ( jsonSchema , hideTitle = true , handleError )
javascript
meshery/meshery
ui/components/MesheryMeshInterface/PatternService/helper.js
https://github.com/meshery/meshery/blob/master/ui/components/MesheryMeshInterface/PatternService/helper.js
Apache-2.0
function getXKubenetesToRJSFCompatibleFieldType(schema) { // todo: add more const xKubernetesIntOrString = 'x-kubernetes-int-or-string'; const xKubernetesPreserveUnknownFields = 'x-kubernetes-preserve-unknown-fields'; const exceptionalFieldToTypeMap = { [xKubernetesIntOrString]: 'string', // string can hold integers too [xKubernetesPreserveUnknownFields]: schema?.type || 'object', }; let returnedType; Object.keys(exceptionalFieldToTypeMap).some((field) => { if ( Object.prototype.hasOwnProperty.call(schema, field) && !Object.prototype.hasOwnProperty.call(schema, 'type') ) { returnedType = exceptionalFieldToTypeMap[field]; delete schema[field]; return true; } }); // handle other x-kubernetes if (!returnedType) { const keys = Object.keys(schema); const isXKubernetesFieldPresent = keys.find((key) => { if (key.startsWith('x-kubernetes')) { return true; } return false; }); if (isXKubernetesFieldPresent) { delete schema[isXKubernetesFieldPresent]; } } return returnedType || false; }
Check if the exsxceptional type fields are present in the schema returns false if any of the exceptional-fields are not present else returns the type of the exceptional-field @see https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#specifying-a-structural-schema
getXKubenetesToRJSFCompatibleFieldType ( schema )
javascript
meshery/meshery
ui/components/MesheryMeshInterface/PatternService/helper.js
https://github.com/meshery/meshery/blob/master/ui/components/MesheryMeshInterface/PatternService/helper.js
Apache-2.0
const sortProperties = (properties) => { const sortedProperties = {}; Object.keys(properties) .sort((a, b) => { // when we have properties[a or b], if we have allOf, oneOf, anyOf, we need to handle them let a_type = properties[a]?.type; let b_type = properties[b]?.type; // if we have oneOf, anyOf, allOf, we need to handle them userPromptKeys.forEach((key) => { if (properties[a]?.[key]) { a_type = properties[a]?.[key][0]?.type; } if (properties[b]?.[key]) { b_type = properties[b]?.[key][0]?.type; } }); return ( sortOrder.indexOf(a_type) - sortOrder.indexOf(b_type) // sort by type ); }) .forEach((key) => { sortedProperties[key] = properties[key]; if (properties[key]?.properties) { // Handles the Objects in the schema sortedProperties[key].properties = sortProperties(properties[key].properties, sortOrder); } if (properties[key].items?.properties) { // Handles Arrays in the schema sortedProperties[key].items.properties = sortProperties( properties[key].items.properties, sortOrder, ); } if (properties[key] || properties[key].items) { // Handles oneOf, anyOf, allOf const handleReserve = properties[key]?.oneOf || properties[key]?.anyOf || properties[key]?.allOf || properties[key]?.items?.oneOf || properties[key]?.items?.anyOf || properties[key]?.items?.allOf; if (!handleReserve) return; handleReserve.forEach((item, index) => { if (item.properties) { // Handles the Objects in the schema handleReserve[index].properties = sortProperties(item.properties, sortOrder); } if (item.items?.properties) { // Handles Arrays in the schema handleReserve[index].items.properties = sortProperties( item.items.properties, sortOrder, ); } }); } }); return sortedProperties; };
Sorts the properties of the jsonSchema in the order of the sortOrder. @param {*} properties @returns
sortProperties
javascript
meshery/meshery
ui/components/MesheryMeshInterface/PatternService/helper.js
https://github.com/meshery/meshery/blob/master/ui/components/MesheryMeshInterface/PatternService/helper.js
Apache-2.0
export const getSchema = (type) => { switch (type) { case 'grafana': return require('../../schemas/credentials/grafana').grafanaSchema; case 'prometheus': return require('../../schemas/credentials/prometheus').prometheusSchema; case 'kubernetes': return require('../../schemas/credentials/kubernetes').kubernetesSchema; default: return; } };
Returns the schema for the credentials. @param {String} type @returns
getSchema
javascript
meshery/meshery
ui/components/MesheryMeshInterface/PatternService/helper.js
https://github.com/meshery/meshery/blob/master/ui/components/MesheryMeshInterface/PatternService/helper.js
Apache-2.0
export const calculateGrid = (element) => { let type = element.type; let __additional_property = element.__additional_property; if (!type) { // handle anyOf, oneOf, allOf const schema = element?.content?.props?.schema; userPromptKeys.forEach((key) => { if (schema[key]) { type = schema[key][0].type; } }); } const grid = { xs: 12, md: 12, lg: 6, }; if (type === 'object' || type === 'array' || __additional_property) { grid.lg = 12; } // if fields have custom annotations to grid them differently grid.lg = element.content.props.schema['x-rjsf-grid-area'] || grid.lg; return grid; };
Calculates the grid for the object field template. @param {*} element @returns
calculateGrid
javascript
meshery/meshery
ui/components/MesheryMeshInterface/PatternService/helper.js
https://github.com/meshery/meshery/blob/master/ui/components/MesheryMeshInterface/PatternService/helper.js
Apache-2.0
function recursivelyParseJsonAndCheckForNonRJSFCompliantFields(jsonSchema) { if (!jsonSchema || _.isEmpty(jsonSchema)) { return; } // 1. Handling the special kubernetes types const rjsfFieldType = getXKubenetesToRJSFCompatibleFieldType(jsonSchema); if (rjsfFieldType) { jsonSchema.type = rjsfFieldType; // Mutating original object by adding a valid type field } // handle allOf if (Object.prototype.hasOwnProperty.call(jsonSchema, 'allOf')) { jsonSchema.allOf.forEach((item) => { recursivelyParseJsonAndCheckForNonRJSFCompliantFields(item); }); } // handle oneOf if (Object.prototype.hasOwnProperty.call(jsonSchema, 'oneOf')) { jsonSchema.oneOf.forEach((item) => { recursivelyParseJsonAndCheckForNonRJSFCompliantFields(item); }); } // handle anyof if (Object.prototype.hasOwnProperty.call(jsonSchema, 'anyOf')) { jsonSchema.anyOf.forEach((item) => { recursivelyParseJsonAndCheckForNonRJSFCompliantFields(item); }); } if (jsonSchema.type === 'object' && jsonSchema.additionalProperties) { recursivelyParseJsonAndCheckForNonRJSFCompliantFields(jsonSchema.additionalProperties); } if (jsonSchema.type === 'object') { const properties = jsonSchema.properties; properties && Object.keys(properties).forEach((key) => { recursivelyParseJsonAndCheckForNonRJSFCompliantFields(properties[key]); }); } if (jsonSchema.type === 'array') { const items = jsonSchema.items; items && recursivelyParseJsonAndCheckForNonRJSFCompliantFields(items); } return jsonSchema; }
An inline object mutating function that could detect and handle the exceptional kubernetes field that are not valid RJSF constructs @param {Object} jsonSchema @returns
recursivelyParseJsonAndCheckForNonRJSFCompliantFields ( jsonSchema )
javascript
meshery/meshery
ui/components/MesheryMeshInterface/PatternService/helper.js
https://github.com/meshery/meshery/blob/master/ui/components/MesheryMeshInterface/PatternService/helper.js
Apache-2.0
function PatternService({ formData, jsonSchema, onChange, type, onSubmit, onDelete, RJSFWrapperComponent, RJSFFormChildComponent, }) { if (Object.keys(jsonSchema?.properties).length > 0) return ( <RJSFWrapper formData={formData} hideSubmit={type === 'trait'} hideTitle={type === 'workload'} jsonSchema={jsonSchema} onChange={onChange} onSubmit={onSubmit} onDelete={onDelete} RJSFWrapperComponent={RJSFWrapperComponent} RJSFFormChildComponent={RJSFFormChildComponent} /> ); return null; }
PatternService returns a component for the given jsonSchema @param {{ jsonSchema: Record<string, any>; onChange: Function; onSubmit?: Function; onDelete?: Function; type: "trait" | "workload" formData: Record<string, any>; RJSFWrapperComponent?: any; RJSFFormChildComponent?: any; }} props @returns
PatternService ( { formData , jsonSchema , onChange , type , onSubmit , onDelete , RJSFWrapperComponent , RJSFFormChildComponent , } )
javascript
meshery/meshery
ui/components/MesheryMeshInterface/PatternService/index.js
https://github.com/meshery/meshery/blob/master/ui/components/MesheryMeshInterface/PatternService/index.js
Apache-2.0
const getRawErrors = (errorSchema) => { if (!errorSchema) return []; const errors = []; Object.keys(errorSchema).forEach((key) => { if (errorSchema?.[key]?.__errors) { errors.push(...errorSchema[key].__errors); } }); return errors; };
Get the raw errors from the error schema. @param {Object} errorSchema error schema. @returns {Array} raw errors.
getRawErrors
javascript
meshery/meshery
ui/components/MesheryMeshInterface/PatternService/RJSFCustomComponents/ObjectFieldTemplate.js
https://github.com/meshery/meshery/blob/master/ui/components/MesheryMeshInterface/PatternService/RJSFCustomComponents/ObjectFieldTemplate.js
Apache-2.0
export const groupRelationshipsByKind = (relationships) => { const groupedRelationships = {}; relationships.forEach((relationship) => { const { id, kind } = relationship; if (!groupedRelationships[kind]) { groupedRelationships[kind] = { kind, relationships: [] }; } groupedRelationships[kind].relationships.push({ id, ...relationship }); }); const resultArray = Object.values(groupedRelationships); return resultArray; };
Group relationships by kind @param {object} - Relationships arrays
groupRelationshipsByKind
javascript
meshery/meshery
ui/components/MeshModelRegistry/helper.js
https://github.com/meshery/meshery/blob/master/ui/components/MeshModelRegistry/helper.js
Apache-2.0
export const reactJsonTheme = (themeType) => ({ base00: themeType === 'dark' ? '#303030' : '#ffffff', base01: '#444c56', base02: themeType === 'dark' ? '#586069' : '#abb2bf', base03: '#6a737d', base04: '#477E96', base05: '#9ea7a6', base06: '#d8dee9', base07: themeType === 'dark' ? '#FFF3C5' : '#002B36', base08: '#2a5491', base09: '#d19a66', base0A: '#EBC017', base0B: '#237986', base0C: '#56b6c2', base0D: '#B1B6B8', base0E: '#e1e6cf', base0F: '#647881', });
To style JSON viewing in react-json-tree. Refer to base-16 theme styling guidelines for more info. https://github.com/chriskempson/base16/blob/main/styling.md @type {Object} @property {string} base00 - BACKGROUND_COLOR @property {string} base02 - OBJECT_OUTLINE_COLOR @property {string} base04 - OBJECT_DETAILS_COLOR @property {string} base07 - OBJECT_KEY_COLOR @property {string} base09 - ITEM_STRING_COLOR, DATE_COLOR, STRING_COLOR @property {string} base0A - SYMBOL_COLOR, FUNCTION_COLOR, UNDEFINED_COLOR, NULL_COLOR @property {string} base0D - ITEM_STRING_EXPANDED_COLOR, ARROW_COLOR @property {string} base0E - BOOLEAN_COLOR, NUMBER_COLOR
reactJsonTheme
javascript
meshery/meshery
ui/components/MeshModelRegistry/helper.js
https://github.com/meshery/meshery/blob/master/ui/components/MeshModelRegistry/helper.js
Apache-2.0
const Level = ({ children }) => { const level = useContext(LevelContext); return <LevelContext.Provider value={level + 1}> {children} </LevelContext.Provider>; };
Level context provider to autoincrement the level of content in the formatter @param {React.PropsWithChildren<{}>} param0 @returns {React.ReactElement}
Level
javascript
meshery/meshery
ui/components/DataFormatter/index.js
https://github.com/meshery/meshery/blob/master/ui/components/DataFormatter/index.js
Apache-2.0
export const formatDate = (date) => { const options = { year: 'numeric', month: 'short', day: 'numeric' }; const formattedDate = new Date(date).toLocaleDateString('en-US', options); return formattedDate; };
Pure function to format data @returns {string}
formatDate
javascript
meshery/meshery
ui/components/DataFormatter/index.js
https://github.com/meshery/meshery/blob/master/ui/components/DataFormatter/index.js
Apache-2.0
function getDynamicVh(scrollPos) { if (window.scrollY === 0) { return '67vh'; } const per = getScrollPercentage(); const threshold = 0.06; const vh = 67 + 15 * (per / threshold); // calc(67vh) if (per < threshold) { return scrollPos > 106 ? `${vh}vh` : '67vh'; } else if (per > 0.95) { return 'calc(100vh - 232px)'; } else { return '82vh'; } }
Provides dynamic height according to scroll calculations @param {DoubleRange} scrollPos @returns dynamically calcultaed height in vh
getDynamicVh ( scrollPos )
javascript
meshery/meshery
ui/components/configuratorComponents/CodeEditor.js
https://github.com/meshery/meshery/blob/master/ui/components/configuratorComponents/CodeEditor.js
Apache-2.0
function convertToSvgStyle(inputStyle, color) { const svgStyle = { stroke: color, // Use the specified color for the SVG stroke fillOpacity: inputStyle['background-opacity'], // Map 'background-opacity' to 'fillOpacity' strokeWidth: inputStyle['border-width'], // Map 'border-width' to 'strokeWidth' //Add more styles as per requirement... }; return svgStyle; }
Converts a set of input styles to SVG-compatible styles. @param {object} inputStyle - The input style object to be converted. @param {string} color - The color to be used for the SVG stroke. @returns {object} An object containing SVG-compatible style properties.
convertToSvgStyle ( inputStyle , color )
javascript
meshery/meshery
ui/components/configuratorComponents/MeshModel/NodeIcon.js
https://github.com/meshery/meshery/blob/master/ui/components/configuratorComponents/MeshModel/NodeIcon.js
Apache-2.0
return function handledesignJsonChange(formData) { const referKey = formReference.current.referKey; const { name, namespace, labels, annotations, ...configuration } = formData; const newInput = { id: referKey, schemaVersion, version, component, displayName: name, model: { name: modelName, version: modelVersion, category: modelCategory, registrant: modelRegistrant, }, configuration: { metadata: { labels, annotations, namespace, }, ...configuration, }, }; setDesignJson((prev) => { let newestKey = false; const currentJson = prev.components?.map((val) => { if (val.id == referKey) { newestKey = true; return newInput; } return val; }) || []; if (!newestKey) { currentJson.push(newInput); } return { ...prev, components: [...currentJson] }; }); };
Handles actual design-json change in response to form-data change @param {*} formData
handledesignJsonChange ( formData )
javascript
meshery/meshery
ui/components/configuratorComponents/MeshModel/hooks/useDesignLifecycle.js
https://github.com/meshery/meshery/blob/master/ui/components/configuratorComponents/MeshModel/hooks/useDesignLifecycle.js
Apache-2.0
function onSettingsChange(componentDefinition, formReference) { const { component, schemaVersion, version, model: { name: modelName, registrant: modelRegistrant, version: modelVersion, category: modelCategory, }, } = componentDefinition; /** * Handles actual design-json change in response to form-data change * @param {*} formData */ return function handledesignJsonChange(formData) { const referKey = formReference.current.referKey; const { name, namespace, labels, annotations, ...configuration } = formData; const newInput = { id: referKey, schemaVersion, version, component, displayName: name, model: { name: modelName, version: modelVersion, category: modelCategory, registrant: modelRegistrant, }, configuration: { metadata: { labels, annotations, namespace, }, ...configuration, }, }; setDesignJson((prev) => { let newestKey = false; const currentJson = prev.components?.map((val) => { if (val.id == referKey) { newestKey = true; return newInput; } return val; }) || []; if (!newestKey) { currentJson.push(newInput); } return { ...prev, components: [...currentJson] }; }); }; }
@param {Types.ComponentDefinition} componentDefinition
onSettingsChange ( componentDefinition , formReference )
javascript
meshery/meshery
ui/components/configuratorComponents/MeshModel/hooks/useDesignLifecycle.js
https://github.com/meshery/meshery/blob/master/ui/components/configuratorComponents/MeshModel/hooks/useDesignLifecycle.js
Apache-2.0
export const getFilters = (filterString, filterSchema) => { const filters = {}; const filterValuePairs = filterString.split(Delimiter.FILTER); filterValuePairs.forEach((filterValuePair) => { const [filter, value] = filterValuePair.split(Delimiter.FILTER_VALUE); if (getFilterByValue(filter, filterSchema)?.multiple == false) { filters[filter] = value; return; } if (filter && value) { filters[filter] = filters[filter] || []; if (!filters[filter].includes(value)) { filters[filter].push(value); } } }); return filters; };
Parses a filter string and returns a filter object. @param {string} filterString - The input filter string of the form "type:value type2:value2 type:value2". @returns {Object} - The filter object with types as keys and arrays of values as values.
getFilters
javascript
meshery/meshery
ui/components/TypingFilter/utils.js
https://github.com/meshery/meshery/blob/master/ui/components/TypingFilter/utils.js
Apache-2.0
export const ValidateDesign = ({ design, currentNodeId, validationMachine }) => { const validationResults = useDesignSchemaValidationResults(validationMachine); const isValidating = useIsValidatingDesignSchema(validationMachine); const designName = design.name; const { configurableComponents, annotationComponents } = processDesign(design); const totalErrors = Object.values(validationResults || {}).reduce( (acc, serviceResult) => acc + (serviceResult?.errors?.length || 0), 0, ); useEffect(() => { validationMachine.send(designValidatorCommands.validateDesignSchema({ design })); }, []); if (isValidating) { return <Loading message="Validating Design" />; } if (!validationResults) { return null; } if (typeof validationResults === 'string') { return <Typography variant="h6">{validationResults}</Typography>; } return ( <ValidationResults validationResults={validationResults} currentNodeId={currentNodeId} errorCount={totalErrors} compCount={configurableComponents.length} annotationCount={annotationComponents.length} design={designName} validationMachine={validationMachine} /> ); };
@param {Design} design is the design file to be validated @returns
ValidateDesign
javascript
meshery/meshery
ui/components/DesignLifeCycle/ValidateDesign.js
https://github.com/meshery/meshery/blob/master/ui/components/DesignLifeCycle/ValidateDesign.js
Apache-2.0
useEffect(() => { fetchTestProfiles(); fetchTests(); }, []);
fetch performance profiles when the page loads
(anonymous)
javascript
meshery/meshery
ui/components/MesheryPerformance/Dashboard.js
https://github.com/meshery/meshery/blob/master/ui/components/MesheryPerformance/Dashboard.js
Apache-2.0
export const generateTestName = (name, meshName) => { if (!name || name.trim() === '') { const mesh = meshName === '' || meshName === 'None' ? 'No mesh' : meshName; return `${mesh}_${new Date().getTime()}`; } return name; };
generateTestName takes in test name and service mesh name and generates a random name (if test name is an empty string or is falsy) or will return the given name @param {string} name @param {string} meshName @returns {string}
generateTestName
javascript
meshery/meshery
ui/components/MesheryPerformance/helper.js
https://github.com/meshery/meshery/blob/master/ui/components/MesheryPerformance/helper.js
Apache-2.0
function generateCalendarEventsFromResults(results) { return results.map(({ test_start_time, name, runner_results }, index) => { // Remove incorrect timezone info const ntzStartTime = new Date( moment(test_start_time).utcOffset(test_start_time).format('MM/DD/YYYY HH:mm'), ); const ntzEndTime = ntzStartTime; ntzEndTime.setSeconds(ntzEndTime.getSeconds() + runner_results.ActualDuration / 1e9); return { title: name, start: ntzStartTime, end: ntzEndTime, resource: index, }; }); }
generateCalendarEventsFromResults takes in performance results data and generate calendar events from them @param {{ meshery_id: string, name: string, test_start_time: string, runner_results: { ActualDuration: number } }[]} results performance results @returns {{ title?: string, start?: Date, end?: Date, resource?: any }[]}
generateCalendarEventsFromResults ( results )
javascript
meshery/meshery
ui/components/MesheryPerformance/PerformanceCalendar.js
https://github.com/meshery/meshery/blob/master/ui/components/MesheryPerformance/PerformanceCalendar.js
Apache-2.0
export const waitForEvent = async ({ page, eventType, timeout_after = 3000 }) => { await waitFor( () => page.evaluate(() => { const debuggerActor = window?.debuggingActorRef; if (!debuggerActor) { return null; } return debuggerActor?.getSnapshot?.()?.status == 'active'; }), timeout_after, );
Waits for a specific event from the XState debugger. @param {Object} params - Parameters object. @param {import('playwright').Page} params.page - Playwright page instance. @param {string} params.eventType - The type of event to wait for. @param {number} [params.timeout_after=3000] - Timeout duration in milliseconds. @returns {Promise<import('playwright').JSHandle>} - Promise resolving to the handle of the received event.
waitForEvent
javascript
meshery/meshery
ui/tests/e2e/utils/inspectXstate.js
https://github.com/meshery/meshery/blob/master/ui/tests/e2e/utils/inspectXstate.js
Apache-2.0
constructor(page) { this.page = page; }
@param {import("@playwright/test").Page} page
constructor ( page )
javascript
meshery/meshery
ui/tests/e2e/fixtures/pages.js
https://github.com/meshery/meshery/blob/master/ui/tests/e2e/fixtures/pages.js
Apache-2.0
export default function debounce(func, timeout = 500) { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => { func.apply(this, args); }, timeout); }; }
The debouncing mechanism for calling the function on the timeout reached. @param {Function} func @param {Number} timeout time in miliseconds @returns
debounce ( func , timeout = 500 )
javascript
meshery/meshery
ui/utils/debounce.js
https://github.com/meshery/meshery/blob/master/ui/utils/debounce.js
Apache-2.0
export default function getMostRecentVersion(versionList) { if (!versionList) return; const stableList = []; const alphaList = []; const betaList = []; versionList.forEach((apiVersion) => { const isStable = /^v[0-9]$/.test(apiVersion); // returns true if matches v1-v9 const isAlpha = apiVersion.includes('alpha'); // returns true if matches alpha in string const isBeta = apiVersion.includes('beta'); // returns true if matches beta in string isStable && stableList.push(apiVersion); isAlpha && alphaList.push(apiVersion); isBeta && betaList.push(apiVersion); }); stableList.sort().reverse(); alphaList.sort().reverse(); betaList.sort().reverse(); // priority order: stable > beta > alpha return stableList?.[0] || betaList?.[0] || alphaList?.[0] || versionList?.[0]; }
returns the API Version that should be used and is most stable Priority Order v1 > v1beta > v1alpha @param {Array.<String>} versionList
getMostRecentVersion ( versionList )
javascript
meshery/meshery
ui/utils/versionSort.js
https://github.com/meshery/meshery/blob/master/ui/utils/versionSort.js
Apache-2.0
export function versionSortComparatorFn(versionA, versionB) { if (!versionA || !versionB) { return; } if (versionA === WILDCARD_V || versionB === WILDCARD_V) { // wildcard support return -1; } const verA = versionA.split('.'); const verB = versionB.split('.'); for (let i = 0; i < verA.length && i < verB.length; i++) { let vA = verA[i]; let vB = verB[i]; // index 0 is the start of the version, remove v if present for proper sorting if (i == 0) { vA = removeVFromVersion(vA); vB = removeVFromVersion(vB); } // move to next comparison if (vA - vB === 0) { continue; } return vA - vB; } }
Sorts version in "INCREASING ORDER", apply reverse if wanted to sort in descreasing order @param {string} versionA @param {string} versionB @returns
versionSortComparatorFn ( versionA , versionB )
javascript
meshery/meshery
ui/utils/versionSort.js
https://github.com/meshery/meshery/blob/master/ui/utils/versionSort.js
Apache-2.0
export const sortByVersionInDecreasingOrder = (versions) => { if (!versions) { return; } // add wildcard only in the case of multiple distinct versions let wildCardV = []; if (versions.length > 1) { wildCardV = [WILDCARD_V]; } return [...wildCardV, ...[...versions].sort(versionSortComparatorFn).reverse()]; };
usually when you sort the version by string, the version 10.0.0 < 2.0.0, because of string sort, ideally, it should be 10.0.0 > 2.0.0 [ "2.2.1", "2.10.11", "10.1.2", "10.1.1" ] using this comparator function returns [ '10.1.2', '10.1.1', '2.10.11', '2.2.1' ] @param {Array.<string>} versions @returns Versions sorted in decreasing order
sortByVersionInDecreasingOrder
javascript
meshery/meshery
ui/utils/versionSort.js
https://github.com/meshery/meshery/blob/master/ui/utils/versionSort.js
Apache-2.0
export function getGreaterVersion(v1, v2) { const comparatorResult = versionSortComparatorFn(v1, v2); if (comparatorResult >= 0) { return v1; } return v2; }
Get Greater version between the two versions passed @param {string} v1 @param {string} v2
getGreaterVersion ( v1 , v2 )
javascript
meshery/meshery
ui/utils/versionSort.js
https://github.com/meshery/meshery/blob/master/ui/utils/versionSort.js
Apache-2.0
function groupModelsByVersion(models) { if (!models) { return []; } let modelMap = {}; models.forEach((model) => { const modelMapCurr = modelMap[model.name]; if (modelMapCurr) { modelMap[model.name].version = [...new Set([...modelMapCurr.version, model.version])]; // remove duplicate entries for version } else { model.version = [model.version]; // the version is a string, to derive consistency the version is changed to array modelMap[model.name] = model; } }); return Object.values(modelMap); }
@param {Array} models @returns {Array} the de-duplicated models array with all the versions available
groupModelsByVersion ( models )
javascript
meshery/meshery
ui/utils/versionSort.js
https://github.com/meshery/meshery/blob/master/ui/utils/versionSort.js
Apache-2.0
export const ziCalc = (p = 1) => { if (p >= 1) { // 1 is the least power for zIndex let zIndex = ''; for (let i = 0; i < p; i++) { zIndex = zIndex + '9'; } return zIndex; } `0`; };
function used to calculate the zIndex @param {number} p - power of zIndex - directly proportional to `zIndex` (css property) value @returns {string} zIndex
ziCalc
javascript
meshery/meshery
ui/utils/zIndex.js
https://github.com/meshery/meshery/blob/master/ui/utils/zIndex.js
Apache-2.0
function getHost() { return window.location.host; }
Finds the host on which Meshery is running, it could be localhost:{port} or an IP adress or a webadress @returns {string} application host
getHost ( )
javascript
meshery/meshery
ui/utils/webApis.js
https://github.com/meshery/meshery/blob/master/ui/utils/webApis.js
Apache-2.0
export function getProtocol() { return window.location.protocol; }
The protocol used by the Meshery Application. It could be , "http:" or "https:" @returns {string}
getProtocol ( )
javascript
meshery/meshery
ui/utils/webApis.js
https://github.com/meshery/meshery/blob/master/ui/utils/webApis.js
Apache-2.0
export function getWebAdress() { return getProtocol() + '//' + getHost(); }
@returns {string} base url on which Meshery is runnning, @example http://localhost:9081
getWebAdress ( )
javascript
meshery/meshery
ui/utils/webApis.js
https://github.com/meshery/meshery/blob/master/ui/utils/webApis.js
Apache-2.0
export function getQueryParam(queryKey) { let queryParamString = window.location.search; queryParamString = queryParamString.replace('?', ''); let queryVal = ''; queryParamString.split('&').forEach((query) => { if (query.split('=')[0] === queryKey) { if (!queryVal) { queryVal = query.split('=')[1]; } } }); return queryVal; }
get value from query param @example for "http://localhost:9081/extension/meshmap?componentInterface=meshmodel" , if called the function like getQueryParam("componentInterface"), then it will return "meshmodel" @param {string} queryKey @returns {string} queryVal
getQueryParam ( queryKey )
javascript
meshery/meshery
ui/utils/webApis.js
https://github.com/meshery/meshery/blob/master/ui/utils/webApis.js
Apache-2.0
export default function normalizeURI(uri) { if (!uri.startsWith('/')) return '/' + uri; return uri; }
normalizeURI takes in a uri and adds "/" to the start of it if they they if it doesn't them already The goal is to be able to easily append the uris without concerning about the slashes @param {string} uri @returns {string}
normalizeURI ( uri )
javascript
meshery/meshery
ui/utils/normalizeURI.js
https://github.com/meshery/meshery/blob/master/ui/utils/normalizeURI.js
Apache-2.0
export function groupWorkloadByVersion(meshfilteredWorkloads) { let versionedFilteredWorkloads = {}; meshfilteredWorkloads.map((wtSet) => { const version = wtSet.workload?.oam_definition?.spec?.metadata?.meshVersion || wtSet.workload.oam_definition?.spec?.metadata?.version || 'Meshery'; if (version) { let versionedFilteredMesh = versionedFilteredWorkloads[version] || []; versionedFilteredMesh.push(wtSet); versionedFilteredWorkloads[version] = versionedFilteredMesh; } }); return versionedFilteredWorkloads; }
Filter-workloads by versions @param {Object} meshfilteredWorkloads array of mesh-filtered-workloads @returns {Array.Array.<Object>} versioned and typed filtered workloads
groupWorkloadByVersion ( meshfilteredWorkloads )
javascript
meshery/meshery
ui/utils/workloadFilter.js
https://github.com/meshery/meshery/blob/master/ui/utils/workloadFilter.js
Apache-2.0
export function isEmptyObj(obj) { return ( !obj || (obj && Object.keys(obj).length === 0 && Object.getPrototypeOf(obj) === Object.prototype) ); }
Check if an object is empty @param {Object} obj @returns {Boolean} if obj is empty
isEmptyObj ( obj )
javascript
meshery/meshery
ui/utils/utils.js
https://github.com/meshery/meshery/blob/master/ui/utils/utils.js
Apache-2.0
export function isEmptyArr(arr) { return arr && arr.length === 0; }
Check if array is empty @param {Array} arr @returns {Boolean} if arr is empty
isEmptyArr ( arr )
javascript
meshery/meshery
ui/utils/utils.js
https://github.com/meshery/meshery/blob/master/ui/utils/utils.js
Apache-2.0
export function isEqualArr(arr1, arr2, orderMatters = true) { if (arr1 === arr2) return true; if (arr1 == null || arr2 == null) return false; if (arr1.length !== arr2.length) return false; if (!orderMatters) { arr1.sort(); arr2.sort(); } for (var i = 0; i < arr1.length; ++i) { if (arr1[i] !== arr2[i]) return false; } return true; }
Check if two arrays are equal @param {Array} arr1 @param {Array} arr2 @param {Boolean} orderMatters @returns
isEqualArr ( arr1 , arr2 , orderMatters = true )
javascript
meshery/meshery
ui/utils/utils.js
https://github.com/meshery/meshery/blob/master/ui/utils/utils.js
Apache-2.0
export function scrollToTop(behavior = 'smooth') { setTimeout(() => { window.scrollTo({ top: 0, left: 0, behavior, }); }, 0); }
ScrollToTop scrolls the window to top @param {( "auto" |"smooth" |"inherit" |"initial" |"revert" |"unset" )} behavior : scroll-behaviour, see https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior
scrollToTop ( behavior = 'smooth' )
javascript
meshery/meshery
ui/utils/utils.js
https://github.com/meshery/meshery/blob/master/ui/utils/utils.js
Apache-2.0
export function randomPatternNameGenerator() { return 'meshery_' + Math.floor(trueRandom() * 100); }
Generates random Pattern Name with the prefix meshery_
randomPatternNameGenerator ( )
javascript
meshery/meshery
ui/utils/utils.js
https://github.com/meshery/meshery/blob/master/ui/utils/utils.js
Apache-2.0
export function getComponentsinFile(file) { if (file) { try { let keys = Object.keys(jsYaml.load(file).services); return keys.length; } catch (e) { if (e.reason?.includes('expected a single document')) { return file.split('---').length; } } } return 0; }
Returns number of components in Pattern/Application/Filters file
getComponentsinFile ( file )
javascript
meshery/meshery
ui/utils/utils.js
https://github.com/meshery/meshery/blob/master/ui/utils/utils.js
Apache-2.0
export function getDecodedFile(dataUrl) { // Extract base64-encoded content const [, base64Content] = dataUrl.split(';base64,'); // Decode base64 content return atob(base64Content); }
Gets the raw b64 file and convert it to Binary @param {string} file @returns
getDecodedFile ( dataUrl )
javascript
meshery/meshery
ui/utils/utils.js
https://github.com/meshery/meshery/blob/master/ui/utils/utils.js
Apache-2.0
export const getUnit8ArrayDecodedFile = (dataUrl) => { // Extract base64 content const [, base64Content] = dataUrl.split(';base64,'); // Decode base64 content const decodedContent = atob(base64Content); // Convert decoded content to Uint8Array directly const uint8Array = Uint8Array.from(decodedContent, (char) => char.charCodeAt(0)); return Array.from(uint8Array); };
Gets the raw b64 file and convert it to uint8Array @param {string} file @returns {array} - return array of uint8Array
getUnit8ArrayDecodedFile
javascript
meshery/meshery
ui/utils/utils.js
https://github.com/meshery/meshery/blob/master/ui/utils/utils.js
Apache-2.0
export const getUnit8ArrayForDesign = (design) => { const uint8Array = Uint8Array.from(design, (char) => char.charCodeAt(0)); return Array.from(uint8Array); };
Gets the stringified meshery pattern_file and convert it to uint8Array @param {string} design @returns {array} - return array of uint8Array *
getUnit8ArrayForDesign
javascript
meshery/meshery
ui/utils/utils.js
https://github.com/meshery/meshery/blob/master/ui/utils/utils.js
Apache-2.0
export const modifyRJSFSchema = (schema, propertyPath, newValue) => { const clonedSchema = _.cloneDeep(schema); _.set(clonedSchema, propertyPath, newValue); return clonedSchema; };
Change the value of a property in RJSF schema @param {string} schema - RJSF schema @param {string} propertyPath - path of the property to be modified @param {any} newValue - new value to be set @returns {object} - modified schema
modifyRJSFSchema
javascript
meshery/meshery
ui/utils/utils.js
https://github.com/meshery/meshery/blob/master/ui/utils/utils.js
Apache-2.0
export function getSharableCommonHostAndprotocolLink(sharedResource) { const webAddr = getWebAdress() + '/extension/meshmap'; if (sharedResource?.application_file) { return `${webAddr}?${APPLICATION}=${sharedResource.id}`; } if (sharedResource?.pattern_file) { return `${webAddr}?mode=${DESIGN}&${DESIGN}=${sharedResource.id}`; } if (sharedResource?.filter_resource) { return `${webAddr}?${FILTER}=${sharedResource.id}`; } return ''; }
get sharable link with same and host and protocol, here until meshery cloud interception @param {Object.<string,string>} sharedResource @returns {string}
getSharableCommonHostAndprotocolLink ( sharedResource )
javascript
meshery/meshery
ui/utils/utils.js
https://github.com/meshery/meshery/blob/master/ui/utils/utils.js
Apache-2.0
export const getColumnValue = (rowData, columnName, columns) => { const columnIndex = columns.findIndex((column) => column.name === columnName); return rowData[columnIndex]; };
Retrieves the value of a specified column from a row of data. @param {Array} rowData - The array representing the row of data. @param {string} columnName - The name of the column whose value you want to retrieve. @param {Array} columns - An array of column definitions. @returns {*} The value of the specified column in the row, or undefined if not found.
getColumnValue
javascript
meshery/meshery
ui/utils/utils.js
https://github.com/meshery/meshery/blob/master/ui/utils/utils.js
Apache-2.0
export const getVisibilityColums = (columns) => { return columns.filter((col) => col?.options?.display !== false); };
Filter the columns to show in visibility switch. @param {string} columns - Full list of columns name.
getVisibilityColums
javascript
meshery/meshery
ui/utils/utils.js
https://github.com/meshery/meshery/blob/master/ui/utils/utils.js
Apache-2.0
export const createScrollHandler = (scrollingView, setPage, scrollRef, buffer) => (event) => { const div = event.target; if (div.scrollTop >= div.scrollHeight - div.clientHeight - buffer) { setPage((prevPage) => ({ ...prevPage, [scrollingView]: prevPage[scrollingView] + 1, })); } scrollRef.current = div.scrollTop; };
Handle scroll event for infinite scrolling @param {string} scrollingView - The view identifier for which scrolling is handled @param {function} setPage - The function to set the page state @param {object} scrollRef - Reference to the scroll element @param {number} buffer - The buffer value for infinite scrolling @returns {function} - Scroll event handler function
createScrollHandler
javascript
meshery/meshery
ui/utils/utils.js
https://github.com/meshery/meshery/blob/master/ui/utils/utils.js
Apache-2.0
export const camelcaseToSnakecase = (value) => { return value?.replace(/[A-Z]/g, (match) => `_${match.toLowerCase()}`); };
Add underscore to camal case variable name. @param {string} value - An array of column definitions.
camelcaseToSnakecase
javascript
meshery/meshery
ui/utils/utils.js
https://github.com/meshery/meshery/blob/master/ui/utils/utils.js
Apache-2.0
export function getWindowDimensions() { const { innerWidth: width, innerHeight: height } = window; return { width, height, }; }
getWindowDimensions - Returns the width and height of the window @returns {object} {width, height}
getWindowDimensions ( )
javascript
meshery/meshery
ui/utils/dimension.js
https://github.com/meshery/meshery/blob/master/ui/utils/dimension.js
Apache-2.0
export default function PascalCaseToKebab(str) { return pascalCaseToCamelCase(str).replace(/[A-Z]/g, '-$&').toLowerCase(); }
PascalCaseToKebab takes in a string in pascal case and returns a kebab cased string @param {string} str string in pascal case or camel case @returns
PascalCaseToKebab ( str )
javascript
meshery/meshery
ui/utils/PascalCaseToKebab.js
https://github.com/meshery/meshery/blob/master/ui/utils/PascalCaseToKebab.js
Apache-2.0
function pascalCaseToCamelCase(str) { return str.charAt(0).toLowerCase() + str.slice(1); }
pascalCaseToCamelCase takes in a string in pascal case and returns it in camelcase format @param {string} str string that needs to be transformed
pascalCaseToCamelCase ( str )
javascript
meshery/meshery
ui/utils/PascalCaseToKebab.js
https://github.com/meshery/meshery/blob/master/ui/utils/PascalCaseToKebab.js
Apache-2.0
export function ctxUrl(url, ctx) { if (ctx?.length) { const contextQuery = ctx.map((context) => `contexts=${context}`).join('&'); return `${url}?${contextQuery}`; } return url; }
A function to be used by the requests sent for the operations based on multi-context support @param {string} url The request URL @param {Array.<string>} ctx The context Array @returns {string} The final query-parametrised URL
ctxUrl ( url , ctx )
javascript
meshery/meshery
ui/utils/multi-ctx.js
https://github.com/meshery/meshery/blob/master/ui/utils/multi-ctx.js
Apache-2.0
export const getK8sClusterIdsFromCtxId = (selectedContexts, k8sconfig) => { if (!selectedContexts || !k8sconfig || selectedContexts.length === 0) { return []; } if (selectedContexts.includes('all')) { return k8sconfig.map((cfg) => cfg?.kubernetes_server_id); } const clusterIds = []; selectedContexts.forEach((context) => { const clusterId = k8sconfig.find((cfg) => cfg.id === context)?.kubernetes_server_id; if (clusterId) { clusterIds.push(clusterId); } }); return clusterIds; };
The function takes in all the context and returns their respective cluster IDs associated to them @param {Array.<string>} selectedContexts @param {Array.<string>} k8sconfig @returns
getK8sClusterIdsFromCtxId
javascript
meshery/meshery
ui/utils/multi-ctx.js
https://github.com/meshery/meshery/blob/master/ui/utils/multi-ctx.js
Apache-2.0
export function getFirstCtxIdFromSelectedCtxIds(selectedK8sContexts, k8sConfig) { if (!selectedK8sContexts?.length) { return ''; } if (selectedK8sContexts?.includes('all')) { return k8sConfig[0]?.id; } return selectedK8sContexts[0]; }
@param {Array.<string>} selectedK8sContexts @param {Array.<string>} k8sConfig @returns {string} The context ID
getFirstCtxIdFromSelectedCtxIds ( selectedK8sContexts , k8sConfig )
javascript
meshery/meshery
ui/utils/multi-ctx.js
https://github.com/meshery/meshery/blob/master/ui/utils/multi-ctx.js
Apache-2.0
export function getK8sConfigIdsFromK8sConfig(k8sConfig) { if (!k8sConfig || !k8sConfig.length) { return []; } return k8sConfig.map((cfg) => cfg.id); }
Get the k8sConfigIds of K8sconfig @param {Array.<Object>} k8sConfig @returns
getK8sConfigIdsFromK8sConfig ( k8sConfig )
javascript
meshery/meshery
ui/utils/multi-ctx.js
https://github.com/meshery/meshery/blob/master/ui/utils/multi-ctx.js
Apache-2.0
export function getK8sContextFromClusterId(clusterId, k8sConfig) { const cluster = k8sConfig.find((cfg) => cfg.kubernetes_server_id === clusterId); if (!cluster) { return {}; } return cluster; }
@param {string} clusterId Kubernetes Cluster ID @param {Array<Object>} k8sConfig Kubernetes config @returns {string} Kubernetes context
getK8sContextFromClusterId ( clusterId , k8sConfig )
javascript
meshery/meshery
ui/utils/multi-ctx.js
https://github.com/meshery/meshery/blob/master/ui/utils/multi-ctx.js
Apache-2.0
export function getClusterNameFromClusterId(clusterId, k8sConfig) { const cluster = k8sConfig.find((cfg) => cfg.kubernetes_server_id === clusterId); if (!cluster) { return ''; } return cluster.name; }
@param {string} clusterId Kubernetes Cluster ID @param {Array<Object>} k8sConfig Kubernetes config @returns {string} Kubernetes cluster name
getClusterNameFromClusterId ( clusterId , k8sConfig )
javascript
meshery/meshery
ui/utils/multi-ctx.js
https://github.com/meshery/meshery/blob/master/ui/utils/multi-ctx.js
Apache-2.0
export function getClusterNameFromConnectionId(connId, k8sConfig) { const cluster = k8sConfig.find((cfg) => cfg.connection_id === connId); if (!cluster) { return ''; } return cluster.name; }
@param {string} connectionId Kubernetes Connection ID @param {Array<Object>} k8sConfig Kubernetes config @returns {string} Kubernetes cluster name
getClusterNameFromConnectionId ( connId , k8sConfig )
javascript
meshery/meshery
ui/utils/multi-ctx.js
https://github.com/meshery/meshery/blob/master/ui/utils/multi-ctx.js
Apache-2.0
export function getConnectionIdFromClusterId(clusterId, k8sConfig) { const cluster = k8sConfig.find((cfg) => cfg.kubernetes_server_id === clusterId); if (!cluster) { return ''; } return cluster.connection_id; }
@param {string} clusterId Kubernetes Cluster ID @param {Array<Object>} k8sConfig Kubernetes config @returns {string} Kubernetes connection ID
getConnectionIdFromClusterId ( clusterId , k8sConfig )
javascript
meshery/meshery
ui/utils/multi-ctx.js
https://github.com/meshery/meshery/blob/master/ui/utils/multi-ctx.js
Apache-2.0
export function getClusterNameFromCtxId(ctxId, k8sConfig) { const cluster = k8sConfig.find((cfg) => cfg.id === ctxId); if (!cluster) { return ''; } return cluster.name; }
@param {string} ctxId Kubernetes context ID @param {Array<Object>} k8sConfig Kubernetes config @returns {string} Kubernetes cluster name
getClusterNameFromCtxId ( ctxId , k8sConfig )
javascript
meshery/meshery
ui/utils/multi-ctx.js
https://github.com/meshery/meshery/blob/master/ui/utils/multi-ctx.js
Apache-2.0
export function getConnectionIDsFromContextIds(contexts, k8sConfig) { const filteredK8sConnfigs = k8sConfig.filter((config) => contexts.some((context) => context == config.id), ); return filteredK8sConnfigs.map((config) => config.connection_id); }
@param {Array<Object>} contextIDs Kubernetes context ids @param {Array<Object>} k8sConfig Kubernetes config @returns {Array<string>} array of connection ID for given kubernetes contexts
getConnectionIDsFromContextIds ( contexts , k8sConfig )
javascript
meshery/meshery
ui/utils/multi-ctx.js
https://github.com/meshery/meshery/blob/master/ui/utils/multi-ctx.js
Apache-2.0
export const findNestedObject = (object, condition) => { const stack = [object]; while (stack.length) { const currentObject = stack.pop(); if (condition(currentObject)) { return currentObject; } if (_.isObject(currentObject) || _.isArray(currentObject)) { if (_.isObject(currentObject) || _.isArray(currentObject)) { const values = _.values(currentObject).filter((value) => value !== currentObject.models); stack.push(...values); } } } return null; };
Finds the first nested object in a tree-like structure that satisfies a given condition. @param {Object} object - The root object to start the search. @param {Function} condition - A function that takes an object as an argument and returns a boolean indicating if the condition is met. @returns {Object|null} - The first object that satisfies the condition, or null if no matching object is found.
findNestedObject
javascript
meshery/meshery
ui/utils/objects.js
https://github.com/meshery/meshery/blob/master/ui/utils/objects.js
Apache-2.0
export const filterEmptyFields = (data) => { if (!data) { return {}; } return Object.keys(data).reduce((acc, key) => { if (data[key] !== undefined && data[key] !== '') { acc[key] = data[key]; } return acc; }, {}); };
Accept object and removes empty properties from object. *
filterEmptyFields
javascript
meshery/meshery
ui/utils/objects.js
https://github.com/meshery/meshery/blob/master/ui/utils/objects.js
Apache-2.0
export default function ExtensionPointSchemaValidator(type) { switch (type) { case 'navigator': return NavigatorExtensionSchemaDecoder; case 'user_prefs': return UserPrefsExtensionSchemaDecoder; case 'collaborator': return CollaboratorExtensionSchemaDecoder; case 'account': return AccountExtensionSchemaDecoder; default: return () => {}; } }
ExtensionPointSchemaValidator returns the schema validator based on the type passed to the function @param {string} type - Type of Schema validator needed. Valid types are - navigator, userprefs, account
ExtensionPointSchemaValidator ( type )
javascript
meshery/meshery
ui/utils/ExtensionPointSchemaValidator.js
https://github.com/meshery/meshery/blob/master/ui/utils/ExtensionPointSchemaValidator.js
Apache-2.0
function UserPrefsExtensionSchemaDecoder(content) { if (Array.isArray(content)) { return content.map((item) => { return { component: item.component || '' }; }); } return []; }
@param {*} content @returns {UserPrefSchema[]}
UserPrefsExtensionSchemaDecoder ( content )
javascript
meshery/meshery
ui/utils/ExtensionPointSchemaValidator.js
https://github.com/meshery/meshery/blob/master/ui/utils/ExtensionPointSchemaValidator.js
Apache-2.0
function CollaboratorExtensionSchemaDecoder(content) { if (Array.isArray(content)) { return content.map((item) => { return { component: item.component || '' }; }); } return []; }
@param {*} content @returns {CollaboratorSchema[]}
CollaboratorExtensionSchemaDecoder ( content )
javascript
meshery/meshery
ui/utils/ExtensionPointSchemaValidator.js
https://github.com/meshery/meshery/blob/master/ui/utils/ExtensionPointSchemaValidator.js
Apache-2.0
export function timeAgo(date, options = {}) { const fromDate = new Date(date); let now = new Date(); if (process.env.UNDER_TEST === 'true') { // For testing, we consider the current moment to be 3 months from the dates we are testing. const days = 24 * 3600 * 1000; // in ms now = new Date(fromDate.getTime() + 90 * days); } return formatDuration(now.getTime() - fromDate.getTime(), options); }
Show the time passed since the given date, in the desired format. @param date - The date since which to calculate the duration. @param options - `format` takes "brief" or "mini". "brief" rounds the date and uses the largest suitable unit (e.g. "4 weeks"). "mini" uses something like "4w" (for 4 weeks). @returns The formatted date.
timeAgo ( date , options = { } )
javascript
meshery/meshery
ui/utils/k8s-utils.js
https://github.com/meshery/meshery/blob/master/ui/utils/k8s-utils.js
Apache-2.0
export function formatDuration(duration, options) { const { format = 'brief' } = options; if (format === 'brief') { return humanize(duration, { fallbacks: ['en'], round: true, largest: 1, }); } return humanize(duration, { language: 'en-mini', spacer: '', fallbacks: ['en'], round: true, largest: 1, }); }
Format a duration in milliseconds to a human-readable string. @param duration - The duration in milliseconds. @param options - `format` takes "brief" or "mini". "brief" rounds the date and uses the largest suitable unit (e.g. "4 weeks"). "mini" uses something like "4w" (for 4 weeks). @returns The formatted duration. *
formatDuration ( duration , options )
javascript
meshery/meshery
ui/utils/k8s-utils.js
https://github.com/meshery/meshery/blob/master/ui/utils/k8s-utils.js
Apache-2.0
const openEvent = (eventId) => { rtkStore.dispatch(toggleNotificationCenter()); };
Opens an event in the notification center. @param {string} eventId - The ID of the event to be opened.
openEvent
javascript
meshery/meshery
ui/utils/hooks/useNotification.js
https://github.com/meshery/meshery/blob/master/ui/utils/hooks/useNotification.js
Apache-2.0
export function withNotify(Component) { return function WrappedWithNotify(props) { const { notify } = useNotification(); return <Component {...props} notify={notify} />; }; }
A higher-order component that provides the `notify` function as a prop to a class-based component. @param {React.Component} Component - The class-based component to be wrapped. @returns {React.Component} The wrapped component with the `notify` prop.
withNotify ( Component )
javascript
meshery/meshery
ui/utils/hooks/useNotification.js
https://github.com/meshery/meshery/blob/master/ui/utils/hooks/useNotification.js
Apache-2.0
export const successHandlerGenerator = (notify, msg, cb) => (res) => { if (res !== undefined) { if (cb !== undefined) cb(res); if (typeof res == 'object') { res = JSON.stringify(res); } notify({ message: `${msg}`, details: `${res}`, event_type: EVENT_TYPES.SUCCESS }); } };
A function that generates a success handler for notifying. @param {function} notify - A function to notify. @param {string} msg - The message to be displayed. @param {function} cb - An optional callback function. @returns {function} - A success handler function.
successHandlerGenerator
javascript
meshery/meshery
ui/utils/helpers/common.js
https://github.com/meshery/meshery/blob/master/ui/utils/helpers/common.js
Apache-2.0
export const errorHandlerGenerator = (notify, msg, cb) => (err) => { if (cb !== undefined) cb(err); err = typeof err !== 'string' ? err.toString() : err; notify({ message: `${msg}`, details: err, event_type: EVENT_TYPES.ERROR }); };
A function that generates an error handler for notifying. @param {function} notify - A function to notify. @param {string} msg - The message to be displayed. @param {function} cb - An optional callback function. @returns {function} - An error handler function
errorHandlerGenerator
javascript
meshery/meshery
ui/utils/helpers/common.js
https://github.com/meshery/meshery/blob/master/ui/utils/helpers/common.js
Apache-2.0
export const fetchAvailableAdapters = () => { return new Promise((res, rej) => dataFetch( '/api/system/adapters', { method: 'GET', credentials: 'include', }, (result) => { if (typeof result !== 'undefined') { const options = result.map((res) => ({ value: res.adapter_location, label: res.adapter_location, name: res.name, version: res.version, })); res(options); } }, (err) => rej(err), ), ); };
fetch the adapters that are available
fetchAvailableAdapters
javascript
meshery/meshery
ui/utils/helpers/serviceMeshes.js
https://github.com/meshery/meshery/blob/master/ui/utils/helpers/serviceMeshes.js
Apache-2.0
export const pingKubernetes = (successHandler, errorHandler, connectionId) => { dataFetch( '/api/system/kubernetes/ping?connection_id=' + connectionId, { credentials: 'include' }, successHandler, errorHandler, ); };
Pings kuberenetes server endpoint @param {(res) => void} successHandler @param {(err) => void} errorHandler
pingKubernetes
javascript
meshery/meshery
ui/utils/helpers/kubernetesHelpers.js
https://github.com/meshery/meshery/blob/master/ui/utils/helpers/kubernetesHelpers.js
Apache-2.0
export const isKubernetesConnected = (isClusterConfigured, kubernetesPingStatus) => { if (isClusterConfigured) { if (kubernetesPingStatus) return true; } return false; };
Figures out if kubernetes connection is established or not @param {true|false} isClusterConfigured - data received from meshery server as to whether or not the server config is found @param {true|false} kubernetesPingStatus - found after pinging the kubernetes server endpoint @return {true|false}
isKubernetesConnected
javascript
meshery/meshery
ui/utils/helpers/kubernetesHelpers.js
https://github.com/meshery/meshery/blob/master/ui/utils/helpers/kubernetesHelpers.js
Apache-2.0
export function extractKubernetesCredentials(data) { const credentials = { credentialName: data.name, secret: { clusterName: data.cluster.name, clusterServerURL: data.cluster.cluster.server, auth: { clusterUserName: data.auth.name, clusterToken: data.auth.user.token, clusterClientCertificateData: data.auth.user['client-certificate-data'], clusterCertificateAuthorityData: data.cluster.cluster['certificate-authority-data'], clusterClientKeyData: data.auth.user['client-key-data'], }, }, }; return credentials; }
Extracts kubernetes credentials from the data received from the server @param {object} data - k8's config data received from the server @returns {object} - k8's credentials
extractKubernetesCredentials ( data )
javascript
meshery/meshery
ui/utils/helpers/kubernetesHelpers.js
https://github.com/meshery/meshery/blob/master/ui/utils/helpers/kubernetesHelpers.js
Apache-2.0
export const getOperatorStatusFromQueryResult = (res) => { var operatorInformation = { operatorInstalled: false, NATSInstalled: false, meshSyncInstalled: false, operatorSwitch: false, operatorVersion: 'N/A', meshSyncVersion: 'N/A', NATSVersion: 'N/A', }; if (res.operator?.error) { return [false, operatorInformation]; } if (res.operator?.status === 'ENABLED') { res.operator?.controllers?.forEach((controller) => { operatorInformation = { ...operatorInformation, [controller.name]: controller, }; if (controller.name === 'broker' && controller.status === 'ENABLED') { operatorInformation = { ...operatorInformation, NATSInstalled: true, NATSVersion: controller.version, }; } else if (controller.name === 'meshsync' && controller.status === 'ENABLED') { operatorInformation = { ...operatorInformation, meshSyncInstalled: true, meshSyncVersion: controller.version, }; } }); operatorInformation = { ...operatorInformation, operatorInstalled: true, operatorVersion: res.operator?.version, }; return [true, operatorInformation]; } return [false, operatorInformation]; };
Returns the connection status of Operator, Meshsync, and Broker (NATS) using the result of graphql `operatorStatusQuery` query @param {object} res - Result of the graphql query @returns {[boolean, object]} result - array with final states and reachability of operator
getOperatorStatusFromQueryResult
javascript
meshery/meshery
ui/utils/helpers/mesheryOperator.js
https://github.com/meshery/meshery/blob/master/ui/utils/helpers/mesheryOperator.js
Apache-2.0
function parseFilters(filters) { return Object.entries(filters).reduce((parsedFilters, [key, value]) => { if (value || typeof value === 'string') { parsedFilters[key] = typeof value === 'string' ? value : JSON.stringify(value, (_key, val) => (val instanceof Set ? [...val] : val)); } return parsedFilters; }, {}); }
Converts an object with filters into a parsed object. This function takes an input object containing filters and returns a parsed object where empty or non-string values are removed, and non-string values (like Sets) are stringified using JSON.stringify. @param {Object} filters - The input object containing filters. @returns {Object} - The parsed object with filters. @example // Example 1: Basic usage const filters = { name: 'John', age: 30, active: true, interests: new Set(['reading', 'gaming']), city: null }; const parsed = parseFilters(filters); // Result: // { // name: 'John', // age: '30', // active: 'true', // interests: '["reading","gaming"]' // } @example // Example 2: Empty values are filtered out const filters = { name: '', age: 0, active: false, city: undefined }; const parsed = parseFilters(filters); // Result: {} (empty object) @example // Example 3: Nested objects are not supported const filters = { person: { name: 'Alice', age: 25 } }; const parsed = parseFilters(filters); // Result: { person: {} }
parseFilters ( filters )
javascript
meshery/meshery
ui/rtk-query/notificationCenter.js
https://github.com/meshery/meshery/blob/master/ui/rtk-query/notificationCenter.js
Apache-2.0
export const initiateQuery = async (query, variables) => { try { return await store.dispatch(query.initiate(variables)); } catch (error) { // Return an object with error details if there's an exception return { data: null, error: error, isFetching: false, isSuccess: false, isLoading: false, isError: true, }; } };
Initiates a query using specified query and variables via store.dispatch. @param {Object} query - The query object containing the initiate function. @param {any} variables - Variables to be passed to the query initiate function. @returns {Promise<Object>} - A Promise resolving with an object containing query execution results.
initiateQuery
javascript
meshery/meshery
ui/rtk-query/utils.js
https://github.com/meshery/meshery/blob/master/ui/rtk-query/utils.js
Apache-2.0
export async function deployPatternWithData(patternFileData, contexts, options) { const { verify = false, dryRun = false } = options; const endpoint = `${ctxUrl(PATTERN_ENDPOINT + '/deploy', contexts)}${ verify ? '&verify=true' : '' }${dryRun ? '&dryRun=true' : ''}`; return await api.post(endpoint, patternFileData); }
Deploys pattern with the content provided to it. It is {pattern_file} property of the patterns meta @param {String} patternFileData @param {String} contexts @param {{verify: Boolean, dryRun: Boolean}} options
deployPatternWithData ( patternFileData , contexts , options )
javascript
meshery/meshery
ui/api/patterns.js
https://github.com/meshery/meshery/blob/master/ui/api/patterns.js
Apache-2.0
export async function fetchRelationships() { return await promisifiedDataFetch(`${MESHMODEL_RELATIONSHIPS_ENDPOINT}`); }
Fetches the Relationships from the server @returns
fetchRelationships ( )
javascript
meshery/meshery
ui/api/meshmodel.js
https://github.com/meshery/meshery/blob/master/ui/api/meshmodel.js
Apache-2.0
export async function searchModels(queryString, options = defaultOptions) { return promisifiedDataFetch( `${MESHMODEL_ENDPOINT}?search=${encodeURI(queryString)}&${optionToQueryConvertor({ ...defaultOptions, ...options, })}`, ); }
@param {string} queryString @param {pageOptions} options
searchModels ( queryString , options = defaultOptions )
javascript
meshery/meshery
ui/api/meshmodel.js
https://github.com/meshery/meshery/blob/master/ui/api/meshmodel.js
Apache-2.0
function matchComponentURI(extensionURI, currentURI) { return currentURI.includes(extensionURI); }
matchComponent matches the extension URI with current given path @param {string} extensionURI @param {string} currentURI @returns {boolean}
matchComponentURI ( extensionURI , currentURI )
javascript
meshery/meshery
ui/pages/extension/[...component].js
https://github.com/meshery/meshery/blob/master/ui/pages/extension/[...component].js
Apache-2.0
constructor(container = '#termynal', options = {}) { this.container = (typeof container === 'string') ? document.querySelector(container) : container; this.pfx = `data-${options.prefix || 'ty'}`; this.startDelay = options.startDelay || parseFloat(this.container.getAttribute(`${this.pfx}-startDelay`)) || 600; this.typeDelay = options.typeDelay || parseFloat(this.container.getAttribute(`${this.pfx}-typeDelay`)) || 90; this.lineDelay = options.lineDelay || parseFloat(this.container.getAttribute(`${this.pfx}-lineDelay`)) || 1500; this.progressLength = options.progressLength || parseFloat(this.container.getAttribute(`${this.pfx}-progressLength`)) || 40; this.progressChar = options.progressChar || this.container.getAttribute(`${this.pfx}-progressChar`) || '█'; this.progressPercent = options.progressPercent || parseFloat(this.container.getAttribute(`${this.pfx}-progressPercent`)) || 100; this.cursor = options.cursor || this.container.getAttribute(`${this.pfx}-cursor`) || '▋'; this.lineData = this.lineDataToElements(options.lineData || []); if (!options.noInit) this.init() }
Construct the widget's settings. @param {(string|Node)=} container - Query selector or container element. @param {Object=} options - Custom settings. @param {string} options.prefix - Prefix to use for data attributes. @param {number} options.startDelay - Delay before animation, in ms. @param {number} options.typeDelay - Delay between each typed character, in ms. @param {number} options.lineDelay - Delay between each line, in ms. @param {number} options.progressLength - Number of characters displayed as progress bar. @param {string} options.progressChar – Character to use for progress bar, defaults to █. @param {number} options.progressPercent - Max percent of progress. @param {string} options.cursor – Character to use for cursor, defaults to ▋. @param {Object[]} lineData - Dynamically loaded line data objects. @param {boolean} options.noInit - Don't initialise the animation.
constructor ( container = '#termynal' , options = { } )
javascript
meshery/meshery
docs/v0.6/assets/js/terminal.js
https://github.com/meshery/meshery/blob/master/docs/v0.6/assets/js/terminal.js
Apache-2.0
init() { // Appends dynamically loaded lines to existing line elements. this.lines = [...this.container.querySelectorAll(`[${this.pfx}]`)].concat(this.lineData); /** * Calculates width and height of Termynal container. * If container is empty and lines are dynamically loaded, defaults to browser `auto` or CSS. */ const containerStyle = getComputedStyle(this.container); this.container.style.width = containerStyle.width !== '0px' ? containerStyle.width : undefined; this.container.style.minHeight = containerStyle.height !== '0px' ? containerStyle.height : undefined; this.container.setAttribute('data-termynal', ''); this.container.innerHTML = ''; var divIndex = this.container.id; var self = this; if(inView(divIndex)){ animatedTerminal.push(divIndex); self.start(); } // scroll eventlistiner for mobile view $(document.body).on('touchmove', mobilescroll); // mobile view function function mobilescroll(){ if (inView(divIndex) && !animatedTerminal.includes(divIndex)) { animatedTerminal.push(divIndex); self.start(); } } // scroll eventlistiner function for window view document.addEventListener('scroll',function(){ if (inView(divIndex) && !animatedTerminal.includes(divIndex)) { animatedTerminal.push(divIndex); self.start(); } }); }
Initialise the widget, get lines, clear container and start animation.
init ( )
javascript
meshery/meshery
docs/v0.6/assets/js/terminal.js
https://github.com/meshery/meshery/blob/master/docs/v0.6/assets/js/terminal.js
Apache-2.0
async start() { await this._wait(this.startDelay); for (let line of this.lines) { const type = line.getAttribute(this.pfx); const delay = line.getAttribute(`${this.pfx}-delay`) || this.lineDelay; if (type == 'input') { line.setAttribute(`${this.pfx}-cursor`, this.cursor); await this.type(line); await this._wait(delay); } else if (type == 'progress') { await this.progress(line); await this._wait(delay); } else { this.container.appendChild(line); await this._wait(delay); } line.removeAttribute(`${this.pfx}-cursor`); } }
Start the animation and rener the lines depending on their data attributes.
start ( )
javascript
meshery/meshery
docs/v0.6/assets/js/terminal.js
https://github.com/meshery/meshery/blob/master/docs/v0.6/assets/js/terminal.js
Apache-2.0
async type(line) { const chars = [...line.textContent]; const delay = line.getAttribute(`${this.pfx}-typeDelay`) || this.typeDelay; line.textContent = ''; this.container.appendChild(line); for (let char of chars) { await this._wait(delay); line.textContent += char; } }
Animate a typed line. @param {Node} line - The line element to render.
type ( line )
javascript
meshery/meshery
docs/v0.6/assets/js/terminal.js
https://github.com/meshery/meshery/blob/master/docs/v0.6/assets/js/terminal.js
Apache-2.0
async progress(line) { const progressLength = line.getAttribute(`${this.pfx}-progressLength`) || this.progressLength; const progressChar = line.getAttribute(`${this.pfx}-progressChar`) || this.progressChar; const chars = progressChar.repeat(progressLength); const progressPercent = line.getAttribute(`${this.pfx}-progressPercent`) || this.progressPercent; line.textContent = ''; this.container.appendChild(line); for (let i = 1; i < chars.length + 1; i++) { await this._wait(this.typeDelay); const percent = Math.round(i / chars.length * 100); line.textContent = `${chars.slice(0, i)} ${percent}%`; if (percent>progressPercent) { break; } } }
Animate a progress bar. @param {Node} line - The line element to render.
progress ( line )
javascript
meshery/meshery
docs/v0.6/assets/js/terminal.js
https://github.com/meshery/meshery/blob/master/docs/v0.6/assets/js/terminal.js
Apache-2.0