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: TicksService.js    From binary-bot with MIT License 6 votes vote down vote up
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 #2
Source File: user-list.js    From ThreatMapper with Apache License 2.0 6 votes vote down vote up
renderUserModalContent({ userId } = {}) {
    const {
      userList,
    } = this.props;
    const userIndex = userList.reduce((acc, user) => {
      acc[user.id] = user;
      return acc;
    }, {});
    const selectedUser = userIndex[userId] || {};
    const initialValues = Map({
      ...selectedUser,
      role: {
        label: selectedUser.role,
        value: selectedUser.role,
      },
      isActive: {
        label: selectedUser.isActive === true ? 'Active' : 'Inactive',
        value: selectedUser.isActive,
      },
      api_key: '',
    });

    return (
      <div>
        <UserForm
          userId={userId}
          initialValues={initialValues}
          onSubmit={this.saveUser}
        />
      </div>
    );
  }
Example #3
Source File: index.js    From strapi-plugin-config-sync with MIT License 6 votes vote down vote up
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 #4
Source File: TicksService.js    From binary-bot with MIT License 6 votes vote down vote up
unsubscribeAllAndSubscribeListeners(symbol) {
    const ohlcSubscriptions = this.subscriptions.getIn(["ohlc", symbol]);
    const tickSubscription = this.subscriptions.getIn(["tick", symbol]);

    const subscription = [
      ...(ohlcSubscriptions ? Array.from(ohlcSubscriptions.values()) : []),
      ...(tickSubscription || []),
    ];

    Promise.all(subscription.map(id => doUntilDone(() => this.api.forget(id))));

    this.subscriptions = new Map();
  }
Example #5
Source File: ConfigStore.js    From spring-boot-ecommerce with Apache License 2.0 6 votes vote down vote up
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 #6
Source File: convertFromHTML.js    From the-eye-knows-the-garbage with MIT License 6 votes vote down vote up
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 #7
Source File: index.js    From Lynx with MIT License 6 votes vote down vote up
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 #8
Source File: config.js    From SubstrateIDE with GNU General Public License v3.0 6 votes vote down vote up
profile = {
  default: Map({}),
  persist: true,
  actions: {
    SET_USER_PROFILE: {
      reducer: (state, { payload }) => state.merge(payload)
    },
    CLEAR_USER_PROFILE: {
      reducer: () => Map({})
    },
  }
}
Example #9
Source File: node-details-cve-severity.js    From ThreatMapper with Apache License 2.0 6 votes vote down vote up
handleSectionClick(section) {
    const {
      openDonutDetailsModal: openAction,
      updateActiveDonut: updateDonutAction,
      nodeCveSeverityIm = Map(),
    } = this.props;

    const { fullImageName } = this.state;

    const nodeCveSeverity = nodeCveSeverityIm.get(fullImageName, []);
    if (nodeCveSeverity.length > 0) {
      const { scanId } = nodeCveSeverity[0];
      updateDonutAction(section.name, 'cve_severity', fullImageName, scanId);
      openAction();
    }
  }
