"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.updateCodeBlockWrappedStateNodeKeys = exports.transferCodeBlockWrappedValue = exports.setCodeBlockFoldState = exports.normalizeMarkdownCodeBlockAttrsInSlice = exports.isCodeBlockWordWrapEnabled = exports.getInsertedCodeBlocksInTransaction = exports.getDefaultCodeBlockAttrs = exports.getCodeBlockFoldState = exports.defaultWordWrapState = exports.codeBlockWrappedStates = exports.areCodeBlockLineNumbersVisible = exports.areCodeBlockLineNumbersHidden = void 0;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _adfSchema = require("@atlaskit/adf-schema");
var _transform = require("@atlaskit/editor-prosemirror/transform");
var _platformFeatureFlags = require("@atlaskit/platform-feature-flags");
var _expValEquals = require("@atlaskit/tmp-editor-statsig/exp-val-equals");
var _expValEqualsNoExposure = require("@atlaskit/tmp-editor-statsig/exp-val-equals-no-exposure");
var _slice = require("../utils/slice");
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } /* eslint-disable @atlaskit/volt-strict-mode/no-multiple-exports */
var defaultWordWrapState = exports.defaultWordWrapState = false;

// Remove the wrap WeakMap fallback when cleaning up platform_editor_code_block_q4_lovability
var codeBlockWrappedStates = exports.codeBlockWrappedStates = new WeakMap();
var getDefaultCodeBlockAttrs = exports.getDefaultCodeBlockAttrs = function getDefaultCodeBlockAttrs(attrs) {
  var _attrs$localId;
  var localId = (_attrs$localId = attrs === null || attrs === void 0 ? void 0 : attrs.localId) !== null && _attrs$localId !== void 0 ? _attrs$localId :
  // eslint-disable-next-line @atlaskit/platform/no-preconditioning
  (0, _expValEquals.expValEquals)('platform_editor_code_block_q4_lovability', 'isEnabled', true) && (0, _platformFeatureFlags.fg)('platform_editor_code_block_language_detection_flow') ? _adfSchema.uuid.generate() : undefined;
  var attrsWithLocalId = localId ? _objectSpread(_objectSpread({}, attrs), {}, {
    localId: localId
  }) : attrs;
  if (!(0, _expValEqualsNoExposure.expValEqualsNoExposure)('platform_editor_code_block_q4_lovability', 'isEnabled', true)) {
    return attrsWithLocalId;
  }

  // Only boolean wrap values represent caller intent. null/undefined means unset.
  if ((attrs === null || attrs === void 0 ? void 0 : attrs.wrap) === true || (attrs === null || attrs === void 0 ? void 0 : attrs.wrap) === false) {
    return attrsWithLocalId;
  }
  return _objectSpread(_objectSpread({}, attrsWithLocalId), {}, {
    wrap: true
  });
};
var normalizeMarkdownCodeBlockAttrsInSlice = exports.normalizeMarkdownCodeBlockAttrsInSlice = function normalizeMarkdownCodeBlockAttrsInSlice(slice, schema) {
  if (!(0, _expValEquals.expValEquals)('platform_editor_code_block_q4_lovability', 'isEnabled', true)) {
    return slice;
  }
  return (0, _slice.mapSlice)(slice, function (node) {
    if (node.type !== schema.nodes.codeBlock || node.attrs.wrap === true) {
      return node;
    }

    // Markdown conversion uses MarkdownParser token mappings and creates code block nodes
    // with the schema-default wrap:false. Since Markdown has no wrap syntax, treat that
    // default as missing user intent and change it to wrap:true.
    return node.type.create(getDefaultCodeBlockAttrs(node.attrs), node.content, node.marks);
  });
};
var isReplaceStep = function isReplaceStep(step) {
  return step instanceof _transform.ReplaceStep || step instanceof _transform.ReplaceAroundStep;
};
var isNodeShellReplaceStep = function isNodeShellReplaceStep(step) {
  return step instanceof _transform.ReplaceAroundStep &&
  // Node shell updates preserve all inner content and only replace the outer node boundary.
  step.gapFrom === step.from + 1 && step.gapTo === step.to - 1;
};
var hasInsertedCodeBlockInStep = function hasInsertedCodeBlockInStep(step, codeBlockType, filter) {
  var hasInsertedCodeBlock = false;
  step.slice.content.descendants(function (node) {
    if (node.type === codeBlockType && (!filter || filter(node))) {
      hasInsertedCodeBlock = true;
      return false;
    }
    return !hasInsertedCodeBlock;
  });
  return hasInsertedCodeBlock;
};
var collectMappedInsertedRanges = function collectMappedInsertedRanges(tr, stepIndex) {
  var ranges = [];
  var stepMap = tr.mapping.maps[stepIndex];
  var remainingMaps = tr.mapping.slice(stepIndex + 1);
  stepMap.forEach(function (_oldStart, _oldEnd, newStart, newEnd) {
    if (newStart === newEnd) {
      return;
    }
    var finalFrom = remainingMaps.map(newStart, 1);
    var finalTo = remainingMaps.map(newEnd, -1);
    if (finalFrom < finalTo) {
      ranges.push([finalFrom, finalTo]);
    }
  });
  return ranges;
};
var getInsertedCodeBlocksInTransaction = exports.getInsertedCodeBlocksInTransaction = function getInsertedCodeBlocksInTransaction(tr, codeBlockType) {
  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var insertedCodeBlocks = [];
  var seenPositions = new Set();
  tr.steps.forEach(function (step, stepIndex) {
    if (!isReplaceStep(step)) {
      return;
    }

    // Attribute/type updates can replace just the node shell while preserving content.
    // Those should not make an existing code block look newly inserted.
    if (isNodeShellReplaceStep(step)) {
      return;
    }
    var insertedCodeBlockByStep = hasInsertedCodeBlockInStep(step, codeBlockType, options.filter);
    if (!insertedCodeBlockByStep) {
      return;
    }
    collectMappedInsertedRanges(tr, stepIndex).forEach(function (_ref) {
      var _ref2 = (0, _slicedToArray2.default)(_ref, 2),
        from = _ref2[0],
        to = _ref2[1];
      tr.doc.nodesBetween(from, to, function (node, pos) {
        if (pos >= from && node.type === codeBlockType && (!options.filter || options.filter(node)) && !seenPositions.has(pos)) {
          seenPositions.add(pos);
          insertedCodeBlocks.push({
            node: node,
            pos: pos
          });
          return false;
        }
        return true;
      });
    });
  });
  return insertedCodeBlocks;
};

