{"_id":"q-en-react-04add7cc87400d8c778139879b72fad39cd35a704885942893986892760d74e7","text":"COMMANDS_TO_RUN+=('./scripts/circleci/build.sh') COMMANDS_TO_RUN+=('yarn test-build --runInBand') COMMANDS_TO_RUN+=('yarn test-build-prod --runInBand') COMMANDS_TO_RUN+=('./scripts/circleci/upload_build.sh') fi if [ $((3 % CIRCLE_NODE_TOTAL)) -eq \"$CIRCLE_NODE_INDEX\" ]; then"} {"_id":"q-en-react-08d1f795b0b106899d6c8039e2ec679bc51dc211e6341a0b87ccd95359bef026","text":"} } while (nextEffect !== null) { if (__DEV__) { setCurrentFiber(nextEffect); } const effectTag = nextEffect.effectTag; if (effectTag & (Update | Callback)) {"} {"_id":"q-en-react-09ac2aa728271f2b62d4a25409bcd2310501e5004b301546250b41af7ae6ae73","text":"const MAX_SIZE = 500; const PAGE_SIZE = 50; function createRecord(key: K): EmptyRecord { function createRecord(key: K): EmptyRecord { return { status: Empty, suspender: null,"} {"_id":"q-en-react-0a2bffbae851a79b71c900082e658405d8903c5f7cd4de93488a70d0627ec09d","text":"return newHead; } function load(emptyRecord: EmptyRecord, suspender: Promise) { const pendingRecord: PendingRecord = (emptyRecord: any); function load(emptyRecord: EmptyRecord, suspender: Promise) { const pendingRecord: PendingRecord = (emptyRecord: any); pendingRecord.status = Pending; pendingRecord.suspender = suspender; suspender.then( value => { // Resource loaded successfully. const resolvedRecord: ResolvedRecord = (pendingRecord: any); const resolvedRecord: ResolvedRecord = (pendingRecord: any); resolvedRecord.status = Resolved; resolvedRecord.suspender = null; resolvedRecord.value = value;"} {"_id":"q-en-react-0a56b098a6dc9769a24fea108d6459673db4cd78868d1d5c0b9e3d7ebda56af0","text":"var propName = propertyInfo.propertyName; // Must explicitly cast values for HAS_SIDE_EFFECTS-properties to the // property type before comparing; only `value` does and is string. // Must set `value` property if it is not null and not yet set. if (!propertyInfo.hasSideEffects || ('' + node[propName]) !== ('' + value) || !node.hasAttribute(propertyInfo.attributeName)) { ('' + node[propName]) !== ('' + value)) { // Contrary to `setAttribute`, object properties are properly // `toString`ed by IE8/9. node[propName] = value;"} {"_id":"q-en-react-16df93b253c4ae0b30bb344813993801464d6751c98c5e66bbc280fe7ae5eafe","text":" {isEditable ? ( dataType={dataType} initialValue={value} overrideValueFn={((overrideValueFn: any): OverrideValueFn)} path={path} initialValue={value} /> ) : ( {displayValue}"} {"_id":"q-en-react-17293207531c6352290b933d4fe9d85d17a1553684093dd654f4cb65ec631b07","text":"do { lastID = internalGetID(current); current = current.parentNode; invariant( current != null, 'findFirstReactDOMImpl(...): Unexpected detached subtree found when ' + 'traversing DOM from node `%s`.', nodeID ); if (current == null) { // The passed-in node has been detached from the container it was // originally rendered into. return null; } } while (lastID !== reactRootID); if (current === containersByReactRootID[reactRootID]) {"} {"_id":"q-en-react-20ce2b27ca5a000860017820efe9643aa6f9e00c779b16e6ed8aeeb6eb93ec59","text":"Markdown is a simple way to format your text inline. For example, surrounding text with asterisks will make it emphasized. First, add the third-party **Showdown** library to your application. This is a JavaScript library which takes Markdown text and converts it to raw HTML. This requires a script tag in your head (which we have already included in the React playground): First, add the third-party library **marked** to your application. This is a JavaScript library which takes Markdown text and converts it to raw HTML. This requires a script tag in your head (which we have already included in the React playground): ```html{7} "} {"_id":"q-en-react-23f2eca2ce19c88138563acc5ba75562e4835e85142f0959692bbc72882b58d6","text":"); } break; case 'option': transaction.getReactMountReady().enqueue( optionPostMount, this ); } return mountImage;"} {"_id":"q-en-react-265eefe968d1d4375df2787a14b2d59073b9eabf6c6692729e0e6ca4fd992a55","text":"\"private\": true, \"scripts\": { \"build\": \"cross-env NODE_ENV=production yarn run build:chrome && yarn run build:firefox && yarn run build:edge\", \"build:dev\": \"cross-env NODE_ENV=development yarn run build:chrome && yarn run build:firefox && yarn run build:edge\", \"build:dev\": \"cross-env NODE_ENV=development yarn run build:chrome:dev && yarn run build:firefox:dev && yarn run build:edge:dev\", \"build:chrome\": \"cross-env NODE_ENV=production node ./chrome/build\", \"build:chrome:crx\": \"cross-env NODE_ENV=production node ./chrome/build --crx\", \"build:chrome:dev\": \"cross-env NODE_ENV=development node ./chrome/build\","} {"_id":"q-en-react-29ec3ef453ea77c05be139bcdc942d399967d4ab420fb3a3567007bf61309356","text":"return markup; }, _constructComponent: function(publicProps, publicContext) { if (__DEV__) { ReactCurrentOwner.current = this; try { return this._constructComponentWithoutOwner(publicProps, publicContext); } finally { ReactCurrentOwner.current = null; } } else { return this._constructComponentWithoutOwner(publicProps, publicContext); } }, _constructComponentWithoutOwner: function(publicProps, publicContext) { var Component = this._currentElement.type; if (shouldConstruct(Component)) { return new Component(publicProps, publicContext, ReactUpdateQueue); } else { return Component(publicProps, publicContext, ReactUpdateQueue); } }, performInitialMountWithErrorHandling: function( renderedElement, nativeParent,"} {"_id":"q-en-react-2be836c71d84ab1ae1a8bac90b0a5eeae0f38355b7cedb761ac3c10c9092c0d9","text":" "} {"_id":"q-en-react-2ecdf99ae0b477493332383441b1b8e37fd7275f72a0cb086c37af80dd52bf6b","text":"const elementType = getElementTypeForFiber(fiber); const {_debugOwner} = fiber; const ownerID = _debugOwner != null ? getFiberIDThrows(_debugOwner) : 0; // Ideally we should call getFiberIDThrows() for _debugOwner, // since owners are almost always higher in the tree (and so have already been processed), // but in some (rare) instances reported in open source, a descendant mounts before an owner. // Since this is a DEV only field it's probably okay to also just lazily generate and ID here if needed. // See https://github.com/facebook/react/issues/21445 const ownerID = _debugOwner != null ? getOrGenerateFiberID(_debugOwner) : 0; const parentID = parentFiber ? getFiberIDThrows(parentFiber) : 0; const displayNameStringID = getStringID(displayName);"} {"_id":"q-en-react-320fb007e8626bf23a4b5d9396e86f181bc8b6c98f43abd30ac69de3fc173817","text":" // // showdown.js -- A javascript port of Markdown. // // Copyright (c) 2007 John Fraser. // // Original Markdown Copyright (c) 2004-2005 John Gruber // // // Redistributable under a BSD-style open source license. // See license.txt for more information. // // The full source distribution is at: // //\t\t\t\tA A L //\t\t\t\tT C A //\t\t\t\tT K B // // // // // Wherever possible, Showdown is a straight, line-by-line port // of the Perl version of Markdown. // // This is not a normal parser design; it's basically just a // series of string substitutions. It's hard to read and // maintain this way, but keeping Showdown close to the original // design makes it easier to port new features. // // More importantly, Showdown behaves like markdown.pl in most // edge cases. So web applications can do client-side preview // in Javascript, and then build identical HTML on the server. // // This port needs the new RegExp functionality of ECMA 262, // 3rd Edition (i.e. Javascript 1.5). Most modern web browsers // should do fine. Even with the new regular expression features, // We do a lot of work to emulate Perl's regex functionality. // The tricky changes in this file mostly have the \"attacklab:\" // label. Major or self-explanatory changes don't. // // Smart diff tools like Araxis Merge will be able to match up // this file with markdown.pl in a useful way. A little tweaking // helps: in a copy of markdown.pl, replace \"#\" with \"//\" and // replace \"$text\" with \"text\". Be sure to ignore whitespace // and line endings. // // // Showdown usage: // // var text = \"Markdown *rocks*.\"; // // var converter = new Showdown.converter(); // var html = converter.makeHtml(text); // // alert(html); // // Note: move the sample code to the bottom of this // file before uncommenting it. // // // Showdown namespace // var Showdown = {}; // // converter // // Wraps all \"globals\" so that the only thing // exposed is makeHtml(). // Showdown.converter = function() { // // Globals: // // Global hashes, used by various utility routines var g_urls; var g_titles; var g_html_blocks; // Used to track when we're inside an ordered or unordered list // (see _ProcessListItems() for details): var g_list_level = 0; this.makeHtml = function(text) { // // Main function. The order in which other subs are called here is // essential. Link and image substitutions need to happen before // _EscapeSpecialCharsWithinTagAttributes(), so that any *'s or _'s in the // and tags get encoded. // // Clear the global hashes. If we don't clear these, you get conflicts // from other articles when generating a page which contains more than // one article (e.g. an index page that shows the N most recent // articles): g_urls = new Array(); g_titles = new Array(); g_html_blocks = new Array(); // attacklab: Replace ~ with ~T // This lets us use tilde as an escape char to avoid md5 hashes // The choice of character is arbitray; anything that isn't // magic in Markdown will work. text = text.replace(/~/g,\"~T\"); // attacklab: Replace $ with ~D // RegExp interprets $ as a special character // when it's in a replacement string text = text.replace(/$/g,\"~D\"); // Standardize line endings text = text.replace(/rn/g,\"n\"); // DOS to Unix text = text.replace(/r/g,\"n\"); // Mac to Unix // Make sure text begins and ends with a couple of newlines: text = \"nn\" + text + \"nn\"; // Convert all tabs to spaces. text = _Detab(text); // Strip any lines consisting only of spaces and tabs. // This makes subsequent regexen easier to write, because we can // match consecutive blank lines with /n+/ instead of something // contorted like /[ t]*n+/ . text = text.replace(/^[ t]+$/mg,\"\"); // Turn block-level HTML blocks into hash entries text = _HashHTMLBlocks(text); // Strip link definitions, store in hashes. text = _StripLinkDefinitions(text); text = _RunBlockGamut(text); text = _UnescapeSpecialChars(text); // attacklab: Restore dollar signs text = text.replace(/~D/g,\"$$\"); // attacklab: Restore tildes text = text.replace(/~T/g,\"~\"); return text; } var _StripLinkDefinitions = function(text) { // // Strips link definitions from text, stores the URLs and titles in // hash references. // // Link defs are in the form: ^[id]: url \"optional title\" /* var text = text.replace(/ ^[ ]{0,3}[(.+)]: // id = $1 attacklab: g_tab_width - 1 [ t]* n?\t\t\t\t// maybe *one* newline [ t]* ?\t\t\t// url = $2 [ t]* n?\t\t\t\t// maybe one newline [ t]* (?: (n*)\t\t\t\t// any lines skipped = $3 attacklab: lookbehind removed [\"(] (.+?)\t\t\t\t// title = $4 [\")] [ t]* )?\t\t\t\t\t// title is optional (?:n+|$) /gm, function(){...}); */ var text = text.replace(/^[ ]{0,3}[(.+)]:[ t]*n?[ t]*?[ t]*n?[ t]*(?:(n*)[\"(](.+?)[\")][ t]*)?(?:n+|Z)/gm, function (wholeMatch,m1,m2,m3,m4) { m1 = m1.toLowerCase(); g_urls[m1] = _EncodeAmpsAndAngles(m2); // Link IDs are case-insensitive if (m3) { // Oops, found blank lines, so it's not a title. // Put back the parenthetical statement we stole. return m3+m4; } else if (m4) { g_titles[m1] = m4.replace(/\"/g,\""\"); } // Completely remove the definition from the text return \"\"; } ); return text; } var _HashHTMLBlocks = function(text) { // attacklab: Double up blank lines to reduce lookaround text = text.replace(/n/g,\"nn\"); // Hashify HTML blocks: // We only want to do this for block-level HTML tags, such as headers, // lists, and tables. That's because we still want to wrap

s around // \"paragraphs\" that are wrapped in non-block-level tags, such as anchors, // phrase emphasis, and spans. The list of tags we're looking for is // hard-coded: var block_tags_a = \"p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del\" var block_tags_b = \"p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math\" // First, look for nested blocks, e.g.: //

//
// tags for inner block must be indented. //
//
// // The outermost tags must start at the left margin for this to match, and // the inner nested divs must be indented. // We need to do this before the next, more liberal match, because the next // match will start at the first `
` and stop at the first `
`. // attacklab: This regex can be expensive when it fails. /* var text = text.replace(/ (\t\t\t\t\t\t// save in $1 ^\t\t\t\t\t// start of line (with /m) <($block_tags_a)\t// start tag = $2 b\t\t\t\t\t// word break // attacklab: hack around khtml/pcre bug... [^r]*?n\t\t\t// any number of lines, minimally matching \t\t\t\t// the matching end tag [ t]*\t\t\t\t// trailing spaces/tabs (?=n+)\t\t\t\t// followed by a newline )\t\t\t\t\t\t// attacklab: there are sentinel newlines at end of document /gm,function(){...}}; */ text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del)b[^r]*?n[ t]*(?=n+))/gm,hashElement); // // Now match more liberally, simply from `n` to `n` // /* var text = text.replace(/ (\t\t\t\t\t\t// save in $1 ^\t\t\t\t\t// start of line (with /m) <($block_tags_b)\t// start tag = $2 b\t\t\t\t\t// word break // attacklab: hack around khtml/pcre bug... [^r]*?\t\t\t\t// any number of lines, minimally matching .*\t\t\t\t// the matching end tag [ t]*\t\t\t\t// trailing spaces/tabs (?=n+)\t\t\t\t// followed by a newline )\t\t\t\t\t\t// attacklab: there are sentinel newlines at end of document /gm,function(){...}}; */ text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math)b[^r]*?.*[ t]*(?=n+)n)/gm,hashElement); // Special case just for
. It was easier to make a special case than // to make the other regex more complicated. /* text = text.replace(/ (\t\t\t\t\t\t// save in $1 nn\t\t\t\t// Starting after a blank line [ ]{0,3} (<(hr)\t\t\t\t// start tag = $2 b\t\t\t\t\t// word break ([^<>])*?\t\t\t// /?>)\t\t\t\t// the matching end tag [ t]* (?=n{2,})\t\t\t// followed by a blank line ) /g,hashElement); */ text = text.replace(/(n[ ]{0,3}(<(hr)b([^<>])*?/?>)[ t]*(?=n{2,}))/g,hashElement); // Special case for standalone HTML comments: /* text = text.replace(/ (\t\t\t\t\t\t// save in $1 nn\t\t\t\t// Starting after a blank line [ ]{0,3}\t\t\t// attacklab: g_tab_width - 1 [ t]* (?=n{2,})\t\t\t// followed by a blank line ) /g,hashElement); */ text = text.replace(/(nn[ ]{0,3}[ t]*(?=n{2,}))/g,hashElement); // PHP and ASP-style processor instructions ( and <%...%>) /* text = text.replace(/ (?: nn\t\t\t\t// Starting after a blank line ) (\t\t\t\t\t\t// save in $1 [ ]{0,3}\t\t\t// attacklab: g_tab_width - 1 (?: <([?%])\t\t\t// $2 [^r]*? 2> ) [ t]* (?=n{2,})\t\t\t// followed by a blank line ) /g,hashElement); */ text = text.replace(/(?:nn)([ ]{0,3}(?:<([?%])[^r]*?2>)[ t]*(?=n{2,}))/g,hashElement); // attacklab: Undo double lines (see comment at top of this function) text = text.replace(/nn/g,\"n\"); return text; } var hashElement = function(wholeMatch,m1) { var blockText = m1; // Undo double lines blockText = blockText.replace(/nn/g,\"n\"); blockText = blockText.replace(/^n/,\"\"); // strip trailing blank lines blockText = blockText.replace(/n+$/g,\"\"); // Replace the element text with a marker (\"~KxK\" where x is its key) blockText = \"nn~K\" + (g_html_blocks.push(blockText)-1) + \"Knn\"; return blockText; }; var _RunBlockGamut = function(text) { // // These are all the transformations that form block-level // tags like paragraphs, headers, and list items. // text = _DoHeaders(text); // Do Horizontal Rules: var key = hashBlock(\"
\"); text = text.replace(/^[ ]{0,2}([ ]?*[ ]?){3,}[ t]*$/gm,key); text = text.replace(/^[ ]{0,2}([ ]?-[ ]?){3,}[ t]*$/gm,key); text = text.replace(/^[ ]{0,2}([ ]?_[ ]?){3,}[ t]*$/gm,key); text = _DoLists(text); text = _DoCodeBlocks(text); text = _DoBlockQuotes(text); // We already ran _HashHTMLBlocks() before, in Markdown(), but that // was to escape raw HTML in the original Markdown source. This time, // we're escaping the markup we've just created, so that we don't wrap //

tags around block-level tags. text = _HashHTMLBlocks(text); text = _FormParagraphs(text); return text; } var _RunSpanGamut = function(text) { // // These are all the transformations that occur *within* block-level // tags like paragraphs, headers, and list items. // text = _DoCodeSpans(text); text = _EscapeSpecialCharsWithinTagAttributes(text); text = _EncodeBackslashEscapes(text); // Process anchor and image tags. Images must come first, // because ![foo][f] looks like an anchor. text = _DoImages(text); text = _DoAnchors(text); // Make links out of things like `` // Must come after _DoAnchors(), because you can use < and > // delimiters in inline links like [this](). text = _DoAutoLinks(text); text = _EncodeAmpsAndAngles(text); text = _DoItalicsAndBold(text); // Do hard breaks: text = text.replace(/ +n/g,\"
n\"); return text; } var _EscapeSpecialCharsWithinTagAttributes = function(text) { // // Within tags -- meaning between < and > -- encode [ ` * _] so they // don't conflict with their use in Markdown for code, italics and strong. // // Build a regex to find HTML tags and comments. See Friedl's // \"Mastering Regular Expressions\", 2nd Ed., pp. 200-201. var regex = /(<[a-z/!$](\"[^\"]*\"|'[^']*'|[^'\">])*>|)/gi; text = text.replace(regex, function(wholeMatch) { var tag = wholeMatch.replace(/(.)(?=.)/g,\"$1`\"); tag = escapeCharacters(tag,\"`*_\"); return tag; }); return text; } var _DoAnchors = function(text) { // // Turn Markdown link shortcuts into XHTML
tags. // // // First, handle reference-style links: [link text] [id] // /* text = text.replace(/ (\t\t\t\t\t\t\t// wrap whole match in $1 [ ( (?: [[^]]*]\t\t// allow brackets nested one level | [^[]\t\t\t// or anything else )* ) ] [ ]?\t\t\t\t\t// one optional space (?:n[ ]*)?\t\t\t\t// one optional newline followed by spaces [ (.*?)\t\t\t\t\t// id = $3 ] )()()()()\t\t\t\t\t// pad remaining backreferences /g,_DoAnchors_callback); */ text = text.replace(/([((?:[[^]]*]|[^[]])*)][ ]?(?:n[ ]*)?[(.*?)])()()()()/g,writeAnchorTag); // // Next, inline-style links: [link text](url \"optional title\") // /* text = text.replace(/ (\t\t\t\t\t\t// wrap whole match in $1 [ ( (?: [[^]]*]\t// allow brackets nested one level | [^[]]\t\t\t// or anything else ) ) ] (\t\t\t\t\t\t// literal paren [ t]* ()\t\t\t\t\t\t// no id, so leave $3 empty ?\t\t\t\t// href = $4 [ t]* (\t\t\t\t\t\t// $5 (['\"])\t\t\t\t// quote char = $6 (.*?)\t\t\t\t// Title = $7 6\t\t\t\t\t// matching quote [ t]*\t\t\t\t// ignore any spaces/tabs between closing quote and ) )?\t\t\t\t\t\t// title is optional ) ) /g,writeAnchorTag); */ text = text.replace(/([((?:[[^]]*]|[^[]])*)]([ t]*()?[ t]*((['\"])(.*?)6[ t]*)?))/g,writeAnchorTag); // // Last, handle reference-style shortcuts: [link text] // These must come last in case you've also got [link test][1] // or [link test](/foo) // /* text = text.replace(/ (\t\t \t\t\t\t\t// wrap whole match in $1 [ ([^[]]+)\t\t\t\t// link text = $2; can't contain '[' or ']' ] )()()()()()\t\t\t\t\t// pad rest of backreferences /g, writeAnchorTag); */ text = text.replace(/([([^[]]+)])()()()()()/g, writeAnchorTag); return text; } var writeAnchorTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) { if (m7 == undefined) m7 = \"\"; var whole_match = m1; var link_text = m2; var link_id\t = m3.toLowerCase(); var url\t\t= m4; var title\t= m7; if (url == \"\") { if (link_id == \"\") { // lower-case and turn embedded newlines into spaces link_id = link_text.toLowerCase().replace(/ ?n/g,\" \"); } url = \"#\"+link_id; if (g_urls[link_id] != undefined) { url = g_urls[link_id]; if (g_titles[link_id] != undefined) { title = g_titles[link_id]; } } else { if (whole_match.search(/(s*)$/m)>-1) { // Special case for explicit empty url url = \"\"; } else { return whole_match; } } } url = escapeCharacters(url,\"*_\"); var result = \"\" + link_text + \"\"; return result; } var _DoImages = function(text) { // // Turn Markdown image shortcuts into tags. // // // First, handle reference-style labeled images: ![alt text][id] // /* text = text.replace(/ (\t\t\t\t\t\t// wrap whole match in $1 ![ (.*?)\t\t\t\t// alt text = $2 ] [ ]?\t\t\t\t// one optional space (?:n[ ]*)?\t\t\t// one optional newline followed by spaces [ (.*?)\t\t\t\t// id = $3 ] )()()()()\t\t\t\t// pad rest of backreferences /g,writeImageTag); */ text = text.replace(/(![(.*?)][ ]?(?:n[ ]*)?[(.*?)])()()()()/g,writeImageTag); // // Next, handle inline images: ![alt text](url \"optional title\") // Don't forget: encode * and _ /* text = text.replace(/ (\t\t\t\t\t\t// wrap whole match in $1 ![ (.*?)\t\t\t\t// alt text = $2 ] s?\t\t\t\t\t// One optional whitespace character (\t\t\t\t\t// literal paren [ t]* ()\t\t\t\t\t// no id, so leave $3 empty ?\t\t\t// src url = $4 [ t]* (\t\t\t\t\t// $5 (['\"])\t\t\t// quote char = $6 (.*?)\t\t\t// title = $7 6\t\t\t\t// matching quote [ t]* )?\t\t\t\t\t// title is optional ) ) /g,writeImageTag); */ text = text.replace(/(![(.*?)]s?([ t]*()?[ t]*((['\"])(.*?)6[ t]*)?))/g,writeImageTag); return text; } var writeImageTag = function(wholeMatch,m1,m2,m3,m4,m5,m6,m7) { var whole_match = m1; var alt_text = m2; var link_id\t = m3.toLowerCase(); var url\t\t= m4; var title\t= m7; if (!title) title = \"\"; if (url == \"\") { if (link_id == \"\") { // lower-case and turn embedded newlines into spaces link_id = alt_text.toLowerCase().replace(/ ?n/g,\" \"); } url = \"#\"+link_id; if (g_urls[link_id] != undefined) { url = g_urls[link_id]; if (g_titles[link_id] != undefined) { title = g_titles[link_id]; } } else { return whole_match; } } alt_text = alt_text.replace(/\"/g,\""\"); url = escapeCharacters(url,\"*_\"); var result = \"\"\"\"; return result; } var _DoHeaders = function(text) { // Setext-style headers: //\tHeader 1 //\t======== // //\tHeader 2 //\t-------- // text = text.replace(/^(.+)[ t]*n=+[ t]*n+/gm, function(wholeMatch,m1){return hashBlock('

