UNPKG

@vericus/slate-kit-highlight-text

Version:

plugin that provide a way to color/highlight a group of text on slate

492 lines (408 loc) 14.9 kB
(function (global, factory) { if (typeof define === "function" && define.amd) { define(["exports", "@vericus/slate-kit-utils-register-helpers", "immutable", "is-plain-obj", "slate", "tinycolor2"], factory); } else if (typeof exports !== "undefined") { factory(exports, require("@vericus/slate-kit-utils-register-helpers"), require("immutable"), require("is-plain-obj"), require("slate"), require("tinycolor2")); } else { var mod = { exports: {} }; factory(mod.exports, global.slateKitUtilsRegisterHelpers, global.immutable, global.isPlainObj, global.slate, global.tinycolor2); global.unknown = mod.exports; } })(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function (_exports, _slateKitUtilsRegisterHelpers, _immutable, _isPlainObj, _slate, _tinycolor) { _exports.__esModule = true; _exports.default = void 0; _slateKitUtilsRegisterHelpers = _interopRequireDefault(_slateKitUtilsRegisterHelpers); _isPlainObj = _interopRequireDefault(_isPlainObj); _tinycolor = _interopRequireDefault(_tinycolor); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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); return Constructor; } 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; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } 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 } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { 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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } 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 _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var defaultOptions = { name: undefined, marks: undefined, type: undefined, styles: undefined, data: undefined, defaultColor: undefined, alpha: 1, renderer: undefined, label: undefined }; var Options = /*#__PURE__*/function (_Record) { _inherits(Options, _Record); var _super = _createSuper(Options); function Options() { _classCallCheck(this, Options); return _super.apply(this, arguments); } _createClass(Options, null, [{ key: "create", value: function create() { var attrs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (Options.isOptions(attrs)) return attrs; if ((0, _isPlainObj.default)(attrs)) return Options.fromJSON(attrs); throw new Error("`Options.create` only accepts objects, strings or options"); } }, { key: "fromJSON", value: function fromJSON(object) { if (Options.isOptions(object)) return object; var name = object.name, type = object.type, data = object.data, styles = object.styles, defaultColor = object.defaultColor, _object$alpha = object.alpha, alpha = _object$alpha === void 0 ? 1 : _object$alpha, renderer = object.renderer; if (!type || !data || !styles || !defaultColor || !Array.isArray(styles)) { throw new Error("Highlight text require type, data and style option"); } if (alpha < 0 || alpha > 1) { throw new Error("Alpha value can only go from 0 to 1"); } return new Options({ marks: _defineProperty({}, type, type), type: type, data: data, styles: styles, alpha: alpha, defaultColor: defaultColor, name: name, renderer: renderer }); } }, { key: "isOptions", value: function isOptions(args) { if (args instanceof _immutable.Record) { var record = args; return ["marks", "type", "data", "styles", "defaultColor"].every(function (key) { return record.has(key); }); } return false; } }]); return Options; }((0, _immutable.Record)(defaultOptions, "highlight text option")); function getLeafNode(el) { if (el.hasAttributes()) { var parentNode = el.parentNode; if (el.getAttribute("data-slate-leaf") === "true") { return el; } if (parentNode) { return getLeafNode(parentNode); } } return null; } function getData(type, data, el) { var marks = (0, _immutable.Set)(); var node = getLeafNode(el) || el; while (node) { var _node = node, firstChild = _node.firstChild; if (node.hasAttributes && node.hasAttributes()) { var color = node.getAttribute("data-slate-kit-".concat(type.toLowerCase())); if (color) { marks = marks.add(new _slate.Mark({ type: type, data: _slate.Data.create(_defineProperty({}, data, color)) })); } } node = firstChild; } if (marks && marks.size > 0) { return { marks: marks.toArray() }; } return {}; } function createStyle(options) { var type = options.type, data = options.data; return { getData: function getData$1(_editor, el) { return getData(type, data, el); } }; } var defaultStyle = { textDecoration: "inherit", textDecorationColor: "inherit" }; function createProps(opts) { var type = opts.type, dataField = opts.data, styleFields = opts.styles, alpha = opts.alpha; return function (props) { if (!props.mark || props.mark.type !== type) return props; var attributes = props.attributes, data = props.mark.data; var _ref = attributes || { style: {} }, style = _ref.style; var color = (0, _tinycolor.default)(data.get(dataField)); style = _objectSpread2(_objectSpread2(_objectSpread2({}, defaultStyle), style), {}, { textDecoration: "inherit", decorationStyle: "initial" }, styleFields.reduce(function (acc, styleField) { return _objectSpread2(_objectSpread2({}, acc), {}, _defineProperty({}, styleField, color.setAlpha(alpha).toRgbString())); }, {})); return _objectSpread2(_objectSpread2({}, props), {}, { attributes: _objectSpread2(_objectSpread2({}, props.attributes), {}, _defineProperty({ style: style }, "data-slate-kit-".concat(type.toLowerCase()), color.setAlpha(alpha).toRgbString())) }); }; } function createCommands(opt) { var defaultColor = opt.defaultColor, data = opt.data, type = opt.type, name = opt.name; return _defineProperty({}, "change".concat(name, "Color"), function changeColor(editor, color) { var value = editor.value; var selection = value.selection; if (editor.hasMark(type)) { if ((0, _tinycolor.default)(color).toName() === defaultColor) { if (selection.isCollapsed) { editor.removeCollapsedMark(type); } else { editor.removeExpandedMark(type); } } else { var newMark = new _slate.Mark({ type: type, data: _slate.Data.create(_defineProperty({}, data, color)) }); if (selection.isCollapsed) { editor.removeCollapsedMark(type).addMark(newMark); } else { editor.removeExpandedMark(type).addMarkAtRange(selection, newMark); } } } else if ((0, _tinycolor.default)(color).toName() !== defaultColor) { var mark = new _slate.Mark({ type: type, data: _slate.Data.create(_defineProperty({}, data, color)) }); if (selection.isCollapsed) { editor.removeCollapsedMark(type).addMark(mark); } else { editor.removeExpandedMark(type).addMarkAtRange(selection, mark); } } editor.focus(); }); } function createUtils(opts) { var defaultColor = opts.defaultColor, data = opts.data, type = opts.type, name = opts.name; return _defineProperty({}, "current".concat(name, "Color"), function currentColor(editor) { var value = editor.value; if (value.selection && value.selection.isFocused && value.activeMarks) { var activeColorMarks = value.activeMarks.filter(function (mark) { return !!(mark && mark.type === type); }).reduce(function (colors, mark) { if (mark && mark.data.get(data)) { return [].concat(_toConsumableArray(colors), [mark.data.get(data)]); } return colors; }, []); var uniqueColorMarks = _toConsumableArray(Array.from(new Set(activeColorMarks))); if (uniqueColorMarks.length !== 0) { return uniqueColorMarks[0]; } } return defaultColor; }); } function createPlugin() { var pluginOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var options = Options.create(pluginOptions); var marks = options.marks, renderer = options.renderer; var commands = createCommands(options); var queries = createUtils(options); var _createStyle = createStyle(options), getData = _createStyle.getData; var props = createProps(options); var plugins = [(0, _slateKitUtilsRegisterHelpers.default)({ options: options, marks: marks, props: props, getData: getData }), { commands: commands, queries: queries }]; if (renderer) { var rendererPlugins = renderer(options); if (Array.isArray(rendererPlugins)) { plugins = [].concat(_toConsumableArray(plugins), _toConsumableArray(rendererPlugins)); } else { plugins = [].concat(_toConsumableArray(plugins), [rendererPlugins]); } } return plugins; } var _default = createPlugin; _exports.default = _default; });