// Code folding state management - similar to word wrapping

var codeBlockFoldStates = new WeakMap();
var isCodeBlockWordWrapEnabled = exports.isCodeBlockWordWrapEnabled = function isCodeBlockWordWrapEnabled(codeBlockNode) {
  if ((0, _expValEqualsNoExposure.expValEqualsNoExposure)('platform_editor_code_block_q4_lovability', 'isEnabled', true)) {
    return Boolean(codeBlockNode.attrs.wrap);
  }
  var currentNodeWordWrapState = codeBlockWrappedStates.get(codeBlockNode);
  return currentNodeWordWrapState !== undefined ? currentNodeWordWrapState : defaultWordWrapState;
};
var areCodeBlockLineNumbersHidden = exports.areCodeBlockLineNumbersHidden = function areCodeBlockLineNumbersHidden(codeBlockNode) {
  if (!(0, _expValEqualsNoExposure.expValEqualsNoExposure)('platform_editor_code_block_q4_lovability', 'isEnabled', true)) {
    return false;
  }
  return Boolean(codeBlockNode.attrs.hideLineNumbers);
};
var areCodeBlockLineNumbersVisible = exports.areCodeBlockLineNumbersVisible = function areCodeBlockLineNumbersVisible(codeBlockNode) {
  return !areCodeBlockLineNumbersHidden(codeBlockNode);
};
var getCodeBlockFoldState = exports.getCodeBlockFoldState = function getCodeBlockFoldState(codeBlockNode) {
  var currentNodeFoldState = codeBlockFoldStates.get(codeBlockNode);
  return currentNodeFoldState || [];
};
var setCodeBlockFoldState = exports.setCodeBlockFoldState = function setCodeBlockFoldState(codeBlockNode, foldRanges) {
  codeBlockFoldStates.set(codeBlockNode, foldRanges);
};

/**
 * Swap the old node key with the new node key in the wrapped states WeakMap.
 */
