function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
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) { _defineProperty(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; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import React, { useEffect } from 'react';
import { createRoot } from 'react-dom/client';
import LiveExample from "dumi/theme/slots/LiveExample";
import { safeEval } from "./utils";
function optionsOf(p) {
  try {
    var _meta$match;
    var meta = p.getAttribute('meta');
    var lang = p.getAttribute('lang');
    var matched = (_meta$match = meta.match(/\|\s*ob\s*({.*})/)) === null || _meta$match === void 0 ? void 0 : _meta$match[1];
    var obOptions = matched ? safeEval(matched) : {};
    return _objectSpread(_objectSpread({}, obOptions), {}, {
      lang: lang
    });
  } catch (e) {
    console.error(e);
    return {};
  }
}
function sourceOf(block) {
  var cloned = block.cloneNode(true);

  // 处理 Prism 语法高亮的 pre 元素
  var preElement = cloned.querySelector('pre.prism-code');
  if (preElement) {
    var lines = Array.from(preElement.children);
    var codeLines = lines.map(function (line) {
      var lineElement = line;
      return lineElement.innerText || lineElement.textContent || '';
    });
    var _code = codeLines.join('\n');
    return _code.replace(/\n\s*\n\s*\n/g, '\n\n');
  }
  var code = cloned.textContent || '';
  return code.replace(/\n\s*\n\s*\n/g, '\n\n');
}
function blockOf() {
  if ((typeof document === "undefined" ? "undefined" : _typeof(document)) !== undefined && document) {
    var blocks = Array.from(document.querySelectorAll('.ob-codeblock .dumi-default-source-code'));
    return blocks;
  }
  return [];
}
export function usePreview() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var select = arguments.length > 1 ? arguments[1] : undefined;
  var key = select + ',' + blockOf().length;
  useEffect(function () {
    var blocks = blockOf();

    // 过滤实际展示的 block
    var I = Array.from({
      length: blocks.length
    }, function (_, i) {
      return i;
    });
    var OI = I.filter(function (i) {
      var p = blocks[i].previousSibling;
      var options = optionsOf(p);
      var _options$only = options.only,
        only = _options$only === void 0 ? false : _options$only;
      return only === true;
    });
    var FI = OI.length === 0 ? I : OI;

    // 将 p 标签替换成渲染后结果
    var W = [];
    var P = [];
    var _iterator = _createForOfIteratorHelper(FI),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var i = _step.value;
        var block = blocks[i];
        var source = sourceOf(block);
        var p = block.previousSibling;

        // 渲染并且挂载代码运行结果
        var wrapper = document.createElement('div');
        var _options = optionsOf(p);
        var root = createRoot(wrapper);
        root.render( /*#__PURE__*/React.createElement(LiveExample, _extends({
          source: source
        }, _options)));
        var container = block.parentElement;
        container.replaceWith(wrapper);
        W[i] = wrapper;
        P[i] = p;
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
    return function () {
      // 复原
      var _iterator2 = _createForOfIteratorHelper(FI),
        _step2;
      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var i = _step2.value;
          var wrapper = W[i];
          var p = P[i];
          wrapper.replaceWith(p);
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }
    };
  }, [key]);
}