Example #10
Source File: index.js    From strapi-plugin-config-sync with MIT License 6 votes vote down vote up
ConfigPage = () => {
  const toggleNotification = useNotification();
  const dispatch = useDispatch();
  const isLoading = useSelector((state) => state.getIn(['config', 'isLoading'], Map({})));
  const configDiff = useSelector((state) => state.getIn(['config', 'configDiff'], Map({})));
  const appEnv = useSelector((state) => state.getIn(['config', 'appEnv']));

  useEffect(() => {
    dispatch(getAllConfigDiff(toggleNotification));
    dispatch(getAppEnv(toggleNotification));
  }, []);

  return (
    <ContentLayout paddingBottom={8}>
      {appEnv === 'production' && (
        <Box paddingBottom={4}>
          <Alert variant="danger">
            <Typography variant="omega" fontWeight="bold">You&apos;re in the production environment</Typography><br />
            Please be careful when syncing your config in production.<br />
            Make sure you are not overriding critical config changes on import.
          </Alert>
        </Box>
      )}
      <ActionButtons />
      <ConfigList isLoading={isLoading} diff={configDiff.toJS()} />
    </ContentLayout>
  );
}
Example #11
Source File: index.js    From strapi-plugin-sitemap with MIT License 6 votes vote down vote up
initialState = fromJS({
  info: {},
  allowedFields: {},
  settings: Map({}),
  contentTypes: {},
  languages: [],
  initialData: Map({}),
  modifiedContentTypes: Map({}),
  modifiedCustomEntries: Map({}),
})
Example #12
Source File: multi-cloud-action.js    From ThreatMapper with Apache License 2.0 6 votes vote down vote up
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 #13
Source File: Sitemap.js    From strapi-plugin-sitemap with MIT License 6 votes vote down vote up
// 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 #14
Source File: ProjectDashboard.js    From minerva with MIT License 5 votes vote down vote up
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: user-list.js    From ThreatMapper with Apache License 2.0 5 votes vote down vote up
UNSAFE_componentWillReceiveProps(newProps) {
    const { deleteError: newDeleteError } = newProps;
    const { dispatch, deleteError: oldDeleteError = Map() } = this.props;
    if (newDeleteError && newDeleteError.get('timestamp') !== oldDeleteError.get('timestamp')) {
      dispatch(toaster(newDeleteError.get('message')));
    }
  }
Example #16
Source File: index.js    From strapi-plugin-sitemap with MIT License 5 votes vote down vote up
CustomURLs = () => {
  const state = useSelector((store) => store.get('sitemap', Map()));
  const dispatch = useDispatch();
  const [modalOpen, setModalOpen] = useState(false);
  const [uid, setUid] = useState(null);

  const handleModalSubmit = (e) => {
    e.preventDefault();
    dispatch(submitModal());
    setModalOpen(false);
    setUid(null);
  };

  const handleModalOpen = (editId) => {
    if (editId) setUid(editId);
    setModalOpen(true);
  };

  const handleModalClose = (closeModal = true) => {
    if (closeModal) setModalOpen(false);
    dispatch(discardModifiedContentTypes());
    setUid(null);
  };

  // Loading state
  if (!state.getIn(['settings', 'customEntries'])) {
    return null;
  }

  return (
    <div>
      <List
        items={state.getIn(['settings', 'customEntries'])}
        openModal={(editId) => handleModalOpen(editId)}
        onDelete={(key) => dispatch(deleteCustomEntry(key))}
        prependSlash
      />
      <ModalForm
        modifiedState={state.get('modifiedCustomEntries')}
        isOpen={modalOpen}
        id={uid}
        onSubmit={(e) => handleModalSubmit(e)}
        onCancel={(closeModal) => handleModalClose(closeModal)}
        onChange={(url, key, value) => dispatch(onChangeCustomEntry(url, key, value))}
        type="custom"
      />
    </div>
  );
}
Example #17
Source File: observer.js    From binary-bot with MIT License 5 votes vote down vote up
constructor() {
        this.eam = new Map(); // event action map
        this.state = {};
    }