var transferCodeBlockWrappedValue = exports.transferCodeBlockWrappedValue = function transferCodeBlockWrappedValue(oldCodeBlockNode, newCodeBlockNode) {
  if ((0, _expValEquals.expValEquals)('platform_editor_code_block_fold_gutter', 'isEnabled', true)) {
    transferCodeBlockFoldValue(oldCodeBlockNode, newCodeBlockNode);
  }

  // Don't overwrite the value for the new node if it already exists.
  // This can happen when a drag&drop is swapping nodes.
  if (codeBlockWrappedStates.has(newCodeBlockNode)) {
    return;
  }
  var previousValue = isCodeBlockWordWrapEnabled(oldCodeBlockNode);
  codeBlockWrappedStates.set(newCodeBlockNode, previousValue);
  codeBlockWrappedStates.delete(oldCodeBlockNode);
};

/**
 * Swap the old node key with the new node key in the fold states WeakMap.
 */
var transferCodeBlockFoldValue = function transferCodeBlockFoldValue(oldCodeBlockNode, newCodeBlockNode) {
  // Don't overwrite the value for the new node if it already exists.
  // This can happen when a drag&drop is swapping nodes.
  if (codeBlockFoldStates.has(newCodeBlockNode)) {
    return;
  }
  var previousValue = getCodeBlockFoldState(oldCodeBlockNode);
  codeBlockFoldStates.set(newCodeBlockNode, previousValue);
  codeBlockFoldStates.delete(oldCodeBlockNode);
};

/**
 * As the code block node is used as the wrapped state key, there is instances where the node will be destroyed & recreated and is no longer a valid key.
 * In these instances, we must get the value from that old node and set it to the value of the new node.
 * This function takes all the given nodes, finds their old nodes from the old state and updates these old node keys.
 */
var updateCodeBlockWrappedStateNodeKeys = exports.updateCodeBlockWrappedStateNodeKeys = function updateCodeBlockWrappedStateNodeKeys(newCodeBlockNodes, oldState) {
  newCodeBlockNodes.forEach(function (newCodeBlockNode) {
    if ((0, _expValEquals.expValEquals)('platform_editor_code_block_fold_gutter', 'isEnabled', true)) {
      updateCodeBlockFoldStateNodeKeys(newCodeBlockNode, oldState);
    }
    // Don't overwrite the value for the new node if it already exists.
    // This can happen when a drag&drop is swapping nodes.
    if (codeBlockWrappedStates.has(newCodeBlockNode.node)) {
      return;
    }

    // Do not go out of range on the oldState doc. Happens on initial load.
    if (oldState.doc.content.size <= newCodeBlockNode.pos) {
      return;
    }
    var oldCodeBlockNode = oldState.doc.nodeAt(newCodeBlockNode.pos);
    if (!oldCodeBlockNode || oldCodeBlockNode.type !== oldState.schema.nodes.codeBlock) {
      return;
    }
    var previousValue = isCodeBlockWordWrapEnabled(oldCodeBlockNode);
    codeBlockWrappedStates.set(newCodeBlockNode.node, previousValue);
  });
};

/**
 * As the code block node is used as the fold state key, there is instances where the node will be destroyed & recreated and is no longer a valid key.
 * In these instances, we must get the value from that old node and set it to the value of the new node.
 * This function takes all the given nodes, finds their old nodes from the old state and updates these old node keys.
 */
var updateCodeBlockFoldStateNodeKeys = function updateCodeBlockFoldStateNodeKeys(newCodeBlockNode, oldState) {
  // Don't overwrite the value for the new node if it already exists.
  // This can happen when a drag&drop is swapping nodes.
  if (codeBlockFoldStates.has(newCodeBlockNode.node)) {
    return;
  }

  // Do not go out of range on the oldState doc. Happens on initial load.
  if (oldState.doc.content.size <= newCodeBlockNode.pos) {
    return;
  }
  var oldCodeBlockNode = oldState.doc.nodeAt(newCodeBlockNode.pos);
  if (!oldCodeBlockNode || oldCodeBlockNode.type !== oldState.schema.nodes.codeBlock) {
    return;
  }
  var previousValue = getCodeBlockFoldState(oldCodeBlockNode);
  codeBlockFoldStates.set(newCodeBlockNode.node, previousValue);
};