/** * When `onBeforeInput` executes, the browser is attempting to insert a * character into the editor. Apply this character data to the document, * allowing native insertion if possible. * * Native insertion is encouraged in order to limit re-rendering and to * preserve spellcheck highlighting, which disappears or flashes if re-render * occurs on the relevant text nodes. */ function editOnBeforeInput(e) { var chars = e.data; // In some cases (ex: IE ideographic space insertion) no character data // is provided. There's nothing to do when this happens. if (!chars) { return; } // Allow the top-level component to handle the insertion manually. This is // useful when triggering interesting behaviors for a character insertion, // Simple examples: replacing a raw text ':)' with a smile emoji or image // decorator, or setting a block to be a list item after typing '- ' at the // start of the block. if (this.props.handleBeforeInput && isEventHandled(this.props.handleBeforeInput(chars))) { e.preventDefault(); return; } // If selection is collapsed, conditionally allow native behavior. This // reduces re-renders and preserves spellcheck highlighting. If the selection // is not collapsed, we will re-render. var editorState = this.props.editorState; var selection = editorState.getSelection(); if (!selection.isCollapsed()) { e.preventDefault(); this.update(replaceText(editorState, chars, editorState.getCurrentInlineStyle(), getEntityKeyForSelection(editorState.getCurrentContent(), editorState.getSelection()))); return; } var mayAllowNative = !isSelectionAtLeafStart(editorState); var newEditorState = replaceText(editorState, chars, editorState.getCurrentInlineStyle(), getEntityKeyForSelection(editorState.getCurrentContent(), editorState.getSelection())); if (!mayAllowNative) { e.preventDefault(); this.update(newEditorState); return; } var anchorKey = selection.getAnchorKey(); var anchorTree = editorState.getBlockTree(anchorKey); // Check the old and new "fingerprints" of the current block to determine // whether this insertion requires any addition or removal of text nodes, // in which case we would prevent the native character insertion. var originalFingerprint = BlockTree.getFingerprint(anchorTree); var newFingerprint = BlockTree.getFingerprint(newEditorState.getBlockTree(anchorKey)); if (mustPreventDefaultForCharacter(chars) || originalFingerprint !== newFingerprint || nullthrows(newEditorState.getDirectionMap()).get(anchorKey) !== nullthrows(editorState.getDirectionMap()).get(anchorKey)) { e.preventDefault(); } else { // The native event is allowed to occur. newEditorState = EditorState.set(newEditorState, { nativelyRenderedContent: newEditorState.getCurrentContent() }); } this.update(newEditorState); }
function onFileLoaded( error, file, dependencyIDs, id, parent, parentDependencyIndex) { if (error) { return; }var _nullthrows = nullthrows(file);const path = _nullthrows.path; dependencyIDs = nullthrows(dependencyIDs); const parentModule = modules.get(parent); invariant(parentModule, 'Invalid parent module: ' + String(parent)); parentModule.dependencies[parentDependencyIndex] = { id, path }; if ((!skip || !skip.has(path)) && !modules.has(path)) { const module = { dependencies: Array(dependencyIDs.length), file: nullthrows(file) }; modules.set(path, module); for (let i = 0; i < dependencyIDs.length; ++i) { loadModule(dependencyIDs[i], path, i); } } }
{var _this = this;return _asyncToGenerator(function* () { const urlObj = nullthrows(url.parse(clientUrl, true));var _nullthrows = nullthrows(urlObj.query);const bundleEntry = _nullthrows.bundleEntry,platform = _nullthrows.platform; const customTransformOptions = parseCustomTransformOptions(urlObj); // Create a new DeltaTransformer for each client. Once the clients are // modified to support Delta Bundles, they'll be able to pass the // DeltaBundleId param through the WS connection and we'll be able to share // the same DeltaTransformer between the WS connection and the HTTP one. const deltaBundler = _this._packagerServer.getDeltaBundler(); const deltaTransformer = yield deltaBundler.getDeltaTransformer( clientUrl, getBundlingOptionsForHmr(bundleEntry, platform, customTransformOptions)); // Trigger an initial build to start up the DeltaTransformer. var _ref = yield deltaTransformer.getDelta();const id = _ref.id; _this._lastSequenceId = id; // Listen to file changes. const client = { clientId: clientUrl, deltaTransformer, sendFn }; deltaTransformer.on('change', _this._handleFileChange.bind(_this, client)); return client;})();
{var _this = this;return _asyncToGenerator(function* () { const urlObj = nullthrows(url.parse(clientUrl, true));var _nullthrows = nullthrows(urlObj.query);const bundleEntry = _nullthrows.bundleEntry,platform = _nullthrows.platform; const customTransformOptions = parseCustomTransformOptions(urlObj); // Create a new graph for each client. Once the clients are // modified to support Delta Bundles, they'll be able to pass the // DeltaBundleId param through the WS connection and we'll be able to share // the same graph between the WS connection and the HTTP one. const graph = yield _this._packagerServer.buildGraph( [getAbsolutePath(bundleEntry, _this._packagerServer.getProjectRoots())], { assetPlugins: [], customTransformOptions, dev: true, hot: true, minify: false, onProgress: null, platform, type: 'module' }); // Listen to file changes. const client = { sendFn, graph }; _this._packagerServer. getDeltaBundler(). listen(graph, _this._handleFileChange.bind(_this, client)); return client;})();
_handleWrappedEvent(event: WrappedEvent) { const payload = nullthrows(event.payload); const socket = this._connections.get(nullthrows(payload.pageId)); if (!socket) { console.error('Invalid pageId from device:', payload.pageId); return; } socket.send(payload.wrappedEvent); }
function getPointForNonTextNode(editorRoot, startNode, childOffset) { var node = startNode; var offsetKey = findAncestorOffsetKey(node); !(offsetKey != null || editorRoot && (editorRoot === node || editorRoot.firstChild === node)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Unknown node in selection range.') : invariant(false) : void 0; // If the editorRoot is the selection, step downward into the content // wrapper. if (editorRoot === node) { node = node.firstChild; !(node instanceof Element && node.getAttribute('data-contents') === 'true') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Invalid DraftEditorContents structure.') : invariant(false) : void 0; if (childOffset > 0) { childOffset = node.childNodes.length; } } // If the child offset is zero and we have an offset key, we're done. // If there's no offset key because the entire editor is selected, // find the leftmost ("first") leaf in the tree and use that as the offset // key. if (childOffset === 0) { var key = null; if (offsetKey != null) { key = offsetKey; } else { var firstLeaf = getFirstLeaf(node); key = nullthrows(getSelectionOffsetKeyForNode(firstLeaf)); } return { key: key, offset: 0 }; } var nodeBeforeCursor = node.childNodes[childOffset - 1]; var leafKey = null; var textLength = null; if (!getSelectionOffsetKeyForNode(nodeBeforeCursor)) { // Our target node may be a leaf or a text node, in which case we're // already where we want to be and can just use the child's length as // our offset. leafKey = nullthrows(offsetKey); textLength = getTextContentLength(nodeBeforeCursor); } else { // Otherwise, we'll look at the child to the left of the cursor and find // the last leaf node in its subtree. var lastLeaf = getLastLeaf(nodeBeforeCursor); leafKey = nullthrows(getSelectionOffsetKeyForNode(lastLeaf)); textLength = getTextContentLength(lastLeaf); } return { key: leafKey, offset: textLength }; }
function deferred() { let reject, resolve; const promise = new Promise((res, rej) => { reject = rej; resolve = res; }); return { promise, reject: nullthrows(reject), resolve: nullthrows(resolve) }; }
_onScroll = (e: Object) => { const newScrollY = e.nativeEvent.contentOffset.y; this._isScrolling = this._scrollOffsetY !== newScrollY; this._scrollOffsetY = newScrollY; this._frameHeight = e.nativeEvent.layoutMeasurement.height; // We don't want to enqueue any updates if any cells are in the middle of an incremental render, // because it would just be wasted work. if (this._cellsInProgress.size === 0) { this._computeRowsToRenderBatcher.schedule(); } if (this.props.onViewableRowsChanged && Object.keys(this._rowFrames).length) { const viewableRows = ViewabilityHelper.computeViewableRows( this.props.viewablePercentThreshold, this._rowFrames, this.props.data, e.nativeEvent.contentOffset.y, e.nativeEvent.layoutMeasurement.height ); if (deepDiffer(viewableRows, this._viewableRows)) { this._viewableRows = viewableRows; nullthrows(this.props.onViewableRowsChanged)(this._viewableRows); } } this.props.onScroll && this.props.onScroll(e); };
scrollResponderScrollTo: function( x?: number | { x?: number, y?: number, animated?: boolean }, y?: number, animated?: boolean ) { if (typeof x === 'number') { console.warn( '`scrollResponderScrollTo(x, y, animated)` is deprecated. Use `scrollResponderScrollTo({x: 5, y: 5, animated: true})` instead.' ); } else { ({ x, y, animated } = x || {}); } var commandID; if (Platform.OS === 'macos') { commandID = UIManager.RCTNativeScrollView.Commands.scrollTo; } else { commandID = UIManager.RCTScrollView.Commands.scrollTo; } UIManager.dispatchViewManagerCommand( nullthrows(this.scrollResponderGetScrollableNode()), UIManager.RCTScrollView.Commands.scrollTo, [x || 0, y || 0, animated !== false] ); },
cut: function cut(editorState) { var content = editorState.getCurrentContent(); var selection = editorState.getSelection(); var targetRange = null; if (selection.isCollapsed()) { var anchorKey = selection.getAnchorKey(); var blockEnd = content.getBlockForKey(anchorKey).getLength(); if (blockEnd === selection.getAnchorOffset()) { return editorState; } targetRange = selection.set('focusOffset', blockEnd); } else { targetRange = selection; } targetRange = nullthrows(targetRange); clipboard = getContentStateFragment(content, targetRange); var afterRemoval = DraftModifier.removeRange(content, targetRange, 'forward'); if (afterRemoval === content) { return editorState; } return EditorState.push(editorState, afterRemoval, 'remove-range'); },
return this.props.tree.map(function (leafSet, ii) { var leavesForLeafSet = leafSet.get('leaves'); var lastLeaf = leavesForLeafSet.size - 1; var leaves = leavesForLeafSet.map(function (leaf, jj) { var offsetKey = DraftOffsetKey.encode(blockKey, ii, jj); var start = leaf.get('start'); var end = leaf.get('end'); return React.createElement(DraftEditorLeaf, { key: offsetKey, offsetKey: offsetKey, blockKey: blockKey, start: start, selection: hasSelection ? _this2.props.selection : undefined, forceSelection: _this2.props.forceSelection, text: text.slice(start, end), styleSet: block.getInlineStyleAt(start), customStyleMap: _this2.props.customStyleMap, customStyleFn: _this2.props.customStyleFn, isLast: ii === lastLeafSet && jj === lastLeaf }); }).toArray(); var decoratorKey = leafSet.get('decoratorKey'); if (decoratorKey == null) { return leaves; } if (!_this2.props.decorator) { return leaves; } var decorator = nullthrows(_this2.props.decorator); var DecoratorComponent = decorator.getComponentForKey(decoratorKey); if (!DecoratorComponent) { return leaves; } var decoratorProps = decorator.getPropsForKey(decoratorKey); var decoratorOffsetKey = DraftOffsetKey.encode(blockKey, ii, 0); var decoratedText = text.slice(leavesForLeafSet.first().get('start'), leavesForLeafSet.last().get('end')); // Resetting dir to the same value on a child node makes Chrome/Firefox // confused on cursor movement. See http://jsfiddle.net/d157kLck/3/ var dir = UnicodeBidiDirection.getHTMLDirIfDifferent(UnicodeBidi.getDirection(decoratedText), _this2.props.direction); return React.createElement( DecoratorComponent, _extends({}, decoratorProps, { contentState: _this2.props.contentState, decoratedText: decoratedText, dir: dir, key: decoratorOffsetKey, entityKey: block.getEntityAt(leafSet.get('start')), offsetKey: decoratorOffsetKey }), leaves ); }).toArray();
onResponderTerminationRequest: (): boolean => { const {onResponderTerminationRequest} = this.props; if (!nullthrows(this.touchableHandleResponderTerminationRequest)()) { return false; } if (onResponderTerminationRequest == null) { return true; } return onResponderTerminationRequest(); },
PendingTransaction.prototype.getFatQuery = function getFatQuery() { if (!this._fatQuery) { var fragment = fromGraphQL.Fragment(this.mutation.getFatQuery()); !(fragment instanceof RelayQuery.Fragment) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'RelayMutationQueue: Expected `getFatQuery` to return a GraphQL ' + 'Fragment') : invariant(false) : undefined; this._fatQuery = nullthrows(flattenRelayQuery(fragment, { preserveEmptyNodes: fragment.isPattern(), shouldRemoveFragments: true })); } return this._fatQuery; };
value: function _renderPlaceholder() { if (this._showPlaceholder()) { return React.createElement(DraftEditorPlaceholder, { text: nullthrows(this.props.placeholder), editorState: this.props.editorState, textAlignment: this.props.textAlignment, accessibilityID: this._placeholderAccessibilityID }); } return null; }
/** * Get a SelectionState for the supplied mouse event. */ function getSelectionForEvent(event, editorState) { var node = null; var offset = null; if (typeof document.caretRangeFromPoint === 'function') { var dropRange = document.caretRangeFromPoint(event.x, event.y); node = dropRange.startContainer; offset = dropRange.startOffset; } else if (event.rangeParent) { node = event.rangeParent; offset = event.rangeOffset; } else { return null; } node = nullthrows(node); offset = nullthrows(offset); var offsetKey = nullthrows(findAncestorOffsetKey(node)); return getUpdatedSelectionState(editorState, offsetKey, offset, offsetKey, offset); }
function* subtree( moduleTransport, moduleTransportsByPath) {let seen = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Set(); seen.add(moduleTransport.id); for (const _ref2 of moduleTransport.dependencies) {const path = _ref2.path; const dependency = nullthrows(moduleTransportsByPath.get(path)); if (!seen.has(dependency.id)) { yield dependency.id; yield* subtree(dependency, moduleTransportsByPath, seen); } } }
module.exports = function parseCustomTransformOptions(urlObj) { const customTransformOptions = Object.create(null); const query = nullthrows(urlObj.query); Object.keys(query).forEach(key => { if (key.startsWith(PREFIX)) { customTransformOptions[key.substr(PREFIX.length)] = query[key]; } }); return customTransformOptions; };
function *subtree( moduleTransport, moduleTransportsByPath, seen = new Set(), ) { seen.add(moduleTransport.id); for (const {path} of moduleTransport.dependencies) { const dependency = nullthrows(moduleTransportsByPath.get(path)); if (!seen.has(dependency.id)) { yield dependency.id; yield *subtree(dependency, moduleTransportsByPath, seen); } } }
RelayMutationQueue.prototype._failCollisionQueue = function _failCollisionQueue(transaction) { var _this2 = this; var collisionKey = transaction.getCollisionKey(); if (collisionKey) { var collisionQueue = nullthrows(this._collisionQueueMap[collisionKey]); // Remove the transaction that called this function. collisionQueue.shift(); collisionQueue.forEach(function (transaction) { return _this2._handleCommitFailure(transaction, null); }); delete this._collisionQueueMap[collisionKey]; } };
RelayMutationQueue.prototype._advanceCollisionQueue = function _advanceCollisionQueue(transaction) { var collisionKey = transaction.getCollisionKey(); if (collisionKey) { var collisionQueue = nullthrows(this._collisionQueueMap[collisionKey]); // Remove the transaction that called this function. collisionQueue.shift(); if (collisionQueue.length) { this._handleCommit(collisionQueue[0]); } else { delete this._collisionQueueMap[collisionKey]; } } };
_loadResourceForFrontend(socket: WebSocket, event: Object) { const id: number = nullthrows(event.id); const url: string = nullthrows(nullthrows(event.params).url); debug('loadResourceForFrontend:', url); http.get(this._normalizeUrl(url), (response) => { // $FlowFixMe callback is optional response.setTimeout(0); let data = ''; response.on('data', (chunk) => { data += chunk; }); response.on('end', () => { socket.send(JSON.stringify({ id: id, result: { statusCode: response.statusCode, content: data, responseHeaders: response.headers, }, })); }); response.on('error', (error) => { console.error('Failed to get resource', error); }); }); }
RelayContainer.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps, nextContext) { var _this3 = this; var _nullthrows = nullthrows(nextContext); var relay = _nullthrows.relay; var route = _nullthrows.route; if (route.useMockData) { return; } this.setState(function (state) { if (_this3.context.relay !== relay) { _this3._cleanup(); } return _this3._initialize(nextProps, relay, route, resetPropOverridesForVariables(spec, nextProps, state.variables)); }); };
wss.on('connection', (socket: WebSocket) => { try { const url = parseUrl(socket.upgradeReq.url, false); const { device, page } = querystring.parse( querystring.unescape(nullthrows(url.query))); if (device === undefined || page === undefined) { throw Error('Must provide device and page'); } const deviceObject = this._devices.get(device); if (!deviceObject) { throw Error('Unknown device: ' + device); } deviceObject.connect(page, socket); } catch (e) { console.error(e); socket.close(1011, e.message); } });
/** * Transform all the calls to `require()` and `import()` in a file into ID- * independent code, and return the list of dependencies. For example, a call * like `require('Foo')` could be transformed to `require(_depMap[3], 'Foo')` * where `_depMap` is provided by the outer scope. As such, we don't need to * know the actual module ID. The second argument is only provided for debugging * purposes. */ function collectDependencies( ast, options) { const visited = new WeakSet();const asyncRequireModulePath = options.asyncRequireModulePath,dynamicRequires = options.dynamicRequires; const context = { asyncRequireModulePath, dynamicRequires, dependencies: [], nameToIndex: new Map() }; const visitor = { Program(path, state) { state.dependencyMapIdentifier = path.scope.generateUidIdentifier( 'dependencyMap'); }, CallExpression(path, state) {const depMapIdent = state.dependencyMapIdentifier; const node = path.node; if (visited.has(node)) { return; } if (node.callee.type === 'Import') { processImportCall(context, path, node, depMapIdent); return; } if (isNativeRequireCall(path)) { const reqNode = processRequireCall(context, path, node, depMapIdent); visited.add(reqNode); } } }; const traversalState = { dependencyMapIdentifier: null }; traverse(ast, visitor, null, traversalState); return { dependencies: context.dependencies, dependencyMapName: nullthrows(traversalState.dependencyMapIdentifier).name }; }
}, ( error: ?Error, result?: {graph: GraphResult, moduleSystem: Array<Module>, polyfills: Array<Module>}, ) => { if (error) { callback(error); return; } const { graph: {modules, entryModules}, moduleSystem, polyfills, } = nullthrows(result); callback(null, { entryModules, modules: concat([prelude(optimize)], moduleSystem, polyfills, modules), }); });
function collectDependencies(ast, replacement, dependencyMapIdentifier) { const visited = new WeakSet(); const traversalState = { dependencyMapIdentifier }; traverse( ast, { Program(path, state) { if (!state.dependencyMapIdentifier) { state.dependencyMapIdentifier = path.scope.generateUidIdentifier( 'dependencyMap'); } }, CallExpression(path, state) { const node = path.node; if (visited.has(node)) { return; } if (isRequireCall(node.callee)) { const arg = replacement.getRequireCallArg(node); const index = replacement.getIndex(arg); node.arguments = replacement.makeArgs( types.numericLiteral(index), arg, state.dependencyMapIdentifier); visited.add(node); } } }, null, traversalState); return { dependencies: replacement.getNames(), dependencyMapName: nullthrows(traversalState.dependencyMapIdentifier).name }; }
toggleBlockType: function toggleBlockType(editorState, blockType) { var selection = editorState.getSelection(); var startKey = selection.getStartKey(); var endKey = selection.getEndKey(); var content = editorState.getCurrentContent(); var target = selection; // Triple-click can lead to a selection that includes offset 0 of the // following block. The `SelectionState` for this case is accurate, but // we should avoid toggling block type for the trailing block because it // is a confusing interaction. if (startKey !== endKey && selection.getEndOffset() === 0) { var blockBefore = nullthrows(content.getBlockBefore(endKey)); endKey = blockBefore.getKey(); target = target.merge({ anchorKey: startKey, anchorOffset: selection.getStartOffset(), focusKey: endKey, focusOffset: blockBefore.getLength(), isBackward: false }); } var hasAtomicBlock = content.getBlockMap().skipWhile(function (_, k) { return k !== startKey; }).reverse().skipWhile(function (_, k) { return k !== endKey; }).some(function (v) { return v.getType() === 'atomic'; }); if (hasAtomicBlock) { return editorState; } var typeToSet = content.getBlockForKey(startKey).getType() === blockType ? 'unstyled' : blockType; return EditorState.push(editorState, DraftModifier.setBlockType(content, target, typeToSet), 'change-block-type'); },
( error, result) => { if (error) { callback(error); return; }var _nullthrows = nullthrows(result),_nullthrows$graph = _nullthrows.graph;const modules = _nullthrows$graph.modules,entryModules = _nullthrows$graph.entryModules,moduleSystem = _nullthrows.moduleSystem,polyfills = _nullthrows.polyfills; const preludeScript = prelude(optimize); const prependedScripts = [preludeScript].concat(_toConsumableArray(moduleSystem), _toConsumableArray(polyfills)); callback(null, { entryModules, modules: prependedScripts.concat(modules), prependedScripts }); });
getName(): Promise<string> { return Promise.resolve(nullthrows(this.data.name)); }
serialized.entryModules = dependencies.map(dep => nullthrows(modules.get(dep.path)));