Example #18
Source File: Toolbar.js    From spring-boot-ecommerce with Apache License 2.0 5 votes vote down vote up
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 #19
Source File: index.js    From strapi-plugin-sitemap with MIT License 5 votes vote down vote up
Settings = () => {
  const { formatMessage } = useIntl();
  const dispatch = useDispatch();
  const [open, setOpen] = useState(false);
  const languages = useSelector((store) => store.getIn(['sitemap', 'languages'], {}));
  const settings = useSelector((state) => state.getIn(['sitemap', 'settings'], Map()));
  const hostnameOverrides = useSelector((state) => state.getIn(['sitemap', 'settings', 'hostname_overrides'], {}));
  const theme = useTheme();

  const saveHostnameOverrides = (hostnames) => {
    dispatch(onChangeSettings('hostname_overrides', hostnames));
    setOpen(false);
  };

  return (
    <Grid gap={4}>
      <GridItem col={6} s={12}>
        <TextInput
          placeholder="https://www.strapi.io"
          label={formatMessage({ id: 'sitemap.Settings.Field.Hostname.Label', defaultMessage: 'Hostname' })}
          name="hostname"
          value={settings.get('hostname')}
          hint={formatMessage({ id: 'sitemap.Settings.Field.Hostname.Description', defaultMessage: 'The URL of your website' })}
          onChange={(e) => dispatch(onChangeSettings('hostname', e.target.value))}
        />
      </GridItem>
      {languages.length > 1 && (
        <GridItem col={12} s={12}>
          <Typography variant="pi" fontWeight="bold">
            {formatMessage({ id: 'sitemap.Settings.Field.HostnameOverrides.Label', defaultMessage: 'Hostname overrides' })}
          </Typography>
          <Button
            onClick={() => setOpen(true)}
            variant="tertiary"
            style={{ marginTop: '5px', marginBottom: '3px' }}
          >
            {formatMessage({ id: 'sitemap.Settings.Field.HostnameOverrides.Button', defaultMessage: 'Configure' })}
          </Button>
          <Typography variant="pi" style={{ color: theme.colors.neutral600 }}>
            {formatMessage({ id: 'sitemap.Settings.Field.HostnameOverrides.Description', defaultMessage: 'Specify hostname per language' })}
          </Typography>
          <HostnameModal
            isOpen={open}
            languages={languages}
            hostnameOverrides={hostnameOverrides}
            onSave={saveHostnameOverrides}
            onCancel={() => setOpen(false)}
          />
        </GridItem>
      )}
      <GridItem col={12} s={12}>
        <ToggleInput
          hint={formatMessage({ id: 'sitemap.Settings.Field.IncludeHomepage.Description', defaultMessage: "Include a '/' entry when none is present." })}
          label={formatMessage({ id: 'sitemap.Settings.Field.IncludeHomepage.Label', defaultMessage: 'Include home page' })}
          name="includeHomepage"
          onLabel="on"
          offLabel="off"
          checked={settings.get('includeHomepage')}
          onChange={(e) => dispatch(onChangeSettings('includeHomepage', e.target.checked))}
        />
      </GridItem>
      <GridItem col={12} s={12}>
        <ToggleInput
          hint={formatMessage({ id: 'sitemap.Settings.Field.ExcludeDrafts.Description', defaultMessage: 'Remove all draft entries from the sitemap.' })}
          label={formatMessage({ id: 'sitemap.Settings.Field.ExcludeDrafts.Label', defaultMessage: 'Exclude drafts' })}
          name="excludeDrafts"
          onLabel="on"
          offLabel="off"
          checked={settings.get('excludeDrafts')}
          onChange={(e) => dispatch(onChangeSettings('excludeDrafts', e.target.checked))}
        />
      </GridItem>
    </Grid>
  );
}
Example #20
Source File: index.js    From strapi-plugin-config-sync with MIT License 5 votes vote down vote up
initialState = fromJS({
  configDiff: Map({}),
  partialDiff: List([]),
  isLoading: false,
  appEnv: 'development',
})
Example #21
Source File: convertFromHTML.js    From the-eye-knows-the-garbage with MIT License 5 votes vote down vote up
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 #22
Source File: reducer.js    From NeteaseCloudMusic with MIT License 5 votes vote down vote up
initState = Map({
  bannersList: [],
  personalizedList: [],
})
Example #23
Source File: report-download-reducer.js    From ThreatMapper with Apache License 2.0 5 votes vote down vote up
initialState = Map()
Example #24
Source File: index.js    From spring-boot-ecommerce with Apache License 2.0 4 votes vote down vote up
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 #25
Source File: cve-reducer.js    From ThreatMapper with Apache License 2.0 4 votes vote down vote up
function containerImageRegistryReducer(state = Map({}), action) {
  switch (action.type) {
    case ActionTypes.SAVE_CONTAINER_IMAGE_REGISTRY_REQUEST: {
      const {
        input: {
          registry_type: registryType,
        },
      } = action;
      state = state.setIn(['add_credentials', 'loading', registryType], true);
      return state;
    }
    case ActionTypes.SAVE_CONTAINER_IMAGE_REGISTRY_SUCCESS: {
      const {
        payload: {
          success,
          error,
        } = {},
        input: {
          registry_type: registryType,
        },
      } = action;

      let errorMessage = '';
      if (error) {
        errorMessage = error.message || '';
      }

      state = state.setIn(['add_credentials', 'loading', registryType], false);
      if (success) {
        state = state.setIn(['add_credentials', 'message', registryType], 'Credentials saved successfully');
        state = state.deleteIn(['add_credentials', 'error', 'message', registryType]);
      } else {
        state = state.setIn(['add_credentials', 'error', 'message', registryType], errorMessage);
      }
      return state;
    }
    case ActionTypes.SAVE_CONTAINER_IMAGE_REGISTRY_FAILURE: {
      const {
        input: {
          registry_type: registryType,
        },
        payload: {
          // eslint-disable-next-line camelcase
          response: response_str,
        } = {},
      } = action;
      const response = JSON.parse(response_str);
      const {
        error,
      } = response;
      let errorMessage = 'Unknown error. Credentials failed to save.';
      if (error) {
        errorMessage = error.message || '';
      }
      state = state.setIn(['add_credentials', 'loading', registryType], false);
      state = state.setIn(['add_credentials', 'error', 'message', registryType], errorMessage);
      return state;
    }
    case ActionTypes.CLEAR_CONTAINER_IMAGE_REGISTRY_ADD_FORM: {
      state = state.deleteIn(['add_credentials', 'loading']);
      state = state.deleteIn(['add_credentials', 'error']);
      return state;
    }

    case ActionTypes.LIST_CONTAINER_IMAGE_REGISTRY_REQUEST: {
      const {
        input: {
          registryType,
        },
      } = action;
      state = state.setIn(['list_credentials', 'loading', registryType], true);
      return state;
    }
    case ActionTypes.LIST_CONTAINER_IMAGE_REGISTRY_SUCCESS: {
      const {
        payload: {
          success,
          data = []
        } = {},
        input: {
          registryType,
        },
      } = action;

      state = state.setIn(['list_credentials', 'loading', registryType], false);
      if (success) {
        state = state.setIn(['list_credentials', 'data', registryType], data);
        state = state.deleteIn(['list_credentials', 'error', 'message', registryType]);
      } else {
        state = state.setIn(['list_credentials', 'error', 'message', registryType], 'Failed to list credentials');
      }
      return state;
    }
    case ActionTypes.LIST_CONTAINER_IMAGE_REGISTRY_FAILURE: {
      const {
        input: {
          registryType,
        },
      } = action;
      state = state.setIn(['list_credentials', 'loading', registryType], false);
      state = state.setIn(['list_credentials', 'error', 'message', registryType], 'Unknown error. Failed to list credentials');
      return state;
    }
    case ActionTypes.CLEAR_CONTAINER_REGISTRY_SEARCH: {
      state = state.delete('search');
      return state;
    }
    case ActionTypes.UPDATE_CONTAINER_REGISTRY_SEARCH: {
      const {
        payload: {
          registryType,
          registryId,
          q = '',
          searchType,
        } = {},
      } = action;
      if (searchType) {
        state = state.setIn(['search', 'type'], searchType);
        state = state.deleteIn(['search', 'q']);
        return state;
      }

      const currentSearchType = state.getIn(['search', 'type']);

      state = state.setIn(['search', 'q'], q);

      const images = state.getIn(['images', registryType, registryId]);
      const normalisedImages = images.map(image => ({
        ...image,
        summary: image.cve_status.summary,
      }));
      const filteredImages = normalisedImages.filter((image) => {
        const value = image[currentSearchType] || '';
        return value.toLowerCase().includes(q.toLowerCase());
      });
      state = state.setIn(['filtered_images', registryType, registryId], filteredImages);
      return state;
    }
    case ActionTypes.LIST_REGISTRY_IMAGES_REQUEST: {
      const {
        initiatedByPollable
      } = action.input || {};
      const {
        input: {
          registryType,
          registry_id: registryId,
        },
      } = action;
      state = state.setIn(['loading', registryType, registryId], true);
      state = state.setIn(['initiatedByPollable', registryType, registryId], initiatedByPollable);
      state = state.deleteIn(['error', 'message', registryType]);
      return state;
    }

    case ActionTypes.LIST_REGISTRY_IMAGES_SUCCESS: {
      const {
        payload: {
          data,
          error,
        },
        input: {
          registryType,
          registry_id: registryId,
        },
      } = action;

      let errorMessage;
      let imageList = [];
      let lastUpdatedStr;
      let total = 0;
      let uniqueImageCount = 0;
      let totalScanned = 0;
      let totalProgress = 0;
      let registryUpdateInProgress = false;
      if (error) {
        errorMessage = error.message;
      }
      if (data) {
        imageList = data.data;
        lastUpdatedStr = data.last_updated;
        // eslint-disable-next-line prefer-destructuring
        total = data.total;
        uniqueImageCount = data.unique_images;
        totalScanned = data.total_scanned;
        totalProgress = data.scan_in_progress;
        registryUpdateInProgress = data.registry_update_in_progress;
    }

      let lastUpdated;
      if (lastUpdatedStr) {
        lastUpdated = moment(lastUpdatedStr).fromNow();
      }

      state = state.setIn(['loading', registryType, registryId], false);
      state = state.setIn(['images', registryType, registryId], imageList);
      state = state.setIn(['total', registryType, registryId], total);
      state = state.setIn(['uniqueImageCount', registryType, registryId], uniqueImageCount);
      state = state.setIn(['updateInProgress', registryType, registryId], registryUpdateInProgress);
      state = state.setIn(['totalScanned', registryType, registryId], totalScanned);
      state = state.setIn(['totalProgress', registryType, registryId], totalProgress);
      state = state.setIn(['filtered_images', registryType, registryId], imageList);
      state = state.setIn(['last_updated', registryType, registryId], lastUpdated);
      state = state.setIn(['error', 'message', registryType, registryId], errorMessage);
      return state;
    }

    case ActionTypes.LIST_REGISTRY_IMAGES_FAILURE: {
      const {
        payload: {
          error: {
            message: errorMessage = 'Sorry, something went wrong',
          } = {},
        },
        input: {
          registry_type: registryType,
        },
      } = action;
      state = state.setIn(['loading', registryType], false);
      state = state.setIn(['error', 'message', registryType], errorMessage);
      return state;
    }

    case ActionTypes.SCAN_REGISTRY_IMAGES_REQUEST: {
      state = state.setIn(['scan_registry', 'loading'], true);
      state = state.deleteIn(['scan_registry', 'error', 'message']);
      state = state.deleteIn(['scan_registry', 'message']);
      return state;
    }

    case ActionTypes.CLEAR_SCAN_REGISTRY_IMAGES: {
      state = state.deleteIn(['scan_registry', 'error', 'message']);
      state = state.deleteIn(['scan_registry', 'message']);
      state = state.setIn(['scan_registry', 'loading'], false);
      return state;
    }

    case ActionTypes.SCAN_REGISTRY_IMAGES_SUCCESS: {
      const {
        payload: {
          success,
          error,
        } = {},
        input: {
          action: apiAction,
        },
      } = action;

      state = state.setIn(['scan_registry', 'loading'], false);

      let errorMessage;
      if (error) {
        errorMessage = error.message;
      }

      if (success) {
        state = state.deleteIn(['scan_registry', 'error', 'message']);
        let message = 'Request to scan for vulnerabilities has been queued';
        if (apiAction === 'start_compliance_scan') {
          message = 'Request to scan for compliance has been queued';
        } else if (apiAction === 'schedule_compliance_scan') {
          message = 'Request to schedule compliance scan has been saved successfully';
        } else if (apiAction === 'schedule_vulnerability_scan') {
          message = 'Request to schedule vulnerability scan has been saved successfully';
        }
        state = state.setIn(['scan_registry', 'message'], message);
      } else {
        state = state.setIn(['scan_registry', 'error', 'message'], errorMessage);
        state = state.deleteIn(['scan_registry', 'message']);
      }
      return state;
    }

    case ActionTypes.SCAN_REGISTRY_IMAGES_FAILURE: {
      state = state.setIn(['scan_registry', 'loading'], false);
      state = state.setIn(['scan_registry', 'error', 'message'], 'Sorry, something went wrong');
      return state;
    }

    case ActionTypes.SECRETS_SCAN_REGISTRY_IMAGES_REQUEST: {
      state = state.setIn(['scan_registry', 'loading'], true);
      state = state.deleteIn(['scan_registry', 'error', 'message']);
      state = state.deleteIn(['scan_registry', 'message']);
      return state;
    }

    case ActionTypes.SECRETS_SCAN_REGISTRY_IMAGES_SUCCESS: {
      const {
        payload: {
          success,
          error,
        } = {},
      } = action;

      state = state.setIn(['scan_registry', 'loading'], false);

      let errorMessage;
      if (error) {
        errorMessage = error.message;
      }
      if (success) {
        state = state.deleteIn(['scan_registry', 'error', 'message']);
        const message = 'Request to scan has been queued';
        state = state.setIn(['scan_registry', 'message'], message);
      } else {
        state = state.setIn(['scan_registry', 'error', 'message'], errorMessage);
        state = state.deleteIn(['scan_registry', 'message']);
      }
      return state;
    }

    case ActionTypes.SECRETS_SCAN_REGISTRY_IMAGES_FAILURE: {
      state = state.setIn(['scan_registry', 'loading'], false);
      state = state.setIn(['scan_registry', 'error', 'message'], 'Sorry, something went wrong');
      return state;
    }

    default:
      return state;
  }
}
Example #26
Source File: index.js    From strapi-plugin-sitemap with MIT License 4 votes vote down vote up
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 #27
Source File: context.js    From minerva with MIT License 4 votes vote down vote up
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 #28
Source File: top-exploitable-vulnerabilities.js    From ThreatMapper with Apache License 2.0 4 votes vote down vote up
render() {
    const {
      topStats = [],
      groupedTopExploits = [],
      globalSearchQuery,
      dispatch,
      attackPaths: attackPathsIndex = Map()
    } = this.props;
    const attackPaths = attackPathsIndex.get(this.state.graphType, []);
    let allEmpty = false;
    if (groupedTopExploits && groupedTopExploits.children) {
      if (
        groupedTopExploits.children[0].children.length === 0
        && groupedTopExploits.children[1].children.length === 0
        && groupedTopExploits.children[2].children.length === 0
        && groupedTopExploits.children[3].children.length === 0
      ) {
        allEmpty = true;
      }
    }
    const emptyData = allEmpty;


    return (
      <div className="runtime-vulnerabilities">
        <div className="runtime-vulnerabilities-chart">
          <div className="charts-heading">Most exploitable vulnerabilities and Top attack paths</div>
          <div className="charts-container">
            <div className="chart-container">
              {emptyData
                ? (
                  <div className="empty-data">
                    Vulnerabilities data not available
                  </div>
                ) : <TopExploitableSeverityReport
                  data={groupedTopExploits}
                  globalSearchQuery={globalSearchQuery}
                  dispatch={dispatch}
                />}
            </div>
            <div className="chart-container dagre-chart-container">
              {
                attackPaths && Array.isArray(attackPaths) && attackPaths.length ? (
                  <DagreGraph
                    data={formatApiDataForDagreGraph(attackPaths)}
                  />
                ) : (
                  <div className="empty-data">
                    No attack paths exist
                  </div>
                )
              }
            </div>
            <div className="chart-container">
              <GraphTypeSelector onChange={(graphType) => {
                this.setState({
                  graphType
                }, () => {
                  this.getTopStats();
                });
              }}
                graphOptions={graphOptions}
              />
            </div>
          </div>
        </div>
        <div className="runtime-vulnerabilities-chart">
          <DfTableV2
            onRowClick={(row) => this.handleCVEIdClick(row.original.docId)}
            enableSorting
            data={topStats}
            showPagination
            columns={[
              {
                Header: 'Rank',
                accessor: 'rank',
                width: 50,
                sortType: 'number'
              },
              {
                Header: 'CVE ID',
                accessor: 'cveId',
                width: 100,
                Cell: row => (
                  <div
                    className="truncate"
                    title={row.value}>
                    {row.value}
                  </div>
                ),
              },
              {
                Header: 'Severity',
                accessor: 'cveSeverity',
                width: 100,
                minWidth: 100,
                Cell: row => (
                  <div
                    className={`${row.value}-severity`}
                  >
                    {row.value}
                  </div>
                ),
              },
              {
                Header: 'Score',
                accessor: 'score',
                width: 50,
                Cell: row => (
                  <div>
                    {row.value.toFixed(2)}
                  </div>
                ),
                sortType: 'number'
              },
              {
                Header: 'Attack Vector',
                accessor: 'attackVector',
                width: 80,
              },
              {
                Header: 'Live Connection',
                accessor: 'liveConnection',
                width: 80,
                Cell: (row) => (
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <div>{row.value ? 'Yes' : 'No'}</div>
                  </div>
                ),
              },
              {
                Header: 'Exploit',
                accessor: 'exploitPoc',
                width: 60,
                Cell: (row) =>{
                  return (
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      {
                        row.value && row.value.length ? (
                          <a href={row.value} onClick={(e) => e.stopPropagation()} target="_blank" without rel="noreferrer">Link &nbsp;<i className='fa fa-external-link-square' /></a>
                        ) : <div>-</div>
                      }
                    </div>
                  )
                },
              },
              {
                Header: 'Image',
                id: 'image',
                accessor: (row) => {
                  const {
                    vulnerableImages = [],
                    image,
                  } = row;
                  const otherImages = vulnerableImages.length - 1;
                  return `${image} ${otherImages ? ` + ${otherImages} image(s)` : ''}`;
                },
                Cell: (row) => {
                  const {
                    original: {
                      vulnerableImages = [],
                    } = {},
                  } = row;
                  const otherImages = vulnerableImages.join(', ');
                  return (
                    <div
                      className="truncate"
                      title={otherImages}>
                      {row.value}
                    </div>
                  );
                },
                width: 200,
              },
              {
                Header: 'Description',
                accessor: 'description',
                Cell: row => (
                  <div
                    className="truncate"
                    title={row.value}>
                    {row.value}
                  </div>
                ),
                width: 300,
              },
            ]} />
        </div>
        {
          this.state.isVulnerabilityModalOpen && this.state.cveData ? (
            <VulnerabilityModal
              data={this.state.cveData}
              onRequestClose={() => {
                this.setState({
                  isVulnerabilityModalOpen: false,
                  cveData: null
                });
              }}
            />
          ) : null
        }
      </div>
    );
  }
Example #29
Source File: convertFromHTML.js    From the-eye-knows-the-garbage with MIT License 4 votes vote down vote up
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;
}