immutable#Map JavaScript Examples
The following examples show how to use
immutable#Map.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: config.js From SubstrateIDE with GNU General Public License v3.0 | 6 votes |
profile = {
default: Map({}),
persist: true,
actions: {
SET_USER_PROFILE: {
reducer: (state, { payload }) => state.merge(payload)
},
CLEAR_USER_PROFILE: {
reducer: () => Map({})
},
}
}
Example #2
Source File: index.js From strapi-plugin-config-sync with MIT License | 6 votes |
ActionButtons = () => {
const dispatch = useDispatch();
const toggleNotification = useNotification();
const [modalIsOpen, setModalIsOpen] = useState(false);
const [actionType, setActionType] = useState('');
const partialDiff = useSelector((state) => state.getIn(['config', 'partialDiff'], Map({}))).toJS();
const closeModal = () => {
setActionType('');
setModalIsOpen(false);
};
const openModal = (type) => {
setActionType(type);
setModalIsOpen(true);
};
return (
<ActionButtonsStyling>
<Button disabled={isEmpty(partialDiff)} onClick={() => openModal('import')}>Import</Button>
<Button disabled={isEmpty(partialDiff)} onClick={() => openModal('export')}>Export</Button>
{!isEmpty(partialDiff) && (
<h4 style={{ display: 'inline' }}>{Object.keys(partialDiff).length} {Object.keys(partialDiff).length === 1 ? "config change" : "config changes"}</h4>
)}
<ConfirmModal
isOpen={modalIsOpen}
onClose={closeModal}
type={actionType}
onSubmit={() => actionType === 'import' ? dispatch(importAllConfig(partialDiff, toggleNotification)) : dispatch(exportAllConfig(partialDiff, toggleNotification))}
/>
</ActionButtonsStyling>
);
}
Example #3
Source File: Sitemap.js From strapi-plugin-sitemap with MIT License | 6 votes |
// Get initial settings
export function getSettings(toggleNotification) {
return async function(dispatch) {
try {
const settings = await request('/sitemap/settings/', { method: 'GET' });
dispatch(getSettingsSucceeded(Map(settings)));
} catch (err) {
toggleNotification({ type: 'warning', message: { id: 'notification.error' } });
}
};
}
Example #4
Source File: multi-cloud-action.js From ThreatMapper with Apache License 2.0 | 6 votes |
bulkStopCVEScan = async (selectedDocIndex = [], paramsIm = Map(), dispatch) => {
const params = paramsIm.toJS();
const nodeListObject = nodeListWithType(selectedDocIndex);
let successCount = 0;
let errorCount = 0;
// eslint-disable-next-line no-unused-vars
for (const [node_type, node_id_list] of Object.entries(nodeListObject)) {
const apiParams = {
action: 'cve_scan_stop',
node_type,
node_id_list,
action_args: {
...params,
},
};
try{
// eslint-disable-next-line no-await-in-loop
const response = await dispatch(scanRegistryImagesAction(apiParams));
const { success } = response;
if (success) {
successCount += node_id_list.length;
} else {
errorCount += node_id_list.length;
}
} catch (e) {
errorCount += node_id_list.length;
}
}
dispatch(toaster(`Request to stop vulnerability scan on ${successCount} nodes queued successfully${errorCount ? ` , failed on ${errorCount} nodes.` : '.'}`));
}
Example #5
Source File: TicksService.js From binary-bot with MIT License | 6 votes |
requestPipSizes() {
if (this.pipSizes) {
return Promise.resolve(this.pipSizes);
}
if (!this.active_symbols_promise) {
this.active_symbols_promise = new Promise(resolve => {
this.getActiveSymbols().then((activeSymbols = []) => {
this.pipSizes = activeSymbols
?.reduce((s, i) => s.set(i.symbol, +(+i.pip).toExponential().substring(3)), new Map())
.toObject();
resolve(this.pipSizes);
});
});
}
return this.active_symbols_promise;
}
Example #6
Source File: ConfigStore.js From spring-boot-ecommerce with Apache License 2.0 | 6 votes |
ConfigStore = function () {
function ConfigStore() {
_classCallCheck(this, ConfigStore);
this._store = Map();
}
ConfigStore.prototype.set = function set(key, value) {
this._store = this._store.set(key, value);
};
ConfigStore.prototype.get = function get(key) {
return this._store.get(key);
};
return ConfigStore;
}()
Example #7
Source File: convertFromHTML.js From the-eye-knows-the-garbage with MIT License | 6 votes |
function getSoftNewlineChunk(block, depth) {
var flat = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var data = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : Map();
if (flat === true) {
return {
text: '\r',
inlines: [OrderedSet()],
entities: new Array(1),
blocks: [{
type: block,
data: data,
depth: Math.max(0, Math.min(MAX_DEPTH, depth))
}],
isNewline: true
};
}
return {
text: '\n',
inlines: [OrderedSet()],
entities: new Array(1),
blocks: []
};
}
Example #8
Source File: index.js From Lynx with MIT License | 6 votes |
structure = {
allowsArrayErrors: false,
empty: Map(),
emptyList: emptyList,
getIn: function getIn(state, field) {
return Iterable.isIterable(state) ? state.getIn(_toPath(field)) : plainGetIn(state, field);
},
setIn: setIn,
deepEqual: deepEqual,
deleteIn: function deleteIn(state, field) {
return state.deleteIn(_toPath(field));
},
forEach: function forEach(items, callback) {
items.forEach(callback);
},
fromJS: function fromJS(jsValue) {
return _fromJS(jsValue, function (key, value) {
return Iterable.isIndexed(value) ? value.toList() : value.toMap();
});
},
keys: keys,
size: function size(list) {
return list ? list.size : 0;
},
some: function some(items, callback) {
return items.some(callback);
},
splice: splice,
toJS: function toJS(value) {
return Iterable.isIterable(value) ? value.toJS() : value;
}
}
Example #9
Source File: index.js From strapi-plugin-config-sync with MIT License | 5 votes |
initialState = fromJS({
configDiff: Map({}),
partialDiff: List([]),
isLoading: false,
appEnv: 'development',
})
Example #10
Source File: index.js From strapi-plugin-sitemap with MIT License | 5 votes |
Header = () => {
const settings = useSelector((state) => state.getIn(['sitemap', 'settings'], Map()));
const initialData = useSelector((state) => state.getIn(['sitemap', 'initialData'], Map()));
const toggleNotification = useNotification();
const dispatch = useDispatch();
const { formatMessage } = useIntl();
const disabled = JSON.stringify(settings) === JSON.stringify(initialData);
const handleSubmit = (e) => {
e.preventDefault();
dispatch(submit(settings.toJS(), toggleNotification));
};
const handleCancel = (e) => {
e.preventDefault();
dispatch(discardAllChanges());
};
return (
<Box background="neutral100">
<HeaderLayout
primaryAction={(
<Box style={{ display: "flex" }}>
<Button
onClick={handleCancel}
disabled={disabled}
type="cancel"
size="L"
variant="secondary"
>
{formatMessage({ id: 'sitemap.Button.Cancel', defaultMessage: 'Cancel' })}
</Button>
<Button
style={{ marginLeft: '10px' }}
onClick={handleSubmit}
disabled={disabled}
type="submit"
startIcon={<CheckIcon />}
size="L"
>
{formatMessage({ id: 'sitemap.Button.Save', defaultMessage: 'Save' })}
</Button>
</Box>
)}
title={formatMessage({ id: 'sitemap.Header.Title', defaultMessage: 'Sitemap' })}
subtitle={formatMessage({ id: 'sitemap.Header.Description', defaultMessage: 'Settings for the sitemap XML' })}
as="h2"
/>
</Box>
);
}
Example #11
Source File: nodes-layout-test.js From ThreatMapper with Apache License 2.0 | 5 votes |
makeMap = Map
Example #12
Source File: observer.js From binary-bot with MIT License | 5 votes |
constructor() {
this.eam = new Map(); // event action map
this.state = {};
}
Example #13
Source File: Toolbar.js From spring-boot-ecommerce with Apache License 2.0 | 5 votes |
Toolbar = function (_React$Component) {
_inherits(Toolbar, _React$Component);
function Toolbar(props) {
_classCallCheck(this, Toolbar);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));
var map = {};
props.plugins.forEach(function (plugin) {
map[plugin.name] = plugin;
});
_this.pluginsMap = Map(map);
_this.state = {
editorState: props.editorState,
toolbars: []
};
return _this;
}
Toolbar.prototype.renderToolbarItem = function renderToolbarItem(pluginName, idx) {
var element = this.pluginsMap.get(pluginName);
if (element && element.component) {
var component = element.component;
var props = {
key: 'toolbar-item-' + idx,
onClick: component.props ? component.props.onClick : noop
};
if (React.isValidElement(component)) {
return React.cloneElement(component, props);
}
return React.createElement(component, props);
}
return null;
};
Toolbar.prototype.conpomentWillReceiveProps = function conpomentWillReceiveProps(nextProps) {
this.render();
};
Toolbar.prototype.render = function render() {
var _this2 = this;
var _props = this.props,
toolbars = _props.toolbars,
prefixCls = _props.prefixCls;
return React.createElement(
'div',
{ className: prefixCls + '-toolbar' },
toolbars.map(function (toolbar, idx) {
var children = React.Children.map(toolbar, _this2.renderToolbarItem.bind(_this2));
return React.createElement(
ToolbarLine,
{ key: 'toolbar-' + idx },
children
);
})
);
};
return Toolbar;
}(React.Component)
Example #14
Source File: ProjectDashboard.js From minerva with MIT License | 5 votes |
ProjectDashboard = (props) => {
const { id } = useParams()
const { fetchExperiments } = useContext(GlobalContext)
const [time, setTime] = useState(Date.now())
const { datasets, projects } = props
const experiments = props.experiments.get(Number(id)) ?? List([])
const project = projects.find((p) => p.id === Number(id)) ?? Map({})
const { datasetId } = project
const dataset = datasets.find((d) => d.id === Number(datasetId)) ?? Map({})
// Fetch experiments
useEffect(() => {
fetchExperiments(Number(id))
}, [id])
// Fetch experiments periodically
useEffect(() => {
const timeoutId = setTimeout(() => {
setTime(Date.now())
fetchExperiments(Number(id))
}, FETCH_EXPERIMENTS_INTERVAL)
return () => {
clearTimeout(timeoutId)
}
}, [time])
return (
<div className='dashboard'>
<ProjectHeader project={project} dataset={dataset} />
<div className='dashboard-body-wrapper'>
<div className='dashboard-body'>
<ExperimentList
project={project}
dataset={dataset}
experiments={experiments}
/>
<ProjectMetrics experiments={experiments} project={project} />
</div>
</div>
</div>
)
}
Example #15
Source File: convertFromHTML.js From the-eye-knows-the-garbage with MIT License | 5 votes |
function getChunkForHTML(html, processCustomInlineStyles, checkEntityNode, checkEntityText, checkBlockType, createEntity, getEntity, mergeEntityData, replaceEntityData, options, DOMBuilder) {
html = html.trim().replace(REGEX_CR, '').replace(REGEX_NBSP, SPACE);
var safeBody = DOMBuilder(html);
if (!safeBody) {
return null;
} // Sometimes we aren't dealing with content that contains nice semantic
// tags. In this case, use divs to separate everything out into paragraphs
// and hope for the best.
var workingBlocks = containsSemanticBlockMarkup(html) ? blockTags.concat(['div']) : ['div']; // Start with -1 block depth to offset the fact that we are passing in a fake
// UL block to sta rt with.
var chunk = genFragment(safeBody, OrderedSet(), 'ul', null, workingBlocks, -1, processCustomInlineStyles, checkEntityNode, checkEntityText, checkBlockType, createEntity, getEntity, mergeEntityData, replaceEntityData, options); // join with previous block to prevent weirdness on paste
if (chunk.text.indexOf('\r') === 0) {
chunk = {
text: chunk.text.slice(1),
inlines: chunk.inlines.slice(1),
entities: chunk.entities.slice(1),
blocks: chunk.blocks
};
} // Kill block delimiter at the end
if (chunk.text.slice(-1) === '\r') {
chunk.text = chunk.text.slice(0, -1);
chunk.inlines = chunk.inlines.slice(0, -1);
chunk.entities = chunk.entities.slice(0, -1);
chunk.blocks.pop();
} // If we saw no block tags, put an unstyled one in
if (chunk.blocks.length === 0) {
chunk.blocks.push({
type: 'unstyled',
data: Map(),
depth: 0
});
} // Sometimes we start with text that isn't in a block, which is then
// followed by blocks. Need to fix up the blocks to add in
// an unstyled block for this content
if (chunk.text.split('\r').length === chunk.blocks.length + 1) {
chunk.blocks.unshift({
type: 'unstyled',
data: Map(),
depth: 0
});
}
return chunk;
}
Example #16
Source File: reducer.js From NeteaseCloudMusic with MIT License | 5 votes |
initState = Map({
bannersList: [],
personalizedList: [],
})
Example #17
Source File: index.js From strapi-plugin-sitemap with MIT License | 4 votes |
Info = () => {
const hasHostname = useSelector((state) => state.getIn(['sitemap', 'initialData', 'hostname'], Map()));
const sitemapInfo = useSelector((state) => state.getIn(['sitemap', 'info'], Map()));
const dispatch = useDispatch();
const toggleNotification = useNotification();
const { formatMessage } = useIntl();
const updateDate = new Date(sitemapInfo.get('updateTime'));
// Format month, day and time.
const month = updateDate.toLocaleString('en', { month: 'numeric' });
const day = updateDate.toLocaleString('en', { day: 'numeric' });
const year = updateDate.getFullYear().toString().slice(2);
const time = formatTime(updateDate, true);
const content = () => {
if (!hasHostname) {
return (
<div>
<Typography variant="delta" style={{ marginBottom: '10px' }}>
{formatMessage({ id: 'sitemap.Info.NoHostname.Title', defaultMessage: 'Set your hostname' })}
</Typography>
<div>
<Typography variant="omega">
{formatMessage({ id: 'sitemap.Info.NoHostname.Description', defaultMessage: 'Before you can generate the sitemap you have to specify the hostname of your website.' })}
</Typography>
<Button
onClick={() => {
document.getElementById('tabs-2-tab').click();
setTimeout(() => document.querySelector('input[name="hostname"]').focus(), 0);
}}
variant="secondary"
style={{ marginTop: '15px' }}
>
{formatMessage({ id: 'sitemap.Header.Button.GoToSettings', defaultMessage: 'Go to settings' })}
</Button>
</div>
</div>
);
} else if (sitemapInfo.size === 0) {
return (
<div>
<Typography variant="delta" style={{ marginBottom: '10px' }}>
{formatMessage({ id: 'sitemap.Info.NoSitemap.Title', defaultMessage: 'No sitemap XML present' })}
</Typography>
<div>
<Typography variant="omega">
{formatMessage({ id: 'sitemap.Info.NoSitemap.Description', defaultMessage: 'Generate your first sitemap XML with the button below.' })}
</Typography>
<Button
onClick={() => dispatch(generateSitemap(toggleNotification))}
variant="secondary"
style={{ marginTop: '15px' }}
>
{formatMessage({ id: 'sitemap.Header.Button.Generate', defaultMessage: 'Generate sitemap' })}
</Button>
</div>
</div>
);
} else {
return (
<div>
<Typography variant="delta" style={{ marginBottom: '10px' }}>
{formatMessage({ id: 'sitemap.Info.SitemapIsPresent.Title', defaultMessage: 'Sitemap XML is present' })}
</Typography>
<div>
<Typography variant="omega">
{formatMessage({ id: 'sitemap.Info.SitemapIsPresent.LastUpdatedAt', defaultMessage: 'Last updated at:' })}
</Typography>
<Typography variant="omega" fontWeight="bold" style={{ marginLeft: '5px' }}>
{`${month}/${day}/${year} - ${time}`}
</Typography>
</div>
<div style={{ marginBottom: '15px' }}>
<Typography variant="omega">
{formatMessage({ id: 'sitemap.Info.SitemapIsPresent.AmountOfURLs', defaultMessage: 'Amount of URLs:' })}
</Typography>
<Typography variant="omega" fontWeight="bold" style={{ marginLeft: '5px' }}>
{sitemapInfo.get('urls')}
</Typography>
</div>
<div style={{ display: 'flex', flexDirection: 'row' }}>
<Button
onClick={() => dispatch(generateSitemap(toggleNotification))}
variant="secondary"
style={{ marginRight: '10px' }}
>
{formatMessage({ id: 'sitemap.Header.Button.Generate', defaultMessage: 'Generate sitemap' })}
</Button>
<Link
href={`${strapi.backendURL}${sitemapInfo.get('location')}`}
target="_blank"
>
{formatMessage({ id: 'sitemap.Header.Button.SitemapLink', defaultMessage: 'Go to the sitemap' })}
</Link>
</div>
</div>
);
}
};
return (
<Box paddingLeft={8} paddingRight={8}>
<Box
background="neutral0"
hasRadius
paddingTop={4}
paddingBottom={4}
paddingLeft={5}
paddingRight={5}
shadow="filterShadow"
>
{content()}
</Box>
</Box>
);
}
Example #18
Source File: reports.js From ThreatMapper with Apache License 2.0 | 4 votes |
Reports = props => {
const {
resource_type,
node_type,
topologyFilters,
duration,
schedule_interval,
pristine,
submitting,
loading,
info,
schedule_info,
tableItems =[],
download_type,
errors,
valid,
} = props;
const showEmailField = schedule_interval;
const downloadButtonLabel = schedule_interval
? 'Schedule Report'
: 'Download';
const [showModal, setShowModal] = useState(false);
// A hook to check for the report generation status by initiating a pollable request
useEffect(() => {
const {
registerPolling,
startPolling,
} = props;
registerPolling(reportDownloadStatus);
startPolling();
}, [])
// A function to initiate the report generation
useEffect(() => {
if (resource_type && node_type) {
const resourceTypeText = resource_type.value;
const nodeTypeText = node_type.value;
props.enumerateFiltersAction({
resource_type: resourceTypeText,
node_type: nodeTypeText,
filters:
'host_name,container_name,image_name_with_tag,os,kubernetes_cluster_name,kubernetes_namespace,masked',
});
}
}, [resource_type, node_type]);
// Function used to display the NodeType dropdown
const renderOne = filter => {
return (
<div
className="nodes-filter-item"
style={{ marginLeft: '0px', width: '400px' }}
>
<Field
key={filter.name}
rootClassName="form-field dir-column"
title={filter.name.replace(/_/g, ' ')}
name={filter.name}
component={DFSearchableSelectField}
buttonLabel={`${filter.label}`}
placeholder="Search"
options={filter.options.map(option => ({
label: option,
value: option,
}))}
isMulti
/>
</div>
);
};
const renderCVESeverityDropdown = () => {
return (
<div
className="nodes-filter-item"
style={{ marginLeft: '0px', width: '400px' }}
>
<Field
name="cve_severity"
rootClassName="form-field dir-column"
component={DFSearchableSelectField}
options={cveSeverityOptions}
buttonLabel="CVE Severity"
clearable={false}
placeholder="Select cve severity"
isMulti
/>
</div>
);
};
const checkIfResourceSelected = resourceValue => {
let selected = false;
if ( resource_type && resource_type.value === resourceValue) {
selected = true;
}
return selected;
};
const durationOptions = durationOption.map(el => ({
value: JSON.stringify({
number: el.number,
time_unit: el.time_unit,
}),
label: el.display,
}));
const reportDownloadStatus = (pollParams) => {
const {
reportDownloadStatusAction: action,
} = props;
const {
initiatedByPollable,
} = pollParams;
const params = {
initiatedByPollable,
};
return action(params);
}
const downloadReportFile = (path) => {
const {
downloadReportAction: action,
} = props;
const params = {
path,
};
return action(params);
}
const renderDownloadLink = (reportStatus = {}) => {
const {
status,
report_path: filePath,
} = reportStatus;
const {
fileDownloadStatusIm = Map(),
} = props;
const loading = fileDownloadStatusIm.getIn([filePath, 'loading']);
if (status === 'Completed' && filePath) {
return (
<div>
<span
className={classnames('fa fa-download', { disabled: loading})}
title="download"
style={{cursor: 'pointer'}}
onClick={() => { if (!loading) downloadReportFile(filePath)}}
/>
{loading}
{loading && <Loader style={{top: '25%', fontSize: '2.0rem'}} />}
</div>
);
}
return null;
}
// Function that creates the params that need to be
// sent to the API call to generate the report
const submitClickHandler = (e, props) => {
e.preventDefault();
if (resource_type && node_type) {
const {
resource_type,
node_type,
duration,
schedule_interval,
email_address,
dead_nodes_toggle,
host_name,
container_name,
image_name_with_tag,
operating_system,
kubernetes_cluster_name,
kubernetes_namespace,
cve_severity,
download_type,
valid,
masked,
reportGenerateAction: actionDownload,
reportScheduleEmailAction: actionEmail,
} = props;
if (!valid) {
return;
}
const resourceTypeText = resource_type.value;
const maskedFilter = masked && masked.map(v => v.value );
const resourceData = [];
if (resourceTypeText && resourceTypeText.includes('cve') && cve_severity) {
resourceData.push({
type: 'cve',
filter: { cve_severity: cve_severity.map(el => el.value).join(','), masked: maskedFilter },
});
}
if (resourceTypeText && resourceTypeText.includes('cve') && !cve_severity) {
resourceData.push({
type: 'cve',
filter: {masked: maskedFilter},
});
}
if (resourceTypeText && resourceTypeText.includes('secret-scan')) {
resourceData.push({
type: 'secret-scan',
filter: {},
});
}
let globalFilter;
const durationValues = duration && duration.value;
const downloadTypeOption = download_type && download_type.value;
if (node_type.value === 'host') {
const hostName = host_name && host_name.map(v => v.value);
const os = operating_system && operating_system.map(v => v.value);
const k8sClusterName =
kubernetes_cluster_name && kubernetes_cluster_name.map(v => v.value);
globalFilter = {
type: [node_type.value],
host_name: hostName,
os,
kubernetes_cluster_name: k8sClusterName,
};
} else if (node_type.value === 'container') {
const hostName = host_name && host_name.map(v => v.value);
const containerName =
container_name && container_name.map(v => v.value);
const imageName =
image_name_with_tag && image_name_with_tag.map(v => v.value);
const k8sClusterName =
kubernetes_cluster_name && kubernetes_cluster_name.map(v => v.value);
globalFilter = {
type: [node_type.value],
host_name: hostName,
container_name: containerName,
image_name_with_tag: imageName,
kubernetes_cluster_name: k8sClusterName,
};
} else if (node_type.value === 'container_image') {
const imageName =
image_name_with_tag && image_name_with_tag.map(v => v.value);
globalFilter = {
type: [node_type.value],
image_name_with_tag: imageName,
};
} else if (node_type.value === 'pod') {
const k8sClusterName =
kubernetes_cluster_name && kubernetes_cluster_name.map(v => v.value);
const k8sNamespace =
kubernetes_namespace && kubernetes_namespace.map(v => v.value);
globalFilter = {
type: [node_type.value],
kubernetes_cluster_name: k8sClusterName,
kubernetes_namespace: k8sNamespace,
};
} else {
globalFilter = {};
}
const scheduleInterval = schedule_interval;
// Checking for the dead nodes toggle value by checking if the host name selceted or is empty
let deadNodes;
if (node_type.value === 'host' || node_type.value === 'container') {
let lenHostName = 0;
globalFilter.host_name &&
globalFilter.host_name.map(x => (lenHostName = lenHostName + 1));
deadNodes = dead_nodes_toggle ? true : false;
if (lenHostName !== 0) {
deadNodes = false;
}
}
let params = {};
// API params for schedule report generation
if (scheduleInterval) {
const emailAddress = email_address && email_address;
params = {
action: 'schedule_send_report',
file_type: downloadTypeOption,
node_type: node_type.value,
include_dead_nodes: deadNodes,
action_args: {
cron: `0 4 */${scheduleInterval} * *`,
report_email: emailAddress,
resources: resourceData,
filters: globalFilter,
durationValues,
},
};
return actionEmail(params);
}
// API params for report generation
params = {
action: 'download_report',
file_type: downloadTypeOption,
node_type: node_type.value,
add_hist: true,
include_dead_nodes: deadNodes,
action_args: {
resources: resourceData,
filters: globalFilter,
durationValues,
},
};
return actionDownload(params);
}
};
return (
<div>
<div className="resource-download-form">
<form
className="df-modal-form"
onSubmit={e => submitClickHandler(e, props)}
>
<div
className="heading"
style={{ paddingLeft: '0px', width: '200px' }}
>
Select Resources{' '}
</div>
<div className="resource-option-wrapper">
<div
className="nodes-filter-item"
style={{ marginLeft: '0px', width: '400px' }}
>
<Field
name="resource_type"
rootClassName="form-field dir-column"
component={DFSearchableSelectField}
options={config}
buttonLabel="Resource type"
clearable={false}
placeholder="Select resource type"
/>
{errors && errors.resource_type && <div className="error-message-reports">{errors.resource_type}</div>}
</div>
</div>
<div>
{checkIfResourceSelected('cve') && (
<div>{renderCVESeverityDropdown()}</div>
)}
</div>
<div className="resource-option-wrapper">
{ checkIfResourceSelected('cve') && (
<div
className="nodes-filter-item"
style={{ marginLeft: '0px', width: '400px' }}
>
<Field
name="node_type"
rootClassName="form-field dir-column"
component={DFSearchableSelectField}
options={nodeTypeOption}
buttonLabel="Node type"
clearable={false}
placeholder="Select node type"
/>
</div>
)}
{ checkIfResourceSelected('secret-scan') && (
<div
className="nodes-filter-item"
style={{ marginLeft: '0px', width: '400px' }}
>
<Field
name="node_type"
rootClassName="form-field dir-column"
component={DFSearchableSelectField}
options={nodeTypeOptionsSecret}
buttonLabel="Node type"
clearable={false}
placeholder="Select node type"
/>
</div>
)}
</div>
<div
className="nodes-filter-item"
style={{ marginLeft: '0px', width: '400px' }}
>
<Field
name="duration"
rootClassName="form-field dir-column"
component={DFSearchableSelectField}
options={durationOptions}
buttonLabel="Duration"
value={durationOptions.filter(
option => option.value === duration
)}
clearable={false}
placeholder="Select Duration"
/>
</div>
{errors && errors.duration && <div className="error-message-reports">{errors.duration}</div>}
<Field
component={renderField}
type="number"
label="Schedule Interval in days (optional)"
name="schedule_interval"
/>
{showEmailField && (
<Field
component={renderField}
type="text"
label="Email Address"
name="email_address"
/>
)}
<Field
name="toggle"
component={ToggleSwitchField}
label="Include dead nodes"
/>
{props.resource_type && (
<span
onClick={() => setShowModal(true)}
className="link"
style={{ cursor: 'pointer', color: '#007FFF' }}
aria-hidden="true"
>
Advanced
</span>
)}
{showModal && (
<div className="ReactModalPortal">
<div
className="ReactModal__Overlay ReactModal__Overlay--after-open"
style={{
position: 'fixed',
inset: '0px',
backgroundColor: 'rgba(16, 16, 16, 0.8)',
zIndex: 100,
}}
>
<div
className="ReactModal__Content ReactModal__Content--after-open"
role="dialog"
aria-modal="true"
style={{
position: 'absolute',
inset: '50% auto auto 50%',
border: '1px solid rgb(37, 37, 37)',
background: 'rgb(16, 16, 16)',
overflow: 'initial',
borderRadius: '4px',
outline: 'none',
padding: '0px',
margin: 'auto',
transform: 'translate(-50%, -50%)',
width: '450px',
}}
>
<div className="df-generic-modal">
<div className="modal-header">
<span className="title">Filters</span>
<i
className="fa fa-close modal-close"
aria-hidden="true"
onClick={() => setShowModal(false)}
/>
</div>
<div className="modal-body" style={{ paddingBottom: '100px' }}>
<div>
{resource_type &&
node_type &&
topologyFilters
.get(
resource_type.value,
[]
)
.map(filter => renderOne(filter))}
</div>
</div>
<button
className="primary-btn"
type="submit"
style={{ margin: '10px 45px', padding: '5px' }}
onClick={() => setShowModal(false)}
>
Done
</button>
</div>
</div>
</div>
</div>
)}
<div
className="nodes-filter-item"
style={{ marginLeft: '0px', width: '400px', marginTop: '20px' }}
>
<Field
name="download"
rootClassName="form-field dir-column"
component={DFSearchableSelectField}
options={downloadOptions}
buttonLabel="Download type"
clearable={false}
placeholder="Select download type"
/>
</div>
{errors && errors.download_type && <div className="error-message-reports">{errors.download_type}</div>}
<div className="form-field relative">
<button
className="primary-btn"
type="submit"
disabled={!duration || !download_type || submitting || pristine || !valid}
>
{downloadButtonLabel}
</button>
{loading && (
<div className="loader">
<Loader
small
style={{
top: '25%',
fontSize: '1.0rem',
marginLeft: '1.0rem',
marginTop: '-1.0rem',
}}
/>
</div>
)}
</div>
{info && <span className="message error-message"> {info} </span>}
{schedule_info && <span className="message error-message"> {schedule_info} </span>}
</form>
</div>
<div className="email-integration-collection-wrapper">
<table className="table table-bordered table-striped">
<thead>
<th> Timestamp </th>
<th> Report Type </th>
<th> Filters Used </th>
<th> Duration </th>
<th> Status </th>
<th> Download </th>
</thead>
<tbody>
{tableItems &&
tableItems.map(key => (
<tr>
<td>
{moment(key['@timestamp']).format(
'MMMM Do YYYY, h:mm:ss a'
)}
</td>
<td>
{key.file_type}
</td>
<td>{key.filters}</td>
<td>{key.duration}</td>
<td>{key.status}</td>
<td>{renderDownloadLink(key)}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}
Example #19
Source File: index.js From spring-boot-ecommerce with Apache License 2.0 | 4 votes |
EditorCore = function (_React$Component) {
_inherits(EditorCore, _React$Component);
function EditorCore(props) {
_classCallCheck(this, EditorCore);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));
_this.cancelForceUpdateImmediate = function () {
clearImmediate(_this.forceUpdateImmediate);
_this.forceUpdateImmediate = null;
};
_this.handlePastedText = function (text, html) {
var editorState = _this.state.editorState;
if (html) {
var contentState = editorState.getCurrentContent();
var selection = editorState.getSelection();
var fragment = customHTML2Content(html, contentState);
var pastedContent = Modifier.replaceWithFragment(contentState, selection, fragment);
var newContent = pastedContent.merge({
selectionBefore: selection,
selectionAfter: pastedContent.getSelectionAfter().set('hasFocus', true)
});
_this.setEditorState(EditorState.push(editorState, newContent, 'insert-fragment'), true);
return 'handled';
}
return 'not-handled';
};
_this.plugins = List(List(props.plugins).flatten(true));
var editorState = void 0;
if (props.value !== undefined) {
if (props.value instanceof EditorState) {
editorState = props.value || EditorState.createEmpty();
} else {
editorState = EditorState.createEmpty();
}
} else {
editorState = EditorState.createEmpty();
}
editorState = _this.generatorDefaultValue(editorState);
_this.state = {
plugins: _this.reloadPlugins(),
editorState: editorState,
customStyleMap: {},
customBlockStyleMap: {},
compositeDecorator: null
};
if (props.value !== undefined) {
_this.controlledMode = true;
}
return _this;
}
EditorCore.ToEditorState = function ToEditorState(text) {
var createEmptyContentState = ContentState.createFromText(decodeContent(text) || '');
var editorState = EditorState.createWithContent(createEmptyContentState);
return EditorState.forceSelection(editorState, createEmptyContentState.getSelectionAfter());
};
EditorCore.prototype.getDefaultValue = function getDefaultValue() {
var _props = this.props,
defaultValue = _props.defaultValue,
value = _props.value;
return value || defaultValue;
};
EditorCore.prototype.Reset = function Reset() {
var defaultValue = this.getDefaultValue();
var contentState = defaultValue ? defaultValue.getCurrentContent() : ContentState.createFromText('');
var updatedEditorState = EditorState.push(this.state.editorState, contentState, 'remove-range');
this.setEditorState(EditorState.forceSelection(updatedEditorState, contentState.getSelectionBefore()));
};
EditorCore.prototype.SetText = function SetText(text) {
var createTextContentState = ContentState.createFromText(text || '');
var editorState = EditorState.push(this.state.editorState, createTextContentState, 'change-block-data');
this.setEditorState(EditorState.moveFocusToEnd(editorState), true);
};
EditorCore.prototype.getChildContext = function getChildContext() {
return {
getEditorState: this.getEditorState,
setEditorState: this.setEditorState
};
};
EditorCore.prototype.reloadPlugins = function reloadPlugins() {
var _this2 = this;
return this.plugins && this.plugins.size ? this.plugins.map(function (plugin) {
// 如果插件有 callbacks 方法,则认为插件已经加载。
if (plugin.callbacks) {
return plugin;
}
// 如果插件有 constructor 方法,则构造插件
if (plugin.hasOwnProperty('constructor')) {
var pluginConfig = _extends(_this2.props.pluginConfig, plugin.config || {}, defaultPluginConfig);
return plugin.constructor(pluginConfig);
}
// else 无效插件
console.warn('>> 插件: [', plugin.name, '] 无效。插件或许已经过期。');
return false;
}).filter(function (plugin) {
return plugin;
}).toArray() : [];
};
EditorCore.prototype.componentWillMount = function componentWillMount() {
var plugins = this.initPlugins().concat([toolbar]);
var customStyleMap = {};
var customBlockStyleMap = {};
var customBlockRenderMap = Map(DefaultDraftBlockRenderMap);
var toHTMLList = List([]);
// initialize compositeDecorator
var compositeDecorator = new CompositeDecorator(plugins.filter(function (plugin) {
return plugin.decorators !== undefined;
}).map(function (plugin) {
return plugin.decorators;
}).reduce(function (prev, curr) {
return prev.concat(curr);
}, []));
// initialize Toolbar
var toolbarPlugins = List(plugins.filter(function (plugin) {
return !!plugin.component && plugin.name !== 'toolbar';
}));
// load inline styles...
plugins.forEach(function (plugin) {
var styleMap = plugin.styleMap,
blockStyleMap = plugin.blockStyleMap,
blockRenderMap = plugin.blockRenderMap,
toHtml = plugin.toHtml;
if (styleMap) {
for (var key in styleMap) {
if (styleMap.hasOwnProperty(key)) {
customStyleMap[key] = styleMap[key];
}
}
}
if (blockStyleMap) {
for (var _key in blockStyleMap) {
if (blockStyleMap.hasOwnProperty(_key)) {
customBlockStyleMap[_key] = blockStyleMap[_key];
customBlockRenderMap = customBlockRenderMap.set(_key, {
element: null
});
}
}
}
if (toHtml) {
toHTMLList = toHTMLList.push(toHtml);
}
if (blockRenderMap) {
for (var _key2 in blockRenderMap) {
if (blockRenderMap.hasOwnProperty(_key2)) {
customBlockRenderMap = customBlockRenderMap.set(_key2, blockRenderMap[_key2]);
}
}
}
});
configStore.set('customStyleMap', customStyleMap);
configStore.set('customBlockStyleMap', customBlockStyleMap);
configStore.set('blockRenderMap', customBlockRenderMap);
configStore.set('customStyleFn', this.customStyleFn.bind(this));
configStore.set('toHTMLList', toHTMLList);
this.setState({
toolbarPlugins: toolbarPlugins,
compositeDecorator: compositeDecorator
});
this.setEditorState(EditorState.set(this.state.editorState, { decorator: compositeDecorator }), false, false);
};
EditorCore.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (this.forceUpdateImmediate) {
this.cancelForceUpdateImmediate();
}
if (this.controlledMode) {
var decorators = nextProps.value.getDecorator();
var editorState = decorators ? nextProps.value : EditorState.set(nextProps.value, { decorator: this.state.compositeDecorator });
this.setState({
editorState: editorState
});
}
};
EditorCore.prototype.componentWillUnmount = function componentWillUnmount() {
this.cancelForceUpdateImmediate();
};
// 处理 value
EditorCore.prototype.generatorDefaultValue = function generatorDefaultValue(editorState) {
var defaultValue = this.getDefaultValue();
if (defaultValue) {
return defaultValue;
}
return editorState;
};
EditorCore.prototype.getStyleMap = function getStyleMap() {
return configStore.get('customStyleMap');
};
EditorCore.prototype.setStyleMap = function setStyleMap(customStyleMap) {
configStore.set('customStyleMap', customStyleMap);
this.render();
};
EditorCore.prototype.initPlugins = function initPlugins() {
var _this3 = this;
var enableCallbacks = ['focus', 'getEditorState', 'setEditorState', 'getStyleMap', 'setStyleMap'];
return this.getPlugins().map(function (plugin) {
enableCallbacks.forEach(function (callbackName) {
if (plugin.callbacks.hasOwnProperty(callbackName)) {
plugin.callbacks[callbackName] = _this3[callbackName].bind(_this3);
}
});
return plugin;
});
};
EditorCore.prototype.focusEditor = function focusEditor(ev) {
this.refs.editor.focus(ev);
if (this.props.readOnly) {
this._focusDummy.focus();
}
if (this.props.onFocus) {
this.props.onFocus(ev);
}
};
EditorCore.prototype._focus = function _focus(ev) {
if (!ev || !ev.nativeEvent || !ev.nativeEvent.target) {
return;
}
if (document.activeElement && document.activeElement.getAttribute('contenteditable') === 'true') {
return;
}
return this.focus(ev);
};
EditorCore.prototype.focus = function focus(ev) {
var _this4 = this;
var event = ev && ev.nativeEvent;
if (event && event.target === this._editorWrapper) {
var editorState = this.state.editorState;
var selection = editorState.getSelection();
if (!selection.getHasFocus()) {
if (selection.isCollapsed()) {
return this.setState({
editorState: EditorState.moveSelectionToEnd(editorState)
}, function () {
_this4.focusEditor(ev);
});
}
}
}
this.focusEditor(ev);
};
EditorCore.prototype.getPlugins = function getPlugins() {
return this.state.plugins.slice();
};
EditorCore.prototype.getEventHandler = function getEventHandler() {
var _this5 = this;
var enabledEvents = ['onUpArrow', 'onDownArrow', 'handleReturn', 'onFocus', 'onBlur', 'onTab', 'handlePastedText'];
var eventHandler = {};
enabledEvents.forEach(function (event) {
eventHandler[event] = _this5.generatorEventHandler(event);
});
return eventHandler;
};
EditorCore.prototype.getEditorState = function getEditorState() {
var needFocus = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
if (needFocus) {
this.refs.editor.focus();
}
return this.state.editorState;
};
EditorCore.prototype.setEditorState = function setEditorState(editorState) {
var _this6 = this;
var focusEditor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var triggerChange = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
var newEditorState = editorState;
this.getPlugins().forEach(function (plugin) {
if (plugin.onChange) {
var updatedEditorState = plugin.onChange(newEditorState);
if (updatedEditorState) {
newEditorState = updatedEditorState;
}
}
});
if (this.props.onChange && triggerChange) {
this.props.onChange(newEditorState);
// close this issue https://github.com/ant-design/ant-design/issues/5788
// when onChange not take any effect
// `<Editor />` won't rerender cause no props is changed.
// add an timeout here,
// if props.onChange not trigger componentWillReceiveProps,
// we will force render Editor with previous editorState,
if (this.controlledMode) {
this.forceUpdateImmediate = setImmediate(function () {
return _this6.setState({
editorState: new EditorState(_this6.state.editorState.getImmutable())
});
});
}
}
if (!this.controlledMode) {
this.setState({ editorState: newEditorState }, focusEditor ? function () {
return setImmediate(function () {
return _this6.refs.editor.focus();
});
} : noop);
}
};
EditorCore.prototype.handleKeyBinding = function handleKeyBinding(ev) {
if (this.props.onKeyDown) {
ev.ctrlKey = hasCommandModifier(ev);
var keyDownResult = this.props.onKeyDown(ev);
if (keyDownResult) {
return keyDownResult;
}
return getDefaultKeyBinding(ev);
}
return getDefaultKeyBinding(ev);
};
EditorCore.prototype.handleKeyCommand = function handleKeyCommand(command) {
if (this.props.multiLines) {
return this.eventHandle('handleKeyBinding', command);
}
return command === 'split-block' ? 'handled' : 'not-handled';
};
EditorCore.prototype.getBlockStyle = function getBlockStyle(contentBlock) {
var customBlockStyleMap = configStore.get('customBlockStyleMap');
var type = contentBlock.getType();
if (customBlockStyleMap.hasOwnProperty(type)) {
return customBlockStyleMap[type];
}
return '';
};
EditorCore.prototype.blockRendererFn = function blockRendererFn(contentBlock) {
var blockRenderResult = null;
this.getPlugins().forEach(function (plugin) {
if (plugin.blockRendererFn) {
var result = plugin.blockRendererFn(contentBlock);
if (result) {
blockRenderResult = result;
}
}
});
return blockRenderResult;
};
EditorCore.prototype.eventHandle = function eventHandle(eventName) {
var _props2;
var plugins = this.getPlugins();
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key3 = 1; _key3 < _len; _key3++) {
args[_key3 - 1] = arguments[_key3];
}
for (var i = 0; i < plugins.length; i++) {
var plugin = plugins[i];
if (plugin.callbacks[eventName] && typeof plugin.callbacks[eventName] === 'function') {
var _plugin$callbacks;
var result = (_plugin$callbacks = plugin.callbacks)[eventName].apply(_plugin$callbacks, args);
if (result === true) {
return 'handled';
}
}
}
return this.props.hasOwnProperty(eventName) && (_props2 = this.props)[eventName].apply(_props2, args) === true ? 'handled' : 'not-handled';
};
EditorCore.prototype.generatorEventHandler = function generatorEventHandler(eventName) {
var _this7 = this;
return function () {
for (var _len2 = arguments.length, args = Array(_len2), _key4 = 0; _key4 < _len2; _key4++) {
args[_key4] = arguments[_key4];
}
return _this7.eventHandle.apply(_this7, [eventName].concat(args));
};
};
EditorCore.prototype.customStyleFn = function customStyleFn(styleSet) {
if (styleSet.size === 0) {
return {};
}
var plugins = this.getPlugins();
var resultStyle = {};
for (var i = 0; i < plugins.length; i++) {
if (plugins[i].customStyleFn) {
var styled = plugins[i].customStyleFn(styleSet);
if (styled) {
_extends(resultStyle, styled);
}
}
}
return resultStyle;
};
EditorCore.prototype.render = function render() {
var _classnames,
_this8 = this;
var _props3 = this.props,
prefixCls = _props3.prefixCls,
toolbars = _props3.toolbars,
style = _props3.style,
readOnly = _props3.readOnly,
multiLines = _props3.multiLines;
var _state = this.state,
editorState = _state.editorState,
toolbarPlugins = _state.toolbarPlugins;
var customStyleMap = configStore.get('customStyleMap');
var blockRenderMap = configStore.get('blockRenderMap');
var eventHandler = this.getEventHandler();
var Toolbar = toolbar.component;
var cls = classnames((_classnames = {}, _classnames[prefixCls + '-editor'] = true, _classnames.readonly = readOnly, _classnames.oneline = !multiLines, _classnames));
return React.createElement(
'div',
{ style: style, className: cls, onClick: this._focus.bind(this) },
React.createElement(Toolbar, { editorState: editorState, prefixCls: prefixCls, className: prefixCls + '-toolbar', plugins: toolbarPlugins, toolbars: toolbars }),
React.createElement(
'div',
{ className: prefixCls + '-editor-wrapper', ref: function ref(ele) {
return _this8._editorWrapper = ele;
}, style: style, onClick: function onClick(ev) {
return ev.preventDefault();
} },
React.createElement(Editor, _extends({}, this.props, eventHandler, { ref: 'editor', customStyleMap: customStyleMap, customStyleFn: this.customStyleFn.bind(this), editorState: editorState, handleKeyCommand: this.handleKeyCommand.bind(this), keyBindingFn: this.handleKeyBinding.bind(this), onChange: this.setEditorState.bind(this), blockStyleFn: this.getBlockStyle.bind(this), blockRenderMap: blockRenderMap, handlePastedText: this.handlePastedText, blockRendererFn: this.blockRendererFn.bind(this) })),
readOnly ? React.createElement('input', { style: focusDummyStyle, ref: function ref(ele) {
return _this8._focusDummy = ele;
}, onBlur: eventHandler.onBlur }) : null,
this.props.children
)
);
};
return EditorCore;
}(React.Component)
Example #20
Source File: context.js From minerva with MIT License | 4 votes |
GlobalProvider = ({ children }) => {
const [datasets, setDatasets] = useState(List([]))
const [projects, setProjects] = useState(List([]))
const [experiments, dispatch] = useReducer(experimentReducer, Map({}))
const [examples, setExamples] = useState(Map({}))
const [status, setStatus] = useState({})
const [statusTime, setStatusTime] = useState(Date.now())
// Initialization
useEffect(() => {
Dataset.getAll()
.then((newDatasets) => setDatasets(List(newDatasets)))
.catch((err) => showNetworkErrorToast(err))
Project.getAll()
.then((newProjects) => setProjects(List(newProjects)))
.catch((err) => showNetworkErrorToast(err))
Status.get()
.then((newStatus) => setStatus(newStatus))
.catch((err) => showNetworkErrorToast(err))
}, [])
// Periodical API calls
useEffect(() => {
const timeoutId = setTimeout(() => {
setStatusTime(Date.now())
Status.get()
.then((newStatus) => setStatus(newStatus))
.catch((err) => showNetworkErrorToast(err))
}, STATUS_API_CALL_INTERVAL)
return () => {
clearTimeout(timeoutId)
}
}, [statusTime])
// Actions
const uploadDataset = (file, isImage, zipFile, progressCallback) => (
Dataset.upload(file, isImage, zipFile, progressCallback)
.then((dataset) => {
setDatasets(datasets.unshift(dataset))
return dataset
})
.catch((err) => showNetworkErrorToast(err))
)
const deleteDataset = deleteFunc(datasets, setDatasets)
const updateDataset = updateFunc(datasets, setDatasets)
const createProject = (datasetId, name, algorithm, progressCallback) => (
Project.create(datasetId, name, algorithm, progressCallback)
.then((project) => {
setProjects(projects.unshift(project))
return project
})
.catch((err) => showNetworkErrorToast(err))
)
const deleteProject = deleteFunc(projects, setProjects)
const updateProject = updateFunc(projects, setProjects)
const fetchExperiments = (projectId) => (
Experiment.getAll(projectId)
.then((newExperiments) => {
dispatch({
type: 'fetch',
projectId: projectId,
experiments: newExperiments
})
return newExperiments
})
.catch((err) => showNetworkErrorToast(err))
)
const createExperiment = (projectId, name, config, progressCallback) => (
Experiment.create(projectId, name, config, progressCallback)
.then((experiment) => {
dispatch({
type: 'create',
projectId: projectId,
experiment: experiment
})
return experiment
})
.catch((err) => showNetworkErrorToast(err))
)
const deleteExperiment = (experiment) => {
dispatch({
type: 'delete',
projectId: experiment.projectId,
experiment: experiment
})
return experiment.delete().catch((err) => showNetworkErrorToast(err))
}
const updateExperiment = (experiment) => {
dispatch({
type: 'update',
projectId: experiment.projectId,
experiment: experiment
})
return experiment.update().catch((err) => showNetworkErrorToast(err))
}
const cancelExperiment = (experiment) => {
dispatch({
type: 'update',
projectId: experiment.projectId,
experiment: experiment.set('isActive', false)
})
return experiment.cancel().catch((err) => showNetworkErrorToast(err))
}
const fetchExampleObservations = (dataset) => {
dataset.getExampleObservations()
.then((observations) => {
const newExamples = examples.set(dataset.id, observations)
setExamples(newExamples)
return observations
})
.catch((err) => showErrorToast(err))
}
return (
<GlobalContext.Provider
value={{
datasets,
projects,
experiments,
examples,
status,
uploadDataset,
deleteDataset,
updateDataset,
createProject,
updateProject,
deleteProject,
fetchExperiments,
createExperiment,
deleteExperiment,
updateExperiment,
cancelExperiment,
fetchExampleObservations,
showErrorToast,
showNetworkErrorToast
}}
>
{children}
</GlobalContext.Provider>
)
}
Example #21
Source File: convertFromHTML.js From the-eye-knows-the-garbage with MIT License | 4 votes |
function genFragment(node, inlineStyle, lastList, inBlock, fragmentBlockTags, depth, processCustomInlineStyles, checkEntityNode, checkEntityText, checkBlockType, createEntity, getEntity, mergeEntityData, replaceEntityData, options, inEntity) {
var nodeName = node.nodeName.toLowerCase();
var newBlock = false;
var nextBlockType = 'unstyled'; // Base Case
if (nodeName === '#text') {
var text = node.textContent;
if (text.trim() === '' && inBlock === null) {
return getEmptyChunk();
}
if (text.trim() === '' && inBlock !== 'code-block') {
return getWhitespaceChunk(inEntity);
}
if (inBlock !== 'code-block') {
// Can't use empty string because MSWord
text = text.replace(REGEX_LF, SPACE);
}
var entities = Array(text.length).fill(inEntity);
var offsetChange = 0;
var textEntities = checkEntityText(text, createEntity, getEntity, mergeEntityData, replaceEntityData).sort(rangeSort);
textEntities.forEach(function (_ref) {
var entity = _ref.entity,
offset = _ref.offset,
length = _ref.length,
result = _ref.result;
var adjustedOffset = offset + offsetChange;
if (result === null || result === undefined) {
result = text.substr(adjustedOffset, length);
}
var textArray = text.split('');
textArray.splice.bind(textArray, adjustedOffset, length).apply(textArray, result.split(''));
text = textArray.join('');
entities.splice.bind(entities, adjustedOffset, length).apply(entities, Array(result.length).fill(entity));
offsetChange += result.length - length;
});
return {
text: text,
inlines: Array(text.length).fill(inlineStyle),
entities: entities,
blocks: []
};
} // BR tags
if (nodeName === 'br') {
var _blockType = inBlock;
if (_blockType === null) {
// BR tag is at top level, treat it as an unstyled block
return getSoftNewlineChunk('unstyled', depth, true);
}
return getSoftNewlineChunk(_blockType || 'unstyled', depth, options.flat);
}
var chunk = getEmptyChunk();
var newChunk = null; // Inline tags
inlineStyle = processInlineTag(nodeName, node, inlineStyle);
inlineStyle = processCustomInlineStyles(nodeName, node, inlineStyle); // Handle lists
if (nodeName === 'ul' || nodeName === 'ol') {
if (lastList) {
depth += 1;
}
lastList = nodeName;
inBlock = null;
} // Block Tags
var blockInfo = checkBlockType(nodeName, node, lastList, inBlock);
var blockType;
var blockDataMap;
if (blockInfo === false) {
return getEmptyChunk();
}
blockInfo = blockInfo || {};
if (typeof blockInfo === 'string') {
blockType = blockInfo;
blockDataMap = Map();
} else {
blockType = typeof blockInfo === 'string' ? blockInfo : blockInfo.type;
blockDataMap = blockInfo.data ? Map(blockInfo.data) : Map();
}
if (!inBlock && (fragmentBlockTags.indexOf(nodeName) !== -1 || blockType)) {
chunk = getBlockDividerChunk(blockType || getBlockTypeForTag(nodeName, lastList), depth, blockDataMap);
inBlock = blockType || getBlockTypeForTag(nodeName, lastList);
newBlock = true;
} else if (lastList && (inBlock === 'ordered-list-item' || inBlock === 'unordered-list-item') && nodeName === 'li') {
var listItemBlockType = getBlockTypeForTag(nodeName, lastList);
chunk = getBlockDividerChunk(listItemBlockType, depth);
inBlock = listItemBlockType;
newBlock = true;
nextBlockType = lastList === 'ul' ? 'unordered-list-item' : 'ordered-list-item';
} else if (inBlock && inBlock !== 'atomic' && blockType === 'atomic') {
inBlock = blockType;
newBlock = true;
chunk = getSoftNewlineChunk(blockType, depth, true, // atomic blocks within non-atomic blocks must always be split out
blockDataMap);
} // Recurse through children
var child = node.firstChild; // hack to allow conversion of atomic blocks from HTML (e.g. <figure><img
// src="..." /></figure>). since metadata must be stored on an entity text
// must exist for the entity to apply to. the way chunks are joined strips
// whitespace at the end so it cannot be a space character.
if (child == null && inEntity && (blockType === 'atomic' || inBlock === 'atomic')) {
child = document.createTextNode('a');
}
if (child != null) {
nodeName = child.nodeName.toLowerCase();
}
var entityId = null;
while (child) {
entityId = checkEntityNode(nodeName, child, createEntity, getEntity, mergeEntityData, replaceEntityData);
newChunk = genFragment(child, inlineStyle, lastList, inBlock, fragmentBlockTags, depth, processCustomInlineStyles, checkEntityNode, checkEntityText, checkBlockType, createEntity, getEntity, mergeEntityData, replaceEntityData, options, entityId || inEntity);
chunk = joinChunks(chunk, newChunk, options.flat);
var sibling = child.nextSibling; // Put in a newline to break up blocks inside blocks
if (sibling && fragmentBlockTags.indexOf(nodeName) >= 0 && inBlock) {
var newBlockInfo = checkBlockType(nodeName, child, lastList, inBlock);
var newBlockType = void 0;
var newBlockData = void 0;
if (newBlockInfo !== false) {
newBlockInfo = newBlockInfo || {};
if (typeof newBlockInfo === 'string') {
newBlockType = newBlockInfo;
newBlockData = Map();
} else {
newBlockType = newBlockInfo.type || getBlockTypeForTag(nodeName, lastList);
newBlockData = newBlockInfo.data ? Map(newBlockInfo.data) : Map();
}
chunk = joinChunks(chunk, getSoftNewlineChunk(newBlockType, depth, options.flat, newBlockData), options.flat);
}
}
if (sibling) {
nodeName = sibling.nodeName.toLowerCase();
}
child = sibling;
}
if (newBlock) {
chunk = joinChunks(chunk, getBlockDividerChunk(nextBlockType, depth, Map()), options.flat);
}
return chunk;
}