' + _RunSpanGamut(m1) + \"

\");}); text = text.replace(/^(.+)[ t]*n-+[ t]*n+/gm, function(matchFound,m1){return hashBlock('

' + _RunSpanGamut(m1) + \"

\");}); // atx-style headers: // # Header 1 // ## Header 2 // ## Header 2 with closing hashes ## // ... // ###### Header 6 // /* text = text.replace(/ ^(#{1,6})\t\t\t\t// $1 = string of #'s [ t]* (.+?)\t\t\t\t\t// $2 = Header text [ t]* #*\t\t\t\t\t\t// optional closing #'s (not counted) n+ /gm, function() {...}); */ text = text.replace(/^(#{1,6})[ t]*(.+?)[ t]*#*n+/gm, function(wholeMatch,m1,m2) { var h_level = m1.length; return hashBlock(\"' + _RunSpanGamut(m2) + \"\"); }); function headerId(m) { return m.replace(/[^w]/g, '').toLowerCase(); } return text; } // This declaration keeps Dojo compressor from outputting garbage: var _ProcessListItems; var _DoLists = function(text) { // // Form HTML ordered (numbered) and unordered (bulleted) lists. // // attacklab: add sentinel to hack around khtml/safari bug: // http://bugs.webkit.org/show_bug.cgi?id=11231 text += \"~0\"; // Re-usable pattern to match any entirel ul or ol list: /* var whole_list = / (\t\t\t\t\t\t\t\t\t// $1 = whole list (\t\t\t\t\t\t\t\t// $2 [ ]{0,3}\t\t\t\t\t// attacklab: g_tab_width - 1 ([*+-]|d+[.])\t\t\t\t// $3 = first list item marker [ t]+ ) [^r]+? (\t\t\t\t\t\t\t\t// $4 ~0\t\t\t\t\t\t\t// sentinel for workaround; should be $ | n{2,} (?=S) (?!\t\t\t\t\t\t\t// Negative lookahead for another list item marker [ t]* (?:[*+-]|d+[.])[ t]+ ) ) )/g */ var whole_list = /^(([ ]{0,3}([*+-]|d+[.])[ t]+)[^r]+?(~0|n{2,}(?=S)(?![ t]*(?:[*+-]|d+[.])[ t]+)))/gm; if (g_list_level) { text = text.replace(whole_list,function(wholeMatch,m1,m2) { var list = m1; var list_type = (m2.search(/[*+-]/g)>-1) ? \"ul\" : \"ol\"; // Turn double returns into triple returns, so that we can make a // paragraph for the last item in a list, if necessary: list = list.replace(/n{2,}/g,\"nnn\");; var result = _ProcessListItems(list); // Trim any trailing whitespace, to put the closing `` // up on the preceding line, to get it past the current stupid // HTML block parser. This is a hack to work around the terrible // hack that is the HTML block parser. result = result.replace(/s+$/,\"\"); result = \"<\"+list_type+\">\" + result + \"n\"; return result; }); } else { whole_list = /(nn|^n?)(([ ]{0,3}([*+-]|d+[.])[ t]+)[^r]+?(~0|n{2,}(?=S)(?![ t]*(?:[*+-]|d+[.])[ t]+)))/g; text = text.replace(whole_list,function(wholeMatch,m1,m2,m3) { var runup = m1; var list = m2; var list_type = (m3.search(/[*+-]/g)>-1) ? \"ul\" : \"ol\"; // Turn double returns into triple returns, so that we can make a // paragraph for the last item in a list, if necessary: var list = list.replace(/n{2,}/g,\"nnn\");; var result = _ProcessListItems(list); result = runup + \"<\"+list_type+\">n\" + result + \"n\"; return result; }); } // attacklab: strip sentinel text = text.replace(/~0/,\"\"); return text; } _ProcessListItems = function(list_str) { // // Process the contents of a single ordered or unordered list, splitting it // into individual list items. // // The $g_list_level global keeps track of when we're inside a list. // Each time we enter a list, we increment it; when we leave a list, // we decrement. If it's zero, we're not in a list anymore. // // We do this because when we're not inside a list, we want to treat // something like this: // // I recommend upgrading to version // 8. Oops, now this line is treated // as a sub-list. // // As a single paragraph, despite the fact that the second line starts // with a digit-period-space sequence. // // Whereas when we're inside a list (or sub-list), that line will be // treated as the start of a sub-list. What a kludge, huh? This is // an aspect of Markdown's syntax that's hard to parse perfectly // without resorting to mind-reading. Perhaps the solution is to // change the syntax rules such that sub-lists must start with a // starting cardinal number; e.g. \"1.\" or \"a.\". g_list_level++; // trim trailing blank lines: list_str = list_str.replace(/n{2,}$/,\"n\"); // attacklab: add sentinel to emulate z list_str += \"~0\"; /* list_str = list_str.replace(/ (n)?\t\t\t\t\t\t\t// leading line = $1 (^[ t]*)\t\t\t\t\t\t// leading whitespace = $2 ([*+-]|d+[.]) [ t]+\t\t\t// list marker = $3 ([^r]+?\t\t\t\t\t\t// list item text = $4 (n{1,2})) (?= n* (~0 | 2 ([*+-]|d+[.]) [ t]+)) /gm, function(){...}); */ list_str = list_str.replace(/(n)?(^[ t]*)([*+-]|d+[.])[ t]+([^r]+?(n{1,2}))(?=n*(~0|2([*+-]|d+[.])[ t]+))/gm, function(wholeMatch,m1,m2,m3,m4){ var item = m4; var leading_line = m1; var leading_space = m2; if (leading_line || (item.search(/n{2,}/)>-1)) { item = _RunBlockGamut(_Outdent(item)); } else { // Recursion for sub-lists: item = _DoLists(_Outdent(item)); item = item.replace(/n$/,\"\"); // chomp(item) item = _RunSpanGamut(item); } return \"
  • \" + item + \"
  • n\"; } ); // attacklab: strip sentinel list_str = list_str.replace(/~0/g,\"\"); g_list_level--; return list_str; } var _DoCodeBlocks = function(text) { // // Process Markdown `
    ` blocks. // /* text = text.replace(text, /(?:nn|^) (\t\t\t\t\t\t\t\t// $1 = the code block -- one or more lines, starting with a space/tab (?: (?:[ ]{4}|t)\t\t\t// Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width .*n+ )+ ) (n*[ ]{0,3}[^ tn]|(?=~0))\t// attacklab: g_tab_width /g,function(){...}); */ // attacklab: sentinel workarounds for lack of A and Z, safarikhtml bug text += \"~0\"; text = text.replace(/(?:nn|^)((?:(?:[ ]{4}|t).*n+)+)(n*[ ]{0,3}[^ tn]|(?=~0))/g, function(wholeMatch,m1,m2) { var codeblock = m1; var nextChar = m2; codeblock = _EncodeCode( _Outdent(codeblock)); codeblock = _Detab(codeblock); codeblock = codeblock.replace(/^n+/g,\"\"); // trim leading newlines codeblock = codeblock.replace(/n+$/g,\"\"); // trim trailing whitespace codeblock = \"
    \" + codeblock + \"n
    \"; return hashBlock(codeblock) + nextChar; } ); // attacklab: strip sentinel text = text.replace(/~0/,\"\"); return text; } var hashBlock = function(text) { text = text.replace(/(^n+|n+$)/g,\"\"); return \"nn~K\" + (g_html_blocks.push(text)-1) + \"Knn\"; } var _DoCodeSpans = function(text) { // // * Backtick quotes are used for spans. // // * You can use multiple backticks as the delimiters if you want to //\t include literal backticks in the code span. So, this input: // //\t\t Just type ``foo `bar` baz`` at the prompt. // //\t Will translate to: // //\t\t

    Just type foo `bar` baz at the prompt.

    // //\tThere's no arbitrary limit to the number of backticks you //\tcan use as delimters. If you need three consecutive backticks //\tin your code, use four for delimiters, etc. // // * You can use spaces to get literal backticks at the edges: // //\t\t ... type `` `bar` `` ... // //\t Turns to: // //\t\t ... type `bar` ... // /* text = text.replace(/ (^|[^])\t\t\t\t\t// Character before opening ` can't be a backslash (`+)\t\t\t\t\t\t// $2 = Opening run of ` (\t\t\t\t\t\t\t// $3 = The code block [^r]*? [^`]\t\t\t\t\t// attacklab: work around lack of lookbehind ) 2\t\t\t\t\t\t\t// Matching closer (?!`) /gm, function(){...}); */ text = text.replace(/(^|[^])(`+)([^r]*?[^`])2(?!`)/gm, function(wholeMatch,m1,m2,m3,m4) { var c = m3; c = c.replace(/^([ t]*)/g,\"\");\t// leading whitespace c = c.replace(/[ t]*$/g,\"\");\t// trailing whitespace c = _EncodeCode(c); return m1+\"\"+c+\"\"; }); return text; } var _EncodeCode = function(text) { // // Encode/escape certain characters inside Markdown code runs. // The point is that in code, these characters are literals, // and lose their special Markdown meanings. // // Encode all ampersands; HTML entities are not // entities within a Markdown code span. text = text.replace(/&/g,\"&\"); // Do the angle bracket song and dance: text = text.replace(//g,\">\"); // Now, escape characters that are magic in Markdown: text = escapeCharacters(text,\"*_{}[]\",false); // jj the line above breaks this: //--- //* Item // 1. Subitem // special char: * //--- return text; } var _DoItalicsAndBold = function(text) { // must go first: text = text.replace(/(**|__)(?=S)([^r]*?S[*_]*)1/g, \"$2\"); text = text.replace(/(*|_)(?=S)([^r]*?S)1/g, \"$2\"); return text; } var _DoBlockQuotes = function(text) { /* text = text.replace(/ (\t\t\t\t\t\t\t\t// Wrap whole match in $1 ( ^[ t]*>[ t]?\t\t\t// '>' at the start of a line .+n\t\t\t\t\t// rest of the first line (.+n)*\t\t\t\t\t// subsequent consecutive lines n*\t\t\t\t\t\t// blanks )+ ) /gm, function(){...}); */ text = text.replace(/((^[ t]*>[ t]?.+n(.+n)*n*)+)/gm, function(wholeMatch,m1) { var bq = m1; // attacklab: hack around Konqueror 3.5.4 bug: // \"----------bug\".replace(/^-/g,\"\") == \"bug\" bq = bq.replace(/^[ t]*>[ t]?/gm,\"~0\");\t// trim one level of quoting // attacklab: clean up hack bq = bq.replace(/~0/g,\"\"); bq = bq.replace(/^[ t]+$/gm,\"\");\t\t// trim whitespace-only lines bq = _RunBlockGamut(bq);\t\t\t\t// recurse bq = bq.replace(/(^|n)/g,\"$1 \"); // These leading spaces screw with
     content, so we need to fix that: bq = bq.replace( /(s*
    [^r]+?
    )/gm, function(wholeMatch,m1) { var pre = m1; // attacklab: hack around Konqueror 3.5.4 bug: pre = pre.replace(/^ /mg,\"~0\"); pre = pre.replace(/~0/g,\"\"); return pre; }); return hashBlock(\"
    n\" + bq + \"n
    \"); }); return text; } var _FormParagraphs = function(text) { // // Params: // $text - string to process with html

    tags // // Strip leading and trailing lines: text = text.replace(/^n+/g,\"\"); text = text.replace(/n+$/g,\"\"); var grafs = text.split(/n{2,}/g); var grafsOut = new Array(); // // Wrap

    tags. // var end = grafs.length; for (var i=0; i= 0) { grafsOut.push(str); } else if (str.search(/S/) >= 0) { str = _RunSpanGamut(str); str = str.replace(/^([ t]*)/g,\"

    \"); str += \"

    \" grafsOut.push(str); } } // // Unhashify HTML blocks // end = grafsOut.length; for (var i=0; i= 0) { var blockText = g_html_blocks[RegExp.$1]; blockText = blockText.replace(/$/g,\"$$$$\"); // Escape any dollar signs grafsOut[i] = grafsOut[i].replace(/~Kd+K/,blockText); } } return grafsOut.join(\"nn\"); } var _EncodeAmpsAndAngles = function(text) { // Smart processing for ampersands and angle brackets that need to be encoded. // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: // http://bumppo.net/projects/amputator/ text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|w+);)/g,\"&\"); // Encode naked <'s text = text.replace(/<(?![a-z/?$!])/gi,\"<\"); return text; } var _EncodeBackslashEscapes = function(text) { // // Parameter: String. // Returns:\tThe string, with after processing the following backslash //\t\t\t escape sequences. // // attacklab: The polite way to do this is with the new // escapeCharacters() function: // // \ttext = escapeCharacters(text,\"\",true); // \ttext = escapeCharacters(text,\"`*_{}[]()>#+-.!\",true); // // ...but we're sidestepping its use of the (slow) RegExp constructor // as an optimization for Firefox. This function gets called a LOT. text = text.replace(/()/g,escapeCharacters_callback); text = text.replace(/([`*_{}[]()>#+-.!])/g,escapeCharacters_callback); return text; } var _DoAutoLinks = function(text) { text = text.replace(/<((https?|ftp|dict):[^'\">s]+)>/gi,\"$1\"); // Email addresses: /* text = text.replace(/ < (?:mailto:)? ( [-.w]+ @ [-a-z0-9]+(.[-a-z0-9]+)*.[a-z]+ ) > /gi, _DoAutoLinks_callback()); */ text = text.replace(/<(?:mailto:)?([-.w]+@[-a-z0-9]+(.[-a-z0-9]+)*.[a-z]+)>/gi, function(wholeMatch,m1) { return _EncodeEmailAddress( _UnescapeSpecialChars(m1) ); } ); return text; } var _EncodeEmailAddress = function(addr) { // // Input: an email address, e.g. \"foo@example.com\" // // Output: the email address as a mailto link, with each character //\tof the address encoded as either a decimal or hex entity, in //\tthe hopes of foiling most address harvesting spam bots. E.g.: // //\tfoo //\t @example.com // // Based on a filter by Matthew Wickline, posted to the BBEdit-Talk // mailing list: // // attacklab: why can't javascript speak hex? function char2hex(ch) { var hexDigits = '0123456789ABCDEF'; var dec = ch.charCodeAt(0); return(hexDigits.charAt(dec>>4) + hexDigits.charAt(dec&15)); } var encode = [ function(ch){return \"&#\"+ch.charCodeAt(0)+\";\";}, function(ch){return \"&#x\"+char2hex(ch)+\";\";}, function(ch){return ch;} ]; addr = \"mailto:\" + addr; addr = addr.replace(/./g, function(ch) { if (ch == \"@\") { // this *must* be encoded. I insist. ch = encode[Math.floor(Math.random()*2)](ch); } else if (ch !=\":\") { // leave ':' alone (to spot mailto: later) var r = Math.random(); // roughly 10% raw, 45% hex, 45% dec ch = ( r > .9 ?\tencode[2](ch) : r > .45 ?\tencode[1](ch) : encode[0](ch) ); } return ch; }); addr = \"\" + addr + \"\"; addr = addr.replace(/\">.+:/g,\"\">\"); // strip the mailto: from the visible part return addr; } var _UnescapeSpecialChars = function(text) { // // Swap back in all the special characters we've hidden. // text = text.replace(/~E(d+)E/g, function(wholeMatch,m1) { var charCodeToReplace = parseInt(m1); return String.fromCharCode(charCodeToReplace); } ); return text; } var _Outdent = function(text) { // // Remove one level of line-leading tabs or spaces // // attacklab: hack around Konqueror 3.5.4 bug: // \"----------bug\".replace(/^-/g,\"\") == \"bug\" text = text.replace(/^(t|[ ]{1,4})/gm,\"~0\"); // attacklab: g_tab_width // attacklab: clean up hack text = text.replace(/~0/g,\"\") return text; } var _Detab = function(text) { // attacklab: Detab's completely rewritten for speed. // In perl we could fix it by anchoring the regexp with G. // In javascript we're less fortunate. // expand first n-1 tabs text = text.replace(/t(?=t)/g,\" \"); // attacklab: g_tab_width // replace the nth with two sentinels text = text.replace(/t/g,\"~A~B\"); // use the sentinel to anchor our regex so it doesn't explode text = text.replace(/~B(.+?)~A/g, function(wholeMatch,m1,m2) { var leadingText = m1; var numSpaces = 4 - leadingText.length % 4; // attacklab: g_tab_width // there *must* be a better way to do this: for (var i=0; i No newline at end of file"} {"_id":"q-en-react-32b235cb6e8ba8d86644eb19024c3bc27f3de5fd6bb953a2d7eb8cbdfb7b6b96","text":": emptyObject; const instance = new ctor(props, context); adoptClassInstance(workInProgress, instance); checkClassInstance(workInProgress); // Cache unmasked context so we can avoid recreating masked context unless necessary. // ReactFiberContext usually updates this cache but can't for newly-created instances."} {"_id":"q-en-react-34809863e22cfed850b2bbd5fb82cf6a0675a65d19d22dcabaf44145537abc89","text":"that support `*.tmLanguage`. * Linting provides accurate line numbers after compiling without sourcemaps. * Elements use standard scoping so linters can find usage of out-of-scope components. ### Debugging [React Developer Tools](https://github.com/facebook/react-devtools) is a [Chrome extension](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en) that allows you to inspect the React component hierarchy in the Chrome Developer Tools. "} {"_id":"q-en-react-3ea985d1ecc0ab09fe963ad918633efcc462876d602e2b15699e358f5de3cc7a","text":"} export function createLaneMap(initial: T): LaneMap { return new Array(TotalLanes).fill(initial); // Intentionally pushing one by one. // https://v8.dev/blog/elements-kinds#avoid-creating-holes const laneMap = []; for (let i = 0; i < TotalLanes; i++) { laneMap.push(initial); } return laneMap; } export function markRootUpdated("} {"_id":"q-en-react-43da6ed3107d08a677a94e7c5385ea2f9c800093187275647e4ad14bacc37606","text":"echo \"Only docs were updated, stopping build process.\" exit fi npm install -g npm npm install -g npm@latest-2 script: - | if [ \"$TEST_TYPE\" = build_website ]; then"} {"_id":"q-en-react-47682078fb800bc66160ca339307e1645454f18f64804cb150a53e95427ed0d7","text":"var Component = this._currentElement.type; // Initialize the public class var inst; var inst = this._constructComponent(publicProps, publicContext); var renderedElement; if (Component.prototype && Component.prototype.isReactComponent) { if (__DEV__) { ReactCurrentOwner.current = this; try { inst = new Component(publicProps, publicContext, ReactUpdateQueue); } finally { ReactCurrentOwner.current = null; } } else { inst = new Component(publicProps, publicContext, ReactUpdateQueue); } } else { if (__DEV__) { ReactCurrentOwner.current = this; try { inst = Component(publicProps, publicContext, ReactUpdateQueue); } finally { ReactCurrentOwner.current = null; } } else { inst = Component(publicProps, publicContext, ReactUpdateQueue); } if (inst == null || inst.render == null) { renderedElement = inst; warnIfInvalidElement(Component, renderedElement); invariant( inst === null || inst === false || ReactElement.isValidElement(inst), '%s(...): A valid React element (or null) must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component' ); inst = new StatelessComponent(Component); } // Support functional components if (!shouldConstruct(Component) && (inst == null || inst.render == null)) { renderedElement = inst; warnIfInvalidElement(Component, renderedElement); invariant( inst === null || inst === false || ReactElement.isValidElement(inst), '%s(...): A valid React element (or null) must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component' ); inst = new StatelessComponent(Component); } if (__DEV__) {"} {"_id":"q-en-react-492afbb3f48cae70bdb81b327c18b39eac6efd1d3e4b48e3d80119a04e0b69c0","text":"items: - id: flux-overview title: Flux Overview href: http://facebook.github.io/flux/docs/overview.html - id: flux-todo-list title: Flux TodoMVC Tutorial href: http://facebook.github.io/flux/docs/todo-list.html "} {"_id":"q-en-react-49fc40239b15bb355df1899968bc8ef1c66a8b7fc85aba4d2a2ad10fc83c1939","text":"const Resolved = 2; const Rejected = 3; type EmptyRecord = {| type EmptyRecord = {| status: 0, suspender: null, key: K, value: null, error: null, next: Record | null, previous: Record | null, next: any, // TODO: (issue #12941) previous: any, // TODO: (issue #12941) /** * Proper types would be something like this: * next: Record | null, * previous: Record | null, */ |}; type PendingRecord = {| status: 1, suspender: Promise, suspender: Promise, key: K, value: null, error: null, next: Record | null, previous: Record | null, next: any, // TODO: (issue #12941) previous: any, // TODO: (issue #12941) /** * Proper types would be something like this: * next: Record | null, * previous: Record | null, */ |}; type ResolvedRecord = {|"} {"_id":"q-en-react-4a709316123d3ccb746754b3bd9cac1c7364e1c4ecf808c2212b13f3ae87a6cb","text":"export const enableSelectiveHydration = false; export const enableChunksAPI = false; export const exposeConcurrentModeAPIs = __EXPERIMENTAL__; export const warnAboutShorthandPropertyCollision = false; export const warnAboutShorthandPropertyCollision = true; export const enableSchedulerDebugging = false; export const debugRenderPhaseSideEffectsForStrictMode = true; export const disableJavaScriptURLs = false;"} {"_id":"q-en-react-4ade246663484a6c7002059bc3cd0c3641cedcfebfef04da9da615081bbf11a0","text":"--- id: flux-todo-list title: Flux TodoMVC Tutorial prev: flux-overview.html --- To demonstrate the Flux architecture with some example code, let's take on the classic TodoMVC application. The entire application is available in the Flux GitHub repo within the [flux-todomvc](https://github.com/facebook/flux/tree/master/examples/flux-todomvc) example directory, but let's walk through the development of it a step at a time. To begin, we'll need some boilerplate and get up and running with a module system. Node's module system, based on CommonJS, will fit the bill very nicely and we can build off of [react-boilerplate](https://github.com/petehunt/react-boilerplate) to get up and running quickly. Assuming you have npm installed, simply clone the react-boilerplate code from GitHub, and navigate into the resulting directory in Terminal (or whatever CLI application you like). Next run the npm scripts to get up and running: `npm install`, then `npm run build`, and lastly `npm start` to continuously build using Browserify. The TodoMVC example has all this built into it as well, but if you're starting with react-boilerplate make sure you edit your package.json file to match the file structure and dependencies described in the TodoMVC example's [package.json](https://github.com/facebook/flux/tree/master/examples/flux-todomvc/package.json), or else your code won't match up with the explanations below. Source Code Structure --------------------- The resulting index.js file may be used as the entry point into our app, but we'll put most of our code in a 'js' directory. Let's let Browserify do its thing, and now we'll open a new tab in Terminal (or a GUI file browser) to look at the directory. It should look something like this: ``` myapp | + ... + js | + app.js + bundle.js // generated by Browserify whenever we make changes. + index.html + ... ``` Next we'll dive into the js directory, and layout our application's primary directory structure: ``` myapp | + ... + js | + actions + components // all React components, both views and controller-views + constants + dispatcher + stores + app.js + bundle.js + index.html + ... ``` Using the Dispatcher -------------------- We'll use the dispatcher from the [Flux GitHub repository](https://github.com/facebook/flux), but let's go over how to get it into our project, how it works and how we'll use it. The dispatcher's source code is written in [ECMAScript 6](https://github.com/lukehoban/es6features), the future version of JavaScript. To use the future of JS in today's browser's we need to transpile it back to a version of JS that browsers can use. We perform this build step, transpiling from ES6 into common JavaScript, using npm. You can get up and running with the dispatcher in a variety of ways, but perhaps the simplest is to use [Michael Jackson](https://twitter.com/mjackson)'s npm module version of the Flux project, called [react-dispatcher](https://www.npmjs.org/package/react-dispatcher): ``` npm install react-dispatcher ``` Afterward, you can require the dispatcher in your project's modules like so: ```javascript var Dispatcher = require('Flux').Dispatcher; ``` Alternatively, you can clone the Flux repo, run the Gulp-based build script with `npm install`, and then simply copy the dispatcher and invariant modules located inside flux/lib/ to the dispatcher directory for your project. This the what we did in the [example code](https://github.com/facebook/flux/tree/master/examples/flux-todomvc/js/dispatcher). The two most important methods that the dispatcher exposes publically are register() and dispatch(). We'll use register() within our stores to register each store's callback. We'll use dispatch() within our action creators to trigger the invocation of the callbacks. ```javascript class Dispatcher { constructor() { this._callbacks = {}; this._isPending = {}; this._isHandled = {}; this._isDispatching = false; this._pendingPayload = null; } /** * Registers a callback to be invoked with every dispatched payload. * * @param {function} callback * @return {string} */ register(callback) { var id = _prefix + _lastID++; this._callbacks[id] = callback; return id; } // ... /** * Dispatches a payload to all registered callbacks. * * @param {object} payload */ dispatch(payload) { invariant( !this._isDispatching, 'Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch.' ); this._startDispatching(payload); try { for (var id in this._callbacks) { if (this._isPending[id]) { continue; } this._invokeCallback(id); } } finally { this._stopDispatching(); } } // ... _invokeCallback(id) { this._isPending[id] = true; this._callbacks[id](this._pendingPayload); this._isHandled[id] = true; } _startDispatching(payload) { for (var id in this._callbacks) { this._isPending[id] = false; this._isHandled[id] = false; } this._pendingPayload = payload; this._isDispatching = true; } _stopDispatching() { this._pendingPayload = null; this._isDispatching = false; } } ``` Now we are all set to create a dispatcher that is more specific to our app, which we'll call AppDispatcher. ```javascript var Dispatcher = require('./Dispatcher'); var merge = require('react/lib/merge'); var AppDispatcher = merge(Dispatcher.prototype, { /** * A bridge function between the views and the dispatcher, marking the action * as a view action. Another variant here could be handleServerAction. * @param {object} action The data coming from the view. */ handleViewAction: function(action) { this.dispatch({ source: 'VIEW_ACTION', action: action }); } }); module.exports = AppDispatcher; ``` Now we've created an implementation that is a bit more specific to our needs, with a helper function we can use when we create actions. We might expand on this later to provide a separate helper for server updates, but for now this is all we need. You don't actually need to create an AppDispatcher in every application, but we wanted to show it here as an example. The creation of the AppDispatcher allows us to extend the functionality of the Dispatcher. In this application, for example, we have provided metadata about the source of the action outside of the action itself. Creating Stores ---------------- We can use Node's EventEmitter to get started with a store. We need EventEmitter to broadcast the 'change' event to our controller-views. So let's take a look at what that looks like. I've omitted some of the code for the sake of brevity, but for the full version see [TodoStore.js](https://github.com/Facebook/flux/blob/master/examples/flux-todomvc/js/stores/TodoStore.js) in the TodoMVC example code. ```javascript var AppDispatcher = require('../dispatcher/AppDispatcher'); var EventEmitter = require('events').EventEmitter; var TodoConstants = require('../constants/TodoConstants'); var merge = require('react/lib/merge'); var CHANGE_EVENT = 'change'; var _todos = {}; // collection of todo items /** * Create a TODO item. * @param {string} text The content of the TODO */ function create(text) { // Using the current timestamp in place of a real id. var id = Date.now(); _todos[id] = { id: id, complete: false, text: text }; } /** * Delete a TODO item. * @param {string} id */ function destroy(id) { delete _todos[id]; } var TodoStore = merge(EventEmitter.prototype, { /** * Get the entire collection of TODOs. * @return {object} */ getAll: function() { return _todos; }, emitChange: function() { this.emit(CHANGE_EVENT); }, /** * @param {function} callback */ addChangeListener: function(callback) { this.on(CHANGE_EVENT, callback); }, /** * @param {function} callback */ removeChangeListener: function(callback) { this.removeListener(CHANGE_EVENT, callback); }, dispatcherIndex: AppDispatcher.register(function(payload) { var action = payload.action; var text; switch(action.actionType) { case TodoConstants.TODO_CREATE: text = action.text.trim(); if (text !== '') { create(text); TodoStore.emitChange(); } break; case TodoConstants.TODO_DESTROY: destroy(action.id); TodoStore.emitChange(); break; // add more cases for other actionTypes, like TODO_UPDATE, etc. } return true; // No errors. Needed by promise in Dispatcher. }) }); module.exports = TodoStore; ``` There are a few important things to note in the above code. To start, we are maintaining a private data structure called _todos. This object contains all the individual to-do items. Because this variable lives outside the class, but within the closure of the module, it remains private — it cannot be directly changed from the outside. This helps us preserve a distinct input/output interface for the flow of data by making it impossible to update the store without using an action. Another important part is the registration of the store's callback with the dispatcher. We pass in our payload handling callback to the dispatcher and preserve the index that this store has in the dispatcher's registry. The callback function currently only handles two actionTypes, but later we can add as many as we need. Listening to Changes with a Controller-View ------------------------------------------- We need a React component near the top of our component hierarchy to listen for changes in the store. In a larger app, we would have more of these listening components, perhaps one for every section of the page. In Facebook's Ads Creation Tool, we have many of these controller-like views, each governing a specific section of the UI. In the Lookback Video Editor, we only had two: one for the animated preview and one for the image selection interface. Here's one for our TodoMVC example. Again, this is slightly abbreviated, but for the full code you can take a look at the TodoMVC example's [TodoApp.react.js](https://github.com/facebook/flux/blob/master/examples/flux-todomvc/js/components/TodoApp.react.js) ```javascript /** @jsx React.DOM */ var Footer = require('./Footer.react'); var Header = require('./Header.react'); var MainSection = require('./MainSection.react'); var React = require('react'); var TodoStore = require('../stores/TodoStore'); function getTodoState() { return { allTodos: TodoStore.getAll() }; } var TodoApp = React.createClass({ getInitialState: function() { return getTodoState(); }, componentDidMount: function() { TodoStore.addChangeListener(this._onChange); }, componentWillUnmount: function() { TodoStore.removeChangeListener(this._onChange); }, /** * @return {object} */ render: function() { return (
    ); }, _onChange: function() { this.setState(getTodoState()); } }); module.exports = TodoApp; ``` Now we're in our familiar React territory, utilizing React's lifecycle methods. We set up the initial state of this controller-view in getInitialState(), register an event listener in componentDidMount(), and then clean up after ourselves within componentWillUnmount(). We render a containing div and pass down the collection of states we got from the TodoStore. The Header component contains the primary text input for the application, but it does not need to know the state of the store. The MainSection and Footer do need this data, so we pass it down to them. More Views ---------- At a high level, the React component hierarchy of the app looks like this: ```javascript
    ``` If a TodoItem is in edit mode, it will also render a TodoTextInput as a child. Let's take a look at how some of these components display the data they receive as props, and how they communicate through actions with the dispatcher. The MainSection needs to iterate over the collection of to-do items it received from TodoApp to create the list of TodoItems. In the component's render() method, we can do that iteration like so: ```javascript var allTodos = this.props.allTodos; for (var key in allTodos) { todos.push(); } return (
      {todos}
    ); ``` Now each TodoItem can display its own text, and perform actions utilizing its own ID. Explaining all the different actions that a TodoItem can invoke in the TodoMVC example goes beyond the scope of this article, but let's just take a look at the action that deletes one of the to-do items. Here is an abbreviated version of the TodoItem: ```javascript /** @jsx React.DOM */ var React = require('react'); var TodoActions = require('../actions/TodoActions'); var TodoTextInput = require('./TodoTextInput.react'); var TodoItem = React.createClass({ propTypes: { todo: React.PropTypes.object.isRequired }, render: function() { var todo = this.props.todo; return (
  • ); }, _onDestroyClick: function() { TodoActions.destroy(this.props.todo.id); } }); module.exports = TodoItem; ``` With a destroy action available in our library of TodoActions, and a store ready to handle it, connecting the user's interaction with application state changes could not be simpler. We just wrap our onClick handler around the destroy action, provide it with the id, and we're done. Now the user can click the destroy button and kick off the Flux cycle to update the rest of the application. Text input, on the other hand, is just a bit more complicated because we need to hang on to the state of the text input within the React component itself. Let's take a look at how TodoTextInput works. As you'll see below, with every change to the input, React expects us to update the state of the component. So when we are finally ready to save the text inside the input, we will put the value held in the component's state in the action's payload. This is UI state, rather than application state, and keeping that distinction in mind is a good guide for where state should live. All application state should live in the store, while components occasionally hold on to UI state. Ideally, React components preserve as little state as possible. Because TodoTextInput is being used in multiple places within our application, with different behaviors, we'll need to pass the onSave method in as a prop from the component's parent. This allows onSave to invoke different action creator methods depending on where it is used. ```javascript /** @jsx React.DOM */ var React = require('react'); var ReactPropTypes = React.PropTypes; var ENTER_KEY_CODE = 13; var TodoTextInput = React.createClass({ propTypes: { className: ReactPropTypes.string, id: ReactPropTypes.string, placeholder: ReactPropTypes.string, onSave: ReactPropTypes.func.isRequired, value: ReactPropTypes.string }, getInitialState: function() { return { value: this.props.value || '' }; }, /** * @return {object} */ render: function() /*object*/ { return ( ); }, /** * Invokes the callback passed in as onSave, allowing this component to be * used in different ways. */ _save: function() { this.props.onSave(this.state.value); this.setState({ value: '' }); }, /** * @param {object} event */ _onChange: function(/*object*/ event) { this.setState({ value: event.target.value }); }, /** * @param {object} event */ _onKeyDown: function(event) { if (event.keyCode === ENTER_KEY_CODE) { this._save(); } } }); module.exports = TodoTextInput; ``` The Header passes in the onSave method as a prop to allow the TodoTextInput to create new to-do items: ```javascript /** @jsx React.DOM */ var React = require('react'); var TodoActions = require('../actions/TodoActions'); var TodoTextInput = require('./TodoTextInput.react'); var Header = React.createClass({ /** * @return {object} */ render: function() { return (

    todos

    ); }, /** * Event handler called within TodoTextInput. * Defining this here allows TodoTextInput to be used in multiple places * in different ways. * @param {string} text */ _onSave: function(text) { TodoActions.create(text); } }); module.exports = Header; ``` In a different context, such as in editing mode for an existing to-do item, we might pass an onSave callback that invokes `TodoActions.update(text)` instead. Creating Actions with Semantic Methods -------------------------------------- Here is the basic code for the two action creator methods we used above in our views: ```javascript /** * TodoActions */ var AppDispatcher = require('../dispatcher/AppDispatcher'); var TodoConstants = require('../constants/TodoConstants'); var TodoActions = { /** * @param {string} text */ create: function(text) { AppDispatcher.handleViewAction({ actionType: TodoConstants.TODO_CREATE, text: text }); }, /** * @param {string} id */ destroy: function(id) { AppDispatcher.handleViewAction({ actionType: TodoConstants.TODO_DESTROY, id: id }); }, }; module.exports = TodoActions; ``` As you can see, we really would not need to have the helpers AppDispatcher.handleViewAction() or TodoActions.create(). We could, in theory, call AppDispatcher.dispatch() directly and provide a payload. But as our application grows, having these helpers keeps the code clean and semantic. It's just a lot cleaner to write TodoActions.destroy(id) instead of writing a whole lot of things that our TodoItem shouldn't have to know about. The payload produced by the TodoActions.create() will look like: ```javascript { source: 'VIEW_ACTION', action: { type: 'TODO_CREATE', text: 'Write blog post about Flux' } } ``` This payload is provided to the TodoStore through its registered callback. The TodoStore then broadcasts the 'change' event, and the MainSection responds by fetching the new collection of to-do items from the TodoStore and changing its state. This change in state causes the TodoApp component to call its own render() method, and the render() method of all of its descendents. Start Me Up ----------- The bootstrap file of our application is app.js. It simply takes the TodoApp component and renders it in the root element of the application. ```javascript /** @jsx React.DOM */ var React = require('react'); var TodoApp = require('./components/TodoApp.react'); React.renderComponent( , document.getElementById('todoapp') ); ``` Dependency Management in the Dispatcher ---------------------------------------------- As our application grows beyond this simple application to contain multiple stores, we'll need a way to be able to manage dependencies between them. That is, Store A might need to derive data based on Store B's data, so Store A would need Store B to update itself first. This functionality is available with the Dispatcher's waitFor() method. We would call waitFor() within the store's registered callback like so: ```javascript Dispatcher.waitFor([StoreB.dispatcherIndex, StoreC.dispatcherIndex]); // now do things, knowing that both StoreB and StoreC have updated ``` In the source code, you can see that we are interupting the synchronous iteration over the callbacks and starting a new iteration of callbacks based on the array of dispatcherIndexes passed into waitFor(). ```javascript /** * Waits for the callbacks specified to be invoked before continuing execution * of the current callback. This method should only be used by a callback in * response to a dispatched payload. * * @param {array} ids */ waitFor(ids) { invariant( this._isDispatching, 'Dispatcher.waitFor(...): Must be invoked while dispatching.' ); for (var ii = 0; ii < ids.length; ii++) { var id = ids[ii]; if (this._isPending[id]) { invariant( this._isHandled[id], 'Dispatcher.waitFor(...): Circular dependency detected while ' + 'waiting for `%s`.', id ); continue; } invariant( this._callbacks[id], 'Dispatcher.waitFor(...): `%s` does not map to a registered callback.', id ); this._invokeCallback(id); } } ``` Now within the store's callback we can explicitly wait for any dependencies to first update before moving forward. However, if Store A waits for Store B, and B waits for A, then a circular dependency will occur. To help prevent this situation, the dispatcher will throw an error in the browser console if we accidentally have two stores that are waiting for each other. The Future of Flux ------------------ A lot of people ask if Facebook will release Flux as an open source framework. Really, Flux is just an architecture, not a framework. But perhaps a Flux boilerplate project might make sense, if there is enough interest. Please let us know if you'd like to see us do this. Thanks for taking the time to read about how we build client-side applications at Facebook. We hope Flux proves as useful to you as it has to us.
    This page has been moved to the Flux website. [View it there](http://facebook.github.io/flux/docs/todo-list.html). "} {"_id":"q-en-react-4d1f3f7ee457e8f03ce85aeb8da4d1460b2b7154b5ae8c25b50312f600c18365","text":"* `Object.create` – Provided by `es5-sham.js` from [kriskowal's es5-shim](https://github.com/kriskowal/es5-shim). * `console.*` – Only needed when using the unminified build. If you need to polyfill this, try [paulmillr's console-polyfill](https://github.com/paulmillr/console-polyfill). ### Cross-browser Issues Although React is pretty good at abstracting browser differences, some browsers are limited or present quirky behaviors that we couldn't find a workaround. #### onScroll event on IE8 On IE8 the `onScroll` event doesn't bubbles and IE8 doesn't have an API to define handlers to the capturing phase of an event, meaning there is no way for React to listen to these events. Currently a handler to this event is ignored on IE8. See the [onScroll doesn't work in IE8](https://github.com/facebook/react/issues/631) GitHub issue for more information. "} {"_id":"q-en-react-4ea2cc92e2a4b7cb71fe9907df30e1a5477772eb55fe5a3809dd716aa0aa3557","text":"
    __html: converter.makeHtml(this.state.value) __html: marked(this.state.value, {sanitize: true}) }} />
    "} {"_id":"q-en-react-53c950b809034dd826390ae3198a9c2902ccb297a244a64b1d7581372e79ec7d","text":"listeners: null, onChange: _handleChange.bind(inst), }; if (__DEV__) { inst._wrapperState.controlled = props.checked !== undefined || props.value !== undefined; } }, updateWrapper: function(inst) {"} {"_id":"q-en-react-56218fdf9cc09dd82e3b50c9eb6eea83dd72340820597f54d64c39cd47343675","text":"): void { if (__DEV__) { currentHookNameInDev = 'useImperativeHandle'; warning( typeof create === 'function', 'Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null', ); } // TODO: If deps are provided, should we skip comparing the ref itself? const nextDeps ="} {"_id":"q-en-react-564d32c40fb2c0c6d1a71ba75d5b644cc5c140e76114a8e2db89df198345e08a","text":"}); ``` This is a special API that intentionally makes it difficult to insert raw HTML, but for Showdown we'll take advantage of this backdoor. This is a special API that intentionally makes it difficult to insert raw HTML, but for marked we'll take advantage of this backdoor. **Remember:** by using this feature you're relying on Showdown to be secure. **Remember:** by using this feature you're relying on marked to be secure. In this case, we pass `sanitize: true` which tells marked to escape any HTML markup in the source instead of passing it through unchanged. ### Hook up the data model"} {"_id":"q-en-react-573855f4ba070faddf901142e798030a25e3a074f22729a1ab2086903f4dbde1","text":"} } function shouldConstruct(Component) { return Component.prototype && Component.prototype.isReactComponent; } /** * ------------------ The Life-Cycle of a Composite Component ------------------ *"} {"_id":"q-en-react-5a4258bbfee395956fead0d91f28e8323df92fe2dd31dd6193563ef066367fc6","text":"); } function optionPostMount() { var inst = this; ReactDOMOption.postMountWrapper(inst); } // There are so many media events, it makes sense to just // maintain a list rather than create a `trapBubbledEvent` for each var mediaEvents = {"} {"_id":"q-en-react-5c9172670a96392cc46167f8a8df1ac26b06a95215bd7af607434f0d28034026","text":"var ReactServerRendering; var ReactTestUtils; var cx; var reactComponentExpect; var mocks; describe('ReactCompositeComponent', function() { beforeEach(function() { cx = require('cx'); mocks = require('mocks'); reactComponentExpect = require('reactComponentExpect');"} {"_id":"q-en-react-61cf5967e634bfa3a5a4c688733f59ab52171ee5dbc7d9b8cce30bf75b34c564","text":"var didWarnValueNull = false; var didWarnValueDefaultValue = false; var didWarnCheckedDefaultChecked = false; var didWarnControlledToUncontrolled = false; var didWarnUncontrolledToControlled = false; function forceUpdateIfMounted() { if (this._rootNodeID) {"} {"_id":"q-en-react-61f145b3ab1da166c3b36c4f2447fbf632d0505e99e942cb338e005a517d7ad9","text":" const React = window.React; import Fixture from '../../Fixture'; class NumberInputDecimal extends React.Component { state = { value: '.98' }; changeValue = () => { this.setState({ value: '0.98', }); } render() { const {value} = this.state; return (
    {this.props.children}
    { this.setState({value: e.target.value}); }} />
    ); } } export default NumberInputDecimal;
    "} {"_id":"q-en-react-629f2bae2515219f2a8988286eb5e10ea6b69e3b33a4375b0fb5c4b6a8168812","text":"*/ import throttle from 'lodash.throttle'; import { useCallback, useEffect, useLayoutEffect, useMemo, useState, } from 'react'; import {useCallback, useEffect, useLayoutEffect, useState} from 'react'; import {unstable_batchedUpdates as batchedUpdates} from 'react-dom'; import { localStorageGetItem,"} {"_id":"q-en-react-62b87c43085c170f5af869c2956ac32ee733c1e2f3ba0cc686ec53e059925926","text":"assign( ShallowComponentWrapper.prototype, ReactCompositeComponent.Mixin, { _constructComponent: ReactCompositeComponent.Mixin._constructComponentWithoutOwner, _instantiateReactComponent: function(element) { return new NoopInternalComponent(element); },"} {"_id":"q-en-react-64fda69ef058a0fb9761664fa37c4a8f83e35b49c000ec35276e35dc033f6876","text":"hookSourceData.originalSourceAST = sourceMetadata.originalSourceAST; hookSourceData.originalSourceCode = sourceMetadata.originalSourceCode; } else { // TypeScript is the most commonly used typed JS variant so let's default to it // unless we detect explicit Flow usage via the \"@flow\" pragma. const plugin = originalSourceCode.indexOf('@flow') > 0 ? 'flow' : 'typescript'; // TODO (named hooks) Parsing should ideally be done off of the main thread. const originalSourceAST = parse(originalSourceCode, { sourceType: 'unambiguous', plugins: ['jsx', 'typescript'], plugins: ['jsx', plugin], }); hookSourceData.originalSourceAST = originalSourceAST; if (__DEBUG__) {"} {"_id":"q-en-react-66da6191bbac8814b5e9666d30d45da137b3e0958753238084670324181fac75","text":"if (__DEV__) { warnIfValueIsNull(props); var initialValue = inst._wrapperState.initialChecked || inst._wrapperState.initialValue; var defaultValue = props.defaultChecked || props.defaultValue; var controlled = props.checked !== undefined || props.value !== undefined; var owner = inst._currentElement._owner; if ( (initialValue || !inst._wrapperState.controlled) && controlled && !didWarnUncontrolledToControlled ) { warning( false, '%s is changing a uncontrolled input of type %s to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or viceversa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type ); didWarnUncontrolledToControlled = true; } if ( inst._wrapperState.controlled && (defaultValue || !controlled) && !didWarnControlledToUncontrolled ) { warning( false, '%s is changing a controlled input of type %s to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or viceversa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type ); didWarnControlledToUncontrolled = true; } } // TODO: Shouldn't this be getChecked(props)?"} {"_id":"q-en-react-69ea2b9c8c126cc114c69938a50120f37931a1ceb54001bf90d024e380581db0","text":"return this.refs.anch; }, render: function() { var className = cx({'anchorClass': this.props.anchorClassOn}); var className = this.props.anchorClassOn ? 'anchorClass' : ''; return this.props.renderAnchor ? : ;"} {"_id":"q-en-react-6af9c9ac80c36e79884e6f136139b9e2d2c79a3d34bbe49bb089df5eda3f64f8","text":"} effect = effect.nextEffect; } while (effect !== null); if (__DEV__) { resetCurrentFiber(); } isRendering = previousIsRendering;"} {"_id":"q-en-react-6c96477edc04d8ccf811044b5c114672baa03bbd04571699ae1b72f737387ae0","text":"\"node\": \">=0.10.0\" }, \"peerDependencies\": { \"envify\": \"~1.0.1\" \"envify\": \"~1.2.0\" }, \"browserify\": { \"transform\": [\"envify\"]"} {"_id":"q-en-react-6d7efc2d7e5693dc32926e539a51b1f288ada36a93d0b3cbcee04388e298e1c1","text":" name: DevTools Check for bug repro on: issues: types: [opened, edited] issue_comment: types: [created, edited] jobs: check-repro: runs-on: ubuntu-latest steps: - uses: actions/github-script@v3 with: github-token: ${{ secrets.GITHUB_TOKEN }} script: | const URL_REGEXP = /### Website or app[rn]+([^#]+)###/m; const REPRO_STEPS_REGEXP = /### Repro steps[rn]+([^#]+)###/m; const LABEL_NEEDS_MORE_INFORMATION = \"Resolution: Needs More Information\"; const LABEL_UNCONFIRMED = \"Status: Unconfirmed\"; function debug(...args) { core.info(args.map(JSON.stringify).join(' ')); } if (context.payload.comment) { debug('Ignoring comment update.'); return; } const user = context.payload.sender.login; const issue = context.payload.issue; const body = issue.body; const urlMatch = body.match(URL_REGEXP); const reproStepsMatch = body.match(REPRO_STEPS_REGEXP); const url = urlMatch !== null ? urlMatch[1].trim() : null; const reproSteps = reproStepsMatch !== null ? reproStepsMatch[1].trim() : null; if (!url || !reproSteps) { debug('This issue is not a DevTools bug report.'); return; } debug(`found URL \"${url}\"`); debug(`found repro steps \"${reproSteps}\"`); function formatComment(comment) { return comment .split(\"n\") .map((line) => line.trim()) .join(\"n\") .trim(); } async function getGitHubActionComments() { debug(`Loading existing comments...`); const comments = await github.issues.listComments({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, }); return comments.data.filter(comment => { debug(`comment by user: \"${comment.user.login}\"`); return comment.user.login === 'github-actions[bot]'; }); } async function getIssueLabels() { const issues = await github.issues.listLabelsOnIssue({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, }); return issues.data; } async function closeWithComment(comment) { if (issue.state !== 'open') { debug(`Issue is not open`); return; } const labels = await getIssueLabels(); const label = labels.find(label => label.name === LABEL_UNCONFIRMED); if (!label) { debug(`Issue was not opened via DevTools bug report template`); return; } const comments = await getGitHubActionComments(); if (comments.length > 0) { debug(`Already commented on issue; won't comment again`); return; } debug(`Missing required information`); await github.issues.addLabels({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, labels: [LABEL_NEEDS_MORE_INFORMATION], }); await github.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, body: formatComment(comment), }); await github.issues.update({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, state: 'closed', }); } async function openWithComment(comment) { if (issue.state !== 'closed') { debug(`Issue is already open`); return; } const labels = await getIssueLabels(); const label = labels.find(label => label.name === LABEL_NEEDS_MORE_INFORMATION); if (!label) { debug(`Issue was not tagged as needs information`); return; } const comments = await getGitHubActionComments(); if (comments.length === 0) { debug(`Issue was closed by someone else; won't reopen`); return; } debug(`Re-opening closed issue`); await github.issues.removeLabel({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, name: LABEL_NEEDS_MORE_INFORMATION, }); await github.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, body: formatComment(comment), }); await github.issues.update({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, state: 'open', }); } const PROBABLY_NOT_A_URL_REGEX = /(^Chrome$|^Firefox$| Website)/i; const COMMENT_HEADER = ` @${user}: We're sorry you've seen this error. ❤️ `.trim(); const COMMENT_FOOTER = ` Please help us by providing a link to a CodeSandbox (https://codesandbox.io/s/new), a repository on GitHub, or a minimal code example that reproduces the problem. (Screenshots or videos can also be helpful if they help provide context on how to repro the bug.) Here are some tips for providing a minimal example: https://stackoverflow.com/help/mcve Issues without repros are automatically closed but we will re-open if you update with repro info. `.trim(); if (url.includes(\"/localhost\")) { closeWithComment(` ${COMMENT_HEADER} Unfortunately the URL you provided (\"localhost\") is not publicly accessible. (This means that we will not be able to reproduce the problem you're reporting.) ${COMMENT_FOOTER} `); } else if (url.length < 10 || url.match(PROBABLY_NOT_A_URL_REGEX)) { closeWithComment(` ${COMMENT_HEADER} It looks like you forgot to specify a valid URL. (This means that we will not be able to reproduce the problem you're reporting.) ${COMMENT_FOOTER} `); } else if (reproSteps.length < 25) { closeWithComment(` ${COMMENT_HEADER} Unfortunately, it doesn't look like this issue has enough info for one of us to reproduce and fix it though. ${COMMENT_FOOTER} `); } else { openWithComment(` Thank you for providing repro steps! Re-opening issue now for triage. `); } "} {"_id":"q-en-react-6e3497be782356eca9011a06a8cd1c87499f85f6464b0bdc794757dfabda927b","text":"form: MUST_USE_ATTRIBUTE, formNoValidate: HAS_BOOLEAN_VALUE, frameBorder: MUST_USE_ATTRIBUTE, headers: null, height: MUST_USE_ATTRIBUTE, hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, href: null,"} {"_id":"q-en-react-6fce99540fe2507e709fc7d4026e8b8ac6c9e78ed3b146299a2c5e136f2c2688","text":"override: - ./scripts/circleci/test_entry_point.sh: parallel: true deployment: staging: branch: /.*/ commands: - ./scripts/circleci/upload_build.sh "} {"_id":"q-en-react-72577d740fc290177bb7e5adeeb330919d60705f76653a48804ee839b8149780","text":"workInProgress: Fiber, priorityLevel: PriorityLevel, ): void { if (__DEV__) { checkClassInstance(workInProgress); } const instance = workInProgress.stateNode; const state = instance.state || null;"} {"_id":"q-en-react-742257d9fdf00fe5542365d2d213b494254075b95cbdf3c8ff69d0774e53a57c","text":" --- layout: none --- {{ site.name }} {{ site.description }} {{ site.url }}{{ site.baseurl }} {% for post in site.posts limit:10 %} {{ post.title | xml_escape }} {{ post.content | xml_escape }} {{ post.date | date_to_xmlschema }} {{ site.url }}{{ site.baseurl }}{{ post.url }} {{ site.url }}{{ site.baseurl }}{{ post.url }} {% endfor %} "} {"_id":"q-en-react-78fd6b64b88a3c6c8369f852efab0b0789a8d90d184d63c629be6d9685e59d88","text":"export function createCache(invalidator: () => mixed): Cache { const resourceMap: ResourceMap = new Map(); function accessRecord(resourceType: any, key: K): Record { function accessRecord(resourceType: any, key: K): Record { if (__DEV__) { warning( typeof resourceType !== 'string' && typeof resourceType !== 'number',"} {"_id":"q-en-react-7caf4e4456c40c08e954ae9b6ef53241c0e0d73a33dcd7ccac6cdfd5af08020f","text":"* @param [string ...] Variable list of classNames in the string case. * @return string Renderable space-separated CSS className. */ 'use strict'; var warning = require('warning'); var warned = false; function cx(classNames) { if (__DEV__) { warning( warned, 'React.addons.classSet will be deprecated in a future version. See ' + 'http://fb.me/react-addons-classset' ); warned = true; } if (typeof classNames == 'object') { return Object.keys(classNames).filter(function(className) { return classNames[className];"} {"_id":"q-en-react-7dc7a35ee6bbd0b5ab9b398962b134075cba411420398775f54f389be456d4e5","text":"); }); it('should not enumerate enumerable numbers (#4776)', function() { /*eslint-disable no-extend-native */ Number.prototype['@@iterator'] = function() { throw new Error('number iterator called'); }; /*eslint-enable no-extend-native */ try { var instance = (
    {5} {12} {13}
    ); var traverseFn = jasmine.createSpy(); traverseAllChildren(instance.props.children, traverseFn, null); expect(traverseFn.calls.length).toBe(3); expect(traverseFn).toHaveBeenCalledWith( null, 5, '.0' ); expect(traverseFn).toHaveBeenCalledWith( null, 12, '.1' ); expect(traverseFn).toHaveBeenCalledWith( null, 13, '.2' ); } finally { delete Number.prototype['@@iterator']; } });
    });"} {"_id":"q-en-react-82fb1ad4d26546d89090af49450fd3359c55089d151b9211925e07b0a04b5e5f","text":" /** * Copyright 2013-2015, 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. * * @emails react-core */ 'use strict'; var React; var ReactDOM; var ReactTestUtils; describe('ReactEventIndependence', function() { beforeEach(function() { require('mock-modules').dumpCache(); React = require('React'); ReactDOM = require('ReactDOM'); ReactTestUtils = require('ReactTestUtils'); }); it('does not crash with other react inside', function() { var clicks = 0; var div = ReactTestUtils.renderIntoDocument(
    clicks++} dangerouslySetInnerHTML={{ __html: '
    ', }} /> ); ReactTestUtils.SimulateNative.click(div.firstChild); expect(clicks).toBe(1); }); it('does not crash with other react outside', function() { var clicks = 0; var outer = document.createElement('div'); outer.setAttribute('data-reactid', '.z'); var inner = ReactDOM.render( , outer ); ReactTestUtils.SimulateNative.click(inner); expect(clicks).toBe(1); }); it('does not when event fired on unmounted tree', function() { var clicks = 0; var container = document.createElement('div'); var button = ReactDOM.render( , container ); // Now we unmount the component, as if caused by a non-React event handler // for the same click we're about to simulate, like closing a layer: ReactDOM.unmountComponentAtNode(container); ReactTestUtils.SimulateNative.click(button); // Since the tree is unmounted, we don't dispatch the click event. expect(clicks).toBe(0); }); });
    "} {"_id":"q-en-react-84484ad3445bd537ebd4e8016e4031fbabb99d6375bbfd8bb836f5638367c868","text":"describe('ReactDOMComponent', function() { var React; var ReactDOM; var ReactDOMFeatureFlags; var ReactDOMServer; beforeEach(function() { jest.resetModuleRegistry(); React = require('React'); ReactDOMFeatureFlags = require('ReactDOMFeatureFlags') ReactDOM = require('ReactDOM'); ReactDOMServer = require('ReactDOMServer'); });"} {"_id":"q-en-react-84a7a3abb70646181d366d0a5d824819f632f0ab5a7930df3b6261d9aa212d25","text":"- Gemfile.lock - README.md - Rakefile url: http://facebook.github.io baseurl: /react permalink: /blog/:year/:month/:day/:title.html"} {"_id":"q-en-react-860df2ea2fb26adbbf66186efc91a81b51fc17fdec5d6e45768d01ac71438b82","text":"expect(console.error.argsForCall.length).toBe(1); }); it('should warn if controlled input switches to uncontrolled', function() { var stub = ; var container = document.createElement('div'); ReactDOM.render(stub, container); ReactDOM.render(, container); expect(console.error.argsForCall.length).toBe(1); expect(console.error.argsForCall[0][0]).toContain( 'A component is changing a controlled input of type text to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or viceversa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components' ); }); it('should warn if controlled input switches to uncontrolled with defaultValue', function() { var stub = ; var container = document.createElement('div'); ReactDOM.render(stub, container); ReactDOM.render(, container); expect(console.error.argsForCall.length).toBe(1); expect(console.error.argsForCall[0][0]).toContain( 'A component is changing a controlled input of type text to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or viceversa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components' ); }); it('should warn if uncontrolled input switches to controlled', function() { var stub = ; var container = document.createElement('div'); ReactDOM.render(stub, container); ReactDOM.render(, container); expect(console.error.argsForCall.length).toBe(1); expect(console.error.argsForCall[0][0]).toContain( 'A component is changing a uncontrolled input of type text to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or viceversa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components' ); }); it('should warn if controlled checkbox switches to uncontrolled', function() { var stub = ; var container = document.createElement('div'); ReactDOM.render(stub, container); ReactDOM.render(, container); expect(console.error.argsForCall.length).toBe(1); expect(console.error.argsForCall[0][0]).toContain( 'A component is changing a controlled input of type checkbox to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or viceversa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components' ); }); it('should warn if controlled checkbox switches to uncontrolled with defaultChecked', function() { var stub = ; var container = document.createElement('div'); ReactDOM.render(stub, container); ReactDOM.render(, container); expect(console.error.argsForCall.length).toBe(1); expect(console.error.argsForCall[0][0]).toContain( 'A component is changing a controlled input of type checkbox to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or viceversa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components' ); }); it('should warn if uncontrolled checkbox switches to controlled', function() { var stub = ; var container = document.createElement('div'); ReactDOM.render(stub, container); ReactDOM.render(, container); expect(console.error.argsForCall.length).toBe(1); expect(console.error.argsForCall[0][0]).toContain( 'A component is changing a uncontrolled input of type checkbox to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or viceversa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components' ); }); it('should warn if controlled radio switches to uncontrolled', function() { var stub = ; var container = document.createElement('div'); ReactDOM.render(stub, container); ReactDOM.render(, container); expect(console.error.argsForCall.length).toBe(1); expect(console.error.argsForCall[0][0]).toContain( 'A component is changing a controlled input of type radio to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or viceversa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components' ); }); it('should warn if controlled radio switches to uncontrolled with defaultChecked', function() { var stub = ; var container = document.createElement('div'); ReactDOM.render(stub, container); ReactDOM.render(, container); expect(console.error.argsForCall.length).toBe(1); expect(console.error.argsForCall[0][0]).toContain( 'A component is changing a controlled input of type radio to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or viceversa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components' ); }); it('should warn if uncontrolled radio switches to controlled', function() { var stub = ; var container = document.createElement('div'); ReactDOM.render(stub, container); ReactDOM.render(, container); expect(console.error.argsForCall.length).toBe(1); expect(console.error.argsForCall[0][0]).toContain( 'A component is changing a uncontrolled input of type radio to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or viceversa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components' ); }); it('sets type before value always', function() { var log = []; var originalCreateElement = document.createElement;"} {"_id":"q-en-react-959b0d37fd4cb58abebfcec76e769684d5d4d7a4e7e36df8993b9b7d4def009d","text":"const [parsedValue, setParsedValue] = useState(initialValue); const [isValid, setIsValid] = useState(initialIsValid); const reset = useCallback(() => { setEditableValue(smartStringify(initialValue)); setParsedValue(initialValue); setIsValid(initialIsValid); }, []); const reset = useCallback( () => { setEditableValue(smartStringify(initialValue)); setParsedValue(initialValue); setIsValid(initialIsValid); }, [initialValue, initialIsValid], ); const update = useCallback(newValue => { let isNewValueValid = false;"} {"_id":"q-en-react-9888ae1c7238e1270c14b9088923185b7af115382f48ae3c3e0a5b9f8dbc74c7","text":"disableInputAttributeSyncing, enableTrustedTypesIntegration, deferPassiveEffectCleanupDuringUnmount, warnAboutShorthandPropertyCollision, } = require('ReactFeatureFlags'); // In www, we have experimental support for gathering data"} {"_id":"q-en-react-9ba6921f4a8333ed819930489bb5d73b9a552824aaa3b08f3b4403f55db3f94e","text":"// TODO: we should warn here. }); }); describe('checked inputs without a value property', function() { // In absence of a value, radio and checkboxes report a value of \"on\". // Between 16 and 16.2, we assigned a node's value to it's current // value in order to \"dettach\" it from defaultValue. This had the unfortunate // side-effect of assigning value=\"on\" to radio and checkboxes it('does not add \"on\" in absence of value on a checkbox', function() { const container = document.createElement('div'); ReactDOM.render( , container, ); const node = container.firstChild; expect(node.value).toBe('on'); expect(node.hasAttribute('value')).toBe(false); }); it('does not add \"on\" in absence of value on a radio', function() { const container = document.createElement('div'); ReactDOM.render(, container); const node = container.firstChild; expect(node.value).toBe('on'); expect(node.hasAttribute('value')).toBe(false); }); }); });"} {"_id":"q-en-react-9bab5275716e0c80daba4826734d2ffe2700ac602b62960aaae5e4295f7e593c","text":"\"benchmark\": \"~1.0.0\", \"browserify\": \"~3.20.0\", \"coverify\": \"~1.0.4\", \"envify\": \"~1.0.1\", \"envify\": \"~1.2.0\", \"es3ify\": \"~0.1.2\", \"es5-shim\": \"~2.3.0\", \"grunt\": \"~0.4.2\","} {"_id":"q-en-react-9d45934101cb246de773a499821a35ddd7d6a1ada72305a31979c7b3af0a7650","text":"charSet: null, challenge: null, checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, cite: null, classID: null, className: null, cols: HAS_POSITIVE_NUMERIC_VALUE,"} {"_id":"q-en-react-9df92b0e5d61e86c236bdc38559c41b06e0c72a3c7e46abcf312215f2ca96a57","text":"

    A Component Using External Plugins

    React is flexible and provides hooks that allow you to interface with other libraries and frameworks. This example uses Showdown, an external other libraries and frameworks. This example uses **marked**, an external Markdown library, to convert the textarea's value in real-time.


    "} {"_id":"q-en-react-a13c5626a6a09da83ac4356b8f1bbf8d53ddca0a5ea240306c3b288a58fd84c5","text":"export const disableJavaScriptURLs = false; export const disableInputAttributeSyncing = false; export const exposeConcurrentModeAPIs = __EXPERIMENTAL__; export const warnAboutShorthandPropertyCollision = false; export const warnAboutShorthandPropertyCollision = true; export const enableSchedulerDebugging = false; export const enableDeprecatedFlareAPI = false; export const enableFundamentalAPI = false;"} {"_id":"q-en-react-a16d084bfe68f2f91f3fb88388c4a1abb2300f395e049656f487a78845a3a100","text":"expect(console.error.argsForCall.length).toBe(0); }); it('should not enumerate enumerable numbers (#4776)', function() { /*eslint-disable no-extend-native */ Number.prototype['@@iterator'] = function() { throw new Error('number iterator called'); }; /*eslint-enable no-extend-native */ try { void (
    {5} {12} {13}
    ); } finally { delete Number.prototype['@@iterator']; } });
    });"} {"_id":"q-en-react-a2fc3bc3907ab56ec8f7ace19e9f7f30d27881628ed908f1ffc0fab543d229ae","text":"]); }); it('warns for bad useImperativeHandle first arg', () => { const {useImperativeHandle} = React; function App() { useImperativeHandle({ focus() {}, }); return null; } expect(() => { expect(() => { ReactTestRenderer.create(); }).toThrow('create is not a function'); }).toWarnDev([ 'Expected useImperativeHandle() first argument to either be a ' + 'ref callback or React.createRef() object. ' + 'Instead received: an object with keys {focus}.', 'Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: undefined.', ]); }); it('warns for bad useImperativeHandle second arg', () => { const {useImperativeHandle} = React; const App = React.forwardRef((props, ref) => { useImperativeHandle(ref, { focus() {}, }); return null; }); expect(() => { ReactTestRenderer.create(); }).toWarnDev([ 'Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: object.', ]); }); // https://github.com/facebook/react/issues/14022 it('works with ReactDOMServer calls inside a component', () => { const {useState} = React;"} {"_id":"q-en-react-a5393811d28ac96fe3b6ed5863705d78a713b336601971def322c7a1ebba147a","text":" "} {"_id":"q-en-react-ad7d3d246a9829d2994dd8fea4e6b62a9c0b15d2f6d4546f09c02ad0a9242ced","text":"inst._wrapperState = {selected: selected}; }, postMountWrapper: function(inst) { // value=\"\" should make a value attribute (#6219) var props = inst._currentElement.props; if (props.value != null) { var node = ReactDOMComponentTree.getNodeFromInstance(inst); node.setAttribute('value', props.value); } }, getNativeProps: function(inst, props) { var nativeProps = Object.assign({selected: undefined, children: undefined}, props);"} {"_id":"q-en-react-ae331086cfe1a2af73bc3f843af0a01084523a7a996aabb5b518a7aac3e1d250","text":" module Jekyll module SidebarItemFilter def sidebar_item_link(item) pageID = @context.registers[:page][\"id\"] itemID = item[\"id\"] href = item[\"href\"] || \"/react/docs/#{itemID}.html\" className = pageID == itemID ? ' class=\"active\"' : '' return \"#{item[\"title\"]}\" end end end Liquid::Template.register_filter(Jekyll::SidebarItemFilter) "} {"_id":"q-en-react-b10e45d1acff1b55b310a3b4ef3351361d8357d3dd8a8d2e3fb1bc831406617e","text":"miss: A => Promise, missArg: A, ): void { const record: Record = accessRecord(resourceType, key); const record: Record = accessRecord(resourceType, key); switch (record.status) { case Empty: // Warm the cache."} {"_id":"q-en-react-b14c69f347268ede884dfa0030412349be926bb0fab35b9484b9dd061e0eeebf","text":"// Control this behavior with a flag to support 16.6 minor releases in the meanwhile. export const exposeConcurrentModeAPIs = __EXPERIMENTAL__; export const warnAboutShorthandPropertyCollision = false; export const warnAboutShorthandPropertyCollision = true; // Experimental React Flare event system and event components support. export const enableDeprecatedFlareAPI = false;"} {"_id":"q-en-react-b1519f314bfffaf415cf930144d222c8a1f05b3be25746cc6b8ac66f08522fa8","text":" ``` Next, let's convert the comment text to Markdown and output it: ```javascript{2,10} ```javascript{9} // tutorial6.js var converter = new Showdown.converter(); var Comment = React.createClass({ render: function() { return ("} {"_id":"q-en-react-b6827fc9142f3ab746d5d6546f18c03baea8ee225bdbd9deaff9a0764cc695e8","text":"export const replayFailedUnitOfWorkWithInvokeGuardedCallback = false; export const warnAboutDeprecatedLifecycles = true; export const warnAboutShorthandPropertyCollision = false; export const disableLegacyContext = false; export const warnAboutStringRefs = false; export const warnAboutDefaultPropsOnFunctionComponents = false;"} {"_id":"q-en-react-b79fd4faf80d63764211b4876b9981357b248a77ab807f7d175019e974fdb1ab","text":"expect(store).toMatchSnapshot('2: add host nodes'); }); // This test is not the same cause as what's reported on GitHub, // but the resulting behavior (owner mounting after descendant) is the same. // Thec ase below is admittedly contrived and relies on side effects. // I'mnot yet sure of how to reduce the GitHub reported production case to a test though. // See https://github.com/facebook/react/issues/21445 it('should handle when a component mounts before its owner', () => { const promise = new Promise(resolve => {}); let Dynamic = null; const Owner = () => { Dynamic = ; throw promise; }; const Parent = () => { return Dynamic; }; const Child = () => null; const container = document.createElement('div'); act(() => ReactDOM.render( <> , container, ), ); expect(store).toMatchInlineSnapshot(` [root] `); }); describe('collapseNodesByDefault:false', () => { beforeEach(() => { store.collapseNodesByDefault = false;"} {"_id":"q-en-react-b8552e574aa63e00ff7351642a17caf16de211243d02c96e8eb0e205f2b901df","text":"var MARKDOWN_COMPONENT = ` var converter = new Showdown.converter(); var MarkdownEditor = React.createClass({ getInitialState: function() { return {value: 'Type some *markdown* here!'};"} {"_id":"q-en-react-c180d2073c9a432e64839c80e749b4f682291c311d8dcc032fc4a5941f414aaf","text":"--- id: flux-overview title: Flux Application Architecture next: flux-todo-list.html --- Flux is the application architecture that Facebook uses for building client-side web applications. It complements React's composable view components by utilizing a unidirectional data flow. It's more of a pattern rather than a formal framework, and you can start using Flux immediately without a lot of new code.
    Flux applications have three major parts: the dispatcher, the stores, and the views (React components). These should not be confused with Model-View-Controller. Controllers do exist in a Flux application, but they are controller-views — views often found at the top of the hierarchy that retrieve data from the stores and pass this data down to their children. Additionally, actions — dispatcher helper methods — are often used to support a semantic dispatcher API. It can be useful to think of them as a fourth part of the Flux update cycle. Flux eschews MVC in favor of a unidirectional data flow. When a user interacts with a React view, the view propagates an action through a central dispatcher, to the various stores that hold the application's data and business logic, which updates all of the views that are affected. This works especially well with React's declarative programming style, which allows the store to send updates without specifying how to transition views between states. We originally set out to deal correctly with derived data: for example, we wanted to show an unread count for message threads while another view showed a list of threads, with the unread ones highlighted. This was difficult to handle with MVC — marking a single thread as read would update the thread model, and then also need to update the unread count model. These dependencies and cascading updates often occur in a large MVC application, leading to a tangled weave of data flow and unpredictable results. Control is inverted with stores: the stores accept updates and reconcile them as appropriate, rather than depending on something external to update its data in a consistent way. Nothing outside the store has any insight into how it manages the data for its domain, helping to keep a clear separation of concerns. This also makes stores more testable than models, especially since stores have no direct setter methods like `setAsRead()`, but instead have only an input point for the payload, which is delivered through the dispatcher and originates with actions. ## Structure and Data Flow Data in a Flux application flows in a single direction, in a cycle:
     Views ---> (actions) ----> Dispatcher ---> (registered callback) ---> Stores -------+ Ʌ                                                                                   | |                                                                                   V +-- (Controller-Views \"change\" event handlers) ---- (Stores emit \"change\" events) --+ 
    A unidirectional data flow is central to the Flux pattern, and in fact Flux takes its name from the Latin word for flow. In the above diagram, the dispatcher, stores and views are independent nodes with distinct inputs and outputs. The actions are simply discrete, semantic helper functions that facilitate passing data to the dispatcher. All data flows through the dispatcher as a central hub. Actions most often originate from user interactions with the views, and are nothing more than a call into the dispatcher. The dispatcher then invokes the callbacks that the stores have registered with it, effectively dispatching the data payload contained in the actions to all stores. Within their registered callbacks, stores determine which actions they are interested in, and respond accordingly. The stores then emit a \"change\" event to alert the controller-views that a change to the data layer has occurred. Controller-views listen for these events and retrieve data from the stores in an event handler. The controller-views call their own `render()` method via `setState()` or `forceUpdate()`, updating themselves and all of their children. This structure allows us to reason easily about our application in a way that is reminiscent of functional reactive programming, or more specifically data-flow programming or flow-based programming, where data flows through the application in a single direction — there are no two-way bindings. Application state is maintained only in the stores, allowing the different parts of the application to remain highly decoupled. Where dependencies do occur between stores, they are kept in a strict hierarchy, with synchronous updates managed by the dispatcher. We found that two-way data bindings led to cascading updates, where changing one object led to another object changing, which could also trigger more updates. As applications grew, these cascading updates made it very difficult to predict what would change as the result of one user interaction. When updates can only change data within a single round, the system as a whole becomes more predictable. Let's look at the various parts of the Flux update cycle up close. A good place to start is the dispatcher. ### A Single Dispatcher The dispatcher is the central hub that manages all data flow in a Flux application. It is essentially a registry of callbacks into the stores. Each store registers itself and provides a callback. When the dispatcher responds to an action, all stores in the application are sent the data payload provided by the action via the callbacks in the registry. As an application grows, the dispatcher becomes more vital, as it can manage dependencies between stores by invoking the registered callbacks in a specific order. Stores can declaratively wait for other stores to finish updating, and then update themselves accordingly. ### Stores Stores contain the application state and logic. Their role is somewhat similar to a model in a traditional MVC, but they manage the state of many objects — they are not instances of one object. Nor are they the same as Backbone's collections. More than simply managing a collection of ORM-style objects, stores manage the application state for a particular __domain__ within the application. For example, Facebook's [Lookback Video Editor](https://facebook.com/lookback/edit) utilized a TimeStore that kept track of the playback time position and the playback state. On the other hand, the same application's ImageStore kept track of a collection of images. The TodoStore in our [TodoMVC example](https://github.com/facebook/flux/tree/master/examples/flux-todomvc) is similar in that it manages a collection of to-do items. A store exhibits characteristics of both a collection of models and a singleton model of a logical domain. As mentioned above, a store registers itself with the dispatcher and provides it with a callback. This callback receives the action's data payload as a parameter. The payload contains a type attribute, identifying the action's type. Within the store's registered callback, a switch statement based on the action's type is used to interpret the payload and to provide the proper hooks into the store's internal methods. This allows an action to result in an update to the state of the store, via the dispatcher. After the stores are updated, they broadcast an event declaring that their state has changed, so the views may query the new state and update themselves. ### Views and Controller-Views React provides the kind of composable views we need for the view layer. Close to the top of the nested view hierarchy, a special kind of view listens for events that are broadcast by the stores that it depends on. One could call this a controller-view, as it provides the glue code to get the data from the stores and to pass this data down the chain of its descendants. We might have one of these controller-views governing any significant section of the page. When it receives the event from the store, it first requests the new data it needs via the stores' public getter methods. It then calls its own `setState()` or `forceUpdate()` methods, causing its `render()` method and the `render()` method of all its descendants to run. We often pass the entire state of the store down the chain of views in a single object, allowing different descendants to use what they need. In addition to keeping the controller-like behavior at the top of the hierarchy, and thus keeping our descendant views as functionally pure as possible, passing down the entire state of the store in a single object also has the effect of reducing the number of props we need to manage. Occasionally we may need to add additional controller-views deeper in the hierarchy to keep components simple. This might help us to better encapsulate a section of the hierarchy related to a specific data domain. Be aware, however, that controller-views deeper in the hierarchy can violate the singular flow of data by introducing a new, potentially conflicting entry point for the data flow. In making the decision of whether to add a deep controller-view, balance the gain of simpler components against the complexity of multiple data updates flowing into the hierarchy at different points. These multiple data updates can lead to odd effects, with React's render method getting invoked repeatedly by updates from different controller-views, potentially increasing the difficulty of debugging. ### Actions The dispatcher exposes a method that allows a view to trigger a dispatch to the stores, and to include a payload of data, or an action. The action construction may be wrapped into a semantic helper method which sends the payload to the dispatcher. For example, we may want to change the text of a to-do item in a to-do list application. We would create an action with a function signature like `updateText(todoId, newText)` in our `TodoActions` module. This method may be invoked from within our views' event handlers, so we can call it in response to a user action. This action method also adds the action type to the payload, so that when the payload is interpreted in the store, it can respond appropriately to a payload with a particular action type. In our example, this type might be named something like `TODO_UPDATE_TEXT`. Actions may also come from other places, such as the server. This happens, for example, during data initialization. It may also happen when the server returns an error code or when the server has updates to provide to the application. We'll talk more about server actions in a future article. In this post we're only concerned with the basics of the data flow. ### What About that Dispatcher? As mentioned earlier, the dispatcher is also able to manage dependencies between stores. This functionality is available through the `waitFor()` method within the Dispatcher class. We did not need to use this method within the extremely simple [TodoMVC application](https://github.com/facebook/flux/tree/master/examples/flux-todomvc), but we have included it [in the example dispatcher](https://github.com/facebook/flux/blob/master/examples/flux-todomvc/js/dispatcher/Dispatcher.js#L110) as an example of what a dispatcher should be able to do in a larger, more complex application. Within the TodoStore's registered callback we could explicitly wait for any dependencies to first update before moving forward: ```javascript case 'TODO_CREATE': Dispatcher.waitFor([ PrependedTextStore.dispatcherIndex, YetAnotherStore.dispatcherIndex ], function() { TodoStore.create(PrependedTextStore.getText() + ' ' + action.text); TodoStore.emit('change'); }); break; ``` The arguments for `waitFor()` are an array of dispatcher registry indexes, and a final callback to invoke after the callbacks at the given indexes have completed. Thus the store that is invoking `waitFor()` can depend on the state of another store to inform how it should update its own state. A problem arises if we create circular dependencies. If Store A waits for Store B, and B waits for A, then we'll have a very bad situation on our hands. We'll need a more robust dispatcher that flags these circular dependencies with console errors, and this is not easily accomplished with promises. Unfortunately, that's a bit beyond the scope of this documentation. In the future we hope to cover how to build a more robust dispatcher and how to initialize, update, and save the state of the application with persistent data, like a web service API.
    This page has been moved to the Flux website. [View it there](http://facebook.github.io/flux/docs/overview.html). "} {"_id":"q-en-react-c22c464c7d55f9d798a26062cebc144f1ff8abb669d9574b95efa6dee506e9d1","text":"}); }); it('does change the string \".98\" to \"0.98\" with no change handler', () => { class Stub extends React.Component { state = { value: '.98', }; render() { return ; } } var stub = ReactTestUtils.renderIntoDocument(); var node = ReactDOM.findDOMNode(stub); stub.setState({value: '0.98'}); expect(node.value).toEqual('0.98'); }); it('should display `defaultValue` of number 0', () => { var stub = ; stub = ReactTestUtils.renderIntoDocument(stub);"} {"_id":"q-en-react-c4ba2890487fd458ca56ee81ab4b26349f9cfe421c3e229f3999aca23440fcd9","text":" {typeof overrideValueFn === 'function' ? ( dataType={type} initialValue={value} overrideValueFn={overrideValueFn} path={[]} value={value} /> ) : ( // $FlowFixMe Cannot create span element because in property children"} {"_id":"q-en-react-c50a9f5c129c7397dd5315fb1e3335912e6fb5d947c794b5c5be23ade37c505d","text":"type EditableValueProps = {| className?: string, dataType: string, initialValue: any, overrideValueFn: OverrideValueFn, path: Array,"} {"_id":"q-en-react-c780745c5b610a34072fad7ebed437954392d35a3feb6e40cc4c6ef47b0505e1","text":"'use strict'; var ReactChildren = require('ReactChildren'); var ReactDOMComponentTree = require('ReactDOMComponentTree'); var ReactDOMSelect = require('ReactDOMSelect'); var warning = require('warning');"} {"_id":"q-en-react-ccaceaa371777e0c90616ab74b91c66666e28c431b53df8411231ddea5909a3a","text":"utils.catchup(openingElement.range[0], state, trimLeft); if (nameObject.namespace) { throw new Error( 'Namespace tags are not supported. ReactJSX is not XML.'); var isFallbackTag = false; if (nameObject.type === Syntax.XJSIdentifier) { if (nameObject.namespace) { throw new Error( 'Namespace tags are not supported. ReactJSX is not XML.'); } isFallbackTag = FALLBACK_TAGS.hasOwnProperty(nameObject.name); } var isFallbackTag = FALLBACK_TAGS.hasOwnProperty(nameObject.name); utils.append( (isFallbackTag ? jsxObjIdent + '.' : '') + (nameObject.name) + '(', state ); utils.append(isFallbackTag ? jsxObjIdent + '.' : '', state); utils.move(nameObject.range[0], state); utils.catchup(nameObject.range[1], state); utils.move(nameObject.range[1], state); utils.append('(', state); var hasAttributes = attributesObject.length;"} {"_id":"q-en-react-cdc1efbe4b0ba6d813c962d86ff94a053c144e2ed1d5c99f425f4664d2d2d276","text":"return () => refCallback(null); } else if (ref !== null && ref !== undefined) { const refObject = ref; if (__DEV__) { warning( refObject.hasOwnProperty('current'), 'Expected useImperativeHandle() first argument to either be a ' + 'ref callback or React.createRef() object. Instead received: %s.', 'an object with keys {' + Object.keys(refObject).join(', ') + '}', ); } const inst = create(); refObject.current = inst; return () => {"} {"_id":"q-en-react-cf4a80ca6ee0af40e77b4ffb70e4bdc2add38fd88359077b4d6604ae45634db9","text":"nextEffect = nextEffect.nextEffect; } if (__DEV__) { resetCurrentFiber(); } } function commitPassiveEffects(root: FiberRoot, firstEffect: Fiber): void {"} {"_id":"q-en-react-d3ae4a1acc61fdbcb7663668bbb60e23452eda1e31b97abf9aacc538395b6a97","text":" /** * marked - a markdown parser * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed) * https://github.com/chjj/marked */ (function(){var block={newline:/^n+/,code:/^( {4}[^n]+n*)+/,fences:noop,hr:/^( *[-*_]){3,} *(?:n+|$)/,heading:/^ *(#{1,6}) *([^n]+?) *#* *(?:n+|$)/,nptable:noop,lheading:/^([^n]+)n *(=|-){2,} *(?:n+|$)/,blockquote:/^( *>[^n]+(n(?!def)[^n]+)*n*)+/,list:/^( *)(bull) [sS]+?(?:hr|def|n{2,}(?! )(?!1bull )n*|s*$)/,html:/^ *(?:comment|closed|closing) *(?:n{2,}|s*$)/,def:/^ *[([^]]+)]: *]+)>?(?: +[\"(]([^n]+)[\")])? *(?:n+|$)/,table:noop,paragraph:/^((?:[^n]+n?(?!hr|heading|lheading|blockquote|tag|def))+)n*/,text:/^[^n]+/};block.bullet=/(?:[*+-]|d+.)/;block.item=/^( *)(bull) [^n]*(?:n(?!1bull )[^n]*)*/;block.item=replace(block.item,\"gm\")(/bull/g,block.bullet)();block.list=replace(block.list)(/bull/g,block.bullet)(\"hr\",\"n+(?=1?(?:[-*_] *){3,}(?:n+|$))\")(\"def\",\"n+(?=\"+block.def.source+\")\")();block.blockquote=replace(block.blockquote)(\"def\",block.def)();block._tag=\"(?!(?:\"+\"a|em|strong|small|s|cite|q|dfn|abbr|data|time|code\"+\"|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo\"+\"|span|br|wbr|ins|del|img)b)w+(?!:/|[^ws@]*@)b\";block.html=replace(block.html)(\"comment\",//)(\"closed\",/<(tag)[sS]+?/)(\"closing\",/])*?>/)(/tag/g,block._tag)();block.paragraph=replace(block.paragraph)(\"hr\",block.hr)(\"heading\",block.heading)(\"lheading\",block.lheading)(\"blockquote\",block.blockquote)(\"tag\",\"<\"+block._tag)(\"def\",block.def)();block.normal=merge({},block);block.gfm=merge({},block.normal,{fences:/^ *(`{3,}|~{3,}) *(S+)? *n([sS]+?)s*1 *(?:n+|$)/,paragraph:/^/});block.gfm.paragraph=replace(block.paragraph)(\"(?!\",\"(?!\"+block.gfm.fences.source.replace(\"1\",\"2\")+\"|\"+block.list.source.replace(\"1\",\"3\")+\"|\")();block.tables=merge({},block.gfm,{nptable:/^ *(S.*|.*)n *([-:]+ *|[-| :]*)n((?:.*|.*(?:n|$))*)n*/,table:/^ *|(.+)n *|( *[-:]+[-| :]*)n((?: *|.*(?:n|$))*)n*/});function Lexer(options){this.tokens=[];this.tokens.links={};this.options=options||marked.defaults;this.rules=block.normal;if(this.options.gfm){if(this.options.tables){this.rules=block.tables}else{this.rules=block.gfm}}}Lexer.rules=block;Lexer.lex=function(src,options){var lexer=new Lexer(options);return lexer.lex(src)};Lexer.prototype.lex=function(src){src=src.replace(/rn|r/g,\"n\").replace(/t/g,\" \").replace(/u00a0/g,\" \").replace(/u2424/g,\"n\");return this.token(src,true)};Lexer.prototype.token=function(src,top,bq){var src=src.replace(/^ +$/gm,\"\"),next,loose,cap,bull,b,item,space,i,l;while(src){if(cap=this.rules.newline.exec(src)){src=src.substring(cap[0].length);if(cap[0].length>1){this.tokens.push({type:\"space\"})}}if(cap=this.rules.code.exec(src)){src=src.substring(cap[0].length);cap=cap[0].replace(/^ {4}/gm,\"\");this.tokens.push({type:\"code\",text:!this.options.pedantic?cap.replace(/n+$/,\"\"):cap});continue}if(cap=this.rules.fences.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:\"code\",lang:cap[2],text:cap[3]});continue}if(cap=this.rules.heading.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:\"heading\",depth:cap[1].length,text:cap[2]});continue}if(top&&(cap=this.rules.nptable.exec(src))){src=src.substring(cap[0].length);item={type:\"table\",header:cap[1].replace(/^ *| *| *$/g,\"\").split(/ *| */),align:cap[2].replace(/^ *|| *$/g,\"\").split(/ *| */),cells:cap[3].replace(/n$/,\"\").split(\"n\")};for(i=0;i ?/gm,\"\");this.token(cap,top,true);this.tokens.push({type:\"blockquote_end\"});continue}if(cap=this.rules.list.exec(src)){src=src.substring(cap[0].length);bull=cap[2];this.tokens.push({type:\"list_start\",ordered:bull.length>1});cap=cap[0].match(this.rules.item);next=false;l=cap.length;i=0;for(;i1&&b.length>1)){src=cap.slice(i+1).join(\"n\")+src;i=l-1}}loose=next||/nn(?!s*$)/.test(item);if(i!==l-1){next=item.charAt(item.length-1)===\"n\";if(!loose)loose=next}this.tokens.push({type:loose?\"loose_item_start\":\"list_item_start\"});this.token(item,false,bq);this.tokens.push({type:\"list_item_end\"})}this.tokens.push({type:\"list_end\"});continue}if(cap=this.rules.html.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:this.options.sanitize?\"paragraph\":\"html\",pre:cap[1]===\"pre\"||cap[1]===\"script\"||cap[1]===\"style\",text:cap[0]});continue}if(!bq&&top&&(cap=this.rules.def.exec(src))){src=src.substring(cap[0].length);this.tokens.links[cap[1].toLowerCase()]={href:cap[2],title:cap[3]};continue}if(top&&(cap=this.rules.table.exec(src))){src=src.substring(cap[0].length);item={type:\"table\",header:cap[1].replace(/^ *| *| *$/g,\"\").split(/ *| */),align:cap[2].replace(/^ *|| *$/g,\"\").split(/ *| */),cells:cap[3].replace(/(?: *| *)?n$/,\"\").split(\"n\")};for(i=0;i])/,autolink:/^<([^ >]+(@|:/)[^ >]+)>/,url:noop,tag:/^|^])*?>/,link:/^!?[(inside)](href)/,reflink:/^!?[(inside)]s*[([^]]*)]/,nolink:/^!?[((?:[[^]]*]|[^[]])*)]/,strong:/^__([sS]+?)__(?!_)|^**([sS]+?)**(?!*)/,em:/^b_((?:__|[sS])+?)_b|^*((?:**|[sS])+?)*(?!*)/,code:/^(`+)s*([sS]*?[^`])s*1(?!`)/,br:/^ {2,}n(?!s*$)/,del:noop,text:/^[sS]+?(?=[?(?:s+['\"]([sS]*?)['\"])?s*/;inline.link=replace(inline.link)(\"inside\",inline._inside)(\"href\",inline._href)();inline.reflink=replace(inline.reflink)(\"inside\",inline._inside)();inline.normal=merge({},inline);inline.pedantic=merge({},inline.normal,{strong:/^__(?=S)([sS]*?S)__(?!_)|^**(?=S)([sS]*?S)**(?!*)/,em:/^_(?=S)([sS]*?S)_(?!_)|^*(?=S)([sS]*?S)*(?!*)/});inline.gfm=merge({},inline.normal,{escape:replace(inline.escape)(\"])\",\"~|])\")(),url:/^(https?://[^s<]+[^<.,:;\"')]s])/,del:/^~~(?=S)([sS]*?S)~~/,text:replace(inline.text)(\"]|\",\"~]|\")(\"|\",\"|https?://|\")()});inline.breaks=merge({},inline.gfm,{br:replace(inline.br)(\"{2,}\",\"*\")(),text:replace(inline.gfm.text)(\"{2,}\",\"*\")()});function InlineLexer(links,options){this.options=options||marked.defaults;this.links=links;this.rules=inline.normal;this.renderer=this.options.renderer||new Renderer;this.renderer.options=this.options;if(!this.links){throw new Error(\"Tokens array requires a `links` property.\")}if(this.options.gfm){if(this.options.breaks){this.rules=inline.breaks}else{this.rules=inline.gfm}}else if(this.options.pedantic){this.rules=inline.pedantic}}InlineLexer.rules=inline;InlineLexer.output=function(src,links,options){var inline=new InlineLexer(links,options);return inline.output(src)};InlineLexer.prototype.output=function(src){var out=\"\",link,text,href,cap;while(src){if(cap=this.rules.escape.exec(src)){src=src.substring(cap[0].length);out+=cap[1];continue}if(cap=this.rules.autolink.exec(src)){src=src.substring(cap[0].length);if(cap[2]===\"@\"){text=cap[1].charAt(6)===\":\"?this.mangle(cap[1].substring(7)):this.mangle(cap[1]);href=this.mangle(\"mailto:\")+text}else{text=escape(cap[1]);href=text}out+=this.renderer.link(href,null,text);continue}if(!this.inLink&&(cap=this.rules.url.exec(src))){src=src.substring(cap[0].length);text=escape(cap[1]);href=text;out+=this.renderer.link(href,null,text);continue}if(cap=this.rules.tag.exec(src)){if(!this.inLink&&/^/i.test(cap[0])){this.inLink=false}src=src.substring(cap[0].length);out+=this.options.sanitize?escape(cap[0]):cap[0];continue}if(cap=this.rules.link.exec(src)){src=src.substring(cap[0].length);this.inLink=true;out+=this.outputLink(cap,{href:cap[2],title:cap[3]});this.inLink=false;continue}if((cap=this.rules.reflink.exec(src))||(cap=this.rules.nolink.exec(src))){src=src.substring(cap[0].length);link=(cap[2]||cap[1]).replace(/s+/g,\" \");link=this.links[link.toLowerCase()];if(!link||!link.href){out+=cap[0].charAt(0);src=cap[0].substring(1)+src;continue}this.inLink=true;out+=this.outputLink(cap,link);this.inLink=false;continue}if(cap=this.rules.strong.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.strong(this.output(cap[2]||cap[1]));continue}if(cap=this.rules.em.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.em(this.output(cap[2]||cap[1]));continue}if(cap=this.rules.code.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.codespan(escape(cap[2],true));continue}if(cap=this.rules.br.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.br();continue}if(cap=this.rules.del.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.del(this.output(cap[1]));continue}if(cap=this.rules.text.exec(src)){src=src.substring(cap[0].length);out+=escape(this.smartypants(cap[0]));continue}if(src){throw new Error(\"Infinite loop on byte: \"+src.charCodeAt(0))}}return out};InlineLexer.prototype.outputLink=function(cap,link){var href=escape(link.href),title=link.title?escape(link.title):null;return cap[0].charAt(0)!==\"!\"?this.renderer.link(href,title,this.output(cap[1])):this.renderer.image(href,title,escape(cap[1]))};InlineLexer.prototype.smartypants=function(text){if(!this.options.smartypants)return text;return text.replace(/--/g,\"—\").replace(/(^|[-u2014/([{\"s])'/g,\"$1‘\").replace(/'/g,\"’\").replace(/(^|[-u2014/([{u2018s])\"/g,\"$1“\").replace(/\"/g,\"”\").replace(/.{3}/g,\"…\")};InlineLexer.prototype.mangle=function(text){var out=\"\",l=text.length,i=0,ch;for(;i.5){ch=\"x\"+ch.toString(16)}out+=\"&#\"+ch+\";\"}return out};function Renderer(options){this.options=options||{}}Renderer.prototype.code=function(code,lang,escaped){if(this.options.highlight){var out=this.options.highlight(code,lang);if(out!=null&&out!==code){escaped=true;code=out}}if(!lang){return\"
    \"+(escaped?code:escape(code,true))+\"n
    \"}return'
    '+(escaped?code:escape(code,true))+\"n
    n\"};Renderer.prototype.blockquote=function(quote){return\"
    n\"+quote+\"
    n\"};Renderer.prototype.html=function(html){return html};Renderer.prototype.heading=function(text,level,raw){return\"'+text+\"n\"};Renderer.prototype.hr=function(){return this.options.xhtml?\"
    n\":\"
    n\"};Renderer.prototype.list=function(body,ordered){var type=ordered?\"ol\":\"ul\";return\"<\"+type+\">n\"+body+\"n\"};Renderer.prototype.listitem=function(text){return\"
  • \"+text+\"
  • n\"};Renderer.prototype.paragraph=function(text){return\"

    \"+text+\"

    n\"};Renderer.prototype.table=function(header,body){return\"n\"+\"n\"+header+\"n\"+\"n\"+body+\"n\"+\"
    n\"};Renderer.prototype.tablerow=function(content){return\"n\"+content+\"n\"};Renderer.prototype.tablecell=function(content,flags){var type=flags.header?\"th\":\"td\";var tag=flags.align?\"<\"+type+' style=\"text-align:'+flags.align+'\">':\"<\"+type+\">\";return tag+content+\"n\"};Renderer.prototype.strong=function(text){return\"\"+text+\"\"};Renderer.prototype.em=function(text){return\"\"+text+\"\"};Renderer.prototype.codespan=function(text){return\"\"+text+\"\"};Renderer.prototype.br=function(){return this.options.xhtml?\"
    \":\"
    \"};Renderer.prototype.del=function(text){return\"\"+text+\"\"};Renderer.prototype.link=function(href,title,text){if(this.options.sanitize){try{var prot=decodeURIComponent(unescape(href)).replace(/[^w:]/g,\"\").toLowerCase()}catch(e){return\"\"}if(prot.indexOf(\"javascript:\")===0){return\"\"}}var out='
    \"+text+\"\";return out};Renderer.prototype.image=function(href,title,text){var out='\"'+text+'\"';if(title){out+='\":\">\";return out};function Parser(options){this.tokens=[];this.token=null;this.options=options||marked.defaults;this.options.renderer=this.options.renderer||new Renderer;this.renderer=this.options.renderer;this.renderer.options=this.options}Parser.parse=function(src,options,renderer){var parser=new Parser(options,renderer);return parser.parse(src)};Parser.prototype.parse=function(src){this.inline=new InlineLexer(src.links,this.options,this.renderer);this.tokens=src.reverse();var out=\"\";while(this.next()){out+=this.tok()}return out};Parser.prototype.next=function(){return this.token=this.tokens.pop()};Parser.prototype.peek=function(){return this.tokens[this.tokens.length-1]||0};Parser.prototype.parseText=function(){var body=this.token.text;while(this.peek().type===\"text\"){body+=\"n\"+this.next().text}return this.inline.output(body)};Parser.prototype.tok=function(){switch(this.token.type){case\"space\":{return\"\"}case\"hr\":{return this.renderer.hr()}case\"heading\":{return this.renderer.heading(this.inline.output(this.token.text),this.token.depth,this.token.text)}case\"code\":{return this.renderer.code(this.token.text,this.token.lang,this.token.escaped)}case\"table\":{var header=\"\",body=\"\",i,row,cell,flags,j;cell=\"\";for(i=0;i/g,\">\").replace(/\"/g,\""\").replace(/'/g,\"'\")}function unescape(html){return html.replace(/&([#w]+);/g,function(_,n){n=n.toLowerCase();if(n===\"colon\")return\":\";if(n.charAt(0)===\"#\"){return n.charAt(1)===\"x\"?String.fromCharCode(parseInt(n.substring(2),16)):String.fromCharCode(+n.substring(1))}return\"\"})}function replace(regex,opt){regex=regex.source;opt=opt||\"\";return function self(name,val){if(!name)return new RegExp(regex,opt);val=val.source||val;val=val.replace(/(^|[^[])^/g,\"$1\");regex=regex.replace(name,val);return self}}function noop(){}noop.exec=noop;function merge(obj){var i=1,target,key;for(;iAn error occured:

    \"+escape(e.message+\"\",true)+\"
    \"}throw e}}marked.options=marked.setOptions=function(opt){merge(marked.defaults,opt);return marked};marked.defaults={gfm:true,tables:true,breaks:false,pedantic:false,sanitize:false,smartLists:false,silent:false,highlight:null,langPrefix:\"lang-\",smartypants:false,headerPrefix:\"\",renderer:new Renderer,xhtml:false};marked.Parser=Parser;marked.parser=Parser.parse;marked.Renderer=Renderer;marked.Lexer=Lexer;marked.lexer=Lexer.lex;marked.InlineLexer=InlineLexer;marked.inlineLexer=InlineLexer.output;marked.parse=marked;if(typeof exports===\"object\"){module.exports=marked}else if(typeof define===\"function\"&&define.amd){define(function(){return marked})}else{this.marked=marked}}).call(function(){return this||(typeof window!==\"undefined\"?window:global)}());
    No newline at end of file"} {"_id":"q-en-react-d44ae03d9a1057a3b1bb7b33adce8fe2b3378c3807dca377719814b7fb837774","text":"``` To make an uncontrolled component, `defaultValue` is used instead. > Note: > > You can pass an array into the `value` attribute, allowing you to select multiple options in a `select` tag: `