"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
exports.findSelection = findSelection;
var _richText = require("@wordpress/rich-text");
var _blocks = require("@wordpress/blocks");
var _store = require("../../../store");
var _preventEventDiscovery = require("../prevent-event-discovery");
var _selection = require("../../../utils/selection");
/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

function findSelection(blocks) {
  let i = blocks.length;
  while (i--) {
    const attributeKey = (0, _selection.retrieveSelectedAttribute)(blocks[i].attributes);
    if (attributeKey) {
      blocks[i].attributes[attributeKey] = blocks[i].attributes[attributeKey]
      // To do: refactor this to use rich text's selection instead, so
      // we no longer have to use on this hack inserting a special
      // character.
      .toString().replace(_selection.START_OF_SELECTED_AREA, '');
      return [blocks[i].clientId, attributeKey, 0, 0];
    }
    const nestedSelection = findSelection(blocks[i].innerBlocks);
    if (nestedSelection) {
      return nestedSelection;
    }
  }
  return [];
}
var _default = props => element => {
  function inputRule() {
    const {
      getValue,
      onReplace,
      selectionChange,
      registry
    } = props.current;
    if (!onReplace) {
      return;
    }

    // We must use getValue() here because value may be update
    // asynchronously.
    const value = getValue();
    const {
      start,
      text
    } = value;
    const characterBefore = text.slice(start - 1, start);

    // The character right before the caret must be a plain space.
    if (characterBefore !== ' ') {
      return;
    }
    const trimmedTextBefore = text.slice(0, start).trim();
    const prefixTransforms = (0, _blocks.getBlockTransforms)('from').filter(({
      type
    }) => type === 'prefix');
    const transformation = (0, _blocks.findTransform)(prefixTransforms, ({
      prefix
    }) => {
      return trimmedTextBefore === prefix;
    });
    if (!transformation) {
      return;
    }
    const content = (0, _richText.toHTMLString)({
      value: (0, _richText.insert)(value, _selection.START_OF_SELECTED_AREA, 0, start)
    });
    const block = transformation.transform(content);
    selectionChange(...findSelection([block]));
    onReplace([block]);
    registry.dispatch(_store.store).__unstableMarkAutomaticChange();
    return true;
  }
  function onInput(event) {
    const {
      inputType,
      type
    } = event;
    const {
      getValue,
      onChange,
      __unstableAllowPrefixTransformations,
      formatTypes,
      registry
    } = props.current;

    // Only run input rules when inserting text.
    if (inputType !== 'insertText' && type !== 'compositionend') {
      return;
    }
    if (__unstableAllowPrefixTransformations && inputRule()) {
      return;
    }
    const value = getValue();
    const transformed = formatTypes.reduce((accumlator, {
      __unstableInputRule
    }) => {
      if (__unstableInputRule) {
        accumlator = __unstableInputRule(accumlator);
      }
      return accumlator;
    }, (0, _preventEventDiscovery.preventEventDiscovery)(value));
    const {
      __unstableMarkLastChangeAsPersistent,
      __unstableMarkAutomaticChange
    } = registry.dispatch(_store.store);
    if (transformed !== value) {
      __unstableMarkLastChangeAsPersistent();
      onChange({
        ...transformed,
        activeFormats: value.activeFormats
      });
      __unstableMarkAutomaticChange();
    }
  }
  element.addEventListener('input', onInput);
  element.addEventListener('compositionend', onInput);
  return () => {
    element.removeEventListener('input', onInput);
    element.removeEventListener('compositionend', onInput);
  };
};
exports.default = _default;
//# sourceMappingURL=input-rules.js.map