64 lines
2.0 KiB
Plaintext
64 lines
2.0 KiB
Plaintext
/**
|
|
* Copyright (c) 2013-present, Facebook, Inc.
|
|
* All rights reserved.
|
|
*
|
|
* This source code is licensed under the BSD-style license found in the
|
|
* LICENSE file in the root directory of this source tree. An additional grant
|
|
* of patent rights can be found in the PATENTS file in the same directory.
|
|
*
|
|
* @providesModule encodeInlineStyleRanges
|
|
* @format
|
|
* @flow
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
import type { BlockNodeRecord } from './BlockNodeRecord';
|
|
import type { DraftInlineStyle } from './DraftInlineStyle';
|
|
import type { InlineStyleRange } from './InlineStyleRange';
|
|
import type { List } from 'immutable';
|
|
|
|
var UnicodeUtils = require('fbjs/lib/UnicodeUtils');
|
|
|
|
var findRangesImmutable = require('./findRangesImmutable');
|
|
|
|
var areEqual = (a, b) => a === b;
|
|
var isTruthy = a => !!a;
|
|
var EMPTY_ARRAY = [];
|
|
|
|
/**
|
|
* Helper function for getting encoded styles for each inline style. Convert
|
|
* to UTF-8 character counts for storage.
|
|
*/
|
|
function getEncodedInlinesForType(block: BlockNodeRecord, styleList: List<DraftInlineStyle>, styleToEncode: string): Array<InlineStyleRange> {
|
|
var ranges = [];
|
|
|
|
// Obtain an array with ranges for only the specified style.
|
|
var filteredInlines = styleList.map(style => style.has(styleToEncode)).toList();
|
|
|
|
findRangesImmutable(filteredInlines, areEqual,
|
|
// We only want to keep ranges with nonzero style values.
|
|
isTruthy, (start, end) => {
|
|
var text = block.getText();
|
|
ranges.push({
|
|
offset: UnicodeUtils.strlen(text.slice(0, start)),
|
|
length: UnicodeUtils.strlen(text.slice(start, end)),
|
|
style: styleToEncode
|
|
});
|
|
});
|
|
|
|
return ranges;
|
|
}
|
|
|
|
/*
|
|
* Retrieve the encoded arrays of inline styles, with each individual style
|
|
* treated separately.
|
|
*/
|
|
function encodeInlineStyleRanges(block: BlockNodeRecord): Array<InlineStyleRange> {
|
|
var styleList = block.getCharacterList().map(c => c.getStyle()).toList();
|
|
var ranges = styleList.flatten().toSet().map(style => getEncodedInlinesForType(block, styleList, style));
|
|
|
|
return Array.prototype.concat.apply(EMPTY_ARRAY, ranges.toJS());
|
|
}
|
|
|
|
module.exports = encodeInlineStyleRanges; |