UNPKG

drip-table

Version:

A tiny and powerful enterprise-class solution for building tables.

282 lines (207 loc) 17.9 kB
"use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; require("viewerjs/dist/viewer.css"); var _cheerio = _interopRequireDefault(require("cheerio")); var _react = _interopRequireDefault(require("react")); var _viewerjs = _interopRequireDefault(require("viewerjs")); var _highlight = _interopRequireDefault(require("../highlight")); var _hooks = require("../../../hooks"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } 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 _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var SAFE_TAG_NAME = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'br', 'button', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'main', 'map', 'mark', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'slot', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'template', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', 'webview', // svg 'a', 'animate', 'animateMotion', 'animateTransform', 'circle', 'clipPath', 'cursor', 'defs', 'desc', 'ellipse', 'feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence', 'filter', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'font-face', 'font', 'foreignObject', 'g', 'glyph', 'glyphRef', 'hkern', 'image', 'line', 'linearGradient', 'marker', 'mask', 'metadata', 'missing-glyph', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'set', 'stop', 'style', 'svg', 'switch', 'symbol', 'text', 'textPath', 'title', 'tref', 'tspan', 'use', 'view', 'vkern']; var DOM_EVENT_TYPE = ['onCopy', 'onCopyCapture', 'onCut', 'onCutCapture', 'onPaste', 'onPasteCapture', 'onCompositionEnd', 'onCompositionEndCapture', 'onCompositionStart', 'onCompositionStartCapture', 'onCompositionUpdate', 'onCompositionUpdateCapture', 'onFocus', 'onFocusCapture', 'onBlur', 'onBlurCapture', 'onChange', 'onChangeCapture', 'onBeforeInput', 'onBeforeInputCapture', 'onInput', 'onInputCapture', 'onReset', 'onResetCapture', 'onSubmit', 'onSubmitCapture', 'onInvalid', 'onInvalidCapture', 'onLoad', 'onLoadCapture', 'onError', 'onErrorCapture', 'onKeyDown', 'onKeyDownCapture', 'onKeyPress', 'onKeyPressCapture', 'onKeyUp', 'onKeyUpCapture', 'onAbort', 'onAbortCapture', 'onCanPlay', 'onCanPlayCapture', 'onCanPlayThrough', 'onCanPlayThroughCapture', 'onDurationChange', 'onDurationChangeCapture', 'onEmptied', 'onEmptiedCapture', 'onEncrypted', 'onEncryptedCapture', 'onEnded', 'onEndedCapture', 'onLoadedData', 'onLoadedDataCapture', 'onLoadedMetadata', 'onLoadedMetadataCapture', 'onLoadStart', 'onLoadStartCapture', 'onPause', 'onPauseCapture', 'onPlay', 'onPlayCapture', 'onPlaying', 'onPlayingCapture', 'onProgress', 'onProgressCapture', 'onRateChange', 'onRateChangeCapture', 'onSeeked', 'onSeekedCapture', 'onSeeking', 'onSeekingCapture', 'onStalled', 'onStalledCapture', 'onSuspend', 'onSuspendCapture', 'onTimeUpdate', 'onTimeUpdateCapture', 'onVolumeChange', 'onVolumeChangeCapture', 'onWaiting', 'onWaitingCapture', 'onAuxClick', 'onAuxClickCapture', 'onClick', 'onClickCapture', 'onContextMenu', 'onContextMenuCapture', 'onDoubleClick', 'onDoubleClickCapture', 'onDrag', 'onDragCapture', 'onDragEnd', 'onDragEndCapture', 'onDragEnter', 'onDragEnterCapture', 'onDragExit', 'onDragExitCapture', 'onDragLeave', 'onDragLeaveCapture', 'onDragOver', 'onDragOverCapture', 'onDragStart', 'onDragStartCapture', 'onDrop', 'onDropCapture', 'onMouseDown', 'onMouseDownCapture', 'onMouseEnter', 'onMouseLeave', 'onMouseMove', 'onMouseMoveCapture', 'onMouseOut', 'onMouseOutCapture', 'onMouseOver', 'onMouseOverCapture', 'onMouseUp', 'onMouseUpCapture', 'onSelect', 'onSelectCapture', 'onTouchCancel', 'onTouchCancelCapture', 'onTouchEnd', 'onTouchEndCapture', 'onTouchMove', 'onTouchMoveCapture', 'onTouchStart', 'onTouchStartCapture', 'onPointerDown', 'onPointerDownCapture', 'onPointerMove', 'onPointerMoveCapture', 'onPointerUp', 'onPointerUpCapture', 'onPointerCancel', 'onPointerCancelCapture', 'onPointerEnter', 'onPointerEnterCapture', 'onPointerLeave', 'onPointerLeaveCapture', 'onPointerOver', 'onPointerOverCapture', 'onPointerOut', 'onPointerOutCapture', 'onGotPointerCapture', 'onGotPointerCaptureCapture', 'onLostPointerCapture', 'onLostPointerCaptureCapture', 'onScroll', 'onScrollCapture', 'onWheel', 'onWheelCapture', 'onAnimationStart', 'onAnimationStartCapture', 'onAnimationEnd', 'onAnimationEndCapture', 'onAnimationIteration', 'onAnimationIterationCapture', 'onTransitionEnd', 'onTransitionEndCapture']; var HIDDEN_TAG_PROP_NAME = new Set(['key', 'class']); /** * 高亮文本 */ var RichText = /*#__PURE__*/function (_React$PureComponent) { _inherits(RichText, _React$PureComponent); var _super = _createSuper(RichText); function RichText() { var _this; _classCallCheck(this, RichText); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _super.call.apply(_super, [this].concat(args)); _defineProperty(_assertThisInitialized(_this), "viewer", void 0); _defineProperty(_assertThisInitialized(_this), "reducerRenderEl", function (prevVal, el, key) { var maxLength = prevVal.maxLength, singleLine = prevVal.singleLine, highlight = prevVal.highlight, tagNames = prevVal.tagNames, domEvents = prevVal.domEvents; if (el.type === 'text') { var _el$data; var text = 'data' in el ? (_el$data = el.data) !== null && _el$data !== void 0 ? _el$data : '' : ''; if (singleLine) { text = text.replace(/[\n\r]/g, '$nbsp'); } if (prevVal.maxLength >= 0) { text = text.slice(0, Math.max(0, prevVal.maxLength)); if (text.length > 0 && text.length === prevVal.maxLength) { text += '...'; } prevVal.maxLength = Math.max(prevVal.maxLength - text.length, 0); } prevVal.elements.push(highlight ? /*#__PURE__*/_react.default.createElement(_highlight.default, _objectSpread(_objectSpread({}, highlight), {}, { key: key, content: text })) : text); return prevVal; } if ('tagName' in el && tagNames.includes(el.tagName)) { var tagName = el.tagName; var _el$attribs = el.attribs, attribs = _el$attribs === void 0 ? {} : _el$attribs, children = el.children; var style = {}; if (attribs.style) { attribs.style.split(';').forEach(function (s) { var _s$split = s.split(':'), _s$split2 = _slicedToArray(_s$split, 2), k = _s$split2[0], v = _s$split2[1]; if (v) { style[k.trim().replace(/\x2D([a-z])/g, function (_, c) { return c.toUpperCase(); })] = v.trim(); } }); } if (tagName === 'img') { style.maxWidth = '100%'; } if (singleLine) { if (tagName === 'br') { prevVal.elements.push( /*#__PURE__*/_react.default.createElement("span", { key: key }, "\xA0")); return prevVal; } style.display = 'inline'; } var props = _objectSpread(_objectSpread(_objectSpread({}, Object.fromEntries(Object.entries(attribs).filter(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), k = _ref2[0], v = _ref2[1]; return !HIDDEN_TAG_PROP_NAME.has(k) && !(k.toLowerCase() in domEvents); }))), Object.fromEntries(Object.entries(attribs).map(function (_ref3) { var _ref4 = _slicedToArray(_ref3, 2), k = _ref4[0], v = _ref4[1]; return [domEvents[k.toLowerCase()], v]; }).filter(function (_ref5) { var _ref6 = _slicedToArray(_ref5, 2), k = _ref6[0], v = _ref6[1]; return k; }).map(function (_ref7) { var _ref8 = _slicedToArray(_ref7, 2), k = _ref8[0], v = _ref8[1]; return [k, _this.context.createEvaluator(v)]; }))), {}, { // static props 静态属性 key: key, style: style, className: attribs.class, src: attribs.src, width: attribs.width, height: attribs.height }); if (tagName === 'a') { props.href = attribs.href; props.target = attribs.target; } if (attribs.title) { props.title = attribs.title; } var content; if (children) { var res = children.reduce(_this.reducerRenderEl, { elements: [], maxLength: maxLength, singleLine: singleLine, highlight: highlight, tagNames: tagNames, domEvents: domEvents }); if (res.elements.length > 0) { content = res.elements; } prevVal.maxLength = res.maxLength; } prevVal.elements.push( /*#__PURE__*/_react.default.createElement(tagName, props, content)); return prevVal; } return prevVal; }); _defineProperty(_assertThisInitialized(_this), "onRef", function (el) { var _this$props$onRef, _this$props; (_this$props$onRef = (_this$props = _this.props).onRef) === null || _this$props$onRef === void 0 ? void 0 : _this$props$onRef.call(_this$props, el); if (!el) { return; } if (_this.viewer) { _this.viewer.destroy(); } _this.viewer = new _viewerjs.default(el); }); return _this; } _createClass(RichText, [{ key: "componentDidUpdate", value: function componentDidUpdate() { if (this.viewer) { this.viewer.update(); } } }, { key: "render", value: function render() { var _this$props$maxLength, _this$props$singleLin, _this$props$tagNames, _this$props$domEvents; var bodyEl = _cheerio.default.load(this.props.html)('body')[0]; return /*#__PURE__*/_react.default.createElement("div", { ref: this.onRef, className: this.props.className, style: this.props.style }, bodyEl && bodyEl.type === 'tag' ? bodyEl.children.reduce(this.reducerRenderEl, { elements: [], maxLength: (_this$props$maxLength = this.props.maxLength) !== null && _this$props$maxLength !== void 0 ? _this$props$maxLength : -1, singleLine: (_this$props$singleLin = this.props.singleLine) !== null && _this$props$singleLin !== void 0 ? _this$props$singleLin : false, highlight: this.props.highlight, tagNames: (_this$props$tagNames = this.props.tagNames) !== null && _this$props$tagNames !== void 0 ? _this$props$tagNames : SAFE_TAG_NAME, domEvents: Object.fromEntries(((_this$props$domEvents = this.props.domEvents) !== null && _this$props$domEvents !== void 0 ? _this$props$domEvents : DOM_EVENT_TYPE).map(function (name) { return [name.toLowerCase(), name]; })) }).elements : void 0); } }]); return RichText; }(_react.default.PureComponent); exports.default = RichText; _defineProperty(RichText, "contextType", _hooks.DripTableContext);