New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@sanity/block-tools

Package Overview
Dependencies
Maintainers
7
Versions
1293
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@sanity/block-tools - npm Package Compare versions

Comparing version 0.125.0-next.f7d2f004 to 0.125.0-rc.0

36

lib/constants.js

@@ -16,6 +16,6 @@ 'use strict';

var BLOCK_DEFAULT_STYLE = exports.BLOCK_DEFAULT_STYLE = 'normal';
const BLOCK_DEFAULT_STYLE = exports.BLOCK_DEFAULT_STYLE = 'normal';
// Slate block
var SLATE_DEFAULT_BLOCK = exports.SLATE_DEFAULT_BLOCK = Object.freeze({
const SLATE_DEFAULT_BLOCK = exports.SLATE_DEFAULT_BLOCK = Object.freeze({
kind: 'block',

@@ -28,3 +28,3 @@ type: 'contentBlock',

var DEFAULT_BLOCK = exports.DEFAULT_BLOCK = Object.freeze({
const DEFAULT_BLOCK = exports.DEFAULT_BLOCK = Object.freeze({
_type: 'block',

@@ -35,3 +35,3 @@ markDefs: [],

var DEFAULT_SPAN = exports.DEFAULT_SPAN = Object.freeze({
const DEFAULT_SPAN = exports.DEFAULT_SPAN = Object.freeze({
_type: 'span',

@@ -41,3 +41,3 @@ marks: []

var HTML_BLOCK_TAGS = exports.HTML_BLOCK_TAGS = {
const HTML_BLOCK_TAGS = exports.HTML_BLOCK_TAGS = {
p: DEFAULT_BLOCK,

@@ -47,7 +47,7 @@ blockquote: _extends({}, DEFAULT_BLOCK, { style: 'blockquote' })

var HTML_SPAN_TAGS = exports.HTML_SPAN_TAGS = {
const HTML_SPAN_TAGS = exports.HTML_SPAN_TAGS = {
span: { kind: 'text' }
};
var HTML_LIST_CONTAINER_TAGS = exports.HTML_LIST_CONTAINER_TAGS = {
const HTML_LIST_CONTAINER_TAGS = exports.HTML_LIST_CONTAINER_TAGS = {
ol: { kind: null },

@@ -57,3 +57,3 @@ ul: { kind: null }

var HTML_HEADER_TAGS = exports.HTML_HEADER_TAGS = {
const HTML_HEADER_TAGS = exports.HTML_HEADER_TAGS = {
h1: _extends({}, DEFAULT_BLOCK, { style: 'h1' }),

@@ -67,6 +67,6 @@ h2: _extends({}, DEFAULT_BLOCK, { style: 'h2' }),

var HTML_MISC_TAGS = exports.HTML_MISC_TAGS = {
const HTML_MISC_TAGS = exports.HTML_MISC_TAGS = {
br: _extends({}, DEFAULT_BLOCK, { style: 'normal' })
};
var HTML_DECORATOR_TAGS = exports.HTML_DECORATOR_TAGS = {
const HTML_DECORATOR_TAGS = exports.HTML_DECORATOR_TAGS = {

@@ -87,3 +87,3 @@ b: 'strong',

var HTML_LIST_ITEM_TAGS = exports.HTML_LIST_ITEM_TAGS = {
const HTML_LIST_ITEM_TAGS = exports.HTML_LIST_ITEM_TAGS = {
li: _extends({}, DEFAULT_BLOCK, {

@@ -96,14 +96,8 @@ style: 'normal',

var ELEMENT_MAP = exports.ELEMENT_MAP = _extends({}, HTML_BLOCK_TAGS, HTML_SPAN_TAGS, HTML_LIST_CONTAINER_TAGS, HTML_LIST_ITEM_TAGS, HTML_HEADER_TAGS, HTML_MISC_TAGS);
const ELEMENT_MAP = exports.ELEMENT_MAP = _extends({}, HTML_BLOCK_TAGS, HTML_SPAN_TAGS, HTML_LIST_CONTAINER_TAGS, HTML_LIST_ITEM_TAGS, HTML_HEADER_TAGS, HTML_MISC_TAGS);
var DEFAULT_SUPPORTED_STYLES = exports.DEFAULT_SUPPORTED_STYLES = (0, _uniq3.default)(Object.keys(ELEMENT_MAP).filter(function (tag) {
return ELEMENT_MAP[tag].style;
}).map(function (tag) {
return ELEMENT_MAP[tag].style;
}));
const DEFAULT_SUPPORTED_STYLES = exports.DEFAULT_SUPPORTED_STYLES = (0, _uniq3.default)(Object.keys(ELEMENT_MAP).filter(tag => ELEMENT_MAP[tag].style).map(tag => ELEMENT_MAP[tag].style));
var DEFAULT_SUPPORTED_DECORATORS = exports.DEFAULT_SUPPORTED_DECORATORS = (0, _uniq3.default)(Object.keys(HTML_DECORATOR_TAGS).map(function (tag) {
return HTML_DECORATOR_TAGS[tag];
}));
const DEFAULT_SUPPORTED_DECORATORS = exports.DEFAULT_SUPPORTED_DECORATORS = (0, _uniq3.default)(Object.keys(HTML_DECORATOR_TAGS).map(tag => HTML_DECORATOR_TAGS[tag]));
var DEFAULT_SUPPORTED_ANNOTATIONS = exports.DEFAULT_SUPPORTED_ANNOTATIONS = ['link'];
const DEFAULT_SUPPORTED_ANNOTATIONS = exports.DEFAULT_SUPPORTED_ANNOTATIONS = ['link'];

@@ -26,3 +26,3 @@ 'use strict';

function resolveTypeName(value) {
var jsType = (0, _resolveJsType2.default)(value);
const jsType = (0, _resolveJsType2.default)(value);
return jsType === 'object' && '_type' in value && value._type || jsType;

@@ -32,3 +32,3 @@ }

function hasKeys(obj) {
for (var key in obj) {
for (const key in obj) {
// eslint-disable-line guard-for-in

@@ -64,25 +64,19 @@ return true;

var text = span.text,
_span$marks = span.marks,
marks = _span$marks === undefined ? [] : _span$marks;
const text = span.text;
var _span$marks = span.marks;
const marks = _span$marks === undefined ? [] : _span$marks;
var decorators = marks.filter(function (mark) {
return !sanityBlock.markDefs.map(function (def) {
return def._key;
}).includes(mark);
const decorators = marks.filter(mark => {
return !sanityBlock.markDefs.map(def => def._key).includes(mark);
});
var annotationKeys = marks.filter(function (x) {
return decorators.indexOf(x) == -1;
});
var annotations = void 0;
const annotationKeys = marks.filter(x => decorators.indexOf(x) == -1);
let annotations;
if (annotationKeys.length) {
annotations = {};
annotationKeys.forEach(function (key) {
var annotation = sanityBlock.markDefs.find(function (def) {
return def._key === key;
});
annotationKeys.forEach(key => {
const annotation = sanityBlock.markDefs.find(def => def._key === key);
annotations[annotation._type] = annotation;
});
}
var range = {
const range = {
kind: 'range',

@@ -102,4 +96,4 @@ text: text,

type: 'span',
data: { annotations: annotations },
nodes: [{ kind: 'text', key: span._key + '0', ranges: [range] }]
data: { annotations },
nodes: [{ kind: 'text', ranges: [range] }]
};

@@ -111,8 +105,8 @@ }

// eslint-disable-next-line no-unused-vars
var children = sanityBlock.children,
_type = sanityBlock._type,
markDefs = sanityBlock.markDefs,
rest = _objectWithoutProperties(sanityBlock, ['children', '_type', 'markDefs']);
const children = sanityBlock.children,
_type = sanityBlock._type,
markDefs = sanityBlock.markDefs,
rest = _objectWithoutProperties(sanityBlock, ['children', '_type', 'markDefs']);
var restData = hasKeys(rest) ? { data: _extends({ _type: _type }, rest) } : {};
const restData = hasKeys(rest) ? { data: _extends({ _type }, rest) } : {};

@@ -129,5 +123,3 @@ if (!sanityBlock._key) {

}, restData, {
nodes: children.map(function (child) {
return sanitySpanToRawSlateBlockNode(child, sanityBlock);
})
nodes: children.map(child => sanitySpanToRawSlateBlockNode(child, sanityBlock))
});

@@ -152,7 +144,5 @@ }

function sanityBlockItemToRawNode(blockItem, type) {
var blockItemType = resolveTypeName(blockItem);
const blockItemType = resolveTypeName(blockItem);
var memberType = type.of.find(function (ofType) {
return ofType.name === blockItemType;
});
const memberType = type.of.find(ofType => ofType.name === blockItemType);

@@ -164,9 +154,7 @@ return blockItemType === 'block' ? sanityBlockToRawNode(blockItem, memberType) : sanityBlockItemToRaw(blockItem, memberType);

return blockArray.filter(Boolean) // this is a temporary guard against null values, @todo: remove
.map(function (item) {
return sanityBlockItemToRawNode(item, type);
});
.map(item => sanityBlockItemToRawNode(item, type));
}
function blocksToSlateState(array, type) {
var defaultNodes = [_extends({}, _constants.SLATE_DEFAULT_BLOCK, { nodes: [{ kind: 'text', text: '' }] })];
const defaultNodes = [_extends({}, _constants.SLATE_DEFAULT_BLOCK, { nodes: [{ kind: 'text', text: '' }] })];
return {

@@ -173,0 +161,0 @@ kind: 'state',

@@ -27,10 +27,8 @@ 'use strict';

if (node.kind === 'text') {
return node.ranges.map(function (range) {
return node.ranges.map(range => {
return {
_type: 'span',
_key: '' + sanityBlock._key + spanIndex(),
_key: `${sanityBlock._key}${spanIndex()}`,
text: range.text,
marks: range.marks.map(function (mark) {
return mark.type;
})
marks: range.marks.map(mark => mark.type)
};

@@ -40,8 +38,8 @@ });

if (node.kind === 'inline') {
var nodes = node.nodes,
data = node.data;
const nodes = node.nodes,
data = node.data;
return (0, _flatten3.default)(nodes.map(function (nodesNode) {
return (0, _flatten3.default)(nodes.map(nodesNode => {
if (nodesNode.kind !== 'text') {
throw new Error('Unexpected non-text child node for inline text: ' + nodesNode.kind);
throw new Error(`Unexpected non-text child node for inline text: ${nodesNode.kind}`);
}

@@ -51,8 +49,8 @@ if (node.type !== 'span') {

}
var annotations = data.annotations;
var annotationKeys = [];
const annotations = data.annotations;
const annotationKeys = [];
if (annotations) {
Object.keys(annotations).forEach(function (name) {
var annotation = annotations[name];
var annotationKey = annotation._key;
Object.keys(annotations).forEach(name => {
const annotation = annotations[name];
const annotationKey = annotation._key;
if (annotation) {

@@ -64,15 +62,11 @@ sanityBlock.markDefs.push(annotation);

}
return nodesNode.ranges.map(function (range) {
return {
_type: 'span',
_key: '' + sanityBlock._key + spanIndex(),
text: range.text,
marks: range.marks.map(function (mark) {
return mark.type;
}).concat(annotationKeys)
};
});
return nodesNode.ranges.map(range => ({
_type: 'span',
_key: `${sanityBlock._key}${spanIndex()}`,
text: range.text,
marks: range.marks.map(mark => mark.type).concat(annotationKeys)
}));
}));
}
throw new Error('Unsupported kind ' + node.kind);
throw new Error(`Unsupported kind ${node.kind}`);
}

@@ -82,3 +76,3 @@

if (block.type === 'contentBlock') {
var sanityBlock = _extends({}, block.data, {
const sanityBlock = _extends({}, block.data, {
_type: 'block',

@@ -88,7 +82,7 @@ _key: block.key || block.data._key || (0, _randomKey2.default)(12),

});
var index = 0;
var spanIndex = function spanIndex() {
let index = 0;
const spanIndex = () => {
return index++;
};
sanityBlock.children = (0, _flatten3.default)(block.nodes.map(function (node) {
sanityBlock.children = (0, _flatten3.default)(block.nodes.map(node => {
return toSanitySpan(node, sanityBlock, spanIndex);

@@ -108,7 +102,7 @@ }));

}
var firstBlock = blocks[0];
const firstBlock = blocks[0];
if (firstBlock._type !== 'block') {
return false;
}
var children = firstBlock.children;
const children = firstBlock.children;
if (children.length === 0) {

@@ -120,3 +114,3 @@ return true;

}
var firstChild = children[0];
const firstChild = children[0];
if (firstChild._type !== 'span') {

@@ -129,8 +123,8 @@ return false;

function slateStateToBlocks(json) {
var nodes = (0, _get3.default)(json, 'document.nodes');
const nodes = (0, _get3.default)(json, 'document.nodes');
if (!nodes || nodes.length === 0) {
return undefined;
}
var blocks = nodes.map(toSanityBlock).filter(Boolean);
const blocks = nodes.map(toSanityBlock).filter(Boolean);
return isEmpty(blocks) ? undefined : blocks;
}

@@ -42,10 +42,10 @@ 'use strict';

function createRuleOptions(blockContentType) {
var options = (0, _blockContentTypeToOptions2.default)(blockContentType);
var enabledBlockStyles = options.enabledBlockStyles || _constants.DEFAULT_SUPPORTED_STYLES;
var enabledSpanDecorators = options.enabledSpanDecorators || _constants.DEFAULT_SUPPORTED_DECORATORS;
var enabledBlockAnnotations = options.enabledBlockAnnotations || _constants.DEFAULT_SUPPORTED_ANNOTATIONS;
const options = (0, _blockContentTypeToOptions2.default)(blockContentType);
const enabledBlockStyles = options.enabledBlockStyles || _constants.DEFAULT_SUPPORTED_STYLES;
const enabledSpanDecorators = options.enabledSpanDecorators || _constants.DEFAULT_SUPPORTED_DECORATORS;
const enabledBlockAnnotations = options.enabledBlockAnnotations || _constants.DEFAULT_SUPPORTED_ANNOTATIONS;
return {
enabledBlockStyles: enabledBlockStyles,
enabledSpanDecorators: enabledSpanDecorators,
enabledBlockAnnotations: enabledBlockAnnotations
enabledBlockStyles,
enabledSpanDecorators,
enabledBlockAnnotations
};

@@ -70,7 +70,7 @@ }

function preprocess(html, parseHtml, evaluate) {
var compactHtml = html.trim() // Trim whitespace
const compactHtml = html.trim() // Trim whitespace
.replace(/\s\s+/g, ' ') // Remove multiple whitespace
.replace(/[\r\n]/g, ' '); // Remove newlines / carriage returns
var doc = parseHtml(compactHtml);
_preprocessors2.default.forEach(function (processor) {
const doc = parseHtml(compactHtml);
_preprocessors2.default.forEach(processor => {
processor(html, doc, evaluate);

@@ -92,3 +92,3 @@ });

}
return function (html) {
return html => {
return new DOMParser().parseFromString(html, 'text/html');

@@ -99,7 +99,7 @@ };

function flattenNestedBlocks(blocks) {
var depth = 0;
var flattened = [];
var traverse = function traverse(_nodes) {
var toRemove = [];
_nodes.forEach(function (node, i) {
let depth = 0;
const flattened = [];
const traverse = _nodes => {
const toRemove = [];
_nodes.forEach((node, i) => {
if (depth === 0) {

@@ -117,3 +117,3 @@ flattened.push(node);

});
toRemove.forEach(function (node) {
toRemove.forEach(node => {
_nodes.splice(_nodes.indexOf(node), 1);

@@ -128,17 +128,17 @@ });

function trimWhitespace(blocks) {
blocks.forEach(function (block) {
var nextSpan = function nextSpan(child, index) {
var next = block.children[index + 1];
blocks.forEach(block => {
const nextSpan = (child, index) => {
const next = block.children[index + 1];
return next && next._type === 'span' ? next : null;
};
var prevSpan = function prevSpan(child, index) {
var prev = block.children[index - 1];
const prevSpan = (child, index) => {
const prev = block.children[index - 1];
return prev && prev._type === 'span' ? prev : null;
};
block.children.forEach(function (child, index) {
block.children.forEach((child, index) => {
if (child._type !== 'span') {
return;
}
var nextChild = nextSpan(child, index);
var prevChild = prevSpan(child, index);
const nextChild = nextSpan(child, index);
const prevChild = prevSpan(child, index);
if (index === 0) {

@@ -165,3 +165,3 @@ child.text = child.text.replace(/^[^\S\n]+/g, '');

function ensureRootIsBlocks(blocks) {
return blocks.reduce(function (memo, node, i, original) {
return blocks.reduce((memo, node, i, original) => {

@@ -174,8 +174,8 @@ if (node._type === 'block') {

if (i > 0 && original[i - 1]._type !== 'block') {
var _block = memo[memo.length - 1];
_block.children.push(node);
const block = memo[memo.length - 1];
block.children.push(node);
return memo;
}
var block = _extends({}, _constants.DEFAULT_BLOCK, {
const block = _extends({}, _constants.DEFAULT_BLOCK, {
children: [node]

@@ -182,0 +182,0 @@ });

@@ -7,4 +7,2 @@ 'use strict';

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _helpers = require('./helpers');

@@ -22,6 +20,2 @@

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**

@@ -31,3 +25,3 @@ * A internal variable to keep track of annotation mark definitions within the 'run' of a block

*/
var _markDefsWithinBlock = [];
let _markDefsWithinBlock = [];

@@ -39,84 +33,79 @@ /**

var HtmlDeserializer =
class HtmlDeserializer {
/**
* Create a new serializer respecting a Sanity block content type's schema
*
* @param {Object} options
* @property {Object} blockContentType
* A compiled version of the block content schema type
* @property {Array} rules
* Optional rules working on the HTML (will be ruled first)
* @property {Function} parseHtml
* API compatible model as returned from DOMParser for using server side.
*/
/**
* Create a new serializer respecting a Sanity block content type's schema
*
* @param {Object} options
* @property {Object} blockContentType
* A compiled version of the block content schema type
* @property {Array} rules
* Optional rules working on the HTML (will be ruled first)
* @property {Function} parseHtml
* API compatible model as returned from DOMParser for using server side.
*/
function HtmlDeserializer() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
constructor(options = {}) {
_initialiseProps.call(this);
_classCallCheck(this, HtmlDeserializer);
var _options$rules = options.rules;
const rules = _options$rules === undefined ? [] : _options$rules;
_initialiseProps.call(this);
const blockContentType = options.blockContentType;
const standardRules = (0, _rules2.default)(blockContentType, (0, _helpers.createRuleOptions)(blockContentType));
this.rules = [...rules, ...standardRules];
const parseHtml = options.parseHtml || (0, _helpers.defaultParseHtml)();
this.parseHtml = html => {
const doc = (0, _helpers.preprocess)(html, parseHtml);
return doc.body;
};
}
var _options$rules = options.rules,
rules = _options$rules === undefined ? [] : _options$rules;
/**
* Deserialize HTML.
*
* @param {String} html
* @return {Array}
*/
var blockContentType = options.blockContentType;
var standardRules = (0, _rules2.default)(blockContentType, (0, _helpers.createRuleOptions)(blockContentType));
this.rules = [].concat(_toConsumableArray(rules), _toConsumableArray(standardRules));
var parseHtml = options.parseHtml || (0, _helpers.defaultParseHtml)();
this.parseHtml = function (html) {
var doc = (0, _helpers.preprocess)(html, parseHtml);
return doc.body;
};
}
/**
* Deserialize an array of DOM elements.
*
* @param {Array} elements
* @return {Array}
*/
/**
* Deserialize HTML.
*
* @param {String} html
* @return {Array}
*/
/**
* Deserialize a DOM element.
*
* @param {Object} element
* @return {Any}
*/
/**
* Deserialize an array of DOM elements.
*
* @param {Array} elements
* @return {Array}
*/
/**
* Deserialize a `__decorator` type
* (an internal made up type to process decorators exclusively)
*
* @param {Object} decorator
* @return {Array}
*/
/**
* Deserialize a DOM element.
*
* @param {Object} element
* @return {Any}
*/
/**
* Deserialize a `__annotation` object.
* (an internal made up type to process annotations exclusively)
*
* @param {Object} annotation
* @return {Array}
*/
/**
* Deserialize a `__decorator` type
* (an internal made up type to process decorators exclusively)
*
* @param {Object} decorator
* @return {Array}
*/
}
exports.default = HtmlDeserializer;
/**
* Deserialize a `__annotation` object.
* (an internal made up type to process annotations exclusively)
*
* @param {Object} annotation
* @return {Array}
*/
;
var _initialiseProps = function _initialiseProps() {
var _this = this;
this.deserialize = html => {
const parseHtml = this.parseHtml;
this.deserialize = function (html) {
var parseHtml = _this.parseHtml;
var fragment = parseHtml(html);
var children = Array.from(fragment.childNodes);
var blocks = _this.deserializeElements(children);
const fragment = parseHtml(html);
const children = Array.from(fragment.childNodes);
let blocks = this.deserializeElements(children);
// Ensure that all top-level objects are wrapped into a block

@@ -128,8 +117,6 @@ blocks = (0, _helpers.ensureRootIsBlocks)(blocks);

this.deserializeElements = function () {
var elements = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var nodes = [];
elements.forEach(function (element, index) {
var node = _this.deserializeElement(element);
this.deserializeElements = (elements = []) => {
let nodes = [];
elements.forEach((element, index) => {
const node = this.deserializeElement(element);
switch ((0, _resolveJsType2.default)(node)) {

@@ -143,3 +130,3 @@ case 'array':

default:
throw new Error('Don\'t know what to do with: ' + JSON.stringify(node));
throw new Error(`Don't know what to do with: ${JSON.stringify(node)}`);
}

@@ -150,6 +137,6 @@ });

this.deserializeElement = function (element) {
this.deserializeElement = element => {
// eslint-disable-line complexity
var node = void 0;
let node;
if (!element.tagName) {

@@ -159,4 +146,4 @@ element.tagName = '';

var next = function next(elements) {
var _elements = elements;
const next = elements => {
let _elements = elements;
if (Object.prototype.toString.call(_elements) == '[object NodeList]') {

@@ -168,5 +155,5 @@ _elements = Array.from(_elements);

case 'array':
return _this.deserializeElements(_elements);
return this.deserializeElements(_elements);
case 'object':
return _this.deserializeElement(_elements);
return this.deserializeElement(_elements);
case 'null':

@@ -176,28 +163,25 @@ case 'undefined':

default:
throw new Error('The `next` argument was called with invalid children: "' + _elements + '".');
throw new Error(`The \`next\` argument was called with invalid children: "${_elements}".`);
}
};
var _loop = function _loop(i) {
var rule = _this.rules[i];
for (let i = 0; i < this.rules.length; i++) {
const rule = this.rules[i];
if (!rule.deserialize) {
return 'continue';
continue;
}
var ret = rule.deserialize(element, next);
var type = (0, _resolveJsType2.default)(ret);
const ret = rule.deserialize(element, next);
const type = (0, _resolveJsType2.default)(ret);
if (type != 'array' && type != 'object' && type != 'null' && type != 'undefined') {
throw new Error('A rule returned an invalid deserialized representation: "' + node + '".');
throw new Error(`A rule returned an invalid deserialized representation: "${node}".`);
}
if (ret === undefined) {
return 'continue';
continue;
} else if (ret === null) {
return {
v: null
};
return null;
} else if (ret._type === '__decorator') {
node = _this.deserializeDecorator(ret);
node = this.deserializeDecorator(ret);
} else if (ret._type === '__annotation') {
node = _this.deserializeAnnotation(ret);
node = this.deserializeAnnotation(ret);
} else if (ret._type === 'block' && _markDefsWithinBlock.length) {

@@ -212,3 +196,3 @@ ret.markDefs = _markDefsWithinBlock;

if (ret && ret._type === 'block' && ret.listItem) {
var parent = element.parentNode.parentNode;
let parent = element.parentNode.parentNode;
while ((0, _helpers.tagName)(parent) === 'li') {

@@ -221,3 +205,3 @@ parent = parent.parentNode.parentNode;

if (ret && ret._type === 'block' && ret.style === 'blockquote') {
ret.children.forEach(function (child, index) {
ret.children.forEach((child, index) => {
if (child._type === 'span' && child.text === '\r') {

@@ -231,29 +215,13 @@ child.text = '\n\n';

}
return 'break';
};
_loop2: for (var i = 0; i < _this.rules.length; i++) {
var _ret = _loop(i);
switch (_ret) {
case 'continue':
continue;
case 'break':
break _loop2;
default:
if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
}
break;
}
return node || next(element.childNodes);
};
this.deserializeDecorator = function (decorator) {
var name = decorator.name;
this.deserializeDecorator = decorator => {
const name = decorator.name;
var applyDecorator = function applyDecorator(node) {
const applyDecorator = node => {
if (node._type === '__decorator') {
return _this.deserializeDecorator(node);
return this.deserializeDecorator(node);
} else if (node._type === 'span') {

@@ -270,4 +238,4 @@ node.marks = node.marks || [];

};
return decorator.children.reduce(function (children, node) {
var ret = applyDecorator(node);
return decorator.children.reduce((children, node) => {
const ret = applyDecorator(node);
if (Array.isArray(ret)) {

@@ -281,9 +249,9 @@ return children.concat(ret);

this.deserializeAnnotation = function (annotation) {
var markDef = annotation.markDef;
this.deserializeAnnotation = annotation => {
const markDef = annotation.markDef;
_markDefsWithinBlock.push(markDef);
var applyAnnotation = function applyAnnotation(node) {
const applyAnnotation = node => {
if (node._type === '__annotation') {
return _this.deserializeAnnotation(node);
return this.deserializeAnnotation(node);
} else if (node._type === 'span') {

@@ -300,4 +268,4 @@ node.marks = node.marks || [];

};
return annotation.children.reduce(function (children, node) {
var ret = applyAnnotation(node);
return annotation.children.reduce((children, node) => {
const ret = applyAnnotation(node);
if (Array.isArray(ret)) {

@@ -310,4 +278,2 @@ return children.concat(ret);

};
};
exports.default = HtmlDeserializer;
};

@@ -9,10 +9,10 @@ 'use strict';

exports.default = function (html, doc) {
exports.default = (html, doc) => {
// Remove this cruft from the document
var unwantedWordDocumentPaths = ['/html/text()', '/html/head/text()', '/html/body/text()', '//comment()', '//style', '//xml', '//script', '//meta', '//link'];
const unwantedWordDocumentPaths = ['/html/text()', '/html/head/text()', '/html/body/text()', '//comment()', '//style', '//xml', '//script', '//meta', '//link'];
var unwantedNodes = doc.evaluate(unwantedWordDocumentPaths.join('|'), doc, null, _index._XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i = unwantedNodes.snapshotLength - 1; i >= 0; i--) {
var unwanted = unwantedNodes.snapshotItem(i);
const unwantedNodes = doc.evaluate(unwantedWordDocumentPaths.join('|'), doc, null, _index._XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (let i = unwantedNodes.snapshotLength - 1; i >= 0; i--) {
const unwanted = unwantedNodes.snapshotItem(i);
unwanted.parentNode.removeChild(unwanted);

@@ -19,0 +19,0 @@ }

@@ -19,3 +19,3 @@ 'use strict';

// We need this here if run server side
var _XPathResult = exports._XPathResult = {
const _XPathResult = exports._XPathResult = {
ANY_TYPE: 0,

@@ -22,0 +22,0 @@ NUMBER_TYPE: 1,

@@ -14,3 +14,3 @@ "use strict";

exports.default = function (html, doc) {
exports.default = (html, doc) => {
if (!isWordHtml(html)) {

@@ -21,9 +21,9 @@ return doc;

// xPaths for elements that will be removed from the document
var unwantedPaths = ["//*[name() = 'o:p']"];
const unwantedPaths = ["//*[name() = 'o:p']"];
// xPaths for elements that needs to be remapped into other tags
var mappedPaths = ["//p[@class='MsoTocHeading']", "//p[@class='MsoTitle']", "//p[@class='MsoToaHeading']", "//p[@class='MsoSubtitle']", "//span[@class='MsoSubtleEmphasis']", "//span[@class='MsoIntenseEmphasis']"];
const mappedPaths = ["//p[@class='MsoTocHeading']", "//p[@class='MsoTitle']", "//p[@class='MsoToaHeading']", "//p[@class='MsoSubtitle']", "//span[@class='MsoSubtleEmphasis']", "//span[@class='MsoIntenseEmphasis']"];
// Which HTML element(s) to map the elements matching mappedPaths into
var elementMap = {
const elementMap = {
MsoTocHeading: ['h3'],

@@ -37,3 +37,3 @@ MsoTitle: ['h1'],

// Remove cruft
};var unwantedNodes = doc.evaluate(unwantedPaths.join('|'), doc, function (prefix) {
};const unwantedNodes = doc.evaluate(unwantedPaths.join('|'), doc, prefix => {
if (prefix === 'o') {

@@ -44,4 +44,4 @@ return 'urn:schemas-microsoft-com:office:office';

}, _index._XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i = unwantedNodes.snapshotLength - 1; i >= 0; i--) {
var unwanted = unwantedNodes.snapshotItem(i);
for (let i = unwantedNodes.snapshotLength - 1; i >= 0; i--) {
const unwanted = unwantedNodes.snapshotItem(i);
unwanted.parentNode.removeChild(unwanted);

@@ -51,12 +51,11 @@ }

// Transform mapped elements into what they should be mapped to
var mappedElements = doc.evaluate(mappedPaths.join('|'), doc, null, _index._XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
var _loop = function _loop(_i) {
var mappedElm = mappedElements.snapshotItem(_i);
var tags = elementMap[mappedElm.className];
var text = new Text(mappedElm.textContent);
var parentElement = document.createElement(tags[0]);
var parent = parentElement;
var child = parentElement;
tags.slice(1).forEach(function (tag) {
const mappedElements = doc.evaluate(mappedPaths.join('|'), doc, null, _index._XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (let i = mappedElements.snapshotLength - 1; i >= 0; i--) {
const mappedElm = mappedElements.snapshotItem(i);
const tags = elementMap[mappedElm.className];
const text = new Text(mappedElm.textContent);
const parentElement = document.createElement(tags[0]);
let parent = parentElement;
let child = parentElement;
tags.slice(1).forEach(tag => {
child = document.createElement(tag);

@@ -68,6 +67,2 @@ parent.appendChild(child);

mappedElm.parentNode.replaceChild(parentElement, mappedElm);
};
for (var _i = mappedElements.snapshotLength - 1; _i >= 0; _i--) {
_loop(_i);
}

@@ -74,0 +69,0 @@

@@ -23,3 +23,3 @@ 'use strict';

function resolveListItem(listNodeTagName) {
var listStyle = void 0;
let listStyle;
switch (listNodeTagName) {

@@ -38,5 +38,3 @@ case 'ul':

function createDefaultRules(blockContentType) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
function createDefaultRules(blockContentType, options = {}) {
return [

@@ -46,4 +44,4 @@

{
deserialize: function deserialize(el) {
var isValidText = el.textContent !== ' ' && (0, _helpers.tagName)(el.parentNode) !== 'body';
deserialize(el) {
const isValidText = el.textContent !== ' ' && (0, _helpers.tagName)(el.parentNode) !== 'body';
if (el.nodeName === '#text' && isValidText) {

@@ -61,14 +59,14 @@ return _extends({}, _constants.DEFAULT_SPAN, {

{
deserialize: function deserialize(el, next) {
deserialize(el, next) {
if ((0, _helpers.tagName)(el) !== 'blockquote') {
return undefined;
}
var blocks = _extends({}, _constants.HTML_BLOCK_TAGS, _constants.HTML_HEADER_TAGS);
const blocks = _extends({}, _constants.HTML_BLOCK_TAGS, _constants.HTML_HEADER_TAGS);
delete blocks.blockquote;
var children = [];
el.childNodes.forEach(function (node, index) {
const children = [];
el.childNodes.forEach((node, index) => {
if (node.nodeType === 1 && Object.keys(blocks).includes(node.localName.toLowerCase())) {
var span = el.ownerDocument.createElement('span');
const span = el.ownerDocument.createElement('span');
span.appendChild(el.ownerDocument.createTextNode('\r'));
node.childNodes.forEach(function (cn) {
node.childNodes.forEach(cn => {
span.appendChild(cn.cloneNode(true));

@@ -96,5 +94,5 @@ });

{
deserialize: function deserialize(el, next) {
var blocks = _extends({}, _constants.HTML_BLOCK_TAGS, _constants.HTML_HEADER_TAGS);
var block = blocks[(0, _helpers.tagName)(el)];
deserialize(el, next) {
const blocks = _extends({}, _constants.HTML_BLOCK_TAGS, _constants.HTML_HEADER_TAGS);
let block = blocks[(0, _helpers.tagName)(el)];
if (!block) {

@@ -119,4 +117,4 @@ return undefined;

{
deserialize: function deserialize(el, next) {
var span = _constants.HTML_SPAN_TAGS[(0, _helpers.tagName)(el)];
deserialize(el, next) {
const span = _constants.HTML_SPAN_TAGS[(0, _helpers.tagName)(el)];
if (!span) {

@@ -131,4 +129,4 @@ return undefined;

{
deserialize: function deserialize(el, next) {
var listContainer = _constants.HTML_LIST_CONTAINER_TAGS[(0, _helpers.tagName)(el)];
deserialize(el, next) {
const listContainer = _constants.HTML_LIST_CONTAINER_TAGS[(0, _helpers.tagName)(el)];
if (!listContainer) {

@@ -143,3 +141,3 @@ return undefined;

{
deserialize: function deserialize(el, next) {
deserialize(el, next) {
if ((0, _helpers.tagName)(el) === 'br') {

@@ -156,4 +154,4 @@ return _extends({}, _constants.DEFAULT_SPAN, {

{
deserialize: function deserialize(el, next) {
var listItem = _constants.HTML_LIST_ITEM_TAGS[(0, _helpers.tagName)(el)];
deserialize(el, next) {
const listItem = _constants.HTML_LIST_ITEM_TAGS[(0, _helpers.tagName)(el)];
if (!listItem || !el.parentNode || !_constants.HTML_LIST_CONTAINER_TAGS[(0, _helpers.tagName)(el.parentNode)]) {

@@ -171,4 +169,4 @@ return undefined;

{
deserialize: function deserialize(el, next) {
var decorator = _constants.HTML_DECORATOR_TAGS[(0, _helpers.tagName)(el)];
deserialize(el, next) {
const decorator = _constants.HTML_DECORATOR_TAGS[(0, _helpers.tagName)(el)];
if (!decorator || !options.enabledSpanDecorators.includes(decorator)) {

@@ -188,12 +186,12 @@ return undefined;

{
deserialize: function deserialize(el, next) {
deserialize(el, next) {
if ((0, _helpers.tagName)(el) != 'a') {
return undefined;
}
var linkEnabled = options.enabledBlockAnnotations.includes('link');
var href = el.getAttribute('href');
const linkEnabled = options.enabledBlockAnnotations.includes('link');
const href = el.getAttribute('href');
if (!href) {
return next(el.childNodes);
}
var markDef = void 0;
let markDef;
if (linkEnabled) {

@@ -209,3 +207,3 @@ markDef = {

markDef: markDef,
children: linkEnabled ? next(el.childNodes) : el.appendChild(new Text(' (' + href + ')') // TODO: make server side compatible
children: linkEnabled ? next(el.childNodes) : el.appendChild(new Text(` (${href})`) // TODO: make server side compatible
) && next(el.childNodes)

@@ -212,0 +210,0 @@ };

@@ -22,8 +22,4 @@ 'use strict';

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function createRules(blockContentType) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return [].concat(_toConsumableArray((0, _misc2.default)(blockContentType, options)), _toConsumableArray((0, _word2.default)(blockContentType, options)), _toConsumableArray((0, _default2.default)(blockContentType, options)));
function createRules(blockContentType, options = {}) {
return [...(0, _misc2.default)(blockContentType, options), ...(0, _word2.default)(blockContentType, options), ...(0, _default2.default)(blockContentType, options)];
}

@@ -11,3 +11,3 @@ 'use strict';

}
var id = el.getAttribute('id');
const id = el.getAttribute('id');
return id && id.match(/^docs-internal-guid-/);

@@ -21,3 +21,3 @@ }

{
deserialize: function deserialize(el, next) {
deserialize(el, next) {
if (isPastedFromGoogleDocs(el)) {

@@ -24,0 +24,0 @@ return next(el.childNodes);

@@ -16,3 +16,3 @@ 'use strict';

function getListItemStyle(el) {
var style = void 0;
let style;
if (style = el.getAttribute('style')) {

@@ -28,9 +28,9 @@ if (!style.match(/lfo\d+/)) {

function getListItemLevel(el) {
var style = void 0;
let style;
if (style = el.getAttribute('style')) {
var levelMatch = style.match(/level\d+/);
const levelMatch = style.match(/level\d+/);
if (!levelMatch) {
return undefined;
}
var level = levelMatch[0].match(/\d/)[0];
const level = levelMatch[0].match(/\d/)[0];
return parseInt(level, 10) || 1;

@@ -48,8 +48,6 @@ }

function createWordRules(blockContentType) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
function createWordRules(blockContentType, options = {}) {
return [{
deserialize: function deserialize(el, next) {
deserialize(el, next) {
if ((0, _helpers.tagName)(el) === 'p' && isWordListElement(el)) {

@@ -56,0 +54,0 @@ return _extends({}, _constants.DEFAULT_BLOCK, {

@@ -11,5 +11,5 @@ 'use strict';

var _blocksToSlateState2 = require('./converters/blocksToSlateState');
var _blocksToSlateState = require('./converters/blocksToSlateState');
var _blocksToSlateState3 = _interopRequireDefault(_blocksToSlateState2);
var _blocksToSlateState2 = _interopRequireDefault(_blocksToSlateState);

@@ -20,5 +20,5 @@ var _HtmlDeserializer = require('./HtmlDeserializer');

var _slateStateToBlocks2 = require('./converters/slateStateToBlocks');
var _slateStateToBlocks = require('./converters/slateStateToBlocks');
var _slateStateToBlocks3 = _interopRequireDefault(_slateStateToBlocks2);
var _slateStateToBlocks2 = _interopRequireDefault(_slateStateToBlocks);

@@ -50,10 +50,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

*/
htmlToBlocks: function htmlToBlocks(html) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var deserializer = new _HtmlDeserializer2.default(options);
htmlToBlocks(html, options = {}) {
const deserializer = new _HtmlDeserializer2.default(options);
return deserializer.deserialize(html);
},
/**

@@ -66,7 +63,6 @@ * Convert a serialized Slate state to blocks

*/
slateStateToBlocks: function slateStateToBlocks(slateJson, blockContentType) {
return (0, _slateStateToBlocks3.default)(slateJson, blockContentType);
slateStateToBlocks(slateJson, blockContentType) {
return (0, _slateStateToBlocks2.default)(slateJson, blockContentType);
},
/**

@@ -80,7 +76,6 @@ * Convert blocks to a serialized Slate state

blocksToSlateState: function blocksToSlateState(blocks, blockContentType) {
return (0, _blocksToSlateState3.default)(blocks, blockContentType);
blocksToSlateState(blocks, blockContentType) {
return (0, _blocksToSlateState2.default)(blocks, blockContentType);
},
/**

@@ -92,5 +87,6 @@ * Returns the feature-set of a compiled block content type.

*/
getBlockContentFeatures: function getBlockContentFeatures(blockType) {
getBlockContentFeatures(blockType) {
return (0, _blockContentTypeToOptions2.default)(blockType);
}
};

@@ -11,46 +11,30 @@ 'use strict';

function resolveEnabledStyles(blockType) {
var styleField = blockType.fields.find(function (btField) {
return btField.name === 'style';
});
const styleField = blockType.fields.find(btField => btField.name === 'style');
if (!styleField) {
throw new Error("A field with name 'style' is not defined in the block type (required).");
}
var textStyles = styleField.type.options.list && styleField.type.options.list.filter(function (style) {
return style.value;
});
const textStyles = styleField.type.options.list && styleField.type.options.list.filter(style => style.value);
if (!textStyles || textStyles.length === 0) {
throw new Error('The style fields need at least one style ' + "defined. I.e: {title: 'Normal', value: 'normal'}.");
}
return textStyles.map(function (style) {
return style.value;
});
return textStyles.map(style => style.value);
}
function resolveEnabledAnnotationTypes(spanType) {
return spanType.annotations.map(function (annotation) {
return annotation.name;
});
return spanType.annotations.map(annotation => annotation.name);
}
function resolveEnabledDecorators(spanType) {
return spanType.decorators.map(function (decorator) {
return decorator.value;
});
return spanType.decorators.map(decorator => decorator.value);
}
function blockContentTypeToOptions(blockContentType) {
var blockType = void 0;
var spanType = void 0;
let blockType;
let spanType;
if (blockContentType) {
blockType = blockContentType.of.find(function (field) {
return field.name === 'block';
});
blockType = blockContentType.of.find(field => field.name === 'block');
if (!blockType) {
throw new Error("'block' type is not defined in this schema (required).");
}
spanType = blockType.fields.find(function (field) {
return field.name === 'spans';
}).type.of.find(function (ofType) {
return ofType.name === 'span';
});
spanType = blockType.fields.find(field => field.name === 'spans').type.of.find(ofType => ofType.name === 'span');
}

@@ -57,0 +41,0 @@ return {

@@ -15,6 +15,4 @@ 'use strict';

// WHATWG crypto RNG - https://w3c.github.io/webcrypto/Overview.html
function whatwgRNG() {
var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 16;
var rnds8 = new Uint8Array(length);
function whatwgRNG(length = 16) {
const rnds8 = new Uint8Array(length);
(0, _getRandomValues2.default)(rnds8);

@@ -24,4 +22,4 @@ return rnds8;

var byteToHex = [];
for (var i = 0; i < 256; ++i) {
const byteToHex = [];
for (let i = 0; i < 256; ++i) {
byteToHex[i] = (i + 0x100).toString(16).substring(1);

@@ -31,5 +29,3 @@ }

function randomKey(length) {
return whatwgRNG(length).reduce(function (str, n) {
return str + byteToHex[n];
}, '').slice(0, length);
return whatwgRNG(length).reduce((str, n) => str + byteToHex[n], '').slice(0, length);
}

@@ -6,7 +6,4 @@ 'use strict';

});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.default = resolveJsType;
var toString = Object.prototype.toString;
const toString = Object.prototype.toString;
// Copied from https://github.com/ForbesLindesay/type-of, but inlined to have fine grained control

@@ -31,3 +28,3 @@

if ((typeof val === 'undefined' ? 'undefined' : _typeof(val)) == 'object' && val && typeof val.length == 'number') {
if (typeof val == 'object' && val && typeof val.length == 'number') {
try {

@@ -62,3 +59,3 @@ if (typeof val.callee == 'function') {

return typeof val === 'undefined' ? 'undefined' : _typeof(val);
return typeof val;
}
{
"name": "@sanity/block-tools",
"version": "0.125.0-next.f7d2f004",
"version": "0.125.0-rc.0",
"description": "Can format HTML, Slate JSON or Sanity block array into any other format.",

@@ -12,3 +12,4 @@ "main": "lib/index.js",

"test": "NODE_ENV=test jest",
"coverage": "NODE_ENV=test jest --coverage"
"coverage": "NODE_ENV=test jest --coverage",
"typecheck": "flow check"
},

@@ -40,26 +41,4 @@ "publishConfig": {

"devDependencies": {
"@sanity/schema": "^0.125.0-next.f7d2f004",
"@sanity/schema": "^0.125.0-rc.0",
"assert": "^1.4.1",
"babel-cli": "^6.26.0",
"babel-eslint": "^8.0.1",
"babel-plugin-css-modules-transform": "^1.1.0",
"babel-plugin-lodash": "^3.2.11",
"babel-plugin-syntax-class-properties": "^6.13.0",
"babel-plugin-syntax-flow": "^6.18.0",
"babel-plugin-syntax-object-rest-spread": "^6.13.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-flow-comments": "^6.22.0",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-polyfill": "^6.23.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-register": "^6.26.0",
"eslint": "^4.11.0",
"eslint-config-sanity": "^3.1.0",
"eslint-import-resolver-webpack": "^0.8.3",
"eslint-plugin-flowtype": "^2.39.1",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-react": "^7.4.0",
"flow-bin": "^0.57.2",
"flow-typed": "^2.2.0",
"in-publish": "^2.0.0",

@@ -66,0 +45,0 @@ "jest": "^21.2.1",

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc