"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.scheduleDocumentRequest = void 0;
exports.toJSON = toJSON;
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _editorJsonTransformer = require("@atlaskit/editor-json-transformer");
var _model = require("@atlaskit/editor-prosemirror/model");
var transformer = new _editorJsonTransformer.JSONTransformer();
function toJSON(node) {
  return transformer.encode(node);
}

/**
 * This throttles the callback with requestIdleCallback.
 */
function createThrottleSchedule(callback) {
  var frameId;
  var lastArgs;
  var wrapperFn = function wrapperFn() {
    var _globalThis$requestId;
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    lastArgs = args;
    if (frameId) {
      return;
    }

    // If `requestIdleCallback` doesn't exist - fallback to `requestAnimationFrame`
    var delayFunction = (_globalThis$requestId = globalThis.requestIdleCallback) !== null && _globalThis$requestId !== void 0 ? _globalThis$requestId : globalThis.requestAnimationFrame;
    frameId = delayFunction(function () {
      frameId = undefined;
      if (lastArgs) {
        callback.apply(void 0, (0, _toConsumableArray2.default)(lastArgs));
      }
    }, {
      timeout: 100
    });
  };
  return wrapperFn;
}
var scheduleDocumentRequest = exports.scheduleDocumentRequest = createThrottleSchedule(returnDocumentRequest);
function returnDocumentRequest(editorView, callback, transformer) {
  var _editorView$state;
  var _ref = (_editorView$state = editorView === null || editorView === void 0 ? void 0 : editorView.state) !== null && _editorView$state !== void 0 ? _editorView$state : {},
    doc = _ref.doc,
    schema = _ref.schema;
  if (!doc || !schema) {
    return undefined;
  }
  var json = toJSON(doc);
  if (typeof transformer === 'undefined') {
    callback(json);
  } else {
    var nodeSanitized = _model.Node.fromJSON(schema, json);
    callback(transformer.encode(nodeSanitized));
  }
}