commit 9ffbab6279a69b878a9914ab783dc644229e96f9
Author: Breck Yunits <breck7@gmail.com> Date: 2025-01-16 15:19:58 -0800 Subject: diff --git a/public/framehub.png b/public/framehub.png new file mode 100644 index 0000000..45e6d61 Binary files /dev/null and b/public/framehub.png differ diff --git a/public/framehub.scroll b/public/framehub.scroll index 3bf0d0e..fd2f346 100644 --- a/public/framehub.scroll +++ b/public/framehub.scroll @@ -6,6 +6,7 @@ openGraphImage framehub.png editButton https://github.com/breck7/framehub editBaseUrl https://github.com/breck7/framehub/blob/main +<meta name="fc:frame" content='{"version":"next","imageUrl":"https://hub.scroll.pub/framehub.png","button":{"title":"Create Frame","action":{"type":"launch_frame","name":"Create frame","url":"https://framehub.pro","splashImageUrl":"https://hub.scroll.pub/framehub.png","splashBackgroundColor":"#FFFFFF"}}}' /> metaTags inlineCss .gazette.css .scroll.css scrollHubStyle.css
commit a7bd2bfa2f3247c3d759f27c7ffb3bbad91025d3
Author: Breck Yunits <breck7@gmail.com> Date: 2025-01-16 15:06:42 -0800 Subject: diff --git a/ScrollHub.js b/ScrollHub.js index 4904db3..794585f 100644 --- a/ScrollHub.js +++ b/ScrollHub.js @@ -732,6 +732,7 @@ If you'd like to create this folder, visit our main site to get started. const prompt = req.body.prompt const agent = (req.body.agent || "claude").toLowerCase() const template = req.body.template + const welcomeMessage = req.body.welcomeMessage || "scrollhub" const domainSuffix = req.body.tld || "scroll.pub" if (!prompt) return res.status(400).send("Prompt is required") @@ -754,7 +755,7 @@ If you'd like to create this folder, visit our main site to get started. // Add to story and redirect this.addStory(req, `created ${folderName} from prompt using ${agent}`) - res.redirect(`/edit.html?folderName=${folderName}&command=showWelcomeMessageCommand`) + res.redirect(`/edit.html?folderName=${folderName}&command=showWelcomeMessageCommand&welcomeMessage=${welcomeMessage}`) } catch (error) { console.error("Error creating from prompt:", error) res.status(500).send("Failed to create website from prompt: " + error.message) diff --git a/public/ai.scroll b/public/ai.scroll index 0cee6ae..698bed9 100644 --- a/public/ai.scroll +++ b/public/ai.scroll @@ -2,6 +2,8 @@ indexTop.scroll replace AGENT Claude replace TEMPLATE website replace TLD scroll.pub +replace WELCOME_MESSAGE scrollhub +replace SOCIAL_LINK <a style="color:blue;" href="https://x.com/breckyunits" target="_blank">X</a> createFromPrompt.scroll promptSettings.scroll indexBottom.scroll \ No newline at end of file diff --git a/public/createFromPrompt.scroll b/public/createFromPrompt.scroll index 3667e6c..f1e9d67 100644 --- a/public/createFromPrompt.scroll +++ b/public/createFromPrompt.scroll @@ -3,6 +3,7 @@ <input type="hidden" name="agent" value="AGENT"> <input type="hidden" name="template" value="TEMPLATE"> <input type="hidden" name="tld" value="TLD"> +<input type="hidden" name="welcomeMessage" value="WELCOME_MESSAGE"> <input type="text" id="folderName" name="prompt" placeholder="Describe the TEMPLATE you want"><button class="scrollButton createButton">Create TEMPLATE</button> <div id="errorMessage"></div> inlineJs create.js @@ -13,7 +14,7 @@ inlineJs create.js <div class="spinner"></div> <p>Creating your TEMPLATE...</p> <p>This takes between 30 and 60 seconds.</p> - <p>While you wait, say hi on <a style="color:blue;" href="https://x.com/breckyunits" target="_blank">X</a></p> + <p>While you wait, say hi on SOCIAL_LINK</p> </div> </div> diff --git a/public/framehub.scroll b/public/framehub.scroll index 045c4d8..3bf0d0e 100644 --- a/public/framehub.scroll +++ b/public/framehub.scroll @@ -54,6 +54,8 @@ css replace AGENT Claude replace TEMPLATE frame replace TLD framehub.pro +replace WELCOME_MESSAGE framehub +replace SOCIAL_LINK <a style="color:blue;" href="https://warpcast.com/breck" target="_blank">Warpcast</a> createFromPrompt.scroll // diff --git a/public/scrollHubEditor.js b/public/scrollHubEditor.js index 943b8e5..15c1a19 100644 --- a/public/scrollHubEditor.js +++ b/public/scrollHubEditor.js @@ -688,7 +688,7 @@ nokey1 showWelcomeMessageCommand Help` } async showWelcomeMessageCommand(event) { - const content = `container 600px + let content = `container 600px # Welcome to ScrollHub! @@ -713,6 +713,26 @@ I'd love to hear your requests and feedback! Contact me on X, GitHub, or email. target _blank -Breck` + if (new URL(window.location).searchParams.get("welcomeMessage") === "framehub") { + content = `container 600px + +# Welcome to FrameHub! + +center +${this.folderName} is live! +<div class="iframeHolder2"><iframe src="${this.permalink}" class="visitIframe"></iframe></div> + +center +Visit ${this.folderName} + link ${this.permalink} + target preview + class newSiteLink + +I'd love to hear your requests and feedback! Find me on Warpcast. + https://warpcast.com/breck Find me on Warpcast + +-Breck` + } const html = await this.fusionEditor.scrollToHtml(content) this.openModal(html, "welcome", event)
commit 27d8b379502669087d533761cea0aa8d1a1e6b8f
Author: Breck Yunits <breck7@gmail.com> Date: 2025-01-16 14:52:59 -0800 Subject: diff --git a/prompts/frame.scroll b/prompts/frame.scroll index 81aaca5..84d4b5e 100644 --- a/prompts/frame.scroll +++ b/prompts/frame.scroll @@ -114,9 +114,12 @@ metaTags meta name viewport content width=device-width, initial-scale=1.0 -meta - name fc:frame - content {\"version\":\"vNext\",\"image\":{\"src\":\"FRAME_IMAGE_URL\",\"aspectRatio\":\"1.91:1\"},\"buttons\":[{\"label\":\"SHOOT! 🏀\",\"action\":\"post\"}]}" + +replaceNodejs + module.exports = {JSONCONTENTS: JSON.stringify(JSON.parse(require("fs").readFileSync("meta.json")))} + +<meta name="fc:frame" content='JSONCONTENTS' /> + meta name fc:frame:image content FRAME_IMAGE_URL @@ -258,10 +261,26 @@ document.addEventListener('DOMContentLoaded', initializeFrame); "action": "post" } ], - "postUrl": "https://DOMAIN_EXPRESSION/api/frame" + "postUrl": "https://DOMAIN_EXPRESSION/api" +} + +---meta.json--- +{ + "version": "next", + "imageUrl": "FRAME_IMAGE_URL", + "button": { + "title": "Launch (something)", + "action": { + "type": "launch_frame", + "name": "(Frame Name)", + "url": "FRAME_URL", + "splashImageUrl": "FRAME_SPLASH_IMAGE", + "splashBackgroundColor": "FRAME_BG_COLOR" + } + } } ----api/frame.js--- +---api.js--- // Frame API handler export default async function handler(req, res) { if (req.method !== 'POST') {
commit 71442afa14b79a03405b9a9426bc952becf804c4
Author: Breck Yunits <breck7@gmail.com> Date: 2025-01-16 14:46:40 -0800 Subject: diff --git a/ScrollHub.js b/ScrollHub.js index 12193ea..4904db3 100644 --- a/ScrollHub.js +++ b/ScrollHub.js @@ -1616,7 +1616,7 @@ If you'd like to create this folder, visit our main site to get started. } shouldFormat(filePath) { - const prettierExtensions = [".js", ".html", ".css"] + const prettierExtensions = [".js", ".html", ".css", ".json", ".htm", ".mjs"] const scrollExtensions = [".scroll", ".parsers"] return prettierExtensions.some(ext => filePath.endsWith(ext)) || scrollExtensions.some(ext => filePath.endsWith(ext)) }
commit f7810f1e5f13dc5b07476df400e9f0d8dcb25e4e
Author: Breck Yunits <breck7@gmail.com> Date: 2025-01-16 14:33:41 -0800 Subject: diff --git a/package.json b/package.json index e9d3c1e..d5c72ed 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,7 @@ "openai": "^4.77.0", "prettier": "^3.3.3", "rss-parser": "^3.13.0", - "scroll-cli": "^168.2.0", + "scroll-cli": "^168.3.0", "scrollsdk": "^100.1.1" }, "bin": { diff --git a/public/ide/parsers.js b/public/ide/parsers.js index 65b8180..b576ae5 100644 --- a/public/ide/parsers.js +++ b/public/ide/parsers.js @@ -1 +1 @@ -const AppConstants = {"parsers":"columnNameAtom\n paint constant\nnewColumnNameAtom\n description Name a derived column.\n paint variable\nconstantAtom\n paint constant\npercentAtom\n paint constant.numeric.float\n extends stringAtom\n // todo: this currently extends from stringAtom b/c scrollsdk needs to be fixed. seems like if extending from number then the hard coded number typescript regex takes precedence over a custom regex\ncountAtom\n extends integerAtom\nyearAtom\n extends integerAtom\npreBuildCommandAtom\n extends cueAtom\n description Give build command atoms their own color.\n paint constant.character.escape\ndelimiterAtom\n description String to use as a delimiter.\n paint string\nbulletPointAtom\n description Any token used as a bullet point such as \"-\" or \"1.\" or \">\"\n paint keyword\ncomparisonAtom\n enum < > <= >= = != includes doesNotInclude empty notEmpty startsWith endsWith\n paint constant\npersonNameAtom\n extends stringAtom\nurlAtom\n paint constant.language\nabsoluteUrlAtom\n paint constant.language\n regex (ftp|https?)://.+\nemailAddressAtom\n extends stringAtom\n paint constant.language\npermalinkAtom\n paint string\n description A string that doesn't contain characters that might interfere with most filesystems. No slashes, for instance.\nfilePathAtom\n paint constant.language\ntagOrUrlAtom\n description An HTML tag or a url.\n paint constant.language\nhtmlAttributesAtom\n paint constant\nhtmlTagAtom\n paint constant.language\n enum div span p a img ul ol li h1 h2 h3 h4 h5 h6 header nav section article aside main footer input button form label select option textarea table tr td th tbody thead tfoot br hr meta link script style title code\nhtmlTypeAtom\n extends stringAtom\n paint constant.language\n enum text password email number tel url search date time datetime-local week month color checkbox radio file submit reset button hidden range\n description HTML input type attribute values.\nclassNameAtom\n paint constant\nhtmlIdAtom\n paint constant\nfontFamilyAtom\n enum Arial Helvetica Verdana Georgia Impact Tahoma Slim\n paint constant\njavascriptAnyAtom\n extends codeAtom\nhtmlAnyAtom\n extends codeAtom\ncolorAtom\n extends codeAtom\nnamedColorAtom\n extends colorAtom\n enum aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkkhaki darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray darkturquoise darkviolet deeppink deepskyblue dimgray dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow honeydew hotpink indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgoldenrodyellow lightgray lightgreen lightpink lightsalmon lightseagreen lightskyblue lightslategray lightsteelblue lightyellow lime limegreen linen magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell sienna silver skyblue slateblue slategray snow springgreen steelblue tan teal thistle tomato turquoise violet wheat white whitesmoke yellow yellowgreen\nbuildCommandAtom\n extends cueAtom\n description Give build command atoms their own color.\n paint constant\ncssAnyAtom\n extends codeAtom\ncssLengthAtom\n extends codeAtom\nreductionTypeAtom\n enum sum mean max min concat first\n paint keyword\ninlineMarkupNameAtom\n description Options to turn on some inline markups.\n enum bold italics code katex none\ntileOptionAtom\n enum default light\nmeasureNameAtom\n extends cueAtom\n // A regex for column names for max compatibility with a broad range of data science tools:\n regex [a-zA-Z][a-zA-Z0-9]*\nabstractConstantAtom\n paint entity.name.tag\njavascriptSafeAlphaNumericIdentifierAtom\n regex [a-zA-Z0-9_]+\n reservedAtoms enum extends function static if while export return class for default require var let const new\nanyAtom\nbaseParsersAtom\n description There are a few classes of special parsers. BlobParsers don't have their subparticles parsed. Error particles always report an error.\n // todo Remove?\n enum blobParser errorParser\n paint variable.parameter\nenumAtom\n paint constant.language\nbooleanAtom\n enum true false\n extends enumAtom\natomParserAtom\n enum prefix postfix omnifix\n paint constant.numeric\natomPropertyNameAtom\n paint variable.parameter\natomTypeIdAtom\n examples integerAtom cueAtom someCustomAtom\n extends javascriptSafeAlphaNumericIdentifierAtom\n enumFromAtomTypes atomTypeIdAtom\n paint storage\nconstantIdentifierAtom\n examples someId myVar\n // todo Extend javascriptSafeAlphaNumericIdentifier\n regex [a-zA-Z]\\w+\n paint constant.other\n description A atom that can be assigned to the parser in the target language.\nconstructorFilePathAtom\nenumOptionAtom\n // todo Add an enumOption top level type, so we can add data to an enum option such as a description.\n paint string\natomExampleAtom\n description Holds an example for a atom with a wide range of options.\n paint string\nextraAtom\n paint invalid\nfileExtensionAtom\n examples js txt doc exe\n regex [a-zA-Z0-9]+\n paint string\nnumberAtom\n paint constant.numeric\nfloatAtom\n extends numberAtom\n regex \\-?[0-9]*\\.?[0-9]*\n paint constant.numeric.float\nintegerAtom\n regex \\-?[0-9]+\n extends numberAtom\n paint constant.numeric.integer\ncueAtom\n description A atom that indicates a certain parser to use.\n paint keyword\njavascriptCodeAtom\nlowercaseAtom\n regex [a-z]+\nparserIdAtom\n examples commentParser addParser\n description This doubles as the class name in Javascript. If this begins with `abstract`, then the parser will be considered an abstract parser, which cannot be used by itself but provides common functionality to parsers that extend it.\n paint variable.parameter\n extends javascriptSafeAlphaNumericIdentifierAtom\n enumFromAtomTypes parserIdAtom\ncueAtom\n paint constant.language\nregexAtom\n paint string.regexp\nreservedAtomAtom\n description A atom that a atom cannot contain.\n paint string\npaintTypeAtom\n enum comment comment.block comment.block.documentation comment.line constant constant.character.escape constant.language constant.numeric constant.numeric.complex constant.numeric.complex.imaginary constant.numeric.complex.real constant.numeric.float constant.numeric.float.binary constant.numeric.float.decimal constant.numeric.float.hexadecimal constant.numeric.float.octal constant.numeric.float.other constant.numeric.integer constant.numeric.integer.binary constant.numeric.integer.decimal constant.numeric.integer.hexadecimal constant.numeric.integer.octal constant.numeric.integer.other constant.other constant.other.placeholder entity entity.name entity.name.class entity.name.class.forward-decl entity.name.constant entity.name.enum entity.name.function entity.name.function.constructor entity.name.function.destructor entity.name.impl entity.name.interface entity.name.label entity.name.namespace entity.name.section entity.name.struct entity.name.tag entity.name.trait entity.name.type entity.name.union entity.other.attribute-name entity.other.inherited-class invalid invalid.deprecated invalid.illegal keyword keyword.control keyword.control.conditional keyword.control.import keyword.declaration keyword.operator keyword.operator.arithmetic keyword.operator.assignment keyword.operator.bitwise keyword.operator.logical keyword.operator.atom keyword.other markup markup.bold markup.deleted markup.heading markup.inserted markup.italic markup.list.numbered markup.list.unnumbered markup.other markup.quote markup.raw.block markup.raw.inline markup.underline markup.underline.link meta meta.annotation meta.annotation.identifier meta.annotation.parameters meta.block meta.braces meta.brackets meta.class meta.enum meta.function meta.function-call meta.function.parameters meta.function.return-type meta.generic meta.group meta.impl meta.interface meta.interpolation meta.namespace meta.paragraph meta.parens meta.path meta.preprocessor meta.string meta.struct meta.tag meta.toc-list meta.trait meta.type meta.union punctuation punctuation.accessor punctuation.definition.annotation punctuation.definition.comment punctuation.definition.generic.begin punctuation.definition.generic.end punctuation.definition.keyword punctuation.definition.string.begin punctuation.definition.string.end punctuation.definition.variable punctuation.section.block.begin punctuation.section.block.end punctuation.section.braces.begin punctuation.section.braces.end punctuation.section.brackets.begin punctuation.section.brackets.end punctuation.section.group.begin punctuation.section.group.end punctuation.section.interpolation.begin punctuation.section.interpolation.end punctuation.section.parens.begin punctuation.section.parens.end punctuation.separator punctuation.separator.continuation punctuation.terminator source source.language-suffix.embedded storage storage.modifier storage.type storage.type keyword.declaration.type storage.type.class keyword.declaration.class storage.type.enum keyword.declaration.enum storage.type.function keyword.declaration.function storage.type.impl keyword.declaration.impl storage.type.interface keyword.declaration.interface storage.type.struct keyword.declaration.struct storage.type.trait keyword.declaration.trait storage.type.union keyword.declaration.union string string.quoted.double string.quoted.other string.quoted.single string.quoted.triple string.regexp string.unquoted support support.class support.constant support.function support.module support.type text text.html text.xml variable variable.annotation variable.function variable.language variable.other variable.other.constant variable.other.member variable.other.readwrite variable.parameter\n paint string\nscriptUrlAtom\nsemanticVersionAtom\n examples 1.0.0 2.2.1\n regex [0-9]+\\.[0-9]+\\.[0-9]+\n paint constant.numeric\ndateAtom\n paint string\nstringAtom\n paint string\natomAtom\n paint constant\n description A non-empty single atom string.\n regex .+\nexampleAnyAtom\n examples lorem ipsem\n // todo Eventually we want to be able to parse correctly the examples.\n paint comment\n extends stringAtom\nblankAtom\ncommentAtom\n paint comment\ncodeAtom\n paint comment\ncolumnNameOrColorAtom\n extends columnNameAtom\nmetaCommandAtom\n extends cueAtom\n description Give meta command atoms their own color.\n paint constant.numeric\n // Obviously this is not numeric. But I like the green color for now.\n We need a better design to replace this \"paint\" concept\n https://github.com/breck7/scrollsdk/issues/186\nvegaDataSetAtom\n paint constant.numeric\n enum airports.csv anscombe.json barley.json birdstrikes.json budget.json budgets.json burtin.json cars.json climate.json co2-concentration.csv countries.json crimea.json descriptions.json disasters.csv driving.json earthquakes.json flare-dependencies.json flare.json flights-10k.json flights-200k.json flights-20k.json flights-2k.json flights-3m.csv flights-5k.json flights-airport.csv gapminder-health-income.csv gapminder.json github.csv graticule.json income.json iowa-electricity.csv iris.json jobs.json la-riots.csv londonBoroughs.json londonCentroids.json londonTubeLines.json lookup_groups.csv lookup_people.csv miserables.json monarchs.json movies.json normal-2d.json obesity.json points.json population.json population_engineers_hurricanes.csv seattle-temps.csv seattle-weather.csv sf-temps.csv sp500.csv stocks.csv udistrict.json unemployment-across-industries.json unemployment.tsv us-10m.json us-employment.csv us-state-capitals.json weather.csv weather.json weball26.json wheat.json windvectors.csv world-110m.json zipcodes.csv\ntagAtom\n extends permalinkAtom\ntagWithOptionalFolderAtom\n description A group name optionally combined with a folder path. Only used when referencing tags, not in posts.\n extends stringAtom\nscrollThemeAtom\n enum roboto gazette dark tufte prestige\n paint constant\nabstractScrollParser\n atoms cueAtom\n javascript\n buildHtmlSnippet(buildSettings) {\n return this.buildHtml(buildSettings)\n }\n buildTxt() {\n return \"\"\n }\n getHtmlRequirements(buildSettings) {\n const {requireOnce} = this\n if (!requireOnce)\n return \"\"\n const set = buildSettings?.alreadyRequired || this.root.alreadyRequired\n if (set.has(requireOnce))\n return \"\"\n set.add(requireOnce)\n return requireOnce + \"\\n\\n\"\n }\nabstractAftertextParser\n description Text followed by markup commands.\n extends abstractScrollParser\n inScope abstractAftertextDirectiveParser abstractAftertextAttributeParser aftertextTagParser abstractCommentParser\n javascript\n get markupInserts() {\n const { originalTextPostLinkify } = this\n return this.filter(particle => particle.isMarkup)\n .map(particle => particle.getInserts(originalTextPostLinkify))\n .filter(i => i)\n .flat()\n }\n get originalText() {\n return this.content ?? \"\"\n }\n get originalTextPostLinkify() {\n const { originalText } = this\n const shouldLinkify = this.get(\"linkify\") === \"false\" || originalText.includes(\"<a \") ? false : true\n return shouldLinkify ? this.replaceNotes(Utils.linkify(originalText)) : originalText\n }\n replaceNotes(originalText) {\n // Skip the replacements if there are no footnotes or the text has none.\n if (!this.root.footnotes.length || !originalText.includes(\"^\")) return originalText\n this.root.footnotes.forEach((note, index) => {\n const needle = note.cue\n const {linkBack} = note\n if (originalText.includes(needle)) originalText = originalText.replace(new RegExp(\"\\\\\" + needle + \"\\\\b\"), `<a href=\"#${note.htmlId}\" class=\"scrollNoteLink\" id=\"${linkBack}\"><sup>${note.label}</sup></a>`)\n })\n return originalText\n }\n get text() {\n const { originalTextPostLinkify, markupInserts } = this\n let adjustment = 0\n let newText = originalTextPostLinkify\n markupInserts.sort((a, b) => {\n if (a.index !== b.index)\n return a.index - b.index\n // If multiple tags start at same index, the tag that closes first should start last. Otherwise HTML breaks.\n if (b.index === b.endIndex) // unless the endIndex is the same as index\n return a.endIndex - b.endIndex\n return b.endIndex - a.endIndex\n })\n markupInserts.forEach(insertion => {\n insertion.index += adjustment\n const consumeStartCharacters = insertion.consumeStartCharacters ?? 0\n const consumeEndCharacters = insertion.consumeEndCharacters ?? 0\n newText = newText.slice(0, insertion.index - consumeEndCharacters) + insertion.string + newText.slice(insertion.index + consumeStartCharacters)\n adjustment += insertion.string.length - consumeEndCharacters - consumeStartCharacters\n })\n return newText\n }\n tag = \"p\"\n get className() {\n if (this.get(\"class\"))\n return this.get(\"class\")\n const classLine = this.getParticle(\"addClass\")\n if (classLine && classLine.applyToParentElement) return classLine.content\n return this.defaultClassName\n }\n defaultClassName = \"scrollParagraph\"\n get isHidden() {\n return this.has(\"hidden\")\n }\n buildHtml(buildSettings) {\n if (this.isHidden) return \"\"\n this.buildSettings = buildSettings\n const { className, styles } = this\n const classAttr = className ? `class=\"${this.className}\"` : \"\"\n const selfClose = this.isSelfClosing ? \" /\" : \"\"\n const tag = this.get(\"tag\") || this.tag\n if (tag === \"none\") // Allow no tag for aftertext in tables\n return this.text\n const id = this.has(\"id\") ? \"\" : `id=\"${this.htmlId}\" ` // always add an html id\n return this.getHtmlRequirements(buildSettings) + `<${tag} ${id}${this.htmlAttributes}${classAttr}${styles}${selfClose}>${this.htmlContents}${this.closingTag}`\n }\n get htmlContents() {\n return this.text\n }\n get closingTag() {\n if (this.isSelfClosing) return \"\"\n const tag = this.get(\"tag\") || this.tag\n return `</${tag}>`\n }\n get htmlAttributes() {\n const attrs = this.filter(particle => particle.isAttribute)\n return attrs.length ? attrs.map(particle => particle.htmlAttributes).join(\" \") + \" \" : \"\"\n }\n get styles() {\n const style = this.getParticle(\"style\")\n const fontFamily = this.getParticle(\"font\")\n const color = this.getParticle(\"color\")\n if (!style && !fontFamily && !color)\n return \"\"\n return ` style=\"${style?.content};${fontFamily?.css};${color?.css}\"`\n }\n get htmlId() {\n return this.get(\"id\") || \"particle\" + this.index\n }\nscrollParagraphParser\n // todo Perhaps rewrite this from scratch and move out of aftertext.\n extends abstractAftertextParser\n catchAllAtomType stringAtom\n description A paragraph.\n boolean suggestInAutocomplete false\n cueFromId\n javascript\n buildHtml(buildSettings) {\n if (this.isHidden) return \"\"\n // Hacky, I know.\n const newLine = this.has(\"inlineMarkupsOn\") ? undefined : this.appendLine(\"inlineMarkupsOn\")\n const compiled = super.buildHtml(buildSettings)\n if (newLine)\n newLine.destroy()\n return compiled\n }\n buildTxt() {\n const subparticles = this.filter(particle => particle.buildTxt).map(particle => particle.buildTxt()).filter(i => i).join(\"\\n\")\n const dateline = this.getParticle(\"dateline\")\n return (dateline ? dateline.day + \"\\n\\n\" : \"\") + (this.originalText || \"\") + (subparticles ? \"\\n \" + subparticles.replace(/\\n/g, \"\\n \") : \"\")\n }\nauthorsParser\n popularity 0.007379\n // multiple authors delimited by \" and \"\n boolean isPopular true\n extends scrollParagraphParser\n description Set author(s) name(s).\n example\n authors Breck Yunits\n https://breckyunits.com Breck Yunits\n // note: once we have mixins in Parsers, lets mixin the below from abstractTopLevelSingleMetaParser\n atoms metaCommandAtom\n javascript\n isTopMatter = true\n isSetterParser = true\n buildHtmlForPrint() {\n // hacky. todo: cleanup\n const originalContent = this.content\n this.setContent(`by ${originalContent}`)\n const html = super.buildHtml()\n this.setContent(originalContent)\n return html\n }\n buildTxtForPrint() {\n return 'by ' + super.buildTxt()\n }\n buildHtml() {\n return \"\"\n }\n buildTxt() {\n return \"\"\n }\n defaultClassName = \"printAuthorsParser\"\nblinkParser\n description Just for fun.\n extends scrollParagraphParser\n example\n blink Carpe diem!\n cue blink\n javascript\n buildHtml() {\n return `<span class=\"scrollBlink\">${super.buildHtml()}</span>\n <script>setInterval(()=>{ Array.from(document.getElementsByClassName(\"scrollBlink\")).forEach(el => el.style.visibility = el.style.visibility === \"hidden\" ? \"visible\" : \"hidden\") }, 500)</script>`\n }\nscrollButtonParser\n extends scrollParagraphParser\n cueFromId\n description A button.\n postParser\n description Post a particle.\n example\n scrollButton Click me\n javascript\n defaultClassName = \"scrollButton\"\n tag = \"button\"\n get htmlAttributes() {\n const link = this.getFromParser(\"scrollLinkParser\")\n const post = this.getParticle(\"post\")\n if (post) {\n const method = \"post\"\n const action = link?.link || \"\"\n const formData = new URLSearchParams({particle: post.subparticlesToString()}).toString()\n return ` onclick=\"fetch('${action}', {method: '${method}', body: '${formData}', headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).then(async (message) => {const el = document.createElement('div'); el.textContent = await message.text(); this.insertAdjacentElement('afterend', el);}); return false;\" `\n }\n return super.htmlAttributes + (link ? `onclick=\"window.location='${link.link}'\"` : \"\")\n }\n getFromParser(parserId) {\n return this.find(particle => particle.doesExtend(parserId))\n }\ncatchAllParagraphParser\n popularity 0.115562\n description A paragraph.\n extends scrollParagraphParser\n boolean suggestInAutocomplete false\n boolean isPopular true\n boolean isArticleContent true\n atoms stringAtom\n javascript\n getErrors() {\n const errors = super.getErrors() || []\n return this.parent.has(\"testStrict\") ? errors.concat(this.makeError(`catchAllParagraphParser should not have any matches when testing with testStrict.`)) : errors\n }\n get originalText() {\n return this.getLine() || \"\"\n }\nscrollCenterParser\n popularity 0.006415\n cue center\n description A centered section.\n extends scrollParagraphParser\n example\n center\n This paragraph is centered.\n javascript\n buildHtml() {\n this.parent.sectionStack.push(\"</center>\")\n return `<center>${super.buildHtml()}`\n }\n buildTxt() {\n return this.content\n }\nabstractIndentableParagraphParser\n extends scrollParagraphParser\n inScope abstractAftertextDirectiveParser abstractAftertextAttributeParser abstractIndentableParagraphParser scrollParagraphParser\n javascript\n get htmlContents() {\n return this.text + this.map(particle => particle.buildHtml())\n .join(\"\\n\")\n .trim()\n }\n buildTxt() {\n return this.getAtom(0) + \" \" + super.buildTxt()\n }\nchecklistTodoParser\n popularity 0.000193\n extends abstractIndentableParagraphParser\n example\n [] Get milk\n description A task todo.\n cue []\n string checked \n javascript\n get text() {\n return `<div style=\"text-indent:${(this.getIndentLevel() - 1) * 20}px;\"><input type=\"checkbox\" ${this.checked} id=\"${this.id}\"><label for=\"${this.id}\">` + super.text + `</label></div>`\n }\n get id() {\n return this.get(\"id\") || \"item\" + this._getUid()\n }\nchecklistDoneParser\n popularity 0.000072\n extends checklistTodoParser\n description A completed task.\n string checked checked\n cue [x]\n example\n [x] get milk\nscrollDivParser\n popularity 0.007524\n description HTML div tag.\n extends abstractIndentableParagraphParser\n cue div\n example\n div\n # Hello world\n p This is a test\n div\n # Deeper\n javascript\n tag = \"div\"\nabstractHtmlElementParser\n extends abstractIndentableParagraphParser\n javascript\n defaultClassName = \"\"\nhtmlSectionParser\n description HTML section tag.\n extends abstractHtmlElementParser\n cue section\n example\n section\n # Hello world\n p This is a test\n section\n # Deeper\n javascript\n tag = \"section\"\nhtmlHeaderParser\n description HTML header tag.\n extends abstractHtmlElementParser\n cue header\n example\n header\n # Title\n javascript\n tag = \"header\"\nhtmlFooterParser\n description HTML footer tag.\n extends abstractHtmlElementParser\n cue footer\n example\n footer\n p Made with love\n javascript\n tag = \"footer\"\nhtmlAsideParser\n description HTML aside tag.\n extends abstractHtmlElementParser\n cue aside\n example\n aside\n h1 Some notes\n javascript\n tag = \"aside\"\nhtmlArticleParser\n description HTML article tag.\n extends abstractHtmlElementParser\n cue article\n example\n article\n h1 My article\n javascript\n tag = \"article\"\nhtmlMainParser\n description HTML main tag.\n extends abstractHtmlElementParser\n cue main\n example\n main\n # Title\n javascript\n tag = \"main\"\nhtmlNavParser\n description HTML nav tag.\n extends abstractHtmlElementParser\n cue nav\n example\n nav\n a Home\n href /\n javascript\n tag = \"nav\"\nhtmlPreParser\n description HTML pre tag.\n extends abstractHtmlElementParser\n cue pre\n example\n pre\n javascript\n tag = \"pre\"\nhtmlUlParser\n description HTML ul tag.\n extends abstractHtmlElementParser\n cue ul\n example\n ul\n li A list\n javascript\n tag = \"ul\"\nhtmlOlParser\n description HTML ol tag.\n extends abstractHtmlElementParser\n cue ol\n example\n ol\n li A list\n javascript\n tag = \"ol\"\nhtmlLiParser\n description HTML li tag.\n extends abstractHtmlElementParser\n cue li\n example\n ol\n li A list\n javascript\n tag = \"li\"\nhtmlImgParser\n description HTML img tag.\n extends abstractHtmlElementParser\n cue img\n example\n img foo.png\n javascript\n tag = \"img\"\n isSelfClosing = true\nhtmlAParser\n description HTML a tag.\n extends abstractHtmlElementParser\n cue a\n example\n a Home\n href /\n javascript\n tag = \"a\"\nhtmlFormParser\n description HTML form tag.\n extends abstractHtmlElementParser\n cue form\n example\n form\n input\n javascript\n tag = \"form\"\nhtmlInputParser\n description HTML input tag.\n extends abstractHtmlElementParser\n cue input\n example\n input\n type text\n placeholder Enter your name\n javascript\n tag = \"input\"\n isSelfClosing = true\nhtmlSelectParser\n description HTML select tag.\n extends abstractHtmlElementParser\n cue select\n example\n select\n option Value 1\n option Value 2\n javascript\n tag = \"select\"\nhtmlOptionParser\n description HTML option tag.\n extends abstractHtmlElementParser\n cue option\n example\n select\n option Choose an option\n option First Option\n javascript\n tag = \"option\"\nhtmlTextareaParser\n description HTML textarea tag.\n extends abstractHtmlElementParser\n cue textarea\n example\n textarea\n placeholder Enter your message\n rows 4\n javascript\n tag = \"textarea\"\nhtmlButtonParser\n description HTML button tag.\n extends abstractHtmlElementParser\n cue button\n example\n button Submit\n type submit\n javascript\n tag = \"button\"\nhtmlLabelParser\n description HTML label tag.\n extends abstractHtmlElementParser\n cue label\n example\n label Name\n for username\n javascript\n tag = \"label\"\nhtmlSpanParser\n description HTML span tag.\n extends abstractHtmlElementParser\n cue span\n example\n span Hello\n javascript\n tag = \"span\"\nhtmlCanvasParser\n description HTML canvas tag.\n extends abstractHtmlElementParser\n cue canvas\n example\n canvas\n javascript\n tag = \"canvas\"\nhtmlIframeParser\n description HTML iframe tag.\n extends abstractHtmlElementParser\n cue iframe\n example\n iframe\n javascript\n tag = \"iframe\"\nh1LiteralParser\n description HTML h1 tag.\n extends abstractHtmlElementParser\n cue h1\n example\n main\n h1 Title\n javascript\n tag = \"h1\"\nh2LiteralParser\n description HTML h2 tag.\n extends abstractHtmlElementParser\n cue h2\n example\n main\n h2 Title\n javascript\n tag = \"h2\"\nh3LiteralParser\n description HTML h3 tag.\n extends abstractHtmlElementParser\n cue h3\n example\n main\n h3 Title\n javascript\n tag = \"h3\"\nh4LiteralParser\n description HTML h4 tag.\n extends abstractHtmlElementParser\n cue h4\n example\n main\n h4 Title\n javascript\n tag = \"h4\"\nhtmlMetaTagParser\n description HTML meta tag.\n extends abstractHtmlElementParser\n cue meta\n example\n meta\n name description\n content A great page about meta tags\n javascript\n tag = \"meta\"\n isSelfClosing = true\nlistAftertextParser\n popularity 0.014325\n extends abstractIndentableParagraphParser\n example\n - I had a _new_ thought.\n description A list item.\n cue -\n javascript\n defaultClassName = \"\"\n buildHtml() {\n const {index, parent} = this\n const particleClass = this.constructor\n const isStartOfList = index === 0 || !(parent.particleAt(index - 1) instanceof particleClass)\n const isEndOfList = parent.length === index + 1 || !(parent.particleAt(index + 1) instanceof particleClass)\n const { listType } = this\n return (isStartOfList ? `<${listType} ${this.attributes}>` : \"\") + `${super.buildHtml()}` + (isEndOfList ? `</${listType}>` : \"\")\n }\n get attributes() {\n return \"\"\n }\n tag = \"li\"\n listType = \"ul\"\nabstractCustomListItemParser\n extends listAftertextParser\n javascript\n get requireOnce() {\n return `<style>\\n.${this.constructor.name} li::marker {content: \"${this.cue} \";}\\n</style>`\n }\n get attributes() {\n return `class=\"${this.constructor.name}\"`\n }\norderedListAftertextParser\n popularity 0.004485\n extends listAftertextParser\n description A list item.\n example\n 1. Hello world\n pattern ^\\d+\\. \n javascript\n listType = \"ol\"\n get attributes() { return ` start=\"${this.getAtom(0)}\"`}\npParagraphParser\n popularity 0.001881\n cue p\n extends abstractIndentableParagraphParser\n description A paragraph.\n boolean isArticleContent true\n example\n p I had a _new_ idea.\nquickQuoteParser\n popularity 0.000482\n cue >\n example\n > The only thing we have to fear is fear itself. - FDR\n boolean isPopular true\n extends abstractIndentableParagraphParser\n description A quote.\n javascript\n defaultClassName = \"scrollQuote\"\n tag = \"blockquote\"\nscrollCounterParser\n description Visualize the speed of something.\n extends scrollParagraphParser\n cue counter\n example\n counter 4.5 Babies Born\n atoms cueAtom numberAtom\n javascript\n buildHtml() {\n const line = this.getLine()\n const atoms = line.split(\" \")\n atoms.shift() // drop the counter atom\n const perSecond = parseFloat(atoms.shift()) // get number\n const increment = perSecond/10\n const id = this._getUid()\n this.setLine(`* <span id=\"counter${id}\" title=\"0\">0</span><script>setInterval(()=>{ const el = document.getElementById('counter${id}'); el.title = parseFloat(el.title) + ${increment}; el.textContent = Math.floor(parseFloat(el.title)).toLocaleString()}, 100)</script> ` + atoms.join(\" \"))\n const html = super.buildHtml()\n this.setLine(line)\n return html\n }\nexpanderParser\n popularity 0.000072\n cueFromId\n description An collapsible HTML details tag.\n extends scrollParagraphParser\n example\n expander Knock Knock\n Who's there?\n javascript\n buildHtml() {\n this.parent.sectionStack.push(\"</details>\")\n return `<details>${super.buildHtml()}`\n }\n buildTxt() {\n return this.content\n }\n tag = \"summary\"\n defaultClassName = \"\"\nfootnoteDefinitionParser\n popularity 0.001953\n description A footnote. Can also be used as section notes.\n extends scrollParagraphParser\n boolean isFootnote true\n pattern ^\\^.+$\n // We need to quickLinks back in scope because there is currently a bug in ScrollSDK/parsers where if a parser extending a parent class has a child parser defined, then any regex parsers in the parent class will not be tested unless explicitly included in scope again.\n inScope quickLinkParser\n labelParser\n description If you want to show a custom label for a footnote. Default label is the note definition index.\n cueFromId\n atoms cueAtom\n catchAllAtomType stringAtom\n javascript\n get htmlId() {\n return `note${this.noteDefinitionIndex}`\n }\n get label() {\n // In the future we could allow common practices like author name\n return this.get(\"label\") || `[${this.noteDefinitionIndex}]`\n }\n get linkBack() {\n return `noteUsage${this.noteDefinitionIndex}`\n }\n get text() {\n return `<a class=\"scrollFootNoteUsageLink\" href=\"#noteUsage${this.noteDefinitionIndex}\">${this.label}</a> ${super.text}`\n }\n get noteDefinitionIndex() {\n return this.parent.footnotes.indexOf(this) + 1\n }\n buildTxt() {\n return this.getAtom(0) + \": \" + super.buildTxt()\n }\nabstractHeaderParser\n extends scrollParagraphParser\n example\n # Hello world\n javascript\n buildHtml(buildSettings) {\n if (this.isHidden) return \"\"\n if (this.parent.sectionStack)\n this.parent.sectionStack.push(\"</div>\")\n return `<div class=\"scrollSection\">` + super.buildHtml(buildSettings)\n }\n buildTxt() {\n const line = super.buildTxt()\n return line + \"\\n\" + \"=\".repeat(line.length)\n }\n isHeader = true\nh1Parser\n popularity 0.017918\n description An html h1 tag.\n extends abstractHeaderParser\n example\n # Hello world\n boolean isArticleContent true\n cue #\n boolean isPopular true\n javascript\n tag = \"h1\"\nh2Parser\n popularity 0.005257\n description An html h2 tag.\n extends abstractHeaderParser\n example\n ## Hello world\n boolean isArticleContent true\n cue ##\n boolean isPopular true\n javascript\n tag = \"h2\"\nh3Parser\n popularity 0.001085\n description An html h3 tag.\n extends abstractHeaderParser\n example\n ### Hello world\n boolean isArticleContent true\n cue ###\n javascript\n tag = \"h3\"\nh4Parser\n popularity 0.000289\n description An html h4 tag.\n example\n #### Hello world\n extends abstractHeaderParser\n cue ####\n javascript\n tag = \"h4\"\nscrollQuestionParser\n popularity 0.004244\n description A question.\n extends h4Parser\n cue ?\n example\n ? Why is the sky blue?\n javascript\n defaultClassName = \"scrollQuestion\"\nh5Parser\n description An html h5 tag.\n extends abstractHeaderParser\n example\n ##### Hello world\n cue #####\n javascript\n tag = \"h5\"\nprintTitleParser\n popularity 0.007572\n description Print title.\n extends abstractHeaderParser\n boolean isPopular true\n example\n title Eureka\n printTitle\n cueFromId\n javascript\n buildHtml(buildSettings) {\n // Hacky, I know.\n const {content} = this\n if (content === undefined)\n this.setContent(this.root.title)\n const { permalink } = this.root\n if (!permalink) {\n this.setContent(content) // Restore it as it was.\n return super.buildHtml(buildSettings)\n }\n const newLine = this.appendLine(`link ${permalink}`)\n const compiled = super.buildHtml(buildSettings)\n newLine.destroy()\n this.setContent(content) // Restore it as it was.\n return compiled\n }\n get originalText() {\n return this.content ?? this.root.title ?? \"\"\n }\n defaultClassName = \"printTitleParser\"\n tag = \"h1\"\ncaptionAftertextParser\n popularity 0.003207\n description An image caption.\n cue caption\n example\n map.png\n caption A map.\n extends scrollParagraphParser\n boolean isPopular true\nabstractMediaParser\n extends scrollParagraphParser\n inScope scrollMediaLoopParser scrollAutoplayParser\n int atomIndex 1\n javascript\n buildTxt() {\n return \"\"\n }\n get filename() {\n return this.getAtom(this.atomIndex)\n }\n getAsHtmlAttribute(attr) {\n if (!this.has(attr)) return \"\"\n const value = this.get(attr)\n return value ? `${attr}=\"${value}\"` : attr\n }\n getAsHtmlAttributes(list) {\n return list.map(atom => this.getAsHtmlAttribute(atom)).filter(i => i).join(\" \")\n }\n buildHtml() {\n return `<${this.tag} src=\"${this.filename}\" controls ${this.getAsHtmlAttributes(\"width height loop autoplay\".split(\" \"))}></${this.tag}>`\n }\nscrollMusicParser\n popularity 0.000024\n extends abstractMediaParser\n cue music\n description Play sound files.\n example\n music sipOfCoffee.m4a\n javascript\n buildHtml() {\n return `<audio controls ${this.getAsHtmlAttributes(\"loop autoplay\".split(\" \"))}><source src=\"${this.filename}\" type=\"audio/mpeg\"></audio>`\n }\nquickSoundParser\n popularity 0.000024\n extends scrollMusicParser\n atoms urlAtom\n pattern ^[^\\s]+\\.(mp3|wav|ogg|aac|m4a|flac)\n int atomIndex 0\n example\n sipOfCoffee.m4a\nscrollVideoParser\n popularity 0.000024\n extends abstractMediaParser\n cue video\n example\n video spirit.mp4\n description Play video files.\n widthParser\n cueFromId\n atoms cueAtom integerAtom\n heightParser\n cueFromId\n atoms cueAtom integerAtom\n javascript\n tag = \"video\"\nquickVideoParser\n popularity 0.000024\n extends scrollVideoParser\n example\n spirit.mp4\n atoms urlAtom\n pattern ^[^\\s]+\\.(mp4|webm|avi|mov)\n int atomIndex 0\nquickParagraphParser\n popularity 0.001881\n cue *\n extends scrollParagraphParser\n description A paragraph.\n boolean isArticleContent true\n example\n * I had a _new_ idea.\nscrollStopwatchParser\n description A stopwatch.\n extends scrollParagraphParser\n cue stopwatch\n example\n stopwatch\n atoms cueAtom\n catchAllAtomType numberAtom\n javascript\n buildHtml() {\n const line = this.getLine()\n const id = this._getUid()\n this.setLine(`* <span class=\"scrollStopwatchParser\" id=\"stopwatch${id}\">0.0</span><script>{let startTime = parseFloat(new URLSearchParams(window.location.search).get('start') || 0); document.getElementById('stopwatch${id}').title = startTime; setInterval(()=>{ const el = document.getElementById('stopwatch${id}'); el.title = parseFloat(el.title) + .1; el.textContent = (parseFloat(el.title)).toFixed(1)}, 100)}</script> `)\n const html = super.buildHtml()\n this.setLine(line)\n return html\n }\nthinColumnsParser\n popularity 0.003690\n extends abstractAftertextParser\n cueFromId\n catchAllAtomType integerAtom\n description Thin columns.\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n columnWidth = 35\n columnGap = 20\n buildHtml() {\n const {columnWidth, columnGap, maxColumns} = this\n const maxTotalWidth = maxColumns * columnWidth + (maxColumns - 1) * columnGap\n const stackContents = this.parent.clearSectionStack() // Starting columns always first clears the section stack.\n if (this.singleColumn) this.parent.sectionStack.push(\"</div>\") // Single columns are self-closing after section break.\n return stackContents + `<div class=\"scrollColumns\" style=\"column-width:${columnWidth}ch;column-count:${maxColumns};max-width:${maxTotalWidth}ch;\">`\n }\n get maxColumns() {\n return this.singleColumn ? 1 : parseInt(this.getAtom(1) ?? 10)\n }\nwideColumnsParser\n popularity 0.000386\n extends thinColumnsParser\n description Wide columns.\n javascript\n columnWidth = 90\nwideColumnParser\n popularity 0.003376\n extends wideColumnsParser\n description A wide column section.\n boolean singleColumn true\nmediumColumnsParser\n popularity 0.003376\n extends thinColumnsParser\n description Medium width columns.\n javascript\n columnWidth = 65\nmediumColumnParser\n popularity 0.003376\n extends mediumColumnsParser\n description A medium column section.\n boolean singleColumn true\nthinColumnParser\n popularity 0.003376\n extends thinColumnsParser\n description A thin column section.\n boolean singleColumn true\nendColumnsParser\n popularity 0.007789\n extends abstractAftertextParser\n cueFromId\n description End columns.\n javascript\n buildHtml() {\n return \"</div>\"\n }\n buildHtmlSnippet() {\n return \"\"\n }\nscrollContainerParser\n popularity 0.000096\n cue container\n description A centered HTML div.\n example\n container 600px\n catchAllAtomType cssLengthAtom\n extends abstractAftertextParser\n boolean isHtml true\n javascript\n get maxWidth() {\n return this.atoms[1] || \"1200px\"\n }\n buildHtmlSnippet() {\n return \"\"\n }\n tag = \"div\"\n defaultClassName = \"scrollContainerParser\"\n buildHtml() {\n this.parent.bodyStack.push(\"</div>\")\n return `<style>.scrollContainerParser{width: 100%; box-sizing: border-box; max-width: ${this.maxWidth}; margin: 0 auto;}</style>` + super.buildHtml()\n }\n get text() { return \"\"}\n get closingTag() { return \"\"}\ndebugSourceStackParser\n // useful for debugging\n description Print compilation steps.\n extends abstractAftertextParser\n cueFromId\n example\n printOriginalSource\n javascript\n get sources() {\n const {file} = this.root\n const passNames = [\"codeAtStart\", \"fusedCode\", \"codeAfterMacroPass\"]\n let lastCode = \"\"\n return passNames.map(name => {\n let code = file[name]\n if (lastCode === code)\n code = \"[Unchanged]\"\n lastCode = file[name]\n return {\n name,\n code\n }})\n }\n buildHtml() {\n return `<code class=\"scrollCodeBlock\">${this.buildTxt().replace(/\\</g, \"&lt;\")}</code>`\n }\n buildTxt() {\n return this.sources.map((pass, index) => `Pass ${index + 1} - ${pass.name}\\n========\\n${pass.code}`).join(\"\\n\\n\\n\")\n }\nabstractDinkusParser\n extends abstractAftertextParser\n boolean isDinkus true\n javascript\n buildHtml() {\n return `<div class=\"${this.defaultClass}\"><span>${this.dinkus}</span></div>`\n }\n defaultClass = \"abstractDinkusParser\"\n buildTxt() {\n return this.dinkus\n }\n get dinkus() {\n return this.content || this.getLine()\n }\nhorizontalRuleParser\n popularity 0.000362\n cue ---\n description A horizontal rule.\n extends abstractDinkusParser\n example\n ---\n javascript\n buildHtml() {\n return `<hr>`\n }\nscrollDinkusParser\n popularity 0.010828\n cue ***\n description A dinkus. Breaks section.\n boolean isPopular true\n example\n ***\n extends abstractDinkusParser\n javascript\n dinkus = \"*\"\ncustomDinkusParser\n cue dinkus\n description A custom dinkus.\n extends abstractDinkusParser\nendOfPostDinkusParser\n popularity 0.005740\n extends abstractDinkusParser\n description End of post dinkus.\n boolean isPopular true\n cue ****\n example\n ****\n javascript\n dinkus = \"⁂\"\nabstractIconButtonParser\n extends abstractAftertextParser\n cueFromId\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n return `<style>.abstractIconButtonParser {position:absolute;top:0.25rem; }.abstractIconButtonParser svg {fill: rgba(204,204,204,.8);width:1.875rem;height:1.875rem; padding: 0 7px;} .abstractIconButtonParser:hover svg{fill: #333;}</style><a href=\"${this.link}\" class=\"doNotPrint abstractIconButtonParser\" style=\"${this.style}\">${this.svg}</a>`\n }\ndownloadButtonParser\n popularity 0.006294\n description Link to download/WWS page.\n extends abstractIconButtonParser\n catchAllAtomType urlAtom\n string style position:relative;\n string svg <svg fill=\"#000000\" xmlns=\"http://www.w3.org/2000/svg\" width=\"800px\" height=\"800px\" viewBox=\"0 0 52 52\" enable-background=\"new 0 0 52 52\" xml:space=\"preserve\"><path d=\"M38.6,20.4c-1-6.5-6.7-11.5-13.5-11.5c-7.6,0-13.7,6.1-13.7,13.7c0,0.3,0,0.7,0.1,1c-5,0.4-8.9,4.6-8.9,9.6 c0,5.4,4.3,9.7,9.7,9.7h11.5c-0.8-0.8-8.1-8.1-8.1-8.1c-0.4-0.4-0.4-0.9,0-1.3l1.3-1.3c0.4-0.4,0.9-0.4,1.3,0l3.5,3.5 c0.4,0.4,1.1,0.1,1.1-0.4V21.8c0-0.4,0.5-0.9,1-0.9h1.9c0.5,0,0.9,0.4,0.9,0.9v13.4c0,0.6,0.8,0.8,1.1,0.4l3.5-3.5 c0.4-0.4,0.9-0.4,1.3,0l1.3,1.3c0.4,0.4,0.4,0.9,0,1.3L26,42.9h12.3v0c6.1-0.1,11-5.1,11-11.3C49.4,25.5,44.6,20.6,38.6,20.4z\"/></svg><!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->\n javascript\n get link() {\n return this.content\n }\neditButtonParser\n popularity 0.013963\n description Print badge top right.\n extends abstractIconButtonParser\n catchAllAtomType urlAtom\n // SVG from https://github.com/32pixelsCo/zest-icons\n string svg <svg width=\"800px\" height=\"800px\" viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\"><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M21.1213 2.70705C19.9497 1.53548 18.0503 1.53547 16.8787 2.70705L15.1989 4.38685L7.29289 12.2928C7.16473 12.421 7.07382 12.5816 7.02986 12.7574L6.02986 16.7574C5.94466 17.0982 6.04451 17.4587 6.29289 17.707C6.54127 17.9554 6.90176 18.0553 7.24254 17.9701L11.2425 16.9701C11.4184 16.9261 11.5789 16.8352 11.7071 16.707L19.5556 8.85857L21.2929 7.12126C22.4645 5.94969 22.4645 4.05019 21.2929 2.87862L21.1213 2.70705ZM18.2929 4.12126C18.6834 3.73074 19.3166 3.73074 19.7071 4.12126L19.8787 4.29283C20.2692 4.68336 20.2692 5.31653 19.8787 5.70705L18.8622 6.72357L17.3068 5.10738L18.2929 4.12126ZM15.8923 6.52185L17.4477 8.13804L10.4888 15.097L8.37437 15.6256L8.90296 13.5112L15.8923 6.52185ZM4 7.99994C4 7.44766 4.44772 6.99994 5 6.99994H10C10.5523 6.99994 11 6.55223 11 5.99994C11 5.44766 10.5523 4.99994 10 4.99994H5C3.34315 4.99994 2 6.34309 2 7.99994V18.9999C2 20.6568 3.34315 21.9999 5 21.9999H16C17.6569 21.9999 19 20.6568 19 18.9999V13.9999C19 13.4477 18.5523 12.9999 18 12.9999C17.4477 12.9999 17 13.4477 17 13.9999V18.9999C17 19.5522 16.5523 19.9999 16 19.9999H5C4.44772 19.9999 4 19.5522 4 18.9999V7.99994Z\"/></svg>\n javascript\n get link() {\n return this.content || this.root.editUrl || \"\"\n }\n get style() {\n return this.parent.findParticles(\"editButton\")[0] === this ? \"right:2rem;\": \"position:relative;\"\n }\nemailButtonParser\n popularity 0.006294\n description Email button.\n extends abstractIconButtonParser\n catchAllAtomType emailAddressAtom\n // todo: should just be \"optionalAtomType\"\n string style position:relative;\n string svg <svg viewBox=\"3 5 24 20\" width=\"24\" height=\"20\" xmlns=\"http://www.w3.org/2000/svg\"><g transform=\"matrix(1, 0, 0, 1, 0, -289.0625)\"><path style=\"opacity:1;stroke:none;stroke-width:0.49999997;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1\" d=\"M 5 5 C 4.2955948 5 3.6803238 5.3628126 3.3242188 5.9101562 L 14.292969 16.878906 C 14.696939 17.282876 15.303061 17.282876 15.707031 16.878906 L 26.675781 5.9101562 C 26.319676 5.3628126 25.704405 5 25 5 L 5 5 z M 3 8.4140625 L 3 23 C 3 24.108 3.892 25 5 25 L 25 25 C 26.108 25 27 24.108 27 23 L 27 8.4140625 L 17.121094 18.292969 C 15.958108 19.455959 14.041892 19.455959 12.878906 18.292969 L 3 8.4140625 z \" transform=\"translate(0,289.0625)\" id=\"rect4592\"/></g></svg>\n javascript\n get link() {\n const email = this.content || this.parent.get(\"email\")\n return email ? `mailto:${email}` : \"\"\n }\nhomeButtonParser\n popularity 0.006391\n description Home button.\n extends abstractIconButtonParser\n catchAllAtomType urlAtom\n string style left:2rem;\n string svg <svg role=\"img\" viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M12.7166 3.79541C12.2835 3.49716 11.7165 3.49716 11.2834 3.79541L4.14336 8.7121C3.81027 8.94146 3.60747 9.31108 3.59247 9.70797C3.54064 11.0799 3.4857 13.4824 3.63658 15.1877C3.7504 16.4742 4.05336 18.1747 4.29944 19.4256C4.41371 20.0066 4.91937 20.4284 5.52037 20.4284H8.84433C8.98594 20.4284 9.10074 20.3111 9.10074 20.1665V15.9754C9.10074 14.9627 9.90433 14.1417 10.8956 14.1417H13.4091C14.4004 14.1417 15.204 14.9627 15.204 15.9754V20.1665C15.204 20.3111 15.3188 20.4284 15.4604 20.4284H18.4796C19.0806 20.4284 19.5863 20.0066 19.7006 19.4256C19.9466 18.1747 20.2496 16.4742 20.3634 15.1877C20.5143 13.4824 20.4594 11.0799 20.4075 9.70797C20.3925 9.31108 20.1897 8.94146 19.8566 8.7121L12.7166 3.79541ZM10.4235 2.49217C11.3764 1.83602 12.6236 1.83602 13.5765 2.49217L20.7165 7.40886C21.4457 7.91098 21.9104 8.73651 21.9448 9.64736C21.9966 11.0178 22.0564 13.5119 21.8956 15.3292C21.7738 16.7067 21.4561 18.4786 21.2089 19.7353C20.9461 21.0711 19.7924 22.0001 18.4796 22.0001H15.4604C14.4691 22.0001 13.6655 21.1791 13.6655 20.1665V15.9754C13.6655 15.8307 13.5507 15.7134 13.4091 15.7134H10.8956C10.754 15.7134 10.6392 15.8307 10.6392 15.9754V20.1665C10.6392 21.1791 9.83561 22.0001 8.84433 22.0001H5.52037C4.20761 22.0001 3.05389 21.0711 2.79113 19.7353C2.54392 18.4786 2.22624 16.7067 2.10437 15.3292C1.94358 13.5119 2.00338 11.0178 2.05515 9.64736C2.08957 8.73652 2.55427 7.91098 3.28346 7.40886L10.4235 2.49217Z\"/></svg>\n javascript\n get link() {\n return this.content || this.get(\"link\") || \"index.html\"\n }\ntheScrollButtonParser\n popularity 0.006294\n description WWS button.\n extends abstractIconButtonParser\n string style position:relative;\n string svg <svg xmlns=\"http://www.w3.org/2000/svg\" direction=\"ltr\" width=\"231.52568231268793\" height=\"249.33156169975996\" viewBox=\"297.27169239534896 1273.121785992385 231.52568231268793 249.33156169975996\" stroke-linecap=\"round\" stroke-linejoin=\"round\" data-color-mode=\"dark\" class=\"tl-container tl-theme__force-sRGB tl-theme__dark\" ><defs/><g transform=\"matrix(1, 0, 0, 1, 395.9682, 1413.3618)\" opacity=\"1\"><g transform=\"scale(1)\"><path d=\"M-5.7342,-1.1484 T-5.0182,-4.6536 -2.6672,-12.9768 1.7374,-22.3903 8.4597,-30.0892 16.5455,-35.2796 25.3478,-37.8247 34.4641,-37.2199 43.0676,-33.4606 50.27,-27.1118 55.7861,-19.7972 59.8042,-11.6764 61.6844,-2.3157 60.8049,7.9615 57.3259,17.5954 51.2605,25.5515 41.9451,31.9237 30.6489,36.2084 18.9812,37.6038 8.4915,36.637 -1.3063,34.5174 -10.6869,31.6604 -19.0463,27.0252 -26.0612,20.1562 -31.864,11.1271 -35.2772,1.0066 -35.7963,-9.1933 -35.203,-19.2337 -32.52,-28.3259 -27.3388,-37.4245 -20.2857,-45.7085 -11.787,-53.0395 -2.4314,-58.4864 7.1724,-61.8739 17.5002,-65.6025 28.2859,-68.1034 38.514,-69.1081 48.1844,-69.9134 57.9136,-70.1787 67.4056,-69.5971 76.297,-67.7446 84.5233,-63.97 92.0158,-57.5003 98.1976,-48.5614 102.8839,-38.056 105.9936,-27.6097 107.074,-18.168 107.175,-8.2882 106.6452,1.9768 105.4734,11.7698 104.0279,21.1013 101.7439,31.0445 98.0977,40.6386 92.7822,49.1039 86.2847,57.2337 78.6099,64.7113 69.8339,70.974 61.2863,75.092 52.4283,78.2186 42.5338,80.7945 32.7733,82.6629 22.8568,83.6574 12.2803,83.3538 2.4971,81.4828 -6.3367,78.789 -15.1061,75.8011 -24.259,72.3779 -33.2286,68.991 -41.5707,64.8363 -49.153,59.1909 -55.8375,52.2938 -62.9311,43.9553 -68.4604,34.4882 -71.2761,23.5855 -72.748,12.7452 -73.7673,2.0453 -74.1187,-8.7386 -72.293,-19.3856 -68.7376,-30.4053 -64.12,-39.7852 -59.1825,-47.8931 -53.7695,-56.4512 -48.1998,-65.7676 -43.1389,-74.401 -36.9006,-81.0179 -28.4317,-86.2639 -18.3342,-90.3521 -8.9259,-93.9355 0.1927,-98.7179 9.3551,-103.3537 18.7651,-106.7552 29.7482,-110.3584 40.9287,-113.446 50.87,-115.2231 57.8279,-116.0074 60.4065,-116.0632 A7.8326,7.8326 0 0 1 61.1735,-100.4168 T58.6018,-100.2201 51.1634,-99.3008 41.695,-96.884 32.4044,-94.0187 22.65,-91.382 13.4974,-87.3756 5.0519,-83.1026 -5.0443,-78.6175 -15.7236,-74.4743 -24.6193,-70.2681 -31.274,-62.5903 -36.3827,-53.9362 -41.2833,-46.2905 -46.0679,-38.5161 -50.639,-30.6576 -54.6876,-22.4063 -57.6038,-12.3346 -58.5104,-1.8678 -57.6022,9.4969 -56.0628,20.477 -53.6434,29.0487 -48.8908,36.7517 -42.4075,43.9784 -35.3064,50.6236 -27.3553,55.2062 -17.6884,59.4064 -7.6442,63.6638 2.4427,67.0449 12.7308,69.4843 22.9294,70.2171 33.2547,69.3921 42.4972,67.7384 52.2753,64.8425 61.8649,60.9142 69.5292,56.0828 76.3604,49.5927 82.431,42.3194 87.219,34.619 90.6076,25.5217 92.547,16.0352 93.8703,7.1315 94.4972,-2.5268 94.3672,-13.3681 93.3204,-24.4252 90.5377,-34.1656 85.7321,-43.6441 78.7334,-51.8057 68.7542,-56.0559 57.9857,-57.2713 48.079,-57.0198 38.4535,-56.3204 28.5246,-55.0036 18.6104,-52.4796 9.6402,-49.559 0.7193,-46.2981 -7.1531,-41.3715 -13.708,-34.8957 -19.5435,-26.853 -22.8356,-17.0622 -23.363,-6.5446 -21.9969,3.1439 -17.1086,11.9113 -9.276,18.744 -0.0685,22.6058 9.3636,24.796 19.2422,25.8817 29.052,25.0411 37.9338,21.3502 45.6819,13.8498 49.6675,4.5228 49.2802,-5.1854 45.3277,-14.4455 38.8603,-21.7879 30.5488,-25.7753 21.3356,-24.3975 13.6687,-19.2391 8.8217,-10.9919 6.423,-2.3609 5.7342,1.1484 A5.8481,5.8481 0 0 1 -5.7342,-1.1484 Z\" stroke-linecap=\"round\"/></g></g></svg>\n javascript\n get link() {\n return \"https://wws.scroll.pub\"\n }\nabstractTextLinkParser\n extends abstractAftertextParser\n cueFromId\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildTxt() {\n return this.text\n }\n buildHtml() {\n return `<div class=\"abstractTextLinkParser\"><a href=\"${this.link}\">${this.text}</a></div>`\n }\neditLinkParser\n popularity 0.001206\n extends abstractTextLinkParser\n description Print \"Edit\" link.\n string text Edit\n javascript\n get link() {\n return this.root.editUrl || \"\"\n }\nscrollVersionLinkParser\n popularity 0.006294\n extends abstractTextLinkParser\n string link https://scroll.pub\n description Print Scroll version.\n javascript\n get text() {\n return `Built with Scroll v${this.root.scrollVersion}`\n }\nclassicFormParser\n cue classicForm\n popularity 0.006391\n description Generate input form for ScrollSet.\n extends abstractAftertextParser\n atoms cueAtom\n catchAllAtomType stringAtom\n string script\n <script>\n sendFormViaEmail = form => {\n const mailto = new URL(\"mailto:\")\n const params = []\n const { value, title } = form.querySelector('button[type=\"submit\"]')\n params.push(`subject=${encodeURIComponent(value)}`)\n params.push(`to=${encodeURIComponent(title)}`)\n const oneTextarea = form.querySelector('textarea[title=\"oneTextarea\"]')\n const body = oneTextarea ? codeMirrorInstance.getValue() : Array.from(new FormData(form)).map(([name, value]) => `${name} ${value}`).join(\"\\\\n\")\n params.push(`body=${encodeURIComponent(body)}`)\n mailto.search = params.join(\"&\")\n window.open(mailto.href, '_blank')\n }\n </script>\n string style\n <style> .scrollFormParser {\n font-family: \"Gill Sans\", \"Bitstream Vera Sans\", sans-serif;\n }\n .scrollFormParser input , .scrollFormParser textarea{\n padding: 10px;\n margin-bottom: 10px;\n width: 100%;\n box-sizing: border-box;\n } .scrollFormParser label {\n display: block;\n margin-bottom: 5px;\n }\n </style>\n javascript\n get inputs() {\n return this.root.measures.filter(measure => !measure.IsComputed).map((measure, index) => {\n const {Name, Question, IsRequired, Type} = measure\n const type = Type || \"text\"\n const placeholder = Question\n const ucFirst = Name.substr(0, 1).toUpperCase() + Name.substr(1)\n // ${index ? \"\" : \"autofocus\"}\n let tag = \"\"\n if (Type === \"textarea\")\n tag = `<textarea placeholder=\"${placeholder}\" id=\"${Name}\" name=\"${Name}\" ${IsRequired ? \"required\" : \"\"}></textarea>`\n else\n tag = `<input placeholder=\"${placeholder}\" type=\"${type}\" id=\"${Name}\" name=\"${Name}\" ${IsRequired ? \"required\" : \"\"}>`\n return `<div><label for=\"${Name}\" title=\"${IsRequired ? \"Required\" : \"\"}\">${ucFirst}${IsRequired ? \"*\" : \"\"}:</label>${tag}</div>`\n }).join(\"\\n\")\n }\n buildHtml() {\n const {isEmail, formDestination, callToAction, subject} = this\n return `${this.script}${this.style}<form ${isEmail ? \"onsubmit='sendFormViaEmail(this); return false;'\" : ` method='post' action='${formDestination}'`} class=\"scrollFormParser\">${this.inputs}<button value=\"${subject}\" title=\"${formDestination}\" class=\"scrollButton\" type=\"submit\">${callToAction}</button>${this.footer}</form>`\n }\n get callToAction() {\n return (this.isEmail ? \"Submit via email\" : (this.subject || \"Post\"))\n }\n get isEmail() {\n return this.formDestination.includes(\"@\")\n }\n get formDestination() {\n return this.getAtom(1) || \"\"\n }\n get subject() {\n return this.getAtomsFrom(2)?.join(\" \") || \"\"\n }\n get footer() {\n return \"\"\n }\nscrollFormParser\n extends classicFormParser\n cue scrollForm\n placeholderParser\n atoms cueAtom\n baseParser blobParser\n cueFromId\n single\n valueParser\n atoms cueAtom\n baseParser blobParser\n cueFromId\n single\n nameParser\n description Name for the post submission.\n atoms cueAtom stringAtom\n cueFromId\n single\n description Generate a Scroll Form.\n string copyFromExternal .codeMirror.css .scrollLibs.js .constants.js\n string requireOnce\n <link rel=\"stylesheet\" href=\".codeMirror.css\">\n <script src=\".scrollLibs.js\"></script>\n <script src=\".constants.js\"></script>\n javascript\n get placeholder() {\n return this.getParticle(\"placeholder\")?.subparticlesToString() || \"\"\n }\n get value() {\n return this.getParticle(\"value\")?.subparticlesToString() || \"\"\n }\n get footer() {\n return \"\"\n }\n get name() {\n return this.get(\"name\") || \"particles\"\n }\n get parsersBundle() {\n const parserRegex = /^[a-zA-Z0-9_]+Parser$/gm\n const clone = this.root.clone()\n const parsers = clone.filter(line => parserRegex.test(line.getLine()))\n return \"\\n\" + parsers.map(particle => {\n particle.prependLine(\"boolean suggestInAutocomplete true\")\n return particle.toString()\n }).join(\"\\n\")\n }\n get inputs() {\n const Name = this.name\n return `<textarea title=\"oneTextarea\" rows=\"${Math.min(this.root.measures.length * 2, 30)}\" placeholder=\"${this.placeholder}\" id=\"${Name}\" name=\"${Name}\"></textarea>\n <script id=\"${Name}Parsers\" type=\"text/plain\">${this.parsersBundle}</script>\n <script>{\n const parserRegex = /^[a-zA-Z0-9_]+Parser$/gm\n let {width, height} = document.getElementById('${Name}').getBoundingClientRect();\n const sp = new Particle(AppConstants.parsers)\n sp.filter(particle => particle.getLine().match(parserRegex)).forEach(part => {\n part.appendLine(\"boolean suggestInAutocomplete false\")\n })\n const customScrollParser = new HandParsersProgram(sp.toString() + document.getElementById(\"${Name}Parsers\").textContent).compileAndReturnRootParser()\n codeMirrorInstance = new ParsersCodeMirrorMode(\"custom\", () => customScrollParser, undefined, CodeMirror).register().fromTextAreaWithAutocomplete(document.getElementById(\"${Name}\"), {\n lineWrapping: false,\n lineNumbers: false\n })\n codeMirrorInstance.setSize(width, height);\n codeMirrorInstance.setValue(\\`${this.value}\\`); }</script>`\n }\n buildHtml(buildSettings) {\n return this.getHtmlRequirements(buildSettings) + super.buildHtml()\n }\nloremIpsumParser\n extends abstractAftertextParser\n cueFromId\n description Generate dummy text.\n catchAllAtomType integerAtom\n string placeholder Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n javascript\n get originalText() {\n return this.placeholder.repeat(this.howMany)\n }\n get howMany() {\n return this.getAtom(1) ? parseInt(this.getAtom(1)) : 1\n }\nnickelbackIpsumParser\n extends loremIpsumParser\n string placeholder And one day, I’ll be at the door. And lose your wings to fall in love? To the bottom of every bottle. I’m on the ledge of the eighteenth story. Why must the blind always lead the blind?\nscrollModalParser\n description A modal dialog overlay.\n extends abstractAftertextParser\n boolean isHtml true\n cue modal\n string requireOnce\n <style>\n .scrollModal {\n display: none;\n position: fixed;\n background: transparent;\n padding: 20px;\n left: 3rem;\n top: 3rem;\n right: 3rem;\n bottom: 3rem;\n z-index: 1000;\n font-family: \"IBM Plex Mono\", monospace;\n /* Frosted glass effect */\n background: rgba(0, 0, 0, 0.2);\n backdrop-filter: blur(8px);\n -webkit-backdrop-filter: blur(8px);\n border: 1px solid rgba(255, 255, 255, 0.1);\n box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);\n border-radius: 8px;\n overflow: hidden;\n }\n .scrollModal .closeButton {\n position: absolute;\n top: 10px;\n right: 10px;\n width: 30px;\n height: 30px;\n border: none;\n background: rgba(255, 255, 255, 0.1);\n color: rgba(255, 255, 255, 0.8);\n border-radius: 4px;\n cursor: pointer;\n font-family: \"IBM Plex Mono\", monospace;\n font-size: 18px;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all 0.2s ease;\n }\n .scrollModal .closeButton:hover {\n background: rgba(255, 255, 255, 0.2);\n color: white;\n }\n </style>\n <script>{\n window.closeModal = modal => {\n modal.style.display = 'none';\n history.pushState(\"\", document.title, window.location.pathname + window.location.search);\n };\n window.openModal = (id, event) => {\n if (event) event.modalJustOpened = true;\n document.querySelector(\"#\" + id).style.display = 'block';\n };\n window.addEventListener('hashchange', () => {\n const modalId = location.hash.slice(1); window.openModal(modalId);\n });\n document.addEventListener('keydown', e => {\n if (e.key === 'Escape') \n document.querySelectorAll('.scrollModal').forEach(closeModal);\n });\n // Check hash on initial load\n document.addEventListener(\"DOMContentLoaded\", e => {\n if (location.hash) \n window.openModal(location.hash.slice(1));\n });\n // Close on outside click\n document.addEventListener('click', e => {\n if (e.modalJustOpened) return;\n const modals = document.querySelectorAll('.scrollModal');\n modals.forEach(modal => {\n if (modal.style.display === 'block' && !modal.contains(e.target)) {\n closeModal(modal);\n }\n });\n });\n }</script>\n javascript\n buildHtml(buildSettings) {\n this.parent.sectionStack.push(\"</div>\")\n return this.getHtmlRequirements(buildSettings) + `<div class=\"scrollModal\" id=\"${this.htmlId}\"><button class=\"closeButton\" onclick=\"closeModal(this.parentElement)\">×</button>`\n }\nprintSnippetsParser\n popularity 0.000338\n // todo: why are we extending AT here and not loops? Is it for class/id etc?\n extends abstractAftertextParser\n cueFromId\n atoms cueAtom\n catchAllAtomType tagWithOptionalFolderAtom\n description Prints snippets matching tag(s).\n example\n printSnippets index\n javascript\n makeSnippet(scrollProgram, buildSettings) {\n const {endSnippetIndex} = scrollProgram\n if (endSnippetIndex === -1) return scrollProgram.buildHtmlSnippet(buildSettings) + scrollProgram.editHtml\n const linkRelativeToCompileTarget = buildSettings.relativePath + scrollProgram.permalink\n const joinChar = \"\\n\"\n const html = scrollProgram\n .map((subparticle, index) => (index >= endSnippetIndex ? \"\" : subparticle.buildHtmlSnippet ? subparticle.buildHtmlSnippet(buildSettings) : subparticle.buildHtml(buildSettings)))\n .filter(i => i)\n .join(joinChar)\n .trim() +\n `<a class=\"scrollContinueReadingLink\" href=\"${linkRelativeToCompileTarget}\">Continue reading...</a>`\n return html\n }\n get files() {\n const thisFile = this.parent.file\n const files = this.root.getFilesByTags(this.content, this.has(\"limit\") ? parseInt(this.get(\"limit\")) : undefined).filter(file => file.file !== thisFile)\n // allow sortBy lastCommit Time\n if (this.get(\"sortBy\") === \"commitTime\") {\n return this.root.sortBy(files, file => file.scrollProgram.lastCommitTime).reverse()\n }\n return files\n }\n buildHtml() {\n const alreadyRequired = this.root.alreadyRequired\n const snippets = this.files.map(file => {\n const buildSettings = {relativePath: file.relativePath, alreadyRequired }\n return `<div class=\"scrollSnippetContainer\">${this.makeSnippet(file.file.scrollProgram, buildSettings)}</div>`\n }).join(\"\\n\\n\")\n return `<div class=\"scrollColumns\" style=\"column-width:35ch;\">${snippets}</div>`\n }\n buildTxt() {\n return this.files.map(file => {\n const {scrollProgram} = file.file\n const {title, date, absoluteLink} = scrollProgram\n const ruler = \"=\".repeat(title.length)\n // Note: I tried to print the description here but the description generating code needs work.\n return `${title}\\n${ruler}\\n${date}\\n${absoluteLink}`\n }).join(\"\\n\\n\")\n }\nscrollNavParser\n popularity 0.000048\n extends printSnippetsParser\n cue fileNav\n description Titles and links in group(s).\n joinParser\n boolean allowTrailingWhitespace true\n cueFromId\n atoms cueAtom\n catchAllAtomType stringAtom\n javascript\n buildHtml() {\n return `<nav class=\"scrollNavParser\">` + this.root.getFilesByTags(this.content).map(file => {\n const { linkTitle, permalink } = file.file.scrollProgram\n return `<a href=\"${permalink}\">${linkTitle}</a>` \n }).join(this.get(\"join\") || \" \") + `</nav>`\n }\nprintFullSnippetsParser\n popularity 0.000048\n extends printSnippetsParser\n cueFromId\n description Print full pages in group(s).\n javascript\n makeSnippet(scrollProgram, buildSettings) {\n return scrollProgram.buildHtmlSnippet(buildSettings) + scrollProgram.editHtml\n }\nprintShortSnippetsParser\n popularity 0.000048\n extends printSnippetsParser\n cueFromId\n description Titles and descriptions in group(s).\n javascript\n makeSnippet(scrollProgram, buildSettings) {\n const { title, permalink, description, timestamp } = scrollProgram\n return `<div><a href=\"${permalink}\">${title}</a><div>${description}...</div><div class=\"subdued\" style=\"text-align:right;\">${this.root.dayjs(timestamp * 1000).format(`MMMM D, YYYY`)}</div></div>`\n }\nprintRelatedParser\n popularity 0.001182\n description Print links to related posts.\n extends printSnippetsParser\n cueFromId\n javascript\n buildHtml() {\n const alreadyRequired = this.root.alreadyRequired\n const list = this.files.map(fileWrapper => {\n const {relativePath, file} = fileWrapper\n const {title, permalink, year} = file.scrollProgram\n return `- ${title}${year ? \" (\" + year + \")\" : \"\"}\\n link ${relativePath + permalink}`\n }).join(\"\\n\")\n const items = this.parent.concat(list)\n const html = items.map(item => item.buildHtml()).join(\"\\n\")\n items.forEach(item => item.destroy())\n return html\n }\nscrollNoticesParser\n extends abstractAftertextParser\n description Display messages in URL query parameters.\n cue notices\n javascript\n buildHtml() {\n const id = this.htmlId\n return `<div id=\"${id}\" class=\"scrollNoticesParser\" style=\"display:none;\"></div><script>(function(){\n const params = new URLSearchParams(window.location.search)\n if (!params.size) return\n document.getElementById('${id}').innerHTML = Array.from(params.entries()).map(([key, value]) => {\n if (key === \"error\") \n return '<div style=\"color:red\">Error: ' + value + '</div>'\n if (key === \"success\")\n return '<div style=\"color:green\">Success: ' + value + '</div>'\n return '<div>' + key + ': ' + value + '</div>'\n }).join(\"\") || \"No query parameters found\"\n document.getElementById('${id}').style.display = \"block\"\n })()</script>`\n }\nabstractAssertionParser\n description Test above particle's output.\n extends abstractScrollParser\n string bindTo previous\n catchAllAtomType codeAtom\n cueFromId\n javascript\n buildHtml() {\n return ``\n }\n get particleToTest() {\n // If the previous particle is also an assertion particle, use the one before that.\n return this.previous.particleToTest ? this.previous.particleToTest : this.previous\n }\n get actual() {return this.particleToTest.buildHtml()}\n getErrors() {\n const {actual, expected} = this\n const errors = super.getErrors()\n if (this.areEqual(actual, expected))\n return errors\n return errors.concat(this.makeError(`'${actual}' did not ${this.kind} '${expected}'`))\n }\n get expected() {\n return this.length ? this.subparticlesToString() : (this.content ? this.content : \"\")\n }\n catchAllParser htmlLineParser\nassertHtmlEqualsParser\n extends abstractAssertionParser\n string kind equal\n example\n <b></b>\n assertHtmlEquals <b></b>\n javascript\n areEqual(actual, expected) {\n return actual === expected\n }\n // todo: why are we having to super here?\n getErrors() { return super.getErrors()}\nassertBuildIncludesParser\n extends abstractAssertionParser\n string kind include\n example\n buildCsv\n assertBuildIncludes virginica\n javascript\n areEqual(actual, expected) {\n return actual.includes(expected)\n }\n get actual() { return this.particleToTest.buildOutput()}\n getErrors() { return super.getErrors()}\nassertHtmlIncludesParser\n extends abstractAssertionParser\n string kind include\n javascript\n areEqual(actual, expected) {\n return actual.includes(expected)\n }\n getErrors() { return super.getErrors()}\nassertHtmlExcludesParser\n extends abstractAssertionParser\n string kind exclude\n javascript\n areEqual(actual, expected) {\n return !actual.includes(expected)\n }\n getErrors() { return super.getErrors()}\nassertIgnoreBelowErrorsParser\n description If you want to ignore any errors in the below particle in automated tests.\n extends abstractScrollParser\n string bindTo next\n cueFromId\nabstractPrintMetaParser\n extends abstractScrollParser\n cueFromId\nprintAuthorsParser\n popularity 0.001664\n description Prints author(s) byline.\n boolean isPopular true\n extends abstractPrintMetaParser\n // todo: we need pattern matching added to sdk to support having no params or a url and personNameAtom\n catchAllAtomType stringAtom\n example\n authors Breck Yunits\n https://breckyunits.com\n printAuthors\n javascript\n buildHtml() {\n return this.parent.getParticle(\"authors\")?.buildHtmlForPrint()\n }\n buildTxt() {\n return this.parent.getParticle(\"authors\")?.buildTxtForPrint()\n }\nprintDateParser\n popularity 0.000434\n extends abstractPrintMetaParser\n // If not present computes the date from the file's ctime.\n description Print published date.\n boolean isPopular true\n example\n date 1/11/2019\n printDate\n javascript\n buildHtml() {\n return `<div class=\"printDateParser\">${this.day}</div>`\n }\n get day() {\n let day = this.content || this.root.date\n if (!day) return \"\"\n return this.root.dayjs(day).format(`MMMM D, YYYY`)\n }\n buildTxt() {\n return this.day\n }\nprintFormatLinksParser\n description Prints links to other formats.\n extends abstractPrintMetaParser\n example\n printFormatLinks\n javascript\n buildHtml() {\n const permalink = this.root.permalink.replace(\".html\", \"\")\n // hacky\n const particle = this.appendSibling(`HTML | TXT`, `class printDateParser\\nlink ${permalink}.html HTML\\nlink ${permalink}.txt TXT\\nstyle text-align:center;`)\n const html = particle.buildHtml()\n particle.destroy()\n return html\n }\n buildTxt() {\n const permalink = this.root.permalink.replace(\".html\", \"\")\n return `HTML | TXT\\n link ${permalink}.html HTML\\n link ${permalink}.txt TXT`\n }\nabstractBuildCommandParser\n extends abstractScrollParser\n cueFromId\n atoms buildCommandAtom\n catchAllAtomType filePathAtom\n inScope slashCommentParser\n javascript\n isTopMatter = true\n buildHtml() {\n return \"\"\n }\n get extension() {\n return this.cue.replace(\"build\", \"\")\n }\n buildOutput() {\n return this.root.compileTo(this.extension)\n }\n get outputFileNames() {\n return this.content?.split(\" \") || [this.root.permalink.replace(\".html\", \".\" + this.extension.toLowerCase())]\n }\n async _buildFileType(extension, options) {\n const {root} = this\n const { fileSystem, folderPath, filename, filePath, path, lodash } = root\n const capitalized = lodash.capitalize(extension)\n const buildKeyword = \"build\" + capitalized\n const {outputFileNames} = this\n for (let name of outputFileNames) {\n try {\n await fileSystem.writeProduct(path.join(folderPath, name), root.compileTo(capitalized))\n root.log(`💾 Built ${name} from ${filename}`)\n } catch (err) {\n console.error(`Error while building '${filePath}' with extension '${extension}'`)\n throw err\n }\n }\n }\nabstractBuildOneCommandParser\n // buildOne and buildTwo are just a dumb/temporary way to have CSVs/JSONs/TSVs build first. Will be merged at some point.\n extends abstractBuildCommandParser\n javascript\n async buildOne(options) { await this._buildFileType(this.extension, options) }\nbuildParsersParser\n popularity 0.000096\n description Compile to Parsers file.\n extends abstractBuildOneCommandParser\nbuildCsvParser\n popularity 0.000096\n example\n buildCsv\n description Compile to CSV file.\n extends abstractBuildOneCommandParser\nbuildTsvParser\n popularity 0.000096\n description Compile to TSV file.\n extends abstractBuildOneCommandParser\nbuildJsonParser\n popularity 0.000096\n description Compile to JSON file.\n extends abstractBuildOneCommandParser\nabstractBuildTwoCommandParser\n extends abstractBuildCommandParser\n javascript\n async buildTwo(options) {\n await this._buildFileType(this.extension, options)\n }\nbuildCssParser\n popularity 0.000048\n description Compile to CSS file.\n extends abstractBuildTwoCommandParser\n example\n buildCss\nbuildHtmlParser\n popularity 0.007645\n description Compile to HTML file.\n extends abstractBuildTwoCommandParser\n boolean isPopular true\n javascript\n async buildTwo(options) {\n await this._copyExternalFiles(options)\n await super.buildTwo(options)\n }\n async _copyExternalFiles(options) {\n if (!this.isNodeJs()) return\n const {root} = this\n const externalFilesCopied = options.externalFilesCopied || {}\n // If this file uses a parser that has external requirements,\n // copy those from external folder into the destination folder.\n const { parsersRequiringExternals, folderPath, fileSystem, filename, parserIdIndex, path, Disk, externalsPath } = root\n if (!externalFilesCopied[folderPath]) externalFilesCopied[folderPath] = {}\n parsersRequiringExternals.forEach(parserId => {\n if (externalFilesCopied[folderPath][parserId]) return\n if (!parserIdIndex[parserId]) return\n parserIdIndex[parserId].map(particle => {\n const externalFiles = particle.copyFromExternal.split(\" \")\n externalFiles.forEach(name => {\n const newPath = path.join(folderPath, name)\n fileSystem.writeProduct(newPath, Disk.read(path.join(externalsPath, name)))\n root.log(`💾 Copied external file needed by ${filename} to ${name}`)\n })\n })\n if (parserId !== \"scrollThemeParser\")\n // todo: generalize when not to cache\n externalFilesCopied[folderPath][parserId] = true\n })\n }\nbuildJsParser\n description Compile to JS file.\n extends abstractBuildTwoCommandParser\nbuildRssParser\n popularity 0.000048\n description Compile to RSS file.\n extends abstractBuildTwoCommandParser\nbuildTxtParser\n popularity 0.007596\n description Compile to TXT file.\n extends abstractBuildTwoCommandParser\n boolean isPopular true\nloadConceptsParser\n // todo: clean this up. just add smarter imports with globs?\n // this currently removes any \"import\" statements.\n description Import all concepts in a folder.\n extends abstractBuildCommandParser\n cueFromId\n atoms preBuildCommandAtom filePathAtom\n javascript\n async load() {\n const { Disk, path, importRegex } = this.root\n const folder = path.join(this.root.folderPath, this.getAtom(1))\n const ONE_BIG_FILE = Disk.getFiles(folder).filter(file => file.endsWith(\".scroll\")).map(Disk.read).join(\"\\n\\n\").replace(importRegex, \"\")\n this.parent.concat(ONE_BIG_FILE)\n //console.log(ONE_BIG_FILE)\n }\n buildHtml() {\n return \"\"\n }\nbuildConceptsParser\n popularity 0.000024\n cueFromId\n description Compile concepts to delimited files.\n extends abstractBuildCommandParser\n sortByParser\n cueFromId\n atoms cueAtom columnNameAtom\n javascript\n async buildOne() {\n const {root} = this\n const { fileSystem, folderPath, filename, path, permalink } = root\n const files = this.getAtomsFrom(1)\n if (!files.length) files.push(permalink.replace(\".html\", \".csv\"))\n const sortBy = this.get(\"sortBy\")\n for (let link of files) {\n await fileSystem.writeProduct(path.join(folderPath, link), root.compileConcepts(link, sortBy))\n root.log(`💾 Built concepts in ${filename} to ${link}`)\n }\n }\nfetchParser\n description Download URL to disk.\n extends abstractBuildCommandParser\n cueFromId\n atoms preBuildCommandAtom urlAtom\n example\n fetch https://breckyunits.com/posts.csv\n fetch https://breckyunits.com/posts.csv renamed.csv\n javascript\n get url() {\n return this.getAtom(1)\n }\n get filename() {\n return this.getAtom(2)\n }\n async load() {\n await this.root.fetch(this.url, this.filename)\n }\n buildHtml() {\n return \"\"\n }\nbuildMeasuresParser\n popularity 0.000024\n cueFromId\n description Compile measures to delimited files.\n extends abstractBuildCommandParser\n sortByParser\n cueFromId\n atoms cueAtom columnNameAtom\n javascript\n async buildOne() {\n const {root} = this\n const { fileSystem, folderPath, filename, path, permalink } = root\n const files = this.getAtomsFrom(1)\n if (!files.length) files.push(permalink.replace(\".html\", \".csv\"))\n const sortBy = this.get(\"sortBy\")\n for (let link of files) {\n await fileSystem.writeProduct(path.join(folderPath, link), root.compileMeasures(link, sortBy))\n root.log(`💾 Built measures in ${filename} to ${link}`)\n }\n }\nbuildPdfParser\n popularity 0.000096\n description Compile to PDF file.\n extends abstractBuildCommandParser\n javascript\n async buildTwo(options) {\n if (!this.isNodeJs()) return \"Only works in Node currently.\"\n const {root} = this\n const { filename } = root\n const outputFile = root.filenameNoExtension + \".pdf\"\n // relevant source code for chrome: https://github.com/chromium/chromium/blob/a56ef4a02086c6c09770446733700312c86f7623/components/headless/command_handler/headless_command_switches.cc#L22\n const command = `/Applications/Google\\\\ Chrome.app/Contents/MacOS/Google\\\\ Chrome --headless --disable-gpu --no-pdf-header-footer --default-background-color=00000000 --no-pdf-background --print-to-pdf=\"${outputFile}\" \"${root.permalink}\"`\n // console.log(`Node.js is running on architecture: ${process.arch}`)\n try {\n const output = require(\"child_process\").execSync(command, { stdio: \"ignore\" })\n root.log(`💾 Built ${outputFile} from ${filename}`)\n } catch (error) {\n console.error(error)\n }\n }\nabstractInlineFileParser\n extends abstractScrollParser\n catchAllAtomType filePathAtom\n catchAllParser scrollFileAddressParser\n string joinChar ;\\n\\n\n string htmlTag script\n javascript\n get files() {\n const inline = this.atoms.slice(1)\n const children = this.map(particle => particle.cue)\n return inline.concat(children)\n }\n get contents() {\n return this.files.map(filename => this.root.readFile(filename)).join(this.joinChar)\n }\n buildHtml() {\n return `<${this.htmlTag}>/* ${this.files.join(\" \")} */\\n${this.contents}</${this.htmlTag}>`\n }\nscrollInlineCssParser\n description Inline CSS from files.\n popularity 0.007211\n extends abstractInlineFileParser\n cue inlineCss\n string joinChar \\n\\n\n string htmlTag style\n javascript\n buildCss() {\n return this.contents\n }\nscrollInlineJsParser\n description Inline JS from files.\n popularity 0.007211\n extends abstractInlineFileParser\n cue inlineJs\n javascript\n buildJs() {\n return this.contents\n }\nabstractTopLevelSingleMetaParser\n description Use these parsers once per file.\n extends abstractScrollParser\n inScope slashCommentParser\n cueFromId\n atoms metaCommandAtom\n javascript\n isTopMatter = true\n isSetterParser = true\n buildHtml() {\n return \"\"\n }\ntestStrictParser\n description Make catchAllParagraphParser = error.\n extends abstractTopLevelSingleMetaParser\nscrollDateParser\n cue date\n popularity 0.006680\n catchAllAtomType dateAtom\n description Set published date.\n extends abstractTopLevelSingleMetaParser\n boolean isPopular true\n example\n date 1/11/2019\n printDate\n Hello world\n dateline\nabstractUrlSettingParser\n extends abstractTopLevelSingleMetaParser\n atoms metaCommandAtom urlAtom\n cueFromId\neditBaseUrlParser\n popularity 0.007838\n description Override edit link baseUrl.\n extends abstractUrlSettingParser\ncanonicalUrlParser\n description Override canonical URL.\n extends abstractUrlSettingParser\nopenGraphImageParser\n popularity 0.000796\n // https://ogp.me/\n // If not defined, Scroll will try to generate it's own using the first image tag on your page.\n description Override Open Graph Image.\n extends abstractUrlSettingParser\nbaseUrlParser\n popularity 0.009188\n description Required for RSS and OpenGraph.\n extends abstractUrlSettingParser\n example\n baseUrl https://hub.scroll.pub/\nrssFeedUrlParser\n popularity 0.008850\n description Set RSS feed URL.\n extends abstractUrlSettingParser\neditUrlParser\n catchAllAtomType urlAtom\n description Override edit link.\n extends abstractTopLevelSingleMetaParser\nsiteOwnerEmailParser\n popularity 0.001302\n description Set email address for site contact.\n extends abstractTopLevelSingleMetaParser\n cue email\n atoms metaCommandAtom emailAddressAtom\nfaviconParser\n popularity 0.001688\n catchAllAtomType stringAtom\n cue favicon\n description Favicon file.\n example\n favicon logo.png\n metatags\n buildHtml\n extends abstractTopLevelSingleMetaParser\nimportOnlyParser\n popularity 0.033569\n // This line will be not be imported into the importing file.\n description Don't build this file.\n cueFromId\n atoms preBuildCommandAtom\n extends abstractTopLevelSingleMetaParser\n javascript\n buildHtml() {\n return \"\"\n }\ninlineMarkupsParser\n popularity 0.000024\n description Set global inline markups.\n extends abstractTopLevelSingleMetaParser\n cueFromId\n example\n inlineMarkups\n * \n // Disable * for bold\n _ u\n // Make _ underline\nhtmlLangParser\n atoms metaCommandAtom stringAtom\n // for the <html lang=\"\"> tag. If not specified will be \"en\". See https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang\n description Override HTML lang attribute.\n extends abstractTopLevelSingleMetaParser\nopenGraphDescriptionParser\n popularity 0.001688\n catchAllAtomType stringAtom\n cue description\n description Description for SEO meta tag.\n extends abstractTopLevelSingleMetaParser\nopenGraphKeywordsParser\n popularity 0.001688\n catchAllAtomType stringAtom\n cue keywords\n description Keywords for SEO meta tag.\n extends abstractTopLevelSingleMetaParser\npermalinkParser\n popularity 0.000265\n description Override output filename.\n extends abstractTopLevelSingleMetaParser\n atoms metaCommandAtom permalinkAtom\nscrollTagsParser\n popularity 0.006801\n cue tags\n description Set tags.\n example\n tags All\n extends abstractTopLevelSingleMetaParser\n catchAllAtomType tagAtom\nscrollTitleParser\n popularity 0.007524\n catchAllAtomType stringAtom\n cue title\n description Set title.\n example\n title Eureka\n printTitle\n extends abstractTopLevelSingleMetaParser\n boolean isPopular true\nscrollLinkTitleParser\n popularity 0.007524\n catchAllAtomType stringAtom\n cue linkTitle\n description Text for links.\n example\n title My blog - Eureka\n linkTitle Eureka\n extends abstractTopLevelSingleMetaParser\nscrollChatParser\n popularity 0.000362\n description A faux text chat conversation.\n catchAllParser chatLineParser\n cue chat\n extends abstractScrollParser\n example\n chat\n Hi\n 👋\n javascript\n buildHtml() {\n return this.map((line, index) => line.asString ? `<div style=\"text-align: ${index % 2 ? \"right\" : \"left\"};\" class=\"scrollChat ${index % 2 ? \"scrollChatRight\" : \"scrollChatLeft\"}\"><span>${line.asString}</span></div>` : \"\").join(\"\")\n }\n buildTxt() {\n return this.subparticlesToString()\n }\nabstractDatatableProviderParser\n description A datatable.\n extends abstractScrollParser\n inScope scrollTableDataParser scrollTableDelimiterParser abstractTableVisualizationParser abstractTableTransformParser h1Parser h2Parser scrollQuestionParser htmlInlineParser scrollBrParser slashCommentParser\n javascript\n get visualizations() {\n return this.topDownArray.filter(particle => particle.isTableVisualization || particle.isHeader || particle.isHtml)\n }\n buildHtml(buildSettings) {\n return this.visualizations.map(particle => particle.buildHtml(buildSettings))\n .join(\"\\n\")\n .trim()\n }\n buildTxt() {\n return this.visualizations.map(particle => particle.buildTxt())\n .join(\"\\n\")\n .trim()\n }\n _coreTable\n get coreTable() {\n if (this._coreTable) return this._coreTable\n const {delimiter, delimitedData} = this\n return []\n }\n get columnNames() {\n return []\n }\nscrollTableParser\n extends abstractDatatableProviderParser\n popularity 0.002133\n cue table\n example\n table\n printTable\n data\n year,count\n 1900,10\n 2000,122\n 2020,23\n catchAllAtomType filePathAtom\n int atomIndex 1\n javascript\n get delimiter() {\n const {filename} = this\n let delimiter = \"\"\n if (filename) {\n const extension = filename.split('?')[0].split(\".\").pop()\n if (extension === \"json\") delimiter = \"json\"\n if (extension === \"particles\") delimiter = \"particles\"\n if (extension === \"csv\") delimiter = \",\"\n if (extension === \"tsv\") delimiter = \"\\t\"\n if (extension === \"ssv\") delimiter = \" \"\n if (extension === \"psv\") delimiter = \"|\"\n }\n if (this.get(\"delimiter\"))\n delimiter = this.get(\"delimiter\")\n else if (!delimiter) {\n const header = this.delimitedData.split(\"\\n\")[0]\n if (header.includes(\"\\t\"))\n delimiter = \"\\t\"\n else if (header.includes(\",\"))\n delimiter = \",\"\n else\n delimiter = \" \"\n }\n return delimiter\n }\n get filename() {\n return this.getAtom(this.atomIndex)\n }\n get coreTable() {\n if (this._coreTable) return this._coreTable\n const {delimiter, delimitedData} = this\n if (delimiter === \"json\") {\n const obj = JSON.parse(delimitedData)\n let rows = []\n // Optimal case: Array of objects\n if (Array.isArray(obj)) { rows = obj}\n else if (!Array.isArray(obj) && typeof obj === \"object\") {\n // Case 2: Nested array under a key\n const arrayKey = Object.keys(obj).find(key => Array.isArray(obj[key]))\n if (arrayKey) rows = obj[arrayKey]\n }\n // Case 3: Array of primitive values\n else if (Array.isArray(obj) && obj.length && typeof obj[0] !== \"object\") {\n rows = obj.map(value => ({ value }))\n }\n this._columnNames = rows.length ? Object.keys(rows[0]) : []\n this._coreTable = rows\n return rows\n }\n else if (delimiter === \"particles\") {\n const d3lib = this.root.d3\n this._coreTable = d3lib.dsvFormat(\",\").parse(new Particle(delimitedData).asCsv, d3lib.autoType)\n } else {\n const d3lib = this.root.d3\n this._coreTable = d3lib.dsvFormat(delimiter).parse(delimitedData, d3lib.autoType)\n }\n this._columnNames = this._coreTable.columns\n delete this._coreTable.columns\n return this._coreTable\n }\n get columnNames() {\n // init coreTable to set columns\n const coreTable = this.coreTable\n return this._columnNames\n }\n async load() {\n if (this.filename)\n await this.root.fetch(this.filename)\n }\n get fileContent() {\n return this.root.readSyncFromFileOrUrl(this.filename)\n }\n get delimitedData() {\n // json csv tsv\n if (this.filename)\n return this.fileContent\n const dataParticle = this.getParticle(\"data\")\n if (dataParticle)\n return dataParticle.subparticlesToString()\n // if not dataparticle and no filename, check [permalink].csv\n if (this.isNodeJs())\n return this.root.readFile(this.root.permalink.replace(\".html\", \"\") + \".csv\")\n return \"\"\n }\nclocParser\n extends scrollTableParser\n description Output results of cloc as table.\n cue cloc\n string copyFromExternal .clocLangs.txt\n javascript\n delimiter = \",\"\n get delimitedData() {\n const { execSync } = require(\"child_process\")\n const results = execSync(this.command).toString().trim()\n const csv = results.split(\"\\n\\n\").pop().replace(/,\\\"github\\.com\\/AlDanial.+/, \"\") // cleanup output\n return csv\n }\n get command(){\n return `cloc --vcs git . --csv --read-lang-def=.clocLangs.txt ${this.content || \"\"}`\n }\nscrollDependenciesParser\n extends scrollTableParser\n description Get files this file depends on.\n cue dependencies\n javascript\n delimiter = \",\"\n get delimitedData() {\n return `file\\n` + this.root.dependencies.join(\"\\n\")\n }\nscrollDiskParser\n extends scrollTableParser\n description Output file into as table.\n cue disk\n javascript\n delimiter = \"json\"\n get delimitedData() {\n return this.isNodeJs() ? this.delimitedDataNodeJs : \"\"\n }\n get delimitedDataNodeJs() {\n const fs = require('fs');\n const path = require('path');\n const {folderPath} = this.root\n const folder = this.content ? path.join(folderPath, this.content) : folderPath\n function getDirectoryContents(dirPath) {\n const directoryContents = [];\n const items = fs.readdirSync(dirPath);\n items.forEach((item) => {\n const itemPath = path.join(dirPath, item);\n const stats = fs.statSync(itemPath);\n directoryContents.push({\n name: item,\n type: stats.isDirectory() ? 'directory' : 'file',\n size: stats.size,\n lastModified: stats.mtime\n });\n });\n return directoryContents;\n }\n return JSON.stringify(getDirectoryContents(folder))\n }\nscrollIrisParser\n extends scrollTableParser\n description Iris dataset from R.A. Fisher.\n cue iris\n example\n iris\n printTable\n scatter\n x SepalLength\n y SepalWidth\n javascript\n delimitedData = this.constructor.iris\nvegaSampleDataParser\n extends scrollTableParser\n description Sample dataset from Vega.\n cue sampleData\n atoms cueAtom vegaDataSetAtom\n example\n sampleData zipcodes.csv\n printTable\n javascript\n get filename() {\n return \"https://ohayo.scroll.pub/ohayo/packages/vega/datasets/\" + this.content\n }\nquickTableParser\n popularity 0.000024\n extends scrollTableParser\n atoms urlAtom\n pattern ^[^\\s]+\\.(tsv|csv|ssv|psv|json)[^\\s]*$\n int atomIndex 0\n javascript\n get dependencies() { return [this.cue]}\nscrollConceptsParser\n description Load concepts as table.\n extends abstractDatatableProviderParser\n cue concepts\n atoms cueAtom\n example\n concepts\n printTable\n javascript\n get coreTable() {\n return this.root.concepts\n }\n get columnNames() {\n return this.root.measures.map(col => col.Name)\n }\nabstractPostsParser\n description Load posts as table.\n extends abstractDatatableProviderParser\n cueFromId\n atoms cueAtom\n catchAllAtomType tagWithOptionalFolderAtom\n javascript\n async load() {\n const dependsOn = this.tags.map(tag => this.root.parseNestedTag(tag)).filter(i => i).map(i => i.folderPath)\n const {fileSystem} = this.root\n for (let folderPath of dependsOn) {\n // console.log(`${this.root.filePath} is loading: ${folderPath} in id '${fileSystem.fusionId}'`)\n await fileSystem.getLoadedFilesInFolder(folderPath, \".scroll\")\n }\n }\n get tags() {\n return this.content?.split(\" \") || []\n }\n get files() {\n const thisFile = this.root.file\n // todo: we can include this file, but just not run asTxt\n const files = this.root.getFilesByTags(this.tags).filter(file => file.file !== thisFile)\n return files\n }\n get coreTable() {\n if (this._coreTable) return this._coreTable\n this._coreTable = this.files.map(file => this.postToRow(file))\n return this._coreTable\n }\n postToRow(file) {\n const {relativePath} = file\n const {scrollProgram} = file.file\n const {title, permalink, asTxt, date, wordCount, minutes} = scrollProgram\n const text = asTxt.replace(/(\\t|\\n)/g, \" \").replace(/</g, \"&lt;\")\n return {\n title, titleLink: relativePath + permalink, text, date, wordCount, minutes\n }\n }\n columnNames = \"title titleLink text date wordCount minutes\".split(\" \")\nscrollPostsParser\n popularity 0.000024\n cue posts\n description Posts as table.\n extends abstractPostsParser\n example\n // Print a search table:\n posts\n printTable\n tableSearch\n // Dump a CSV of blog:\n buildHtml\n buildCsv\n buildJson\nscrollPostsMetaParser\n popularity 0.000024\n cue postsMeta\n description Post meta as table.\n extends abstractPostsParser\n javascript\n columnNames = [\"date\", \"year\", \"title\", \"permalink\", \"authors\", \"tags\", \"wordCount\", \"minutes\"]\n postToRow(file) {\n const {date, year, title, permalink, authors, tags, wordCount, minutes} = file.file.scrollProgram\n return {\n date, year, title, permalink, authors, tags, wordCount, minutes\n }\n }\nprintFeedParser\n popularity 0.000048\n description Print group to RSS.\n extends abstractPostsParser\n example\n printFeed index\n printFeed cars/index\n buildRss\n javascript\n buildRss() {\n const {dayjs} = this.root\n const scrollPrograms = this.files.map(file => file.file.scrollProgram)\n const { title, baseUrl, description } = this.root\n return `<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n <rss version=\"2.0\">\n <channel>\n <title>${title}</title>\n <link>${baseUrl}</link>\n <description>${description}</description>\n <lastBuildDate>${dayjs().format(\"ddd, DD MMM YYYY HH:mm:ss ZZ\")}</lastBuildDate>\n <language>en-us</language>\n ${scrollPrograms.map(program => program.toRss()).join(\"\\n\")}\n </channel>\n </rss>`\n }\n buildTxt() {\n return this.buildRss()\n }\nprintSourceParser\n popularity 0.000024\n description Print source for files in group(s).\n extends printFeedParser\n example\n printSource index\n buildTxt source.txt\n javascript\n buildHtml() {\n const files = this.root.getFilesByTags(this.content).map(file => file.file)\n return `${files.map(file => file.filePath + \"\\n \" + file.codeAtStart.replace(/\\n/g, \"\\n \") ).join(\"\\n\")}`\n }\nprintSiteMapParser\n popularity 0.000072\n extends abstractPostsParser\n description Print text sitemap.\n example\n baseUrl http://test.com\n printSiteMap\n javascript\n buildHtml() {\n const { baseUrl } = this.root\n return this.files.map(file => baseUrl + file.relativePath + file.file.scrollProgram.permalink).join(\"\\n\")\n }\n buildTxt() {\n return this.buildHtml()\n }\n get dependencies() { return this.files}\ncodeParser\n popularity 0.001929\n description A code block.\n catchAllParser lineOfCodeParser\n extends abstractScrollParser\n boolean isPopular true\n example\n code\n two = 1 + 1\n javascript\n buildHtml() {\n return `<code class=\"scrollCodeBlock\">${this.code.replace(/\\</g, \"&lt;\")}</code>`\n }\n buildTxt() {\n return \"```\\n\" + this.code + \"\\n```\"\n }\n get code() {\n return this.subparticlesToString()\n }\n cueFromId\ncodeWithHeaderParser\n popularity 0.000169\n cueFromId\n catchAllAtomType stringAtom\n extends codeParser\n example\n codeWithHeader math.py\n two = 1 + 1\n javascript\n buildHtml() {\n return `<div class=\"codeWithHeader\"><div class=\"codeHeader\">${this.content}</div>${super.buildHtml()}</div>`\n }\n buildTxt() {\n return \"```\" + this.content + \"\\n\" + this.code + \"\\n```\"\n }\ncodeFromFileParser\n popularity 0.000169\n cueFromId\n atoms cueAtom urlAtom\n extends codeWithHeaderParser\n example\n codeFromFile math.py\n javascript\n get code() {\n return this.root.readSyncFromFileOrUrl(this.content)\n }\ncodeWithLanguageParser\n popularity 0.000458\n description Use this to specify the language of the code block, such as csvCode or rustCode.\n extends codeParser\n pattern ^[a-zA-Z0-9_]+Code$\ndebugParsersParser\n description Print the parsers used.\n extends codeParser\n cueFromId\n javascript\n buildParsers() { return this.code}\n get code() {\n let code = new Particle(this.root.definition.toString())\n // Remove comments\n code.filter((line) => line.getLine().startsWith(\"//\")).forEach((particle) => particle.destroy())\n // Remove blank lines\n code = code.toString().replace(/^\\n/gm, \"\")\n return code\n }\nabstractScrollWithRequirementsParser\n extends abstractScrollParser\n cueFromId\n javascript\n buildHtml(buildSettings) {\n return this.getHtmlRequirements(buildSettings) + this.buildInstance()\n }\ncopyButtonsParser\n popularity 0.001471\n extends abstractScrollWithRequirementsParser\n description Copy code widget.\n javascript\n buildInstance() {\n return \"\"\n }\n string requireOnce\n <script>\n document.addEventListener(\"DOMContentLoaded\", () => document.querySelectorAll(\".scrollCodeBlock\").forEach(block =>\n {\n if (!navigator.clipboard) return\n const button = document.createElement(\"span\")\n button.classList.add(\"scrollCopyButton\")\n block.appendChild(button)\n button.addEventListener(\"click\", async () => {\n await navigator.clipboard.writeText(block.innerText)\n button.classList.add(\"scrollCopiedButton\")\n })\n }\n ))\n </script>\nabstractTableVisualizationParser\n extends abstractScrollWithRequirementsParser\n boolean isTableVisualization true\n javascript\n get columnNames() {\n return this.parent.columnNames\n }\nheatrixParser\n cueFromId\n example\n heatrix\n '2007 '2008 '2009 '2010 '2011 '2012 '2013 '2014 '2015 '2016 '2017 '2018 '2019 '2020 '2021 '2022 '2023 '2024\n 4 11 23 37 3 14 12 0 0 0 5 1 2 11 15 10 12 56\n description A heatmap matrix data visualization.\n catchAllParser heatrixCatchAllParser\n extends abstractTableVisualizationParser\n javascript\n buildHtml() {\n // A hacky but simple way to do this for now.\n const advanced = new Particle(\"heatrixAdvanced\")\n advanced.appendLineAndSubparticles(\"table\", \"\\n \" + this.tableData.replace(/\\n/g, \"\\n \"))\n const particle = this.appendSibling(\"heatrixAdvanced\", advanced.subparticlesToString())\n const html = particle.buildHtml()\n particle.destroy()\n return html\n }\n get tableData() {\n const {coreTable} = this.parent\n if (!coreTable)\n return this.subparticlesToString()\n let table = new Particle(coreTable).asSsv\n if (this.parent.cue === \"transpose\") {\n // drop first line after transpose\n const lines = table.split(\"\\n\")\n lines.shift()\n table = lines.join(\"\\n\")\n }\n // detect years and make strings\n const lines = table.split(\"\\n\")\n const yearLine = / \\d{4}(\\s+\\d{4})+$/\n if (yearLine.test(lines[0])) {\n lines[0] = lines[0].replace(/ /g, \" '\")\n table = lines.join(\"\\n\")\n }\n return table\n }\nheatrixAdvancedParser\n popularity 0.000048\n cueFromId\n catchAllParser heatrixCatchAllParser\n extends abstractTableVisualizationParser\n description Advanced heatrix.\n example\n heatrix\n table\n \n %h10; '2007 '2008 '2009\n 12 4 323\n scale\n #ebedf0 0\n #c7e9c0 100\n #a1d99b 400\n #74c476 1600\n javascript\n buildHtml() {\n class Heatrix {\n static HeatrixId = 0\n uid = Heatrix.HeatrixId++\n constructor(program) {\n const isDirective = atom => /^(f|l|w|h)\\d+$/.test(atom) || atom === \"right\" || atom === \"left\" || atom.startsWith(\"http://\") || atom.startsWith(\"https://\") || atom.endsWith(\".html\")\n const particle = new Particle(program)\n this.program = particle\n const generateColorBinningString = (data, colors) => {\n const sortedData = [...data].sort((a, b) => a - b);\n const n = sortedData.length;\n const numBins = colors.length;\n // Calculate the indices for each quantile\n const indices = [];\n for (let i = 1; i < numBins; i++) {\n indices.push(Math.floor((i / numBins) * n));\n }\n // Get the quantile values and round them\n const thresholds = indices.map(index => Math.round(sortedData[index]));\n // Generate the string\n let result = '';\n colors.forEach((color, index) => {\n const threshold = index === colors.length - 1 ? thresholds[index - 1] * 2 : thresholds[index];\n result += `${color} ${threshold}\\n`;\n });\n return result.trim();\n }\n const buildScale = (table) => {\n const numbers = table.split(\"\\n\").map(line => line.split(\" \")).flat().filter(atom => !isDirective(atom)).map(atom => parseFloat(atom)).filter(number => !isNaN(number))\n const colors = ['#ebedf0', '#c7e9c0', '#a1d99b', '#74c476', '#41ab5d', '#238b45', '#005a32'];\n numbers.unshift(0)\n return generateColorBinningString(numbers, colors);\n }\n const table = particle.getParticle(\"table\").subparticlesToString()\n const scale = particle.getParticle(\"scale\")?.subparticlesToString() || buildScale(table)\n const thresholds = []\n const colors = []\n scale.split(\"\\n\").map((line) => {\n const parts = line.split(\" \")\n thresholds.push(parseFloat(parts[1]))\n colors.push(parts[0])\n })\n const colorCount = colors.length\n const colorFunction = (value) => {\n if (isNaN(value)) return \"\" // #ebedf0\n for (let index = 0; index < colorCount; index++) {\n const threshold = thresholds[index]\n if (value <= threshold) return colors[index]\n }\n return colors[colorCount - 1]\n }\n const directiveDelimiter = \";\"\n const getSize = (directives, letter) =>\n directives\n .filter((directive) => directive.startsWith(letter))\n .map((dir) => dir.replace(letter, \"\") + \"px\")[0] ?? \"\"\n this.table = table.split(\"\\n\").map((line) =>\n line\n .trimEnd()\n .split(\" \")\n .map((atom) => {\n const atoms = atom.split(directiveDelimiter).filter((atom) => !isDirective(atom)).join(\"\")\n const directivesInThisAtom = atom\n .split(directiveDelimiter)\n .filter(isDirective)\n const value = parseFloat(atoms)\n const label = atoms.includes(\"'\") ? atoms.split(\"'\")[1] : atoms\n const alignment = directivesInThisAtom.includes(\"right\")\n ? \"right\"\n : directivesInThisAtom.includes(\"left\")\n ? \"left\"\n : \"\"\n const color = colorFunction(value)\n const width = getSize(directivesInThisAtom, \"w\")\n const height = getSize(directivesInThisAtom, \"h\")\n const fontSize = getSize(directivesInThisAtom, \"f\")\n const lineHeight = getSize(directivesInThisAtom, \"l\") || height\n const link = directivesInThisAtom.filter(i => i.startsWith(\"http\") || i.endsWith(\".html\"))[0]\n const style = {\n \"background-color\": color,\n width,\n height,\n \"font-size\": fontSize,\n \"line-height\": lineHeight,\n \"text-align\": alignment,\n }\n Object.keys(style).filter(key => !style[key]).forEach((key) => delete style[key])\n return {\n value,\n label,\n style,\n link,\n }\n })\n )\n }\n get html() {\n const { program } = this\n const cssId = `#heatrix${this.uid}`\n const defaultWidth = \"40px\"\n const defaultHeight = \"40px\"\n const fontSize = \"10px\"\n const lineHeight = defaultHeight\n const style = `<style>\n .heatrixContainer {\n margin: auto;\n }.heatrixRow {white-space: nowrap;}\n ${cssId} .heatrixAtom {\n font-family: arial;\n border-radius: 2px;\n border: 1px solid transparent;\n display: inline-block;\n margin: 1px;\n text-align: center;\n vertical-align: middle;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n .heatrixAtom a {\n color: black;\n }\n ${cssId} .heatrixAtom{\n width: ${defaultWidth};\n height: ${defaultHeight};\n font-size: ${fontSize};\n line-height: ${lineHeight};\n }\n </style>`\n const firstRow = this.table[0]\n return (\n `<div class=\"heatrixContainer\" id=\"heatrix${this.uid}\">${style}` +\n this.table\n .map((row, rowIndex) => {\n if (!rowIndex) return \"\"\n const rowStyle = row[0].style\n return `<div class=\"heatrixRow heatrixRow${rowIndex}\">${row\n .map((atom, columnIndex) => {\n if (!columnIndex) return \"\"\n const columnStyle = firstRow[columnIndex]?.style || {}\n let { value, label, style, link } = atom\n const extendedStyle = Object.assign(\n {},\n rowStyle,\n columnStyle,\n style\n )\n const inlineStyle = Object.keys(extendedStyle)\n .map((key) => `${key}:${extendedStyle[key]};`)\n .join(\"\")\n let valueClass = value ? \" valueAtom\" : \"\"\n const href = link ? ` href=\"${link}\"` : \"\"\n return `<div class=\"heatrixAtom heatrixColumn${columnIndex}${valueClass}\" style=\"${inlineStyle}\"><a title=\"${label}\" ${href}>${label}</a></div>`\n })\n .join(\"\")}</div>`\n })\n .join(\"\\n\") +\n \"</div>\"\n ).replace(/\\n/g, \"\")\n }\n }\n return new Heatrix(this.subparticlesToString().trim()).html\n }\nmapParser\n latParser\n atoms cueAtom floatAtom\n cueFromId\n single\n longParser\n atoms cueAtom floatAtom\n cueFromId\n single\n tilesParser\n atoms cueAtom tileOptionAtom\n cueFromId\n single\n zoomParser\n atoms cueAtom integerAtom\n cueFromId\n single\n geolocateParser\n description Geolocate user.\n atoms cueAtom\n cueFromId\n single\n radiusParser\n atoms cueAtom floatAtom\n cueFromId\n single\n fillOpacityParser\n atoms cueAtom floatAtom\n cueFromId\n single\n fillColorParser\n atoms cueAtom colorAtom\n cueFromId\n single\n colorParser\n atoms cueAtom colorAtom\n cueFromId\n single\n heightParser\n atoms cueAtom floatAtom\n cueFromId\n single\n hoverParser\n atoms cueAtom\n catchAllAtomType colorAtom\n cueFromId\n single\n extends abstractTableVisualizationParser\n description Map widget.\n string copyFromExternal .leaflet.css .leaflet.js .scrollLibs.js\n string requireOnce\n <link rel=\"stylesheet\" href=\".leaflet.css\">\n <script src=\".leaflet.js\"></script>\n <script src=\".scrollLibs.js\"></script>\n javascript\n buildInstance() {\n const height = this.get(\"height\") || 500\n const id = this._getUid()\n const obj = this.toObject()\n const template = {}\n const style = height !== \"full\" ? `height: ${height}px;` : `height: 100%; position: fixed; z-index: -1; left: 0; top: 0; width: 100%;`\n const strs = [\"color\", \"fillColor\"]\n const nums = [\"radius\", \"fillOpacity\"]\n strs.filter(i => obj[i]).forEach(i => template[i] = obj[i])\n nums.filter(i => obj[i]).forEach(i => template[i] = parseFloat(obj[i]))\n const mapId = `map${id}`\n return `<div id=\"${mapId}\" style=\"${style}\"></div>\n <script>\n {\n if (!window.maps) window.maps = {}\n const moveToMyLocation = () => {\n if (!navigator.geolocation) return\n navigator.geolocation.getCurrentPosition((position) => {\n const { latitude, longitude } = position.coords\n window.maps.${mapId}.setView([latitude, longitude])\n L.circleMarker([latitude, longitude], {\n fillOpacity: 0.8,\n radius: 20,\n weight: 4\n })\n .addTo(window.maps.${mapId})\n }, () => {})\n }\n const lat = ${this.get(\"lat\") ?? 37.8}\n const long = ${this.get(\"long\") ?? 4}\n if (${this.has(\"geolocate\")}){\n moveToMyLocation()\n }\n const zoomLevel = ${this.get(\"zoom\") ?? 4}\n const hover = '${this.get(\"hover\") || \"<b>{title}</b><br>{description}\"}'\n const template = ${JSON.stringify(template)}\n const points = ${JSON.stringify((this.parent.coreTable || []).filter(point => point.lat && point.long), undefined, 2)}\n window.maps.${mapId} = L.map(\"map${id}\").setView([lat, long], zoomLevel)\n const map = window.maps.${mapId}\n const tileOptions = {\n \"default\": {\n baseLayer: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',\n attribution: '<a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors'\n },\n light: {\n baseLayer: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png',\n attribution: '<a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors <a href=\"https://carto.com/ attributions\">CARTO</a>'\n },\n }\n const {baseLayer, attribution} = tileOptions.${this.get(\"tiles\") || \"default\"}\n L.tileLayer(baseLayer, {\n attribution,\n maxZoom: 19\n }).addTo(map);\n points.forEach(point => {\n L.circleMarker([point.lat, point.long], {...template, ...Object.fromEntries(\n Object.entries(point).filter(([key, value]) => value !== null)\n )})\n .addTo(map)\n .bindPopup(new Particle(point).evalTemplateString(hover))\n })\n }\n </script>`\n }\nabstractPlotParser\n // Observablehq\n extends abstractTableVisualizationParser\n string copyFromExternal .d3.js .plot.js\n string requireOnce\n <script src=\".d3.js\"></script>\n <script src=\".plot.js\"></script>\n example\n plot\n inScope abstractColumnNameParser\n widthParser\n cueFromId\n atoms cueAtom integerAtom\n heightParser\n cueFromId\n atoms cueAtom integerAtom\n titleParser\n extends abstractPlotLabelParser\n subtitleParser\n extends abstractPlotLabelParser\n captionParser\n extends abstractPlotLabelParser\n javascript\n buildInstance() {\n const id = \"plot\" + this._getUid()\n return `<div id=\"${id}\"></div><script>\n {\n let loadChart = async () => {\n const data = ${this.dataCode}\n const get = (col, index ) => col !== \"undefined\" ? col : (index === undefined ? undefined : Object.keys(data[0])[index])\n document.querySelector(\"#${id}\").append(Plot.plot(${this.plotOptions}))\n }\n loadChart()\n }\n </script>`\n }\n get sortExpression() {\n const sort = this.get(\"sort\")\n if (!sort) return \"\"\n let sort_expr = \"\"\n if (sort.startsWith(\"-\")) {\n // Sort by a value descending\n const sortCol = sort.slice(1)\n sort_expr = `, sort: {x: \"y\", reverse: true}`\n } else if (sort.includes(\" \")) {\n // Fixed order specified\n const order = sort.split(\" \")\n sort_expr = `, sort: {x: (a,b) => {\n const order = ${JSON.stringify(order)};\n return order.indexOf(a) - order.indexOf(b)\n }}`\n } else if (sort === \"asc\") {\n sort_expr = `, sort: {x: \"x\"}`\n } else if (sort === \"desc\") {\n sort_expr = `, sort: {x: \"x\", reverse: true}`\n }\n return sort_expr\n }\n get marks() {\n // just for testing purposes\n return `Plot.rectY({length: 10000}, Plot.binX({y: \"count\"}, {x: d3.randomNormal()}))`\n }\n get dataCode() {\n const {coreTable} = this.parent\n return `d3.csvParse(\\`${new Particle(coreTable).asCsv}\\`, d3.autoType)`\n }\n get plotOptions() {\n return `{\n title: \"${this.get(\"title\") || \"\"}\",\n subtitle: \"${this.get(\"subtitle\") || \"\"}\",\n caption: \"${this.get(\"caption\") || \"\"}\",\n symbol: {legend: ${this.has(\"symbol\")}},\n color: {legend: ${this.has(\"fill\") || this.has(\"stroke\")}},\n grid: ${this.get(\"grid\") !== \"false\"},\n marks: [${this.marks}],\n width: ${this.get(\"width\") || 640},\n height: ${this.get(\"height\") || 400},\n }`\n }\nplotScatterplotParser\n cue scatterplot\n extends abstractPlotParser\n description Scatterplot Widget.\n example\n iris\n scatterplot\n javascript\n get marks() {\n const x = this.get(\"x\")\n const y = this.get(\"y\")\n const text = this.get(\"label\")\n return `Plot.dot(data, {\n x: get(\"${x}\", 0),\n y: get(\"${y}\", 1),\n r: get(\"${this.get(\"radius\")}\"),\n fill: get(\"${this.get(\"fill\")}\"),\n tip: true${this.sortExpression},\n symbol: get(\"${this.get(\"symbol\")}\")} ), Plot.text(data, {x: get(\"${x}\",0), y: get(\"${y}\", 1), text: \"${text}\", dy: -6, lineAnchor: \"bottom\"})`\n }\nplotBarchartParser\n cue barchart\n extends abstractPlotParser\n description Bar chart widget.\n example\n iris\n barchart\n javascript\n get marks() {\n const x = this.get(\"x\")\n const y = this.get(\"y\")\n const text = this.get(\"label\")\n const fill = this.get(\"fill\")\n return `Plot.barY(data, {\n x: get(\"${x}\", 0),\n y: get(\"${y}\", 1),\n fill: get(\"${fill}\"),\n tip: true${this.sortExpression}\n }), Plot.ruleY([0])`\n }\nplotLineChartParser\n cue linechart\n extends abstractPlotParser\n description Line chart widget.\n example\n iris\n linechart\n x SepalLength\n y SepalWidth\n javascript\n get marks() {\n const x = this.get(\"x\")\n const y = this.get(\"y\")\n const stroke = this.get(\"stroke\") || \"steelblue\"\n const strokeWidth = this.get(\"strokeWidth\") || 2\n const strokeLinecap = this.get(\"strokeLinecap\") || \"round\"\n const fill = this.get(\"fill\")\n return `Plot.line(data, {\n x: get(\"${x}\", 0),\n y: get(\"${y}\", 1),\n stroke: \"${stroke}\",\n fill: get(\"${fill}\"),\n strokeWidth: ${strokeWidth},\n strokeLinecap: \"${strokeLinecap}\"${this.sortExpression}\n })`\n }\nsparklineParser\n popularity 0.000024\n description Sparkline widget.\n extends abstractTableVisualizationParser\n example\n sparkline 1 2 3 4 5\n string copyFromExternal .sparkline.js\n string requireOnce <script src=\".sparkline.js\"></script>\n catchAllAtomType numberAtom\n // we need pattern matching\n inScope scrollYParser\n javascript\n buildInstance() {\n const id = \"spark\" + this._getUid()\n const {columnValues} = this\n const start = this.has(\"start\") ? parseInt(this.get(\"start\")) : 0\n const width = this.get(\"width\") || 100\n const height = this.get(\"height\") || 30\n const lineColor = this.get(\"color\") || \"black\"\n return `<span id=\"${id}\"></span><script>new Sparkline(document.getElementById(\"${id}\"), {dotRadius: 0, width: ${width}, height: ${height}, lineColor: \"${lineColor}\", tooltip: (value,index) => ${start} + index + \": \" + value}).draw(${JSON.stringify(columnValues)})</script>`\n }\n get columnValues() {\n if (this.content)\n return this.content.split(\" \").map(str => parseFloat(str))\n const {coreTable} = this.parent\n if (coreTable) {\n const columnName = this.get(\"y\") || Object.keys(coreTable[0]).find(key => typeof coreTable[0][key] === 'number')\n return coreTable.map(row => row[columnName])\n }\n }\nprintColumnParser\n popularity 0.000024\n description Print one column\n extends abstractTableVisualizationParser\n example\n printColumn tags\n catchAllAtomType columnNameAtom\n joinParser\n boolean allowTrailingWhitespace true\n cueFromId\n atoms cueAtom\n catchAllAtomType stringAtom\n javascript\n buildHtml() {\n return this.columnValues.join(this.join)\n }\n buildTxt() {\n return this.columnValues.join(this.join)\n }\n get join() {\n return this.get(\"join\") || \"\\n\"\n }\n get columnName() {\n return this.atoms[1]\n }\n get columnValues() {\n return this.parent.coreTable.map(row => row[this.columnName])\n }\nprintTableParser\n popularity 0.001085\n cueFromId\n description Print table.\n extends abstractTableVisualizationParser\n javascript\n get tableHeader() {\n return this.columns.filter(col => !col.isLink).map(column => `<th>${column.name}</th>\\n`)\n }\n get columnNames() {\n return this.parent.columnNames\n }\n buildJson() {\n return JSON.stringify(this.coreTable, undefined, 2)\n }\n buildCsv() {\n return new Particle(this.coreTable).asCsv\n }\n buildTsv() {\n return new Particle(this.coreTable).asTsv\n }\n get columns() {\n const {columnNames} = this\n return columnNames.map((name, index) => {\n const isLink = name.endsWith(\"Link\")\n const linkIndex = columnNames.indexOf(name + \"Link\")\n return {\n name,\n isLink,\n linkIndex\n }\n })\n }\n toRow(row) {\n const {columns} = this\n const atoms = columns.map(col => row[col.name])\n let str = \"\"\n let column = 0\n const columnCount = columns.length\n while (column < columnCount) {\n const col = columns[column]\n column++\n const content = ((columnCount === column ? atoms.slice(columnCount - 1).join(\" \") : atoms[column - 1]) ?? \"\").toString()\n if (col.isLink) continue\n const isTimestamp = col.name.toLowerCase().includes(\"time\") && /^\\d{10}(\\d{3})?$/.test(content)\n const text = isTimestamp ? new Date(parseInt(content.length === 10 ? content * 1000 : content)).toLocaleString() : content\n let tagged = text\n const link = atoms[col.linkIndex]\n const isUrl = content.match(/^https?\\:[^ ]+$/)\n if (col.linkIndex > -1 && link) tagged = `<a href=\"${link}\">${text}</a>`\n else if (col.name.endsWith(\"Url\")) tagged = `<a href=\"${content}\">${col.name.replace(\"Url\", \"\")}</a>`\n else if (isUrl) tagged = `<a href=\"${content}\">${text}</a>`\n str += `<td>${tagged}</td>\\n`\n }\n return str\n }\n get coreTable() {\n return this.parent.coreTable\n }\n get tableBody() {\n return this.coreTable\n .map(row => `<tr>${this.toRow(row)}</tr>`)\n .join(\"\\n\")\n }\n buildHtml() {\n return `<table id=\"table${this._getUid()}\" class=\"scrollTable\">\n <thead><tr>${this.tableHeader.join(\"\\n\")}</tr></thead>\n <tbody>${this.tableBody}</tbody>\n </table>`\n }\n buildTxt() {\n return this.parent.delimitedData || new Particle(this.coreTable).asCsv\n }\nkatexParser\n popularity 0.001592\n extends abstractScrollWithRequirementsParser\n catchAllAtomType codeAtom\n catchAllParser lineOfCodeParser\n example\n katex\n \\text{E} = \\text{T} / \\text{A}!\n description KaTex widget for typeset math.\n string copyFromExternal .katex.min.css .katex.min.js\n string requireOnce\n <link rel=\"stylesheet\" href=\".katex.min.css\">\n <script defer src=\".katex.min.js\"></script>\n <script>\n document.addEventListener(\"DOMContentLoaded\", () => document.querySelectorAll(\".scrollKatex\").forEach(el =>\n {\n katex.render(el.innerText, el, {\n throwOnError: false\n });\n }\n ))\n </script>\n javascript\n buildInstance() {\n const id = this._getUid()\n const content = this.content === undefined ? \"\" : this.content\n return `<div class=\"scrollKatex\" id=\"${id}\">${content + this.subparticlesToString()}</div>`\n }\n buildTxt() {\n return ( this.content ? this.content : \"\" )+ this.subparticlesToString()\n }\nhelpfulNotFoundParser\n popularity 0.000048\n extends abstractScrollWithRequirementsParser\n catchAllAtomType filePathAtom\n string copyFromExternal .helpfulNotFound.js\n description Helpful not found widget.\n javascript\n buildInstance() {\n return `<style>#helpfulNotFound{margin: 100px 0;}</style><h1 id=\"helpfulNotFound\"></h1><script defer src=\"/.helpfulNotFound.js\"></script><script>document.addEventListener(\"DOMContentLoaded\", () => new NotFoundApp('${this.content}'))</script>`\n }\nslideshowParser\n // Left and right arrows navigate.\n description Slideshow widget. *** delimits slides.\n extends abstractScrollWithRequirementsParser\n string copyFromExternal .jquery-3.7.1.min.js .slideshow.js\n example\n slideshow\n Why did the cow cross the road?\n ***\n Because it wanted to go to the MOOOO-vies.\n ***\n THE END\n ****\n javascript\n buildHtml() {\n return `<style>html {font-size: var(--scrollBaseFontSize, 28px);} body {margin: auto; width: 500px;}.slideshowNav{text-align: center; margin-bottom:20px; font-size: 24px;color: rgba(204,204,204,.8);} a{text-decoration: none; color: rgba(204,204,204,.8);}</style><script defer src=\".jquery-3.7.1.min.js\"></script><div class=\"slideshowNav\"></div><script defer src=\".slideshow.js\"></script>`\n }\ntableSearchParser\n popularity 0.000072\n extends abstractScrollWithRequirementsParser\n string copyFromExternal .jquery-3.7.1.min.js .datatables.css .dayjs.min.js .datatables.js .tableSearch.js\n string requireOnce\n <script defer src=\".jquery-3.7.1.min.js\"></script>\n <style>.dt-search{font-family: \"SF Pro\", \"Helvetica Neue\", \"Segoe UI\", \"Arial\";}</style>\n <link rel=\"stylesheet\" href=\".datatables.css\">\n <script defer src=\".datatables.js\"></script>\n <script defer src=\".dayjs.min.js\"></script>\n <script defer src=\".tableSearch.js\"></script>\n // adds to all tables on page\n description Table search and sort widget.\n javascript\n buildInstance() {\n return \"\"\n }\nabstractCommentParser\n description Prints nothing.\n catchAllAtomType commentAtom\n atoms commentAtom\n extends abstractScrollParser\n baseParser blobParser\n string bindTo next\n javascript\n buildHtml() {\n return ``\n }\n catchAllParser commentLineParser\ncommentParser\n popularity 0.000193\n extends abstractCommentParser\n cueFromId\ncounterpointParser\n description Counterpoint comment. Prints nothing.\n extends commentParser\n cue !\nslashCommentParser\n popularity 0.005643\n extends abstractCommentParser\n cue //\n boolean isPopular true\n description A comment. Prints nothing.\nthanksToParser\n description Acknowledgements comment. Prints nothing.\n extends abstractCommentParser\n cueFromId\nscrollClearStackParser\n popularity 0.000096\n cue clearStack\n description Clear body stack.\n extends abstractScrollParser\n boolean isHtml true\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n return this.root.clearBodyStack().trim()\n }\ncssParser\n popularity 0.007211\n extends abstractScrollParser\n description A style tag.\n example\n css\n body { color: red;}\n cueFromId\n catchAllParser cssLineParser\n catchAllAtomType cssAnyAtom\n javascript\n buildHtml() {\n return `<style>${this.css}</style>`\n }\n get css() {\n return this.content ?? this.subparticlesToString()\n }\n buildCss() {\n return this.css\n }\nscrollBackgroundColorParser\n description Quickly set CSS background.\n popularity 0.007211\n extends abstractScrollParser\n cue background\n catchAllAtomType cssAnyAtom\n example\n background red\n javascript\n buildHtml() {\n return `<style>html, body { background: ${this.content};}</style>`\n }\nscrollFontColorParser\n description Quickly set CSS font-color.\n popularity 0.007211\n extends abstractScrollParser\n cue color\n catchAllAtomType cssAnyAtom\n javascript\n buildHtml() {\n return `<style>html, body { color: ${this.content};}</style>`\n }\nscrollFontParser\n description Quickly set font family.\n popularity 0.007211\n extends abstractScrollParser\n cue font\n atoms cueAtom fontFamilyAtom\n catchAllAtomType cssAnyAtom\n example\n font Slim\n javascript\n buildHtml() {\n const font = this.content === \"Slim\" ? \"Helvetica Neue; font-weight:100;\" : this.content\n return `<style>html, body, h1,h2,h3 { font-family: ${font};}</style>`\n }\nabstractQuickIncludeParser\n popularity 0.007524\n extends abstractScrollParser\n atoms urlAtom\n javascript\n get dependencies() { return [this.filename]}\n get filename() {\n return this.getAtom(0)\n }\nquickCssParser\n popularity 0.007524\n description Make a CSS tag.\n extends abstractQuickIncludeParser\n example\n style.css\n atoms urlAtom\n pattern ^[^\\s]+\\.(css)$\n javascript\n buildHtml() {\n return `<link rel=\"stylesheet\" type=\"text/css\" href=\"${this.filename}\">`\n }\n buildHtmlSnippet() {\n return \"\"\n }\nquickIncludeHtmlParser\n popularity 0.007524\n description Include an HTML file.\n extends abstractQuickIncludeParser\n example\n body.html\n atoms urlAtom\n pattern ^[^\\s]+\\.(html|htm)$\n javascript\n buildHtml() {\n return this.root.readFile(this.filename)\n }\nquickScriptParser\n popularity 0.007524\n description Make a Javascript tag.\n extends abstractQuickIncludeParser\n atoms urlAtom\n example\n script.js\n pattern ^[^\\s]+\\.(js)$\n javascript\n attr = \"\"\n buildHtml() {\n return `<script ${this.attr} src=\"${this.filename}\"></script>`\n }\n buildHtmlSnippet() {\n return \"\"\n }\nquickModuleScriptParser\n description Make a Javascript module tag.\n extends quickScriptParser\n example\n script.mjs\n pattern ^[^\\s]+\\.(mjs)$\n javascript\n attr = 'type=\"module\"'\nscrollDashboardParser\n popularity 0.000145\n description Key stats in large font.\n catchAllParser lineOfCodeParser\n cue dashboard\n extends abstractScrollParser\n example\n dashboard\n #2 Popularity\n 30 Years Old\n $456 Revenue\n javascript\n get tableBody() {\n const items = this.topDownArray\n let str = \"\"\n for (let i = 0; i < items.length; i = i + 3) {\n str += this.makeRow(items.slice(i, i + 3))\n }\n return str\n }\n makeRow(items) {\n return `<tr>` + items.map(particle => `<td>${particle.cue}<span>${particle.content}</span></td>`).join(\"\\n\") + `</tr>\\n`\n }\n buildHtml() {\n return `<table class=\"scrollDashboard\">${this.tableBody}</table>`\n }\n buildTxt() {\n return this.subparticlesToString()\n }\nbelowAsCodeParser\n popularity 0.000651\n description Print code below.\n string bindTo next\n extends abstractScrollParser\n catchAllAtomType integerAtom\n example\n belowAsCode\n iris\n printTable\n cueFromId\n javascript\n method = \"next\"\n get selectedParticles() {\n const { method } = this\n let code = \"\"\n let particles = []\n let next = this[method]\n let {howMany} = this\n while (howMany) {\n particles.push(next)\n next = next[method]\n howMany--\n }\n if (this.reverse) particles.reverse()\n return particles\n }\n get code() {\n return this.selectedParticles.map(particle => particle.asString).join(\"\\n\")\n }\n reverse = false\n buildHtml() {\n return `<code class=\"scrollCodeBlock\">${this.code.replace(/\\</g, \"&lt;\")}</code>`\n }\n get howMany() {\n let howMany = parseInt(this.getAtom(1))\n if (!howMany || isNaN(howMany)) howMany = 1\n return howMany\n }\ndebugBelowParser\n description Inspect particle below.\n extends belowAsCodeParser\n string copyFromExternal .debug.css\n javascript\n get code() {\n const mapFn = particle => {\n const atomTypes = particle.lineAtomTypes.split(\" \")\n return `<div class=\"debugParticle\"><span class=\"debugParticleId\">${particle.constructor.name}</span>${particle.atoms.map((atom, index) => `<span class=\"debugAtom\">${atom}<span class=\"debugAtomType\">${atomTypes[index]}</span></span>`).join(\" \")}${(particle.length ? `<br><div class=\"debugSubparticles\">` + particle.map(mapFn).join(\"<br>\") + `</div>` : \"\")}</div>`}\n return this.selectedParticles.map(mapFn).join(\"<br>\")\n }\n buildHtml() {\n return `<link rel=\"stylesheet\" href=\".debug.css\">` + this.code\n }\n buildTxt() {\n const mapFn = particle => {\n const atomTypes = particle.lineAtomTypes.split(\" \")\n return `${particle.constructor.name} ${particle.atoms.map((atom, index) => `${atomTypes[index]}:${atom}`).join(\" \")}${(particle.length ? `\\n ` + particle.map(mapFn).join(\"\\n\") + `` : \"\")}`}\n return this.selectedParticles.map(mapFn).join(\"\\n\")\n }\n buildParsers() {return this.buildTxt()}\ndebugAboveParser\n description Inspect particle above.\n extends debugBelowParser\n string bindTo previous\n javascript\n method = \"previous\"\n reverse = true\ndebugAllParser\n description Inspect entire document.\n extends debugBelowParser\n javascript\n get selectedParticles() { return this.root.getSubparticles()}\nbelowAsCodeUntilParser\n description Print code above until match.\n extends belowAsCodeParser\n catchAllAtomType codeAtom\n example\n belowAsCode\n counter 1 second\n javascript\n get howMany() {\n let howMany = 1\n const query = this.content\n let particle = this.next\n while (particle !== this) {\n if (particle.getLine().startsWith(query))\n return howMany\n particle = particle.next\n howMany++\n }\n return howMany\n }\naboveAsCodeParser\n popularity 0.000482\n string bindTo previous\n description Print code above.\n example\n counter 1 second\n aboveAsCode\n extends belowAsCodeParser\n javascript\n method = \"previous\"\n reverse = true\nbelowAsHtmlParser\n extends belowAsCodeParser\n description Displays html output of next particle in a code block.\n cueFromId\n example\n belowAsHtml\n # Hello world\n javascript\n get code() {\n return this.selectedParticles.filter(p => p.buildHtml).map(p => p.buildHtml()).join(\"\\n\")\n }\naboveAsHtmlParser\n description Displays html output of previous particle in a code block.\n extends belowAsHtmlParser\n example\n # Hello world\n aboveAsHtml\n javascript\n method = \"previous\"\n reverse = true\nscrollDefParser\n popularity 0.004244\n description Parser short form.\n pattern ^[a-zA-Z0-9_]+Def\n extends abstractScrollParser\n catchAllAtomType stringAtom\n example\n urlDef What is the URL?\n javascript\n buildParsers(index) {\n const idStuff = index ? \"\" : `boolean isMeasure true\n boolean isMeasureRequired true\n boolean isConceptDelimiter true`\n const description = this.content\n const cue = this.cue.replace(\"Def\", \"\")\n const sortIndex = 1 + index/10\n return `${cue}DefParser\n cue ${cue}\n extends abstractStringMeasureParser\n description ${description}\n float sortIndex ${sortIndex}\n ${idStuff}`.trim()\n }\nhakonParser\n cueFromId\n extends abstractScrollParser\n description Compile Hakon to CSS.\n catchAllParser hakonContentParser\n javascript\n buildHtml() {\n return `<style>${this.css}</style>`\n }\n get css() {\n const {hakonParser} = this.root\n return new hakonParser(this.subparticlesToString()).compile()\n }\n buildCss() {\n return this.css\n }\nhamlParser\n popularity 0.007524\n description HTML tag via HAML syntax.\n extends abstractScrollParser\n atoms urlAtom\n catchAllAtomType stringAtom\n pattern ^%?[\\w\\.]+#[\\w\\.]+ *\n javascript\n get tag() {\n return this.atoms[0].split(/[#\\.]/).shift().replace(\"%\", \"\")\n }\n get htmlId() {\n const idMatch = this.atoms[0].match(/#([\\w-]+)/)\n return idMatch ? idMatch[1] : \"\"\n }\n get htmlClasses() {\n return this.atoms[0].match(/\\.([\\w-]+)/g)?.map(cls => cls.slice(1)) || [];\n }\n buildHtml() {\n const {htmlId, htmlClasses, content, tag} = this\n this.parent.sectionStack.unshift(`</${tag}>`)\n const attrs = [htmlId ? ' id=\"' + htmlId + '\"' : \"\", htmlClasses.length ? ' class=\"' + htmlClasses.join(\" \") + '\"' : \"\"].join(\" \").trim()\n return `<${tag}${attrs ? \" \" + attrs : \"\"}>${content || \"\"}`\n }\n buildTxt() {\n return this.content\n }\nhamlTagParser\n // Match plain tags like %h1\n extends hamlParser\n pattern ^%[^#]+$\nabstractHtmlParser\n extends abstractScrollParser\n catchAllParser htmlLineParser\n catchAllAtomType htmlAnyAtom\n javascript\n buildHtml() {\n return `${this.content ?? \"\"}${this.subparticlesToString()}`\n }\n buildTxt() {\n return \"\"\n }\nhtmlParser\n popularity 0.000048\n extends abstractHtmlParser\n description HTML one liners or blocks.\n cueFromId\nhtmlInlineParser\n popularity 0.005788\n extends abstractHtmlParser\n atoms htmlAnyAtom\n boolean isHtml true\n example\n <h1>Inline HTML</h1>\n pattern ^<\n description Inline HTML.\n boolean isPopular true\n javascript\n buildHtml() {\n return `${this.getLine() ?? \"\"}${this.subparticlesToString()}`\n }\nscrollBrParser\n popularity 0.000096\n cue br\n example\n br 2\n description A break.\n extends abstractScrollParser\n catchAllAtomType integerAtom\n boolean isHtml true\n javascript\n buildHtml() {\n return `<br>`.repeat(parseInt(this.getAtom(1) || 1))\n }\niframesParser\n popularity 0.000121\n cueFromId\n catchAllAtomType urlAtom\n extends abstractScrollParser\n description An iframe(s).\n example\n iframes frame.html\n javascript\n buildHtml() {\n return this.atoms.slice(1).map(url => `<iframe src=\"${url}\" frameborder=\"0\"></iframe>`).join(\"\\n\")\n }\nabstractCaptionedParser\n extends abstractScrollParser\n atoms cueAtom urlAtom\n inScope captionAftertextParser slashCommentParser\n cueFromId\n javascript\n buildHtml(buildSettings) {\n const caption = this.getParticle(\"caption\")\n const captionFig = caption ? `<figcaption>${caption.buildHtml()}</figcaption>` : \"\"\n const {figureWidth} = this\n const widthStyle = figureWidth ? `width:${figureWidth}px; margin: auto;` : \"\"\n const float = this.has(\"float\") ? `margin: 20px; float: ${this.get(\"float\")};` : \"\"\n return `<figure class=\"scrollCaptionedFigure\" style=\"${widthStyle + float}\">${this.getFigureContent(buildSettings)}${captionFig}</figure>`\n }\n get figureWidth() {\n return this.get(\"width\")\n }\nscrollImageParser\n cue image\n popularity 0.005908\n description An img tag.\n boolean isPopular true\n extends abstractCaptionedParser\n int atomIndex 1\n example\n image screenshot.png\n caption A caption.\n inScope addClassMarkupParser aftertextIdParser scrollLinkParser linkTargetParser openGraphParser\n javascript\n get dimensions() {\n const width = this.get(\"width\")\n const height = this.get(\"height\")\n if (width || height)\n return {width, height}\n if (!this.isNodeJs())\n return {}\n const src = this.filename\n // If its a local image, get the dimensions and put them in the HTML\n // to avoid flicker\n if (src.startsWith(\"http:\") || src.startsWith(\"https:\")) return {}\n if (this._dimensions)\n return this._dimensions\n try {\n const sizeOf = require(\"image-size\")\n const path = require(\"path\")\n const fullImagePath = path.join(this.root.folderPath, src)\n this._dimensions = sizeOf(fullImagePath)\n return this._dimensions\n } catch (err) {\n console.error(err)\n }\n return {}\n }\n get figureWidth() {\n return this.dimensions.width\n }\n get filename() {\n return this.getAtom(this.atomIndex)\n }\n get dependencies() { return [this.filename]}\n getFigureContent(buildSettings) {\n const linkRelativeToCompileTarget = (buildSettings ? (buildSettings.relativePath ?? \"\") : \"\") + this.filename\n const {width, height} = this.dimensions\n let dimensionAttributes = width || height ? `width=\"${width}\" height=\"${height}\" ` : \"\"\n // Todo: can we reuse more code from aftertext?\n const className = this.has(\"class\") ? ` class=\"${this.get(\"class\")}\" ` : \"\"\n const id = this.has(\"id\") ? ` id=\"${this.get(\"id\")}\" ` : \"\"\n const clickLink = this.find(particle => particle.definition.isOrExtendsAParserInScope([\"scrollLinkParser\"])) || linkRelativeToCompileTarget \n const target = this.has(\"target\") ? this.get(\"target\") : (this.has(\"link\") ? \"\" : \"_blank\")\n return `<a href=\"${clickLink}\" target=\"${target}\" ${className} ${id}><img src=\"${linkRelativeToCompileTarget}\" ${dimensionAttributes}loading=\"lazy\"></a>`\n }\n buildTxt() {\n const subparticles = this.filter(particle => particle.buildTxt).map(particle => particle.buildTxt()).filter(i => i).join(\"\\n\")\n return \"[Image Omitted]\" + (subparticles ? \"\\n \" + subparticles.replace(/\\n/g, \"\\n \") : \"\")\n }\nquickImageParser\n popularity 0.005788\n extends scrollImageParser\n example\n screenshot.png\n atoms urlAtom\n pattern ^[^\\s]+\\.(jpg|jpeg|png|gif|webp|svg|bmp)\n int atomIndex 0\nqrcodeParser\n extends abstractCaptionedParser\n description Make a QR code from a link.\n example\n qrcode https://scroll.pub\n javascript\n getFigureContent() {\n const url = this.atoms[1]\n const isNode = this.isNodeJs()\n if (isNode) {\n const {externalsPath} = this.root\n const path = require(\"path\")\n const {qrcodegen, toSvgString} = require(path.join(externalsPath, \".qrcodegen.js\"))\n const QRC = qrcodegen.QrCode;\n const qr0 = QRC.encodeText(url, QRC.Ecc.MEDIUM);\n const svg = toSvgString(qr0, 4); // See qrcodegen-input-demo\n return svg\n }\n return `Not yet supported in browser.`\n }\nyoutubeParser\n popularity 0.000121\n extends abstractCaptionedParser\n // Include the YouTube embed URL such as https://www.youtube.com/embed/CYPYZnVQoLg\n description A YouTube video widget.\n example\n youtube https://www.youtube.com/watch?v=lO8blNtYYBA\n javascript\n getFigureContent() {\n const url = this.getAtom(1).replace(\"youtube.com/watch?v=\", \"youtube.com/embed/\")\n return `<div class=\"scrollYouTubeHolder\"><iframe class=\"scrollYouTubeEmbed\" src=\"${url}\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe></div>`\n }\nyouTubeParser\n extends youtubeParser\n tags deprecate\n // Deprecated. You youtube all lowercase.\nimportParser\n description Import a file.\n popularity 0.007524\n cueFromId\n atoms preBuildCommandAtom\n extends abstractScrollParser\n catchAllAtomType filePathAtom\n javascript\n buildHtml() {\n return \"\"\n }\n example\n import header.scroll\nscrollImportedParser\n description Inserted at import pass.\n boolean suggestInAutocomplete false\n cue imported\n atoms preBuildCommandAtom\n extends abstractScrollParser\n baseParser blobParser\n catchAllAtomType filePathAtom\n javascript\n buildHtml() {\n return \"\"\n }\n getErrors() {\n if (this.get(\"exists\") === \"false\" && this.previous.getLine() !== \"// optional\")\n return [this.makeError(`File '${this.atoms[1]}' does not exist.`)]\n return []\n }\nquickImportParser\n popularity 0.007524\n description Import a Scroll or Parsers file.\n extends abstractScrollParser\n boolean isPopular true\n inScope importToFooterParser abstractCommentParser\n atoms urlAtom\n pattern ^[^\\s]+\\.(scroll|parsers)$\n javascript\n buildHtml() {\n return \"\"\n }\n example\n header.scroll\nscriptParser\n extends abstractScrollParser\n description Print script tag.\n cueFromId\n catchAllParser scriptLineParser\n catchAllAtomType javascriptAnyAtom\n javascript\n buildHtml() {\n return `<script>${this.scriptContent}</script>`\n }\n get scriptContent() {\n return this.content ?? this.subparticlesToString()\n }\n buildJs() {\n return this.scriptContent\n }\njsonScriptParser\n popularity 0.007524\n cueFromId\n description Include JSON and assign to window.\n extends abstractScrollParser\n atoms cueAtom urlAtom\n javascript\n buildHtml() {\n const varName = this.filename.split(\"/\").pop().replace(\".json\", \"\")\n return `<script>window.${varName} = ${this.root.readFile(this.filename)}</script>`\n }\n get filename() {\n return this.getAtom(1)\n }\nscrollLeftRightButtonsParser\n popularity 0.006342\n cue leftRightButtons\n description Previous and next nav buttons.\n extends abstractScrollParser\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n const { linkToPrevious, linkToNext } = this.root\n if (!linkToPrevious) return \"\"\n const style = `a.keyboardNav {display:block;position:absolute;top:0.25rem; color: rgba(204,204,204,.8); font-size: 1.875rem; line-height: 1.7rem;}a.keyboardNav:hover{color: #333;text-decoration: none;}`\n return `<style>${style}</style><a class=\"keyboardNav doNotPrint\" style=\"left:.5rem;\" href=\"${linkToPrevious}\">&lt;</a><a class=\"keyboardNav doNotPrint\" style=\"right:.5rem;\" href=\"${linkToNext}\">&gt;</a>`\n }\nkeyboardNavParser\n popularity 0.007476\n description Make left and right navigate files.\n extends abstractScrollParser\n cueFromId\n catchAllAtomType urlAtom\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n const {root} = this\n const linkToPrevious = this.getAtom(1) ?? root.linkToPrevious\n const linkToNext = this.getAtom(2) ?? root.linkToNext\n const script = `<script>document.addEventListener('keydown', function(event) {\n if (document.activeElement !== document.body) return\n if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return // dont interfere with keyboard back button shortcut\n const getLinks = () => document.getElementsByClassName(\"scrollKeyboardNav\")[0].getElementsByTagName(\"a\")\n if (event.key === \"ArrowLeft\")\n getLinks()[0].click()\n else if (event.key === \"ArrowRight\")\n getLinks()[1].click()\n });</script>`\n return `<div class=\"scrollKeyboardNav\" style=\"display:none;\"><a href=\"${linkToPrevious}\">${linkToPrevious}</a> · ${root.permalink} · <a href=\"${linkToNext}\">${linkToNext}</a>${script}</div>`\n }\nprintUsageStatsParser\n popularity 0.000096\n // todo: if we include the atom \"Parser\" in a cue, bad things seem to happen.\n description Parser usage stats for folder.\n extends abstractScrollParser\n cueFromId\n javascript\n get stats() {\n const input = this.root.allScrollFiles.map(file => file.scrollProgram).map(program => program.parserIds.join(\"\\n\")).join(\"\\n\")\n const result = input.split('\\n').reduce((acc, atom) => (acc[atom] = (acc[atom] || 0) + 1, acc), {})\n const rows = Object.entries(result).map(([atom, count]) => { return {atom, count}})\n const sorted = this.root.lodash.sortBy(rows, \"count\").reverse()\n return \"parserId uses\\n\" + sorted.map(row => `${row.atom} ${row.count}`).join('\\n')\n }\n buildHtml() {\n // A hacky but simple way to do this for now.\n const particle = this.appendSibling(\"table\")\n particle.appendLine(\"delimiter \")\n particle.appendLine(\"printTable\")\n const dataParticle = particle.appendLine(\"data\")\n dataParticle.setSubparticles(this.stats)\n const html = particle.buildHtml()\n particle.destroy()\n return html\n }\n buildTxt() {\n return this.stats\n }\n buildCsv() {\n return this.stats.replace(/ /g, \",\")\n }\nprintScrollLeetSheetParser\n popularity 0.000024\n description Print Scroll parser leet sheet.\n extends abstractScrollParser\n tags experimental\n cueFromId\n javascript\n get parsersToDocument() {\n const clone = this.root.clone()\n clone.setSubparticles(\"\")\n const atoms = clone.getAutocompleteResultsAt(0,0).matches.map(a => a.text)\n atoms.push(\"blankline\") // manually add blank line\n atoms.push(\"Catch All Paragraph.\") // manually add catch all paragraph\n atoms.push(\"<h></h>\") // manually add html\n atoms.sort()\n clone.setSubparticles(atoms.join(\"\\n\").replace(/blankline/, \"\")) // insert blank line in right spot\n return clone\n }\n sortDocs(docs) {\n return docs.map(particle => {\n const {definition} = particle\n const {id, description, isPopular, examples, popularity} = definition\n const tags = definition.get(\"tags\") || \"\"\n if (tags.includes(\"deprecate\") || tags.includes(\"experimental\"))\n return null\n const category = this.getCategory(tags)\n const note = this.getNote(category)\n return {id: definition.cueIfAny || id, description, isPopular, examples, note, popularity: Math.ceil(parseFloat(popularity) * 100000)}\n }).filter(i => i).sort((a, b) => a.id.localeCompare(b.id))\n }\n makeLink(examples, cue) {\n // if (!examples.length) console.log(cue) // find particles that need docs\n const example = examples.length ? examples[0].subparticlesToString() : cue\n const base = `https://try.scroll.pub/`\n const particle = new Particle()\n particle.appendLineAndSubparticles(\"scroll\", \"theme gazette\\n\" + example)\n return base + \"#\" + encodeURIComponent(particle.asString)\n }\n docToHtml(doc) {\n const css = `#scrollLeetSheet {color: grey;} #scrollLeetSheet a {color: #3498db; }`\n return `<style>${css}</style><div id=\"scrollLeetSheet\">` + doc.map(obj => `<div class=\"${obj.category}\"><a href=\"${this.makeLink(obj.examples, obj.id)}\">${obj.isPopular ? \"<b>\" : \"\"}${obj.id}</a> ${obj.description}${obj.isPopular ? \"</b>\" : \"\"}${obj.note}</div>`).join(\"\\n\") + \"</div>\"\n }\n buildHtml() {\n return this.docToHtml(this.sortDocs(this.parsersToDocument))\n }\n buildTxt() {\n return this.sortDocs(this.parsersToDocument).map(obj => `${obj.id} - ${obj.description}`).join(\"\\n\")\n }\n getCategory(input) {\n return \"\"\n }\n getNote() {\n return \"\"\n }\n get docs() {\n const rows = this.sortDocs(this.parsersToDocument).map(obj => {\n const {id, isPopular, description, popularity, category, examples, cue} = obj\n const example = examples.length ? examples[0].subparticlesToString() : cue\n return {\n id,\n isPopular,\n description,\n popularity,\n example,\n category\n }\n })\n return this.root.lodash.sortBy(rows, \"isPopular\")\n }\n buildJson() {\n return JSON.stringify(this.docs, undefined, 2)\n }\n buildCsv() {\n return new Particle(this.docs).asCsv\n }\nprintparsersLeetSheetParser\n popularity 0.000024\n // todo: fix parse bug when atom Parser appears in parserId\n extends printScrollLeetSheetParser\n tags experimental\n description Parsers leetsheet.\n javascript\n buildHtml() {\n return \"<p><b>Parser Definition Parsers</b> define parsers that acquire, analyze and act on code.</p>\" + this.docToHtml(this.sortDocs(this.parsersToDocument)) + \"<p><b>Atom Definition Parsers</b> analyze the atoms in a line.</p>\" + this.docToHtml(this.sortDocs(this.atomParsersToDocument))\n }\n makeLink() {\n return \"\"\n }\n categories = \"assemblePhase acquirePhase analyzePhase actPhase\".split(\" \")\n getCategory(tags) {\n return tags.split(\" \").filter(w => w.endsWith(\"Phase\"))[0]\n }\n getNote(category) {\n return ` <span class=\"note\">A${category.replace(\"Phase\", \"\").substr(1)}Time.</span>`\n }\n get atomParsersToDocument() {\n const parsersParser = require(\"scrollsdk/products/parsers.nodejs.js\")\n const clone = new parsersParser(\"anyAtom\\n \").clone()\n const parserParticle = clone.getParticle(\"anyAtom\")\n const atoms = clone.getAutocompleteResultsAt(1,1).matches.map(a => a.text)\n atoms.sort()\n parserParticle.setSubparticles(atoms.join(\"\\n\"))\n return parserParticle\n }\n get parsersToDocument() {\n const parsersParser = require(\"scrollsdk/products/parsers.nodejs.js\")\n const clone = new parsersParser(\"latinParser\\n \").clone()\n const parserParticle = clone.getParticle(\"latinParser\")\n const atoms = clone.getAutocompleteResultsAt(1,1).matches.map(a => a.text)\n atoms.sort()\n parserParticle.setSubparticles(atoms.join(\"\\n\"))\n clone.appendLine(\"myParser\")\n clone.appendLine(\"myAtom\")\n return parserParticle\n }\nabstractMeasureParser\n atoms measureNameAtom\n description Base parser all measures extend.\n cueFromId\n boolean isMeasure true\n float sortIndex 1.9\n boolean isComputed false\n string typeForWebForms text\n extends abstractScrollParser\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n return \"\"\n }\n get measureValue() {\n return this.content ?? \"\"\n }\n get measureName() {\n return this.getCuePath().replace(/ /g, \"_\")\n }\nabstractAtomMeasureParser\n description Contains a single word.\n atoms measureNameAtom atomAtom\n example\n nicknameParser\n extends abstractAtomMeasureParser\n id Breck\n nickname breck\n extends abstractMeasureParser\nabstractEmailMeasureParser\n description Email address.\n example\n emailParser\n extends abstractEmailMeasureParser\n id Breck\n email breck7@gmail.com\n string typeForWebForms email\n atoms measureNameAtom emailAddressAtom\n extends abstractAtomMeasureParser\nabstractUrlMeasureParser\n description A single url.\n example\n homepageParser\n extends abstractUrlMeasureParser\n id Breck\n homepage https://breckyunits.com\n string typeForWebForms url\n atoms measureNameAtom urlAtom\n extends abstractAtomMeasureParser\nabstractStringMeasureParser\n description General text data with no specific format.\n catchAllAtomType stringAtom\n example\n titleParser\n extends abstractStringMeasureParser\n id Breck\n title I build languages for scientists of all ages\n extends abstractMeasureParser\nabstractIdParser\n cue id\n description What is the ID of this concept?\n extends abstractStringMeasureParser\n example\n idParser\n extends abstractIdParser\n id breck\n float sortIndex 1\n boolean isMeasureRequired true\n boolean isConceptDelimiter true\n javascript\n getErrors() {\n const errors = super.getErrors()\n let requiredMeasureNames = this.root.measures.filter(measure => measure.isMeasureRequired).map(measure => measure.Name).filter(name => name !== \"id\")\n if (!requiredMeasureNames.length) return errors\n let next = this.next\n while (requiredMeasureNames.length && next.cue !== \"id\" && next.index !== 0) {\n requiredMeasureNames = requiredMeasureNames.filter(i => i !== next.cue)\n next = next.next\n }\n requiredMeasureNames.forEach(name =>\n errors.push(this.makeError(`Concept \"${this.content}\" is missing required measure \"${name}\".`))\n )\n return errors\n }\nabstractIdMeasureParser\n description Alias for abstractIdParser.\n extends abstractIdParser\nabstractTextareaMeasureParser\n string typeForWebForms textarea\n example\n bioParser\n extends abstractTextareaMeasureParser\n id Breck\n bio\n I build languages for scientists of all ages\n description Long-form text content with preserved line breaks.\n extends abstractMeasureParser\n baseParser blobParser\n javascript\n get measureValue() {\n return this.subparticlesToString().replace(/\\n/g, \"\\\\n\")\n }\nabstractNumericMeasureParser\n string typeForWebForms number\n description Base number type.\n extends abstractMeasureParser\n javascript\n get measureValue() {\n const {content} = this\n return content === undefined ? \"\" : parseFloat(content)\n }\nabstractNumberMeasureParser\n description Alias to abstractNumericMeasureParser.\n extends abstractNumericMeasureParser\nabstractIntegerMeasureParser\n description An integer.\n example\n ageParser\n extends abstractIntegerMeasureParser\n id Breck\n age 40\n atoms measureNameAtom integerAtom\n extends abstractNumericMeasureParser\n javascript\n get measureValue() {\n const {content} = this\n return content === undefined ? \"\" : parseInt(content)\n }\nabstractIntMeasureParser\n description Alias to abstractIntegerMeasureParser.\n extends abstractIntegerMeasureParser\nabstractFloatMeasureParser\n description A float.\n example\n temperatureParser\n extends abstractFloatMeasureParser\n id Breck\n temperature 31.8\n atoms measureNameAtom floatAtom\n extends abstractNumericMeasureParser\nabstractPercentageMeasureParser\n description A percentage.\n atoms measureNameAtom percentAtom\n extends abstractNumericMeasureParser\n example\n ownershipParser\n extends abstractPercentageMeasureParser\n id Breck\n ownership 31.8\n javascript\n get measureValue() {\n const {content} = this\n return content === undefined ? \"\" : parseFloat(content)\n }\nabstractEnumMeasureParser\n description A single enum.\n atoms measureNameAtom enumAtom\n extends abstractMeasureParser\n example\n favoriteHtmlTagParser\n extends abstractEnumMeasureParser\n atoms measureNameAtom htmlTagAtom\n id Breck\n favoriteHtmlTag 2020\nabstractBooleanMeasureParser\n description A single boolean.\n atoms measureNameAtom booleanAtom\n extends abstractMeasureParser\n example\n hasBillOfRightsParser\n extends abstractBooleanMeasureParser\n id USA\n hasBillOfRights true\n javascript\n get measureValue() {\n const {content} = this\n return content === undefined ? \"\" : content == \"true\"\n }\nabstractDateMeasureParser\n description Year/month/day in ISO 8601, US, European formats.\n atoms measureNameAtom dateAtom\n extends abstractMeasureParser\n string typeForWebForms date\n javascript\n get measureValue() {\n const {content} = this\n if (!content) return \"\"\n const {dayjs} = this.root\n try {\n // First try parsing with dayjs\n const parsed = dayjs(content)\n if (parsed.isValid())\n return parsed.format(\"YYYY-MM-DD\")\n // Try parsing other common formats\n const formats = [\n \"MM/DD/YYYY\",\n \"DD/MM/YYYY\", \n \"YYYY/MM/DD\",\n \"MM-DD-YYYY\",\n \"DD-MM-YYYY\",\n \"YYYY-MM-DD\",\n \"DD.MM.YYYY\",\n \"YYYY.MM.DD\"\n ]\n for (const format of formats) {\n const attempt = dayjs(content, format)\n if (attempt.isValid())\n return attempt.format(\"YYYY-MM-DD\")\n }\n } catch (err) {\n console.error(err)\n return \"\"\n }\n return \"\"\n }\n get valueAsTimestamp() {\n const {measureValue} = this\n return measureValue ? this.root.dayjs(measureValue).unix() : \"\"\n }\nmetaTagsParser\n popularity 0.007693\n cueFromId\n extends abstractScrollParser\n description Print meta tags including title.\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n const {root} = this\n const { title, description, canonicalUrl, gitRepo, scrollVersion, openGraphImage, keywords } = root\n const rssFeedUrl = root.get(\"rssFeedUrl\")\n const favicon = root.get(\"favicon\")\n const faviconTag = favicon ? `<link rel=\"icon\" href=\"${favicon}\">` : \"\"\n const keywordsTag = keywords ? `<meta name=\"keywords\" content=\"${keywords}\">` : \"\"\n const rssTag = rssFeedUrl ? `<link rel=\"alternate\" type=\"application/rss+xml\" title=\"${title}\" href=\"${rssFeedUrl}\">` : \"\"\n const gitTag = gitRepo ? `<link rel=\"source\" type=\"application/git\" title=\"Source Code Repository\" href=\"${gitRepo}\">` : \"\"\n return `<head>\n <meta charset=\"utf-8\">\n <title>${title}</title>\n <script>/* This HTML was generated by 📜 Scroll v${scrollVersion}. https://scroll.pub */</script>\n <style>@media print {.doNotPrint {display: none !important;}}</style>\n <link rel=\"canonical\" href=\"${canonicalUrl}\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n <meta name=\"description\" content=\"${description}\">\n ${keywordsTag}\n <meta name=\"generator\" content=\"Scroll v${scrollVersion}\">\n <meta property=\"og:title\" content=\"${title}\">\n <meta property=\"og:description\" content=\"${description}\">\n <meta property=\"og:image\" content=\"${openGraphImage}\">\n ${faviconTag}\n ${gitTag}\n ${rssTag}\n <meta name=\"twitter:card\" content=\"summary_large_image\">\n </head>\n <body>`\n }\nquoteParser\n popularity 0.001471\n cueFromId\n description A quote.\n catchAllParser quoteLineParser\n extends abstractScrollParser\n javascript\n buildHtml() {\n return `<blockquote class=\"scrollQuote\">${this.subparticlesToString()}</blockquote>`\n }\n buildTxt() {\n return this.subparticlesToString()\n }\nredirectToParser\n popularity 0.000072\n description HTML redirect tag.\n extends abstractScrollParser\n atoms cueAtom urlAtom\n cueFromId\n example\n redirectTo https://scroll.pub/releaseNotes.html\n javascript\n buildHtml() {\n return `<meta http-equiv=\"Refresh\" content=\"0; url='${this.getAtom(1)}'\" />`\n }\nabstractVariableParser\n extends abstractScrollParser\n catchAllAtomType stringAtom\n atoms preBuildCommandAtom\n cueFromId\n javascript\n isTopMatter = true\n buildHtml() {\n return \"\"\n }\nreplaceParser\n description Replace this with that.\n extends abstractVariableParser\n baseParser blobParser\n example\n replace YEAR 2022\nreplaceJsParser\n description Replace this with evaled JS.\n extends replaceParser\n catchAllAtomType javascriptAnyAtom\n example\n replaceJs SUM 1+1\n * 1+1 = SUM\nreplaceNodejsParser\n description Replace with evaled Node.JS.\n extends abstractVariableParser\n catchAllAtomType javascriptAnyAtom\n baseParser blobParser\n example\n replaceNodejs\n module.exports = {SCORE : 1 + 2}\n * The score is SCORE\ntoFooterParser\n extends abstractScrollParser\n description Experimental way to move a section to the footer.\n atoms preBuildCommandAtom\n cueFromId\nrunScriptParser\n popularity 0.000024\n description Run script and dump stdout.\n extends abstractScrollParser\n atoms cueAtom urlAtom\n cue run\n int filenameIndex 1\n javascript\n get dependencies() { return [this.filename]}\n results = \"Not yet run\"\n async execute() {\n if (!this.filename) return\n await this.root.fetch(this.filename)\n // todo: make async\n const { execSync } = require(\"child_process\")\n this.results = execSync(this.command)\n }\n get command() {\n const path = this.root.path\n const {filename }= this\n const fullPath = this.root.makeFullPath(filename)\n const ext = path.extname(filename).slice(1)\n const interpreterMap = {\n php: \"php\",\n py: \"python3\",\n rb: \"ruby\",\n pl: \"perl\",\n sh: \"sh\"\n }\n return [interpreterMap[ext], fullPath].join(\" \")\n }\n buildHtml() {\n return this.buildTxt()\n }\n get filename() {\n return this.getAtom(this.filenameIndex)\n }\n buildTxt() {\n return this.results.toString().trim()\n }\nquickRunScriptParser\n extends runScriptParser\n atoms urlAtom\n pattern ^[^\\s]+\\.(py|pl|sh|rb|php)$\n int filenameIndex 0\nendSnippetParser\n popularity 0.004293\n description Cut for snippet here.\n extends abstractScrollParser\n cueFromId\n javascript\n buildHtml() {\n return \"\"\n }\ntoStampParser\n description Print a directory to stamp.\n extends abstractScrollParser\n catchAllAtomType filePathAtom\n cueFromId\n javascript\n buildTxt() {\n return this.makeStamp(this.content)\n }\n buildHtml() {\n return `<pre>${this.buildTxt()}</pre>`\n }\n makeStamp(dir) {\n const fs = require('fs');\n const path = require('path');\n const { execSync } = require('child_process');\n let stamp = 'stamp\\n';\n const handleFile = (indentation, relativePath, itemPath, ) => {\n stamp += `${indentation}${relativePath}\\n`;\n const content = fs.readFileSync(itemPath, 'utf8');\n stamp += `${indentation} ${content.replace(/\\n/g, `\\n${indentation} `)}\\n`;\n }\n let gitTrackedFiles\n function processDirectory(currentPath, depth) {\n const items = fs.readdirSync(currentPath);\n items.forEach(item => {\n const itemPath = path.join(currentPath, item);\n const relativePath = path.relative(dir, itemPath);\n //if (!gitTrackedFiles.has(item)) return\n const stats = fs.statSync(itemPath);\n const indentation = ' '.repeat(depth);\n if (stats.isDirectory()) {\n stamp += `${indentation}${relativePath}/\\n`;\n processDirectory(itemPath, depth + 1);\n } else if (stats.isFile())\n handleFile(indentation, relativePath, itemPath)\n });\n }\n const stats = fs.statSync(dir);\n if (stats.isDirectory()) {\n // Get list of git-tracked files\n gitTrackedFiles = new Set(execSync('git ls-files', { cwd: dir, encoding: 'utf-8' })\n .split('\\n')\n .filter(Boolean))\n processDirectory(dir, 1)\n }\n else\n handleFile(\" \", dir, dir)\n return stamp.trim();\n }\nstampParser\n description Expand project template to disk.\n extends abstractScrollParser\n inScope stampFolderParser\n catchAllParser stampFileParser\n example\n stamp\n .gitignore\n *.html\n readme.scroll\n # Hello world\n <script src=\"scripts/nested/hello.js\"></script>\n scripts/\n nested/\n hello.js\n console.log(\"Hello world\")\n cueFromId\n atoms preBuildCommandAtom\n javascript\n execute() {\n const dir = this.root.folderPath\n this.forEach(particle => particle.execute(dir))\n }\nscrollStumpParser\n cue stump\n extends abstractScrollParser\n description Compile Stump to HTML.\n catchAllParser stumpContentParser\n javascript\n buildHtml() {\n const {stumpParser} = this\n return new stumpParser(this.subparticlesToString()).compile()\n }\n get stumpParser() {\n return this.isNodeJs() ? require(\"scrollsdk/products/stump.nodejs.js\") : stumpParser\n }\nstumpNoSnippetParser\n popularity 0.010177\n // todo: make noSnippets an aftertext directive?\n extends scrollStumpParser\n description Compile Stump unless snippet.\n cueFromId\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\nplainTextParser\n description Plain text oneliner or block.\n cueFromId\n extends abstractScrollParser\n catchAllParser plainTextLineParser\n catchAllAtomType stringAtom\n javascript\n buildHtml() {\n return this.buildTxt()\n }\n buildTxt() {\n return `${this.content ?? \"\"}${this.subparticlesToString()}`\n }\nplainTextOnlyParser\n popularity 0.000072\n extends plainTextParser\n description Only print for buildTxt.\n javascript\n buildHtml() {\n return \"\"\n }\nscrollThemeParser\n popularity 0.007524\n boolean isPopular true\n cue theme\n example\n theme gazette\n extends abstractScrollParser\n catchAllAtomType scrollThemeAtom\n description A collection of simple themes.\n string copyFromExternal .gazette.css\n // Note this will be replaced at runtime\n javascript\n get copyFromExternal() {\n return this.files.join(\" \")\n }\n get files() {\n return this.atoms.slice(1).map(name => `.${name}.css`).concat([\".scroll.css\"])\n }\n buildHtml() {\n return this.files.map(name => `<link rel=\"stylesheet\" type=\"text/css\" href=\"${name}\">`).join(\"\\n\")\n }\nabstractAftertextAttributeParser\n atoms cueAtom\n boolean isAttribute true\n javascript\n get htmlAttributes() {\n return `${this.cue}=\"${this.content}\"`\n }\n buildHtml() {\n return \"\"\n }\naftertextIdParser\n popularity 0.000145\n cue id\n description Provide an ID to be output in the generated HTML tag.\n extends abstractAftertextAttributeParser\n atoms cueAtom htmlIdAtom\n single\naftertextStyleParser\n popularity 0.000217\n cue style\n description Set HTML style attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType cssAnyAtom\n javascript\n htmlAttributes = \"\" // special case this one\n get css() { return `${this.property}:${this.content};` }\naftertextFontParser\n popularity 0.000217\n cue font\n description Set font.\n extends aftertextStyleParser\n atoms cueAtom fontFamilyAtom\n catchAllAtomType cssAnyAtom\n string property font-family\n javascript\n get css() {\n if (this.content === \"Slim\") return \"font-family:Helvetica Neue; font-weight:100;\"\n return super.css\n }\naftertextColorParser\n popularity 0.000217\n cue color\n description Set font color.\n extends aftertextStyleParser\n catchAllAtomType cssAnyAtom\n string property color\n example\n color blue\naftertextHrefParser\n popularity 0.000217\n cue href\n description Set HTML href attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom urlAtom\naftertextSrcParser\n extends aftertextHrefParser\n cue src\n description Set HTML src attribute.\naftertextOnclickParser\n popularity 0.000217\n cue onclick\n description Set HTML onclick attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType javascriptAnyAtom\naftertextHiddenParser\n cue hidden\n atoms cueAtom\n description Do not compile this particle to HTML.\n extends abstractAftertextAttributeParser\n single\naftertextValueParser\n popularity 0.000217\n cue value\n description Set HTML value attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextForParser\n popularity 0.000217\n cue for\n description Set HTML for attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom htmlAnyAtom\naftertextPlaceholderParser\n popularity 0.000217\n cue placeholder\n description Set HTML placeholder attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextRowsParser\n popularity 0.000217\n cue rows\n description Set HTML rows attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom integerAtom\naftertextTypeParser\n popularity 0.000217\n cue type\n description Set HTML type attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom htmlTypeAtom\naftertextAltParser\n popularity 0.000217\n cue alt\n description Set HTML alt attribute for images.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextTitleParser\n popularity 0.000217\n cue title\n description Set HTML title attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextNameParser\n popularity 0.000217\n cue name\n description Set HTML name attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextOnsubmitParser\n popularity 0.000217\n cue onsubmit\n description Set HTML onsubmit attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType javascriptAnyAtom\naftertextClassParser\n popularity 0.000217\n cue class\n description Set HTML class attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType classNameAtom\naftertextMaxlengthParser\n popularity 0.000217\n cue maxlength\n description Set HTML maxlength attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom integerAtom\naftertextPatternParser\n popularity 0.000217\n cue pattern\n description Set HTML pattern attribute for input validation.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextRequiredParser\n popularity 0.000217\n cue required\n description Set HTML required attribute.\n extends abstractAftertextAttributeParser\n single\naftertextDisabledParser\n popularity 0.000217\n cue disabled\n description Set HTML disabled attribute.\n extends abstractAftertextAttributeParser\n single\naftertextReadonlyParser\n popularity 0.000217\n cue readonly\n description Set HTML readonly attribute.\n extends abstractAftertextAttributeParser\n single\naftertextAriaLabelParser\n popularity 0.000217\n cue aria-label\n description Set ARIA label for accessibility.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextTargetParser\n popularity 0.000217\n cue target\n description Set HTML target attribute for links.\n extends abstractAftertextAttributeParser\n atoms cueAtom htmlAnyAtom\naftertextContentParser\n popularity 0.000217\n cue content\n description Set HTML content attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextTagParser\n atoms cueAtom htmlTagAtom\n description Override the HTML tag that the compiled particle will use.\n cue tag\n javascript\n buildHtml() {\n return \"\"\n }\nabstractAftertextDirectiveParser\n atoms cueAtom\n catchAllAtomType stringAtom\n javascript\n isMarkup = true\n buildHtml() {\n return \"\"\n }\n getErrors() {\n const errors = super.getErrors()\n if (!this.isMarkup || this.matchWholeLine) return errors\n const inserts = this.getInserts(this.parent.originalTextPostLinkify)\n // todo: make AbstractParticleError class exported by sdk to allow Parsers to define their own error types.\n // todo: also need to be able to map lines back to their line in source (pre-imports)\n if (!inserts.length)\n errors.push(this.makeError(`No match found for \"${this.getLine()}\".`))\n return errors\n }\n get pattern() {\n return this.getAtomsFrom(1).join(\" \")\n }\n get shouldMatchAll() {\n return this.has(\"matchAll\")\n }\n getMatches(text) {\n const { pattern } = this\n const escapedPattern = pattern.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\")\n return [...text.matchAll(new RegExp(escapedPattern, \"g\"))].map(match => {\n const { index } = match\n const endIndex = index + pattern.length\n return [\n { index, string: `<${this.openTag}${this.allAttributes}>`, endIndex },\n { index: endIndex, endIndex, string: `</${this.closeTag}>` }\n ]\n })\n }\n getInserts(text) {\n const matches = this.getMatches(text)\n if (!matches.length) return false\n if (this.shouldMatchAll) return matches.flat()\n const match = this.getParticle(\"match\")\n if (match)\n return match.indexes\n .map(index => matches[index])\n .filter(i => i)\n .flat()\n return matches[0]\n }\n get allAttributes() {\n const attr = this.attributes.join(\" \")\n return attr ? \" \" + attr : \"\"\n }\n get attributes() {\n return []\n }\n get openTag() {\n return this.tag\n }\n get closeTag() {\n return this.tag\n }\nabstractMarkupParser\n extends abstractAftertextDirectiveParser\n inScope abstractMarkupParameterParser\n javascript\n get matchWholeLine() {\n return this.getAtomsFrom(this.patternStartsAtAtom).length === 0\n }\n get pattern() {\n return this.matchWholeLine ? this.parent.originalText : this.getAtomsFrom(this.patternStartsAtAtom).join(\" \")\n }\n patternStartsAtAtom = 1\nboldParser\n popularity 0.000096\n cueFromId\n description Bold matching text.\n extends abstractMarkupParser\n javascript\n tag = \"b\"\nitalicsParser\n popularity 0.000241\n cueFromId\n description Italicize matching text.\n extends abstractMarkupParser\n javascript\n tag = \"i\"\nunderlineParser\n popularity 0.000024\n description Underline matching text.\n cueFromId\n extends abstractMarkupParser\n javascript\n tag = \"u\"\nafterTextCenterParser\n popularity 0.000193\n description Center paragraph.\n cue center\n extends abstractMarkupParser\n javascript\n tag = \"center\"\naftertextCodeParser\n popularity 0.000145\n description Wrap matching text in code span.\n cue code\n extends abstractMarkupParser\n javascript\n tag = \"code\"\naftertextStrikeParser\n popularity 0.000048\n description Wrap matching text in s span.\n cue strike\n extends abstractMarkupParser\n javascript\n tag = \"s\"\naddClassMarkupParser\n popularity 0.000772\n description Add a custom class to parent element. Provide query to add span matching text.\n extends abstractMarkupParser\n atoms cueAtom classNameAtom\n cue addClass\n javascript\n tag = \"span\"\n get applyToParentElement() {\n return this.atoms.length === 2\n }\n getInserts(text) {\n // If no select text is added, set the class on the parent element.\n if (this.applyToParentElement) return []\n return super.getInserts(text)\n }\n get className() {\n return this.getAtom(1)\n }\n get attributes() {\n return [`class=\"${this.className}\"`]\n }\n get matchWholeLine() {\n return this.applyToParentElement\n }\n get pattern() {\n return this.matchWholeLine ? this.parent.content : this.getAtomsFrom(2).join(\" \")\n }\nhoverNoteParser\n popularity 0.000265\n description Add a caveat viewable on hover on matching text. When you want to be sure you've thoroughly addressed obvious concerns but ones that don't warrant to distract from the main argument of the text.\n cueFromId\n extends addClassMarkupParser\n catchAllParser lineOfTextParser\n atoms cueAtom\n javascript\n get pattern() {\n return this.getAtomsFrom(1).join(\" \")\n }\n get attributes() {\n return [`class=\"scrollHoverNote\"`, `title=\"${this.hoverNoteText}\"`]\n }\n get hoverNoteText() {\n return this.subparticlesToString().replace(/\\n/g, \" \")\n }\nscrollLinkParser\n popularity 0.008706\n extends abstractMarkupParser\n description Put the matching text in an <a> tag.\n atoms cueAtom urlAtom\n inScope linkTitleParser linkTargetParser abstractCommentParser\n programParser\n description Anything here will be URI encoded and then appended to the link.\n cueFromId\n atoms cueAtom\n catchAllParser programLinkParser\n javascript\n get encoded() {\n return encodeURIComponent(this.subparticlesToString())\n }\n cue link\n javascript\n tag = \"a\"\n buildTxt() {\n return this.root.ensureAbsoluteLink(this.link) + \" \" + this.pattern\n }\n get link() {\n const {baseLink} = this\n if (this.has(\"program\"))\n return baseLink + this.getParticle(\"program\").encoded\n return baseLink\n }\n get baseLink() {\n const link = this.getAtom(1)\n const isAbsoluteLink = link.includes(\"://\")\n if (isAbsoluteLink) return link\n const relativePath = this.parent.buildSettings?.relativePath || \"\"\n return relativePath + link\n }\n get linkAttribute() {\n return \"href\"\n }\n get attributes() {\n const attrs = [`${this.linkAttribute}=\"${this.link}\"`]\n const options = [\"title\", \"target\"]\n options.forEach(option => {\n const particle = this.getParticle(option)\n if (particle) attrs.push(`${option}=\"${particle.content}\"`)\n })\n return attrs\n }\n patternStartsAtAtom = 2\nscrollClickParser\n extends scrollLinkParser\n description An a tag with an onclick.\n cue click\n javascript\n get linkAttribute() {\n return \"onclick\"\n }\nemailLinkParser\n popularity 0.000048\n description A mailto link\n cue email\n extends scrollLinkParser\n javascript\n get attributes() {\n return [`href=\"mailto:${this.link}\"`]\n }\nquickLinkParser\n popularity 0.029228\n pattern ^https?\\:\n extends scrollLinkParser\n atoms urlAtom\n javascript\n get link() {\n return this.cue\n }\n patternStartsAtAtom = 1\nquickRelativeLinkParser\n popularity 0.029228\n description Relative links.\n // note: only works if relative link ends in .html\n pattern ^[^\\s]+\\.(html|htm)\n extends scrollLinkParser\n atoms urlAtom\n javascript\n get link() {\n return this.cue\n }\n patternStartsAtAtom = 1\ndatelineParser\n popularity 0.006005\n cueFromId\n description Gives your paragraph a dateline like \"December 15, 2021 — The...\"\n extends abstractAftertextDirectiveParser\n javascript\n getInserts() {\n const {day} = this\n if (!day) return false\n return [{ index: 0, string: `<span class=\"scrollDateline\">${day} — </span>` }]\n }\n matchWholeLine = true\n get day() {\n let day = this.content || this.root.date\n if (!day) return \"\"\n return this.root.dayjs(day).format(`MMMM D, YYYY`)\n }\ndayjsParser\n description Advanced directive that evals some Javascript code in an environment including \"dayjs\".\n cueFromId\n extends abstractAftertextDirectiveParser\n javascript\n getInserts() {\n const dayjs = this.root.dayjs\n const days = eval(this.content)\n const index = this.parent.originalTextPostLinkify.indexOf(\"days\")\n return [{ index, string: `${days} ` }]\n }\ninlineMarkupsOnParser\n popularity 0.000024\n cueFromId\n description Enable these inline markups only.\n example\n Hello *world*!\n inlineMarkupsOn bold\n extends abstractAftertextDirectiveParser\n catchAllAtomType inlineMarkupNameAtom\n javascript\n get shouldMatchAll() {\n return true\n }\n get markups() {\n const {root} = this\n let markups = [{delimiter: \"`\", tag: \"code\", exclusive: true, name: \"code\"},{delimiter: \"*\", tag: \"strong\", name: \"bold\"}, {delimiter: \"_\", tag: \"em\", name: \"italics\"}]\n // only add katex markup if the root doc has katex.\n if (root.has(\"katex\"))\n markups.unshift({delimiter: \"$\", tag: \"span\", attributes: ' class=\"scrollKatex\"', exclusive: true, name: \"katex\"})\n if (this.content)\n return markups.filter(markup => this.content.includes(markup.name))\n if (root.has(\"inlineMarkups\")) {\n root.getParticle(\"inlineMarkups\").forEach(markup => {\n const delimiter = markup.getAtom(0)\n const tag = markup.getAtom(1)\n // todo: add support for providing custom functions for inline markups?\n // for example, !2+2! could run eval, or :about: could search a link map.\n const attributes = markup.getAtomsFrom(2).join(\" \")\n markups = markups.filter(mu => mu.delimiter !== delimiter) // Remove any overridden markups\n if (tag)\n markups.push({delimiter, tag, attributes})\n })\n }\n return markups\n }\n matchWholeLine = true\n getMatches(text) {\n const exclusives = []\n return this.markups.map(markup => this.applyMarkup(text, markup, exclusives)).filter(i => i).flat()\n }\n applyMarkup(text, markup, exclusives = []) {\n const {delimiter, tag, attributes} = markup\n const escapedDelimiter = delimiter.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\")\n const pattern = new RegExp(`${escapedDelimiter}[^${escapedDelimiter}]+${escapedDelimiter}`, \"g\")\n const delimiterLength = delimiter.length\n return [...text.matchAll(pattern)].map(match => {\n const { index } = match\n const endIndex = index + match[0].length\n // I'm too lazy to clean up sdk to write a proper inline markup parser so doing this for now.\n // The exclusive idea is to not try and apply bold or italic styles inside a TeX or code inline style.\n // Note that the way this is currently implemented any TeX in an inline code will get rendered, but code\n // inline of TeX will not. Seems like an okay tradeoff until a proper refactor and cleanup can be done.\n if (exclusives.some(exclusive => index >= exclusive[0] && index <= exclusive[1]))\n return undefined\n if (markup.exclusive)\n exclusives.push([index, endIndex])\n return [\n { index, string: `<${tag + (attributes ? \" \" + attributes : \"\")}>`, endIndex, consumeStartCharacters: delimiterLength },\n { index: endIndex, endIndex, string: `</${tag}>`, consumeEndCharacters: delimiterLength }\n ]\n }).filter(i => i)\n }\ninlineMarkupParser\n popularity 0.000169\n cueFromId\n atoms cueAtom delimiterAtom tagOrUrlAtom\n catchAllAtomType htmlAttributesAtom\n extends inlineMarkupsOnParser\n description Custom inline markup. for\n example\n @This@ will be in italics.\n inlineMarkup @ em\n javascript\n getMatches(text) {\n try {\n const delimiter = this.getAtom(1)\n const tag = this.getAtom(2)\n const attributes = this.getAtomsFrom(3).join(\" \")\n return this.applyMarkup(text, {delimiter, tag, attributes})\n } catch (err) {\n console.error(err)\n return []\n }\n // Note: doubling up doesn't work because of the consumption characters.\n }\nlinkifyParser\n description Use this to disable linkify on the text.\n extends abstractAftertextDirectiveParser\n cueFromId\n atoms cueAtom booleanAtom\nabstractMarkupParameterParser\n atoms cueAtom\n cueFromId\nmatchAllParser\n popularity 0.000024\n description Use this to match all occurrences of the text.\n extends abstractMarkupParameterParser\nmatchParser\n popularity 0.000048\n catchAllAtomType integerAtom\n description Use this to specify which index(es) to match.\n javascript\n get indexes() {\n return this.getAtomsFrom(1).map(num => parseInt(num))\n }\n example\n aftertext\n hello ello ello\n bold ello\n match 0 2\n extends abstractMarkupParameterParser\nabstractHtmlAttributeParser\n javascript\n buildHtml() {\n return \"\"\n }\nlinkTargetParser\n popularity 0.000024\n extends abstractHtmlAttributeParser\n description If you want to set the target of the link. To \"_blank\", for example.\n cue target\n atoms cueAtom codeAtom\nblankLineParser\n popularity 0.308149\n description Print nothing. Break section.\n atoms blankAtom\n boolean isPopular true\n javascript\n buildHtml() {\n return this.parent.clearSectionStack()\n }\n pattern ^$\n tags doNotSynthesize\nscrollFileAddressParser\n catchAllAtomType filePathAtom\n catchAllParser scrollFileAddressParser\nchatLineParser\n popularity 0.009887\n catchAllAtomType stringAtom\n catchAllParser chatLineParser\nlineOfCodeParser\n popularity 0.018665\n catchAllAtomType codeAtom\n catchAllParser lineOfCodeParser\ncommentLineParser\n catchAllAtomType commentAtom\ncssLineParser\n popularity 0.002870\n catchAllAtomType cssAnyAtom\n catchAllParser cssLineParser\nabstractTableTransformParser\n atoms cueAtom\n inScope abstractTableVisualizationParser abstractTableTransformParser h1Parser h2Parser scrollQuestionParser htmlInlineParser scrollBrParser slashCommentParser\n javascript\n get coreTable() {\n return this.parent.coreTable\n }\n get columnNames() {\n return this.parent.columnNames\n }\n connectColumnNames(userColumnNames, availableColumnNames = this.parent.columnNames) {\n const result = {}\n const normalize = str => str.toLowerCase().trim()\n userColumnNames.forEach(userColumn => {\n // Strategy 1: Exact match\n const exactMatch = availableColumnNames.find(col => col === userColumn)\n if (exactMatch) {\n result[userColumn] = exactMatch\n return\n }\n // Strategy 2: Case-insensitive match\n const normalizedUserColumn = normalize(userColumn)\n const caseInsensitiveMatch = availableColumnNames.find(col => normalize(col) === normalizedUserColumn)\n if (caseInsensitiveMatch) {\n result[userColumn] = caseInsensitiveMatch\n return\n }\n // Strategy 3: Levenshtein distance match\n const THRESHOLD = 2 // Consider matches with distance <= 2 as \"very close\"\n let bestMatch = null\n let bestDistance = Infinity\n availableColumnNames.forEach(col => {\n const distance = this.root.levenshteinDistance(userColumn, col)\n if (distance < bestDistance) {\n bestDistance = distance\n bestMatch = col\n }\n })\n // Only use Levenshtein match if it's very close\n if (bestDistance <= THRESHOLD) {\n result[userColumn] = bestMatch\n return\n }\n // Strategy 4: Fallback - use original unmatched name\n result[userColumn] = userColumn\n })\n return result\n }\n connectColumnName(name) {\n return this.connectColumnNames([name])[name]\n }\n getErrors() {\n const errors = super.getErrors()\n if (errors.length && this.previous.cue !== \"assertIgnoreBelowErrors\")\n return errors\n return []\n }\n getRunTimeEnumOptions(atom) {\n if (atom.atomTypeId === \"columnNameAtom\")\n return this.parent.columnNames\n return super.getRunTimeEnumOptions(atom)\n }\n getRunTimeEnumOptionsForValidation(atom) {\n // Note: this will fail if the CSV file hasnt been built yet.\n if (atom.atomTypeId === \"columnNameAtom\")\n return this.parent.columnNames.concat(this.parent.columnNames.map(c => \"-\" + c)) // Add reverse names\n return super.getRunTimeEnumOptions(atom)\n }\nabstractDateSplitTransformParser\n extends abstractTableTransformParser\n atoms cueAtom\n catchAllAtomType columnNameAtom\n javascript\n get coreTable() {\n const columnName = this.getAtom(1) || this.detectDateColumn()\n if (!columnName) return this.parent.coreTable\n return this.parent.coreTable.map(row => {\n const newRow = {...row}\n try {\n const date = this.root.dayjs(row[columnName])\n if (date.isValid())\n newRow[this.newColumnName] = this.transformDate(date)\n } catch (err) {}\n return newRow\n })\n }\n detectDateColumn() {\n const columns = this.parent.columnNames\n const dateColumns = ['date', 'created', 'published', 'timestamp']\n for (const col of dateColumns) {\n if (columns.includes(col)) return col\n }\n for (const col of columns) {\n const sample = this.parent.coreTable[0][col]\n if (sample && this.root.dayjs(sample).isValid())\n return col\n }\n return null\n }\n get columnNames() {\n return [...this.parent.columnNames, this.newColumnName]\n }\n transformDate(date) {\n const formatted = date.format(this.dateFormat)\n const isInt = !this.cue.includes(\"Name\")\n return isInt ? parseInt(formatted) : formatted\n }\nscrollSplitYearParser\n extends abstractDateSplitTransformParser\n description Extract year into new column.\n cue splitYear\n string newColumnName year\n string dateFormat YYYY\nscrollSplitDayNameParser\n extends abstractDateSplitTransformParser\n description Extract day name into new column.\n cue splitDayName\n string newColumnName dayName\n string dateFormat dddd\nscrollSplitMonthNameParser\n extends abstractDateSplitTransformParser\n description Extract month name into new column.\n cue splitMonthName\n string newColumnName monthName\n string dateFormat MMMM\nscrollSplitMonthParser\n extends abstractDateSplitTransformParser\n description Extract month number (1-12) into new column.\n cue splitMonth\n string newColumnName month\n string dateFormat M\nscrollSplitDayOfMonthParser\n extends abstractDateSplitTransformParser\n description Extract day of month (1-31) into new column.\n cue splitDayOfMonth\n string newColumnName dayOfMonth\n string dateFormat D\nscrollSplitDayOfWeekParser\n extends abstractDateSplitTransformParser\n description Extract day of week (0-6) into new column.\n cue splitDay\n string newColumnName day\n string dateFormat d\nscrollParseDateParser\n extends abstractTableTransformParser\n description Parse dates in a column into standard format.\n cue parseDate\n atoms cueAtom columnNameAtom\n example\n sampleData stocks.csv\n parseDate date\n linechart\n x date\n y price\n javascript\n get coreTable() {\n const columnName = this.connectColumnName(this.getAtom(1))\n const formatOut = this.get(\"format\") || \"YYYY-MM-DD\"\n const {dayjs} = this.root\n return this.parent.coreTable.map(row => {\n const newRow = {...row}\n try {\n const value = row[columnName]\n if (value) {\n const date = dayjs(value)\n if (date.isValid())\n newRow[columnName] = date.format(formatOut)\n }\n } catch (err) {\n console.error(`Error parsing date in column ${columnName}:`, err)\n }\n return newRow\n })\n }\n formatParser\n description Specify output date format\n atoms cueAtom stringAtom\n cueFromId\n single\nscrollGroupByParser\n catchAllAtomType columnNameAtom\n extends abstractTableTransformParser\n reduceParser\n description Specify how to aggregate a column when grouping data\n atoms cueAtom columnNameAtom reductionTypeAtom newColumnNameAtom\n cue reduce\n example\n data.csv\n groupBy year\n reduce score sum totalScore\n reduce name concat names\n printTable\n javascript\n get reduction() {\n return {\n source: this.getAtom(1),\n reduction: this.getAtom(2),\n name: this.getAtom(3) || this.getAtomsFrom(1).join(\"_\")\n }\n }\n description Combine rows with matching values into groups.\n example\n tables posts.csv\n groupBy year\n printTable\n cue groupBy\n javascript\n get coreTable() {\n if (this._coreTable) return this._coreTable\n const groupByColNames = this.getAtomsFrom(1)\n const {coreTable} = this.parent\n if (!groupByColNames.length) return coreTable\n const newCols = this.findParticles(\"reduce\").map(particle => particle.reduction)\n // Pivot is shorthand for group and reduce?\n const makePivotTable = (rows, groupByColumnNames, inputColumnNames, newCols) => {\n const colMap = {}\n inputColumnNames.forEach((col) => (colMap[col] = true))\n const groupByCols = groupByColumnNames.filter((col) => colMap[col])\n return new PivotTable(rows, inputColumnNames.map(c => {return {name: c}}), newCols).getNewRows(groupByCols)\n }\n class PivotTable {\n constructor(rows, inputColumns, outputColumns) {\n this._columns = {}\n this._rows = rows\n inputColumns.forEach((col) => (this._columns[col.name] = col))\n outputColumns.forEach((col) => (this._columns[col.name] = col))\n }\n _getGroups(allRows, groupByColNames) {\n const rowsInGroups = new Map()\n allRows.forEach((row) => {\n const groupKey = groupByColNames.map((col) => row[col]?.toString().replace(/ /g, \"\") || \"\").join(\" \")\n if (!rowsInGroups.has(groupKey)) rowsInGroups.set(groupKey, [])\n rowsInGroups.get(groupKey).push(row)\n })\n return rowsInGroups\n }\n getNewRows(groupByCols) {\n // make new particles\n const rowsInGroups = this._getGroups(this._rows, groupByCols)\n // Any column in the group should be reused by the children\n const columns = [\n {\n name: \"count\",\n type: \"number\",\n min: 0,\n },\n ]\n groupByCols.forEach((colName) => columns.push(this._columns[colName]))\n const colsToReduce = Object.values(this._columns).filter((col) => !!col.reduction)\n colsToReduce.forEach((col) => columns.push(col))\n // for each group\n const rows = []\n const totalGroups = rowsInGroups.size\n for (let [groupId, group] of rowsInGroups) {\n const firstRow = group[0]\n const newRow = {}\n groupByCols.forEach((col) =>\n newRow[col] = firstRow ? firstRow[col] : 0\n )\n newRow.count = group.length\n // todo: add more reductions? count, stddev, median, variance.\n colsToReduce.forEach((col) => {\n const sourceColName = col.source\n const reduction = col.reduction\n const newColName = col.name\n if (reduction === \"concat\") {\n newRow[newColName] = group.map((row) => row[sourceColName]).join(\" \")\n return \n }\n if (reduction === \"first\") {\n newRow[newColName] = group.find((row) => row[sourceColName] !== \"\")?.[sourceColName]\n return \n }\n const values = group.map((row) => row[sourceColName]).filter((val) => typeof val === \"number\" && !isNaN(val))\n let reducedValue = firstRow[sourceColName]\n if (reduction === \"sum\") reducedValue = values.reduce((prev, current) => prev + current, 0)\n if (reduction === \"max\") reducedValue = Math.max(...values)\n if (reduction === \"min\") reducedValue = Math.min(...values)\n if (reduction === \"mean\") reducedValue = values.reduce((prev, current) => prev + current, 0) / values.length\n newRow[newColName] = reducedValue\n })\n rows.push(newRow)\n }\n // todo: add tests. figure out this api better.\n Object.values(columns).forEach((col) => {\n // For pivot columns, remove the source and reduction info for now. Treat things as immutable.\n delete col.source\n delete col.reduction\n })\n return {\n rows,\n columns,\n }\n }\n }\n const pivotTable = makePivotTable(coreTable, groupByColNames, this.parent.columnNames, newCols)\n this._coreTable = pivotTable.rows\n this._columnNames = pivotTable.columns.map(col => col.name)\n return pivotTable.rows\n }\n get columnNames() {\n const {coreTable} = this\n return this._columnNames || this.parent.columnNames\n }\nscrollWhereParser\n extends abstractTableTransformParser\n description Filter rows by condition.\n cue where\n atoms cueAtom columnNameAtom comparisonAtom\n catchAllAtomType constantAtom\n example\n table iris.csv\n where Species = setosa\n javascript\n get coreTable() {\n // todo: use atoms here.\n const columnName = this.connectColumnName(this.getAtom(1))\n const operator = this.getAtom(2)\n let untypedComparisonValue = this.getAtom(3)\n const typedComparisonValue = isNaN(parseFloat(untypedComparisonValue)) ? untypedComparisonValue : parseFloat(untypedComparisonValue)\n const coreTable = this.parent.coreTable\n if (!columnName || !operator || (untypedComparisonValue === undefined && !operator.includes(\"mpty\"))) return coreTable\n const filterFn = row => {\n const atom = row[columnName]\n const typedAtom = atom === null ? undefined : atom // convert nulls to undefined\n if (operator === \"=\") return typedComparisonValue === typedAtom\n else if (operator === \"!=\") return typedComparisonValue !== typedAtom\n else if (operator === \"includes\") return typedAtom !== undefined && typedAtom.includes(typedComparisonValue)\n else if (operator === \"startsWith\") return typedAtom !== undefined && typedAtom.toString().startsWith(typedComparisonValue)\n else if (operator === \"endsWith\") return typedAtom !== undefined && typedAtom.toString().endsWith(typedComparisonValue)\n else if (operator === \"doesNotInclude\") return typedAtom === undefined || !typedAtom.includes(typedComparisonValue)\n else if (operator === \">\") return typedAtom > typedComparisonValue\n else if (operator === \"<\") return typedAtom < typedComparisonValue\n else if (operator === \">=\") return typedAtom >= typedComparisonValue\n else if (operator === \"<=\") return typedAtom <= typedComparisonValue\n else if (operator === \"empty\") return typedAtom === \"\" || typedAtom === undefined\n else if (operator === \"notEmpty\") return typedAtom !== \"\" && typedAtom !== undefined\n }\n return coreTable.filter(filterFn)\n }\nscrollSelectParser\n catchAllAtomType columnNameAtom\n extends abstractTableTransformParser\n description Drop all columns except these.\n example\n tables\n data\n name,year,count\n index,2022,2\n about,2023,4\n select name year\n printTable\n cue select\n javascript\n get coreTable() {\n const {coreTable} = this.parent\n const {columnNames} = this\n if (!columnNames.length) return coreTable\n return coreTable.map(row => Object.fromEntries(columnNames.map(colName => [colName, row[colName]])))\n }\n get columnNames() {\n if (!this._columnNames) {\n const names = this.getAtomsFrom(1)\n this._columnNamesMap = this.connectColumnNames(names)\n this._columnNames = names.map(name => this._columnNamesMap[name])\n }\n return this._columnNames\n }\nscrollReverseParser\n extends abstractTableTransformParser\n description Reverse rows.\n cue reverse\n javascript\n get coreTable() {\n return this.parent.coreTable.slice().reverse()\n }\nscrollComposeParser\n extends abstractTableTransformParser\n description Add column using format string.\n catchAllAtomType codeAtom\n cue compose\n atoms cueAtom newColumnNameAtom\n example\n table\n compose sentence My name is {name}\n printTable\n javascript\n get coreTable() {\n const {newColumnName} = this\n const formatString = this.getAtomsFrom(2).join(\" \")\n return this.parent.coreTable.map((row, index) => {\n const newRow = Object.assign({}, row)\n newRow[newColumnName] = this.evaluate(new Particle(row).evalTemplateString(formatString), index)\n return newRow\n })\n }\n evaluate(str) {\n return str\n }\n get newColumnName() {\n return this.atoms[1]\n }\n get columnNames() {\n return this.parent.columnNames.concat(this.newColumnName)\n }\nscrollComputeParser\n extends scrollComposeParser\n description Add column by evaling format string.\n cue compute\n javascript\n evaluate(str) {\n return parseFloat(eval(str))\n }\nscrollEvalParser\n extends scrollComputeParser\n description Add column by evaling format string.\n cue eval\n javascript\n evaluate(str) {\n return eval(str)\n }\nscrollRankParser\n extends scrollComposeParser\n description Add rank column.\n atoms cueAtom\n string newColumnName rank\n cue rank\n javascript\n evaluate(str, index) { return index + 1 }\nscrollLinksParser\n extends abstractTableTransformParser\n description Add column with links.\n cue links\n catchAllAtomType columnNameAtom\n javascript\n get coreTable() {\n const {newColumnName, linkColumns} = this\n return this.parent.coreTable.map(row => {\n const newRow = Object.assign({}, row)\n let newValue = []\n linkColumns.forEach(name => {\n const value = newRow[name]\n delete newRow[name]\n if (value) newValue.push(`<a href=\"${value.includes(\"@\") ? \"mailto:\" : \"\"}${value}\">${name}</a>`)\n })\n newRow[newColumnName] = newValue.join(\" \")\n return newRow\n })\n }\n get newColumnName() {\n return \"links\"\n }\n get linkColumns() {\n return this.getAtomsFrom(1)\n }\n get columnNames() {\n const {linkColumns} = this\n return this.parent.columnNames.filter(name => !linkColumns.includes(name)).concat(this.newColumnName)\n }\nscrollLimitParser\n extends abstractTableTransformParser\n description Select a subset.\n cue limit\n atoms cueAtom integerAtom integerAtom\n javascript\n get coreTable() {\n let start = this.getAtom(1)\n let end = this.getAtom(2)\n if (end === undefined) {\n end = start\n start = 0\n }\n return this.parent.coreTable.slice(parseInt(start), parseInt(end))\n }\nscrollShuffleParser\n extends abstractTableTransformParser\n description Randomly reorder rows.\n cue shuffle\n example\n table data.csv\n shuffle\n printTable\n javascript\n get coreTable() {\n // Create a copy of the table to avoid modifying original\n const rows = this.parent.coreTable.slice()\n // Fisher-Yates shuffle algorithm\n for (let i = rows.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * (i + 1))\n ;[rows[i], rows[j]] = [rows[j], rows[i]]\n }\n return rows\n }\nscrollTransposeParser\n extends abstractTableTransformParser\n description Tranpose table.\n cue transpose\n javascript\n get coreTable() {\n // todo: we need to switch to column based coreTable, instead of row based\n const transpose = arr => Object.keys(arr[0]).map(key => [key, ...arr.map(row => row[key])]);\n return transpose(this.parent.coreTable)\n }\nscrollImputeParser\n extends abstractTableTransformParser\n description Impute missing values of a columm.\n atoms cueAtom columnNameAtom\n cue impute\n javascript\n get coreTable() {\n const {columnName} = this\n const sorted = this.root.lodash.orderBy(this.parent.coreTable.slice(), columnName)\n // ascending\n const imputed = []\n let lastInserted = sorted[0][columnName]\n sorted.forEach(row => {\n const measuredTime = row[columnName]\n while (measuredTime > lastInserted + 1) {\n lastInserted++\n // synthesize rows\n const imputedRow = {}\n imputedRow[columnName] = lastInserted\n imputedRow.count = 0\n imputed.push(imputedRow)\n }\n lastInserted = measuredTime\n imputed.push(row)\n })\n return imputed\n }\n get columnName() {\n return this.connectColumnName(this.getAtom(1))\n }\nscrollOrderByParser\n extends abstractTableTransformParser\n description Sort rows by column(s).\n catchAllAtomType columnNameAtom\n cue orderBy\n javascript\n get coreTable() {\n const makeLodashOrderByParams = str => {\n const part1 = str.split(\" \")\n const part2 = part1.map(col => (col.startsWith(\"-\") ? \"desc\" : \"asc\"))\n return [part1.map(col => this.connectColumnName(col.replace(/^\\-/, \"\"))), part2]\n }\n const orderBy = makeLodashOrderByParams(this.content)\n return this.root.lodash.orderBy(this.parent.coreTable.slice(), orderBy[0], orderBy[1])\n }\nassertRowCountParser\n extends abstractTableTransformParser\n description Test row count is expected value.\n atoms cueAtom integerAtom\n cueFromId\n javascript\n getErrors() {\n const errors = super.getErrors()\n const actualRows = this.coreTable.length\n const expectedRows = parseInt(this.content)\n if (actualRows !== expectedRows)\n return errors.concat(this.makeError(`Expected '${expectedRows}' rows but got '${actualRows}'.`))\n return errors\n }\nscrollRenameParser\n // todo: add support in Parsers for tuple catch alls\n catchAllAtomType columnNameAtom newColumnNameAtom\n catchAllAtomType newColumnNameAtom\n extends abstractTableTransformParser\n description Rename columns.\n example\n tables\n data\n name,year,count\n index,2022,2\n rename name Name year Year\n printTable\n cue rename\n javascript\n get coreTable() {\n const {coreTable} = this.parent\n const {renameMap} = this\n if (!Object.keys(renameMap).length) return coreTable\n return coreTable.map(row => {\n const newRow = {}\n Object.keys(row).forEach(key => {\n const name = renameMap[key] || key\n newRow[name] = row[key]\n })\n return newRow\n })\n }\n get renameMap() {\n const map = {}\n const pairs = this.getAtomsFrom(1)\n let oldName\n while (oldName = pairs.shift()) {\n map[oldName] = pairs.shift()\n }\n return map\n }\n _renamed\n get columnNames() {\n if (this._renamed)\n return this._renamed\n const {renameMap} = this\n this._renamed = this.parent.columnNames.map(name => renameMap[name] || name )\n return this._renamed\n }\nscrollSummarizeParser\n extends abstractTableTransformParser\n description Generate summary statistics for each column.\n cue summarize\n example\n table data.csv\n summarize\n printTable\n javascript\n get coreTable() {\n const {lodash} = this.root\n const sourceData = this.parent.coreTable\n if (!sourceData.length) return []\n return this.parent.columnNames.map(colName => {\n const values = sourceData.map(row => row[colName]).filter(val => val !== undefined && val !== null)\n const numericValues = values.filter(val => typeof val === \"number\" && !isNaN(val))\n const sorted = [...numericValues].sort((a, b) => a - b)\n // Calculate mode\n const frequency = {}\n values.forEach(val => {\n frequency[val] = (frequency[val] || 0) + 1\n })\n const mode = Object.entries(frequency)\n .sort((a, b) => b[1] - a[1])\n .map(entry => entry[0])[0]\n // Calculate median for numeric values\n const median = sorted.length ? \n sorted.length % 2 === 0 \n ? (sorted[sorted.length/2 - 1] + sorted[sorted.length/2]) / 2\n : sorted[Math.floor(sorted.length/2)]\n : null\n const sum = numericValues.length ? numericValues.reduce((a, b) => a + b, 0) : null\n const theType = typeof values[0]\n const count = values.length\n const mean = theType === \"number\" ? sum/count : \"\"\n return {\n name: colName,\n type: theType,\n incompleteCount: sourceData.length - values.length,\n uniqueCount: new Set(values).size,\n count,\n sum,\n median,\n mean,\n min: sorted.length ? sorted[0] : null,\n max: sorted.length ? sorted[sorted.length - 1] : null,\n mode\n }\n })\n }\n get columnNames() {\n return [\"name\", \"type\", \"incompleteCount\", \"uniqueCount\", \"count\", \"sum\", \"median\", \"mean\", \"min\", \"max\", \"mode\"]\n }\nerrorParser\n baseParser errorParser\nhakonContentParser\n popularity 0.102322\n catchAllAtomType codeAtom\nheatrixCatchAllParser\n popularity 0.000193\n // todo Fill this out\n catchAllAtomType stringAtom\nlineOfTextParser\n popularity 0.000289\n catchAllAtomType stringAtom\n boolean isTextParser true\nhtmlLineParser\n popularity 0.005209\n catchAllAtomType htmlAnyAtom\n catchAllParser htmlLineParser\nopenGraphParser\n // todo: fix Parsers scope issue so we can move this parser def under scrollImageParser\n description Add this line to make this the open graph image.\n cueFromId\n atoms cueAtom\nimportToFooterParser\n description Import to bottom of file.\n atoms preBuildCommandAtom\n cue footer\nscriptLineParser\n catchAllAtomType javascriptAnyAtom\n catchAllParser scriptLineParser\nlinkTitleParser\n popularity 0.000048\n description If you want to set the title of the link.\n cue title\n atoms cueAtom\n catchAllAtomType stringAtom\n example\n * This report showed the treatment had a big impact.\n https://example.com/report This report.\n title The average growth in the treatment group was 14.2x higher than the control group.\nprogramLinkParser\n popularity 0.000531\n catchAllAtomType codeAtom\nscrollMediaLoopParser\n popularity 0.000048\n cue loop\n atoms cueAtom\nscrollAutoplayParser\n cue autoplay\n atoms cueAtom\nabstractCompilerRuleParser\n catchAllAtomType anyAtom\n atoms cueAtom\ncloseSubparticlesParser\n extends abstractCompilerRuleParser\n description When compiling a parent particle to a string, this string is appended to the compiled and joined subparticles. Default is blank.\n cueFromId\nindentCharacterParser\n extends abstractCompilerRuleParser\n description You can change the indent character for compiled subparticles. Default is a space.\n cueFromId\ncatchAllAtomDelimiterParser\n description If a particle has a catchAllAtom, this is the string delimiter that will be used to join those atoms. Default is comma.\n extends abstractCompilerRuleParser\n cueFromId\nopenSubparticlesParser\n extends abstractCompilerRuleParser\n description When compiling a parent particle to a string, this string is prepended to the compiled and joined subparticles. Default is blank.\n cueFromId\nstringTemplateParser\n extends abstractCompilerRuleParser\n description This template string is used to compile this line, and accepts strings of the format: const var = {someAtomId}\n cueFromId\njoinSubparticlesWithParser\n description When compiling a parent particle to a string, subparticles are compiled to strings and joined by this character. Default is a newline.\n extends abstractCompilerRuleParser\n cueFromId\nabstractConstantParser\n description A constant.\n atoms cueAtom\n cueFromId\n // todo: make tags inherit\n tags actPhase\nparsersBooleanParser\n cue boolean\n atoms cueAtom constantIdentifierAtom\n catchAllAtomType booleanAtom\n extends abstractConstantParser\n tags actPhase\nparsersFloatParser\n cue float\n atoms cueAtom constantIdentifierAtom\n catchAllAtomType floatAtom\n extends abstractConstantParser\n tags actPhase\nparsersIntParser\n cue int\n atoms cueAtom constantIdentifierAtom\n catchAllAtomType integerAtom\n tags actPhase\n extends abstractConstantParser\nparsersStringParser\n cue string\n atoms cueAtom constantIdentifierAtom\n catchAllAtomType stringAtom\n catchAllParser catchAllMultilineStringConstantParser\n extends abstractConstantParser\n tags actPhase\nabstractParserRuleParser\n single\n atoms cueAtom\nabstractNonTerminalParserRuleParser\n extends abstractParserRuleParser\nparsersBaseParserParser\n atoms cueAtom baseParsersAtom\n description Set for blobs or errors. \n // In rare cases with untyped content you can use a blobParser, for now, to skip parsing for performance gains. The base errorParser will report errors when parsed. Use that if you don't want to implement your own error parser.\n extends abstractParserRuleParser\n cue baseParser\n tags analyzePhase\ncatchAllAtomTypeParser\n atoms cueAtom atomTypeIdAtom\n description Use for lists.\n // Aka 'listAtomType'. Use this when the value in a key/value pair is a list. If there are extra atoms in the particle's line, parse these atoms as this type. Often used with `listDelimiterParser`.\n extends abstractParserRuleParser\n cueFromId\n tags analyzePhase\natomParserParser\n atoms cueAtom atomParserAtom\n description Set parsing strategy.\n // prefix/postfix/omnifix parsing strategy. If missing, defaults to prefix.\n extends abstractParserRuleParser\n cueFromId\n tags experimental analyzePhase\ncatchAllParserParser\n description Attach this to unmatched lines.\n // If a parser is not found in the inScope list, instantiate this type of particle instead.\n atoms cueAtom parserIdAtom\n extends abstractParserRuleParser\n cueFromId\n tags acquirePhase\nparsersAtomsParser\n catchAllAtomType atomTypeIdAtom\n description Set required atomTypes.\n extends abstractParserRuleParser\n cue atoms\n tags analyzePhase\nparsersCompilerParser\n // todo Remove this and its subparticles?\n description Deprecated. For simple compilers.\n inScope stringTemplateParser catchAllAtomDelimiterParser openSubparticlesParser closeSubparticlesParser indentCharacterParser joinSubparticlesWithParser\n extends abstractParserRuleParser\n cue compiler\n tags deprecate\n boolean suggestInAutocomplete false\nparserDescriptionParser\n description Parser description.\n catchAllAtomType stringAtom\n extends abstractParserRuleParser\n cue description\n tags assemblePhase\nparsersExampleParser\n // todo Should this just be a \"string\" constant on particles?\n description Set example for docs and tests.\n catchAllAtomType exampleAnyAtom\n catchAllParser catchAllExampleLineParser\n extends abstractParserRuleParser\n cue example\n tags assemblePhase\nextendsParserParser\n cue extends\n tags assemblePhase\n description Extend another parser.\n // todo: add a catchall that is used for mixins\n atoms cueAtom parserIdAtom\n extends abstractParserRuleParser\nparsersPopularityParser\n // todo Remove this parser. Switch to conditional frequencies.\n description Parser popularity.\n atoms cueAtom floatAtom\n extends abstractParserRuleParser\n cue popularity\n tags assemblePhase\ninScopeParser\n description Parsers in scope.\n catchAllAtomType parserIdAtom\n extends abstractParserRuleParser\n cueFromId\n tags acquirePhase\nparsersJavascriptParser\n // todo Urgently need to get submode syntax highlighting running! (And eventually LSP)\n description Javascript code for Parser Actions.\n catchAllParser catchAllJavascriptCodeLineParser\n extends abstractParserRuleParser\n tags actPhase\n javascript\n format() {\n if (this.isNodeJs()) {\n const template = `class FOO{ ${this.subparticlesToString()}}`\n this.setSubparticles(\n require(\"prettier\")\n .format(template, { semi: false, useTabs: true, parser: \"babel\", printWidth: 240 })\n .replace(/class FOO \\{\\s+/, \"\")\n .replace(/\\s+\\}\\s+$/, \"\")\n .replace(/\\n\\t/g, \"\\n\") // drop one level of indent\n .replace(/\\t/g, \" \") // we used tabs instead of spaces to be able to dedent without breaking literals.\n )\n }\n return this\n }\n cue javascript\nabstractParseRuleParser\n // Each particle should have a pattern that it matches on unless it's a catch all particle.\n extends abstractParserRuleParser\n cueFromId\nparsersCueParser\n atoms cueAtom stringAtom\n description Attach by matching first atom.\n extends abstractParseRuleParser\n tags acquirePhase\n cue cue\ncueFromIdParser\n atoms cueAtom\n description Derive cue from parserId.\n // for example 'fooParser' would have cue of 'foo'.\n extends abstractParseRuleParser\n tags acquirePhase\nparsersPatternParser\n catchAllAtomType regexAtom\n description Attach via regex.\n extends abstractParseRuleParser\n tags acquirePhase\n cue pattern\nparsersRequiredParser\n description Assert is present at least once.\n extends abstractParserRuleParser\n cue required\n tags analyzePhase\nabstractValidationRuleParser\n extends abstractParserRuleParser\n cueFromId\n catchAllAtomType booleanAtom\nparsersSingleParser\n description Assert used once.\n // Can be overridden by a child class by setting to false.\n extends abstractValidationRuleParser\n tags analyzePhase\n cue single\nuniqueLineParser\n description Assert unique lines. For pattern parsers.\n // Can be overridden by a child class by setting to false.\n extends abstractValidationRuleParser\n tags analyzePhase\nuniqueCueParser\n description Assert unique first atoms. For pattern parsers.\n // For catch all parsers or pattern particles, use this to indicate the \n extends abstractValidationRuleParser\n tags analyzePhase\nlistDelimiterParser\n description Split content by this delimiter.\n extends abstractParserRuleParser\n cueFromId\n catchAllAtomType stringAtom\n tags analyzePhase\ncontentKeyParser\n description Deprecated. For to/from JSON.\n // Advanced keyword to help with isomorphic JSON serialization/deserialization. If present will serialize the particle to an object and set a property with this key and the value set to the particle's content.\n extends abstractParserRuleParser\n cueFromId\n catchAllAtomType stringAtom\n tags deprecate\n boolean suggestInAutocomplete false\nsubparticlesKeyParser\n // todo: deprecate?\n description Deprecated. For to/from JSON.\n // Advanced keyword to help with serialization/deserialization of blobs. If present will serialize the particle to an object and set a property with this key and the value set to the particle's subparticles.\n extends abstractParserRuleParser\n cueFromId\n catchAllAtomType stringAtom\n tags deprecate\n boolean suggestInAutocomplete false\nparsersTagsParser\n catchAllAtomType stringAtom\n extends abstractParserRuleParser\n description Custom metadata.\n cue tags\n tags assemblePhase\natomTypeDescriptionParser\n description Atom Type description.\n catchAllAtomType stringAtom\n cue description\n tags assemblePhase\ncatchAllErrorParser\n baseParser errorParser\ncatchAllExampleLineParser\n catchAllAtomType exampleAnyAtom\n catchAllParser catchAllExampleLineParser\n atoms exampleAnyAtom\ncatchAllJavascriptCodeLineParser\n catchAllAtomType javascriptCodeAtom\n catchAllParser catchAllJavascriptCodeLineParser\ncatchAllMultilineStringConstantParser\n description String constants can span multiple lines.\n catchAllAtomType stringAtom\n catchAllParser catchAllMultilineStringConstantParser\n atoms stringAtom\natomTypeDefinitionParser\n // todo Generate a class for each atom type?\n // todo Allow abstract atom types?\n // todo Change pattern to postfix.\n pattern ^[a-zA-Z0-9_]+Atom$\n inScope parsersPaintParser parsersRegexParser reservedAtomsParser enumFromAtomTypesParser atomTypeDescriptionParser parsersEnumParser slashCommentParser extendsAtomTypeParser parsersExamplesParser atomMinParser atomMaxParser\n atoms atomTypeIdAtom\n tags assemblePhase\n javascript\n buildHtml() {return \"\"}\nenumFromAtomTypesParser\n description Runtime enum options.\n catchAllAtomType atomTypeIdAtom\n atoms atomPropertyNameAtom\n cueFromId\n tags analyzePhase\nparsersEnumParser\n description Set enum options.\n cue enum\n catchAllAtomType enumOptionAtom\n atoms atomPropertyNameAtom\n tags analyzePhase\nparsersExamplesParser\n description Examples for documentation and tests.\n // If the domain of possible atom values is large, such as a string type, it can help certain methods—such as program synthesis—to provide a few examples.\n cue examples\n catchAllAtomType atomExampleAtom\n atoms atomPropertyNameAtom\n tags assemblePhase\natomMinParser\n description Specify a min if numeric.\n cue min\n atoms atomPropertyNameAtom numberAtom\n tags analyzePhase\natomMaxParser\n description Specify a max if numeric.\n cue max\n atoms atomPropertyNameAtom numberAtom\n tags analyzePhase\nparsersPaintParser\n atoms cueAtom paintTypeAtom\n description Instructor editor how to color these.\n single\n cue paint\n tags analyzePhase\nparserDefinitionParser\n // todo Add multiple dispatch?\n pattern ^[a-zA-Z0-9_]+Parser$\n description Parser types are a core unit of your language. They translate to 1 class per parser. Examples of parser would be \"header\", \"person\", \"if\", \"+\", \"define\", etc.\n catchAllParser catchAllErrorParser\n inScope abstractParserRuleParser abstractConstantParser slashCommentParser parserDefinitionParser\n atoms parserIdAtom\n tags assemblePhase\n javascript\n buildHtml() { return \"\"}\nparsersRegexParser\n catchAllAtomType regexAtom\n description Atoms must match this.\n single\n atoms atomPropertyNameAtom\n cue regex\n tags analyzePhase\nreservedAtomsParser\n single\n description Atoms can't be any of these.\n catchAllAtomType reservedAtomAtom\n atoms atomPropertyNameAtom\n cueFromId\n tags analyzePhase\nextendsAtomTypeParser\n cue extends\n description Extend another atomType.\n // todo Add mixin support in addition to extends?\n atoms cueAtom atomTypeIdAtom\n tags assemblePhase\n single\nabstractColumnNameParser\n atoms cueAtom columnNameAtom\n javascript\n getRunTimeEnumOptions(atom) {\n if (atom.atomTypeId === \"columnNameAtom\")\n return this.parent.columnNames\n return super.getRunTimeEnumOptions(atom)\n }\nscrollRadiusParser\n cue radius\n extends abstractColumnNameParser\nscrollSymbolParser\n cue symbol\n extends abstractColumnNameParser\nabstractColumnNameOrColorParser\n extends abstractColumnNameParser\n atoms cueAtom columnNameOrColorAtom\n javascript\n //todo: cleanup\n colorOptions = \"aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkkhaki darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray darkturquoise darkviolet deeppink deepskyblue dimgray dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow honeydew hotpink indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgoldenrodyellow lightgray lightgreen lightpink lightsalmon lightseagreen lightskyblue lightslategray lightsteelblue lightyellow lime limegreen linen magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell sienna silver skyblue slateblue slategray snow springgreen steelblue tan teal thistle tomato turquoise violet wheat white whitesmoke yellow yellowgreen\".split(\" \")\n getRunTimeEnumOptions(atom) {\n if (atom.atomTypeId === \"columnNameOrColorAtom\")\n return this.parent.columnNames.join(this.colorOptions)\n return super.getRunTimeEnumOptions(atom)\n }\nscrollFillParser\n cue fill\n extends abstractColumnNameOrColorParser\nscrollStrokeParser\n cue stroke\n extends abstractColumnNameOrColorParser\nscrollLabelParser\n cue label\n extends abstractColumnNameParser\nscrollSortParser\n cue sort\n extends abstractColumnNameParser\nscrollXParser\n cue x\n extends abstractColumnNameParser\nscrollYParser\n cue y\n extends abstractColumnNameParser\nabstractPlotLabelParser\n cueFromId\n atoms cueAtom\n catchAllAtomType stringAtom\nquoteLineParser\n popularity 0.004172\n catchAllAtomType stringAtom\n catchAllParser quoteLineParser\nscrollParser\n description Scroll is a language for scientists of all ages. Refine, share and collaborate on ideas.\n root\n inScope abstractScrollParser blankLineParser atomTypeDefinitionParser parserDefinitionParser\n catchAllParser catchAllParagraphParser\n javascript\n setFile(file) {\n this.file = file\n const date = this.get(\"date\")\n if (date) this.file.timestamp = this.dayjs(this.get(\"date\")).unix()\n return this\n }\n buildHtml(buildSettings) {\n this.sectionStack = []\n return this.filter(subparticle => subparticle.buildHtml).map(subparticle => { try {return subparticle.buildHtml(buildSettings)} catch (err) {console.error(err); return \"\"} }).filter(i => i).join(\"\\n\") + this.clearSectionStack()\n }\n sectionStack = []\n clearSectionStack() {\n const result = this.sectionStack.join(\"\\n\")\n this.sectionStack = []\n return result\n }\n bodyStack = []\n clearBodyStack() {\n const result = this.bodyStack.join(\"\")\n this.bodyStack = []\n return result\n }\n get hakonParser() {\n if (this.isNodeJs())\n return require(\"scrollsdk/products/hakon.nodejs.js\")\n return hakonParser\n }\n readSyncFromFileOrUrl(fileOrUrl) {\n if (!this.isNodeJs()) return this.getInBrowser(fileOrUrl)\n const isUrl = fileOrUrl.match(/^https?\\:[^ ]+$/)\n if (!isUrl) return this.root.readFile(fileOrUrl)\n return this.readFile(this.makeFullPath(new URL(fileOrUrl).pathname.split('/').pop()))\n }\n getInBrowser(key) {\n return localStorage.getItem(key) || (window.inMemStorage ? window.inMemStorage[key] : \"\") || \"\"\n }\n async fetch(url, filename) {\n const isUrl = url.match(/^https?\\:[^ ]+$/)\n if (!isUrl) return\n return this.isNodeJs() ? this.fetchNode(url, filename) : this.fetchBrowser(url)\n }\n get path() {\n return require(\"path\")\n }\n makeFullPath(filename) {\n return this.path.join(this.folderPath, filename)\n }\n _nextAndPrevious(arr, index) {\n const nextIndex = index + 1\n const previousIndex = index - 1\n return {\n previous: arr[previousIndex] ?? arr[arr.length - 1],\n next: arr[nextIndex] ?? arr[0]\n }\n }\n // keyboard nav is always in the same folder. does not currently support cross folder\n includeFileInKeyboardNav(file) {\n const { scrollProgram } = file\n return scrollProgram.buildsHtml && scrollProgram.hasKeyboardNav && scrollProgram.tags.includes(this.primaryTag)\n }\n get timeIndex() {\n return this.file.timeIndex || 0\n }\n get linkToPrevious() {\n if (!this.hasKeyboardNav)\n // Dont provide link to next unless keyboard nav is on\n return undefined\n const {allScrollFiles} = this\n let file = this._nextAndPrevious(allScrollFiles, this.timeIndex).previous\n while (!this.includeFileInKeyboardNav(file)) {\n file = this._nextAndPrevious(allScrollFiles, file.timeIndex).previous\n }\n return file.scrollProgram.permalink\n }\n importRegex = /^(import |[a-zA-Z\\_\\-\\.0-9\\/]+\\.(scroll|parsers)$|https?:\\/\\/.+\\.(scroll|parsers)$)/gm\n get linkToNext() {\n if (!this.hasKeyboardNav)\n // Dont provide link to next unless keyboard nav is on\n return undefined\n const {allScrollFiles} = this\n let file = this._nextAndPrevious(allScrollFiles, this.timeIndex).next\n while (!this.includeFileInKeyboardNav(file)) {\n file = this._nextAndPrevious(allScrollFiles, file.timeIndex).next\n }\n return file.scrollProgram.permalink\n }\n // todo: clean up this naming pattern and add a parser instead of special casing 404.html\n get allHtmlFiles() {\n return this.allScrollFiles.filter(file => file.scrollProgram.buildsHtml && file.scrollProgram.permalink !== \"404.html\")\n }\n parseNestedTag(tag) {\n if (!tag.includes(\"/\")) return;\n const {path} = this\n const parts = tag.split(\"/\")\n const group = parts.pop()\n const relativePath = parts.join(\"/\")\n return {\n group,\n relativePath,\n folderPath: path.join(this.folderPath, path.normalize(relativePath))\n }\n }\n getFilesByTags(tags, limit) {\n // todo: tags is currently matching partial substrings\n const getFilesWithTag = (tag, files) => files.filter(file => file.scrollProgram.buildsHtml && file.scrollProgram.tags.includes(tag))\n if (typeof tags === \"string\") tags = tags.split(\" \")\n if (!tags || !tags.length)\n return this.allHtmlFiles\n .filter(file => file !== this) // avoid infinite loops. todo: think this through better.\n .map(file => {\n return { file, relativePath: \"\" }\n })\n .slice(0, limit)\n let arr = []\n tags.forEach(tag => {\n if (!tag.includes(\"/\"))\n return (arr = arr.concat(\n getFilesWithTag(tag, this.allScrollFiles)\n .map(file => {\n return { file, relativePath: \"\" }\n })\n .slice(0, limit)\n ))\n const {folderPath, group, relativePath} = this.parseNestedTag(tag)\n let files = []\n try {\n files = this.fileSystem.getCachedLoadedFilesInFolder(folderPath, this)\n } catch (err) {\n console.error(err)\n }\n const filtered = getFilesWithTag(group, files).map(file => {\n return { file, relativePath: relativePath + \"/\" }\n })\n arr = arr.concat(filtered.slice(0, limit))\n })\n return this.lodash.sortBy(arr, file => file.file.timestamp).reverse()\n }\n async fetchNode(url, filename) {\n filename = filename || new URL(url).pathname.split('/').pop()\n const fullpath = this.makeFullPath(filename)\n if (require(\"fs\").existsSync(fullpath)) return this.readFile(fullpath)\n this.log(`🛜 fetching ${url} to ${fullpath} `)\n await this.downloadToDisk(url, fullpath)\n return this.readFile(fullpath)\n }\n log(message) {\n if (this.logger) this.logger.log(message)\n }\n async fetchBrowser(url) {\n const content = this.getInBrowser(url)\n if (content) return content\n return this.downloadToLocalStorage(url)\n }\n async downloadToDisk(url, destination) {\n const { writeFile } = require('fs').promises\n const response = await fetch(url)\n const fileBuffer = await response.arrayBuffer()\n await writeFile(destination, Buffer.from(fileBuffer))\n return this.readFile(destination)\n }\n async downloadToLocalStorage(url) {\n const response = await fetch(url)\n const blob = await response.blob()\n const text = await blob.text()\n try {\n localStorage.setItem(url, text)\n return localStorage.getItem(url)\n } catch (err) {\n if (!window.inMemStorage) window.inMemStorage = {}\n window.inMemStorage[url] = text\n console.error(err)\n return text\n }\n }\n readFile(filename) {\n const {path} = this\n const fs = require(\"fs\")\n const fullPath = path.join(this.folderPath, filename.replace(this.folderPath, \"\"))\n try {\n if (fs.existsSync(fullPath))\n return fs.readFileSync(fullPath, \"utf8\")\n console.error(`File '${filename}' not found`)\n return \"\"\n } catch (err) {\n console.error(`Error in '${this.filePath}' reading file: '${fullPath}'`)\n console.error(err)\n return \"\"\n }\n }\n alreadyRequired = new Set()\n buildHtmlSnippet(buildSettings) {\n this.sectionStack = []\n return this.map(subparticle => (subparticle.buildHtmlSnippet ? subparticle.buildHtmlSnippet(buildSettings) : subparticle.buildHtml(buildSettings)))\n .filter(i => i)\n .join(\"\\n\")\n .trim() + this.clearSectionStack()\n }\n get footnotes() {\n if (this._footnotes === undefined) this._footnotes = this.filter(particle => particle.isFootnote)\n return this._footnotes\n }\n get authors() {\n return this.get(\"authors\")\n }\n get allScrollFiles() {\n try {\n return this.fileSystem.getCachedLoadedFilesInFolder(this.folderPath, this)\n } catch (err) {\n console.error(err)\n return []\n }\n }\n async doThing(thing) {\n await Promise.all(this.filter(particle => particle[thing]).map(async particle => particle[thing]()))\n }\n async load() {\n await this.doThing(\"load\")\n }\n async execute() {\n await this.doThing(\"execute\")\n }\n file = {}\n getFromParserId(parserId) {\n return this.parserIdIndex[parserId]?.[0].content\n }\n get fileSystem() {\n return this.file.fileSystem\n }\n get filePath() {\n return this.file.filePath\n }\n get folderPath() {\n return this.file.folderPath\n }\n get filename() {\n return this.file.filename || \"\"\n }\n get hasKeyboardNav() {\n return this.has(\"keyboardNav\")\n }\n get editHtml() {\n return `<a href=\"${this.editUrl}\" class=\"abstractTextLinkParser\">Edit</a>`\n }\n get externalsPath() {\n return this.file.EXTERNALS_PATH\n }\n get endSnippetIndex() {\n // Get the line number that the snippet should stop at.\n // First if its hard coded, use that\n if (this.has(\"endSnippet\")) return this.getParticle(\"endSnippet\").index\n // Next look for a dinkus\n const snippetBreak = this.find(particle => particle.isDinkus)\n if (snippetBreak) return snippetBreak.index\n return -1\n }\n get parserIds() {\n return this.topDownArray.map(particle => particle.definition.id)\n }\n get tags() {\n return this.get(\"tags\") || \"\"\n }\n get primaryTag() {\n return this.tags.split(\" \")[0]\n }\n get filenameNoExtension() {\n return this.filename.replace(\".scroll\", \"\")\n }\n // todo: rename publishedUrl? Or something to indicate that this is only for stuff on the web (not localhost)\n // BaseUrl must be provided for RSS Feeds and OpenGraph tags to work\n get baseUrl() {\n const baseUrl = (this.get(\"baseUrl\") || \"\").replace(/\\/$/, \"\")\n return baseUrl + \"/\"\n }\n get canonicalUrl() {\n return this.get(\"canonicalUrl\") || this.baseUrl + this.permalink\n }\n get openGraphImage() {\n const openGraphImage = this.get(\"openGraphImage\")\n if (openGraphImage !== undefined) return this.ensureAbsoluteLink(openGraphImage)\n const images = this.filter(particle => particle.doesExtend(\"scrollImageParser\"))\n const hit = images.find(particle => particle.has(\"openGraph\")) || images[0]\n if (!hit) return \"\"\n return this.ensureAbsoluteLink(hit.filename)\n }\n get absoluteLink() {\n return this.ensureAbsoluteLink(this.permalink)\n }\n ensureAbsoluteLink(link) {\n if (link.includes(\"://\")) return link\n return this.baseUrl + link.replace(/^\\//, \"\")\n }\n get editUrl() {\n const editUrl = this.get(\"editUrl\")\n if (editUrl) return editUrl\n const editBaseUrl = this.get(\"editBaseUrl\")\n return (editBaseUrl ? editBaseUrl.replace(/\\/$/, \"\") + \"/\" : \"\") + this.filename\n }\n get gitRepo() {\n // given https://github.com/breck7/breckyunits.com/blob/main/four-tips-to-improve-communication.scroll\n // return https://github.com/breck7/breckyunits.com\n return this.editUrl.split(\"/\").slice(0, 5).join(\"/\")\n }\n get scrollVersion() {\n // currently manually updated\n return \"168.1.0\"\n }\n // Use the first paragraph for the description\n // todo: add a particle method version of get that gets you the first particle. (actulaly make get return array?)\n // would speed up a lot.\n get description() {\n const description = this.getFromParserId(\"openGraphDescriptionParser\")\n if (description) return description\n return this.generatedDescription\n }\n get keywords() {\n if (this.has(\"keywords\"))\n return this.get(\"keywords\")\n const tags = this.get(\"tags\")\n if (tags)\n return tags.split(\" \").join(\", \")\n return \"\"\n }\n get generatedDescription() {\n const firstParagraph = this.find(particle => particle.isArticleContent)\n return firstParagraph ? firstParagraph.originalText.substr(0, 100).replace(/[&\"<>']/g, \"\") : \"\"\n }\n get titleFromFilename() {\n const unCamelCase = str => str.replace(/([a-z])([A-Z])/g, \"$1 $2\").replace(/^./, match => match.toUpperCase())\n return unCamelCase(this.filenameNoExtension)\n }\n get title() {\n return this.getFromParserId(\"scrollTitleParser\") || this.titleFromFilename\n }\n get linkTitle() {\n return this.getFromParserId(\"scrollLinkTitleParser\") || this.title\n }\n get permalink() {\n return this.get(\"permalink\") || (this.filename ? this.filenameNoExtension + \".html\" : \"\")\n }\n compileTo(extensionCapitalized) {\n if (extensionCapitalized === \"Txt\")\n return this.asTxt\n if (extensionCapitalized === \"Html\")\n return this.asHtml\n const methodName = \"build\" + extensionCapitalized\n return this.topDownArray\n .filter(particle => particle[methodName])\n .map((particle, index) => particle[methodName](index))\n .join(\"\\n\")\n .trim()\n }\n get asTxt() {\n return (\n this.map(particle => {\n const text = particle.buildTxt ? particle.buildTxt() : \"\"\n if (text) return text + \"\\n\"\n if (!particle.getLine().length) return \"\\n\"\n return \"\"\n })\n .join(\"\")\n .replace(/<[^>]*>/g, \"\")\n .replace(/\\n\\n\\n+/g, \"\\n\\n\") // Maximum 2 newlines in a row\n .trim() + \"\\n\" // Always end in a newline, Posix style\n )\n }\n get dependencies() {\n const dependencies = this.file.dependencies?.slice() || []\n const files = this.topDownArray.filter(particle => particle.dependencies).map(particle => particle.dependencies).flat()\n return dependencies.concat(files)\n }\n get buildsHtml() {\n const { permalink } = this\n return !this.file.importOnly && (permalink.endsWith(\".html\") || permalink.endsWith(\".htm\"))\n }\n // Without specifying the language hyphenation will not work.\n get lang() {\n return this.get(\"htmlLang\") || \"en\"\n }\n _compiledHtml = \"\"\n get asHtml() {\n if (!this._compiledHtml) {\n const { permalink, buildsHtml } = this\n const content = (this.buildHtml() + this.clearBodyStack()).trim()\n // Don't add html tags to CSV feeds. A little hacky as calling a getter named _html_ to get _xml_ is not ideal. But\n // <1% of use case so might be good enough.\n const wrapWithHtmlTags = buildsHtml\n const bodyTag = this.has(\"metaTags\") ? \"\" : \"<body>\\n\"\n this._compiledHtml = wrapWithHtmlTags ? `<!DOCTYPE html>\\n<html lang=\"${this.lang}\">\\n${bodyTag}${content}\\n</body>\\n</html>` : content\n }\n return this._compiledHtml\n }\n get wordCount() {\n return this.asTxt.match(/\\b\\w+\\b/g)?.length || 0\n }\n get minutes() {\n return parseFloat((this.wordCount / 200).toFixed(1))\n }\n get date() {\n const date = this.get(\"date\") || (this.file.timestamp ? this.file.timestamp : 0)\n return this.dayjs(date).format(`MM/DD/YYYY`)\n }\n get year() {\n return parseInt(this.dayjs(this.date).format(`YYYY`))\n }\n get dayjs() {\n if (!this.isNodeJs()) return dayjs\n const lib = require(\"dayjs\")\n const relativeTime = require(\"dayjs/plugin/relativeTime\")\n lib.extend(relativeTime)\n return lib\n }\n get lodash() {\n return this.isNodeJs() ? require(\"lodash\") : lodash\n }\n get d3() {\n return this.isNodeJs() ? require('d3') : d3\n }\n getConcepts(parsed) {\n const concepts = []\n let currentConcept\n parsed.forEach(particle => {\n if (particle.isConceptDelimiter) {\n if (currentConcept) concepts.push(currentConcept)\n currentConcept = []\n }\n if (currentConcept && particle.isMeasure) currentConcept.push(particle)\n })\n if (currentConcept) concepts.push(currentConcept)\n return concepts\n }\n _formatConcepts(parsed) {\n const concepts = this.getConcepts(parsed)\n if (!concepts.length) return false\n const {lodash} = this\n // does a destructive sort in place on the parsed program\n concepts.forEach(concept => {\n let currentSection\n const newCode = lodash\n .sortBy(concept, [\"sortIndex\"])\n .map(particle => {\n let newLines = \"\"\n const section = particle.sortIndex.toString().split(\".\")[0]\n if (section !== currentSection) {\n currentSection = section\n newLines = \"\\n\"\n }\n return newLines + particle.toString()\n })\n .join(\"\\n\")\n concept.forEach((particle, index) => (index ? particle.destroy() : \"\"))\n concept[0].replaceParticle(() => newCode)\n })\n }\n get formatted() {\n return this.getFormatted(this.file.codeAtStart)\n }\n get lastCommitTime() {\n // todo: speed this up and do a proper release. also could add more metrics like this.\n if (this._lastCommitTime === undefined) {\n try {\n this._lastCommitTime = require(\"child_process\").execSync(`git log -1 --format=\"%at\" -- \"${this.filePath}\"`).toString().trim()\n } catch (err) {\n this._lastCommitTime = 0\n }\n }\n return this._lastCommitTime\n }\n getFormatted(codeAtStart = this.toString()) {\n let formatted = codeAtStart.replace(/\\r/g, \"\") // remove all carriage returns if there are any\n const parsed = new this.constructor(formatted)\n parsed.topDownArray.forEach(subparticle => {\n subparticle.format()\n const original = subparticle.getLine()\n const trimmed = original.replace(/(\\S.*?)[ \\t]*$/gm, \"$1\")\n // Trim trailing whitespace unless parser allows it\n if (original !== trimmed && !subparticle.allowTrailingWhitespace) subparticle.setLine(trimmed)\n })\n this._formatConcepts(parsed)\n let importOnlys = []\n let topMatter = []\n let allElse = []\n // Create any bindings\n parsed.forEach(particle => {\n if (particle.bindTo === \"next\") particle.binding = particle.next\n if (particle.bindTo === \"previous\") particle.binding = particle.previous\n })\n parsed.forEach(particle => {\n if (particle.getLine() === \"importOnly\") importOnlys.push(particle)\n else if (particle.isTopMatter) topMatter.push(particle)\n else allElse.push(particle)\n })\n const combined = importOnlys.concat(topMatter, allElse)\n // Move any bound particles\n combined\n .filter(particle => particle.bindTo)\n .forEach(particle => {\n // First remove the particle from its current position\n const originalIndex = combined.indexOf(particle)\n combined.splice(originalIndex, 1)\n // Then insert it at the new position\n // We need to find the binding index again after removal\n const bindingIndex = combined.indexOf(particle.binding)\n if (particle.bindTo === \"next\") combined.splice(bindingIndex, 0, particle)\n else combined.splice(bindingIndex + 1, 0, particle)\n })\n const trimmed = combined\n .map(particle => particle.toString())\n .join(\"\\n\")\n .replace(/^\\n*/, \"\") // Remove leading newlines\n .replace(/\\n\\n\\n+/g, \"\\n\\n\") // Maximum 2 newlines in a row\n .replace(/\\n+$/, \"\")\n return trimmed === \"\" ? trimmed : trimmed + \"\\n\" // End non blank Scroll files in a newline character POSIX style for better working with tools like git\n }\n get parser() {\n return this.constructor\n }\n get parsersRequiringExternals() {\n const { parser } = this\n // todo: could be cleaned up a bit\n if (!parser.parsersRequiringExternals) parser.parsersRequiringExternals = parser.cachedHandParsersProgramRoot.filter(particle => particle.copyFromExternal).map(particle => particle.atoms[0])\n return parser.parsersRequiringExternals\n }\n get Disk() { return this.isNodeJs() ? require(\"scrollsdk/products/Disk.node.js\").Disk : {}}\n async buildAll(options = {}) {\n await this.load()\n await this.buildOne(options)\n await this.buildTwo(options)\n }\n async buildOne(options) {\n await this.execute()\n const toBuild = this.filter(particle => particle.buildOne)\n for (let particle of toBuild) {\n await particle.buildOne(options)\n }\n }\n async buildTwo(options) {\n const toBuild = this.filter(particle => particle.buildTwo)\n for (let particle of toBuild) {\n await particle.buildTwo(options)\n }\n }\n get outputFileNames() {\n return this.filter(p => p.outputFileNames).map(p => p.outputFileNames).flat()\n }\n _compileArray(filename, arr) {\n const removeBlanks = data => data.map(obj => Object.fromEntries(Object.entries(obj).filter(([_, value]) => value !== \"\")))\n const parts = filename.split(\".\")\n const format = parts.pop()\n if (format === \"json\") return JSON.stringify(removeBlanks(arr), null, 2)\n if (format === \"js\") return `const ${parts[0]} = ` + JSON.stringify(removeBlanks(arr), null, 2)\n if (format === \"csv\") return this.arrayToCSV(arr)\n if (format === \"tsv\") return this.arrayToCSV(arr, \"\\t\")\n if (format === \"particles\") return particles.toString()\n return particles.toString()\n }\n levenshteinDistance(a, b) {\n const m = a.length\n const n = b.length\n const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0))\n for (let i = 0; i <= m; i++) {\n dp[i][0] = i\n }\n for (let j = 0; j <= n; j++) {\n dp[0][j] = j\n }\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1\n dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost)\n }\n }\n return dp[m][n]\n }\n makeLodashOrderByParams(str) {\n const part1 = str.split(\" \")\n const part2 = part1.map(col => (col.startsWith(\"-\") ? \"desc\" : \"asc\"))\n return [part1.map(col => col.replace(/^\\-/, \"\")), part2]\n }\n arrayToCSV(data, delimiter = \",\") {\n if (!data.length) return \"\"\n // Extract headers\n const headers = Object.keys(data[0])\n const csv = data.map(row =>\n headers\n .map(fieldName => {\n const fieldValue = row[fieldName]\n // Escape commas if the value is a string\n if (typeof fieldValue === \"string\" && fieldValue.includes(delimiter)) {\n return `\"${fieldValue.replace(/\"/g, '\"\"')}\"` // Escape double quotes and wrap in double quotes\n }\n return fieldValue\n })\n .join(delimiter)\n )\n csv.unshift(headers.join(delimiter)) // Add header row at the top\n return csv.join(\"\\n\")\n }\n compileConcepts(filename = \"csv\", sortBy = \"\") {\n const {lodash} = this\n if (!sortBy) return this._compileArray(filename, this.concepts)\n const orderBy = this.makeLodashOrderByParams(sortBy)\n return this._compileArray(filename, lodash.orderBy(this.concepts, orderBy[0], orderBy[1]))\n }\n _withStats\n get measuresWithStats() {\n if (!this._withStats) this._withStats = this.addMeasureStats(this.concepts, this.measures)\n return this._withStats\n }\n addMeasureStats(concepts, measures){\n return measures.map(measure => {\n let Type = false\n concepts.forEach(concept => {\n const value = concept[measure.Name]\n if (value === undefined || value === \"\") return\n measure.Values++\n if (!Type) {\n measure.Example = value.toString().replace(/\\n/g, \" \")\n measure.Type = typeof value\n Type = true\n }\n })\n measure.Coverage = Math.floor((100 * measure.Values) / concepts.length) + \"%\"\n return measure\n })\n }\n parseMeasures(parser) {\n if (!Particle.measureCache)\n Particle.measureCache = new Map()\n const measureCache = Particle.measureCache\n if (measureCache.get(parser)) return measureCache.get(parser)\n const {lodash} = this\n // todo: clean this up\n const getCueAtoms = rootParserProgram =>\n rootParserProgram\n .filter(particle => particle.getLine().endsWith(\"Parser\") && !particle.getLine().startsWith(\"abstract\"))\n .map(particle => particle.get(\"cue\") || particle.getLine())\n .map(line => line.replace(/Parser$/, \"\"))\n // Generate a fake program with one of every of the available parsers. Then parse it. Then we can easily access the meta data on the parsers\n const dummyProgram = new parser(\n Array.from(\n new Set(\n getCueAtoms(parser.cachedHandParsersProgramRoot) // is there a better method name than this?\n )\n ).join(\"\\n\")\n )\n // Delete any particles that are not measures\n dummyProgram.filter(particle => !particle.isMeasure).forEach(particle => particle.destroy())\n dummyProgram.forEach(particle => {\n // add nested measures\n Object.keys(particle.definition.cueMapWithDefinitions).forEach(key => particle.appendLine(key))\n })\n // Delete any nested particles that are not measures\n dummyProgram.topDownArray.filter(particle => !particle.isMeasure).forEach(particle => particle.destroy())\n const measures = dummyProgram.topDownArray.map(particle => {\n return {\n Name: particle.measureName,\n Values: 0,\n Coverage: 0,\n Question: particle.definition.description,\n Example: particle.definition.getParticle(\"example\")?.subparticlesToString() || \"\",\n Type: particle.typeForWebForms,\n Source: particle.sourceDomain,\n //Definition: parsedProgram.root.filename + \":\" + particle.lineNumber\n SortIndex: particle.sortIndex,\n IsComputed: particle.isComputed,\n IsRequired: particle.isMeasureRequired,\n IsConceptDelimiter: particle.isConceptDelimiter,\n Cue: particle.definition.get(\"cue\")\n }\n })\n measureCache.set(parser, lodash.sortBy(measures, \"SortIndex\"))\n return measureCache.get(parser)\n }\n _concepts\n get concepts() {\n if (this._concepts) return this._concepts\n this._concepts = this.parseConcepts(this, this.measures)\n return this._concepts\n }\n _measures\n get measures() {\n if (this._measures) return this._measures\n this._measures = this.parseMeasures(this.parser)\n return this._measures\n }\n parseConcepts(parsedProgram, measures){\n // Todo: might be a perf/memory/simplicity win to have a \"segment\" method in ScrollSDK, where you could\n // virtually split a Particle into multiple segments, and then query on those segments.\n // So we would \"segment\" on \"id \", and then not need to create a bunch of new objects, and the original\n // already parsed lines could then learn about/access to their respective segments.\n const conceptDelimiter = measures.filter(measure => measure.IsConceptDelimiter)[0]\n if (!conceptDelimiter) return []\n const concepts = parsedProgram.split(conceptDelimiter.Cue || conceptDelimiter.Name)\n concepts.shift() // Remove the part before \"id\"\n return concepts.map(concept => {\n const row = {}\n measures.forEach(measure => {\n const measureName = measure.Name\n const measureKey = measure.Cue || measureName.replace(/_/g, \" \")\n if (!measure.IsComputed) row[measureName] = concept.getParticle(measureKey)?.measureValue ?? \"\"\n else row[measureName] = this.computeMeasure(parsedProgram, measureName, concept, concepts)\n })\n return row\n })\n }\n computeMeasure(parsedProgram, measureName, concept, concepts){\n // note that this is currently global, assuming there wont be. name conflicts in computed measures in a single scroll\n if (!Particle.measureFnCache) Particle.measureFnCache = {}\n const measureFnCache = Particle.measureFnCache\n if (!measureFnCache[measureName]) {\n // a bit hacky but works??\n const particle = parsedProgram.appendLine(measureName)\n measureFnCache[measureName] = particle.computeValue\n particle.destroy()\n }\n return measureFnCache[measureName](concept, measureName, parsedProgram, concepts)\n }\n compileMeasures(filename = \"csv\", sortBy = \"\") {\n const withStats = this.measuresWithStats\n if (!sortBy) return this._compileArray(filename, withStats)\n const orderBy = this.makeLodashOrderByParams(sortBy)\n return this._compileArray(filename, this.lodash.orderBy(withStats, orderBy[0], orderBy[1]))\n }\n evalNodeJsMacros(value, macroMap, filePath) {\n const tempPath = filePath + \".js\"\n const {Disk} = this\n if (Disk.exists(tempPath)) throw new Error(`Failed to write/require replaceNodejs snippet since '${tempPath}' already exists.`)\n try {\n Disk.write(tempPath, value)\n const results = require(tempPath)\n Object.keys(results).forEach(key => (macroMap[key] = results[key]))\n } catch (err) {\n console.error(`Error in evalMacros in file '${filePath}'`)\n console.error(err)\n } finally {\n Disk.rm(tempPath)\n }\n }\n evalMacros(fusedFile) {\n const {fusedCode, codeAtStart, filePath} = fusedFile\n let code = fusedCode\n const absolutePath = filePath\n // note: the 2 params above are not used in this method, but may be used in user eval code. (todo: cleanup)\n const regex = /^(replace|toFooter$)/gm\n if (!regex.test(code)) return code\n const particle = new Particle(code) // todo: this can be faster. a more lightweight particle class?\n // Process macros\n const macroMap = {}\n particle\n .filter(particle => {\n const parserAtom = particle.cue\n return parserAtom === \"replace\" || parserAtom === \"replaceJs\" || parserAtom === \"replaceNodejs\"\n })\n .forEach(particle => {\n let value = particle.length ? particle.subparticlesToString() : particle.getAtomsFrom(2).join(\" \")\n const kind = particle.cue\n try {\n if (kind === \"replaceJs\") value = eval(value)\n if (this.isNodeJs() && kind === \"replaceNodejs\")\n this.evalNodeJsMacros(value, macroMap, absolutePath)\n else macroMap[particle.getAtom(1)] = value\n } catch (err) {\n console.error(err)\n }\n particle.destroy() // Destroy definitions after eval\n })\n if (particle.has(\"toFooter\")) {\n const pushes = particle.getParticles(\"toFooter\")\n const append = pushes.map(push => push.section.join(\"\\n\")).join(\"\\n\")\n pushes.forEach(push => {\n push.section.forEach(particle => particle.destroy())\n push.destroy()\n })\n code = particle.asString + append\n }\n const keys = Object.keys(macroMap)\n if (!keys.length) return code\n let codeAfterMacroSubstitution = particle.asString\n // Todo: speed up. build a template?\n Object.keys(macroMap).forEach(key => (codeAfterMacroSubstitution = codeAfterMacroSubstitution.replace(new RegExp(key, \"g\"), macroMap[key])))\n return codeAfterMacroSubstitution\n }\n toRss() {\n const { title, canonicalUrl } = this\n return ` <item>\n <title>${title}</title>\n <link>${canonicalUrl}</link>\n <pubDate>${this.dayjs(this.timestamp * 1000).format(\"ddd, DD MMM YYYY HH:mm:ss ZZ\")}</pubDate>\n </item>`\n }\n example\n # Hello world\n ## This is Scroll\n * It compiles to HTML.\n \n code\n // You can add code as well.\n print(\"Hello world\")\nstampFileParser\n catchAllAtomType stringAtom\n description Create a file.\n javascript\n execute(parentDir) {\n const fs = require(\"fs\")\n const path = require(\"path\")\n const fullPath = path.join(parentDir, this.getLine())\n this.root.log(`Creating file ${fullPath}`)\n fs.mkdirSync(path.dirname(fullPath), {recursive: true})\n const content = this.subparticlesToString()\n fs.writeFileSync(fullPath, content, \"utf8\")\n const isExecutable = content.startsWith(\"#!\")\n if (isExecutable) fs.chmodSync(fullPath, \"755\")\n }\nstampFolderParser\n catchAllAtomType stringAtom\n description Create a folder.\n inScope stampFolderParser\n catchAllParser stampFileParser\n pattern \\/$\n javascript\n execute(parentDir) {\n const fs = require(\"fs\")\n const path = require(\"path\")\n const newPath = path.join(parentDir, this.getLine())\n this.root.log(`Creating folder ${newPath}`)\n fs.mkdirSync(newPath, {recursive: true})\n this.forEach(particle => particle.execute(newPath))\n }\nstumpContentParser\n popularity 0.102322\n catchAllAtomType codeAtom\nscrollTableDataParser\n popularity 0.001061\n cue data\n atoms cueAtom\n description Table from inline delimited data.\n baseParser blobParser\nscrollTableDelimiterParser\n popularity 0.001037\n description Set the delimiter.\n cue delimiter\n atoms cueAtom stringAtom\n javascript\n buildHtml() {\n return \"\"\n }\nplainTextLineParser\n popularity 0.000121\n catchAllAtomType stringAtom\n catchAllParser plainTextLineParser"} \ No newline at end of file +const AppConstants = {"parsers":"columnNameAtom\n paint constant\nnewColumnNameAtom\n description Name a derived column.\n paint variable\nconstantAtom\n paint constant\npercentAtom\n paint constant.numeric.float\n extends stringAtom\n // todo: this currently extends from stringAtom b/c scrollsdk needs to be fixed. seems like if extending from number then the hard coded number typescript regex takes precedence over a custom regex\ncountAtom\n extends integerAtom\nyearAtom\n extends integerAtom\npreBuildCommandAtom\n extends cueAtom\n description Give build command atoms their own color.\n paint constant.character.escape\ndelimiterAtom\n description String to use as a delimiter.\n paint string\nbulletPointAtom\n description Any token used as a bullet point such as \"-\" or \"1.\" or \">\"\n paint keyword\ncomparisonAtom\n enum < > <= >= = != includes doesNotInclude empty notEmpty startsWith endsWith\n paint constant\npersonNameAtom\n extends stringAtom\nurlAtom\n paint constant.language\nabsoluteUrlAtom\n paint constant.language\n regex (ftp|https?)://.+\nemailAddressAtom\n extends stringAtom\n paint constant.language\npermalinkAtom\n paint string\n description A string that doesn't contain characters that might interfere with most filesystems. No slashes, for instance.\nfilePathAtom\n paint constant.language\ntagOrUrlAtom\n description An HTML tag or a url.\n paint constant.language\nhtmlAttributesAtom\n paint constant\nhtmlTagAtom\n paint constant.language\n enum div span p a img ul ol li h1 h2 h3 h4 h5 h6 header nav section article aside main footer input button form label select option textarea table tr td th tbody thead tfoot br hr meta link script style title code\nhtmlTypeAtom\n extends stringAtom\n paint constant.language\n enum text password email number tel url search date time datetime-local week month color checkbox radio file submit reset button hidden range\n description HTML input type attribute values.\nclassNameAtom\n paint constant\nhtmlIdAtom\n paint constant\nfontFamilyAtom\n enum Arial Helvetica Verdana Georgia Impact Tahoma Slim\n paint constant\njavascriptAnyAtom\n extends codeAtom\nhtmlAnyAtom\n extends codeAtom\ncolorAtom\n extends codeAtom\nnamedColorAtom\n extends colorAtom\n enum aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkkhaki darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray darkturquoise darkviolet deeppink deepskyblue dimgray dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow honeydew hotpink indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgoldenrodyellow lightgray lightgreen lightpink lightsalmon lightseagreen lightskyblue lightslategray lightsteelblue lightyellow lime limegreen linen magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell sienna silver skyblue slateblue slategray snow springgreen steelblue tan teal thistle tomato turquoise violet wheat white whitesmoke yellow yellowgreen\nbuildCommandAtom\n extends cueAtom\n description Give build command atoms their own color.\n paint constant\ncssAnyAtom\n extends codeAtom\ncssLengthAtom\n extends codeAtom\nreductionTypeAtom\n enum sum mean max min concat first\n paint keyword\ninlineMarkupNameAtom\n description Options to turn on some inline markups.\n enum bold italics code katex none\ntileOptionAtom\n enum default light\nmeasureNameAtom\n extends cueAtom\n // A regex for column names for max compatibility with a broad range of data science tools:\n regex [a-zA-Z][a-zA-Z0-9]*\nabstractConstantAtom\n paint entity.name.tag\njavascriptSafeAlphaNumericIdentifierAtom\n regex [a-zA-Z0-9_]+\n reservedAtoms enum extends function static if while export return class for default require var let const new\nanyAtom\nbaseParsersAtom\n description There are a few classes of special parsers. BlobParsers don't have their subparticles parsed. Error particles always report an error.\n // todo Remove?\n enum blobParser errorParser\n paint variable.parameter\nenumAtom\n paint constant.language\nbooleanAtom\n enum true false\n extends enumAtom\natomParserAtom\n enum prefix postfix omnifix\n paint constant.numeric\natomPropertyNameAtom\n paint variable.parameter\natomTypeIdAtom\n examples integerAtom cueAtom someCustomAtom\n extends javascriptSafeAlphaNumericIdentifierAtom\n enumFromAtomTypes atomTypeIdAtom\n paint storage\nconstantIdentifierAtom\n examples someId myVar\n // todo Extend javascriptSafeAlphaNumericIdentifier\n regex [a-zA-Z]\\w+\n paint constant.other\n description A atom that can be assigned to the parser in the target language.\nconstructorFilePathAtom\nenumOptionAtom\n // todo Add an enumOption top level type, so we can add data to an enum option such as a description.\n paint string\natomExampleAtom\n description Holds an example for a atom with a wide range of options.\n paint string\nextraAtom\n paint invalid\nfileExtensionAtom\n examples js txt doc exe\n regex [a-zA-Z0-9]+\n paint string\nnumberAtom\n paint constant.numeric\nfloatAtom\n extends numberAtom\n regex \\-?[0-9]*\\.?[0-9]*\n paint constant.numeric.float\nintegerAtom\n regex \\-?[0-9]+\n extends numberAtom\n paint constant.numeric.integer\ncueAtom\n description A atom that indicates a certain parser to use.\n paint keyword\njavascriptCodeAtom\nlowercaseAtom\n regex [a-z]+\nparserIdAtom\n examples commentParser addParser\n description This doubles as the class name in Javascript. If this begins with `abstract`, then the parser will be considered an abstract parser, which cannot be used by itself but provides common functionality to parsers that extend it.\n paint variable.parameter\n extends javascriptSafeAlphaNumericIdentifierAtom\n enumFromAtomTypes parserIdAtom\ncueAtom\n paint constant.language\nregexAtom\n paint string.regexp\nreservedAtomAtom\n description A atom that a atom cannot contain.\n paint string\npaintTypeAtom\n enum comment comment.block comment.block.documentation comment.line constant constant.character.escape constant.language constant.numeric constant.numeric.complex constant.numeric.complex.imaginary constant.numeric.complex.real constant.numeric.float constant.numeric.float.binary constant.numeric.float.decimal constant.numeric.float.hexadecimal constant.numeric.float.octal constant.numeric.float.other constant.numeric.integer constant.numeric.integer.binary constant.numeric.integer.decimal constant.numeric.integer.hexadecimal constant.numeric.integer.octal constant.numeric.integer.other constant.other constant.other.placeholder entity entity.name entity.name.class entity.name.class.forward-decl entity.name.constant entity.name.enum entity.name.function entity.name.function.constructor entity.name.function.destructor entity.name.impl entity.name.interface entity.name.label entity.name.namespace entity.name.section entity.name.struct entity.name.tag entity.name.trait entity.name.type entity.name.union entity.other.attribute-name entity.other.inherited-class invalid invalid.deprecated invalid.illegal keyword keyword.control keyword.control.conditional keyword.control.import keyword.declaration keyword.operator keyword.operator.arithmetic keyword.operator.assignment keyword.operator.bitwise keyword.operator.logical keyword.operator.atom keyword.other markup markup.bold markup.deleted markup.heading markup.inserted markup.italic markup.list.numbered markup.list.unnumbered markup.other markup.quote markup.raw.block markup.raw.inline markup.underline markup.underline.link meta meta.annotation meta.annotation.identifier meta.annotation.parameters meta.block meta.braces meta.brackets meta.class meta.enum meta.function meta.function-call meta.function.parameters meta.function.return-type meta.generic meta.group meta.impl meta.interface meta.interpolation meta.namespace meta.paragraph meta.parens meta.path meta.preprocessor meta.string meta.struct meta.tag meta.toc-list meta.trait meta.type meta.union punctuation punctuation.accessor punctuation.definition.annotation punctuation.definition.comment punctuation.definition.generic.begin punctuation.definition.generic.end punctuation.definition.keyword punctuation.definition.string.begin punctuation.definition.string.end punctuation.definition.variable punctuation.section.block.begin punctuation.section.block.end punctuation.section.braces.begin punctuation.section.braces.end punctuation.section.brackets.begin punctuation.section.brackets.end punctuation.section.group.begin punctuation.section.group.end punctuation.section.interpolation.begin punctuation.section.interpolation.end punctuation.section.parens.begin punctuation.section.parens.end punctuation.separator punctuation.separator.continuation punctuation.terminator source source.language-suffix.embedded storage storage.modifier storage.type storage.type keyword.declaration.type storage.type.class keyword.declaration.class storage.type.enum keyword.declaration.enum storage.type.function keyword.declaration.function storage.type.impl keyword.declaration.impl storage.type.interface keyword.declaration.interface storage.type.struct keyword.declaration.struct storage.type.trait keyword.declaration.trait storage.type.union keyword.declaration.union string string.quoted.double string.quoted.other string.quoted.single string.quoted.triple string.regexp string.unquoted support support.class support.constant support.function support.module support.type text text.html text.xml variable variable.annotation variable.function variable.language variable.other variable.other.constant variable.other.member variable.other.readwrite variable.parameter\n paint string\nscriptUrlAtom\nsemanticVersionAtom\n examples 1.0.0 2.2.1\n regex [0-9]+\\.[0-9]+\\.[0-9]+\n paint constant.numeric\ndateAtom\n paint string\nstringAtom\n paint string\natomAtom\n paint constant\n description A non-empty single atom string.\n regex .+\nexampleAnyAtom\n examples lorem ipsem\n // todo Eventually we want to be able to parse correctly the examples.\n paint comment\n extends stringAtom\nblankAtom\ncommentAtom\n paint comment\ncodeAtom\n paint comment\ncolumnNameOrColorAtom\n extends columnNameAtom\nmetaCommandAtom\n extends cueAtom\n description Give meta command atoms their own color.\n paint constant.numeric\n // Obviously this is not numeric. But I like the green color for now.\n We need a better design to replace this \"paint\" concept\n https://github.com/breck7/scrollsdk/issues/186\nvegaDataSetAtom\n paint constant.numeric\n enum airports.csv anscombe.json barley.json birdstrikes.json budget.json budgets.json burtin.json cars.json climate.json co2-concentration.csv countries.json crimea.json descriptions.json disasters.csv driving.json earthquakes.json flare-dependencies.json flare.json flights-10k.json flights-200k.json flights-20k.json flights-2k.json flights-3m.csv flights-5k.json flights-airport.csv gapminder-health-income.csv gapminder.json github.csv graticule.json income.json iowa-electricity.csv iris.json jobs.json la-riots.csv londonBoroughs.json londonCentroids.json londonTubeLines.json lookup_groups.csv lookup_people.csv miserables.json monarchs.json movies.json normal-2d.json obesity.json points.json population.json population_engineers_hurricanes.csv seattle-temps.csv seattle-weather.csv sf-temps.csv sp500.csv stocks.csv udistrict.json unemployment-across-industries.json unemployment.tsv us-10m.json us-employment.csv us-state-capitals.json weather.csv weather.json weball26.json wheat.json windvectors.csv world-110m.json zipcodes.csv\ntagAtom\n extends permalinkAtom\ntagWithOptionalFolderAtom\n description A group name optionally combined with a folder path. Only used when referencing tags, not in posts.\n extends stringAtom\nscrollThemeAtom\n enum roboto gazette dark tufte prestige\n paint constant\nabstractScrollParser\n atoms cueAtom\n javascript\n buildHtmlSnippet(buildSettings) {\n return this.buildHtml(buildSettings)\n }\n buildTxt() {\n return \"\"\n }\n getHtmlRequirements(buildSettings) {\n const {requireOnce} = this\n if (!requireOnce)\n return \"\"\n const set = buildSettings?.alreadyRequired || this.root.alreadyRequired\n if (set.has(requireOnce))\n return \"\"\n set.add(requireOnce)\n return requireOnce + \"\\n\\n\"\n }\nabstractAftertextParser\n description Text followed by markup commands.\n extends abstractScrollParser\n inScope abstractAftertextDirectiveParser abstractAftertextAttributeParser aftertextTagParser abstractCommentParser\n javascript\n get markupInserts() {\n const { originalTextPostLinkify } = this\n return this.filter(particle => particle.isMarkup)\n .map(particle => particle.getInserts(originalTextPostLinkify))\n .filter(i => i)\n .flat()\n }\n get originalText() {\n return this.content ?? \"\"\n }\n get originalTextPostLinkify() {\n const { originalText } = this\n const shouldLinkify = this.get(\"linkify\") === \"false\" || originalText.includes(\"<a \") ? false : true\n return shouldLinkify ? this.replaceNotes(Utils.linkify(originalText)) : originalText\n }\n replaceNotes(originalText) {\n // Skip the replacements if there are no footnotes or the text has none.\n if (!this.root.footnotes.length || !originalText.includes(\"^\")) return originalText\n this.root.footnotes.forEach((note, index) => {\n const needle = note.cue\n const {linkBack} = note\n if (originalText.includes(needle)) originalText = originalText.replace(new RegExp(\"\\\\\" + needle + \"\\\\b\"), `<a href=\"#${note.htmlId}\" class=\"scrollNoteLink\" id=\"${linkBack}\"><sup>${note.label}</sup></a>`)\n })\n return originalText\n }\n get text() {\n const { originalTextPostLinkify, markupInserts } = this\n let adjustment = 0\n let newText = originalTextPostLinkify\n markupInserts.sort((a, b) => {\n if (a.index !== b.index)\n return a.index - b.index\n // If multiple tags start at same index, the tag that closes first should start last. Otherwise HTML breaks.\n if (b.index === b.endIndex) // unless the endIndex is the same as index\n return a.endIndex - b.endIndex\n return b.endIndex - a.endIndex\n })\n markupInserts.forEach(insertion => {\n insertion.index += adjustment\n const consumeStartCharacters = insertion.consumeStartCharacters ?? 0\n const consumeEndCharacters = insertion.consumeEndCharacters ?? 0\n newText = newText.slice(0, insertion.index - consumeEndCharacters) + insertion.string + newText.slice(insertion.index + consumeStartCharacters)\n adjustment += insertion.string.length - consumeEndCharacters - consumeStartCharacters\n })\n return newText\n }\n tag = \"p\"\n get className() {\n if (this.get(\"class\"))\n return this.get(\"class\")\n const classLine = this.getParticle(\"addClass\")\n if (classLine && classLine.applyToParentElement) return classLine.content\n return this.defaultClassName\n }\n defaultClassName = \"scrollParagraph\"\n get isHidden() {\n return this.has(\"hidden\")\n }\n buildHtml(buildSettings) {\n if (this.isHidden) return \"\"\n this.buildSettings = buildSettings\n const { className, styles } = this\n const classAttr = className ? `class=\"${this.className}\"` : \"\"\n const selfClose = this.isSelfClosing ? \" /\" : \"\"\n const tag = this.get(\"tag\") || this.tag\n if (tag === \"none\") // Allow no tag for aftertext in tables\n return this.text\n const id = this.has(\"id\") ? \"\" : `id=\"${this.htmlId}\" ` // always add an html id\n return this.getHtmlRequirements(buildSettings) + `<${tag} ${id}${this.htmlAttributes}${classAttr}${styles}${selfClose}>${this.htmlContents}${this.closingTag}`\n }\n get htmlContents() {\n return this.text\n }\n get closingTag() {\n if (this.isSelfClosing) return \"\"\n const tag = this.get(\"tag\") || this.tag\n return `</${tag}>`\n }\n get htmlAttributes() {\n const attrs = this.filter(particle => particle.isAttribute)\n return attrs.length ? attrs.map(particle => particle.htmlAttributes).join(\" \") + \" \" : \"\"\n }\n get styles() {\n const style = this.getParticle(\"style\")\n const fontFamily = this.getParticle(\"font\")\n const color = this.getParticle(\"color\")\n if (!style && !fontFamily && !color)\n return \"\"\n return ` style=\"${style?.content};${fontFamily?.css};${color?.css}\"`\n }\n get htmlId() {\n return this.get(\"id\") || \"particle\" + this.index\n }\nscrollParagraphParser\n // todo Perhaps rewrite this from scratch and move out of aftertext.\n extends abstractAftertextParser\n catchAllAtomType stringAtom\n description A paragraph.\n boolean suggestInAutocomplete false\n cueFromId\n javascript\n buildHtml(buildSettings) {\n if (this.isHidden) return \"\"\n // Hacky, I know.\n const newLine = this.has(\"inlineMarkupsOn\") ? undefined : this.appendLine(\"inlineMarkupsOn\")\n const compiled = super.buildHtml(buildSettings)\n if (newLine)\n newLine.destroy()\n return compiled\n }\n buildTxt() {\n const subparticles = this.filter(particle => particle.buildTxt).map(particle => particle.buildTxt()).filter(i => i).join(\"\\n\")\n const dateline = this.getParticle(\"dateline\")\n return (dateline ? dateline.day + \"\\n\\n\" : \"\") + (this.originalText || \"\") + (subparticles ? \"\\n \" + subparticles.replace(/\\n/g, \"\\n \") : \"\")\n }\nauthorsParser\n popularity 0.007379\n // multiple authors delimited by \" and \"\n boolean isPopular true\n extends scrollParagraphParser\n description Set author(s) name(s).\n example\n authors Breck Yunits\n https://breckyunits.com Breck Yunits\n // note: once we have mixins in Parsers, lets mixin the below from abstractTopLevelSingleMetaParser\n atoms metaCommandAtom\n javascript\n isTopMatter = true\n isSetterParser = true\n buildHtmlForPrint() {\n // hacky. todo: cleanup\n const originalContent = this.content\n this.setContent(`by ${originalContent}`)\n const html = super.buildHtml()\n this.setContent(originalContent)\n return html\n }\n buildTxtForPrint() {\n return 'by ' + super.buildTxt()\n }\n buildHtml() {\n return \"\"\n }\n buildTxt() {\n return \"\"\n }\n defaultClassName = \"printAuthorsParser\"\nblinkParser\n description Just for fun.\n extends scrollParagraphParser\n example\n blink Carpe diem!\n cue blink\n javascript\n buildHtml() {\n return `<span class=\"scrollBlink\">${super.buildHtml()}</span>\n <script>setInterval(()=>{ Array.from(document.getElementsByClassName(\"scrollBlink\")).forEach(el => el.style.visibility = el.style.visibility === \"hidden\" ? \"visible\" : \"hidden\") }, 500)</script>`\n }\nscrollButtonParser\n extends scrollParagraphParser\n cueFromId\n description A button.\n postParser\n description Post a particle.\n example\n scrollButton Click me\n javascript\n defaultClassName = \"scrollButton\"\n tag = \"button\"\n get htmlAttributes() {\n const link = this.getFromParser(\"scrollLinkParser\")\n const post = this.getParticle(\"post\")\n if (post) {\n const method = \"post\"\n const action = link?.link || \"\"\n const formData = new URLSearchParams({particle: post.subparticlesToString()}).toString()\n return ` onclick=\"fetch('${action}', {method: '${method}', body: '${formData}', headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).then(async (message) => {const el = document.createElement('div'); el.textContent = await message.text(); this.insertAdjacentElement('afterend', el);}); return false;\" `\n }\n return super.htmlAttributes + (link ? `onclick=\"window.location='${link.link}'\"` : \"\")\n }\n getFromParser(parserId) {\n return this.find(particle => particle.doesExtend(parserId))\n }\ncatchAllParagraphParser\n popularity 0.115562\n description A paragraph.\n extends scrollParagraphParser\n boolean suggestInAutocomplete false\n boolean isPopular true\n boolean isArticleContent true\n atoms stringAtom\n javascript\n getErrors() {\n const errors = super.getErrors() || []\n return this.parent.has(\"testStrict\") ? errors.concat(this.makeError(`catchAllParagraphParser should not have any matches when testing with testStrict.`)) : errors\n }\n get originalText() {\n return this.getLine() || \"\"\n }\nscrollCenterParser\n popularity 0.006415\n cue center\n description A centered section.\n extends scrollParagraphParser\n example\n center\n This paragraph is centered.\n javascript\n buildHtml() {\n this.parent.sectionStack.push(\"</center>\")\n return `<center>${super.buildHtml()}`\n }\n buildTxt() {\n return this.content\n }\nabstractIndentableParagraphParser\n extends scrollParagraphParser\n inScope abstractAftertextDirectiveParser abstractAftertextAttributeParser abstractIndentableParagraphParser scrollParagraphParser\n javascript\n get htmlContents() {\n return this.text + this.map(particle => particle.buildHtml())\n .join(\"\\n\")\n .trim()\n }\n buildTxt() {\n return this.getAtom(0) + \" \" + super.buildTxt()\n }\nchecklistTodoParser\n popularity 0.000193\n extends abstractIndentableParagraphParser\n example\n [] Get milk\n description A task todo.\n cue []\n string checked \n javascript\n get text() {\n return `<div style=\"text-indent:${(this.getIndentLevel() - 1) * 20}px;\"><input type=\"checkbox\" ${this.checked} id=\"${this.id}\"><label for=\"${this.id}\">` + super.text + `</label></div>`\n }\n get id() {\n return this.get(\"id\") || \"item\" + this._getUid()\n }\nchecklistDoneParser\n popularity 0.000072\n extends checklistTodoParser\n description A completed task.\n string checked checked\n cue [x]\n example\n [x] get milk\nscrollDivParser\n popularity 0.007524\n description HTML div tag.\n extends abstractIndentableParagraphParser\n cue div\n example\n div\n # Hello world\n p This is a test\n div\n # Deeper\n javascript\n tag = \"div\"\nabstractHtmlElementParser\n extends abstractIndentableParagraphParser\n javascript\n defaultClassName = \"\"\nhtmlSectionParser\n description HTML section tag.\n extends abstractHtmlElementParser\n cue section\n example\n section\n # Hello world\n p This is a test\n section\n # Deeper\n javascript\n tag = \"section\"\nhtmlHeaderParser\n description HTML header tag.\n extends abstractHtmlElementParser\n cue header\n example\n header\n # Title\n javascript\n tag = \"header\"\nhtmlFooterParser\n description HTML footer tag.\n extends abstractHtmlElementParser\n cue footer\n example\n footer\n p Made with love\n javascript\n tag = \"footer\"\nhtmlAsideParser\n description HTML aside tag.\n extends abstractHtmlElementParser\n cue aside\n example\n aside\n h1 Some notes\n javascript\n tag = \"aside\"\nhtmlArticleParser\n description HTML article tag.\n extends abstractHtmlElementParser\n cue article\n example\n article\n h1 My article\n javascript\n tag = \"article\"\nhtmlMainParser\n description HTML main tag.\n extends abstractHtmlElementParser\n cue main\n example\n main\n # Title\n javascript\n tag = \"main\"\nhtmlNavParser\n description HTML nav tag.\n extends abstractHtmlElementParser\n cue nav\n example\n nav\n a Home\n href /\n javascript\n tag = \"nav\"\nhtmlPreParser\n description HTML pre tag.\n extends abstractHtmlElementParser\n cue pre\n example\n pre\n javascript\n tag = \"pre\"\nhtmlUlParser\n description HTML ul tag.\n extends abstractHtmlElementParser\n cue ul\n example\n ul\n li A list\n javascript\n tag = \"ul\"\nhtmlOlParser\n description HTML ol tag.\n extends abstractHtmlElementParser\n cue ol\n example\n ol\n li A list\n javascript\n tag = \"ol\"\nhtmlLiParser\n description HTML li tag.\n extends abstractHtmlElementParser\n cue li\n example\n ol\n li A list\n javascript\n tag = \"li\"\nhtmlImgParser\n description HTML img tag.\n extends abstractHtmlElementParser\n cue img\n example\n img foo.png\n javascript\n tag = \"img\"\n isSelfClosing = true\nhtmlAParser\n description HTML a tag.\n extends abstractHtmlElementParser\n cue a\n example\n a Home\n href /\n javascript\n tag = \"a\"\nhtmlFormParser\n description HTML form tag.\n extends abstractHtmlElementParser\n cue form\n example\n form\n input\n javascript\n tag = \"form\"\nhtmlInputParser\n description HTML input tag.\n extends abstractHtmlElementParser\n cue input\n example\n input\n type text\n placeholder Enter your name\n javascript\n tag = \"input\"\n isSelfClosing = true\nhtmlSelectParser\n description HTML select tag.\n extends abstractHtmlElementParser\n cue select\n example\n select\n option Value 1\n option Value 2\n javascript\n tag = \"select\"\nhtmlOptionParser\n description HTML option tag.\n extends abstractHtmlElementParser\n cue option\n example\n select\n option Choose an option\n option First Option\n javascript\n tag = \"option\"\nhtmlTextareaParser\n description HTML textarea tag.\n extends abstractHtmlElementParser\n cue textarea\n example\n textarea\n placeholder Enter your message\n rows 4\n javascript\n tag = \"textarea\"\nhtmlButtonParser\n description HTML button tag.\n extends abstractHtmlElementParser\n cue button\n example\n button Submit\n type submit\n javascript\n tag = \"button\"\nhtmlLabelParser\n description HTML label tag.\n extends abstractHtmlElementParser\n cue label\n example\n label Name\n for username\n javascript\n tag = \"label\"\nhtmlSpanParser\n description HTML span tag.\n extends abstractHtmlElementParser\n cue span\n example\n span Hello\n javascript\n tag = \"span\"\nhtmlCanvasParser\n description HTML canvas tag.\n extends abstractHtmlElementParser\n cue canvas\n example\n canvas\n javascript\n tag = \"canvas\"\nhtmlIframeParser\n description HTML iframe tag.\n extends abstractHtmlElementParser\n cue iframe\n example\n iframe\n javascript\n tag = \"iframe\"\nh1LiteralParser\n description HTML h1 tag.\n extends abstractHtmlElementParser\n cue h1\n example\n main\n h1 Title\n javascript\n tag = \"h1\"\nh2LiteralParser\n description HTML h2 tag.\n extends abstractHtmlElementParser\n cue h2\n example\n main\n h2 Title\n javascript\n tag = \"h2\"\nh3LiteralParser\n description HTML h3 tag.\n extends abstractHtmlElementParser\n cue h3\n example\n main\n h3 Title\n javascript\n tag = \"h3\"\nh4LiteralParser\n description HTML h4 tag.\n extends abstractHtmlElementParser\n cue h4\n example\n main\n h4 Title\n javascript\n tag = \"h4\"\nhtmlMetaTagParser\n description HTML meta tag.\n extends abstractHtmlElementParser\n cue meta\n example\n meta\n name description\n content A great page about meta tags\n javascript\n tag = \"meta\"\n isSelfClosing = true\nlistAftertextParser\n popularity 0.014325\n extends abstractIndentableParagraphParser\n example\n - I had a _new_ thought.\n description A list item.\n cue -\n javascript\n defaultClassName = \"\"\n buildHtml() {\n const {index, parent} = this\n const particleClass = this.constructor\n const isStartOfList = index === 0 || !(parent.particleAt(index - 1) instanceof particleClass)\n const isEndOfList = parent.length === index + 1 || !(parent.particleAt(index + 1) instanceof particleClass)\n const { listType } = this\n return (isStartOfList ? `<${listType} ${this.attributes}>` : \"\") + `${super.buildHtml()}` + (isEndOfList ? `</${listType}>` : \"\")\n }\n get attributes() {\n return \"\"\n }\n tag = \"li\"\n listType = \"ul\"\nabstractCustomListItemParser\n extends listAftertextParser\n javascript\n get requireOnce() {\n return `<style>\\n.${this.constructor.name} li::marker {content: \"${this.cue} \";}\\n</style>`\n }\n get attributes() {\n return `class=\"${this.constructor.name}\"`\n }\norderedListAftertextParser\n popularity 0.004485\n extends listAftertextParser\n description A list item.\n example\n 1. Hello world\n pattern ^\\d+\\. \n javascript\n listType = \"ol\"\n get attributes() { return ` start=\"${this.getAtom(0)}\"`}\npParagraphParser\n popularity 0.001881\n cue p\n extends abstractIndentableParagraphParser\n description A paragraph.\n boolean isArticleContent true\n example\n p I had a _new_ idea.\nquickQuoteParser\n popularity 0.000482\n cue >\n example\n > The only thing we have to fear is fear itself. - FDR\n boolean isPopular true\n extends abstractIndentableParagraphParser\n description A quote.\n javascript\n defaultClassName = \"scrollQuote\"\n tag = \"blockquote\"\nscrollCounterParser\n description Visualize the speed of something.\n extends scrollParagraphParser\n cue counter\n example\n counter 4.5 Babies Born\n atoms cueAtom numberAtom\n javascript\n buildHtml() {\n const line = this.getLine()\n const atoms = line.split(\" \")\n atoms.shift() // drop the counter atom\n const perSecond = parseFloat(atoms.shift()) // get number\n const increment = perSecond/10\n const id = this._getUid()\n this.setLine(`* <span id=\"counter${id}\" title=\"0\">0</span><script>setInterval(()=>{ const el = document.getElementById('counter${id}'); el.title = parseFloat(el.title) + ${increment}; el.textContent = Math.floor(parseFloat(el.title)).toLocaleString()}, 100)</script> ` + atoms.join(\" \"))\n const html = super.buildHtml()\n this.setLine(line)\n return html\n }\nexpanderParser\n popularity 0.000072\n cueFromId\n description An collapsible HTML details tag.\n extends scrollParagraphParser\n example\n expander Knock Knock\n Who's there?\n javascript\n buildHtml() {\n this.parent.sectionStack.push(\"</details>\")\n return `<details>${super.buildHtml()}`\n }\n buildTxt() {\n return this.content\n }\n tag = \"summary\"\n defaultClassName = \"\"\nfootnoteDefinitionParser\n popularity 0.001953\n description A footnote. Can also be used as section notes.\n extends scrollParagraphParser\n boolean isFootnote true\n pattern ^\\^.+$\n // We need to quickLinks back in scope because there is currently a bug in ScrollSDK/parsers where if a parser extending a parent class has a child parser defined, then any regex parsers in the parent class will not be tested unless explicitly included in scope again.\n inScope quickLinkParser\n labelParser\n description If you want to show a custom label for a footnote. Default label is the note definition index.\n cueFromId\n atoms cueAtom\n catchAllAtomType stringAtom\n javascript\n get htmlId() {\n return `note${this.noteDefinitionIndex}`\n }\n get label() {\n // In the future we could allow common practices like author name\n return this.get(\"label\") || `[${this.noteDefinitionIndex}]`\n }\n get linkBack() {\n return `noteUsage${this.noteDefinitionIndex}`\n }\n get text() {\n return `<a class=\"scrollFootNoteUsageLink\" href=\"#noteUsage${this.noteDefinitionIndex}\">${this.label}</a> ${super.text}`\n }\n get noteDefinitionIndex() {\n return this.parent.footnotes.indexOf(this) + 1\n }\n buildTxt() {\n return this.getAtom(0) + \": \" + super.buildTxt()\n }\nabstractHeaderParser\n extends scrollParagraphParser\n example\n # Hello world\n javascript\n buildHtml(buildSettings) {\n if (this.isHidden) return \"\"\n if (this.parent.sectionStack)\n this.parent.sectionStack.push(\"</div>\")\n return `<div class=\"scrollSection\">` + super.buildHtml(buildSettings)\n }\n buildTxt() {\n const line = super.buildTxt()\n return line + \"\\n\" + \"=\".repeat(line.length)\n }\n isHeader = true\nh1Parser\n popularity 0.017918\n description An html h1 tag.\n extends abstractHeaderParser\n example\n # Hello world\n boolean isArticleContent true\n cue #\n boolean isPopular true\n javascript\n tag = \"h1\"\nh2Parser\n popularity 0.005257\n description An html h2 tag.\n extends abstractHeaderParser\n example\n ## Hello world\n boolean isArticleContent true\n cue ##\n boolean isPopular true\n javascript\n tag = \"h2\"\nh3Parser\n popularity 0.001085\n description An html h3 tag.\n extends abstractHeaderParser\n example\n ### Hello world\n boolean isArticleContent true\n cue ###\n javascript\n tag = \"h3\"\nh4Parser\n popularity 0.000289\n description An html h4 tag.\n example\n #### Hello world\n extends abstractHeaderParser\n cue ####\n javascript\n tag = \"h4\"\nscrollQuestionParser\n popularity 0.004244\n description A question.\n extends h4Parser\n cue ?\n example\n ? Why is the sky blue?\n javascript\n defaultClassName = \"scrollQuestion\"\nh5Parser\n description An html h5 tag.\n extends abstractHeaderParser\n example\n ##### Hello world\n cue #####\n javascript\n tag = \"h5\"\nprintTitleParser\n popularity 0.007572\n description Print title.\n extends abstractHeaderParser\n boolean isPopular true\n example\n title Eureka\n printTitle\n cueFromId\n javascript\n buildHtml(buildSettings) {\n // Hacky, I know.\n const {content} = this\n if (content === undefined)\n this.setContent(this.root.title)\n const { permalink } = this.root\n if (!permalink) {\n this.setContent(content) // Restore it as it was.\n return super.buildHtml(buildSettings)\n }\n const newLine = this.appendLine(`link ${permalink}`)\n const compiled = super.buildHtml(buildSettings)\n newLine.destroy()\n this.setContent(content) // Restore it as it was.\n return compiled\n }\n get originalText() {\n return this.content ?? this.root.title ?? \"\"\n }\n defaultClassName = \"printTitleParser\"\n tag = \"h1\"\ncaptionAftertextParser\n popularity 0.003207\n description An image caption.\n cue caption\n example\n map.png\n caption A map.\n extends scrollParagraphParser\n boolean isPopular true\nabstractMediaParser\n extends scrollParagraphParser\n inScope scrollMediaLoopParser scrollAutoplayParser\n int atomIndex 1\n javascript\n buildTxt() {\n return \"\"\n }\n get filename() {\n return this.getAtom(this.atomIndex)\n }\n getAsHtmlAttribute(attr) {\n if (!this.has(attr)) return \"\"\n const value = this.get(attr)\n return value ? `${attr}=\"${value}\"` : attr\n }\n getAsHtmlAttributes(list) {\n return list.map(atom => this.getAsHtmlAttribute(atom)).filter(i => i).join(\" \")\n }\n buildHtml() {\n return `<${this.tag} src=\"${this.filename}\" controls ${this.getAsHtmlAttributes(\"width height loop autoplay\".split(\" \"))}></${this.tag}>`\n }\nscrollMusicParser\n popularity 0.000024\n extends abstractMediaParser\n cue music\n description Play sound files.\n example\n music sipOfCoffee.m4a\n javascript\n buildHtml() {\n return `<audio controls ${this.getAsHtmlAttributes(\"loop autoplay\".split(\" \"))}><source src=\"${this.filename}\" type=\"audio/mpeg\"></audio>`\n }\nquickSoundParser\n popularity 0.000024\n extends scrollMusicParser\n atoms urlAtom\n pattern ^[^\\s]+\\.(mp3|wav|ogg|aac|m4a|flac)\n int atomIndex 0\n example\n sipOfCoffee.m4a\nscrollVideoParser\n popularity 0.000024\n extends abstractMediaParser\n cue video\n example\n video spirit.mp4\n description Play video files.\n widthParser\n cueFromId\n atoms cueAtom integerAtom\n heightParser\n cueFromId\n atoms cueAtom integerAtom\n javascript\n tag = \"video\"\nquickVideoParser\n popularity 0.000024\n extends scrollVideoParser\n example\n spirit.mp4\n atoms urlAtom\n pattern ^[^\\s]+\\.(mp4|webm|avi|mov)\n int atomIndex 0\nquickParagraphParser\n popularity 0.001881\n cue *\n extends scrollParagraphParser\n description A paragraph.\n boolean isArticleContent true\n example\n * I had a _new_ idea.\nscrollStopwatchParser\n description A stopwatch.\n extends scrollParagraphParser\n cue stopwatch\n example\n stopwatch\n atoms cueAtom\n catchAllAtomType numberAtom\n javascript\n buildHtml() {\n const line = this.getLine()\n const id = this._getUid()\n this.setLine(`* <span class=\"scrollStopwatchParser\" id=\"stopwatch${id}\">0.0</span><script>{let startTime = parseFloat(new URLSearchParams(window.location.search).get('start') || 0); document.getElementById('stopwatch${id}').title = startTime; setInterval(()=>{ const el = document.getElementById('stopwatch${id}'); el.title = parseFloat(el.title) + .1; el.textContent = (parseFloat(el.title)).toFixed(1)}, 100)}</script> `)\n const html = super.buildHtml()\n this.setLine(line)\n return html\n }\nthinColumnsParser\n popularity 0.003690\n extends abstractAftertextParser\n cueFromId\n catchAllAtomType integerAtom\n description Thin columns.\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n columnWidth = 35\n columnGap = 20\n buildHtml() {\n const {columnWidth, columnGap, maxColumns} = this\n const maxTotalWidth = maxColumns * columnWidth + (maxColumns - 1) * columnGap\n const stackContents = this.parent.clearSectionStack() // Starting columns always first clears the section stack.\n if (this.singleColumn) this.parent.sectionStack.push(\"</div>\") // Single columns are self-closing after section break.\n return stackContents + `<div class=\"scrollColumns\" style=\"column-width:${columnWidth}ch;column-count:${maxColumns};max-width:${maxTotalWidth}ch;\">`\n }\n get maxColumns() {\n return this.singleColumn ? 1 : parseInt(this.getAtom(1) ?? 10)\n }\nwideColumnsParser\n popularity 0.000386\n extends thinColumnsParser\n description Wide columns.\n javascript\n columnWidth = 90\nwideColumnParser\n popularity 0.003376\n extends wideColumnsParser\n description A wide column section.\n boolean singleColumn true\nmediumColumnsParser\n popularity 0.003376\n extends thinColumnsParser\n description Medium width columns.\n javascript\n columnWidth = 65\nmediumColumnParser\n popularity 0.003376\n extends mediumColumnsParser\n description A medium column section.\n boolean singleColumn true\nthinColumnParser\n popularity 0.003376\n extends thinColumnsParser\n description A thin column section.\n boolean singleColumn true\nendColumnsParser\n popularity 0.007789\n extends abstractAftertextParser\n cueFromId\n description End columns.\n javascript\n buildHtml() {\n return \"</div>\"\n }\n buildHtmlSnippet() {\n return \"\"\n }\nscrollContainerParser\n popularity 0.000096\n cue container\n description A centered HTML div.\n example\n container 600px\n catchAllAtomType cssLengthAtom\n extends abstractAftertextParser\n boolean isHtml true\n javascript\n get maxWidth() {\n return this.atoms[1] || \"1200px\"\n }\n buildHtmlSnippet() {\n return \"\"\n }\n tag = \"div\"\n defaultClassName = \"scrollContainerParser\"\n buildHtml() {\n this.parent.bodyStack.push(\"</div>\")\n return `<style>.scrollContainerParser{width: 100%; box-sizing: border-box; max-width: ${this.maxWidth}; margin: 0 auto;}</style>` + super.buildHtml()\n }\n get text() { return \"\"}\n get closingTag() { return \"\"}\ndebugSourceStackParser\n // useful for debugging\n description Print compilation steps.\n extends abstractAftertextParser\n cueFromId\n example\n printOriginalSource\n javascript\n get sources() {\n const {file} = this.root\n const passNames = [\"codeAtStart\", \"fusedCode\", \"codeAfterMacroPass\"]\n let lastCode = \"\"\n return passNames.map(name => {\n let code = file[name]\n if (lastCode === code)\n code = \"[Unchanged]\"\n lastCode = file[name]\n return {\n name,\n code\n }})\n }\n buildHtml() {\n return `<code class=\"scrollCodeBlock\">${this.buildTxt().replace(/\\</g, \"&lt;\")}</code>`\n }\n buildTxt() {\n return this.sources.map((pass, index) => `Pass ${index + 1} - ${pass.name}\\n========\\n${pass.code}`).join(\"\\n\\n\\n\")\n }\nabstractDinkusParser\n extends abstractAftertextParser\n boolean isDinkus true\n javascript\n buildHtml() {\n return `<div class=\"${this.defaultClass}\"><span>${this.dinkus}</span></div>`\n }\n defaultClass = \"abstractDinkusParser\"\n buildTxt() {\n return this.dinkus\n }\n get dinkus() {\n return this.content || this.getLine()\n }\nhorizontalRuleParser\n popularity 0.000362\n cue ---\n description A horizontal rule.\n extends abstractDinkusParser\n example\n ---\n javascript\n buildHtml() {\n return `<hr>`\n }\nscrollDinkusParser\n popularity 0.010828\n cue ***\n description A dinkus. Breaks section.\n boolean isPopular true\n example\n ***\n extends abstractDinkusParser\n javascript\n dinkus = \"*\"\ncustomDinkusParser\n cue dinkus\n description A custom dinkus.\n extends abstractDinkusParser\nendOfPostDinkusParser\n popularity 0.005740\n extends abstractDinkusParser\n description End of post dinkus.\n boolean isPopular true\n cue ****\n example\n ****\n javascript\n dinkus = \"⁂\"\nabstractIconButtonParser\n extends abstractAftertextParser\n cueFromId\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n return `<style>.abstractIconButtonParser {position:absolute;top:0.25rem; }.abstractIconButtonParser svg {fill: rgba(204,204,204,.8);width:1.875rem;height:1.875rem; padding: 0 7px;} .abstractIconButtonParser:hover svg{fill: #333;}</style><a href=\"${this.link}\" class=\"doNotPrint abstractIconButtonParser\" style=\"${this.style}\">${this.svg}</a>`\n }\ndownloadButtonParser\n popularity 0.006294\n description Link to download/WWS page.\n extends abstractIconButtonParser\n catchAllAtomType urlAtom\n string style position:relative;\n string svg <svg fill=\"#000000\" xmlns=\"http://www.w3.org/2000/svg\" width=\"800px\" height=\"800px\" viewBox=\"0 0 52 52\" enable-background=\"new 0 0 52 52\" xml:space=\"preserve\"><path d=\"M38.6,20.4c-1-6.5-6.7-11.5-13.5-11.5c-7.6,0-13.7,6.1-13.7,13.7c0,0.3,0,0.7,0.1,1c-5,0.4-8.9,4.6-8.9,9.6 c0,5.4,4.3,9.7,9.7,9.7h11.5c-0.8-0.8-8.1-8.1-8.1-8.1c-0.4-0.4-0.4-0.9,0-1.3l1.3-1.3c0.4-0.4,0.9-0.4,1.3,0l3.5,3.5 c0.4,0.4,1.1,0.1,1.1-0.4V21.8c0-0.4,0.5-0.9,1-0.9h1.9c0.5,0,0.9,0.4,0.9,0.9v13.4c0,0.6,0.8,0.8,1.1,0.4l3.5-3.5 c0.4-0.4,0.9-0.4,1.3,0l1.3,1.3c0.4,0.4,0.4,0.9,0,1.3L26,42.9h12.3v0c6.1-0.1,11-5.1,11-11.3C49.4,25.5,44.6,20.6,38.6,20.4z\"/></svg><!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->\n javascript\n get link() {\n return this.content\n }\neditButtonParser\n popularity 0.013963\n description Print badge top right.\n extends abstractIconButtonParser\n catchAllAtomType urlAtom\n // SVG from https://github.com/32pixelsCo/zest-icons\n string svg <svg width=\"800px\" height=\"800px\" viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\"><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M21.1213 2.70705C19.9497 1.53548 18.0503 1.53547 16.8787 2.70705L15.1989 4.38685L7.29289 12.2928C7.16473 12.421 7.07382 12.5816 7.02986 12.7574L6.02986 16.7574C5.94466 17.0982 6.04451 17.4587 6.29289 17.707C6.54127 17.9554 6.90176 18.0553 7.24254 17.9701L11.2425 16.9701C11.4184 16.9261 11.5789 16.8352 11.7071 16.707L19.5556 8.85857L21.2929 7.12126C22.4645 5.94969 22.4645 4.05019 21.2929 2.87862L21.1213 2.70705ZM18.2929 4.12126C18.6834 3.73074 19.3166 3.73074 19.7071 4.12126L19.8787 4.29283C20.2692 4.68336 20.2692 5.31653 19.8787 5.70705L18.8622 6.72357L17.3068 5.10738L18.2929 4.12126ZM15.8923 6.52185L17.4477 8.13804L10.4888 15.097L8.37437 15.6256L8.90296 13.5112L15.8923 6.52185ZM4 7.99994C4 7.44766 4.44772 6.99994 5 6.99994H10C10.5523 6.99994 11 6.55223 11 5.99994C11 5.44766 10.5523 4.99994 10 4.99994H5C3.34315 4.99994 2 6.34309 2 7.99994V18.9999C2 20.6568 3.34315 21.9999 5 21.9999H16C17.6569 21.9999 19 20.6568 19 18.9999V13.9999C19 13.4477 18.5523 12.9999 18 12.9999C17.4477 12.9999 17 13.4477 17 13.9999V18.9999C17 19.5522 16.5523 19.9999 16 19.9999H5C4.44772 19.9999 4 19.5522 4 18.9999V7.99994Z\"/></svg>\n javascript\n get link() {\n return this.content || this.root.editUrl || \"\"\n }\n get style() {\n return this.parent.findParticles(\"editButton\")[0] === this ? \"right:2rem;\": \"position:relative;\"\n }\nemailButtonParser\n popularity 0.006294\n description Email button.\n extends abstractIconButtonParser\n catchAllAtomType emailAddressAtom\n // todo: should just be \"optionalAtomType\"\n string style position:relative;\n string svg <svg viewBox=\"3 5 24 20\" width=\"24\" height=\"20\" xmlns=\"http://www.w3.org/2000/svg\"><g transform=\"matrix(1, 0, 0, 1, 0, -289.0625)\"><path style=\"opacity:1;stroke:none;stroke-width:0.49999997;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1\" d=\"M 5 5 C 4.2955948 5 3.6803238 5.3628126 3.3242188 5.9101562 L 14.292969 16.878906 C 14.696939 17.282876 15.303061 17.282876 15.707031 16.878906 L 26.675781 5.9101562 C 26.319676 5.3628126 25.704405 5 25 5 L 5 5 z M 3 8.4140625 L 3 23 C 3 24.108 3.892 25 5 25 L 25 25 C 26.108 25 27 24.108 27 23 L 27 8.4140625 L 17.121094 18.292969 C 15.958108 19.455959 14.041892 19.455959 12.878906 18.292969 L 3 8.4140625 z \" transform=\"translate(0,289.0625)\" id=\"rect4592\"/></g></svg>\n javascript\n get link() {\n const email = this.content || this.parent.get(\"email\")\n return email ? `mailto:${email}` : \"\"\n }\nhomeButtonParser\n popularity 0.006391\n description Home button.\n extends abstractIconButtonParser\n catchAllAtomType urlAtom\n string style left:2rem;\n string svg <svg role=\"img\" viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M12.7166 3.79541C12.2835 3.49716 11.7165 3.49716 11.2834 3.79541L4.14336 8.7121C3.81027 8.94146 3.60747 9.31108 3.59247 9.70797C3.54064 11.0799 3.4857 13.4824 3.63658 15.1877C3.7504 16.4742 4.05336 18.1747 4.29944 19.4256C4.41371 20.0066 4.91937 20.4284 5.52037 20.4284H8.84433C8.98594 20.4284 9.10074 20.3111 9.10074 20.1665V15.9754C9.10074 14.9627 9.90433 14.1417 10.8956 14.1417H13.4091C14.4004 14.1417 15.204 14.9627 15.204 15.9754V20.1665C15.204 20.3111 15.3188 20.4284 15.4604 20.4284H18.4796C19.0806 20.4284 19.5863 20.0066 19.7006 19.4256C19.9466 18.1747 20.2496 16.4742 20.3634 15.1877C20.5143 13.4824 20.4594 11.0799 20.4075 9.70797C20.3925 9.31108 20.1897 8.94146 19.8566 8.7121L12.7166 3.79541ZM10.4235 2.49217C11.3764 1.83602 12.6236 1.83602 13.5765 2.49217L20.7165 7.40886C21.4457 7.91098 21.9104 8.73651 21.9448 9.64736C21.9966 11.0178 22.0564 13.5119 21.8956 15.3292C21.7738 16.7067 21.4561 18.4786 21.2089 19.7353C20.9461 21.0711 19.7924 22.0001 18.4796 22.0001H15.4604C14.4691 22.0001 13.6655 21.1791 13.6655 20.1665V15.9754C13.6655 15.8307 13.5507 15.7134 13.4091 15.7134H10.8956C10.754 15.7134 10.6392 15.8307 10.6392 15.9754V20.1665C10.6392 21.1791 9.83561 22.0001 8.84433 22.0001H5.52037C4.20761 22.0001 3.05389 21.0711 2.79113 19.7353C2.54392 18.4786 2.22624 16.7067 2.10437 15.3292C1.94358 13.5119 2.00338 11.0178 2.05515 9.64736C2.08957 8.73652 2.55427 7.91098 3.28346 7.40886L10.4235 2.49217Z\"/></svg>\n javascript\n get link() {\n return this.content || this.get(\"link\") || \"index.html\"\n }\ntheScrollButtonParser\n popularity 0.006294\n description WWS button.\n extends abstractIconButtonParser\n string style position:relative;\n string svg <svg xmlns=\"http://www.w3.org/2000/svg\" direction=\"ltr\" width=\"231.52568231268793\" height=\"249.33156169975996\" viewBox=\"297.27169239534896 1273.121785992385 231.52568231268793 249.33156169975996\" stroke-linecap=\"round\" stroke-linejoin=\"round\" data-color-mode=\"dark\" class=\"tl-container tl-theme__force-sRGB tl-theme__dark\" ><defs/><g transform=\"matrix(1, 0, 0, 1, 395.9682, 1413.3618)\" opacity=\"1\"><g transform=\"scale(1)\"><path d=\"M-5.7342,-1.1484 T-5.0182,-4.6536 -2.6672,-12.9768 1.7374,-22.3903 8.4597,-30.0892 16.5455,-35.2796 25.3478,-37.8247 34.4641,-37.2199 43.0676,-33.4606 50.27,-27.1118 55.7861,-19.7972 59.8042,-11.6764 61.6844,-2.3157 60.8049,7.9615 57.3259,17.5954 51.2605,25.5515 41.9451,31.9237 30.6489,36.2084 18.9812,37.6038 8.4915,36.637 -1.3063,34.5174 -10.6869,31.6604 -19.0463,27.0252 -26.0612,20.1562 -31.864,11.1271 -35.2772,1.0066 -35.7963,-9.1933 -35.203,-19.2337 -32.52,-28.3259 -27.3388,-37.4245 -20.2857,-45.7085 -11.787,-53.0395 -2.4314,-58.4864 7.1724,-61.8739 17.5002,-65.6025 28.2859,-68.1034 38.514,-69.1081 48.1844,-69.9134 57.9136,-70.1787 67.4056,-69.5971 76.297,-67.7446 84.5233,-63.97 92.0158,-57.5003 98.1976,-48.5614 102.8839,-38.056 105.9936,-27.6097 107.074,-18.168 107.175,-8.2882 106.6452,1.9768 105.4734,11.7698 104.0279,21.1013 101.7439,31.0445 98.0977,40.6386 92.7822,49.1039 86.2847,57.2337 78.6099,64.7113 69.8339,70.974 61.2863,75.092 52.4283,78.2186 42.5338,80.7945 32.7733,82.6629 22.8568,83.6574 12.2803,83.3538 2.4971,81.4828 -6.3367,78.789 -15.1061,75.8011 -24.259,72.3779 -33.2286,68.991 -41.5707,64.8363 -49.153,59.1909 -55.8375,52.2938 -62.9311,43.9553 -68.4604,34.4882 -71.2761,23.5855 -72.748,12.7452 -73.7673,2.0453 -74.1187,-8.7386 -72.293,-19.3856 -68.7376,-30.4053 -64.12,-39.7852 -59.1825,-47.8931 -53.7695,-56.4512 -48.1998,-65.7676 -43.1389,-74.401 -36.9006,-81.0179 -28.4317,-86.2639 -18.3342,-90.3521 -8.9259,-93.9355 0.1927,-98.7179 9.3551,-103.3537 18.7651,-106.7552 29.7482,-110.3584 40.9287,-113.446 50.87,-115.2231 57.8279,-116.0074 60.4065,-116.0632 A7.8326,7.8326 0 0 1 61.1735,-100.4168 T58.6018,-100.2201 51.1634,-99.3008 41.695,-96.884 32.4044,-94.0187 22.65,-91.382 13.4974,-87.3756 5.0519,-83.1026 -5.0443,-78.6175 -15.7236,-74.4743 -24.6193,-70.2681 -31.274,-62.5903 -36.3827,-53.9362 -41.2833,-46.2905 -46.0679,-38.5161 -50.639,-30.6576 -54.6876,-22.4063 -57.6038,-12.3346 -58.5104,-1.8678 -57.6022,9.4969 -56.0628,20.477 -53.6434,29.0487 -48.8908,36.7517 -42.4075,43.9784 -35.3064,50.6236 -27.3553,55.2062 -17.6884,59.4064 -7.6442,63.6638 2.4427,67.0449 12.7308,69.4843 22.9294,70.2171 33.2547,69.3921 42.4972,67.7384 52.2753,64.8425 61.8649,60.9142 69.5292,56.0828 76.3604,49.5927 82.431,42.3194 87.219,34.619 90.6076,25.5217 92.547,16.0352 93.8703,7.1315 94.4972,-2.5268 94.3672,-13.3681 93.3204,-24.4252 90.5377,-34.1656 85.7321,-43.6441 78.7334,-51.8057 68.7542,-56.0559 57.9857,-57.2713 48.079,-57.0198 38.4535,-56.3204 28.5246,-55.0036 18.6104,-52.4796 9.6402,-49.559 0.7193,-46.2981 -7.1531,-41.3715 -13.708,-34.8957 -19.5435,-26.853 -22.8356,-17.0622 -23.363,-6.5446 -21.9969,3.1439 -17.1086,11.9113 -9.276,18.744 -0.0685,22.6058 9.3636,24.796 19.2422,25.8817 29.052,25.0411 37.9338,21.3502 45.6819,13.8498 49.6675,4.5228 49.2802,-5.1854 45.3277,-14.4455 38.8603,-21.7879 30.5488,-25.7753 21.3356,-24.3975 13.6687,-19.2391 8.8217,-10.9919 6.423,-2.3609 5.7342,1.1484 A5.8481,5.8481 0 0 1 -5.7342,-1.1484 Z\" stroke-linecap=\"round\"/></g></g></svg>\n javascript\n get link() {\n return \"https://wws.scroll.pub\"\n }\nabstractTextLinkParser\n extends abstractAftertextParser\n cueFromId\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildTxt() {\n return this.text\n }\n buildHtml() {\n return `<div class=\"abstractTextLinkParser\"><a href=\"${this.link}\">${this.text}</a></div>`\n }\neditLinkParser\n popularity 0.001206\n extends abstractTextLinkParser\n description Print \"Edit\" link.\n string text Edit\n javascript\n get link() {\n return this.root.editUrl || \"\"\n }\nscrollVersionLinkParser\n popularity 0.006294\n extends abstractTextLinkParser\n string link https://scroll.pub\n description Print Scroll version.\n javascript\n get text() {\n return `Built with Scroll v${this.root.scrollVersion}`\n }\nclassicFormParser\n cue classicForm\n popularity 0.006391\n description Generate input form for ScrollSet.\n extends abstractAftertextParser\n atoms cueAtom\n catchAllAtomType stringAtom\n string script\n <script>\n sendFormViaEmail = form => {\n const mailto = new URL(\"mailto:\")\n const params = []\n const { value, title } = form.querySelector('button[type=\"submit\"]')\n params.push(`subject=${encodeURIComponent(value)}`)\n params.push(`to=${encodeURIComponent(title)}`)\n const oneTextarea = form.querySelector('textarea[title=\"oneTextarea\"]')\n const body = oneTextarea ? codeMirrorInstance.getValue() : Array.from(new FormData(form)).map(([name, value]) => `${name} ${value}`).join(\"\\\\n\")\n params.push(`body=${encodeURIComponent(body)}`)\n mailto.search = params.join(\"&\")\n window.open(mailto.href, '_blank')\n }\n </script>\n string style\n <style> .scrollFormParser {\n font-family: \"Gill Sans\", \"Bitstream Vera Sans\", sans-serif;\n }\n .scrollFormParser input , .scrollFormParser textarea{\n padding: 10px;\n margin-bottom: 10px;\n width: 100%;\n box-sizing: border-box;\n } .scrollFormParser label {\n display: block;\n margin-bottom: 5px;\n }\n </style>\n javascript\n get inputs() {\n return this.root.measures.filter(measure => !measure.IsComputed).map((measure, index) => {\n const {Name, Question, IsRequired, Type} = measure\n const type = Type || \"text\"\n const placeholder = Question\n const ucFirst = Name.substr(0, 1).toUpperCase() + Name.substr(1)\n // ${index ? \"\" : \"autofocus\"}\n let tag = \"\"\n if (Type === \"textarea\")\n tag = `<textarea placeholder=\"${placeholder}\" id=\"${Name}\" name=\"${Name}\" ${IsRequired ? \"required\" : \"\"}></textarea>`\n else\n tag = `<input placeholder=\"${placeholder}\" type=\"${type}\" id=\"${Name}\" name=\"${Name}\" ${IsRequired ? \"required\" : \"\"}>`\n return `<div><label for=\"${Name}\" title=\"${IsRequired ? \"Required\" : \"\"}\">${ucFirst}${IsRequired ? \"*\" : \"\"}:</label>${tag}</div>`\n }).join(\"\\n\")\n }\n buildHtml() {\n const {isEmail, formDestination, callToAction, subject} = this\n return `${this.script}${this.style}<form ${isEmail ? \"onsubmit='sendFormViaEmail(this); return false;'\" : ` method='post' action='${formDestination}'`} class=\"scrollFormParser\">${this.inputs}<button value=\"${subject}\" title=\"${formDestination}\" class=\"scrollButton\" type=\"submit\">${callToAction}</button>${this.footer}</form>`\n }\n get callToAction() {\n return (this.isEmail ? \"Submit via email\" : (this.subject || \"Post\"))\n }\n get isEmail() {\n return this.formDestination.includes(\"@\")\n }\n get formDestination() {\n return this.getAtom(1) || \"\"\n }\n get subject() {\n return this.getAtomsFrom(2)?.join(\" \") || \"\"\n }\n get footer() {\n return \"\"\n }\nscrollFormParser\n extends classicFormParser\n cue scrollForm\n placeholderParser\n atoms cueAtom\n baseParser blobParser\n cueFromId\n single\n valueParser\n atoms cueAtom\n baseParser blobParser\n cueFromId\n single\n nameParser\n description Name for the post submission.\n atoms cueAtom stringAtom\n cueFromId\n single\n description Generate a Scroll Form.\n string copyFromExternal .codeMirror.css .scrollLibs.js .constants.js\n string requireOnce\n <link rel=\"stylesheet\" href=\".codeMirror.css\">\n <script src=\".scrollLibs.js\"></script>\n <script src=\".constants.js\"></script>\n javascript\n get placeholder() {\n return this.getParticle(\"placeholder\")?.subparticlesToString() || \"\"\n }\n get value() {\n return this.getParticle(\"value\")?.subparticlesToString() || \"\"\n }\n get footer() {\n return \"\"\n }\n get name() {\n return this.get(\"name\") || \"particles\"\n }\n get parsersBundle() {\n const parserRegex = /^[a-zA-Z0-9_]+Parser$/gm\n const clone = this.root.clone()\n const parsers = clone.filter(line => parserRegex.test(line.getLine()))\n return \"\\n\" + parsers.map(particle => {\n particle.prependLine(\"boolean suggestInAutocomplete true\")\n return particle.toString()\n }).join(\"\\n\")\n }\n get inputs() {\n const Name = this.name\n return `<textarea title=\"oneTextarea\" rows=\"${Math.min(this.root.measures.length * 2, 30)}\" placeholder=\"${this.placeholder}\" id=\"${Name}\" name=\"${Name}\"></textarea>\n <script id=\"${Name}Parsers\" type=\"text/plain\">${this.parsersBundle}</script>\n <script>{\n const parserRegex = /^[a-zA-Z0-9_]+Parser$/gm\n let {width, height} = document.getElementById('${Name}').getBoundingClientRect();\n const sp = new Particle(AppConstants.parsers)\n sp.filter(particle => particle.getLine().match(parserRegex)).forEach(part => {\n part.appendLine(\"boolean suggestInAutocomplete false\")\n })\n const customScrollParser = new HandParsersProgram(sp.toString() + document.getElementById(\"${Name}Parsers\").textContent).compileAndReturnRootParser()\n codeMirrorInstance = new ParsersCodeMirrorMode(\"custom\", () => customScrollParser, undefined, CodeMirror).register().fromTextAreaWithAutocomplete(document.getElementById(\"${Name}\"), {\n lineWrapping: false,\n lineNumbers: false\n })\n codeMirrorInstance.setSize(width, height);\n codeMirrorInstance.setValue(\\`${this.value}\\`); }</script>`\n }\n buildHtml(buildSettings) {\n return this.getHtmlRequirements(buildSettings) + super.buildHtml()\n }\nloremIpsumParser\n extends abstractAftertextParser\n cueFromId\n description Generate dummy text.\n catchAllAtomType integerAtom\n string placeholder Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n javascript\n get originalText() {\n return this.placeholder.repeat(this.howMany)\n }\n get howMany() {\n return this.getAtom(1) ? parseInt(this.getAtom(1)) : 1\n }\nnickelbackIpsumParser\n extends loremIpsumParser\n string placeholder And one day, I’ll be at the door. And lose your wings to fall in love? To the bottom of every bottle. I’m on the ledge of the eighteenth story. Why must the blind always lead the blind?\nscrollModalParser\n description A modal dialog overlay.\n extends abstractAftertextParser\n boolean isHtml true\n cue modal\n string requireOnce\n <style>\n .scrollModal {\n display: none;\n position: fixed;\n background: transparent;\n padding: 20px;\n left: 3rem;\n top: 3rem;\n right: 3rem;\n bottom: 3rem;\n z-index: 1000;\n font-family: \"IBM Plex Mono\", monospace;\n /* Frosted glass effect */\n background: rgba(0, 0, 0, 0.2);\n backdrop-filter: blur(8px);\n -webkit-backdrop-filter: blur(8px);\n border: 1px solid rgba(255, 255, 255, 0.1);\n box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);\n border-radius: 8px;\n overflow: hidden;\n }\n .scrollModal .closeButton {\n position: absolute;\n top: 10px;\n right: 10px;\n width: 30px;\n height: 30px;\n border: none;\n background: rgba(255, 255, 255, 0.1);\n color: rgba(255, 255, 255, 0.8);\n border-radius: 4px;\n cursor: pointer;\n font-family: \"IBM Plex Mono\", monospace;\n font-size: 18px;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all 0.2s ease;\n }\n .scrollModal .closeButton:hover {\n background: rgba(255, 255, 255, 0.2);\n color: white;\n }\n </style>\n <script>{\n window.closeModal = modal => {\n modal.style.display = 'none';\n history.pushState(\"\", document.title, window.location.pathname + window.location.search);\n };\n window.openModal = (id, event) => {\n if (event) event.modalJustOpened = true;\n document.querySelector(\"#\" + id).style.display = 'block';\n };\n window.addEventListener('hashchange', () => {\n const modalId = location.hash.slice(1); window.openModal(modalId);\n });\n document.addEventListener('keydown', e => {\n if (e.key === 'Escape') \n document.querySelectorAll('.scrollModal').forEach(closeModal);\n });\n // Check hash on initial load\n document.addEventListener(\"DOMContentLoaded\", e => {\n if (location.hash) \n window.openModal(location.hash.slice(1));\n });\n // Close on outside click\n document.addEventListener('click', e => {\n if (e.modalJustOpened) return;\n const modals = document.querySelectorAll('.scrollModal');\n modals.forEach(modal => {\n if (modal.style.display === 'block' && !modal.contains(e.target)) {\n closeModal(modal);\n }\n });\n });\n }</script>\n javascript\n buildHtml(buildSettings) {\n this.parent.sectionStack.push(\"</div>\")\n return this.getHtmlRequirements(buildSettings) + `<div class=\"scrollModal\" id=\"${this.htmlId}\"><button class=\"closeButton\" onclick=\"closeModal(this.parentElement)\">×</button>`\n }\nprintSnippetsParser\n popularity 0.000338\n // todo: why are we extending AT here and not loops? Is it for class/id etc?\n extends abstractAftertextParser\n cueFromId\n atoms cueAtom\n catchAllAtomType tagWithOptionalFolderAtom\n description Prints snippets matching tag(s).\n example\n printSnippets index\n javascript\n makeSnippet(scrollProgram, buildSettings) {\n const {endSnippetIndex} = scrollProgram\n if (endSnippetIndex === -1) return scrollProgram.buildHtmlSnippet(buildSettings) + scrollProgram.editHtml\n const linkRelativeToCompileTarget = buildSettings.relativePath + scrollProgram.permalink\n const joinChar = \"\\n\"\n const html = scrollProgram\n .map((subparticle, index) => (index >= endSnippetIndex ? \"\" : subparticle.buildHtmlSnippet ? subparticle.buildHtmlSnippet(buildSettings) : subparticle.buildHtml(buildSettings)))\n .filter(i => i)\n .join(joinChar)\n .trim() +\n `<a class=\"scrollContinueReadingLink\" href=\"${linkRelativeToCompileTarget}\">Continue reading...</a>`\n return html\n }\n get files() {\n const thisFile = this.parent.file\n const files = this.root.getFilesByTags(this.content, this.has(\"limit\") ? parseInt(this.get(\"limit\")) : undefined).filter(file => file.file !== thisFile)\n // allow sortBy lastCommit Time\n if (this.get(\"sortBy\") === \"commitTime\") {\n return this.root.sortBy(files, file => file.scrollProgram.lastCommitTime).reverse()\n }\n return files\n }\n buildHtml() {\n const alreadyRequired = this.root.alreadyRequired\n const snippets = this.files.map(file => {\n const buildSettings = {relativePath: file.relativePath, alreadyRequired }\n return `<div class=\"scrollSnippetContainer\">${this.makeSnippet(file.file.scrollProgram, buildSettings)}</div>`\n }).join(\"\\n\\n\")\n return `<div class=\"scrollColumns\" style=\"column-width:35ch;\">${snippets}</div>`\n }\n buildTxt() {\n return this.files.map(file => {\n const {scrollProgram} = file.file\n const {title, date, absoluteLink} = scrollProgram\n const ruler = \"=\".repeat(title.length)\n // Note: I tried to print the description here but the description generating code needs work.\n return `${title}\\n${ruler}\\n${date}\\n${absoluteLink}`\n }).join(\"\\n\\n\")\n }\nscrollNavParser\n popularity 0.000048\n extends printSnippetsParser\n cue fileNav\n description Titles and links in group(s).\n joinParser\n boolean allowTrailingWhitespace true\n cueFromId\n atoms cueAtom\n catchAllAtomType stringAtom\n javascript\n buildHtml() {\n return `<nav class=\"scrollNavParser\">` + this.root.getFilesByTags(this.content).map(file => {\n const { linkTitle, permalink } = file.file.scrollProgram\n return `<a href=\"${permalink}\">${linkTitle}</a>` \n }).join(this.get(\"join\") || \" \") + `</nav>`\n }\nprintFullSnippetsParser\n popularity 0.000048\n extends printSnippetsParser\n cueFromId\n description Print full pages in group(s).\n javascript\n makeSnippet(scrollProgram, buildSettings) {\n return scrollProgram.buildHtmlSnippet(buildSettings) + scrollProgram.editHtml\n }\nprintShortSnippetsParser\n popularity 0.000048\n extends printSnippetsParser\n cueFromId\n description Titles and descriptions in group(s).\n javascript\n makeSnippet(scrollProgram, buildSettings) {\n const { title, permalink, description, timestamp } = scrollProgram\n return `<div><a href=\"${permalink}\">${title}</a><div>${description}...</div><div class=\"subdued\" style=\"text-align:right;\">${this.root.dayjs(timestamp * 1000).format(`MMMM D, YYYY`)}</div></div>`\n }\nprintRelatedParser\n popularity 0.001182\n description Print links to related posts.\n extends printSnippetsParser\n cueFromId\n javascript\n buildHtml() {\n const alreadyRequired = this.root.alreadyRequired\n const list = this.files.map(fileWrapper => {\n const {relativePath, file} = fileWrapper\n const {title, permalink, year} = file.scrollProgram\n return `- ${title}${year ? \" (\" + year + \")\" : \"\"}\\n link ${relativePath + permalink}`\n }).join(\"\\n\")\n const items = this.parent.concat(list)\n const html = items.map(item => item.buildHtml()).join(\"\\n\")\n items.forEach(item => item.destroy())\n return html\n }\nscrollNoticesParser\n extends abstractAftertextParser\n description Display messages in URL query parameters.\n cue notices\n javascript\n buildHtml() {\n const id = this.htmlId\n return `<div id=\"${id}\" class=\"scrollNoticesParser\" style=\"display:none;\"></div><script>(function(){\n const params = new URLSearchParams(window.location.search)\n if (!params.size) return\n document.getElementById('${id}').innerHTML = Array.from(params.entries()).map(([key, value]) => {\n if (key === \"error\") \n return '<div style=\"color:red\">Error: ' + value + '</div>'\n if (key === \"success\")\n return '<div style=\"color:green\">Success: ' + value + '</div>'\n return '<div>' + key + ': ' + value + '</div>'\n }).join(\"\") || \"No query parameters found\"\n document.getElementById('${id}').style.display = \"block\"\n })()</script>`\n }\nabstractAssertionParser\n description Test above particle's output.\n extends abstractScrollParser\n string bindTo previous\n catchAllAtomType codeAtom\n cueFromId\n javascript\n buildHtml() {\n return ``\n }\n get particleToTest() {\n // If the previous particle is also an assertion particle, use the one before that.\n return this.previous.particleToTest ? this.previous.particleToTest : this.previous\n }\n get actual() {return this.particleToTest.buildHtml()}\n getErrors() {\n const {actual, expected} = this\n const errors = super.getErrors()\n if (this.areEqual(actual, expected))\n return errors\n return errors.concat(this.makeError(`'${actual}' did not ${this.kind} '${expected}'`))\n }\n get expected() {\n return this.length ? this.subparticlesToString() : (this.content ? this.content : \"\")\n }\n catchAllParser htmlLineParser\nassertHtmlEqualsParser\n extends abstractAssertionParser\n string kind equal\n example\n <b></b>\n assertHtmlEquals <b></b>\n javascript\n areEqual(actual, expected) {\n return actual === expected\n }\n // todo: why are we having to super here?\n getErrors() { return super.getErrors()}\nassertBuildIncludesParser\n extends abstractAssertionParser\n string kind include\n example\n buildCsv\n assertBuildIncludes virginica\n javascript\n areEqual(actual, expected) {\n return actual.includes(expected)\n }\n get actual() { return this.particleToTest.buildOutput()}\n getErrors() { return super.getErrors()}\nassertHtmlIncludesParser\n extends abstractAssertionParser\n string kind include\n javascript\n areEqual(actual, expected) {\n return actual.includes(expected)\n }\n getErrors() { return super.getErrors()}\nassertHtmlExcludesParser\n extends abstractAssertionParser\n string kind exclude\n javascript\n areEqual(actual, expected) {\n return !actual.includes(expected)\n }\n getErrors() { return super.getErrors()}\nassertIgnoreBelowErrorsParser\n description If you want to ignore any errors in the below particle in automated tests.\n extends abstractScrollParser\n string bindTo next\n cueFromId\nabstractPrintMetaParser\n extends abstractScrollParser\n cueFromId\nprintAuthorsParser\n popularity 0.001664\n description Prints author(s) byline.\n boolean isPopular true\n extends abstractPrintMetaParser\n // todo: we need pattern matching added to sdk to support having no params or a url and personNameAtom\n catchAllAtomType stringAtom\n example\n authors Breck Yunits\n https://breckyunits.com\n printAuthors\n javascript\n buildHtml() {\n return this.parent.getParticle(\"authors\")?.buildHtmlForPrint()\n }\n buildTxt() {\n return this.parent.getParticle(\"authors\")?.buildTxtForPrint()\n }\nprintDateParser\n popularity 0.000434\n extends abstractPrintMetaParser\n // If not present computes the date from the file's ctime.\n description Print published date.\n boolean isPopular true\n example\n date 1/11/2019\n printDate\n javascript\n buildHtml() {\n return `<div class=\"printDateParser\">${this.day}</div>`\n }\n get day() {\n let day = this.content || this.root.date\n if (!day) return \"\"\n return this.root.dayjs(day).format(`MMMM D, YYYY`)\n }\n buildTxt() {\n return this.day\n }\nprintFormatLinksParser\n description Prints links to other formats.\n extends abstractPrintMetaParser\n example\n printFormatLinks\n javascript\n buildHtml() {\n const permalink = this.root.permalink.replace(\".html\", \"\")\n // hacky\n const particle = this.appendSibling(`HTML | TXT`, `class printDateParser\\nlink ${permalink}.html HTML\\nlink ${permalink}.txt TXT\\nstyle text-align:center;`)\n const html = particle.buildHtml()\n particle.destroy()\n return html\n }\n buildTxt() {\n const permalink = this.root.permalink.replace(\".html\", \"\")\n return `HTML | TXT\\n link ${permalink}.html HTML\\n link ${permalink}.txt TXT`\n }\nabstractBuildCommandParser\n extends abstractScrollParser\n cueFromId\n atoms buildCommandAtom\n catchAllAtomType filePathAtom\n inScope slashCommentParser\n javascript\n isTopMatter = true\n buildHtml() {\n return \"\"\n }\n get extension() {\n return this.cue.replace(\"build\", \"\")\n }\n buildOutput() {\n return this.root.compileTo(this.extension)\n }\n get outputFileNames() {\n return this.content?.split(\" \") || [this.root.permalink.replace(\".html\", \".\" + this.extension.toLowerCase())]\n }\n async _buildFileType(extension, options) {\n const {root} = this\n const { fileSystem, folderPath, filename, filePath, path, lodash } = root\n const capitalized = lodash.capitalize(extension)\n const buildKeyword = \"build\" + capitalized\n const {outputFileNames} = this\n for (let name of outputFileNames) {\n try {\n await fileSystem.writeProduct(path.join(folderPath, name), root.compileTo(capitalized))\n root.log(`💾 Built ${name} from ${filename}`)\n } catch (err) {\n console.error(`Error while building '${filePath}' with extension '${extension}'`)\n throw err\n }\n }\n }\nabstractBuildOneCommandParser\n // buildOne and buildTwo are just a dumb/temporary way to have CSVs/JSONs/TSVs build first. Will be merged at some point.\n extends abstractBuildCommandParser\n javascript\n async buildOne(options) { await this._buildFileType(this.extension, options) }\nbuildParsersParser\n popularity 0.000096\n description Compile to Parsers file.\n extends abstractBuildOneCommandParser\nbuildCsvParser\n popularity 0.000096\n example\n buildCsv\n description Compile to CSV file.\n extends abstractBuildOneCommandParser\nbuildTsvParser\n popularity 0.000096\n description Compile to TSV file.\n extends abstractBuildOneCommandParser\nbuildJsonParser\n popularity 0.000096\n description Compile to JSON file.\n extends abstractBuildOneCommandParser\nabstractBuildTwoCommandParser\n extends abstractBuildCommandParser\n javascript\n async buildTwo(options) {\n await this._buildFileType(this.extension, options)\n }\nbuildCssParser\n popularity 0.000048\n description Compile to CSS file.\n extends abstractBuildTwoCommandParser\n example\n buildCss\nbuildHtmlParser\n popularity 0.007645\n description Compile to HTML file.\n extends abstractBuildTwoCommandParser\n boolean isPopular true\n javascript\n async buildTwo(options) {\n await this._copyExternalFiles(options)\n await super.buildTwo(options)\n }\n async _copyExternalFiles(options) {\n if (!this.isNodeJs()) return\n const {root} = this\n const externalFilesCopied = options.externalFilesCopied || {}\n // If this file uses a parser that has external requirements,\n // copy those from external folder into the destination folder.\n const { parsersRequiringExternals, folderPath, fileSystem, filename, parserIdIndex, path, Disk, externalsPath } = root\n if (!externalFilesCopied[folderPath]) externalFilesCopied[folderPath] = {}\n parsersRequiringExternals.forEach(parserId => {\n if (externalFilesCopied[folderPath][parserId]) return\n if (!parserIdIndex[parserId]) return\n parserIdIndex[parserId].map(particle => {\n const externalFiles = particle.copyFromExternal.split(\" \")\n externalFiles.forEach(name => {\n const newPath = path.join(folderPath, name)\n fileSystem.writeProduct(newPath, Disk.read(path.join(externalsPath, name)))\n root.log(`💾 Copied external file needed by ${filename} to ${name}`)\n })\n })\n if (parserId !== \"scrollThemeParser\")\n // todo: generalize when not to cache\n externalFilesCopied[folderPath][parserId] = true\n })\n }\nbuildJsParser\n description Compile to JS file.\n extends abstractBuildTwoCommandParser\nbuildRssParser\n popularity 0.000048\n description Compile to RSS file.\n extends abstractBuildTwoCommandParser\nbuildTxtParser\n popularity 0.007596\n description Compile to TXT file.\n extends abstractBuildTwoCommandParser\n boolean isPopular true\nloadConceptsParser\n // todo: clean this up. just add smarter imports with globs?\n // this currently removes any \"import\" statements.\n description Import all concepts in a folder.\n extends abstractBuildCommandParser\n cueFromId\n atoms preBuildCommandAtom filePathAtom\n javascript\n async load() {\n const { Disk, path, importRegex } = this.root\n const folder = path.join(this.root.folderPath, this.getAtom(1))\n const ONE_BIG_FILE = Disk.getFiles(folder).filter(file => file.endsWith(\".scroll\")).map(Disk.read).join(\"\\n\\n\").replace(importRegex, \"\")\n this.parent.concat(ONE_BIG_FILE)\n //console.log(ONE_BIG_FILE)\n }\n buildHtml() {\n return \"\"\n }\nbuildConceptsParser\n popularity 0.000024\n cueFromId\n description Compile concepts to delimited files.\n extends abstractBuildCommandParser\n sortByParser\n cueFromId\n atoms cueAtom columnNameAtom\n javascript\n async buildOne() {\n const {root} = this\n const { fileSystem, folderPath, filename, path, permalink } = root\n const files = this.getAtomsFrom(1)\n if (!files.length) files.push(permalink.replace(\".html\", \".csv\"))\n const sortBy = this.get(\"sortBy\")\n for (let link of files) {\n await fileSystem.writeProduct(path.join(folderPath, link), root.compileConcepts(link, sortBy))\n root.log(`💾 Built concepts in ${filename} to ${link}`)\n }\n }\nfetchParser\n description Download URL to disk.\n extends abstractBuildCommandParser\n cueFromId\n atoms preBuildCommandAtom urlAtom\n example\n fetch https://breckyunits.com/posts.csv\n fetch https://breckyunits.com/posts.csv renamed.csv\n javascript\n get url() {\n return this.getAtom(1)\n }\n get filename() {\n return this.getAtom(2)\n }\n async load() {\n await this.root.fetch(this.url, this.filename)\n }\n buildHtml() {\n return \"\"\n }\nbuildMeasuresParser\n popularity 0.000024\n cueFromId\n description Compile measures to delimited files.\n extends abstractBuildCommandParser\n sortByParser\n cueFromId\n atoms cueAtom columnNameAtom\n javascript\n async buildOne() {\n const {root} = this\n const { fileSystem, folderPath, filename, path, permalink } = root\n const files = this.getAtomsFrom(1)\n if (!files.length) files.push(permalink.replace(\".html\", \".csv\"))\n const sortBy = this.get(\"sortBy\")\n for (let link of files) {\n await fileSystem.writeProduct(path.join(folderPath, link), root.compileMeasures(link, sortBy))\n root.log(`💾 Built measures in ${filename} to ${link}`)\n }\n }\nbuildPdfParser\n popularity 0.000096\n description Compile to PDF file.\n extends abstractBuildCommandParser\n javascript\n async buildTwo(options) {\n if (!this.isNodeJs()) return \"Only works in Node currently.\"\n const {root} = this\n const { filename } = root\n const outputFile = root.filenameNoExtension + \".pdf\"\n // relevant source code for chrome: https://github.com/chromium/chromium/blob/a56ef4a02086c6c09770446733700312c86f7623/components/headless/command_handler/headless_command_switches.cc#L22\n const command = `/Applications/Google\\\\ Chrome.app/Contents/MacOS/Google\\\\ Chrome --headless --disable-gpu --no-pdf-header-footer --default-background-color=00000000 --no-pdf-background --print-to-pdf=\"${outputFile}\" \"${root.permalink}\"`\n // console.log(`Node.js is running on architecture: ${process.arch}`)\n try {\n const output = require(\"child_process\").execSync(command, { stdio: \"ignore\" })\n root.log(`💾 Built ${outputFile} from ${filename}`)\n } catch (error) {\n console.error(error)\n }\n }\nabstractInlineFileParser\n extends abstractScrollParser\n catchAllAtomType filePathAtom\n catchAllParser scrollFileAddressParser\n string joinChar ;\\n\\n\n string htmlTag script\n javascript\n get files() {\n const inline = this.atoms.slice(1)\n const children = this.map(particle => particle.cue)\n return inline.concat(children)\n }\n get contents() {\n return this.files.map(filename => this.root.readFile(filename)).join(this.joinChar)\n }\n buildHtml() {\n return `<${this.htmlTag}>/* ${this.files.join(\" \")} */\\n${this.contents}</${this.htmlTag}>`\n }\nscrollInlineCssParser\n description Inline CSS from files.\n popularity 0.007211\n extends abstractInlineFileParser\n cue inlineCss\n string joinChar \\n\\n\n string htmlTag style\n javascript\n buildCss() {\n return this.contents\n }\nscrollInlineJsParser\n description Inline JS from files.\n popularity 0.007211\n extends abstractInlineFileParser\n cue inlineJs\n javascript\n buildJs() {\n return this.contents\n }\nabstractTopLevelSingleMetaParser\n description Use these parsers once per file.\n extends abstractScrollParser\n inScope slashCommentParser\n cueFromId\n atoms metaCommandAtom\n javascript\n isTopMatter = true\n isSetterParser = true\n buildHtml() {\n return \"\"\n }\ntestStrictParser\n description Make catchAllParagraphParser = error.\n extends abstractTopLevelSingleMetaParser\nscrollDateParser\n cue date\n popularity 0.006680\n catchAllAtomType dateAtom\n description Set published date.\n extends abstractTopLevelSingleMetaParser\n boolean isPopular true\n example\n date 1/11/2019\n printDate\n Hello world\n dateline\nabstractUrlSettingParser\n extends abstractTopLevelSingleMetaParser\n atoms metaCommandAtom urlAtom\n cueFromId\neditBaseUrlParser\n popularity 0.007838\n description Override edit link baseUrl.\n extends abstractUrlSettingParser\ncanonicalUrlParser\n description Override canonical URL.\n extends abstractUrlSettingParser\nopenGraphImageParser\n popularity 0.000796\n // https://ogp.me/\n // If not defined, Scroll will try to generate it's own using the first image tag on your page.\n description Override Open Graph Image.\n extends abstractUrlSettingParser\nbaseUrlParser\n popularity 0.009188\n description Required for RSS and OpenGraph.\n extends abstractUrlSettingParser\n example\n baseUrl https://hub.scroll.pub/\nrssFeedUrlParser\n popularity 0.008850\n description Set RSS feed URL.\n extends abstractUrlSettingParser\neditUrlParser\n catchAllAtomType urlAtom\n description Override edit link.\n extends abstractTopLevelSingleMetaParser\nsiteOwnerEmailParser\n popularity 0.001302\n description Set email address for site contact.\n extends abstractTopLevelSingleMetaParser\n cue email\n atoms metaCommandAtom emailAddressAtom\nfaviconParser\n popularity 0.001688\n catchAllAtomType stringAtom\n cue favicon\n description Favicon file.\n example\n favicon logo.png\n metatags\n buildHtml\n extends abstractTopLevelSingleMetaParser\nimportOnlyParser\n popularity 0.033569\n // This line will be not be imported into the importing file.\n description Don't build this file.\n cueFromId\n atoms preBuildCommandAtom\n extends abstractTopLevelSingleMetaParser\n javascript\n buildHtml() {\n return \"\"\n }\ninlineMarkupsParser\n popularity 0.000024\n description Set global inline markups.\n extends abstractTopLevelSingleMetaParser\n cueFromId\n example\n inlineMarkups\n * \n // Disable * for bold\n _ u\n // Make _ underline\nhtmlLangParser\n atoms metaCommandAtom stringAtom\n // for the <html lang=\"\"> tag. If not specified will be \"en\". See https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang\n description Override HTML lang attribute.\n extends abstractTopLevelSingleMetaParser\nopenGraphDescriptionParser\n popularity 0.001688\n catchAllAtomType stringAtom\n cue description\n description Description for SEO meta tag.\n extends abstractTopLevelSingleMetaParser\nopenGraphKeywordsParser\n popularity 0.001688\n catchAllAtomType stringAtom\n cue keywords\n description Keywords for SEO meta tag.\n extends abstractTopLevelSingleMetaParser\npermalinkParser\n popularity 0.000265\n description Override output filename.\n extends abstractTopLevelSingleMetaParser\n atoms metaCommandAtom permalinkAtom\nscrollTagsParser\n popularity 0.006801\n cue tags\n description Set tags.\n example\n tags All\n extends abstractTopLevelSingleMetaParser\n catchAllAtomType tagAtom\nscrollTitleParser\n popularity 0.007524\n catchAllAtomType stringAtom\n cue title\n description Set title.\n example\n title Eureka\n printTitle\n extends abstractTopLevelSingleMetaParser\n boolean isPopular true\nscrollLinkTitleParser\n popularity 0.007524\n catchAllAtomType stringAtom\n cue linkTitle\n description Text for links.\n example\n title My blog - Eureka\n linkTitle Eureka\n extends abstractTopLevelSingleMetaParser\nscrollChatParser\n popularity 0.000362\n description A faux text chat conversation.\n catchAllParser chatLineParser\n cue chat\n extends abstractScrollParser\n example\n chat\n Hi\n 👋\n javascript\n buildHtml() {\n return this.map((line, index) => line.asString ? `<div style=\"text-align: ${index % 2 ? \"right\" : \"left\"};\" class=\"scrollChat ${index % 2 ? \"scrollChatRight\" : \"scrollChatLeft\"}\"><span>${line.asString}</span></div>` : \"\").join(\"\")\n }\n buildTxt() {\n return this.subparticlesToString()\n }\nabstractDatatableProviderParser\n description A datatable.\n extends abstractScrollParser\n inScope scrollTableDataParser scrollTableDelimiterParser abstractTableVisualizationParser abstractTableTransformParser h1Parser h2Parser scrollQuestionParser htmlInlineParser scrollBrParser slashCommentParser\n javascript\n get visualizations() {\n return this.topDownArray.filter(particle => particle.isTableVisualization || particle.isHeader || particle.isHtml)\n }\n buildHtml(buildSettings) {\n return this.visualizations.map(particle => particle.buildHtml(buildSettings))\n .join(\"\\n\")\n .trim()\n }\n buildTxt() {\n return this.visualizations.map(particle => particle.buildTxt())\n .join(\"\\n\")\n .trim()\n }\n _coreTable\n get coreTable() {\n if (this._coreTable) return this._coreTable\n const {delimiter, delimitedData} = this\n return []\n }\n get columnNames() {\n return []\n }\nscrollTableParser\n extends abstractDatatableProviderParser\n popularity 0.002133\n cue table\n example\n table\n printTable\n data\n year,count\n 1900,10\n 2000,122\n 2020,23\n catchAllAtomType filePathAtom\n int atomIndex 1\n javascript\n get delimiter() {\n const {filename} = this\n let delimiter = \"\"\n if (filename) {\n const extension = filename.split('?')[0].split(\".\").pop()\n if (extension === \"json\") delimiter = \"json\"\n if (extension === \"particles\") delimiter = \"particles\"\n if (extension === \"csv\") delimiter = \",\"\n if (extension === \"tsv\") delimiter = \"\\t\"\n if (extension === \"ssv\") delimiter = \" \"\n if (extension === \"psv\") delimiter = \"|\"\n }\n if (this.get(\"delimiter\"))\n delimiter = this.get(\"delimiter\")\n else if (!delimiter) {\n const header = this.delimitedData.split(\"\\n\")[0]\n if (header.includes(\"\\t\"))\n delimiter = \"\\t\"\n else if (header.includes(\",\"))\n delimiter = \",\"\n else\n delimiter = \" \"\n }\n return delimiter\n }\n get filename() {\n return this.getAtom(this.atomIndex)\n }\n get coreTable() {\n if (this._coreTable) return this._coreTable\n const {delimiter, delimitedData} = this\n if (delimiter === \"json\") {\n const obj = JSON.parse(delimitedData)\n let rows = []\n // Optimal case: Array of objects\n if (Array.isArray(obj)) { rows = obj}\n else if (!Array.isArray(obj) && typeof obj === \"object\") {\n // Case 2: Nested array under a key\n const arrayKey = Object.keys(obj).find(key => Array.isArray(obj[key]))\n if (arrayKey) rows = obj[arrayKey]\n }\n // Case 3: Array of primitive values\n else if (Array.isArray(obj) && obj.length && typeof obj[0] !== \"object\") {\n rows = obj.map(value => ({ value }))\n }\n this._columnNames = rows.length ? Object.keys(rows[0]) : []\n this._coreTable = rows\n return rows\n }\n else if (delimiter === \"particles\") {\n const d3lib = this.root.d3\n this._coreTable = d3lib.dsvFormat(\",\").parse(new Particle(delimitedData).asCsv, d3lib.autoType)\n } else {\n const d3lib = this.root.d3\n this._coreTable = d3lib.dsvFormat(delimiter).parse(delimitedData, d3lib.autoType)\n }\n this._columnNames = this._coreTable.columns\n delete this._coreTable.columns\n return this._coreTable\n }\n get columnNames() {\n // init coreTable to set columns\n const coreTable = this.coreTable\n return this._columnNames\n }\n async load() {\n if (this.filename)\n await this.root.fetch(this.filename)\n }\n get fileContent() {\n return this.root.readSyncFromFileOrUrl(this.filename)\n }\n get delimitedData() {\n // json csv tsv\n if (this.filename)\n return this.fileContent\n const dataParticle = this.getParticle(\"data\")\n if (dataParticle)\n return dataParticle.subparticlesToString()\n // if not dataparticle and no filename, check [permalink].csv\n if (this.isNodeJs())\n return this.root.readFile(this.root.permalink.replace(\".html\", \"\") + \".csv\")\n return \"\"\n }\nclocParser\n extends scrollTableParser\n description Output results of cloc as table.\n cue cloc\n string copyFromExternal .clocLangs.txt\n javascript\n delimiter = \",\"\n get delimitedData() {\n const { execSync } = require(\"child_process\")\n const results = execSync(this.command).toString().trim()\n const csv = results.split(\"\\n\\n\").pop().replace(/,\\\"github\\.com\\/AlDanial.+/, \"\") // cleanup output\n return csv\n }\n get command(){\n return `cloc --vcs git . --csv --read-lang-def=.clocLangs.txt ${this.content || \"\"}`\n }\nscrollDependenciesParser\n extends scrollTableParser\n description Get files this file depends on.\n cue dependencies\n javascript\n delimiter = \",\"\n get delimitedData() {\n return `file\\n` + this.root.dependencies.join(\"\\n\")\n }\nscrollDiskParser\n extends scrollTableParser\n description Output file into as table.\n cue disk\n javascript\n delimiter = \"json\"\n get delimitedData() {\n return this.isNodeJs() ? this.delimitedDataNodeJs : \"\"\n }\n get delimitedDataNodeJs() {\n const fs = require('fs');\n const path = require('path');\n const {folderPath} = this.root\n const folder = this.content ? path.join(folderPath, this.content) : folderPath\n function getDirectoryContents(dirPath) {\n const directoryContents = [];\n const items = fs.readdirSync(dirPath);\n items.forEach((item) => {\n const itemPath = path.join(dirPath, item);\n const stats = fs.statSync(itemPath);\n directoryContents.push({\n name: item,\n type: stats.isDirectory() ? 'directory' : 'file',\n size: stats.size,\n lastModified: stats.mtime\n });\n });\n return directoryContents;\n }\n return JSON.stringify(getDirectoryContents(folder))\n }\nscrollIrisParser\n extends scrollTableParser\n description Iris dataset from R.A. Fisher.\n cue iris\n example\n iris\n printTable\n scatter\n x SepalLength\n y SepalWidth\n javascript\n delimitedData = this.constructor.iris\nvegaSampleDataParser\n extends scrollTableParser\n description Sample dataset from Vega.\n cue sampleData\n atoms cueAtom vegaDataSetAtom\n example\n sampleData zipcodes.csv\n printTable\n javascript\n get filename() {\n return \"https://ohayo.scroll.pub/ohayo/packages/vega/datasets/\" + this.content\n }\nquickTableParser\n popularity 0.000024\n extends scrollTableParser\n atoms urlAtom\n pattern ^[^\\s]+\\.(tsv|csv|ssv|psv|json)[^\\s]*$\n int atomIndex 0\n javascript\n get dependencies() { return [this.cue]}\nscrollConceptsParser\n description Load concepts as table.\n extends abstractDatatableProviderParser\n cue concepts\n atoms cueAtom\n example\n concepts\n printTable\n javascript\n get coreTable() {\n return this.root.concepts\n }\n get columnNames() {\n return this.root.measures.map(col => col.Name)\n }\nabstractPostsParser\n description Load posts as table.\n extends abstractDatatableProviderParser\n cueFromId\n atoms cueAtom\n catchAllAtomType tagWithOptionalFolderAtom\n javascript\n async load() {\n const dependsOn = this.tags.map(tag => this.root.parseNestedTag(tag)).filter(i => i).map(i => i.folderPath)\n const {fileSystem} = this.root\n for (let folderPath of dependsOn) {\n // console.log(`${this.root.filePath} is loading: ${folderPath} in id '${fileSystem.fusionId}'`)\n await fileSystem.getLoadedFilesInFolder(folderPath, \".scroll\")\n }\n }\n get tags() {\n return this.content?.split(\" \") || []\n }\n get files() {\n const thisFile = this.root.file\n // todo: we can include this file, but just not run asTxt\n const files = this.root.getFilesByTags(this.tags).filter(file => file.file !== thisFile)\n return files\n }\n get coreTable() {\n if (this._coreTable) return this._coreTable\n this._coreTable = this.files.map(file => this.postToRow(file))\n return this._coreTable\n }\n postToRow(file) {\n const {relativePath} = file\n const {scrollProgram} = file.file\n const {title, permalink, asTxt, date, wordCount, minutes} = scrollProgram\n const text = asTxt.replace(/(\\t|\\n)/g, \" \").replace(/</g, \"&lt;\")\n return {\n title, titleLink: relativePath + permalink, text, date, wordCount, minutes\n }\n }\n columnNames = \"title titleLink text date wordCount minutes\".split(\" \")\nscrollPostsParser\n popularity 0.000024\n cue posts\n description Posts as table.\n extends abstractPostsParser\n example\n // Print a search table:\n posts\n printTable\n tableSearch\n // Dump a CSV of blog:\n buildHtml\n buildCsv\n buildJson\nscrollPostsMetaParser\n popularity 0.000024\n cue postsMeta\n description Post meta as table.\n extends abstractPostsParser\n javascript\n columnNames = [\"date\", \"year\", \"title\", \"permalink\", \"authors\", \"tags\", \"wordCount\", \"minutes\"]\n postToRow(file) {\n const {date, year, title, permalink, authors, tags, wordCount, minutes} = file.file.scrollProgram\n return {\n date, year, title, permalink, authors, tags, wordCount, minutes\n }\n }\nprintFeedParser\n popularity 0.000048\n description Print group to RSS.\n extends abstractPostsParser\n example\n printFeed index\n printFeed cars/index\n buildRss\n javascript\n buildRss() {\n const {dayjs} = this.root\n const scrollPrograms = this.files.map(file => file.file.scrollProgram)\n const { title, baseUrl, description } = this.root\n return `<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n <rss version=\"2.0\">\n <channel>\n <title>${title}</title>\n <link>${baseUrl}</link>\n <description>${description}</description>\n <lastBuildDate>${dayjs().format(\"ddd, DD MMM YYYY HH:mm:ss ZZ\")}</lastBuildDate>\n <language>en-us</language>\n ${scrollPrograms.map(program => program.toRss()).join(\"\\n\")}\n </channel>\n </rss>`\n }\n buildTxt() {\n return this.buildRss()\n }\nprintSourceParser\n popularity 0.000024\n description Print source for files in group(s).\n extends printFeedParser\n example\n printSource index\n buildTxt source.txt\n javascript\n buildHtml() {\n const files = this.root.getFilesByTags(this.content).map(file => file.file)\n return `${files.map(file => file.filePath + \"\\n \" + file.codeAtStart.replace(/\\n/g, \"\\n \") ).join(\"\\n\")}`\n }\nprintSiteMapParser\n popularity 0.000072\n extends abstractPostsParser\n description Print text sitemap.\n example\n baseUrl http://test.com\n printSiteMap\n javascript\n buildHtml() {\n const { baseUrl } = this.root\n return this.files.map(file => baseUrl + file.relativePath + file.file.scrollProgram.permalink).join(\"\\n\")\n }\n buildTxt() {\n return this.buildHtml()\n }\n get dependencies() { return this.files}\ncodeParser\n popularity 0.001929\n description A code block.\n catchAllParser lineOfCodeParser\n extends abstractScrollParser\n boolean isPopular true\n example\n code\n two = 1 + 1\n javascript\n buildHtml() {\n return `<code class=\"scrollCodeBlock\">${this.code.replace(/\\</g, \"&lt;\")}</code>`\n }\n buildTxt() {\n return \"```\\n\" + this.code + \"\\n```\"\n }\n get code() {\n return this.subparticlesToString()\n }\n cueFromId\ncodeWithHeaderParser\n popularity 0.000169\n cueFromId\n catchAllAtomType stringAtom\n extends codeParser\n example\n codeWithHeader math.py\n two = 1 + 1\n javascript\n buildHtml() {\n return `<div class=\"codeWithHeader\"><div class=\"codeHeader\">${this.content}</div>${super.buildHtml()}</div>`\n }\n buildTxt() {\n return \"```\" + this.content + \"\\n\" + this.code + \"\\n```\"\n }\ncodeFromFileParser\n popularity 0.000169\n cueFromId\n atoms cueAtom urlAtom\n extends codeWithHeaderParser\n example\n codeFromFile math.py\n javascript\n get code() {\n return this.root.readSyncFromFileOrUrl(this.content)\n }\ncodeWithLanguageParser\n popularity 0.000458\n description Use this to specify the language of the code block, such as csvCode or rustCode.\n extends codeParser\n pattern ^[a-zA-Z0-9_]+Code$\ndebugParsersParser\n description Print the parsers used.\n extends codeParser\n cueFromId\n javascript\n buildParsers() { return this.code}\n get code() {\n let code = new Particle(this.root.definition.toString())\n // Remove comments\n code.filter((line) => line.getLine().startsWith(\"//\")).forEach((particle) => particle.destroy())\n // Remove blank lines\n code = code.toString().replace(/^\\n/gm, \"\")\n return code\n }\nabstractScrollWithRequirementsParser\n extends abstractScrollParser\n cueFromId\n javascript\n buildHtml(buildSettings) {\n return this.getHtmlRequirements(buildSettings) + this.buildInstance()\n }\ncopyButtonsParser\n popularity 0.001471\n extends abstractScrollWithRequirementsParser\n description Copy code widget.\n javascript\n buildInstance() {\n return \"\"\n }\n string requireOnce\n <script>\n document.addEventListener(\"DOMContentLoaded\", () => document.querySelectorAll(\".scrollCodeBlock\").forEach(block =>\n {\n if (!navigator.clipboard) return\n const button = document.createElement(\"span\")\n button.classList.add(\"scrollCopyButton\")\n block.appendChild(button)\n button.addEventListener(\"click\", async () => {\n await navigator.clipboard.writeText(block.innerText)\n button.classList.add(\"scrollCopiedButton\")\n })\n }\n ))\n </script>\nabstractTableVisualizationParser\n extends abstractScrollWithRequirementsParser\n boolean isTableVisualization true\n javascript\n get columnNames() {\n return this.parent.columnNames\n }\nheatrixParser\n cueFromId\n example\n heatrix\n '2007 '2008 '2009 '2010 '2011 '2012 '2013 '2014 '2015 '2016 '2017 '2018 '2019 '2020 '2021 '2022 '2023 '2024\n 4 11 23 37 3 14 12 0 0 0 5 1 2 11 15 10 12 56\n description A heatmap matrix data visualization.\n catchAllParser heatrixCatchAllParser\n extends abstractTableVisualizationParser\n javascript\n buildHtml() {\n // A hacky but simple way to do this for now.\n const advanced = new Particle(\"heatrixAdvanced\")\n advanced.appendLineAndSubparticles(\"table\", \"\\n \" + this.tableData.replace(/\\n/g, \"\\n \"))\n const particle = this.appendSibling(\"heatrixAdvanced\", advanced.subparticlesToString())\n const html = particle.buildHtml()\n particle.destroy()\n return html\n }\n get tableData() {\n const {coreTable} = this.parent\n if (!coreTable)\n return this.subparticlesToString()\n let table = new Particle(coreTable).asSsv\n if (this.parent.cue === \"transpose\") {\n // drop first line after transpose\n const lines = table.split(\"\\n\")\n lines.shift()\n table = lines.join(\"\\n\")\n }\n // detect years and make strings\n const lines = table.split(\"\\n\")\n const yearLine = / \\d{4}(\\s+\\d{4})+$/\n if (yearLine.test(lines[0])) {\n lines[0] = lines[0].replace(/ /g, \" '\")\n table = lines.join(\"\\n\")\n }\n return table\n }\nheatrixAdvancedParser\n popularity 0.000048\n cueFromId\n catchAllParser heatrixCatchAllParser\n extends abstractTableVisualizationParser\n description Advanced heatrix.\n example\n heatrix\n table\n \n %h10; '2007 '2008 '2009\n 12 4 323\n scale\n #ebedf0 0\n #c7e9c0 100\n #a1d99b 400\n #74c476 1600\n javascript\n buildHtml() {\n class Heatrix {\n static HeatrixId = 0\n uid = Heatrix.HeatrixId++\n constructor(program) {\n const isDirective = atom => /^(f|l|w|h)\\d+$/.test(atom) || atom === \"right\" || atom === \"left\" || atom.startsWith(\"http://\") || atom.startsWith(\"https://\") || atom.endsWith(\".html\")\n const particle = new Particle(program)\n this.program = particle\n const generateColorBinningString = (data, colors) => {\n const sortedData = [...data].sort((a, b) => a - b);\n const n = sortedData.length;\n const numBins = colors.length;\n // Calculate the indices for each quantile\n const indices = [];\n for (let i = 1; i < numBins; i++) {\n indices.push(Math.floor((i / numBins) * n));\n }\n // Get the quantile values and round them\n const thresholds = indices.map(index => Math.round(sortedData[index]));\n // Generate the string\n let result = '';\n colors.forEach((color, index) => {\n const threshold = index === colors.length - 1 ? thresholds[index - 1] * 2 : thresholds[index];\n result += `${color} ${threshold}\\n`;\n });\n return result.trim();\n }\n const buildScale = (table) => {\n const numbers = table.split(\"\\n\").map(line => line.split(\" \")).flat().filter(atom => !isDirective(atom)).map(atom => parseFloat(atom)).filter(number => !isNaN(number))\n const colors = ['#ebedf0', '#c7e9c0', '#a1d99b', '#74c476', '#41ab5d', '#238b45', '#005a32'];\n numbers.unshift(0)\n return generateColorBinningString(numbers, colors);\n }\n const table = particle.getParticle(\"table\").subparticlesToString()\n const scale = particle.getParticle(\"scale\")?.subparticlesToString() || buildScale(table)\n const thresholds = []\n const colors = []\n scale.split(\"\\n\").map((line) => {\n const parts = line.split(\" \")\n thresholds.push(parseFloat(parts[1]))\n colors.push(parts[0])\n })\n const colorCount = colors.length\n const colorFunction = (value) => {\n if (isNaN(value)) return \"\" // #ebedf0\n for (let index = 0; index < colorCount; index++) {\n const threshold = thresholds[index]\n if (value <= threshold) return colors[index]\n }\n return colors[colorCount - 1]\n }\n const directiveDelimiter = \";\"\n const getSize = (directives, letter) =>\n directives\n .filter((directive) => directive.startsWith(letter))\n .map((dir) => dir.replace(letter, \"\") + \"px\")[0] ?? \"\"\n this.table = table.split(\"\\n\").map((line) =>\n line\n .trimEnd()\n .split(\" \")\n .map((atom) => {\n const atoms = atom.split(directiveDelimiter).filter((atom) => !isDirective(atom)).join(\"\")\n const directivesInThisAtom = atom\n .split(directiveDelimiter)\n .filter(isDirective)\n const value = parseFloat(atoms)\n const label = atoms.includes(\"'\") ? atoms.split(\"'\")[1] : atoms\n const alignment = directivesInThisAtom.includes(\"right\")\n ? \"right\"\n : directivesInThisAtom.includes(\"left\")\n ? \"left\"\n : \"\"\n const color = colorFunction(value)\n const width = getSize(directivesInThisAtom, \"w\")\n const height = getSize(directivesInThisAtom, \"h\")\n const fontSize = getSize(directivesInThisAtom, \"f\")\n const lineHeight = getSize(directivesInThisAtom, \"l\") || height\n const link = directivesInThisAtom.filter(i => i.startsWith(\"http\") || i.endsWith(\".html\"))[0]\n const style = {\n \"background-color\": color,\n width,\n height,\n \"font-size\": fontSize,\n \"line-height\": lineHeight,\n \"text-align\": alignment,\n }\n Object.keys(style).filter(key => !style[key]).forEach((key) => delete style[key])\n return {\n value,\n label,\n style,\n link,\n }\n })\n )\n }\n get html() {\n const { program } = this\n const cssId = `#heatrix${this.uid}`\n const defaultWidth = \"40px\"\n const defaultHeight = \"40px\"\n const fontSize = \"10px\"\n const lineHeight = defaultHeight\n const style = `<style>\n .heatrixContainer {\n margin: auto;\n }.heatrixRow {white-space: nowrap;}\n ${cssId} .heatrixAtom {\n font-family: arial;\n border-radius: 2px;\n border: 1px solid transparent;\n display: inline-block;\n margin: 1px;\n text-align: center;\n vertical-align: middle;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n .heatrixAtom a {\n color: black;\n }\n ${cssId} .heatrixAtom{\n width: ${defaultWidth};\n height: ${defaultHeight};\n font-size: ${fontSize};\n line-height: ${lineHeight};\n }\n </style>`\n const firstRow = this.table[0]\n return (\n `<div class=\"heatrixContainer\" id=\"heatrix${this.uid}\">${style}` +\n this.table\n .map((row, rowIndex) => {\n if (!rowIndex) return \"\"\n const rowStyle = row[0].style\n return `<div class=\"heatrixRow heatrixRow${rowIndex}\">${row\n .map((atom, columnIndex) => {\n if (!columnIndex) return \"\"\n const columnStyle = firstRow[columnIndex]?.style || {}\n let { value, label, style, link } = atom\n const extendedStyle = Object.assign(\n {},\n rowStyle,\n columnStyle,\n style\n )\n const inlineStyle = Object.keys(extendedStyle)\n .map((key) => `${key}:${extendedStyle[key]};`)\n .join(\"\")\n let valueClass = value ? \" valueAtom\" : \"\"\n const href = link ? ` href=\"${link}\"` : \"\"\n return `<div class=\"heatrixAtom heatrixColumn${columnIndex}${valueClass}\" style=\"${inlineStyle}\"><a title=\"${label}\" ${href}>${label}</a></div>`\n })\n .join(\"\")}</div>`\n })\n .join(\"\\n\") +\n \"</div>\"\n ).replace(/\\n/g, \"\")\n }\n }\n return new Heatrix(this.subparticlesToString().trim()).html\n }\nmapParser\n latParser\n atoms cueAtom floatAtom\n cueFromId\n single\n longParser\n atoms cueAtom floatAtom\n cueFromId\n single\n tilesParser\n atoms cueAtom tileOptionAtom\n cueFromId\n single\n zoomParser\n atoms cueAtom integerAtom\n cueFromId\n single\n geolocateParser\n description Geolocate user.\n atoms cueAtom\n cueFromId\n single\n radiusParser\n atoms cueAtom floatAtom\n cueFromId\n single\n fillOpacityParser\n atoms cueAtom floatAtom\n cueFromId\n single\n fillColorParser\n atoms cueAtom colorAtom\n cueFromId\n single\n colorParser\n atoms cueAtom colorAtom\n cueFromId\n single\n heightParser\n atoms cueAtom floatAtom\n cueFromId\n single\n hoverParser\n atoms cueAtom\n catchAllAtomType colorAtom\n cueFromId\n single\n extends abstractTableVisualizationParser\n description Map widget.\n string copyFromExternal .leaflet.css .leaflet.js .scrollLibs.js\n string requireOnce\n <link rel=\"stylesheet\" href=\".leaflet.css\">\n <script src=\".leaflet.js\"></script>\n <script src=\".scrollLibs.js\"></script>\n javascript\n buildInstance() {\n const height = this.get(\"height\") || 500\n const id = this._getUid()\n const obj = this.toObject()\n const template = {}\n const style = height !== \"full\" ? `height: ${height}px;` : `height: 100%; position: fixed; z-index: -1; left: 0; top: 0; width: 100%;`\n const strs = [\"color\", \"fillColor\"]\n const nums = [\"radius\", \"fillOpacity\"]\n strs.filter(i => obj[i]).forEach(i => template[i] = obj[i])\n nums.filter(i => obj[i]).forEach(i => template[i] = parseFloat(obj[i]))\n const mapId = `map${id}`\n return `<div id=\"${mapId}\" style=\"${style}\"></div>\n <script>\n {\n if (!window.maps) window.maps = {}\n const moveToMyLocation = () => {\n if (!navigator.geolocation) return\n navigator.geolocation.getCurrentPosition((position) => {\n const { latitude, longitude } = position.coords\n window.maps.${mapId}.setView([latitude, longitude])\n L.circleMarker([latitude, longitude], {\n fillOpacity: 0.8,\n radius: 20,\n weight: 4\n })\n .addTo(window.maps.${mapId})\n }, () => {})\n }\n const lat = ${this.get(\"lat\") ?? 37.8}\n const long = ${this.get(\"long\") ?? 4}\n if (${this.has(\"geolocate\")}){\n moveToMyLocation()\n }\n const zoomLevel = ${this.get(\"zoom\") ?? 4}\n const hover = '${this.get(\"hover\") || \"<b>{title}</b><br>{description}\"}'\n const template = ${JSON.stringify(template)}\n const points = ${JSON.stringify((this.parent.coreTable || []).filter(point => point.lat && point.long), undefined, 2)}\n window.maps.${mapId} = L.map(\"map${id}\").setView([lat, long], zoomLevel)\n const map = window.maps.${mapId}\n const tileOptions = {\n \"default\": {\n baseLayer: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',\n attribution: '<a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors'\n },\n light: {\n baseLayer: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png',\n attribution: '<a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors <a href=\"https://carto.com/ attributions\">CARTO</a>'\n },\n }\n const {baseLayer, attribution} = tileOptions.${this.get(\"tiles\") || \"default\"}\n L.tileLayer(baseLayer, {\n attribution,\n maxZoom: 19\n }).addTo(map);\n points.forEach(point => {\n L.circleMarker([point.lat, point.long], {...template, ...Object.fromEntries(\n Object.entries(point).filter(([key, value]) => value !== null)\n )})\n .addTo(map)\n .bindPopup(new Particle(point).evalTemplateString(hover))\n })\n }\n </script>`\n }\nabstractPlotParser\n // Observablehq\n extends abstractTableVisualizationParser\n string copyFromExternal .d3.js .plot.js\n string requireOnce\n <script src=\".d3.js\"></script>\n <script src=\".plot.js\"></script>\n example\n plot\n inScope abstractColumnNameParser\n widthParser\n cueFromId\n atoms cueAtom integerAtom\n heightParser\n cueFromId\n atoms cueAtom integerAtom\n titleParser\n extends abstractPlotLabelParser\n subtitleParser\n extends abstractPlotLabelParser\n captionParser\n extends abstractPlotLabelParser\n javascript\n buildInstance() {\n const id = \"plot\" + this._getUid()\n return `<div id=\"${id}\"></div><script>\n {\n let loadChart = async () => {\n const data = ${this.dataCode}\n const get = (col, index ) => col !== \"undefined\" ? col : (index === undefined ? undefined : Object.keys(data[0])[index])\n document.querySelector(\"#${id}\").append(Plot.plot(${this.plotOptions}))\n }\n loadChart()\n }\n </script>`\n }\n get sortExpression() {\n const sort = this.get(\"sort\")\n if (!sort) return \"\"\n let sort_expr = \"\"\n if (sort.startsWith(\"-\")) {\n // Sort by a value descending\n const sortCol = sort.slice(1)\n sort_expr = `, sort: {x: \"y\", reverse: true}`\n } else if (sort.includes(\" \")) {\n // Fixed order specified\n const order = sort.split(\" \")\n sort_expr = `, sort: {x: (a,b) => {\n const order = ${JSON.stringify(order)};\n return order.indexOf(a) - order.indexOf(b)\n }}`\n } else if (sort === \"asc\") {\n sort_expr = `, sort: {x: \"x\"}`\n } else if (sort === \"desc\") {\n sort_expr = `, sort: {x: \"x\", reverse: true}`\n }\n return sort_expr\n }\n get marks() {\n // just for testing purposes\n return `Plot.rectY({length: 10000}, Plot.binX({y: \"count\"}, {x: d3.randomNormal()}))`\n }\n get dataCode() {\n const {coreTable} = this.parent\n return `d3.csvParse(\\`${new Particle(coreTable).asCsv}\\`, d3.autoType)`\n }\n get plotOptions() {\n return `{\n title: \"${this.get(\"title\") || \"\"}\",\n subtitle: \"${this.get(\"subtitle\") || \"\"}\",\n caption: \"${this.get(\"caption\") || \"\"}\",\n symbol: {legend: ${this.has(\"symbol\")}},\n color: {legend: ${this.has(\"fill\") || this.has(\"stroke\")}},\n grid: ${this.get(\"grid\") !== \"false\"},\n marks: [${this.marks}],\n width: ${this.get(\"width\") || 640},\n height: ${this.get(\"height\") || 400},\n }`\n }\nplotScatterplotParser\n cue scatterplot\n extends abstractPlotParser\n description Scatterplot Widget.\n example\n iris\n scatterplot\n javascript\n get marks() {\n const x = this.get(\"x\")\n const y = this.get(\"y\")\n const text = this.get(\"label\")\n return `Plot.dot(data, {\n x: get(\"${x}\", 0),\n y: get(\"${y}\", 1),\n r: get(\"${this.get(\"radius\")}\"),\n fill: get(\"${this.get(\"fill\")}\"),\n tip: true${this.sortExpression},\n symbol: get(\"${this.get(\"symbol\")}\")} ), Plot.text(data, {x: get(\"${x}\",0), y: get(\"${y}\", 1), text: \"${text}\", dy: -6, lineAnchor: \"bottom\"})`\n }\nplotBarchartParser\n cue barchart\n extends abstractPlotParser\n description Bar chart widget.\n example\n iris\n barchart\n javascript\n get marks() {\n const x = this.get(\"x\")\n const y = this.get(\"y\")\n const text = this.get(\"label\")\n const fill = this.get(\"fill\")\n return `Plot.barY(data, {\n x: get(\"${x}\", 0),\n y: get(\"${y}\", 1),\n fill: get(\"${fill}\"),\n tip: true${this.sortExpression}\n }), Plot.ruleY([0])`\n }\nplotLineChartParser\n cue linechart\n extends abstractPlotParser\n description Line chart widget.\n example\n iris\n linechart\n x SepalLength\n y SepalWidth\n javascript\n get marks() {\n const x = this.get(\"x\")\n const y = this.get(\"y\")\n const stroke = this.get(\"stroke\") || \"steelblue\"\n const strokeWidth = this.get(\"strokeWidth\") || 2\n const strokeLinecap = this.get(\"strokeLinecap\") || \"round\"\n const fill = this.get(\"fill\")\n return `Plot.line(data, {\n x: get(\"${x}\", 0),\n y: get(\"${y}\", 1),\n stroke: \"${stroke}\",\n fill: get(\"${fill}\"),\n strokeWidth: ${strokeWidth},\n strokeLinecap: \"${strokeLinecap}\"${this.sortExpression}\n })`\n }\nsparklineParser\n popularity 0.000024\n description Sparkline widget.\n extends abstractTableVisualizationParser\n example\n sparkline 1 2 3 4 5\n string copyFromExternal .sparkline.js\n string requireOnce <script src=\".sparkline.js\"></script>\n catchAllAtomType numberAtom\n // we need pattern matching\n inScope scrollYParser\n javascript\n buildInstance() {\n const id = \"spark\" + this._getUid()\n const {columnValues} = this\n const start = this.has(\"start\") ? parseInt(this.get(\"start\")) : 0\n const width = this.get(\"width\") || 100\n const height = this.get(\"height\") || 30\n const lineColor = this.get(\"color\") || \"black\"\n return `<span id=\"${id}\"></span><script>new Sparkline(document.getElementById(\"${id}\"), {dotRadius: 0, width: ${width}, height: ${height}, lineColor: \"${lineColor}\", tooltip: (value,index) => ${start} + index + \": \" + value}).draw(${JSON.stringify(columnValues)})</script>`\n }\n get columnValues() {\n if (this.content)\n return this.content.split(\" \").map(str => parseFloat(str))\n const {coreTable} = this.parent\n if (coreTable) {\n const columnName = this.get(\"y\") || Object.keys(coreTable[0]).find(key => typeof coreTable[0][key] === 'number')\n return coreTable.map(row => row[columnName])\n }\n }\nprintColumnParser\n popularity 0.000024\n description Print one column\n extends abstractTableVisualizationParser\n example\n printColumn tags\n catchAllAtomType columnNameAtom\n joinParser\n boolean allowTrailingWhitespace true\n cueFromId\n atoms cueAtom\n catchAllAtomType stringAtom\n javascript\n buildHtml() {\n return this.columnValues.join(this.join)\n }\n buildTxt() {\n return this.columnValues.join(this.join)\n }\n get join() {\n return this.get(\"join\") || \"\\n\"\n }\n get columnName() {\n return this.atoms[1]\n }\n get columnValues() {\n return this.parent.coreTable.map(row => row[this.columnName])\n }\nprintTableParser\n popularity 0.001085\n cueFromId\n description Print table.\n extends abstractTableVisualizationParser\n javascript\n get tableHeader() {\n return this.columns.filter(col => !col.isLink).map(column => `<th>${column.name}</th>\\n`)\n }\n get columnNames() {\n return this.parent.columnNames\n }\n buildJson() {\n return JSON.stringify(this.coreTable, undefined, 2)\n }\n buildCsv() {\n return new Particle(this.coreTable).asCsv\n }\n buildTsv() {\n return new Particle(this.coreTable).asTsv\n }\n get columns() {\n const {columnNames} = this\n return columnNames.map((name, index) => {\n const isLink = name.endsWith(\"Link\")\n const linkIndex = columnNames.indexOf(name + \"Link\")\n return {\n name,\n isLink,\n linkIndex\n }\n })\n }\n toRow(row) {\n const {columns} = this\n const atoms = columns.map(col => row[col.name])\n let str = \"\"\n let column = 0\n const columnCount = columns.length\n while (column < columnCount) {\n const col = columns[column]\n column++\n const content = ((columnCount === column ? atoms.slice(columnCount - 1).join(\" \") : atoms[column - 1]) ?? \"\").toString()\n if (col.isLink) continue\n const isTimestamp = col.name.toLowerCase().includes(\"time\") && /^\\d{10}(\\d{3})?$/.test(content)\n const text = isTimestamp ? new Date(parseInt(content.length === 10 ? content * 1000 : content)).toLocaleString() : content\n let tagged = text\n const link = atoms[col.linkIndex]\n const isUrl = content.match(/^https?\\:[^ ]+$/)\n if (col.linkIndex > -1 && link) tagged = `<a href=\"${link}\">${text}</a>`\n else if (col.name.endsWith(\"Url\")) tagged = `<a href=\"${content}\">${col.name.replace(\"Url\", \"\")}</a>`\n else if (isUrl) tagged = `<a href=\"${content}\">${text}</a>`\n str += `<td>${tagged}</td>\\n`\n }\n return str\n }\n get coreTable() {\n return this.parent.coreTable\n }\n get tableBody() {\n return this.coreTable\n .map(row => `<tr>${this.toRow(row)}</tr>`)\n .join(\"\\n\")\n }\n buildHtml() {\n return `<table id=\"table${this._getUid()}\" class=\"scrollTable\">\n <thead><tr>${this.tableHeader.join(\"\\n\")}</tr></thead>\n <tbody>${this.tableBody}</tbody>\n </table>`\n }\n buildTxt() {\n return this.parent.delimitedData || new Particle(this.coreTable).asCsv\n }\nkatexParser\n popularity 0.001592\n extends abstractScrollWithRequirementsParser\n catchAllAtomType codeAtom\n catchAllParser lineOfCodeParser\n example\n katex\n \\text{E} = \\text{T} / \\text{A}!\n description KaTex widget for typeset math.\n string copyFromExternal .katex.min.css .katex.min.js\n string requireOnce\n <link rel=\"stylesheet\" href=\".katex.min.css\">\n <script defer src=\".katex.min.js\"></script>\n <script>\n document.addEventListener(\"DOMContentLoaded\", () => document.querySelectorAll(\".scrollKatex\").forEach(el =>\n {\n katex.render(el.innerText, el, {\n throwOnError: false\n });\n }\n ))\n </script>\n javascript\n buildInstance() {\n const id = this._getUid()\n const content = this.content === undefined ? \"\" : this.content\n return `<div class=\"scrollKatex\" id=\"${id}\">${content + this.subparticlesToString()}</div>`\n }\n buildTxt() {\n return ( this.content ? this.content : \"\" )+ this.subparticlesToString()\n }\nhelpfulNotFoundParser\n popularity 0.000048\n extends abstractScrollWithRequirementsParser\n catchAllAtomType filePathAtom\n string copyFromExternal .helpfulNotFound.js\n description Helpful not found widget.\n javascript\n buildInstance() {\n return `<style>#helpfulNotFound{margin: 100px 0;}</style><h1 id=\"helpfulNotFound\"></h1><script defer src=\"/.helpfulNotFound.js\"></script><script>document.addEventListener(\"DOMContentLoaded\", () => new NotFoundApp('${this.content}'))</script>`\n }\nslideshowParser\n // Left and right arrows navigate.\n description Slideshow widget. *** delimits slides.\n extends abstractScrollWithRequirementsParser\n string copyFromExternal .jquery-3.7.1.min.js .slideshow.js\n example\n slideshow\n Why did the cow cross the road?\n ***\n Because it wanted to go to the MOOOO-vies.\n ***\n THE END\n ****\n javascript\n buildHtml() {\n return `<style>html {font-size: var(--scrollBaseFontSize, 28px);} body {margin: auto; width: 500px;}.slideshowNav{text-align: center; margin-bottom:20px; font-size: 24px;color: rgba(204,204,204,.8);} a{text-decoration: none; color: rgba(204,204,204,.8);}</style><script defer src=\".jquery-3.7.1.min.js\"></script><div class=\"slideshowNav\"></div><script defer src=\".slideshow.js\"></script>`\n }\ntableSearchParser\n popularity 0.000072\n extends abstractScrollWithRequirementsParser\n string copyFromExternal .jquery-3.7.1.min.js .datatables.css .dayjs.min.js .datatables.js .tableSearch.js\n string requireOnce\n <script defer src=\".jquery-3.7.1.min.js\"></script>\n <style>.dt-search{font-family: \"SF Pro\", \"Helvetica Neue\", \"Segoe UI\", \"Arial\";}</style>\n <link rel=\"stylesheet\" href=\".datatables.css\">\n <script defer src=\".datatables.js\"></script>\n <script defer src=\".dayjs.min.js\"></script>\n <script defer src=\".tableSearch.js\"></script>\n // adds to all tables on page\n description Table search and sort widget.\n javascript\n buildInstance() {\n return \"\"\n }\nabstractCommentParser\n description Prints nothing.\n catchAllAtomType commentAtom\n atoms commentAtom\n extends abstractScrollParser\n baseParser blobParser\n string bindTo next\n javascript\n buildHtml() {\n return ``\n }\n catchAllParser commentLineParser\ncommentParser\n popularity 0.000193\n extends abstractCommentParser\n cueFromId\ncounterpointParser\n description Counterpoint comment. Prints nothing.\n extends commentParser\n cue !\nslashCommentParser\n popularity 0.005643\n extends abstractCommentParser\n cue //\n boolean isPopular true\n description A comment. Prints nothing.\nthanksToParser\n description Acknowledgements comment. Prints nothing.\n extends abstractCommentParser\n cueFromId\nscrollClearStackParser\n popularity 0.000096\n cue clearStack\n description Clear body stack.\n extends abstractScrollParser\n boolean isHtml true\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n return this.root.clearBodyStack().trim()\n }\ncssParser\n popularity 0.007211\n extends abstractScrollParser\n description A style tag.\n example\n css\n body { color: red;}\n cueFromId\n catchAllParser cssLineParser\n catchAllAtomType cssAnyAtom\n javascript\n buildHtml() {\n return `<style>${this.css}</style>`\n }\n get css() {\n return this.content ?? this.subparticlesToString()\n }\n buildCss() {\n return this.css\n }\nscrollBackgroundColorParser\n description Quickly set CSS background.\n popularity 0.007211\n extends abstractScrollParser\n cue background\n catchAllAtomType cssAnyAtom\n example\n background red\n javascript\n buildHtml() {\n return `<style>html, body { background: ${this.content};}</style>`\n }\nscrollFontColorParser\n description Quickly set CSS font-color.\n popularity 0.007211\n extends abstractScrollParser\n cue color\n catchAllAtomType cssAnyAtom\n javascript\n buildHtml() {\n return `<style>html, body { color: ${this.content};}</style>`\n }\nscrollFontParser\n description Quickly set font family.\n popularity 0.007211\n extends abstractScrollParser\n cue font\n atoms cueAtom fontFamilyAtom\n catchAllAtomType cssAnyAtom\n example\n font Slim\n javascript\n buildHtml() {\n const font = this.content === \"Slim\" ? \"Helvetica Neue; font-weight:100;\" : this.content\n return `<style>html, body, h1,h2,h3 { font-family: ${font};}</style>`\n }\nabstractQuickIncludeParser\n popularity 0.007524\n extends abstractScrollParser\n atoms urlAtom\n javascript\n get dependencies() { return [this.filename]}\n get filename() {\n return this.getAtom(0)\n }\nquickCssParser\n popularity 0.007524\n description Make a CSS tag.\n extends abstractQuickIncludeParser\n example\n style.css\n atoms urlAtom\n pattern ^[^\\s]+\\.(css)$\n javascript\n buildHtml() {\n return `<link rel=\"stylesheet\" type=\"text/css\" href=\"${this.filename}\">`\n }\n buildHtmlSnippet() {\n return \"\"\n }\nquickIncludeHtmlParser\n popularity 0.007524\n description Include an HTML file.\n extends abstractQuickIncludeParser\n example\n body.html\n atoms urlAtom\n pattern ^[^\\s]+\\.(html|htm)$\n javascript\n buildHtml() {\n return this.root.readFile(this.filename)\n }\nquickScriptParser\n popularity 0.007524\n description Make a Javascript tag.\n extends abstractQuickIncludeParser\n atoms urlAtom\n example\n script.js\n pattern ^[^\\s]+\\.(js)$\n javascript\n attr = \"\"\n buildHtml() {\n return `<script ${this.attr} src=\"${this.filename}\"></script>`\n }\n buildHtmlSnippet() {\n return \"\"\n }\nquickModuleScriptParser\n description Make a Javascript module tag.\n extends quickScriptParser\n example\n script.mjs\n pattern ^[^\\s]+\\.(mjs)$\n javascript\n attr = 'type=\"module\"'\nscrollDashboardParser\n popularity 0.000145\n description Key stats in large font.\n catchAllParser lineOfCodeParser\n cue dashboard\n extends abstractScrollParser\n example\n dashboard\n #2 Popularity\n 30 Years Old\n $456 Revenue\n javascript\n get tableBody() {\n const items = this.topDownArray\n let str = \"\"\n for (let i = 0; i < items.length; i = i + 3) {\n str += this.makeRow(items.slice(i, i + 3))\n }\n return str\n }\n makeRow(items) {\n return `<tr>` + items.map(particle => `<td>${particle.cue}<span>${particle.content}</span></td>`).join(\"\\n\") + `</tr>\\n`\n }\n buildHtml() {\n return `<table class=\"scrollDashboard\">${this.tableBody}</table>`\n }\n buildTxt() {\n return this.subparticlesToString()\n }\nbelowAsCodeParser\n popularity 0.000651\n description Print code below.\n string bindTo next\n extends abstractScrollParser\n catchAllAtomType integerAtom\n example\n belowAsCode\n iris\n printTable\n cueFromId\n javascript\n method = \"next\"\n get selectedParticles() {\n const { method } = this\n let code = \"\"\n let particles = []\n let next = this[method]\n let {howMany} = this\n while (howMany) {\n particles.push(next)\n next = next[method]\n howMany--\n }\n if (this.reverse) particles.reverse()\n return particles\n }\n get code() {\n return this.selectedParticles.map(particle => particle.asString).join(\"\\n\")\n }\n reverse = false\n buildHtml() {\n return `<code class=\"scrollCodeBlock\">${this.code.replace(/\\</g, \"&lt;\")}</code>`\n }\n get howMany() {\n let howMany = parseInt(this.getAtom(1))\n if (!howMany || isNaN(howMany)) howMany = 1\n return howMany\n }\ndebugBelowParser\n description Inspect particle below.\n extends belowAsCodeParser\n string copyFromExternal .debug.css\n javascript\n get code() {\n const mapFn = particle => {\n const atomTypes = particle.lineAtomTypes.split(\" \")\n return `<div class=\"debugParticle\"><span class=\"debugParticleId\">${particle.constructor.name}</span>${particle.atoms.map((atom, index) => `<span class=\"debugAtom\">${atom}<span class=\"debugAtomType\">${atomTypes[index]}</span></span>`).join(\" \")}${(particle.length ? `<br><div class=\"debugSubparticles\">` + particle.map(mapFn).join(\"<br>\") + `</div>` : \"\")}</div>`}\n return this.selectedParticles.map(mapFn).join(\"<br>\")\n }\n buildHtml() {\n return `<link rel=\"stylesheet\" href=\".debug.css\">` + this.code\n }\n buildTxt() {\n const mapFn = particle => {\n const atomTypes = particle.lineAtomTypes.split(\" \")\n return `${particle.constructor.name} ${particle.atoms.map((atom, index) => `${atomTypes[index]}:${atom}`).join(\" \")}${(particle.length ? `\\n ` + particle.map(mapFn).join(\"\\n\") + `` : \"\")}`}\n return this.selectedParticles.map(mapFn).join(\"\\n\")\n }\n buildParsers() {return this.buildTxt()}\ndebugAboveParser\n description Inspect particle above.\n extends debugBelowParser\n string bindTo previous\n javascript\n method = \"previous\"\n reverse = true\ndebugAllParser\n description Inspect entire document.\n extends debugBelowParser\n javascript\n get selectedParticles() { return this.root.getSubparticles()}\nbelowAsCodeUntilParser\n description Print code above until match.\n extends belowAsCodeParser\n catchAllAtomType codeAtom\n example\n belowAsCode\n counter 1 second\n javascript\n get howMany() {\n let howMany = 1\n const query = this.content\n let particle = this.next\n while (particle !== this) {\n if (particle.getLine().startsWith(query))\n return howMany\n particle = particle.next\n howMany++\n }\n return howMany\n }\naboveAsCodeParser\n popularity 0.000482\n string bindTo previous\n description Print code above.\n example\n counter 1 second\n aboveAsCode\n extends belowAsCodeParser\n javascript\n method = \"previous\"\n reverse = true\nbelowAsHtmlParser\n extends belowAsCodeParser\n description Displays html output of next particle in a code block.\n cueFromId\n example\n belowAsHtml\n # Hello world\n javascript\n get code() {\n return this.selectedParticles.filter(p => p.buildHtml).map(p => p.buildHtml()).join(\"\\n\")\n }\naboveAsHtmlParser\n description Displays html output of previous particle in a code block.\n extends belowAsHtmlParser\n example\n # Hello world\n aboveAsHtml\n javascript\n method = \"previous\"\n reverse = true\nscrollDefParser\n popularity 0.004244\n description Parser short form.\n pattern ^[a-zA-Z0-9_]+Def\n extends abstractScrollParser\n catchAllAtomType stringAtom\n example\n urlDef What is the URL?\n javascript\n buildParsers(index) {\n const idStuff = index ? \"\" : `boolean isMeasure true\n boolean isMeasureRequired true\n boolean isConceptDelimiter true`\n const description = this.content\n const cue = this.cue.replace(\"Def\", \"\")\n const sortIndex = 1 + index/10\n return `${cue}DefParser\n cue ${cue}\n extends abstractStringMeasureParser\n description ${description}\n float sortIndex ${sortIndex}\n ${idStuff}`.trim()\n }\nhakonParser\n cueFromId\n extends abstractScrollParser\n description Compile Hakon to CSS.\n catchAllParser hakonContentParser\n javascript\n buildHtml() {\n return `<style>${this.css}</style>`\n }\n get css() {\n const {hakonParser} = this.root\n return new hakonParser(this.subparticlesToString()).compile()\n }\n buildCss() {\n return this.css\n }\nhamlParser\n popularity 0.007524\n description HTML tag via HAML syntax.\n extends abstractScrollParser\n atoms urlAtom\n catchAllAtomType stringAtom\n pattern ^%?[\\w\\.]+#[\\w\\.]+ *\n javascript\n get tag() {\n return this.atoms[0].split(/[#\\.]/).shift().replace(\"%\", \"\")\n }\n get htmlId() {\n const idMatch = this.atoms[0].match(/#([\\w-]+)/)\n return idMatch ? idMatch[1] : \"\"\n }\n get htmlClasses() {\n return this.atoms[0].match(/\\.([\\w-]+)/g)?.map(cls => cls.slice(1)) || [];\n }\n buildHtml() {\n const {htmlId, htmlClasses, content, tag} = this\n this.parent.sectionStack.unshift(`</${tag}>`)\n const attrs = [htmlId ? ' id=\"' + htmlId + '\"' : \"\", htmlClasses.length ? ' class=\"' + htmlClasses.join(\" \") + '\"' : \"\"].join(\" \").trim()\n return `<${tag}${attrs ? \" \" + attrs : \"\"}>${content || \"\"}`\n }\n buildTxt() {\n return this.content\n }\nhamlTagParser\n // Match plain tags like %h1\n extends hamlParser\n pattern ^%[^#]+$\nabstractHtmlParser\n extends abstractScrollParser\n catchAllParser htmlLineParser\n catchAllAtomType htmlAnyAtom\n javascript\n buildHtml() {\n return `${this.content ?? \"\"}${this.subparticlesToString()}`\n }\n buildTxt() {\n return \"\"\n }\nhtmlParser\n popularity 0.000048\n extends abstractHtmlParser\n description HTML one liners or blocks.\n cueFromId\nhtmlInlineParser\n popularity 0.005788\n extends abstractHtmlParser\n atoms htmlAnyAtom\n boolean isHtml true\n example\n <h1>Inline HTML</h1>\n pattern ^<\n description Inline HTML.\n boolean isPopular true\n javascript\n buildHtml() {\n return `${this.getLine() ?? \"\"}${this.subparticlesToString()}`\n }\nscrollBrParser\n popularity 0.000096\n cue br\n example\n br 2\n description A break.\n extends abstractScrollParser\n catchAllAtomType integerAtom\n boolean isHtml true\n javascript\n buildHtml() {\n return `<br>`.repeat(parseInt(this.getAtom(1) || 1))\n }\niframesParser\n popularity 0.000121\n cueFromId\n catchAllAtomType urlAtom\n extends abstractScrollParser\n description An iframe(s).\n example\n iframes frame.html\n javascript\n buildHtml() {\n return this.atoms.slice(1).map(url => `<iframe src=\"${url}\" frameborder=\"0\"></iframe>`).join(\"\\n\")\n }\nabstractCaptionedParser\n extends abstractScrollParser\n atoms cueAtom urlAtom\n inScope captionAftertextParser slashCommentParser\n cueFromId\n javascript\n buildHtml(buildSettings) {\n const caption = this.getParticle(\"caption\")\n const captionFig = caption ? `<figcaption>${caption.buildHtml()}</figcaption>` : \"\"\n const {figureWidth} = this\n const widthStyle = figureWidth ? `width:${figureWidth}px; margin: auto;` : \"\"\n const float = this.has(\"float\") ? `margin: 20px; float: ${this.get(\"float\")};` : \"\"\n return `<figure class=\"scrollCaptionedFigure\" style=\"${widthStyle + float}\">${this.getFigureContent(buildSettings)}${captionFig}</figure>`\n }\n get figureWidth() {\n return this.get(\"width\")\n }\nscrollImageParser\n cue image\n popularity 0.005908\n description An img tag.\n boolean isPopular true\n extends abstractCaptionedParser\n int atomIndex 1\n example\n image screenshot.png\n caption A caption.\n inScope addClassMarkupParser aftertextIdParser scrollLinkParser linkTargetParser openGraphParser\n javascript\n get dimensions() {\n const width = this.get(\"width\")\n const height = this.get(\"height\")\n if (width || height)\n return {width, height}\n if (!this.isNodeJs())\n return {}\n const src = this.filename\n // If its a local image, get the dimensions and put them in the HTML\n // to avoid flicker\n if (src.startsWith(\"http:\") || src.startsWith(\"https:\")) return {}\n if (this._dimensions)\n return this._dimensions\n try {\n const sizeOf = require(\"image-size\")\n const path = require(\"path\")\n const fullImagePath = path.join(this.root.folderPath, src)\n this._dimensions = sizeOf(fullImagePath)\n return this._dimensions\n } catch (err) {\n console.error(err)\n }\n return {}\n }\n get figureWidth() {\n return this.dimensions.width\n }\n get filename() {\n return this.getAtom(this.atomIndex)\n }\n get dependencies() { return [this.filename]}\n getFigureContent(buildSettings) {\n const linkRelativeToCompileTarget = (buildSettings ? (buildSettings.relativePath ?? \"\") : \"\") + this.filename\n const {width, height} = this.dimensions\n let dimensionAttributes = width || height ? `width=\"${width}\" height=\"${height}\" ` : \"\"\n // Todo: can we reuse more code from aftertext?\n const className = this.has(\"class\") ? ` class=\"${this.get(\"class\")}\" ` : \"\"\n const id = this.has(\"id\") ? ` id=\"${this.get(\"id\")}\" ` : \"\"\n const clickLink = this.find(particle => particle.definition.isOrExtendsAParserInScope([\"scrollLinkParser\"])) || linkRelativeToCompileTarget \n const target = this.has(\"target\") ? this.get(\"target\") : (this.has(\"link\") ? \"\" : \"_blank\")\n return `<a href=\"${clickLink}\" target=\"${target}\" ${className} ${id}><img src=\"${linkRelativeToCompileTarget}\" ${dimensionAttributes}loading=\"lazy\"></a>`\n }\n buildTxt() {\n const subparticles = this.filter(particle => particle.buildTxt).map(particle => particle.buildTxt()).filter(i => i).join(\"\\n\")\n return \"[Image Omitted]\" + (subparticles ? \"\\n \" + subparticles.replace(/\\n/g, \"\\n \") : \"\")\n }\nquickImageParser\n popularity 0.005788\n extends scrollImageParser\n example\n screenshot.png\n atoms urlAtom\n pattern ^[^\\s]+\\.(jpg|jpeg|png|gif|webp|svg|bmp)\n int atomIndex 0\nqrcodeParser\n extends abstractCaptionedParser\n description Make a QR code from a link.\n example\n qrcode https://scroll.pub\n javascript\n getFigureContent() {\n const url = this.atoms[1]\n const isNode = this.isNodeJs()\n if (isNode) {\n const {externalsPath} = this.root\n const path = require(\"path\")\n const {qrcodegen, toSvgString} = require(path.join(externalsPath, \".qrcodegen.js\"))\n const QRC = qrcodegen.QrCode;\n const qr0 = QRC.encodeText(url, QRC.Ecc.MEDIUM);\n const svg = toSvgString(qr0, 4); // See qrcodegen-input-demo\n return svg\n }\n return `Not yet supported in browser.`\n }\nyoutubeParser\n popularity 0.000121\n extends abstractCaptionedParser\n // Include the YouTube embed URL such as https://www.youtube.com/embed/CYPYZnVQoLg\n description A YouTube video widget.\n example\n youtube https://www.youtube.com/watch?v=lO8blNtYYBA\n javascript\n getFigureContent() {\n const url = this.getAtom(1).replace(\"youtube.com/watch?v=\", \"youtube.com/embed/\")\n return `<div class=\"scrollYouTubeHolder\"><iframe class=\"scrollYouTubeEmbed\" src=\"${url}\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe></div>`\n }\nyouTubeParser\n extends youtubeParser\n tags deprecate\n // Deprecated. You youtube all lowercase.\nimportParser\n description Import a file.\n popularity 0.007524\n cueFromId\n atoms preBuildCommandAtom\n extends abstractScrollParser\n catchAllAtomType filePathAtom\n javascript\n buildHtml() {\n return \"\"\n }\n example\n import header.scroll\nscrollImportedParser\n description Inserted at import pass.\n boolean suggestInAutocomplete false\n cue imported\n atoms preBuildCommandAtom\n extends abstractScrollParser\n baseParser blobParser\n catchAllAtomType filePathAtom\n javascript\n buildHtml() {\n return \"\"\n }\n getErrors() {\n if (this.get(\"exists\") === \"false\" && this.previous.getLine() !== \"// optional\")\n return [this.makeError(`File '${this.atoms[1]}' does not exist.`)]\n return []\n }\nquickImportParser\n popularity 0.007524\n description Import a Scroll or Parsers file.\n extends abstractScrollParser\n boolean isPopular true\n inScope importToFooterParser abstractCommentParser\n atoms urlAtom\n pattern ^[^\\s]+\\.(scroll|parsers)$\n javascript\n buildHtml() {\n return \"\"\n }\n example\n header.scroll\nscriptParser\n extends abstractScrollParser\n description Print script tag.\n cueFromId\n catchAllParser scriptLineParser\n catchAllAtomType javascriptAnyAtom\n javascript\n buildHtml() {\n return `<script>${this.scriptContent}</script>`\n }\n get scriptContent() {\n return this.content ?? this.subparticlesToString()\n }\n buildJs() {\n return this.scriptContent\n }\njsonScriptParser\n popularity 0.007524\n cueFromId\n description Include JSON and assign to window.\n extends abstractScrollParser\n atoms cueAtom urlAtom\n javascript\n buildHtml() {\n const varName = this.filename.split(\"/\").pop().replace(\".json\", \"\")\n return `<script>window.${varName} = ${this.root.readFile(this.filename)}</script>`\n }\n get filename() {\n return this.getAtom(1)\n }\nscrollLeftRightButtonsParser\n popularity 0.006342\n cue leftRightButtons\n description Previous and next nav buttons.\n extends abstractScrollParser\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n const { linkToPrevious, linkToNext } = this.root\n if (!linkToPrevious) return \"\"\n const style = `a.keyboardNav {display:block;position:absolute;top:0.25rem; color: rgba(204,204,204,.8); font-size: 1.875rem; line-height: 1.7rem;}a.keyboardNav:hover{color: #333;text-decoration: none;}`\n return `<style>${style}</style><a class=\"keyboardNav doNotPrint\" style=\"left:.5rem;\" href=\"${linkToPrevious}\">&lt;</a><a class=\"keyboardNav doNotPrint\" style=\"right:.5rem;\" href=\"${linkToNext}\">&gt;</a>`\n }\nkeyboardNavParser\n popularity 0.007476\n description Make left and right navigate files.\n extends abstractScrollParser\n cueFromId\n catchAllAtomType urlAtom\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n const {root} = this\n const linkToPrevious = this.getAtom(1) ?? root.linkToPrevious\n const linkToNext = this.getAtom(2) ?? root.linkToNext\n const script = `<script>document.addEventListener('keydown', function(event) {\n if (document.activeElement !== document.body) return\n if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return // dont interfere with keyboard back button shortcut\n const getLinks = () => document.getElementsByClassName(\"scrollKeyboardNav\")[0].getElementsByTagName(\"a\")\n if (event.key === \"ArrowLeft\")\n getLinks()[0].click()\n else if (event.key === \"ArrowRight\")\n getLinks()[1].click()\n });</script>`\n return `<div class=\"scrollKeyboardNav\" style=\"display:none;\"><a href=\"${linkToPrevious}\">${linkToPrevious}</a> · ${root.permalink} · <a href=\"${linkToNext}\">${linkToNext}</a>${script}</div>`\n }\nprintUsageStatsParser\n popularity 0.000096\n // todo: if we include the atom \"Parser\" in a cue, bad things seem to happen.\n description Parser usage stats for folder.\n extends abstractScrollParser\n cueFromId\n javascript\n get stats() {\n const input = this.root.allScrollFiles.map(file => file.scrollProgram).map(program => program.parserIds.join(\"\\n\")).join(\"\\n\")\n const result = input.split('\\n').reduce((acc, atom) => (acc[atom] = (acc[atom] || 0) + 1, acc), {})\n const rows = Object.entries(result).map(([atom, count]) => { return {atom, count}})\n const sorted = this.root.lodash.sortBy(rows, \"count\").reverse()\n return \"parserId uses\\n\" + sorted.map(row => `${row.atom} ${row.count}`).join('\\n')\n }\n buildHtml() {\n // A hacky but simple way to do this for now.\n const particle = this.appendSibling(\"table\")\n particle.appendLine(\"delimiter \")\n particle.appendLine(\"printTable\")\n const dataParticle = particle.appendLine(\"data\")\n dataParticle.setSubparticles(this.stats)\n const html = particle.buildHtml()\n particle.destroy()\n return html\n }\n buildTxt() {\n return this.stats\n }\n buildCsv() {\n return this.stats.replace(/ /g, \",\")\n }\nprintScrollLeetSheetParser\n popularity 0.000024\n description Print Scroll parser leet sheet.\n extends abstractScrollParser\n tags experimental\n cueFromId\n javascript\n get parsersToDocument() {\n const clone = this.root.clone()\n clone.setSubparticles(\"\")\n const atoms = clone.getAutocompleteResultsAt(0,0).matches.map(a => a.text)\n atoms.push(\"blankline\") // manually add blank line\n atoms.push(\"Catch All Paragraph.\") // manually add catch all paragraph\n atoms.push(\"<h></h>\") // manually add html\n atoms.sort()\n clone.setSubparticles(atoms.join(\"\\n\").replace(/blankline/, \"\")) // insert blank line in right spot\n return clone\n }\n sortDocs(docs) {\n return docs.map(particle => {\n const {definition} = particle\n const {id, description, isPopular, examples, popularity} = definition\n const tags = definition.get(\"tags\") || \"\"\n if (tags.includes(\"deprecate\") || tags.includes(\"experimental\"))\n return null\n const category = this.getCategory(tags)\n const note = this.getNote(category)\n return {id: definition.cueIfAny || id, description, isPopular, examples, note, popularity: Math.ceil(parseFloat(popularity) * 100000)}\n }).filter(i => i).sort((a, b) => a.id.localeCompare(b.id))\n }\n makeLink(examples, cue) {\n // if (!examples.length) console.log(cue) // find particles that need docs\n const example = examples.length ? examples[0].subparticlesToString() : cue\n const base = `https://try.scroll.pub/`\n const particle = new Particle()\n particle.appendLineAndSubparticles(\"scroll\", \"theme gazette\\n\" + example)\n return base + \"#\" + encodeURIComponent(particle.asString)\n }\n docToHtml(doc) {\n const css = `#scrollLeetSheet {color: grey;} #scrollLeetSheet a {color: #3498db; }`\n return `<style>${css}</style><div id=\"scrollLeetSheet\">` + doc.map(obj => `<div class=\"${obj.category}\"><a href=\"${this.makeLink(obj.examples, obj.id)}\">${obj.isPopular ? \"<b>\" : \"\"}${obj.id}</a> ${obj.description}${obj.isPopular ? \"</b>\" : \"\"}${obj.note}</div>`).join(\"\\n\") + \"</div>\"\n }\n buildHtml() {\n return this.docToHtml(this.sortDocs(this.parsersToDocument))\n }\n buildTxt() {\n return this.sortDocs(this.parsersToDocument).map(obj => `${obj.id} - ${obj.description}`).join(\"\\n\")\n }\n getCategory(input) {\n return \"\"\n }\n getNote() {\n return \"\"\n }\n get docs() {\n const rows = this.sortDocs(this.parsersToDocument).map(obj => {\n const {id, isPopular, description, popularity, category, examples, cue} = obj\n const example = examples.length ? examples[0].subparticlesToString() : cue\n return {\n id,\n isPopular,\n description,\n popularity,\n example,\n category\n }\n })\n return this.root.lodash.sortBy(rows, \"isPopular\")\n }\n buildJson() {\n return JSON.stringify(this.docs, undefined, 2)\n }\n buildCsv() {\n return new Particle(this.docs).asCsv\n }\nprintparsersLeetSheetParser\n popularity 0.000024\n // todo: fix parse bug when atom Parser appears in parserId\n extends printScrollLeetSheetParser\n tags experimental\n description Parsers leetsheet.\n javascript\n buildHtml() {\n return \"<p><b>Parser Definition Parsers</b> define parsers that acquire, analyze and act on code.</p>\" + this.docToHtml(this.sortDocs(this.parsersToDocument)) + \"<p><b>Atom Definition Parsers</b> analyze the atoms in a line.</p>\" + this.docToHtml(this.sortDocs(this.atomParsersToDocument))\n }\n makeLink() {\n return \"\"\n }\n categories = \"assemblePhase acquirePhase analyzePhase actPhase\".split(\" \")\n getCategory(tags) {\n return tags.split(\" \").filter(w => w.endsWith(\"Phase\"))[0]\n }\n getNote(category) {\n return ` <span class=\"note\">A${category.replace(\"Phase\", \"\").substr(1)}Time.</span>`\n }\n get atomParsersToDocument() {\n const parsersParser = require(\"scrollsdk/products/parsers.nodejs.js\")\n const clone = new parsersParser(\"anyAtom\\n \").clone()\n const parserParticle = clone.getParticle(\"anyAtom\")\n const atoms = clone.getAutocompleteResultsAt(1,1).matches.map(a => a.text)\n atoms.sort()\n parserParticle.setSubparticles(atoms.join(\"\\n\"))\n return parserParticle\n }\n get parsersToDocument() {\n const parsersParser = require(\"scrollsdk/products/parsers.nodejs.js\")\n const clone = new parsersParser(\"latinParser\\n \").clone()\n const parserParticle = clone.getParticle(\"latinParser\")\n const atoms = clone.getAutocompleteResultsAt(1,1).matches.map(a => a.text)\n atoms.sort()\n parserParticle.setSubparticles(atoms.join(\"\\n\"))\n clone.appendLine(\"myParser\")\n clone.appendLine(\"myAtom\")\n return parserParticle\n }\nabstractMeasureParser\n atoms measureNameAtom\n description Base parser all measures extend.\n cueFromId\n boolean isMeasure true\n float sortIndex 1.9\n boolean isComputed false\n string typeForWebForms text\n extends abstractScrollParser\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n return \"\"\n }\n get measureValue() {\n return this.content ?? \"\"\n }\n get measureName() {\n return this.getCuePath().replace(/ /g, \"_\")\n }\nabstractAtomMeasureParser\n description Contains a single word.\n atoms measureNameAtom atomAtom\n example\n nicknameParser\n extends abstractAtomMeasureParser\n id Breck\n nickname breck\n extends abstractMeasureParser\nabstractEmailMeasureParser\n description Email address.\n example\n emailParser\n extends abstractEmailMeasureParser\n id Breck\n email breck7@gmail.com\n string typeForWebForms email\n atoms measureNameAtom emailAddressAtom\n extends abstractAtomMeasureParser\nabstractUrlMeasureParser\n description A single url.\n example\n homepageParser\n extends abstractUrlMeasureParser\n id Breck\n homepage https://breckyunits.com\n string typeForWebForms url\n atoms measureNameAtom urlAtom\n extends abstractAtomMeasureParser\nabstractStringMeasureParser\n description General text data with no specific format.\n catchAllAtomType stringAtom\n example\n titleParser\n extends abstractStringMeasureParser\n id Breck\n title I build languages for scientists of all ages\n extends abstractMeasureParser\nabstractIdParser\n cue id\n description What is the ID of this concept?\n extends abstractStringMeasureParser\n example\n idParser\n extends abstractIdParser\n id breck\n float sortIndex 1\n boolean isMeasureRequired true\n boolean isConceptDelimiter true\n javascript\n getErrors() {\n const errors = super.getErrors()\n let requiredMeasureNames = this.root.measures.filter(measure => measure.isMeasureRequired).map(measure => measure.Name).filter(name => name !== \"id\")\n if (!requiredMeasureNames.length) return errors\n let next = this.next\n while (requiredMeasureNames.length && next.cue !== \"id\" && next.index !== 0) {\n requiredMeasureNames = requiredMeasureNames.filter(i => i !== next.cue)\n next = next.next\n }\n requiredMeasureNames.forEach(name =>\n errors.push(this.makeError(`Concept \"${this.content}\" is missing required measure \"${name}\".`))\n )\n return errors\n }\nabstractIdMeasureParser\n description Alias for abstractIdParser.\n extends abstractIdParser\nabstractTextareaMeasureParser\n string typeForWebForms textarea\n example\n bioParser\n extends abstractTextareaMeasureParser\n id Breck\n bio\n I build languages for scientists of all ages\n description Long-form text content with preserved line breaks.\n extends abstractMeasureParser\n baseParser blobParser\n javascript\n get measureValue() {\n return this.subparticlesToString().replace(/\\n/g, \"\\\\n\")\n }\nabstractNumericMeasureParser\n string typeForWebForms number\n description Base number type.\n extends abstractMeasureParser\n javascript\n get measureValue() {\n const {content} = this\n return content === undefined ? \"\" : parseFloat(content)\n }\nabstractNumberMeasureParser\n description Alias to abstractNumericMeasureParser.\n extends abstractNumericMeasureParser\nabstractIntegerMeasureParser\n description An integer.\n example\n ageParser\n extends abstractIntegerMeasureParser\n id Breck\n age 40\n atoms measureNameAtom integerAtom\n extends abstractNumericMeasureParser\n javascript\n get measureValue() {\n const {content} = this\n return content === undefined ? \"\" : parseInt(content)\n }\nabstractIntMeasureParser\n description Alias to abstractIntegerMeasureParser.\n extends abstractIntegerMeasureParser\nabstractFloatMeasureParser\n description A float.\n example\n temperatureParser\n extends abstractFloatMeasureParser\n id Breck\n temperature 31.8\n atoms measureNameAtom floatAtom\n extends abstractNumericMeasureParser\nabstractPercentageMeasureParser\n description A percentage.\n atoms measureNameAtom percentAtom\n extends abstractNumericMeasureParser\n example\n ownershipParser\n extends abstractPercentageMeasureParser\n id Breck\n ownership 31.8\n javascript\n get measureValue() {\n const {content} = this\n return content === undefined ? \"\" : parseFloat(content)\n }\nabstractEnumMeasureParser\n description A single enum.\n atoms measureNameAtom enumAtom\n extends abstractMeasureParser\n example\n favoriteHtmlTagParser\n extends abstractEnumMeasureParser\n atoms measureNameAtom htmlTagAtom\n id Breck\n favoriteHtmlTag 2020\nabstractBooleanMeasureParser\n description A single boolean.\n atoms measureNameAtom booleanAtom\n extends abstractMeasureParser\n example\n hasBillOfRightsParser\n extends abstractBooleanMeasureParser\n id USA\n hasBillOfRights true\n javascript\n get measureValue() {\n const {content} = this\n return content === undefined ? \"\" : content == \"true\"\n }\nabstractDateMeasureParser\n description Year/month/day in ISO 8601, US, European formats.\n atoms measureNameAtom dateAtom\n extends abstractMeasureParser\n string typeForWebForms date\n javascript\n get measureValue() {\n const {content} = this\n if (!content) return \"\"\n const {dayjs} = this.root\n try {\n // First try parsing with dayjs\n const parsed = dayjs(content)\n if (parsed.isValid())\n return parsed.format(\"YYYY-MM-DD\")\n // Try parsing other common formats\n const formats = [\n \"MM/DD/YYYY\",\n \"DD/MM/YYYY\", \n \"YYYY/MM/DD\",\n \"MM-DD-YYYY\",\n \"DD-MM-YYYY\",\n \"YYYY-MM-DD\",\n \"DD.MM.YYYY\",\n \"YYYY.MM.DD\"\n ]\n for (const format of formats) {\n const attempt = dayjs(content, format)\n if (attempt.isValid())\n return attempt.format(\"YYYY-MM-DD\")\n }\n } catch (err) {\n console.error(err)\n return \"\"\n }\n return \"\"\n }\n get valueAsTimestamp() {\n const {measureValue} = this\n return measureValue ? this.root.dayjs(measureValue).unix() : \"\"\n }\nmetaTagsParser\n popularity 0.007693\n cueFromId\n extends abstractScrollParser\n description Print meta tags including title.\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n const {root} = this\n const { title, description, canonicalUrl, gitRepo, scrollVersion, openGraphImage, keywords } = root\n const rssFeedUrl = root.get(\"rssFeedUrl\")\n const favicon = root.get(\"favicon\")\n const faviconTag = favicon ? `<link rel=\"icon\" href=\"${favicon}\">` : \"\"\n const keywordsTag = keywords ? `<meta name=\"keywords\" content=\"${keywords}\">` : \"\"\n const rssTag = rssFeedUrl ? `<link rel=\"alternate\" type=\"application/rss+xml\" title=\"${title}\" href=\"${rssFeedUrl}\">` : \"\"\n const gitTag = gitRepo ? `<link rel=\"source\" type=\"application/git\" title=\"Source Code Repository\" href=\"${gitRepo}\">` : \"\"\n return `<head>\n <meta charset=\"utf-8\">\n <title>${title}</title>\n <script>/* This HTML was generated by 📜 Scroll v${scrollVersion}. https://scroll.pub */</script>\n <style>@media print {.doNotPrint {display: none !important;}}</style>\n <link rel=\"canonical\" href=\"${canonicalUrl}\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n <meta name=\"description\" content=\"${description}\">\n ${keywordsTag}\n <meta name=\"generator\" content=\"Scroll v${scrollVersion}\">\n <meta property=\"og:title\" content=\"${title}\">\n <meta property=\"og:description\" content=\"${description}\">\n <meta property=\"og:image\" content=\"${openGraphImage}\">\n ${faviconTag}\n ${gitTag}\n ${rssTag}\n <meta name=\"twitter:card\" content=\"summary_large_image\">\n </head>\n <body>`\n }\nquoteParser\n popularity 0.001471\n cueFromId\n description A quote.\n catchAllParser quoteLineParser\n extends abstractScrollParser\n javascript\n buildHtml() {\n return `<blockquote class=\"scrollQuote\">${this.subparticlesToString()}</blockquote>`\n }\n buildTxt() {\n return this.subparticlesToString()\n }\nredirectToParser\n popularity 0.000072\n description HTML redirect tag.\n extends abstractScrollParser\n atoms cueAtom urlAtom\n cueFromId\n example\n redirectTo https://scroll.pub/releaseNotes.html\n javascript\n buildHtml() {\n return `<meta http-equiv=\"Refresh\" content=\"0; url='${this.getAtom(1)}'\" />`\n }\nabstractVariableParser\n extends abstractScrollParser\n catchAllAtomType stringAtom\n atoms preBuildCommandAtom\n cueFromId\n javascript\n isTopMatter = true\n buildHtml() {\n return \"\"\n }\nreplaceParser\n description Replace this with that.\n extends abstractVariableParser\n baseParser blobParser\n example\n replace YEAR 2022\nreplaceJsParser\n description Replace this with evaled JS.\n extends replaceParser\n catchAllAtomType javascriptAnyAtom\n example\n replaceJs SUM 1+1\n * 1+1 = SUM\nreplaceNodejsParser\n description Replace with evaled Node.JS.\n extends abstractVariableParser\n catchAllAtomType javascriptAnyAtom\n baseParser blobParser\n example\n replaceNodejs\n module.exports = {SCORE : 1 + 2}\n * The score is SCORE\ntoFooterParser\n extends abstractScrollParser\n description Experimental way to move a section to the footer.\n atoms preBuildCommandAtom\n cueFromId\nrunScriptParser\n popularity 0.000024\n description Run script and dump stdout.\n extends abstractScrollParser\n atoms cueAtom urlAtom\n cue run\n int filenameIndex 1\n javascript\n get dependencies() { return [this.filename]}\n results = \"Not yet run\"\n async execute() {\n if (!this.filename) return\n await this.root.fetch(this.filename)\n // todo: make async\n const { execSync } = require(\"child_process\")\n this.results = execSync(this.command)\n }\n get command() {\n const path = this.root.path\n const {filename }= this\n const fullPath = this.root.makeFullPath(filename)\n const ext = path.extname(filename).slice(1)\n const interpreterMap = {\n php: \"php\",\n py: \"python3\",\n rb: \"ruby\",\n pl: \"perl\",\n sh: \"sh\"\n }\n return [interpreterMap[ext], fullPath].join(\" \")\n }\n buildHtml() {\n return this.buildTxt()\n }\n get filename() {\n return this.getAtom(this.filenameIndex)\n }\n buildTxt() {\n return this.results.toString().trim()\n }\nquickRunScriptParser\n extends runScriptParser\n atoms urlAtom\n pattern ^[^\\s]+\\.(py|pl|sh|rb|php)$\n int filenameIndex 0\nendSnippetParser\n popularity 0.004293\n description Cut for snippet here.\n extends abstractScrollParser\n cueFromId\n javascript\n buildHtml() {\n return \"\"\n }\ntoStampParser\n description Print a directory to stamp.\n extends abstractScrollParser\n catchAllAtomType filePathAtom\n cueFromId\n javascript\n buildTxt() {\n return this.makeStamp(this.content)\n }\n buildHtml() {\n return `<pre>${this.buildTxt()}</pre>`\n }\n makeStamp(dir) {\n const fs = require('fs');\n const path = require('path');\n const { execSync } = require('child_process');\n let stamp = 'stamp\\n';\n const handleFile = (indentation, relativePath, itemPath, ) => {\n stamp += `${indentation}${relativePath}\\n`;\n const content = fs.readFileSync(itemPath, 'utf8');\n stamp += `${indentation} ${content.replace(/\\n/g, `\\n${indentation} `)}\\n`;\n }\n let gitTrackedFiles\n function processDirectory(currentPath, depth) {\n const items = fs.readdirSync(currentPath);\n items.forEach(item => {\n const itemPath = path.join(currentPath, item);\n const relativePath = path.relative(dir, itemPath);\n //if (!gitTrackedFiles.has(item)) return\n const stats = fs.statSync(itemPath);\n const indentation = ' '.repeat(depth);\n if (stats.isDirectory()) {\n stamp += `${indentation}${relativePath}/\\n`;\n processDirectory(itemPath, depth + 1);\n } else if (stats.isFile())\n handleFile(indentation, relativePath, itemPath)\n });\n }\n const stats = fs.statSync(dir);\n if (stats.isDirectory()) {\n // Get list of git-tracked files\n gitTrackedFiles = new Set(execSync('git ls-files', { cwd: dir, encoding: 'utf-8' })\n .split('\\n')\n .filter(Boolean))\n processDirectory(dir, 1)\n }\n else\n handleFile(\" \", dir, dir)\n return stamp.trim();\n }\nstampParser\n description Expand project template to disk.\n extends abstractScrollParser\n inScope stampFolderParser\n catchAllParser stampFileParser\n example\n stamp\n .gitignore\n *.html\n readme.scroll\n # Hello world\n <script src=\"scripts/nested/hello.js\"></script>\n scripts/\n nested/\n hello.js\n console.log(\"Hello world\")\n cueFromId\n atoms preBuildCommandAtom\n javascript\n execute() {\n const dir = this.root.folderPath\n this.forEach(particle => particle.execute(dir))\n }\nscrollStumpParser\n cue stump\n extends abstractScrollParser\n description Compile Stump to HTML.\n catchAllParser stumpContentParser\n javascript\n buildHtml() {\n const {stumpParser} = this\n return new stumpParser(this.subparticlesToString()).compile()\n }\n get stumpParser() {\n return this.isNodeJs() ? require(\"scrollsdk/products/stump.nodejs.js\") : stumpParser\n }\nstumpNoSnippetParser\n popularity 0.010177\n // todo: make noSnippets an aftertext directive?\n extends scrollStumpParser\n description Compile Stump unless snippet.\n cueFromId\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\nplainTextParser\n description Plain text oneliner or block.\n cueFromId\n extends abstractScrollParser\n catchAllParser plainTextLineParser\n catchAllAtomType stringAtom\n javascript\n buildHtml() {\n return this.buildTxt()\n }\n buildTxt() {\n return `${this.content ?? \"\"}${this.subparticlesToString()}`\n }\nplainTextOnlyParser\n popularity 0.000072\n extends plainTextParser\n description Only print for buildTxt.\n javascript\n buildHtml() {\n return \"\"\n }\nscrollThemeParser\n popularity 0.007524\n boolean isPopular true\n cue theme\n example\n theme gazette\n extends abstractScrollParser\n catchAllAtomType scrollThemeAtom\n description A collection of simple themes.\n string copyFromExternal .gazette.css\n // Note this will be replaced at runtime\n javascript\n get copyFromExternal() {\n return this.files.join(\" \")\n }\n get files() {\n return this.atoms.slice(1).map(name => `.${name}.css`).concat([\".scroll.css\"])\n }\n buildHtml() {\n return this.files.map(name => `<link rel=\"stylesheet\" type=\"text/css\" href=\"${name}\">`).join(\"\\n\")\n }\nabstractAftertextAttributeParser\n atoms cueAtom\n boolean isAttribute true\n javascript\n get htmlAttributes() {\n return `${this.cue}=\"${this.content}\"`\n }\n buildHtml() {\n return \"\"\n }\naftertextIdParser\n popularity 0.000145\n cue id\n description Provide an ID to be output in the generated HTML tag.\n extends abstractAftertextAttributeParser\n atoms cueAtom htmlIdAtom\n single\naftertextStyleParser\n popularity 0.000217\n cue style\n description Set HTML style attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType cssAnyAtom\n javascript\n htmlAttributes = \"\" // special case this one\n get css() { return `${this.property}:${this.content};` }\naftertextFontParser\n popularity 0.000217\n cue font\n description Set font.\n extends aftertextStyleParser\n atoms cueAtom fontFamilyAtom\n catchAllAtomType cssAnyAtom\n string property font-family\n javascript\n get css() {\n if (this.content === \"Slim\") return \"font-family:Helvetica Neue; font-weight:100;\"\n return super.css\n }\naftertextColorParser\n popularity 0.000217\n cue color\n description Set font color.\n extends aftertextStyleParser\n catchAllAtomType cssAnyAtom\n string property color\n example\n color blue\naftertextHrefParser\n popularity 0.000217\n cue href\n description Set HTML href attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom urlAtom\naftertextSrcParser\n extends aftertextHrefParser\n cue src\n description Set HTML src attribute.\naftertextOnclickParser\n popularity 0.000217\n cue onclick\n description Set HTML onclick attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType javascriptAnyAtom\naftertextHiddenParser\n cue hidden\n atoms cueAtom\n description Do not compile this particle to HTML.\n extends abstractAftertextAttributeParser\n single\naftertextValueParser\n popularity 0.000217\n cue value\n description Set HTML value attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextForParser\n popularity 0.000217\n cue for\n description Set HTML for attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom htmlAnyAtom\naftertextPlaceholderParser\n popularity 0.000217\n cue placeholder\n description Set HTML placeholder attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextRowsParser\n popularity 0.000217\n cue rows\n description Set HTML rows attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom integerAtom\naftertextTypeParser\n popularity 0.000217\n cue type\n description Set HTML type attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom htmlTypeAtom\naftertextAltParser\n popularity 0.000217\n cue alt\n description Set HTML alt attribute for images.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextTitleParser\n popularity 0.000217\n cue title\n description Set HTML title attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextNameParser\n popularity 0.000217\n cue name\n description Set HTML name attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextOnsubmitParser\n popularity 0.000217\n cue onsubmit\n description Set HTML onsubmit attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType javascriptAnyAtom\naftertextClassParser\n popularity 0.000217\n cue class\n description Set HTML class attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType classNameAtom\naftertextMaxlengthParser\n popularity 0.000217\n cue maxlength\n description Set HTML maxlength attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom integerAtom\naftertextPatternParser\n popularity 0.000217\n cue pattern\n description Set HTML pattern attribute for input validation.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextRequiredParser\n popularity 0.000217\n cue required\n description Set HTML required attribute.\n extends abstractAftertextAttributeParser\n single\naftertextDisabledParser\n popularity 0.000217\n cue disabled\n description Set HTML disabled attribute.\n extends abstractAftertextAttributeParser\n single\naftertextReadonlyParser\n popularity 0.000217\n cue readonly\n description Set HTML readonly attribute.\n extends abstractAftertextAttributeParser\n single\naftertextAriaLabelParser\n popularity 0.000217\n cue aria-label\n description Set ARIA label for accessibility.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextTargetParser\n popularity 0.000217\n cue target\n description Set HTML target attribute for links.\n extends abstractAftertextAttributeParser\n atoms cueAtom htmlAnyAtom\naftertextContentParser\n popularity 0.000217\n cue content\n description Set HTML content attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextDataParser\n popularity 0.000217\n pattern ^data\\-\n description Set HTML data- attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom\n catchAllAtomType htmlAnyAtom\n example\n div My score\n data-score 100\naftertextTagParser\n atoms cueAtom htmlTagAtom\n description Override the HTML tag that the compiled particle will use.\n cue tag\n javascript\n buildHtml() {\n return \"\"\n }\nabstractAftertextDirectiveParser\n atoms cueAtom\n catchAllAtomType stringAtom\n javascript\n isMarkup = true\n buildHtml() {\n return \"\"\n }\n getErrors() {\n const errors = super.getErrors()\n if (!this.isMarkup || this.matchWholeLine) return errors\n const inserts = this.getInserts(this.parent.originalTextPostLinkify)\n // todo: make AbstractParticleError class exported by sdk to allow Parsers to define their own error types.\n // todo: also need to be able to map lines back to their line in source (pre-imports)\n if (!inserts.length)\n errors.push(this.makeError(`No match found for \"${this.getLine()}\".`))\n return errors\n }\n get pattern() {\n return this.getAtomsFrom(1).join(\" \")\n }\n get shouldMatchAll() {\n return this.has(\"matchAll\")\n }\n getMatches(text) {\n const { pattern } = this\n const escapedPattern = pattern.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\")\n return [...text.matchAll(new RegExp(escapedPattern, \"g\"))].map(match => {\n const { index } = match\n const endIndex = index + pattern.length\n return [\n { index, string: `<${this.openTag}${this.allAttributes}>`, endIndex },\n { index: endIndex, endIndex, string: `</${this.closeTag}>` }\n ]\n })\n }\n getInserts(text) {\n const matches = this.getMatches(text)\n if (!matches.length) return false\n if (this.shouldMatchAll) return matches.flat()\n const match = this.getParticle(\"match\")\n if (match)\n return match.indexes\n .map(index => matches[index])\n .filter(i => i)\n .flat()\n return matches[0]\n }\n get allAttributes() {\n const attr = this.attributes.join(\" \")\n return attr ? \" \" + attr : \"\"\n }\n get attributes() {\n return []\n }\n get openTag() {\n return this.tag\n }\n get closeTag() {\n return this.tag\n }\nabstractMarkupParser\n extends abstractAftertextDirectiveParser\n inScope abstractMarkupParameterParser\n javascript\n get matchWholeLine() {\n return this.getAtomsFrom(this.patternStartsAtAtom).length === 0\n }\n get pattern() {\n return this.matchWholeLine ? this.parent.originalText : this.getAtomsFrom(this.patternStartsAtAtom).join(\" \")\n }\n patternStartsAtAtom = 1\nboldParser\n popularity 0.000096\n cueFromId\n description Bold matching text.\n extends abstractMarkupParser\n javascript\n tag = \"b\"\nitalicsParser\n popularity 0.000241\n cueFromId\n description Italicize matching text.\n extends abstractMarkupParser\n javascript\n tag = \"i\"\nunderlineParser\n popularity 0.000024\n description Underline matching text.\n cueFromId\n extends abstractMarkupParser\n javascript\n tag = \"u\"\nafterTextCenterParser\n popularity 0.000193\n description Center paragraph.\n cue center\n extends abstractMarkupParser\n javascript\n tag = \"center\"\naftertextCodeParser\n popularity 0.000145\n description Wrap matching text in code span.\n cue code\n extends abstractMarkupParser\n javascript\n tag = \"code\"\naftertextStrikeParser\n popularity 0.000048\n description Wrap matching text in s span.\n cue strike\n extends abstractMarkupParser\n javascript\n tag = \"s\"\naddClassMarkupParser\n popularity 0.000772\n description Add a custom class to parent element. Provide query to add span matching text.\n extends abstractMarkupParser\n atoms cueAtom classNameAtom\n cue addClass\n javascript\n tag = \"span\"\n get applyToParentElement() {\n return this.atoms.length === 2\n }\n getInserts(text) {\n // If no select text is added, set the class on the parent element.\n if (this.applyToParentElement) return []\n return super.getInserts(text)\n }\n get className() {\n return this.getAtom(1)\n }\n get attributes() {\n return [`class=\"${this.className}\"`]\n }\n get matchWholeLine() {\n return this.applyToParentElement\n }\n get pattern() {\n return this.matchWholeLine ? this.parent.content : this.getAtomsFrom(2).join(\" \")\n }\nhoverNoteParser\n popularity 0.000265\n description Add a caveat viewable on hover on matching text. When you want to be sure you've thoroughly addressed obvious concerns but ones that don't warrant to distract from the main argument of the text.\n cueFromId\n extends addClassMarkupParser\n catchAllParser lineOfTextParser\n atoms cueAtom\n javascript\n get pattern() {\n return this.getAtomsFrom(1).join(\" \")\n }\n get attributes() {\n return [`class=\"scrollHoverNote\"`, `title=\"${this.hoverNoteText}\"`]\n }\n get hoverNoteText() {\n return this.subparticlesToString().replace(/\\n/g, \" \")\n }\nscrollLinkParser\n popularity 0.008706\n extends abstractMarkupParser\n description Put the matching text in an <a> tag.\n atoms cueAtom urlAtom\n inScope linkTitleParser linkTargetParser abstractCommentParser\n programParser\n description Anything here will be URI encoded and then appended to the link.\n cueFromId\n atoms cueAtom\n catchAllParser programLinkParser\n javascript\n get encoded() {\n return encodeURIComponent(this.subparticlesToString())\n }\n cue link\n javascript\n tag = \"a\"\n buildTxt() {\n return this.root.ensureAbsoluteLink(this.link) + \" \" + this.pattern\n }\n get link() {\n const {baseLink} = this\n if (this.has(\"program\"))\n return baseLink + this.getParticle(\"program\").encoded\n return baseLink\n }\n get baseLink() {\n const link = this.getAtom(1)\n const isAbsoluteLink = link.includes(\"://\")\n if (isAbsoluteLink) return link\n const relativePath = this.parent.buildSettings?.relativePath || \"\"\n return relativePath + link\n }\n get linkAttribute() {\n return \"href\"\n }\n get attributes() {\n const attrs = [`${this.linkAttribute}=\"${this.link}\"`]\n const options = [\"title\", \"target\"]\n options.forEach(option => {\n const particle = this.getParticle(option)\n if (particle) attrs.push(`${option}=\"${particle.content}\"`)\n })\n return attrs\n }\n patternStartsAtAtom = 2\nscrollClickParser\n extends scrollLinkParser\n description An a tag with an onclick.\n cue click\n javascript\n get linkAttribute() {\n return \"onclick\"\n }\nemailLinkParser\n popularity 0.000048\n description A mailto link\n cue email\n extends scrollLinkParser\n javascript\n get attributes() {\n return [`href=\"mailto:${this.link}\"`]\n }\nquickLinkParser\n popularity 0.029228\n pattern ^https?\\:\n extends scrollLinkParser\n atoms urlAtom\n javascript\n get link() {\n return this.cue\n }\n patternStartsAtAtom = 1\nquickRelativeLinkParser\n popularity 0.029228\n description Relative links.\n // note: only works if relative link ends in .html\n pattern ^[^\\s]+\\.(html|htm)\n extends scrollLinkParser\n atoms urlAtom\n javascript\n get link() {\n return this.cue\n }\n patternStartsAtAtom = 1\ndatelineParser\n popularity 0.006005\n cueFromId\n description Gives your paragraph a dateline like \"December 15, 2021 — The...\"\n extends abstractAftertextDirectiveParser\n javascript\n getInserts() {\n const {day} = this\n if (!day) return false\n return [{ index: 0, string: `<span class=\"scrollDateline\">${day} — </span>` }]\n }\n matchWholeLine = true\n get day() {\n let day = this.content || this.root.date\n if (!day) return \"\"\n return this.root.dayjs(day).format(`MMMM D, YYYY`)\n }\ndayjsParser\n description Advanced directive that evals some Javascript code in an environment including \"dayjs\".\n cueFromId\n extends abstractAftertextDirectiveParser\n javascript\n getInserts() {\n const dayjs = this.root.dayjs\n const days = eval(this.content)\n const index = this.parent.originalTextPostLinkify.indexOf(\"days\")\n return [{ index, string: `${days} ` }]\n }\ninlineMarkupsOnParser\n popularity 0.000024\n cueFromId\n description Enable these inline markups only.\n example\n Hello *world*!\n inlineMarkupsOn bold\n extends abstractAftertextDirectiveParser\n catchAllAtomType inlineMarkupNameAtom\n javascript\n get shouldMatchAll() {\n return true\n }\n get markups() {\n const {root} = this\n let markups = [{delimiter: \"`\", tag: \"code\", exclusive: true, name: \"code\"},{delimiter: \"*\", tag: \"strong\", name: \"bold\"}, {delimiter: \"_\", tag: \"em\", name: \"italics\"}]\n // only add katex markup if the root doc has katex.\n if (root.has(\"katex\"))\n markups.unshift({delimiter: \"$\", tag: \"span\", attributes: ' class=\"scrollKatex\"', exclusive: true, name: \"katex\"})\n if (this.content)\n return markups.filter(markup => this.content.includes(markup.name))\n if (root.has(\"inlineMarkups\")) {\n root.getParticle(\"inlineMarkups\").forEach(markup => {\n const delimiter = markup.getAtom(0)\n const tag = markup.getAtom(1)\n // todo: add support for providing custom functions for inline markups?\n // for example, !2+2! could run eval, or :about: could search a link map.\n const attributes = markup.getAtomsFrom(2).join(\" \")\n markups = markups.filter(mu => mu.delimiter !== delimiter) // Remove any overridden markups\n if (tag)\n markups.push({delimiter, tag, attributes})\n })\n }\n return markups\n }\n matchWholeLine = true\n getMatches(text) {\n const exclusives = []\n return this.markups.map(markup => this.applyMarkup(text, markup, exclusives)).filter(i => i).flat()\n }\n applyMarkup(text, markup, exclusives = []) {\n const {delimiter, tag, attributes} = markup\n const escapedDelimiter = delimiter.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\")\n const pattern = new RegExp(`${escapedDelimiter}[^${escapedDelimiter}]+${escapedDelimiter}`, \"g\")\n const delimiterLength = delimiter.length\n return [...text.matchAll(pattern)].map(match => {\n const { index } = match\n const endIndex = index + match[0].length\n // I'm too lazy to clean up sdk to write a proper inline markup parser so doing this for now.\n // The exclusive idea is to not try and apply bold or italic styles inside a TeX or code inline style.\n // Note that the way this is currently implemented any TeX in an inline code will get rendered, but code\n // inline of TeX will not. Seems like an okay tradeoff until a proper refactor and cleanup can be done.\n if (exclusives.some(exclusive => index >= exclusive[0] && index <= exclusive[1]))\n return undefined\n if (markup.exclusive)\n exclusives.push([index, endIndex])\n return [\n { index, string: `<${tag + (attributes ? \" \" + attributes : \"\")}>`, endIndex, consumeStartCharacters: delimiterLength },\n { index: endIndex, endIndex, string: `</${tag}>`, consumeEndCharacters: delimiterLength }\n ]\n }).filter(i => i)\n }\ninlineMarkupParser\n popularity 0.000169\n cueFromId\n atoms cueAtom delimiterAtom tagOrUrlAtom\n catchAllAtomType htmlAttributesAtom\n extends inlineMarkupsOnParser\n description Custom inline markup. for\n example\n @This@ will be in italics.\n inlineMarkup @ em\n javascript\n getMatches(text) {\n try {\n const delimiter = this.getAtom(1)\n const tag = this.getAtom(2)\n const attributes = this.getAtomsFrom(3).join(\" \")\n return this.applyMarkup(text, {delimiter, tag, attributes})\n } catch (err) {\n console.error(err)\n return []\n }\n // Note: doubling up doesn't work because of the consumption characters.\n }\nlinkifyParser\n description Use this to disable linkify on the text.\n extends abstractAftertextDirectiveParser\n cueFromId\n atoms cueAtom booleanAtom\nabstractMarkupParameterParser\n atoms cueAtom\n cueFromId\nmatchAllParser\n popularity 0.000024\n description Use this to match all occurrences of the text.\n extends abstractMarkupParameterParser\nmatchParser\n popularity 0.000048\n catchAllAtomType integerAtom\n description Use this to specify which index(es) to match.\n javascript\n get indexes() {\n return this.getAtomsFrom(1).map(num => parseInt(num))\n }\n example\n aftertext\n hello ello ello\n bold ello\n match 0 2\n extends abstractMarkupParameterParser\nabstractHtmlAttributeParser\n javascript\n buildHtml() {\n return \"\"\n }\nlinkTargetParser\n popularity 0.000024\n extends abstractHtmlAttributeParser\n description If you want to set the target of the link. To \"_blank\", for example.\n cue target\n atoms cueAtom codeAtom\nblankLineParser\n popularity 0.308149\n description Print nothing. Break section.\n atoms blankAtom\n boolean isPopular true\n javascript\n buildHtml() {\n return this.parent.clearSectionStack()\n }\n pattern ^$\n tags doNotSynthesize\nscrollFileAddressParser\n catchAllAtomType filePathAtom\n catchAllParser scrollFileAddressParser\nchatLineParser\n popularity 0.009887\n catchAllAtomType stringAtom\n catchAllParser chatLineParser\nlineOfCodeParser\n popularity 0.018665\n catchAllAtomType codeAtom\n catchAllParser lineOfCodeParser\ncommentLineParser\n catchAllAtomType commentAtom\ncssLineParser\n popularity 0.002870\n catchAllAtomType cssAnyAtom\n catchAllParser cssLineParser\nabstractTableTransformParser\n atoms cueAtom\n inScope abstractTableVisualizationParser abstractTableTransformParser h1Parser h2Parser scrollQuestionParser htmlInlineParser scrollBrParser slashCommentParser\n javascript\n get coreTable() {\n return this.parent.coreTable\n }\n get columnNames() {\n return this.parent.columnNames\n }\n connectColumnNames(userColumnNames, availableColumnNames = this.parent.columnNames) {\n const result = {}\n const normalize = str => str.toLowerCase().trim()\n userColumnNames.forEach(userColumn => {\n // Strategy 1: Exact match\n const exactMatch = availableColumnNames.find(col => col === userColumn)\n if (exactMatch) {\n result[userColumn] = exactMatch\n return\n }\n // Strategy 2: Case-insensitive match\n const normalizedUserColumn = normalize(userColumn)\n const caseInsensitiveMatch = availableColumnNames.find(col => normalize(col) === normalizedUserColumn)\n if (caseInsensitiveMatch) {\n result[userColumn] = caseInsensitiveMatch\n return\n }\n // Strategy 3: Levenshtein distance match\n const THRESHOLD = 2 // Consider matches with distance <= 2 as \"very close\"\n let bestMatch = null\n let bestDistance = Infinity\n availableColumnNames.forEach(col => {\n const distance = this.root.levenshteinDistance(userColumn, col)\n if (distance < bestDistance) {\n bestDistance = distance\n bestMatch = col\n }\n })\n // Only use Levenshtein match if it's very close\n if (bestDistance <= THRESHOLD) {\n result[userColumn] = bestMatch\n return\n }\n // Strategy 4: Fallback - use original unmatched name\n result[userColumn] = userColumn\n })\n return result\n }\n connectColumnName(name) {\n return this.connectColumnNames([name])[name]\n }\n getErrors() {\n const errors = super.getErrors()\n if (errors.length && this.previous.cue !== \"assertIgnoreBelowErrors\")\n return errors\n return []\n }\n getRunTimeEnumOptions(atom) {\n if (atom.atomTypeId === \"columnNameAtom\")\n return this.parent.columnNames\n return super.getRunTimeEnumOptions(atom)\n }\n getRunTimeEnumOptionsForValidation(atom) {\n // Note: this will fail if the CSV file hasnt been built yet.\n if (atom.atomTypeId === \"columnNameAtom\")\n return this.parent.columnNames.concat(this.parent.columnNames.map(c => \"-\" + c)) // Add reverse names\n return super.getRunTimeEnumOptions(atom)\n }\nabstractDateSplitTransformParser\n extends abstractTableTransformParser\n atoms cueAtom\n catchAllAtomType columnNameAtom\n javascript\n get coreTable() {\n const columnName = this.getAtom(1) || this.detectDateColumn()\n if (!columnName) return this.parent.coreTable\n return this.parent.coreTable.map(row => {\n const newRow = {...row}\n try {\n const date = this.root.dayjs(row[columnName])\n if (date.isValid())\n newRow[this.newColumnName] = this.transformDate(date)\n } catch (err) {}\n return newRow\n })\n }\n detectDateColumn() {\n const columns = this.parent.columnNames\n const dateColumns = ['date', 'created', 'published', 'timestamp']\n for (const col of dateColumns) {\n if (columns.includes(col)) return col\n }\n for (const col of columns) {\n const sample = this.parent.coreTable[0][col]\n if (sample && this.root.dayjs(sample).isValid())\n return col\n }\n return null\n }\n get columnNames() {\n return [...this.parent.columnNames, this.newColumnName]\n }\n transformDate(date) {\n const formatted = date.format(this.dateFormat)\n const isInt = !this.cue.includes(\"Name\")\n return isInt ? parseInt(formatted) : formatted\n }\nscrollSplitYearParser\n extends abstractDateSplitTransformParser\n description Extract year into new column.\n cue splitYear\n string newColumnName year\n string dateFormat YYYY\nscrollSplitDayNameParser\n extends abstractDateSplitTransformParser\n description Extract day name into new column.\n cue splitDayName\n string newColumnName dayName\n string dateFormat dddd\nscrollSplitMonthNameParser\n extends abstractDateSplitTransformParser\n description Extract month name into new column.\n cue splitMonthName\n string newColumnName monthName\n string dateFormat MMMM\nscrollSplitMonthParser\n extends abstractDateSplitTransformParser\n description Extract month number (1-12) into new column.\n cue splitMonth\n string newColumnName month\n string dateFormat M\nscrollSplitDayOfMonthParser\n extends abstractDateSplitTransformParser\n description Extract day of month (1-31) into new column.\n cue splitDayOfMonth\n string newColumnName dayOfMonth\n string dateFormat D\nscrollSplitDayOfWeekParser\n extends abstractDateSplitTransformParser\n description Extract day of week (0-6) into new column.\n cue splitDay\n string newColumnName day\n string dateFormat d\nscrollParseDateParser\n extends abstractTableTransformParser\n description Parse dates in a column into standard format.\n cue parseDate\n atoms cueAtom columnNameAtom\n example\n sampleData stocks.csv\n parseDate date\n linechart\n x date\n y price\n javascript\n get coreTable() {\n const columnName = this.connectColumnName(this.getAtom(1))\n const formatOut = this.get(\"format\") || \"YYYY-MM-DD\"\n const {dayjs} = this.root\n return this.parent.coreTable.map(row => {\n const newRow = {...row}\n try {\n const value = row[columnName]\n if (value) {\n const date = dayjs(value)\n if (date.isValid())\n newRow[columnName] = date.format(formatOut)\n }\n } catch (err) {\n console.error(`Error parsing date in column ${columnName}:`, err)\n }\n return newRow\n })\n }\n formatParser\n description Specify output date format\n atoms cueAtom stringAtom\n cueFromId\n single\nscrollGroupByParser\n catchAllAtomType columnNameAtom\n extends abstractTableTransformParser\n reduceParser\n description Specify how to aggregate a column when grouping data\n atoms cueAtom columnNameAtom reductionTypeAtom newColumnNameAtom\n cue reduce\n example\n data.csv\n groupBy year\n reduce score sum totalScore\n reduce name concat names\n printTable\n javascript\n get reduction() {\n return {\n source: this.getAtom(1),\n reduction: this.getAtom(2),\n name: this.getAtom(3) || this.getAtomsFrom(1).join(\"_\")\n }\n }\n description Combine rows with matching values into groups.\n example\n tables posts.csv\n groupBy year\n printTable\n cue groupBy\n javascript\n get coreTable() {\n if (this._coreTable) return this._coreTable\n const groupByColNames = this.getAtomsFrom(1)\n const {coreTable} = this.parent\n if (!groupByColNames.length) return coreTable\n const newCols = this.findParticles(\"reduce\").map(particle => particle.reduction)\n // Pivot is shorthand for group and reduce?\n const makePivotTable = (rows, groupByColumnNames, inputColumnNames, newCols) => {\n const colMap = {}\n inputColumnNames.forEach((col) => (colMap[col] = true))\n const groupByCols = groupByColumnNames.filter((col) => colMap[col])\n return new PivotTable(rows, inputColumnNames.map(c => {return {name: c}}), newCols).getNewRows(groupByCols)\n }\n class PivotTable {\n constructor(rows, inputColumns, outputColumns) {\n this._columns = {}\n this._rows = rows\n inputColumns.forEach((col) => (this._columns[col.name] = col))\n outputColumns.forEach((col) => (this._columns[col.name] = col))\n }\n _getGroups(allRows, groupByColNames) {\n const rowsInGroups = new Map()\n allRows.forEach((row) => {\n const groupKey = groupByColNames.map((col) => row[col]?.toString().replace(/ /g, \"\") || \"\").join(\" \")\n if (!rowsInGroups.has(groupKey)) rowsInGroups.set(groupKey, [])\n rowsInGroups.get(groupKey).push(row)\n })\n return rowsInGroups\n }\n getNewRows(groupByCols) {\n // make new particles\n const rowsInGroups = this._getGroups(this._rows, groupByCols)\n // Any column in the group should be reused by the children\n const columns = [\n {\n name: \"count\",\n type: \"number\",\n min: 0,\n },\n ]\n groupByCols.forEach((colName) => columns.push(this._columns[colName]))\n const colsToReduce = Object.values(this._columns).filter((col) => !!col.reduction)\n colsToReduce.forEach((col) => columns.push(col))\n // for each group\n const rows = []\n const totalGroups = rowsInGroups.size\n for (let [groupId, group] of rowsInGroups) {\n const firstRow = group[0]\n const newRow = {}\n groupByCols.forEach((col) =>\n newRow[col] = firstRow ? firstRow[col] : 0\n )\n newRow.count = group.length\n // todo: add more reductions? count, stddev, median, variance.\n colsToReduce.forEach((col) => {\n const sourceColName = col.source\n const reduction = col.reduction\n const newColName = col.name\n if (reduction === \"concat\") {\n newRow[newColName] = group.map((row) => row[sourceColName]).join(\" \")\n return \n }\n if (reduction === \"first\") {\n newRow[newColName] = group.find((row) => row[sourceColName] !== \"\")?.[sourceColName]\n return \n }\n const values = group.map((row) => row[sourceColName]).filter((val) => typeof val === \"number\" && !isNaN(val))\n let reducedValue = firstRow[sourceColName]\n if (reduction === \"sum\") reducedValue = values.reduce((prev, current) => prev + current, 0)\n if (reduction === \"max\") reducedValue = Math.max(...values)\n if (reduction === \"min\") reducedValue = Math.min(...values)\n if (reduction === \"mean\") reducedValue = values.reduce((prev, current) => prev + current, 0) / values.length\n newRow[newColName] = reducedValue\n })\n rows.push(newRow)\n }\n // todo: add tests. figure out this api better.\n Object.values(columns).forEach((col) => {\n // For pivot columns, remove the source and reduction info for now. Treat things as immutable.\n delete col.source\n delete col.reduction\n })\n return {\n rows,\n columns,\n }\n }\n }\n const pivotTable = makePivotTable(coreTable, groupByColNames, this.parent.columnNames, newCols)\n this._coreTable = pivotTable.rows\n this._columnNames = pivotTable.columns.map(col => col.name)\n return pivotTable.rows\n }\n get columnNames() {\n const {coreTable} = this\n return this._columnNames || this.parent.columnNames\n }\nscrollWhereParser\n extends abstractTableTransformParser\n description Filter rows by condition.\n cue where\n atoms cueAtom columnNameAtom comparisonAtom\n catchAllAtomType constantAtom\n example\n table iris.csv\n where Species = setosa\n javascript\n get coreTable() {\n // todo: use atoms here.\n const columnName = this.connectColumnName(this.getAtom(1))\n const operator = this.getAtom(2)\n let untypedComparisonValue = this.getAtom(3)\n const typedComparisonValue = isNaN(parseFloat(untypedComparisonValue)) ? untypedComparisonValue : parseFloat(untypedComparisonValue)\n const coreTable = this.parent.coreTable\n if (!columnName || !operator || (untypedComparisonValue === undefined && !operator.includes(\"mpty\"))) return coreTable\n const filterFn = row => {\n const atom = row[columnName]\n const typedAtom = atom === null ? undefined : atom // convert nulls to undefined\n if (operator === \"=\") return typedComparisonValue === typedAtom\n else if (operator === \"!=\") return typedComparisonValue !== typedAtom\n else if (operator === \"includes\") return typedAtom !== undefined && typedAtom.includes(typedComparisonValue)\n else if (operator === \"startsWith\") return typedAtom !== undefined && typedAtom.toString().startsWith(typedComparisonValue)\n else if (operator === \"endsWith\") return typedAtom !== undefined && typedAtom.toString().endsWith(typedComparisonValue)\n else if (operator === \"doesNotInclude\") return typedAtom === undefined || !typedAtom.includes(typedComparisonValue)\n else if (operator === \">\") return typedAtom > typedComparisonValue\n else if (operator === \"<\") return typedAtom < typedComparisonValue\n else if (operator === \">=\") return typedAtom >= typedComparisonValue\n else if (operator === \"<=\") return typedAtom <= typedComparisonValue\n else if (operator === \"empty\") return typedAtom === \"\" || typedAtom === undefined\n else if (operator === \"notEmpty\") return typedAtom !== \"\" && typedAtom !== undefined\n }\n return coreTable.filter(filterFn)\n }\nscrollSelectParser\n catchAllAtomType columnNameAtom\n extends abstractTableTransformParser\n description Drop all columns except these.\n example\n tables\n data\n name,year,count\n index,2022,2\n about,2023,4\n select name year\n printTable\n cue select\n javascript\n get coreTable() {\n const {coreTable} = this.parent\n const {columnNames} = this\n if (!columnNames.length) return coreTable\n return coreTable.map(row => Object.fromEntries(columnNames.map(colName => [colName, row[colName]])))\n }\n get columnNames() {\n if (!this._columnNames) {\n const names = this.getAtomsFrom(1)\n this._columnNamesMap = this.connectColumnNames(names)\n this._columnNames = names.map(name => this._columnNamesMap[name])\n }\n return this._columnNames\n }\nscrollReverseParser\n extends abstractTableTransformParser\n description Reverse rows.\n cue reverse\n javascript\n get coreTable() {\n return this.parent.coreTable.slice().reverse()\n }\nscrollComposeParser\n extends abstractTableTransformParser\n description Add column using format string.\n catchAllAtomType codeAtom\n cue compose\n atoms cueAtom newColumnNameAtom\n example\n table\n compose sentence My name is {name}\n printTable\n javascript\n get coreTable() {\n const {newColumnName} = this\n const formatString = this.getAtomsFrom(2).join(\" \")\n return this.parent.coreTable.map((row, index) => {\n const newRow = Object.assign({}, row)\n newRow[newColumnName] = this.evaluate(new Particle(row).evalTemplateString(formatString), index)\n return newRow\n })\n }\n evaluate(str) {\n return str\n }\n get newColumnName() {\n return this.atoms[1]\n }\n get columnNames() {\n return this.parent.columnNames.concat(this.newColumnName)\n }\nscrollComputeParser\n extends scrollComposeParser\n description Add column by evaling format string.\n cue compute\n javascript\n evaluate(str) {\n return parseFloat(eval(str))\n }\nscrollEvalParser\n extends scrollComputeParser\n description Add column by evaling format string.\n cue eval\n javascript\n evaluate(str) {\n return eval(str)\n }\nscrollRankParser\n extends scrollComposeParser\n description Add rank column.\n atoms cueAtom\n string newColumnName rank\n cue rank\n javascript\n evaluate(str, index) { return index + 1 }\nscrollLinksParser\n extends abstractTableTransformParser\n description Add column with links.\n cue links\n catchAllAtomType columnNameAtom\n javascript\n get coreTable() {\n const {newColumnName, linkColumns} = this\n return this.parent.coreTable.map(row => {\n const newRow = Object.assign({}, row)\n let newValue = []\n linkColumns.forEach(name => {\n const value = newRow[name]\n delete newRow[name]\n if (value) newValue.push(`<a href=\"${value.includes(\"@\") ? \"mailto:\" : \"\"}${value}\">${name}</a>`)\n })\n newRow[newColumnName] = newValue.join(\" \")\n return newRow\n })\n }\n get newColumnName() {\n return \"links\"\n }\n get linkColumns() {\n return this.getAtomsFrom(1)\n }\n get columnNames() {\n const {linkColumns} = this\n return this.parent.columnNames.filter(name => !linkColumns.includes(name)).concat(this.newColumnName)\n }\nscrollLimitParser\n extends abstractTableTransformParser\n description Select a subset.\n cue limit\n atoms cueAtom integerAtom integerAtom\n javascript\n get coreTable() {\n let start = this.getAtom(1)\n let end = this.getAtom(2)\n if (end === undefined) {\n end = start\n start = 0\n }\n return this.parent.coreTable.slice(parseInt(start), parseInt(end))\n }\nscrollShuffleParser\n extends abstractTableTransformParser\n description Randomly reorder rows.\n cue shuffle\n example\n table data.csv\n shuffle\n printTable\n javascript\n get coreTable() {\n // Create a copy of the table to avoid modifying original\n const rows = this.parent.coreTable.slice()\n // Fisher-Yates shuffle algorithm\n for (let i = rows.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * (i + 1))\n ;[rows[i], rows[j]] = [rows[j], rows[i]]\n }\n return rows\n }\nscrollTransposeParser\n extends abstractTableTransformParser\n description Tranpose table.\n cue transpose\n javascript\n get coreTable() {\n // todo: we need to switch to column based coreTable, instead of row based\n const transpose = arr => Object.keys(arr[0]).map(key => [key, ...arr.map(row => row[key])]);\n return transpose(this.parent.coreTable)\n }\nscrollImputeParser\n extends abstractTableTransformParser\n description Impute missing values of a columm.\n atoms cueAtom columnNameAtom\n cue impute\n javascript\n get coreTable() {\n const {columnName} = this\n const sorted = this.root.lodash.orderBy(this.parent.coreTable.slice(), columnName)\n // ascending\n const imputed = []\n let lastInserted = sorted[0][columnName]\n sorted.forEach(row => {\n const measuredTime = row[columnName]\n while (measuredTime > lastInserted + 1) {\n lastInserted++\n // synthesize rows\n const imputedRow = {}\n imputedRow[columnName] = lastInserted\n imputedRow.count = 0\n imputed.push(imputedRow)\n }\n lastInserted = measuredTime\n imputed.push(row)\n })\n return imputed\n }\n get columnName() {\n return this.connectColumnName(this.getAtom(1))\n }\nscrollOrderByParser\n extends abstractTableTransformParser\n description Sort rows by column(s).\n catchAllAtomType columnNameAtom\n cue orderBy\n javascript\n get coreTable() {\n const makeLodashOrderByParams = str => {\n const part1 = str.split(\" \")\n const part2 = part1.map(col => (col.startsWith(\"-\") ? \"desc\" : \"asc\"))\n return [part1.map(col => this.connectColumnName(col.replace(/^\\-/, \"\"))), part2]\n }\n const orderBy = makeLodashOrderByParams(this.content)\n return this.root.lodash.orderBy(this.parent.coreTable.slice(), orderBy[0], orderBy[1])\n }\nassertRowCountParser\n extends abstractTableTransformParser\n description Test row count is expected value.\n atoms cueAtom integerAtom\n cueFromId\n javascript\n getErrors() {\n const errors = super.getErrors()\n const actualRows = this.coreTable.length\n const expectedRows = parseInt(this.content)\n if (actualRows !== expectedRows)\n return errors.concat(this.makeError(`Expected '${expectedRows}' rows but got '${actualRows}'.`))\n return errors\n }\nscrollRenameParser\n // todo: add support in Parsers for tuple catch alls\n catchAllAtomType columnNameAtom newColumnNameAtom\n catchAllAtomType newColumnNameAtom\n extends abstractTableTransformParser\n description Rename columns.\n example\n tables\n data\n name,year,count\n index,2022,2\n rename name Name year Year\n printTable\n cue rename\n javascript\n get coreTable() {\n const {coreTable} = this.parent\n const {renameMap} = this\n if (!Object.keys(renameMap).length) return coreTable\n return coreTable.map(row => {\n const newRow = {}\n Object.keys(row).forEach(key => {\n const name = renameMap[key] || key\n newRow[name] = row[key]\n })\n return newRow\n })\n }\n get renameMap() {\n const map = {}\n const pairs = this.getAtomsFrom(1)\n let oldName\n while (oldName = pairs.shift()) {\n map[oldName] = pairs.shift()\n }\n return map\n }\n _renamed\n get columnNames() {\n if (this._renamed)\n return this._renamed\n const {renameMap} = this\n this._renamed = this.parent.columnNames.map(name => renameMap[name] || name )\n return this._renamed\n }\nscrollSummarizeParser\n extends abstractTableTransformParser\n description Generate summary statistics for each column.\n cue summarize\n example\n table data.csv\n summarize\n printTable\n javascript\n get coreTable() {\n const {lodash} = this.root\n const sourceData = this.parent.coreTable\n if (!sourceData.length) return []\n return this.parent.columnNames.map(colName => {\n const values = sourceData.map(row => row[colName]).filter(val => val !== undefined && val !== null)\n const numericValues = values.filter(val => typeof val === \"number\" && !isNaN(val))\n const sorted = [...numericValues].sort((a, b) => a - b)\n // Calculate mode\n const frequency = {}\n values.forEach(val => {\n frequency[val] = (frequency[val] || 0) + 1\n })\n const mode = Object.entries(frequency)\n .sort((a, b) => b[1] - a[1])\n .map(entry => entry[0])[0]\n // Calculate median for numeric values\n const median = sorted.length ? \n sorted.length % 2 === 0 \n ? (sorted[sorted.length/2 - 1] + sorted[sorted.length/2]) / 2\n : sorted[Math.floor(sorted.length/2)]\n : null\n const sum = numericValues.length ? numericValues.reduce((a, b) => a + b, 0) : null\n const theType = typeof values[0]\n const count = values.length\n const mean = theType === \"number\" ? sum/count : \"\"\n return {\n name: colName,\n type: theType,\n incompleteCount: sourceData.length - values.length,\n uniqueCount: new Set(values).size,\n count,\n sum,\n median,\n mean,\n min: sorted.length ? sorted[0] : null,\n max: sorted.length ? sorted[sorted.length - 1] : null,\n mode\n }\n })\n }\n get columnNames() {\n return [\"name\", \"type\", \"incompleteCount\", \"uniqueCount\", \"count\", \"sum\", \"median\", \"mean\", \"min\", \"max\", \"mode\"]\n }\nerrorParser\n baseParser errorParser\nhakonContentParser\n popularity 0.102322\n catchAllAtomType codeAtom\nheatrixCatchAllParser\n popularity 0.000193\n // todo Fill this out\n catchAllAtomType stringAtom\nlineOfTextParser\n popularity 0.000289\n catchAllAtomType stringAtom\n boolean isTextParser true\nhtmlLineParser\n popularity 0.005209\n catchAllAtomType htmlAnyAtom\n catchAllParser htmlLineParser\nopenGraphParser\n // todo: fix Parsers scope issue so we can move this parser def under scrollImageParser\n description Add this line to make this the open graph image.\n cueFromId\n atoms cueAtom\nimportToFooterParser\n description Import to bottom of file.\n atoms preBuildCommandAtom\n cue footer\nscriptLineParser\n catchAllAtomType javascriptAnyAtom\n catchAllParser scriptLineParser\nlinkTitleParser\n popularity 0.000048\n description If you want to set the title of the link.\n cue title\n atoms cueAtom\n catchAllAtomType stringAtom\n example\n * This report showed the treatment had a big impact.\n https://example.com/report This report.\n title The average growth in the treatment group was 14.2x higher than the control group.\nprogramLinkParser\n popularity 0.000531\n catchAllAtomType codeAtom\nscrollMediaLoopParser\n popularity 0.000048\n cue loop\n atoms cueAtom\nscrollAutoplayParser\n cue autoplay\n atoms cueAtom\nabstractCompilerRuleParser\n catchAllAtomType anyAtom\n atoms cueAtom\ncloseSubparticlesParser\n extends abstractCompilerRuleParser\n description When compiling a parent particle to a string, this string is appended to the compiled and joined subparticles. Default is blank.\n cueFromId\nindentCharacterParser\n extends abstractCompilerRuleParser\n description You can change the indent character for compiled subparticles. Default is a space.\n cueFromId\ncatchAllAtomDelimiterParser\n description If a particle has a catchAllAtom, this is the string delimiter that will be used to join those atoms. Default is comma.\n extends abstractCompilerRuleParser\n cueFromId\nopenSubparticlesParser\n extends abstractCompilerRuleParser\n description When compiling a parent particle to a string, this string is prepended to the compiled and joined subparticles. Default is blank.\n cueFromId\nstringTemplateParser\n extends abstractCompilerRuleParser\n description This template string is used to compile this line, and accepts strings of the format: const var = {someAtomId}\n cueFromId\njoinSubparticlesWithParser\n description When compiling a parent particle to a string, subparticles are compiled to strings and joined by this character. Default is a newline.\n extends abstractCompilerRuleParser\n cueFromId\nabstractConstantParser\n description A constant.\n atoms cueAtom\n cueFromId\n // todo: make tags inherit\n tags actPhase\nparsersBooleanParser\n cue boolean\n atoms cueAtom constantIdentifierAtom\n catchAllAtomType booleanAtom\n extends abstractConstantParser\n tags actPhase\nparsersFloatParser\n cue float\n atoms cueAtom constantIdentifierAtom\n catchAllAtomType floatAtom\n extends abstractConstantParser\n tags actPhase\nparsersIntParser\n cue int\n atoms cueAtom constantIdentifierAtom\n catchAllAtomType integerAtom\n tags actPhase\n extends abstractConstantParser\nparsersStringParser\n cue string\n atoms cueAtom constantIdentifierAtom\n catchAllAtomType stringAtom\n catchAllParser catchAllMultilineStringConstantParser\n extends abstractConstantParser\n tags actPhase\nabstractParserRuleParser\n single\n atoms cueAtom\nabstractNonTerminalParserRuleParser\n extends abstractParserRuleParser\nparsersBaseParserParser\n atoms cueAtom baseParsersAtom\n description Set for blobs or errors. \n // In rare cases with untyped content you can use a blobParser, for now, to skip parsing for performance gains. The base errorParser will report errors when parsed. Use that if you don't want to implement your own error parser.\n extends abstractParserRuleParser\n cue baseParser\n tags analyzePhase\ncatchAllAtomTypeParser\n atoms cueAtom atomTypeIdAtom\n description Use for lists.\n // Aka 'listAtomType'. Use this when the value in a key/value pair is a list. If there are extra atoms in the particle's line, parse these atoms as this type. Often used with `listDelimiterParser`.\n extends abstractParserRuleParser\n cueFromId\n tags analyzePhase\natomParserParser\n atoms cueAtom atomParserAtom\n description Set parsing strategy.\n // prefix/postfix/omnifix parsing strategy. If missing, defaults to prefix.\n extends abstractParserRuleParser\n cueFromId\n tags experimental analyzePhase\ncatchAllParserParser\n description Attach this to unmatched lines.\n // If a parser is not found in the inScope list, instantiate this type of particle instead.\n atoms cueAtom parserIdAtom\n extends abstractParserRuleParser\n cueFromId\n tags acquirePhase\nparsersAtomsParser\n catchAllAtomType atomTypeIdAtom\n description Set required atomTypes.\n extends abstractParserRuleParser\n cue atoms\n tags analyzePhase\nparsersCompilerParser\n // todo Remove this and its subparticles?\n description Deprecated. For simple compilers.\n inScope stringTemplateParser catchAllAtomDelimiterParser openSubparticlesParser closeSubparticlesParser indentCharacterParser joinSubparticlesWithParser\n extends abstractParserRuleParser\n cue compiler\n tags deprecate\n boolean suggestInAutocomplete false\nparserDescriptionParser\n description Parser description.\n catchAllAtomType stringAtom\n extends abstractParserRuleParser\n cue description\n tags assemblePhase\nparsersExampleParser\n // todo Should this just be a \"string\" constant on particles?\n description Set example for docs and tests.\n catchAllAtomType exampleAnyAtom\n catchAllParser catchAllExampleLineParser\n extends abstractParserRuleParser\n cue example\n tags assemblePhase\nextendsParserParser\n cue extends\n tags assemblePhase\n description Extend another parser.\n // todo: add a catchall that is used for mixins\n atoms cueAtom parserIdAtom\n extends abstractParserRuleParser\nparsersPopularityParser\n // todo Remove this parser. Switch to conditional frequencies.\n description Parser popularity.\n atoms cueAtom floatAtom\n extends abstractParserRuleParser\n cue popularity\n tags assemblePhase\ninScopeParser\n description Parsers in scope.\n catchAllAtomType parserIdAtom\n extends abstractParserRuleParser\n cueFromId\n tags acquirePhase\nparsersJavascriptParser\n // todo Urgently need to get submode syntax highlighting running! (And eventually LSP)\n description Javascript code for Parser Actions.\n catchAllParser catchAllJavascriptCodeLineParser\n extends abstractParserRuleParser\n tags actPhase\n javascript\n format() {\n if (this.isNodeJs()) {\n const template = `class FOO{ ${this.subparticlesToString()}}`\n this.setSubparticles(\n require(\"prettier\")\n .format(template, { semi: false, useTabs: true, parser: \"babel\", printWidth: 240 })\n .replace(/class FOO \\{\\s+/, \"\")\n .replace(/\\s+\\}\\s+$/, \"\")\n .replace(/\\n\\t/g, \"\\n\") // drop one level of indent\n .replace(/\\t/g, \" \") // we used tabs instead of spaces to be able to dedent without breaking literals.\n )\n }\n return this\n }\n cue javascript\nabstractParseRuleParser\n // Each particle should have a pattern that it matches on unless it's a catch all particle.\n extends abstractParserRuleParser\n cueFromId\nparsersCueParser\n atoms cueAtom stringAtom\n description Attach by matching first atom.\n extends abstractParseRuleParser\n tags acquirePhase\n cue cue\ncueFromIdParser\n atoms cueAtom\n description Derive cue from parserId.\n // for example 'fooParser' would have cue of 'foo'.\n extends abstractParseRuleParser\n tags acquirePhase\nparsersPatternParser\n catchAllAtomType regexAtom\n description Attach via regex.\n extends abstractParseRuleParser\n tags acquirePhase\n cue pattern\nparsersRequiredParser\n description Assert is present at least once.\n extends abstractParserRuleParser\n cue required\n tags analyzePhase\nabstractValidationRuleParser\n extends abstractParserRuleParser\n cueFromId\n catchAllAtomType booleanAtom\nparsersSingleParser\n description Assert used once.\n // Can be overridden by a child class by setting to false.\n extends abstractValidationRuleParser\n tags analyzePhase\n cue single\nuniqueLineParser\n description Assert unique lines. For pattern parsers.\n // Can be overridden by a child class by setting to false.\n extends abstractValidationRuleParser\n tags analyzePhase\nuniqueCueParser\n description Assert unique first atoms. For pattern parsers.\n // For catch all parsers or pattern particles, use this to indicate the \n extends abstractValidationRuleParser\n tags analyzePhase\nlistDelimiterParser\n description Split content by this delimiter.\n extends abstractParserRuleParser\n cueFromId\n catchAllAtomType stringAtom\n tags analyzePhase\ncontentKeyParser\n description Deprecated. For to/from JSON.\n // Advanced keyword to help with isomorphic JSON serialization/deserialization. If present will serialize the particle to an object and set a property with this key and the value set to the particle's content.\n extends abstractParserRuleParser\n cueFromId\n catchAllAtomType stringAtom\n tags deprecate\n boolean suggestInAutocomplete false\nsubparticlesKeyParser\n // todo: deprecate?\n description Deprecated. For to/from JSON.\n // Advanced keyword to help with serialization/deserialization of blobs. If present will serialize the particle to an object and set a property with this key and the value set to the particle's subparticles.\n extends abstractParserRuleParser\n cueFromId\n catchAllAtomType stringAtom\n tags deprecate\n boolean suggestInAutocomplete false\nparsersTagsParser\n catchAllAtomType stringAtom\n extends abstractParserRuleParser\n description Custom metadata.\n cue tags\n tags assemblePhase\natomTypeDescriptionParser\n description Atom Type description.\n catchAllAtomType stringAtom\n cue description\n tags assemblePhase\ncatchAllErrorParser\n baseParser errorParser\ncatchAllExampleLineParser\n catchAllAtomType exampleAnyAtom\n catchAllParser catchAllExampleLineParser\n atoms exampleAnyAtom\ncatchAllJavascriptCodeLineParser\n catchAllAtomType javascriptCodeAtom\n catchAllParser catchAllJavascriptCodeLineParser\ncatchAllMultilineStringConstantParser\n description String constants can span multiple lines.\n catchAllAtomType stringAtom\n catchAllParser catchAllMultilineStringConstantParser\n atoms stringAtom\natomTypeDefinitionParser\n // todo Generate a class for each atom type?\n // todo Allow abstract atom types?\n // todo Change pattern to postfix.\n pattern ^[a-zA-Z0-9_]+Atom$\n inScope parsersPaintParser parsersRegexParser reservedAtomsParser enumFromAtomTypesParser atomTypeDescriptionParser parsersEnumParser slashCommentParser extendsAtomTypeParser parsersExamplesParser atomMinParser atomMaxParser\n atoms atomTypeIdAtom\n tags assemblePhase\n javascript\n buildHtml() {return \"\"}\nenumFromAtomTypesParser\n description Runtime enum options.\n catchAllAtomType atomTypeIdAtom\n atoms atomPropertyNameAtom\n cueFromId\n tags analyzePhase\nparsersEnumParser\n description Set enum options.\n cue enum\n catchAllAtomType enumOptionAtom\n atoms atomPropertyNameAtom\n tags analyzePhase\nparsersExamplesParser\n description Examples for documentation and tests.\n // If the domain of possible atom values is large, such as a string type, it can help certain methods—such as program synthesis—to provide a few examples.\n cue examples\n catchAllAtomType atomExampleAtom\n atoms atomPropertyNameAtom\n tags assemblePhase\natomMinParser\n description Specify a min if numeric.\n cue min\n atoms atomPropertyNameAtom numberAtom\n tags analyzePhase\natomMaxParser\n description Specify a max if numeric.\n cue max\n atoms atomPropertyNameAtom numberAtom\n tags analyzePhase\nparsersPaintParser\n atoms cueAtom paintTypeAtom\n description Instructor editor how to color these.\n single\n cue paint\n tags analyzePhase\nparserDefinitionParser\n // todo Add multiple dispatch?\n pattern ^[a-zA-Z0-9_]+Parser$\n description Parser types are a core unit of your language. They translate to 1 class per parser. Examples of parser would be \"header\", \"person\", \"if\", \"+\", \"define\", etc.\n catchAllParser catchAllErrorParser\n inScope abstractParserRuleParser abstractConstantParser slashCommentParser parserDefinitionParser\n atoms parserIdAtom\n tags assemblePhase\n javascript\n buildHtml() { return \"\"}\nparsersRegexParser\n catchAllAtomType regexAtom\n description Atoms must match this.\n single\n atoms atomPropertyNameAtom\n cue regex\n tags analyzePhase\nreservedAtomsParser\n single\n description Atoms can't be any of these.\n catchAllAtomType reservedAtomAtom\n atoms atomPropertyNameAtom\n cueFromId\n tags analyzePhase\nextendsAtomTypeParser\n cue extends\n description Extend another atomType.\n // todo Add mixin support in addition to extends?\n atoms cueAtom atomTypeIdAtom\n tags assemblePhase\n single\nabstractColumnNameParser\n atoms cueAtom columnNameAtom\n javascript\n getRunTimeEnumOptions(atom) {\n if (atom.atomTypeId === \"columnNameAtom\")\n return this.parent.columnNames\n return super.getRunTimeEnumOptions(atom)\n }\nscrollRadiusParser\n cue radius\n extends abstractColumnNameParser\nscrollSymbolParser\n cue symbol\n extends abstractColumnNameParser\nabstractColumnNameOrColorParser\n extends abstractColumnNameParser\n atoms cueAtom columnNameOrColorAtom\n javascript\n //todo: cleanup\n colorOptions = \"aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkkhaki darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray darkturquoise darkviolet deeppink deepskyblue dimgray dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow honeydew hotpink indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgoldenrodyellow lightgray lightgreen lightpink lightsalmon lightseagreen lightskyblue lightslategray lightsteelblue lightyellow lime limegreen linen magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell sienna silver skyblue slateblue slategray snow springgreen steelblue tan teal thistle tomato turquoise violet wheat white whitesmoke yellow yellowgreen\".split(\" \")\n getRunTimeEnumOptions(atom) {\n if (atom.atomTypeId === \"columnNameOrColorAtom\")\n return this.parent.columnNames.join(this.colorOptions)\n return super.getRunTimeEnumOptions(atom)\n }\nscrollFillParser\n cue fill\n extends abstractColumnNameOrColorParser\nscrollStrokeParser\n cue stroke\n extends abstractColumnNameOrColorParser\nscrollLabelParser\n cue label\n extends abstractColumnNameParser\nscrollSortParser\n cue sort\n extends abstractColumnNameParser\nscrollXParser\n cue x\n extends abstractColumnNameParser\nscrollYParser\n cue y\n extends abstractColumnNameParser\nabstractPlotLabelParser\n cueFromId\n atoms cueAtom\n catchAllAtomType stringAtom\nquoteLineParser\n popularity 0.004172\n catchAllAtomType stringAtom\n catchAllParser quoteLineParser\nscrollParser\n description Scroll is a language for scientists of all ages. Refine, share and collaborate on ideas.\n root\n inScope abstractScrollParser blankLineParser atomTypeDefinitionParser parserDefinitionParser\n catchAllParser catchAllParagraphParser\n javascript\n setFile(file) {\n this.file = file\n const date = this.get(\"date\")\n if (date) this.file.timestamp = this.dayjs(this.get(\"date\")).unix()\n return this\n }\n buildHtml(buildSettings) {\n this.sectionStack = []\n return this.filter(subparticle => subparticle.buildHtml).map(subparticle => { try {return subparticle.buildHtml(buildSettings)} catch (err) {console.error(err); return \"\"} }).filter(i => i).join(\"\\n\") + this.clearSectionStack()\n }\n sectionStack = []\n clearSectionStack() {\n const result = this.sectionStack.join(\"\\n\")\n this.sectionStack = []\n return result\n }\n bodyStack = []\n clearBodyStack() {\n const result = this.bodyStack.join(\"\")\n this.bodyStack = []\n return result\n }\n get hakonParser() {\n if (this.isNodeJs())\n return require(\"scrollsdk/products/hakon.nodejs.js\")\n return hakonParser\n }\n readSyncFromFileOrUrl(fileOrUrl) {\n if (!this.isNodeJs()) return this.getInBrowser(fileOrUrl)\n const isUrl = fileOrUrl.match(/^https?\\:[^ ]+$/)\n if (!isUrl) return this.root.readFile(fileOrUrl)\n return this.readFile(this.makeFullPath(new URL(fileOrUrl).pathname.split('/').pop()))\n }\n getInBrowser(key) {\n return localStorage.getItem(key) || (window.inMemStorage ? window.inMemStorage[key] : \"\") || \"\"\n }\n async fetch(url, filename) {\n const isUrl = url.match(/^https?\\:[^ ]+$/)\n if (!isUrl) return\n return this.isNodeJs() ? this.fetchNode(url, filename) : this.fetchBrowser(url)\n }\n get path() {\n return require(\"path\")\n }\n makeFullPath(filename) {\n return this.path.join(this.folderPath, filename)\n }\n _nextAndPrevious(arr, index) {\n const nextIndex = index + 1\n const previousIndex = index - 1\n return {\n previous: arr[previousIndex] ?? arr[arr.length - 1],\n next: arr[nextIndex] ?? arr[0]\n }\n }\n // keyboard nav is always in the same folder. does not currently support cross folder\n includeFileInKeyboardNav(file) {\n const { scrollProgram } = file\n return scrollProgram.buildsHtml && scrollProgram.hasKeyboardNav && scrollProgram.tags.includes(this.primaryTag)\n }\n get timeIndex() {\n return this.file.timeIndex || 0\n }\n get linkToPrevious() {\n if (!this.hasKeyboardNav)\n // Dont provide link to next unless keyboard nav is on\n return undefined\n const {allScrollFiles} = this\n let file = this._nextAndPrevious(allScrollFiles, this.timeIndex).previous\n while (!this.includeFileInKeyboardNav(file)) {\n file = this._nextAndPrevious(allScrollFiles, file.timeIndex).previous\n }\n return file.scrollProgram.permalink\n }\n importRegex = /^(import |[a-zA-Z\\_\\-\\.0-9\\/]+\\.(scroll|parsers)$|https?:\\/\\/.+\\.(scroll|parsers)$)/gm\n get linkToNext() {\n if (!this.hasKeyboardNav)\n // Dont provide link to next unless keyboard nav is on\n return undefined\n const {allScrollFiles} = this\n let file = this._nextAndPrevious(allScrollFiles, this.timeIndex).next\n while (!this.includeFileInKeyboardNav(file)) {\n file = this._nextAndPrevious(allScrollFiles, file.timeIndex).next\n }\n return file.scrollProgram.permalink\n }\n // todo: clean up this naming pattern and add a parser instead of special casing 404.html\n get allHtmlFiles() {\n return this.allScrollFiles.filter(file => file.scrollProgram.buildsHtml && file.scrollProgram.permalink !== \"404.html\")\n }\n parseNestedTag(tag) {\n if (!tag.includes(\"/\")) return;\n const {path} = this\n const parts = tag.split(\"/\")\n const group = parts.pop()\n const relativePath = parts.join(\"/\")\n return {\n group,\n relativePath,\n folderPath: path.join(this.folderPath, path.normalize(relativePath))\n }\n }\n getFilesByTags(tags, limit) {\n // todo: tags is currently matching partial substrings\n const getFilesWithTag = (tag, files) => files.filter(file => file.scrollProgram.buildsHtml && file.scrollProgram.tags.includes(tag))\n if (typeof tags === \"string\") tags = tags.split(\" \")\n if (!tags || !tags.length)\n return this.allHtmlFiles\n .filter(file => file !== this) // avoid infinite loops. todo: think this through better.\n .map(file => {\n return { file, relativePath: \"\" }\n })\n .slice(0, limit)\n let arr = []\n tags.forEach(tag => {\n if (!tag.includes(\"/\"))\n return (arr = arr.concat(\n getFilesWithTag(tag, this.allScrollFiles)\n .map(file => {\n return { file, relativePath: \"\" }\n })\n .slice(0, limit)\n ))\n const {folderPath, group, relativePath} = this.parseNestedTag(tag)\n let files = []\n try {\n files = this.fileSystem.getCachedLoadedFilesInFolder(folderPath, this)\n } catch (err) {\n console.error(err)\n }\n const filtered = getFilesWithTag(group, files).map(file => {\n return { file, relativePath: relativePath + \"/\" }\n })\n arr = arr.concat(filtered.slice(0, limit))\n })\n return this.lodash.sortBy(arr, file => file.file.timestamp).reverse()\n }\n async fetchNode(url, filename) {\n filename = filename || new URL(url).pathname.split('/').pop()\n const fullpath = this.makeFullPath(filename)\n if (require(\"fs\").existsSync(fullpath)) return this.readFile(fullpath)\n this.log(`🛜 fetching ${url} to ${fullpath} `)\n await this.downloadToDisk(url, fullpath)\n return this.readFile(fullpath)\n }\n log(message) {\n if (this.logger) this.logger.log(message)\n }\n async fetchBrowser(url) {\n const content = this.getInBrowser(url)\n if (content) return content\n return this.downloadToLocalStorage(url)\n }\n async downloadToDisk(url, destination) {\n const { writeFile } = require('fs').promises\n const response = await fetch(url)\n const fileBuffer = await response.arrayBuffer()\n await writeFile(destination, Buffer.from(fileBuffer))\n return this.readFile(destination)\n }\n async downloadToLocalStorage(url) {\n const response = await fetch(url)\n const blob = await response.blob()\n const text = await blob.text()\n try {\n localStorage.setItem(url, text)\n return localStorage.getItem(url)\n } catch (err) {\n if (!window.inMemStorage) window.inMemStorage = {}\n window.inMemStorage[url] = text\n console.error(err)\n return text\n }\n }\n readFile(filename) {\n const {path} = this\n const fs = require(\"fs\")\n const fullPath = path.join(this.folderPath, filename.replace(this.folderPath, \"\"))\n try {\n if (fs.existsSync(fullPath))\n return fs.readFileSync(fullPath, \"utf8\")\n console.error(`File '${filename}' not found`)\n return \"\"\n } catch (err) {\n console.error(`Error in '${this.filePath}' reading file: '${fullPath}'`)\n console.error(err)\n return \"\"\n }\n }\n alreadyRequired = new Set()\n buildHtmlSnippet(buildSettings) {\n this.sectionStack = []\n return this.map(subparticle => (subparticle.buildHtmlSnippet ? subparticle.buildHtmlSnippet(buildSettings) : subparticle.buildHtml(buildSettings)))\n .filter(i => i)\n .join(\"\\n\")\n .trim() + this.clearSectionStack()\n }\n get footnotes() {\n if (this._footnotes === undefined) this._footnotes = this.filter(particle => particle.isFootnote)\n return this._footnotes\n }\n get authors() {\n return this.get(\"authors\")\n }\n get allScrollFiles() {\n try {\n return this.fileSystem.getCachedLoadedFilesInFolder(this.folderPath, this)\n } catch (err) {\n console.error(err)\n return []\n }\n }\n async doThing(thing) {\n await Promise.all(this.filter(particle => particle[thing]).map(async particle => particle[thing]()))\n }\n async load() {\n await this.doThing(\"load\")\n }\n async execute() {\n await this.doThing(\"execute\")\n }\n file = {}\n getFromParserId(parserId) {\n return this.parserIdIndex[parserId]?.[0].content\n }\n get fileSystem() {\n return this.file.fileSystem\n }\n get filePath() {\n return this.file.filePath\n }\n get folderPath() {\n return this.file.folderPath\n }\n get filename() {\n return this.file.filename || \"\"\n }\n get hasKeyboardNav() {\n return this.has(\"keyboardNav\")\n }\n get editHtml() {\n return `<a href=\"${this.editUrl}\" class=\"abstractTextLinkParser\">Edit</a>`\n }\n get externalsPath() {\n return this.file.EXTERNALS_PATH\n }\n get endSnippetIndex() {\n // Get the line number that the snippet should stop at.\n // First if its hard coded, use that\n if (this.has(\"endSnippet\")) return this.getParticle(\"endSnippet\").index\n // Next look for a dinkus\n const snippetBreak = this.find(particle => particle.isDinkus)\n if (snippetBreak) return snippetBreak.index\n return -1\n }\n get parserIds() {\n return this.topDownArray.map(particle => particle.definition.id)\n }\n get tags() {\n return this.get(\"tags\") || \"\"\n }\n get primaryTag() {\n return this.tags.split(\" \")[0]\n }\n get filenameNoExtension() {\n return this.filename.replace(\".scroll\", \"\")\n }\n // todo: rename publishedUrl? Or something to indicate that this is only for stuff on the web (not localhost)\n // BaseUrl must be provided for RSS Feeds and OpenGraph tags to work\n get baseUrl() {\n const baseUrl = (this.get(\"baseUrl\") || \"\").replace(/\\/$/, \"\")\n return baseUrl + \"/\"\n }\n get canonicalUrl() {\n return this.get(\"canonicalUrl\") || this.baseUrl + this.permalink\n }\n get openGraphImage() {\n const openGraphImage = this.get(\"openGraphImage\")\n if (openGraphImage !== undefined) return this.ensureAbsoluteLink(openGraphImage)\n const images = this.filter(particle => particle.doesExtend(\"scrollImageParser\"))\n const hit = images.find(particle => particle.has(\"openGraph\")) || images[0]\n if (!hit) return \"\"\n return this.ensureAbsoluteLink(hit.filename)\n }\n get absoluteLink() {\n return this.ensureAbsoluteLink(this.permalink)\n }\n ensureAbsoluteLink(link) {\n if (link.includes(\"://\")) return link\n return this.baseUrl + link.replace(/^\\//, \"\")\n }\n get editUrl() {\n const editUrl = this.get(\"editUrl\")\n if (editUrl) return editUrl\n const editBaseUrl = this.get(\"editBaseUrl\")\n return (editBaseUrl ? editBaseUrl.replace(/\\/$/, \"\") + \"/\" : \"\") + this.filename\n }\n get gitRepo() {\n // given https://github.com/breck7/breckyunits.com/blob/main/four-tips-to-improve-communication.scroll\n // return https://github.com/breck7/breckyunits.com\n return this.editUrl.split(\"/\").slice(0, 5).join(\"/\")\n }\n get scrollVersion() {\n // currently manually updated\n return \"168.2.0\"\n }\n // Use the first paragraph for the description\n // todo: add a particle method version of get that gets you the first particle. (actulaly make get return array?)\n // would speed up a lot.\n get description() {\n const description = this.getFromParserId(\"openGraphDescriptionParser\")\n if (description) return description\n return this.generatedDescription\n }\n get keywords() {\n if (this.has(\"keywords\"))\n return this.get(\"keywords\")\n const tags = this.get(\"tags\")\n if (tags)\n return tags.split(\" \").join(\", \")\n return \"\"\n }\n get generatedDescription() {\n const firstParagraph = this.find(particle => particle.isArticleContent)\n return firstParagraph ? firstParagraph.originalText.substr(0, 100).replace(/[&\"<>']/g, \"\") : \"\"\n }\n get titleFromFilename() {\n const unCamelCase = str => str.replace(/([a-z])([A-Z])/g, \"$1 $2\").replace(/^./, match => match.toUpperCase())\n return unCamelCase(this.filenameNoExtension)\n }\n get title() {\n return this.getFromParserId(\"scrollTitleParser\") || this.titleFromFilename\n }\n get linkTitle() {\n return this.getFromParserId(\"scrollLinkTitleParser\") || this.title\n }\n get permalink() {\n return this.get(\"permalink\") || (this.filename ? this.filenameNoExtension + \".html\" : \"\")\n }\n compileTo(extensionCapitalized) {\n if (extensionCapitalized === \"Txt\")\n return this.asTxt\n if (extensionCapitalized === \"Html\")\n return this.asHtml\n const methodName = \"build\" + extensionCapitalized\n return this.topDownArray\n .filter(particle => particle[methodName])\n .map((particle, index) => particle[methodName](index))\n .join(\"\\n\")\n .trim()\n }\n get asTxt() {\n return (\n this.map(particle => {\n const text = particle.buildTxt ? particle.buildTxt() : \"\"\n if (text) return text + \"\\n\"\n if (!particle.getLine().length) return \"\\n\"\n return \"\"\n })\n .join(\"\")\n .replace(/<[^>]*>/g, \"\")\n .replace(/\\n\\n\\n+/g, \"\\n\\n\") // Maximum 2 newlines in a row\n .trim() + \"\\n\" // Always end in a newline, Posix style\n )\n }\n get dependencies() {\n const dependencies = this.file.dependencies?.slice() || []\n const files = this.topDownArray.filter(particle => particle.dependencies).map(particle => particle.dependencies).flat()\n return dependencies.concat(files)\n }\n get buildsHtml() {\n const { permalink } = this\n return !this.file.importOnly && (permalink.endsWith(\".html\") || permalink.endsWith(\".htm\"))\n }\n // Without specifying the language hyphenation will not work.\n get lang() {\n return this.get(\"htmlLang\") || \"en\"\n }\n _compiledHtml = \"\"\n get asHtml() {\n if (!this._compiledHtml) {\n const { permalink, buildsHtml } = this\n const content = (this.buildHtml() + this.clearBodyStack()).trim()\n // Don't add html tags to CSV feeds. A little hacky as calling a getter named _html_ to get _xml_ is not ideal. But\n // <1% of use case so might be good enough.\n const wrapWithHtmlTags = buildsHtml\n const bodyTag = this.has(\"metaTags\") ? \"\" : \"<body>\\n\"\n this._compiledHtml = wrapWithHtmlTags ? `<!DOCTYPE html>\\n<html lang=\"${this.lang}\">\\n${bodyTag}${content}\\n</body>\\n</html>` : content\n }\n return this._compiledHtml\n }\n get wordCount() {\n return this.asTxt.match(/\\b\\w+\\b/g)?.length || 0\n }\n get minutes() {\n return parseFloat((this.wordCount / 200).toFixed(1))\n }\n get date() {\n const date = this.get(\"date\") || (this.file.timestamp ? this.file.timestamp : 0)\n return this.dayjs(date).format(`MM/DD/YYYY`)\n }\n get year() {\n return parseInt(this.dayjs(this.date).format(`YYYY`))\n }\n get dayjs() {\n if (!this.isNodeJs()) return dayjs\n const lib = require(\"dayjs\")\n const relativeTime = require(\"dayjs/plugin/relativeTime\")\n lib.extend(relativeTime)\n return lib\n }\n get lodash() {\n return this.isNodeJs() ? require(\"lodash\") : lodash\n }\n get d3() {\n return this.isNodeJs() ? require('d3') : d3\n }\n getConcepts(parsed) {\n const concepts = []\n let currentConcept\n parsed.forEach(particle => {\n if (particle.isConceptDelimiter) {\n if (currentConcept) concepts.push(currentConcept)\n currentConcept = []\n }\n if (currentConcept && particle.isMeasure) currentConcept.push(particle)\n })\n if (currentConcept) concepts.push(currentConcept)\n return concepts\n }\n _formatConcepts(parsed) {\n const concepts = this.getConcepts(parsed)\n if (!concepts.length) return false\n const {lodash} = this\n // does a destructive sort in place on the parsed program\n concepts.forEach(concept => {\n let currentSection\n const newCode = lodash\n .sortBy(concept, [\"sortIndex\"])\n .map(particle => {\n let newLines = \"\"\n const section = particle.sortIndex.toString().split(\".\")[0]\n if (section !== currentSection) {\n currentSection = section\n newLines = \"\\n\"\n }\n return newLines + particle.toString()\n })\n .join(\"\\n\")\n concept.forEach((particle, index) => (index ? particle.destroy() : \"\"))\n concept[0].replaceParticle(() => newCode)\n })\n }\n get formatted() {\n return this.getFormatted(this.file.codeAtStart)\n }\n get lastCommitTime() {\n // todo: speed this up and do a proper release. also could add more metrics like this.\n if (this._lastCommitTime === undefined) {\n try {\n this._lastCommitTime = require(\"child_process\").execSync(`git log -1 --format=\"%at\" -- \"${this.filePath}\"`).toString().trim()\n } catch (err) {\n this._lastCommitTime = 0\n }\n }\n return this._lastCommitTime\n }\n getFormatted(codeAtStart = this.toString()) {\n let formatted = codeAtStart.replace(/\\r/g, \"\") // remove all carriage returns if there are any\n const parsed = new this.constructor(formatted)\n parsed.topDownArray.forEach(subparticle => {\n subparticle.format()\n const original = subparticle.getLine()\n const trimmed = original.replace(/(\\S.*?)[ \\t]*$/gm, \"$1\")\n // Trim trailing whitespace unless parser allows it\n if (original !== trimmed && !subparticle.allowTrailingWhitespace) subparticle.setLine(trimmed)\n })\n this._formatConcepts(parsed)\n let importOnlys = []\n let topMatter = []\n let allElse = []\n // Create any bindings\n parsed.forEach(particle => {\n if (particle.bindTo === \"next\") particle.binding = particle.next\n if (particle.bindTo === \"previous\") particle.binding = particle.previous\n })\n parsed.forEach(particle => {\n if (particle.getLine() === \"importOnly\") importOnlys.push(particle)\n else if (particle.isTopMatter) topMatter.push(particle)\n else allElse.push(particle)\n })\n const combined = importOnlys.concat(topMatter, allElse)\n // Move any bound particles\n combined\n .filter(particle => particle.bindTo)\n .forEach(particle => {\n // First remove the particle from its current position\n const originalIndex = combined.indexOf(particle)\n combined.splice(originalIndex, 1)\n // Then insert it at the new position\n // We need to find the binding index again after removal\n const bindingIndex = combined.indexOf(particle.binding)\n if (particle.bindTo === \"next\") combined.splice(bindingIndex, 0, particle)\n else combined.splice(bindingIndex + 1, 0, particle)\n })\n const trimmed = combined\n .map(particle => particle.toString())\n .join(\"\\n\")\n .replace(/^\\n*/, \"\") // Remove leading newlines\n .replace(/\\n\\n\\n+/g, \"\\n\\n\") // Maximum 2 newlines in a row\n .replace(/\\n+$/, \"\")\n return trimmed === \"\" ? trimmed : trimmed + \"\\n\" // End non blank Scroll files in a newline character POSIX style for better working with tools like git\n }\n get parser() {\n return this.constructor\n }\n get parsersRequiringExternals() {\n const { parser } = this\n // todo: could be cleaned up a bit\n if (!parser.parsersRequiringExternals) parser.parsersRequiringExternals = parser.cachedHandParsersProgramRoot.filter(particle => particle.copyFromExternal).map(particle => particle.atoms[0])\n return parser.parsersRequiringExternals\n }\n get Disk() { return this.isNodeJs() ? require(\"scrollsdk/products/Disk.node.js\").Disk : {}}\n async buildAll(options = {}) {\n await this.load()\n await this.buildOne(options)\n await this.buildTwo(options)\n }\n async buildOne(options) {\n await this.execute()\n const toBuild = this.filter(particle => particle.buildOne)\n for (let particle of toBuild) {\n await particle.buildOne(options)\n }\n }\n async buildTwo(options) {\n const toBuild = this.filter(particle => particle.buildTwo)\n for (let particle of toBuild) {\n await particle.buildTwo(options)\n }\n }\n get outputFileNames() {\n return this.filter(p => p.outputFileNames).map(p => p.outputFileNames).flat()\n }\n _compileArray(filename, arr) {\n const removeBlanks = data => data.map(obj => Object.fromEntries(Object.entries(obj).filter(([_, value]) => value !== \"\")))\n const parts = filename.split(\".\")\n const format = parts.pop()\n if (format === \"json\") return JSON.stringify(removeBlanks(arr), null, 2)\n if (format === \"js\") return `const ${parts[0]} = ` + JSON.stringify(removeBlanks(arr), null, 2)\n if (format === \"csv\") return this.arrayToCSV(arr)\n if (format === \"tsv\") return this.arrayToCSV(arr, \"\\t\")\n if (format === \"particles\") return particles.toString()\n return particles.toString()\n }\n levenshteinDistance(a, b) {\n const m = a.length\n const n = b.length\n const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0))\n for (let i = 0; i <= m; i++) {\n dp[i][0] = i\n }\n for (let j = 0; j <= n; j++) {\n dp[0][j] = j\n }\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1\n dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost)\n }\n }\n return dp[m][n]\n }\n makeLodashOrderByParams(str) {\n const part1 = str.split(\" \")\n const part2 = part1.map(col => (col.startsWith(\"-\") ? \"desc\" : \"asc\"))\n return [part1.map(col => col.replace(/^\\-/, \"\")), part2]\n }\n arrayToCSV(data, delimiter = \",\") {\n if (!data.length) return \"\"\n // Extract headers\n const headers = Object.keys(data[0])\n const csv = data.map(row =>\n headers\n .map(fieldName => {\n const fieldValue = row[fieldName]\n // Escape commas if the value is a string\n if (typeof fieldValue === \"string\" && fieldValue.includes(delimiter)) {\n return `\"${fieldValue.replace(/\"/g, '\"\"')}\"` // Escape double quotes and wrap in double quotes\n }\n return fieldValue\n })\n .join(delimiter)\n )\n csv.unshift(headers.join(delimiter)) // Add header row at the top\n return csv.join(\"\\n\")\n }\n compileConcepts(filename = \"csv\", sortBy = \"\") {\n const {lodash} = this\n if (!sortBy) return this._compileArray(filename, this.concepts)\n const orderBy = this.makeLodashOrderByParams(sortBy)\n return this._compileArray(filename, lodash.orderBy(this.concepts, orderBy[0], orderBy[1]))\n }\n _withStats\n get measuresWithStats() {\n if (!this._withStats) this._withStats = this.addMeasureStats(this.concepts, this.measures)\n return this._withStats\n }\n addMeasureStats(concepts, measures){\n return measures.map(measure => {\n let Type = false\n concepts.forEach(concept => {\n const value = concept[measure.Name]\n if (value === undefined || value === \"\") return\n measure.Values++\n if (!Type) {\n measure.Example = value.toString().replace(/\\n/g, \" \")\n measure.Type = typeof value\n Type = true\n }\n })\n measure.Coverage = Math.floor((100 * measure.Values) / concepts.length) + \"%\"\n return measure\n })\n }\n parseMeasures(parser) {\n if (!Particle.measureCache)\n Particle.measureCache = new Map()\n const measureCache = Particle.measureCache\n if (measureCache.get(parser)) return measureCache.get(parser)\n const {lodash} = this\n // todo: clean this up\n const getCueAtoms = rootParserProgram =>\n rootParserProgram\n .filter(particle => particle.getLine().endsWith(\"Parser\") && !particle.getLine().startsWith(\"abstract\"))\n .map(particle => particle.get(\"cue\") || particle.getLine())\n .map(line => line.replace(/Parser$/, \"\"))\n // Generate a fake program with one of every of the available parsers. Then parse it. Then we can easily access the meta data on the parsers\n const dummyProgram = new parser(\n Array.from(\n new Set(\n getCueAtoms(parser.cachedHandParsersProgramRoot) // is there a better method name than this?\n )\n ).join(\"\\n\")\n )\n // Delete any particles that are not measures\n dummyProgram.filter(particle => !particle.isMeasure).forEach(particle => particle.destroy())\n dummyProgram.forEach(particle => {\n // add nested measures\n Object.keys(particle.definition.cueMapWithDefinitions).forEach(key => particle.appendLine(key))\n })\n // Delete any nested particles that are not measures\n dummyProgram.topDownArray.filter(particle => !particle.isMeasure).forEach(particle => particle.destroy())\n const measures = dummyProgram.topDownArray.map(particle => {\n return {\n Name: particle.measureName,\n Values: 0,\n Coverage: 0,\n Question: particle.definition.description,\n Example: particle.definition.getParticle(\"example\")?.subparticlesToString() || \"\",\n Type: particle.typeForWebForms,\n Source: particle.sourceDomain,\n //Definition: parsedProgram.root.filename + \":\" + particle.lineNumber\n SortIndex: particle.sortIndex,\n IsComputed: particle.isComputed,\n IsRequired: particle.isMeasureRequired,\n IsConceptDelimiter: particle.isConceptDelimiter,\n Cue: particle.definition.get(\"cue\")\n }\n })\n measureCache.set(parser, lodash.sortBy(measures, \"SortIndex\"))\n return measureCache.get(parser)\n }\n _concepts\n get concepts() {\n if (this._concepts) return this._concepts\n this._concepts = this.parseConcepts(this, this.measures)\n return this._concepts\n }\n _measures\n get measures() {\n if (this._measures) return this._measures\n this._measures = this.parseMeasures(this.parser)\n return this._measures\n }\n parseConcepts(parsedProgram, measures){\n // Todo: might be a perf/memory/simplicity win to have a \"segment\" method in ScrollSDK, where you could\n // virtually split a Particle into multiple segments, and then query on those segments.\n // So we would \"segment\" on \"id \", and then not need to create a bunch of new objects, and the original\n // already parsed lines could then learn about/access to their respective segments.\n const conceptDelimiter = measures.filter(measure => measure.IsConceptDelimiter)[0]\n if (!conceptDelimiter) return []\n const concepts = parsedProgram.split(conceptDelimiter.Cue || conceptDelimiter.Name)\n concepts.shift() // Remove the part before \"id\"\n return concepts.map(concept => {\n const row = {}\n measures.forEach(measure => {\n const measureName = measure.Name\n const measureKey = measure.Cue || measureName.replace(/_/g, \" \")\n if (!measure.IsComputed) row[measureName] = concept.getParticle(measureKey)?.measureValue ?? \"\"\n else row[measureName] = this.computeMeasure(parsedProgram, measureName, concept, concepts)\n })\n return row\n })\n }\n computeMeasure(parsedProgram, measureName, concept, concepts){\n // note that this is currently global, assuming there wont be. name conflicts in computed measures in a single scroll\n if (!Particle.measureFnCache) Particle.measureFnCache = {}\n const measureFnCache = Particle.measureFnCache\n if (!measureFnCache[measureName]) {\n // a bit hacky but works??\n const particle = parsedProgram.appendLine(measureName)\n measureFnCache[measureName] = particle.computeValue\n particle.destroy()\n }\n return measureFnCache[measureName](concept, measureName, parsedProgram, concepts)\n }\n compileMeasures(filename = \"csv\", sortBy = \"\") {\n const withStats = this.measuresWithStats\n if (!sortBy) return this._compileArray(filename, withStats)\n const orderBy = this.makeLodashOrderByParams(sortBy)\n return this._compileArray(filename, this.lodash.orderBy(withStats, orderBy[0], orderBy[1]))\n }\n evalNodeJsMacros(value, macroMap, filePath) {\n const tempPath = filePath + \".js\"\n const {Disk} = this\n if (Disk.exists(tempPath)) throw new Error(`Failed to write/require replaceNodejs snippet since '${tempPath}' already exists.`)\n try {\n Disk.write(tempPath, value)\n const results = require(tempPath)\n Object.keys(results).forEach(key => (macroMap[key] = results[key]))\n } catch (err) {\n console.error(`Error in evalMacros in file '${filePath}'`)\n console.error(err)\n } finally {\n Disk.rm(tempPath)\n }\n }\n evalMacros(fusedFile) {\n const {fusedCode, codeAtStart, filePath} = fusedFile\n let code = fusedCode\n const absolutePath = filePath\n // note: the 2 params above are not used in this method, but may be used in user eval code. (todo: cleanup)\n const regex = /^(replace|toFooter$)/gm\n if (!regex.test(code)) return code\n const particle = new Particle(code) // todo: this can be faster. a more lightweight particle class?\n // Process macros\n const macroMap = {}\n particle\n .filter(particle => {\n const parserAtom = particle.cue\n return parserAtom === \"replace\" || parserAtom === \"replaceJs\" || parserAtom === \"replaceNodejs\"\n })\n .forEach(particle => {\n let value = particle.length ? particle.subparticlesToString() : particle.getAtomsFrom(2).join(\" \")\n const kind = particle.cue\n try {\n if (kind === \"replaceJs\") value = eval(value)\n if (this.isNodeJs() && kind === \"replaceNodejs\")\n this.evalNodeJsMacros(value, macroMap, absolutePath)\n else macroMap[particle.getAtom(1)] = value\n } catch (err) {\n console.error(err)\n }\n particle.destroy() // Destroy definitions after eval\n })\n if (particle.has(\"toFooter\")) {\n const pushes = particle.getParticles(\"toFooter\")\n const append = pushes.map(push => push.section.join(\"\\n\")).join(\"\\n\")\n pushes.forEach(push => {\n push.section.forEach(particle => particle.destroy())\n push.destroy()\n })\n code = particle.asString + append\n }\n const keys = Object.keys(macroMap)\n if (!keys.length) return code\n let codeAfterMacroSubstitution = particle.asString\n // Todo: speed up. build a template?\n Object.keys(macroMap).forEach(key => (codeAfterMacroSubstitution = codeAfterMacroSubstitution.replace(new RegExp(key, \"g\"), macroMap[key])))\n return codeAfterMacroSubstitution\n }\n toRss() {\n const { title, canonicalUrl } = this\n return ` <item>\n <title>${title}</title>\n <link>${canonicalUrl}</link>\n <pubDate>${this.dayjs(this.timestamp * 1000).format(\"ddd, DD MMM YYYY HH:mm:ss ZZ\")}</pubDate>\n </item>`\n }\n example\n # Hello world\n ## This is Scroll\n * It compiles to HTML.\n \n code\n // You can add code as well.\n print(\"Hello world\")\nstampFileParser\n catchAllAtomType stringAtom\n description Create a file.\n javascript\n execute(parentDir) {\n const fs = require(\"fs\")\n const path = require(\"path\")\n const fullPath = path.join(parentDir, this.getLine())\n this.root.log(`Creating file ${fullPath}`)\n fs.mkdirSync(path.dirname(fullPath), {recursive: true})\n const content = this.subparticlesToString()\n fs.writeFileSync(fullPath, content, \"utf8\")\n const isExecutable = content.startsWith(\"#!\")\n if (isExecutable) fs.chmodSync(fullPath, \"755\")\n }\nstampFolderParser\n catchAllAtomType stringAtom\n description Create a folder.\n inScope stampFolderParser\n catchAllParser stampFileParser\n pattern \\/$\n javascript\n execute(parentDir) {\n const fs = require(\"fs\")\n const path = require(\"path\")\n const newPath = path.join(parentDir, this.getLine())\n this.root.log(`Creating folder ${newPath}`)\n fs.mkdirSync(newPath, {recursive: true})\n this.forEach(particle => particle.execute(newPath))\n }\nstumpContentParser\n popularity 0.102322\n catchAllAtomType codeAtom\nscrollTableDataParser\n popularity 0.001061\n cue data\n atoms cueAtom\n description Table from inline delimited data.\n baseParser blobParser\nscrollTableDelimiterParser\n popularity 0.001037\n description Set the delimiter.\n cue delimiter\n atoms cueAtom stringAtom\n javascript\n buildHtml() {\n return \"\"\n }\nplainTextLineParser\n popularity 0.000121\n catchAllAtomType stringAtom\n catchAllParser plainTextLineParser"} \ No newline at end of file
commit 1038a50df258ddcfe70e74b33e281b009bf7da61
Author: Breck Yunits <breck7@gmail.com> Date: 2025-01-16 14:24:18 -0800 Subject: frame building for wc hackathon diff --git a/prompts/frame.scroll b/prompts/frame.scroll new file mode 100644 index 0000000..81aaca5 --- /dev/null +++ b/prompts/frame.scroll @@ -0,0 +1,297 @@ +You are an expert web and Warpcast/Farcaster developer. Create a WarpCast v2 Frame based on this request: "USER_PROMPT" + +Requirements: +- Use Farcaster Frames v2 +- Use only Scroll, CSS, and JavaScript (NO frameworks, NO external dependencies) +- Create clean, semantic HTML5 +- Make it mobile-responsive +- Follow modern best practices and accessibility guidelines +- Keep it simple but professional +- Use only relative links and no external resources +- Do not put a copyright symbol or all rights reserved in the footer. +- Make it beautiful. Dazzling. Advanced used of CSS. + +The Frames v2 docs are here: https://framesv2.com/ +The Frames v2 dev tools are here: https://warpcast.com/~/developers/frames + +As a refresher, for doing the html body, Scroll is a whitespace based language that uses a single indented space to mark a line (aka particle) as a subparticle of a parent line. + +For example: + +header + class hero + nav + div Scroll + class logo + div + class nav-links + a Features + href #features + a Examples + href #examples + a Edit + href edit.html + a GitHub + class cta-button + href https://github.com/breck7/scroll + div + class hero-content + h1 Write Better with Scroll + p The extendible markup language that makes source beautiful and compiles to anything + a Get Started + class primary-button + href https://hub.scroll.pub/ +main + section + id features + class features + h2 Why Scroll? + div + class feature-grid + div + class feature-card + div ⚡ + class feature-icon + h3 Simple Syntax + p Like Markdown, but more powerful. No parentheses needed. + div + class feature-card + div 🧩 + class feature-icon + h3 Extendible + p Build your own custom parsers. + div + class feature-card + div 🎨 + class feature-icon + h3 Beautiful Output + p Create stunning documents with minimal effort. + div + class feature-card + div 🚀 + class feature-icon + h3 Fast & Light + p Built on the efficient PPS Stack. + section + id examples + class code-demo + h2 See It In Action + div + class code-container + pre + class code-example + div + class code-output +footer + div + class footer-content + div + class footer-links + a Documentation + href https://scroll.pub/tutorial.html + a Community + href https://www.reddit.com/r/WorldWideScroll/ + a Blog + href https://scroll.pub/blog + p Started by Breck Yunits. Evolved by a community. + https://twitter.com/breckyunits Breck Yunits + https://github.com/breck7/scroll/graphs/contributors community + + +DOMAIN_PROMPT +---index.scroll--- +buildHtml +baseUrl https://DOMAIN_EXPRESSION +import head.scroll +title FRAME_TITLE +description FRAME_DESCRIPTION +style.css +frame.scroll +script.js + +---head.scroll--- +metaTags +meta + name viewport + content width=device-width, initial-scale=1.0 +meta + name fc:frame + content {\"version\":\"vNext\",\"image\":{\"src\":\"FRAME_IMAGE_URL\",\"aspectRatio\":\"1.91:1\"},\"buttons\":[{\"label\":\"SHOOT! 🏀\",\"action\":\"post\"}]}" +meta + name fc:frame:image + content FRAME_IMAGE_URL +meta + name fc:frame:post_url + content https://DOMAIN_EXPRESSION/api/frame + +---frame.scroll--- +main + class frameContainer + div + class frameContent + h1 FRAME_TITLE + class frameTitle + div + class frameActionArea + button Start + class frameButton + data-action post + +---style.css--- +:root { + --frame-bg: #1c1c1c; + --frame-text: #ffffff; + --frame-accent: #5277FF; + --frame-radius: 12px; +} + +* { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +body { + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; + background: var(--frame-bg); + color: var(--frame-text); + min-height: 100vh; + display: flex; + flex-direction: column; +} + +.frameContainer { + width: 100%; + max-width: 600px; + margin: 0 auto; + padding: 20px; +} + +.frameContent { + background: rgba(255, 255, 255, 0.05); + border-radius: var(--frame-radius); + padding: 24px; + backdrop-filter: blur(10px); +} + +.frameTitle { + font-size: 24px; + font-weight: 700; + margin-bottom: 16px; + text-align: center; +} + +.frameActionArea { + display: flex; + justify-content: center; + margin-top: 24px; +} + +.frameButton { + background: var(--frame-accent); + color: var(--frame-text); + border: none; + padding: 12px 24px; + border-radius: var(--frame-radius); + font-size: 16px; + font-weight: 600; + cursor: pointer; + transition: all 0.2s ease; +} + +.frameButton:hover { + transform: translateY(-2px); + box-shadow: 0 4px 12px rgba(82, 119, 255, 0.25); +} + +@media (max-width: 480px) { + .frameContainer { + padding: 16px; + } + + .frameTitle { + font-size: 20px; + } +} + +---script.js--- +// Initialize Frame SDK +const initializeFrame = async () => { + try { + // Initialize Frame context + const frameContext = await window.frames.getContext(); + console.log('Frame context:', frameContext); + + // Handle button clicks + document.querySelector('.frameButton').addEventListener('click', async () => { + try { + await window.frames.postMessage({ + action: 'post' + }); + } catch (error) { + console.error('Frame action error:', error); + } + }); + + // Signal frame is ready + await window.frames.ready(); + } catch (error) { + console.error('Frame initialization error:', error); + } +}; + +// Start Frame when DOM is loaded +document.addEventListener('DOMContentLoaded', initializeFrame); + +---manifest.json--- +{ + "version": "vNext", + "name": "FRAME_TITLE", + "description": "FRAME_DESCRIPTION", + "image": { + "src": "FRAME_IMAGE_URL", + "aspectRatio": "1.91:1" + }, + "buttons": [ + { + "label": "START", + "action": "post" + } + ], + "postUrl": "https://DOMAIN_EXPRESSION/api/frame" +} + +---api/frame.js--- +// Frame API handler +export default async function handler(req, res) { + if (req.method !== 'POST') { + return res.status(405).json({ error: 'Method not allowed' }); + } + + try { + // Handle Frame interaction + const frameData = req.body; + + // Process frame action here + + // Return next frame state + return res.status(200).json({ + version: 'vNext', + image: { + src: 'FRAME_IMAGE_URL', + aspectRatio: '1.91:1' + }, + buttons: [ + { + label: 'CONTINUE', + action: 'post' + } + ] + }); + } catch (error) { + console.error('Frame API error:', error); + return res.status(500).json({ error: 'Internal server error' }); + } +} + +---end--- \ No newline at end of file diff --git a/public/framehub.scroll b/public/framehub.scroll new file mode 100644 index 0000000..045c4d8 --- /dev/null +++ b/public/framehub.scroll @@ -0,0 +1,74 @@ +buildHtml +title FrameHub: the fastest way to launch frames + +baseUrl http://framehub.pro/ +openGraphImage framehub.png +editButton https://github.com/breck7/framehub +editBaseUrl https://github.com/breck7/framehub/blob/main + + +metaTags +inlineCss .gazette.css .scroll.css scrollHubStyle.css +css html[data-theme=dark], html[data-theme=dark] * { color-scheme: dark; } +css .thin {font-weight: 100;} + +# *Frame*Hub + style font-size: 320%; font-weight:200; +## The _fastest_ way to launch frames + +br 2 + +css + :root { + --primary-color: #1e1e2e; + --secondary-color: #353348; + --accent-color: #6b5bc4; + --scrollColorLink: white; + --scrollPrimaryRgb: 104,77,179; + } + * { + margin: 0; + padding: 0; + box-sizing: border-box; + z-index: 1; + } + body { + min-height: 100vh; + background: radial-gradient(circle at center, var(--secondary-color), var(--primary-color)); + font-family: system-ui, -apple-system, sans-serif; + color: white; + position: relative; + } + #nodesCanvas { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + z-index: -1; + } +<canvas id="nodesCanvas"></canvas> +// nodes.js + + +replace AGENT Claude +replace TEMPLATE frame +replace TLD framehub.pro +createFromPrompt.scroll + +// + br 2 + center + foldersPublished.html + +br 2 + +center +Built by Breck + class greyText + https://warpcast.com/breck + +// + https://github.com/breck7/week-1 + https://github.com/weeklyhackathon/week-1 + https://warpcast.com/~/developers/frames diff --git a/public/promptSettings.scroll b/public/promptSettings.scroll index 38d0e61..f4de4dc 100644 --- a/public/promptSettings.scroll +++ b/public/promptSettings.scroll @@ -22,6 +22,7 @@ css font-size: 12px; } +// Todo: generate these options dynamically on server <div class="promptSettings"> <select> <option value="claude">Claude</option> @@ -30,6 +31,7 @@ css <select> <option value="scroll.pub">Scroll.pub</option> <option value="powerhouse.wiki">Powerhouse.wiki</option> + <option value="framehub.pro">FrameHub.pro</option> </select> </div>
commit 4db96a9e23a6602689e6d06cc2db7d06e02299ad
Author: Breck Yunits <breck7@gmail.com> Date: 2025-01-16 14:18:30 -0800 Subject: diff --git a/package.json b/package.json index 3852e15..e9d3c1e 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,7 @@ "openai": "^4.77.0", "prettier": "^3.3.3", "rss-parser": "^3.13.0", - "scroll-cli": "^168.1.0", + "scroll-cli": "^168.2.0", "scrollsdk": "^100.1.1" }, "bin": { diff --git a/public/ide/parsers.js b/public/ide/parsers.js index 4d78553..65b8180 100644 --- a/public/ide/parsers.js +++ b/public/ide/parsers.js @@ -1 +1 @@ -const AppConstants = {"parsers":"columnNameAtom\n paint constant\nnewColumnNameAtom\n description Name a derived column.\n paint variable\nconstantAtom\n paint constant\npercentAtom\n paint constant.numeric.float\n extends stringAtom\n // todo: this currently extends from stringAtom b/c scrollsdk needs to be fixed. seems like if extending from number then the hard coded number typescript regex takes precedence over a custom regex\ncountAtom\n extends integerAtom\nyearAtom\n extends integerAtom\npreBuildCommandAtom\n extends cueAtom\n description Give build command atoms their own color.\n paint constant.character.escape\ndelimiterAtom\n description String to use as a delimiter.\n paint string\nbulletPointAtom\n description Any token used as a bullet point such as \"-\" or \"1.\" or \">\"\n paint keyword\ncomparisonAtom\n enum < > <= >= = != includes doesNotInclude empty notEmpty startsWith endsWith\n paint constant\npersonNameAtom\n extends stringAtom\nurlAtom\n paint constant.language\nabsoluteUrlAtom\n paint constant.language\n regex (ftp|https?)://.+\nemailAddressAtom\n extends stringAtom\n paint constant.language\npermalinkAtom\n paint string\n description A string that doesn't contain characters that might interfere with most filesystems. No slashes, for instance.\nfilePathAtom\n paint constant.language\ntagOrUrlAtom\n description An HTML tag or a url.\n paint constant.language\nhtmlAttributesAtom\n paint constant\nhtmlTagAtom\n paint constant.language\n enum div span p a img ul ol li h1 h2 h3 h4 h5 h6 header nav section article aside main footer input button form label select option textarea table tr td th tbody thead tfoot br hr meta link script style title code\nhtmlTypeAtom\n extends stringAtom\n paint constant.language\n enum text password email number tel url search date time datetime-local week month color checkbox radio file submit reset button hidden range\n description HTML input type attribute values.\nclassNameAtom\n paint constant\nhtmlIdAtom\n paint constant\nfontFamilyAtom\n enum Arial Helvetica Verdana Georgia Impact Tahoma Slim\n paint constant\njavascriptAnyAtom\n extends codeAtom\nhtmlAnyAtom\n extends codeAtom\ncolorAtom\n extends codeAtom\nnamedColorAtom\n extends colorAtom\n enum aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkkhaki darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray darkturquoise darkviolet deeppink deepskyblue dimgray dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow honeydew hotpink indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgoldenrodyellow lightgray lightgreen lightpink lightsalmon lightseagreen lightskyblue lightslategray lightsteelblue lightyellow lime limegreen linen magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell sienna silver skyblue slateblue slategray snow springgreen steelblue tan teal thistle tomato turquoise violet wheat white whitesmoke yellow yellowgreen\nbuildCommandAtom\n extends cueAtom\n description Give build command atoms their own color.\n paint constant\ncssAnyAtom\n extends codeAtom\ncssLengthAtom\n extends codeAtom\nreductionTypeAtom\n enum sum mean max min concat first\n paint keyword\ninlineMarkupNameAtom\n description Options to turn on some inline markups.\n enum bold italics code katex none\ntileOptionAtom\n enum default light\nmeasureNameAtom\n extends cueAtom\n // A regex for column names for max compatibility with a broad range of data science tools:\n regex [a-zA-Z][a-zA-Z0-9]*\nabstractConstantAtom\n paint entity.name.tag\njavascriptSafeAlphaNumericIdentifierAtom\n regex [a-zA-Z0-9_]+\n reservedAtoms enum extends function static if while export return class for default require var let const new\nanyAtom\nbaseParsersAtom\n description There are a few classes of special parsers. BlobParsers don't have their subparticles parsed. Error particles always report an error.\n // todo Remove?\n enum blobParser errorParser\n paint variable.parameter\nenumAtom\n paint constant.language\nbooleanAtom\n enum true false\n extends enumAtom\natomParserAtom\n enum prefix postfix omnifix\n paint constant.numeric\natomPropertyNameAtom\n paint variable.parameter\natomTypeIdAtom\n examples integerAtom cueAtom someCustomAtom\n extends javascriptSafeAlphaNumericIdentifierAtom\n enumFromAtomTypes atomTypeIdAtom\n paint storage\nconstantIdentifierAtom\n examples someId myVar\n // todo Extend javascriptSafeAlphaNumericIdentifier\n regex [a-zA-Z]\\w+\n paint constant.other\n description A atom that can be assigned to the parser in the target language.\nconstructorFilePathAtom\nenumOptionAtom\n // todo Add an enumOption top level type, so we can add data to an enum option such as a description.\n paint string\natomExampleAtom\n description Holds an example for a atom with a wide range of options.\n paint string\nextraAtom\n paint invalid\nfileExtensionAtom\n examples js txt doc exe\n regex [a-zA-Z0-9]+\n paint string\nnumberAtom\n paint constant.numeric\nfloatAtom\n extends numberAtom\n regex \\-?[0-9]*\\.?[0-9]*\n paint constant.numeric.float\nintegerAtom\n regex \\-?[0-9]+\n extends numberAtom\n paint constant.numeric.integer\ncueAtom\n description A atom that indicates a certain parser to use.\n paint keyword\njavascriptCodeAtom\nlowercaseAtom\n regex [a-z]+\nparserIdAtom\n examples commentParser addParser\n description This doubles as the class name in Javascript. If this begins with `abstract`, then the parser will be considered an abstract parser, which cannot be used by itself but provides common functionality to parsers that extend it.\n paint variable.parameter\n extends javascriptSafeAlphaNumericIdentifierAtom\n enumFromAtomTypes parserIdAtom\ncueAtom\n paint constant.language\nregexAtom\n paint string.regexp\nreservedAtomAtom\n description A atom that a atom cannot contain.\n paint string\npaintTypeAtom\n enum comment comment.block comment.block.documentation comment.line constant constant.character.escape constant.language constant.numeric constant.numeric.complex constant.numeric.complex.imaginary constant.numeric.complex.real constant.numeric.float constant.numeric.float.binary constant.numeric.float.decimal constant.numeric.float.hexadecimal constant.numeric.float.octal constant.numeric.float.other constant.numeric.integer constant.numeric.integer.binary constant.numeric.integer.decimal constant.numeric.integer.hexadecimal constant.numeric.integer.octal constant.numeric.integer.other constant.other constant.other.placeholder entity entity.name entity.name.class entity.name.class.forward-decl entity.name.constant entity.name.enum entity.name.function entity.name.function.constructor entity.name.function.destructor entity.name.impl entity.name.interface entity.name.label entity.name.namespace entity.name.section entity.name.struct entity.name.tag entity.name.trait entity.name.type entity.name.union entity.other.attribute-name entity.other.inherited-class invalid invalid.deprecated invalid.illegal keyword keyword.control keyword.control.conditional keyword.control.import keyword.declaration keyword.operator keyword.operator.arithmetic keyword.operator.assignment keyword.operator.bitwise keyword.operator.logical keyword.operator.atom keyword.other markup markup.bold markup.deleted markup.heading markup.inserted markup.italic markup.list.numbered markup.list.unnumbered markup.other markup.quote markup.raw.block markup.raw.inline markup.underline markup.underline.link meta meta.annotation meta.annotation.identifier meta.annotation.parameters meta.block meta.braces meta.brackets meta.class meta.enum meta.function meta.function-call meta.function.parameters meta.function.return-type meta.generic meta.group meta.impl meta.interface meta.interpolation meta.namespace meta.paragraph meta.parens meta.path meta.preprocessor meta.string meta.struct meta.tag meta.toc-list meta.trait meta.type meta.union punctuation punctuation.accessor punctuation.definition.annotation punctuation.definition.comment punctuation.definition.generic.begin punctuation.definition.generic.end punctuation.definition.keyword punctuation.definition.string.begin punctuation.definition.string.end punctuation.definition.variable punctuation.section.block.begin punctuation.section.block.end punctuation.section.braces.begin punctuation.section.braces.end punctuation.section.brackets.begin punctuation.section.brackets.end punctuation.section.group.begin punctuation.section.group.end punctuation.section.interpolation.begin punctuation.section.interpolation.end punctuation.section.parens.begin punctuation.section.parens.end punctuation.separator punctuation.separator.continuation punctuation.terminator source source.language-suffix.embedded storage storage.modifier storage.type storage.type keyword.declaration.type storage.type.class keyword.declaration.class storage.type.enum keyword.declaration.enum storage.type.function keyword.declaration.function storage.type.impl keyword.declaration.impl storage.type.interface keyword.declaration.interface storage.type.struct keyword.declaration.struct storage.type.trait keyword.declaration.trait storage.type.union keyword.declaration.union string string.quoted.double string.quoted.other string.quoted.single string.quoted.triple string.regexp string.unquoted support support.class support.constant support.function support.module support.type text text.html text.xml variable variable.annotation variable.function variable.language variable.other variable.other.constant variable.other.member variable.other.readwrite variable.parameter\n paint string\nscriptUrlAtom\nsemanticVersionAtom\n examples 1.0.0 2.2.1\n regex [0-9]+\\.[0-9]+\\.[0-9]+\n paint constant.numeric\ndateAtom\n paint string\nstringAtom\n paint string\natomAtom\n paint constant\n description A non-empty single atom string.\n regex .+\nexampleAnyAtom\n examples lorem ipsem\n // todo Eventually we want to be able to parse correctly the examples.\n paint comment\n extends stringAtom\nblankAtom\ncommentAtom\n paint comment\ncodeAtom\n paint comment\ncolumnNameOrColorAtom\n extends columnNameAtom\nmetaCommandAtom\n extends cueAtom\n description Give meta command atoms their own color.\n paint constant.numeric\n // Obviously this is not numeric. But I like the green color for now.\n We need a better design to replace this \"paint\" concept\n https://github.com/breck7/scrollsdk/issues/186\nvegaDataSetAtom\n paint constant.numeric\n enum airports.csv anscombe.json barley.json birdstrikes.json budget.json budgets.json burtin.json cars.json climate.json co2-concentration.csv countries.json crimea.json descriptions.json disasters.csv driving.json earthquakes.json flare-dependencies.json flare.json flights-10k.json flights-200k.json flights-20k.json flights-2k.json flights-3m.csv flights-5k.json flights-airport.csv gapminder-health-income.csv gapminder.json github.csv graticule.json income.json iowa-electricity.csv iris.json jobs.json la-riots.csv londonBoroughs.json londonCentroids.json londonTubeLines.json lookup_groups.csv lookup_people.csv miserables.json monarchs.json movies.json normal-2d.json obesity.json points.json population.json population_engineers_hurricanes.csv seattle-temps.csv seattle-weather.csv sf-temps.csv sp500.csv stocks.csv udistrict.json unemployment-across-industries.json unemployment.tsv us-10m.json us-employment.csv us-state-capitals.json weather.csv weather.json weball26.json wheat.json windvectors.csv world-110m.json zipcodes.csv\ntagAtom\n extends permalinkAtom\ntagWithOptionalFolderAtom\n description A group name optionally combined with a folder path. Only used when referencing tags, not in posts.\n extends stringAtom\nscrollThemeAtom\n enum roboto gazette dark tufte prestige\n paint constant\nabstractScrollParser\n atoms cueAtom\n javascript\n buildHtmlSnippet(buildSettings) {\n return this.buildHtml(buildSettings)\n }\n buildTxt() {\n return \"\"\n }\n getHtmlRequirements(buildSettings) {\n const {requireOnce} = this\n if (!requireOnce)\n return \"\"\n const set = buildSettings?.alreadyRequired || this.root.alreadyRequired\n if (set.has(requireOnce))\n return \"\"\n set.add(requireOnce)\n return requireOnce + \"\\n\\n\"\n }\nabstractAftertextParser\n description Text followed by markup commands.\n extends abstractScrollParser\n inScope abstractAftertextDirectiveParser abstractAftertextAttributeParser aftertextTagParser abstractCommentParser\n javascript\n get markupInserts() {\n const { originalTextPostLinkify } = this\n return this.filter(particle => particle.isMarkup)\n .map(particle => particle.getInserts(originalTextPostLinkify))\n .filter(i => i)\n .flat()\n }\n get originalText() {\n return this.content ?? \"\"\n }\n get originalTextPostLinkify() {\n const { originalText } = this\n const shouldLinkify = this.get(\"linkify\") === \"false\" || originalText.includes(\"<a \") ? false : true\n return shouldLinkify ? this.replaceNotes(Utils.linkify(originalText)) : originalText\n }\n replaceNotes(originalText) {\n // Skip the replacements if there are no footnotes or the text has none.\n if (!this.root.footnotes.length || !originalText.includes(\"^\")) return originalText\n this.root.footnotes.forEach((note, index) => {\n const needle = note.cue\n const {linkBack} = note\n if (originalText.includes(needle)) originalText = originalText.replace(new RegExp(\"\\\\\" + needle + \"\\\\b\"), `<a href=\"#${note.htmlId}\" class=\"scrollNoteLink\" id=\"${linkBack}\"><sup>${note.label}</sup></a>`)\n })\n return originalText\n }\n get text() {\n const { originalTextPostLinkify, markupInserts } = this\n let adjustment = 0\n let newText = originalTextPostLinkify\n markupInserts.sort((a, b) => {\n if (a.index !== b.index)\n return a.index - b.index\n // If multiple tags start at same index, the tag that closes first should start last. Otherwise HTML breaks.\n if (b.index === b.endIndex) // unless the endIndex is the same as index\n return a.endIndex - b.endIndex\n return b.endIndex - a.endIndex\n })\n markupInserts.forEach(insertion => {\n insertion.index += adjustment\n const consumeStartCharacters = insertion.consumeStartCharacters ?? 0\n const consumeEndCharacters = insertion.consumeEndCharacters ?? 0\n newText = newText.slice(0, insertion.index - consumeEndCharacters) + insertion.string + newText.slice(insertion.index + consumeStartCharacters)\n adjustment += insertion.string.length - consumeEndCharacters - consumeStartCharacters\n })\n return newText\n }\n tag = \"p\"\n get className() {\n if (this.get(\"class\"))\n return this.get(\"class\")\n const classLine = this.getParticle(\"addClass\")\n if (classLine && classLine.applyToParentElement) return classLine.content\n return this.defaultClassName\n }\n defaultClassName = \"scrollParagraph\"\n get isHidden() {\n return this.has(\"hidden\")\n }\n buildHtml(buildSettings) {\n if (this.isHidden) return \"\"\n this.buildSettings = buildSettings\n const { className, styles } = this\n const classAttr = className ? `class=\"${this.className}\"` : \"\"\n const selfClose = this.isSelfClosing ? \" /\" : \"\"\n const tag = this.get(\"tag\") || this.tag\n if (tag === \"none\") // Allow no tag for aftertext in tables\n return this.text\n const id = this.has(\"id\") ? \"\" : `id=\"${this.htmlId}\" ` // always add an html id\n return this.getHtmlRequirements(buildSettings) + `<${tag} ${id}${this.htmlAttributes}${classAttr}${styles}${selfClose}>${this.htmlContents}${this.closingTag}`\n }\n get htmlContents() {\n return this.text\n }\n get closingTag() {\n if (this.isSelfClosing) return \"\"\n const tag = this.get(\"tag\") || this.tag\n return `</${tag}>`\n }\n get htmlAttributes() {\n const attrs = this.filter(particle => particle.isAttribute)\n return attrs.length ? attrs.map(particle => particle.htmlAttributes).join(\" \") + \" \" : \"\"\n }\n get styles() {\n const style = this.getParticle(\"style\")\n const fontFamily = this.getParticle(\"font\")\n const color = this.getParticle(\"color\")\n if (!style && !fontFamily && !color)\n return \"\"\n return ` style=\"${style?.content};${fontFamily?.css};${color?.css}\"`\n }\n get htmlId() {\n return this.get(\"id\") || \"particle\" + this.index\n }\nscrollParagraphParser\n // todo Perhaps rewrite this from scratch and move out of aftertext.\n extends abstractAftertextParser\n catchAllAtomType stringAtom\n description A paragraph.\n boolean suggestInAutocomplete false\n cueFromId\n javascript\n buildHtml(buildSettings) {\n if (this.isHidden) return \"\"\n // Hacky, I know.\n const newLine = this.has(\"inlineMarkupsOn\") ? undefined : this.appendLine(\"inlineMarkupsOn\")\n const compiled = super.buildHtml(buildSettings)\n if (newLine)\n newLine.destroy()\n return compiled\n }\n buildTxt() {\n const subparticles = this.filter(particle => particle.buildTxt).map(particle => particle.buildTxt()).filter(i => i).join(\"\\n\")\n const dateline = this.getParticle(\"dateline\")\n return (dateline ? dateline.day + \"\\n\\n\" : \"\") + (this.originalText || \"\") + (subparticles ? \"\\n \" + subparticles.replace(/\\n/g, \"\\n \") : \"\")\n }\nauthorsParser\n popularity 0.007379\n // multiple authors delimited by \" and \"\n boolean isPopular true\n extends scrollParagraphParser\n description Set author(s) name(s).\n example\n authors Breck Yunits\n https://breckyunits.com Breck Yunits\n // note: once we have mixins in Parsers, lets mixin the below from abstractTopLevelSingleMetaParser\n atoms metaCommandAtom\n javascript\n isTopMatter = true\n isSetterParser = true\n buildHtmlForPrint() {\n // hacky. todo: cleanup\n const originalContent = this.content\n this.setContent(`by ${originalContent}`)\n const html = super.buildHtml()\n this.setContent(originalContent)\n return html\n }\n buildTxtForPrint() {\n return 'by ' + super.buildTxt()\n }\n buildHtml() {\n return \"\"\n }\n buildTxt() {\n return \"\"\n }\n defaultClassName = \"printAuthorsParser\"\nblinkParser\n description Just for fun.\n extends scrollParagraphParser\n example\n blink Carpe diem!\n cue blink\n javascript\n buildHtml() {\n return `<span class=\"scrollBlink\">${super.buildHtml()}</span>\n <script>setInterval(()=>{ Array.from(document.getElementsByClassName(\"scrollBlink\")).forEach(el => el.style.visibility = el.style.visibility === \"hidden\" ? \"visible\" : \"hidden\") }, 500)</script>`\n }\nscrollButtonParser\n extends scrollParagraphParser\n cueFromId\n description A button.\n postParser\n description Post a particle.\n example\n scrollButton Click me\n javascript\n defaultClassName = \"scrollButton\"\n tag = \"button\"\n get htmlAttributes() {\n const link = this.getFromParser(\"scrollLinkParser\")\n const post = this.getParticle(\"post\")\n if (post) {\n const method = \"post\"\n const action = link?.link || \"\"\n const formData = new URLSearchParams({particle: post.subparticlesToString()}).toString()\n return ` onclick=\"fetch('${action}', {method: '${method}', body: '${formData}', headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).then(async (message) => {const el = document.createElement('div'); el.textContent = await message.text(); this.insertAdjacentElement('afterend', el);}); return false;\" `\n }\n return super.htmlAttributes + (link ? `onclick=\"window.location='${link.link}'\"` : \"\")\n }\n getFromParser(parserId) {\n return this.find(particle => particle.doesExtend(parserId))\n }\ncatchAllParagraphParser\n popularity 0.115562\n description A paragraph.\n extends scrollParagraphParser\n boolean suggestInAutocomplete false\n boolean isPopular true\n boolean isArticleContent true\n atoms stringAtom\n javascript\n getErrors() {\n const errors = super.getErrors() || []\n return this.parent.has(\"testStrict\") ? errors.concat(this.makeError(`catchAllParagraphParser should not have any matches when testing with testStrict.`)) : errors\n }\n get originalText() {\n return this.getLine() || \"\"\n }\nscrollCenterParser\n popularity 0.006415\n cue center\n description A centered section.\n extends scrollParagraphParser\n example\n center\n This paragraph is centered.\n javascript\n buildHtml() {\n this.parent.sectionStack.push(\"</center>\")\n return `<center>${super.buildHtml()}`\n }\n buildTxt() {\n return this.content\n }\nabstractIndentableParagraphParser\n extends scrollParagraphParser\n inScope abstractAftertextDirectiveParser abstractAftertextAttributeParser abstractIndentableParagraphParser scrollParagraphParser\n javascript\n get htmlContents() {\n return this.text + this.map(particle => particle.buildHtml())\n .join(\"\\n\")\n .trim()\n }\n buildTxt() {\n return this.getAtom(0) + \" \" + super.buildTxt()\n }\nchecklistTodoParser\n popularity 0.000193\n extends abstractIndentableParagraphParser\n example\n [] Get milk\n description A task todo.\n cue []\n string checked \n javascript\n get text() {\n return `<div style=\"text-indent:${(this.getIndentLevel() - 1) * 20}px;\"><input type=\"checkbox\" ${this.checked} id=\"${this.id}\"><label for=\"${this.id}\">` + super.text + `</label></div>`\n }\n get id() {\n return this.get(\"id\") || \"item\" + this._getUid()\n }\nchecklistDoneParser\n popularity 0.000072\n extends checklistTodoParser\n description A completed task.\n string checked checked\n cue [x]\n example\n [x] get milk\nscrollDivParser\n popularity 0.007524\n description HTML div tag.\n extends abstractIndentableParagraphParser\n cue div\n example\n div\n # Hello world\n p This is a test\n div\n # Deeper\n javascript\n tag = \"div\"\nabstractHtmlElementParser\n extends abstractIndentableParagraphParser\n javascript\n defaultClassName = \"\"\nhtmlSectionParser\n description HTML section tag.\n extends abstractHtmlElementParser\n cue section\n example\n section\n # Hello world\n p This is a test\n section\n # Deeper\n javascript\n tag = \"section\"\nhtmlHeaderParser\n description HTML header tag.\n extends abstractHtmlElementParser\n cue header\n example\n header\n # Title\n javascript\n tag = \"header\"\nhtmlFooterParser\n description HTML footer tag.\n extends abstractHtmlElementParser\n cue footer\n example\n footer\n p Made with love\n javascript\n tag = \"footer\"\nhtmlAsideParser\n description HTML aside tag.\n extends abstractHtmlElementParser\n cue aside\n example\n aside\n h1 Some notes\n javascript\n tag = \"aside\"\nhtmlArticleParser\n description HTML article tag.\n extends abstractHtmlElementParser\n cue article\n example\n article\n h1 My article\n javascript\n tag = \"article\"\nhtmlMainParser\n description HTML main tag.\n extends abstractHtmlElementParser\n cue main\n example\n main\n # Title\n javascript\n tag = \"main\"\nhtmlNavParser\n description HTML nav tag.\n extends abstractHtmlElementParser\n cue nav\n example\n nav\n a Home\n href /\n javascript\n tag = \"nav\"\nhtmlPreParser\n description HTML pre tag.\n extends abstractHtmlElementParser\n cue pre\n example\n pre\n javascript\n tag = \"pre\"\nhtmlUlParser\n description HTML ul tag.\n extends abstractHtmlElementParser\n cue ul\n example\n ul\n li A list\n javascript\n tag = \"ul\"\nhtmlOlParser\n description HTML ol tag.\n extends abstractHtmlElementParser\n cue ol\n example\n ol\n li A list\n javascript\n tag = \"ol\"\nhtmlLiParser\n description HTML li tag.\n extends abstractHtmlElementParser\n cue li\n example\n ol\n li A list\n javascript\n tag = \"li\"\nhtmlImgParser\n description HTML img tag.\n extends abstractHtmlElementParser\n cue img\n example\n img foo.png\n javascript\n tag = \"img\"\n isSelfClosing = true\nhtmlAParser\n description HTML a tag.\n extends abstractHtmlElementParser\n cue a\n example\n a Home\n href /\n javascript\n tag = \"a\"\nhtmlFormParser\n description HTML form tag.\n extends abstractHtmlElementParser\n cue form\n example\n form\n input\n javascript\n tag = \"form\"\nhtmlInputParser\n description HTML input tag.\n extends abstractHtmlElementParser\n cue input\n example\n input\n type text\n placeholder Enter your name\n javascript\n tag = \"input\"\n isSelfClosing = true\nhtmlSelectParser\n description HTML select tag.\n extends abstractHtmlElementParser\n cue select\n example\n select\n option Value 1\n option Value 2\n javascript\n tag = \"select\"\nhtmlOptionParser\n description HTML option tag.\n extends abstractHtmlElementParser\n cue option\n example\n select\n option Choose an option\n option First Option\n javascript\n tag = \"option\"\nhtmlTextareaParser\n description HTML textarea tag.\n extends abstractHtmlElementParser\n cue textarea\n example\n textarea\n placeholder Enter your message\n rows 4\n javascript\n tag = \"textarea\"\nhtmlButtonParser\n description HTML button tag.\n extends abstractHtmlElementParser\n cue button\n example\n button Submit\n type submit\n javascript\n tag = \"button\"\nhtmlLabelParser\n description HTML label tag.\n extends abstractHtmlElementParser\n cue label\n example\n label Name\n for username\n javascript\n tag = \"label\"\nhtmlSpanParser\n description HTML span tag.\n extends abstractHtmlElementParser\n cue span\n example\n span Hello\n javascript\n tag = \"span\"\nhtmlCanvasParser\n description HTML canvas tag.\n extends abstractHtmlElementParser\n cue canvas\n example\n canvas\n javascript\n tag = \"canvas\"\nhtmlIframeParser\n description HTML iframe tag.\n extends abstractHtmlElementParser\n cue iframe\n example\n iframe\n javascript\n tag = \"iframe\"\nh1LiteralParser\n description HTML h1 tag.\n extends abstractHtmlElementParser\n cue h1\n example\n main\n h1 Title\n javascript\n tag = \"h1\"\nh2LiteralParser\n description HTML h2 tag.\n extends abstractHtmlElementParser\n cue h2\n example\n main\n h2 Title\n javascript\n tag = \"h2\"\nh3LiteralParser\n description HTML h3 tag.\n extends abstractHtmlElementParser\n cue h3\n example\n main\n h3 Title\n javascript\n tag = \"h3\"\nh4LiteralParser\n description HTML h4 tag.\n extends abstractHtmlElementParser\n cue h4\n example\n main\n h4 Title\n javascript\n tag = \"h4\"\nlistAftertextParser\n popularity 0.014325\n extends abstractIndentableParagraphParser\n example\n - I had a _new_ thought.\n description A list item.\n cue -\n javascript\n defaultClassName = \"\"\n buildHtml() {\n const {index, parent} = this\n const particleClass = this.constructor\n const isStartOfList = index === 0 || !(parent.particleAt(index - 1) instanceof particleClass)\n const isEndOfList = parent.length === index + 1 || !(parent.particleAt(index + 1) instanceof particleClass)\n const { listType } = this\n return (isStartOfList ? `<${listType} ${this.attributes}>` : \"\") + `${super.buildHtml()}` + (isEndOfList ? `</${listType}>` : \"\")\n }\n get attributes() {\n return \"\"\n }\n tag = \"li\"\n listType = \"ul\"\nabstractCustomListItemParser\n extends listAftertextParser\n javascript\n get requireOnce() {\n return `<style>\\n.${this.constructor.name} li::marker {content: \"${this.cue} \";}\\n</style>`\n }\n get attributes() {\n return `class=\"${this.constructor.name}\"`\n }\norderedListAftertextParser\n popularity 0.004485\n extends listAftertextParser\n description A list item.\n example\n 1. Hello world\n pattern ^\\d+\\. \n javascript\n listType = \"ol\"\n get attributes() { return ` start=\"${this.getAtom(0)}\"`}\npParagraphParser\n popularity 0.001881\n cue p\n extends abstractIndentableParagraphParser\n description A paragraph.\n boolean isArticleContent true\n example\n p I had a _new_ idea.\nquickQuoteParser\n popularity 0.000482\n cue >\n example\n > The only thing we have to fear is fear itself. - FDR\n boolean isPopular true\n extends abstractIndentableParagraphParser\n description A quote.\n javascript\n defaultClassName = \"scrollQuote\"\n tag = \"blockquote\"\nscrollCounterParser\n description Visualize the speed of something.\n extends scrollParagraphParser\n cue counter\n example\n counter 4.5 Babies Born\n atoms cueAtom numberAtom\n javascript\n buildHtml() {\n const line = this.getLine()\n const atoms = line.split(\" \")\n atoms.shift() // drop the counter atom\n const perSecond = parseFloat(atoms.shift()) // get number\n const increment = perSecond/10\n const id = this._getUid()\n this.setLine(`* <span id=\"counter${id}\" title=\"0\">0</span><script>setInterval(()=>{ const el = document.getElementById('counter${id}'); el.title = parseFloat(el.title) + ${increment}; el.textContent = Math.floor(parseFloat(el.title)).toLocaleString()}, 100)</script> ` + atoms.join(\" \"))\n const html = super.buildHtml()\n this.setLine(line)\n return html\n }\nexpanderParser\n popularity 0.000072\n cueFromId\n description An collapsible HTML details tag.\n extends scrollParagraphParser\n example\n expander Knock Knock\n Who's there?\n javascript\n buildHtml() {\n this.parent.sectionStack.push(\"</details>\")\n return `<details>${super.buildHtml()}`\n }\n buildTxt() {\n return this.content\n }\n tag = \"summary\"\n defaultClassName = \"\"\nfootnoteDefinitionParser\n popularity 0.001953\n description A footnote. Can also be used as section notes.\n extends scrollParagraphParser\n boolean isFootnote true\n pattern ^\\^.+$\n // We need to quickLinks back in scope because there is currently a bug in ScrollSDK/parsers where if a parser extending a parent class has a child parser defined, then any regex parsers in the parent class will not be tested unless explicitly included in scope again.\n inScope quickLinkParser\n labelParser\n description If you want to show a custom label for a footnote. Default label is the note definition index.\n cueFromId\n atoms cueAtom\n catchAllAtomType stringAtom\n javascript\n get htmlId() {\n return `note${this.noteDefinitionIndex}`\n }\n get label() {\n // In the future we could allow common practices like author name\n return this.get(\"label\") || `[${this.noteDefinitionIndex}]`\n }\n get linkBack() {\n return `noteUsage${this.noteDefinitionIndex}`\n }\n get text() {\n return `<a class=\"scrollFootNoteUsageLink\" href=\"#noteUsage${this.noteDefinitionIndex}\">${this.label}</a> ${super.text}`\n }\n get noteDefinitionIndex() {\n return this.parent.footnotes.indexOf(this) + 1\n }\n buildTxt() {\n return this.getAtom(0) + \": \" + super.buildTxt()\n }\nabstractHeaderParser\n extends scrollParagraphParser\n example\n # Hello world\n javascript\n buildHtml(buildSettings) {\n if (this.isHidden) return \"\"\n if (this.parent.sectionStack)\n this.parent.sectionStack.push(\"</div>\")\n return `<div class=\"scrollSection\">` + super.buildHtml(buildSettings)\n }\n buildTxt() {\n const line = super.buildTxt()\n return line + \"\\n\" + \"=\".repeat(line.length)\n }\n isHeader = true\nh1Parser\n popularity 0.017918\n description An html h1 tag.\n extends abstractHeaderParser\n example\n # Hello world\n boolean isArticleContent true\n cue #\n boolean isPopular true\n javascript\n tag = \"h1\"\nh2Parser\n popularity 0.005257\n description An html h2 tag.\n extends abstractHeaderParser\n example\n ## Hello world\n boolean isArticleContent true\n cue ##\n boolean isPopular true\n javascript\n tag = \"h2\"\nh3Parser\n popularity 0.001085\n description An html h3 tag.\n extends abstractHeaderParser\n example\n ### Hello world\n boolean isArticleContent true\n cue ###\n javascript\n tag = \"h3\"\nh4Parser\n popularity 0.000289\n description An html h4 tag.\n example\n #### Hello world\n extends abstractHeaderParser\n cue ####\n javascript\n tag = \"h4\"\nscrollQuestionParser\n popularity 0.004244\n description A question.\n extends h4Parser\n cue ?\n example\n ? Why is the sky blue?\n javascript\n defaultClassName = \"scrollQuestion\"\nh5Parser\n description An html h5 tag.\n extends abstractHeaderParser\n example\n ##### Hello world\n cue #####\n javascript\n tag = \"h5\"\nprintTitleParser\n popularity 0.007572\n description Print title.\n extends abstractHeaderParser\n boolean isPopular true\n example\n title Eureka\n printTitle\n cueFromId\n javascript\n buildHtml(buildSettings) {\n // Hacky, I know.\n const {content} = this\n if (content === undefined)\n this.setContent(this.root.title)\n const { permalink } = this.root\n if (!permalink) {\n this.setContent(content) // Restore it as it was.\n return super.buildHtml(buildSettings)\n }\n const newLine = this.appendLine(`link ${permalink}`)\n const compiled = super.buildHtml(buildSettings)\n newLine.destroy()\n this.setContent(content) // Restore it as it was.\n return compiled\n }\n get originalText() {\n return this.content ?? this.root.title ?? \"\"\n }\n defaultClassName = \"printTitleParser\"\n tag = \"h1\"\ncaptionAftertextParser\n popularity 0.003207\n description An image caption.\n cue caption\n example\n map.png\n caption A map.\n extends scrollParagraphParser\n boolean isPopular true\nabstractMediaParser\n extends scrollParagraphParser\n inScope scrollMediaLoopParser scrollAutoplayParser\n int atomIndex 1\n javascript\n buildTxt() {\n return \"\"\n }\n get filename() {\n return this.getAtom(this.atomIndex)\n }\n getAsHtmlAttribute(attr) {\n if (!this.has(attr)) return \"\"\n const value = this.get(attr)\n return value ? `${attr}=\"${value}\"` : attr\n }\n getAsHtmlAttributes(list) {\n return list.map(atom => this.getAsHtmlAttribute(atom)).filter(i => i).join(\" \")\n }\n buildHtml() {\n return `<${this.tag} src=\"${this.filename}\" controls ${this.getAsHtmlAttributes(\"width height loop autoplay\".split(\" \"))}></${this.tag}>`\n }\nscrollMusicParser\n popularity 0.000024\n extends abstractMediaParser\n cue music\n description Play sound files.\n example\n music sipOfCoffee.m4a\n javascript\n buildHtml() {\n return `<audio controls ${this.getAsHtmlAttributes(\"loop autoplay\".split(\" \"))}><source src=\"${this.filename}\" type=\"audio/mpeg\"></audio>`\n }\nquickSoundParser\n popularity 0.000024\n extends scrollMusicParser\n atoms urlAtom\n pattern ^[^\\s]+\\.(mp3|wav|ogg|aac|m4a|flac)\n int atomIndex 0\n example\n sipOfCoffee.m4a\nscrollVideoParser\n popularity 0.000024\n extends abstractMediaParser\n cue video\n example\n video spirit.mp4\n description Play video files.\n widthParser\n cueFromId\n atoms cueAtom integerAtom\n heightParser\n cueFromId\n atoms cueAtom integerAtom\n javascript\n tag = \"video\"\nquickVideoParser\n popularity 0.000024\n extends scrollVideoParser\n example\n spirit.mp4\n atoms urlAtom\n pattern ^[^\\s]+\\.(mp4|webm|avi|mov)\n int atomIndex 0\nquickParagraphParser\n popularity 0.001881\n cue *\n extends scrollParagraphParser\n description A paragraph.\n boolean isArticleContent true\n example\n * I had a _new_ idea.\nscrollStopwatchParser\n description A stopwatch.\n extends scrollParagraphParser\n cue stopwatch\n example\n stopwatch\n atoms cueAtom\n catchAllAtomType numberAtom\n javascript\n buildHtml() {\n const line = this.getLine()\n const id = this._getUid()\n this.setLine(`* <span class=\"scrollStopwatchParser\" id=\"stopwatch${id}\">0.0</span><script>{let startTime = parseFloat(new URLSearchParams(window.location.search).get('start') || 0); document.getElementById('stopwatch${id}').title = startTime; setInterval(()=>{ const el = document.getElementById('stopwatch${id}'); el.title = parseFloat(el.title) + .1; el.textContent = (parseFloat(el.title)).toFixed(1)}, 100)}</script> `)\n const html = super.buildHtml()\n this.setLine(line)\n return html\n }\nthinColumnsParser\n popularity 0.003690\n extends abstractAftertextParser\n cueFromId\n catchAllAtomType integerAtom\n description Thin columns.\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n columnWidth = 35\n columnGap = 20\n buildHtml() {\n const {columnWidth, columnGap, maxColumns} = this\n const maxTotalWidth = maxColumns * columnWidth + (maxColumns - 1) * columnGap\n const stackContents = this.parent.clearSectionStack() // Starting columns always first clears the section stack.\n if (this.singleColumn) this.parent.sectionStack.push(\"</div>\") // Single columns are self-closing after section break.\n return stackContents + `<div class=\"scrollColumns\" style=\"column-width:${columnWidth}ch;column-count:${maxColumns};max-width:${maxTotalWidth}ch;\">`\n }\n get maxColumns() {\n return this.singleColumn ? 1 : parseInt(this.getAtom(1) ?? 10)\n }\nwideColumnsParser\n popularity 0.000386\n extends thinColumnsParser\n description Wide columns.\n javascript\n columnWidth = 90\nwideColumnParser\n popularity 0.003376\n extends wideColumnsParser\n description A wide column section.\n boolean singleColumn true\nmediumColumnsParser\n popularity 0.003376\n extends thinColumnsParser\n description Medium width columns.\n javascript\n columnWidth = 65\nmediumColumnParser\n popularity 0.003376\n extends mediumColumnsParser\n description A medium column section.\n boolean singleColumn true\nthinColumnParser\n popularity 0.003376\n extends thinColumnsParser\n description A thin column section.\n boolean singleColumn true\nendColumnsParser\n popularity 0.007789\n extends abstractAftertextParser\n cueFromId\n description End columns.\n javascript\n buildHtml() {\n return \"</div>\"\n }\n buildHtmlSnippet() {\n return \"\"\n }\nscrollContainerParser\n popularity 0.000096\n cue container\n description A centered HTML div.\n example\n container 600px\n catchAllAtomType cssLengthAtom\n extends abstractAftertextParser\n boolean isHtml true\n javascript\n get maxWidth() {\n return this.atoms[1] || \"1200px\"\n }\n buildHtmlSnippet() {\n return \"\"\n }\n tag = \"div\"\n defaultClassName = \"scrollContainerParser\"\n buildHtml() {\n this.parent.bodyStack.push(\"</div>\")\n return `<style>.scrollContainerParser{width: 100%; box-sizing: border-box; max-width: ${this.maxWidth}; margin: 0 auto;}</style>` + super.buildHtml()\n }\n get text() { return \"\"}\n get closingTag() { return \"\"}\ndebugSourceStackParser\n // useful for debugging\n description Print compilation steps.\n extends abstractAftertextParser\n cueFromId\n example\n printOriginalSource\n javascript\n get sources() {\n const {file} = this.root\n const passNames = [\"codeAtStart\", \"fusedCode\", \"codeAfterMacroPass\"]\n let lastCode = \"\"\n return passNames.map(name => {\n let code = file[name]\n if (lastCode === code)\n code = \"[Unchanged]\"\n lastCode = file[name]\n return {\n name,\n code\n }})\n }\n buildHtml() {\n return `<code class=\"scrollCodeBlock\">${this.buildTxt().replace(/\\</g, \"&lt;\")}</code>`\n }\n buildTxt() {\n return this.sources.map((pass, index) => `Pass ${index + 1} - ${pass.name}\\n========\\n${pass.code}`).join(\"\\n\\n\\n\")\n }\nabstractDinkusParser\n extends abstractAftertextParser\n boolean isDinkus true\n javascript\n buildHtml() {\n return `<div class=\"${this.defaultClass}\"><span>${this.dinkus}</span></div>`\n }\n defaultClass = \"abstractDinkusParser\"\n buildTxt() {\n return this.dinkus\n }\n get dinkus() {\n return this.content || this.getLine()\n }\nhorizontalRuleParser\n popularity 0.000362\n cue ---\n description A horizontal rule.\n extends abstractDinkusParser\n example\n ---\n javascript\n buildHtml() {\n return `<hr>`\n }\nscrollDinkusParser\n popularity 0.010828\n cue ***\n description A dinkus. Breaks section.\n boolean isPopular true\n example\n ***\n extends abstractDinkusParser\n javascript\n dinkus = \"*\"\ncustomDinkusParser\n cue dinkus\n description A custom dinkus.\n extends abstractDinkusParser\nendOfPostDinkusParser\n popularity 0.005740\n extends abstractDinkusParser\n description End of post dinkus.\n boolean isPopular true\n cue ****\n example\n ****\n javascript\n dinkus = \"⁂\"\nabstractIconButtonParser\n extends abstractAftertextParser\n cueFromId\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n return `<style>.abstractIconButtonParser {position:absolute;top:0.25rem; }.abstractIconButtonParser svg {fill: rgba(204,204,204,.8);width:1.875rem;height:1.875rem; padding: 0 7px;} .abstractIconButtonParser:hover svg{fill: #333;}</style><a href=\"${this.link}\" class=\"doNotPrint abstractIconButtonParser\" style=\"${this.style}\">${this.svg}</a>`\n }\ndownloadButtonParser\n popularity 0.006294\n description Link to download/WWS page.\n extends abstractIconButtonParser\n catchAllAtomType urlAtom\n string style position:relative;\n string svg <svg fill=\"#000000\" xmlns=\"http://www.w3.org/2000/svg\" width=\"800px\" height=\"800px\" viewBox=\"0 0 52 52\" enable-background=\"new 0 0 52 52\" xml:space=\"preserve\"><path d=\"M38.6,20.4c-1-6.5-6.7-11.5-13.5-11.5c-7.6,0-13.7,6.1-13.7,13.7c0,0.3,0,0.7,0.1,1c-5,0.4-8.9,4.6-8.9,9.6 c0,5.4,4.3,9.7,9.7,9.7h11.5c-0.8-0.8-8.1-8.1-8.1-8.1c-0.4-0.4-0.4-0.9,0-1.3l1.3-1.3c0.4-0.4,0.9-0.4,1.3,0l3.5,3.5 c0.4,0.4,1.1,0.1,1.1-0.4V21.8c0-0.4,0.5-0.9,1-0.9h1.9c0.5,0,0.9,0.4,0.9,0.9v13.4c0,0.6,0.8,0.8,1.1,0.4l3.5-3.5 c0.4-0.4,0.9-0.4,1.3,0l1.3,1.3c0.4,0.4,0.4,0.9,0,1.3L26,42.9h12.3v0c6.1-0.1,11-5.1,11-11.3C49.4,25.5,44.6,20.6,38.6,20.4z\"/></svg><!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->\n javascript\n get link() {\n return this.content\n }\neditButtonParser\n popularity 0.013963\n description Print badge top right.\n extends abstractIconButtonParser\n catchAllAtomType urlAtom\n // SVG from https://github.com/32pixelsCo/zest-icons\n string svg <svg width=\"800px\" height=\"800px\" viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\"><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M21.1213 2.70705C19.9497 1.53548 18.0503 1.53547 16.8787 2.70705L15.1989 4.38685L7.29289 12.2928C7.16473 12.421 7.07382 12.5816 7.02986 12.7574L6.02986 16.7574C5.94466 17.0982 6.04451 17.4587 6.29289 17.707C6.54127 17.9554 6.90176 18.0553 7.24254 17.9701L11.2425 16.9701C11.4184 16.9261 11.5789 16.8352 11.7071 16.707L19.5556 8.85857L21.2929 7.12126C22.4645 5.94969 22.4645 4.05019 21.2929 2.87862L21.1213 2.70705ZM18.2929 4.12126C18.6834 3.73074 19.3166 3.73074 19.7071 4.12126L19.8787 4.29283C20.2692 4.68336 20.2692 5.31653 19.8787 5.70705L18.8622 6.72357L17.3068 5.10738L18.2929 4.12126ZM15.8923 6.52185L17.4477 8.13804L10.4888 15.097L8.37437 15.6256L8.90296 13.5112L15.8923 6.52185ZM4 7.99994C4 7.44766 4.44772 6.99994 5 6.99994H10C10.5523 6.99994 11 6.55223 11 5.99994C11 5.44766 10.5523 4.99994 10 4.99994H5C3.34315 4.99994 2 6.34309 2 7.99994V18.9999C2 20.6568 3.34315 21.9999 5 21.9999H16C17.6569 21.9999 19 20.6568 19 18.9999V13.9999C19 13.4477 18.5523 12.9999 18 12.9999C17.4477 12.9999 17 13.4477 17 13.9999V18.9999C17 19.5522 16.5523 19.9999 16 19.9999H5C4.44772 19.9999 4 19.5522 4 18.9999V7.99994Z\"/></svg>\n javascript\n get link() {\n return this.content || this.root.editUrl || \"\"\n }\n get style() {\n return this.parent.findParticles(\"editButton\")[0] === this ? \"right:2rem;\": \"position:relative;\"\n }\nemailButtonParser\n popularity 0.006294\n description Email button.\n extends abstractIconButtonParser\n catchAllAtomType emailAddressAtom\n // todo: should just be \"optionalAtomType\"\n string style position:relative;\n string svg <svg viewBox=\"3 5 24 20\" width=\"24\" height=\"20\" xmlns=\"http://www.w3.org/2000/svg\"><g transform=\"matrix(1, 0, 0, 1, 0, -289.0625)\"><path style=\"opacity:1;stroke:none;stroke-width:0.49999997;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1\" d=\"M 5 5 C 4.2955948 5 3.6803238 5.3628126 3.3242188 5.9101562 L 14.292969 16.878906 C 14.696939 17.282876 15.303061 17.282876 15.707031 16.878906 L 26.675781 5.9101562 C 26.319676 5.3628126 25.704405 5 25 5 L 5 5 z M 3 8.4140625 L 3 23 C 3 24.108 3.892 25 5 25 L 25 25 C 26.108 25 27 24.108 27 23 L 27 8.4140625 L 17.121094 18.292969 C 15.958108 19.455959 14.041892 19.455959 12.878906 18.292969 L 3 8.4140625 z \" transform=\"translate(0,289.0625)\" id=\"rect4592\"/></g></svg>\n javascript\n get link() {\n const email = this.content || this.parent.get(\"email\")\n return email ? `mailto:${email}` : \"\"\n }\nhomeButtonParser\n popularity 0.006391\n description Home button.\n extends abstractIconButtonParser\n catchAllAtomType urlAtom\n string style left:2rem;\n string svg <svg role=\"img\" viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M12.7166 3.79541C12.2835 3.49716 11.7165 3.49716 11.2834 3.79541L4.14336 8.7121C3.81027 8.94146 3.60747 9.31108 3.59247 9.70797C3.54064 11.0799 3.4857 13.4824 3.63658 15.1877C3.7504 16.4742 4.05336 18.1747 4.29944 19.4256C4.41371 20.0066 4.91937 20.4284 5.52037 20.4284H8.84433C8.98594 20.4284 9.10074 20.3111 9.10074 20.1665V15.9754C9.10074 14.9627 9.90433 14.1417 10.8956 14.1417H13.4091C14.4004 14.1417 15.204 14.9627 15.204 15.9754V20.1665C15.204 20.3111 15.3188 20.4284 15.4604 20.4284H18.4796C19.0806 20.4284 19.5863 20.0066 19.7006 19.4256C19.9466 18.1747 20.2496 16.4742 20.3634 15.1877C20.5143 13.4824 20.4594 11.0799 20.4075 9.70797C20.3925 9.31108 20.1897 8.94146 19.8566 8.7121L12.7166 3.79541ZM10.4235 2.49217C11.3764 1.83602 12.6236 1.83602 13.5765 2.49217L20.7165 7.40886C21.4457 7.91098 21.9104 8.73651 21.9448 9.64736C21.9966 11.0178 22.0564 13.5119 21.8956 15.3292C21.7738 16.7067 21.4561 18.4786 21.2089 19.7353C20.9461 21.0711 19.7924 22.0001 18.4796 22.0001H15.4604C14.4691 22.0001 13.6655 21.1791 13.6655 20.1665V15.9754C13.6655 15.8307 13.5507 15.7134 13.4091 15.7134H10.8956C10.754 15.7134 10.6392 15.8307 10.6392 15.9754V20.1665C10.6392 21.1791 9.83561 22.0001 8.84433 22.0001H5.52037C4.20761 22.0001 3.05389 21.0711 2.79113 19.7353C2.54392 18.4786 2.22624 16.7067 2.10437 15.3292C1.94358 13.5119 2.00338 11.0178 2.05515 9.64736C2.08957 8.73652 2.55427 7.91098 3.28346 7.40886L10.4235 2.49217Z\"/></svg>\n javascript\n get link() {\n return this.content || this.get(\"link\") || \"index.html\"\n }\ntheScrollButtonParser\n popularity 0.006294\n description WWS button.\n extends abstractIconButtonParser\n string style position:relative;\n string svg <svg xmlns=\"http://www.w3.org/2000/svg\" direction=\"ltr\" width=\"231.52568231268793\" height=\"249.33156169975996\" viewBox=\"297.27169239534896 1273.121785992385 231.52568231268793 249.33156169975996\" stroke-linecap=\"round\" stroke-linejoin=\"round\" data-color-mode=\"dark\" class=\"tl-container tl-theme__force-sRGB tl-theme__dark\" ><defs/><g transform=\"matrix(1, 0, 0, 1, 395.9682, 1413.3618)\" opacity=\"1\"><g transform=\"scale(1)\"><path d=\"M-5.7342,-1.1484 T-5.0182,-4.6536 -2.6672,-12.9768 1.7374,-22.3903 8.4597,-30.0892 16.5455,-35.2796 25.3478,-37.8247 34.4641,-37.2199 43.0676,-33.4606 50.27,-27.1118 55.7861,-19.7972 59.8042,-11.6764 61.6844,-2.3157 60.8049,7.9615 57.3259,17.5954 51.2605,25.5515 41.9451,31.9237 30.6489,36.2084 18.9812,37.6038 8.4915,36.637 -1.3063,34.5174 -10.6869,31.6604 -19.0463,27.0252 -26.0612,20.1562 -31.864,11.1271 -35.2772,1.0066 -35.7963,-9.1933 -35.203,-19.2337 -32.52,-28.3259 -27.3388,-37.4245 -20.2857,-45.7085 -11.787,-53.0395 -2.4314,-58.4864 7.1724,-61.8739 17.5002,-65.6025 28.2859,-68.1034 38.514,-69.1081 48.1844,-69.9134 57.9136,-70.1787 67.4056,-69.5971 76.297,-67.7446 84.5233,-63.97 92.0158,-57.5003 98.1976,-48.5614 102.8839,-38.056 105.9936,-27.6097 107.074,-18.168 107.175,-8.2882 106.6452,1.9768 105.4734,11.7698 104.0279,21.1013 101.7439,31.0445 98.0977,40.6386 92.7822,49.1039 86.2847,57.2337 78.6099,64.7113 69.8339,70.974 61.2863,75.092 52.4283,78.2186 42.5338,80.7945 32.7733,82.6629 22.8568,83.6574 12.2803,83.3538 2.4971,81.4828 -6.3367,78.789 -15.1061,75.8011 -24.259,72.3779 -33.2286,68.991 -41.5707,64.8363 -49.153,59.1909 -55.8375,52.2938 -62.9311,43.9553 -68.4604,34.4882 -71.2761,23.5855 -72.748,12.7452 -73.7673,2.0453 -74.1187,-8.7386 -72.293,-19.3856 -68.7376,-30.4053 -64.12,-39.7852 -59.1825,-47.8931 -53.7695,-56.4512 -48.1998,-65.7676 -43.1389,-74.401 -36.9006,-81.0179 -28.4317,-86.2639 -18.3342,-90.3521 -8.9259,-93.9355 0.1927,-98.7179 9.3551,-103.3537 18.7651,-106.7552 29.7482,-110.3584 40.9287,-113.446 50.87,-115.2231 57.8279,-116.0074 60.4065,-116.0632 A7.8326,7.8326 0 0 1 61.1735,-100.4168 T58.6018,-100.2201 51.1634,-99.3008 41.695,-96.884 32.4044,-94.0187 22.65,-91.382 13.4974,-87.3756 5.0519,-83.1026 -5.0443,-78.6175 -15.7236,-74.4743 -24.6193,-70.2681 -31.274,-62.5903 -36.3827,-53.9362 -41.2833,-46.2905 -46.0679,-38.5161 -50.639,-30.6576 -54.6876,-22.4063 -57.6038,-12.3346 -58.5104,-1.8678 -57.6022,9.4969 -56.0628,20.477 -53.6434,29.0487 -48.8908,36.7517 -42.4075,43.9784 -35.3064,50.6236 -27.3553,55.2062 -17.6884,59.4064 -7.6442,63.6638 2.4427,67.0449 12.7308,69.4843 22.9294,70.2171 33.2547,69.3921 42.4972,67.7384 52.2753,64.8425 61.8649,60.9142 69.5292,56.0828 76.3604,49.5927 82.431,42.3194 87.219,34.619 90.6076,25.5217 92.547,16.0352 93.8703,7.1315 94.4972,-2.5268 94.3672,-13.3681 93.3204,-24.4252 90.5377,-34.1656 85.7321,-43.6441 78.7334,-51.8057 68.7542,-56.0559 57.9857,-57.2713 48.079,-57.0198 38.4535,-56.3204 28.5246,-55.0036 18.6104,-52.4796 9.6402,-49.559 0.7193,-46.2981 -7.1531,-41.3715 -13.708,-34.8957 -19.5435,-26.853 -22.8356,-17.0622 -23.363,-6.5446 -21.9969,3.1439 -17.1086,11.9113 -9.276,18.744 -0.0685,22.6058 9.3636,24.796 19.2422,25.8817 29.052,25.0411 37.9338,21.3502 45.6819,13.8498 49.6675,4.5228 49.2802,-5.1854 45.3277,-14.4455 38.8603,-21.7879 30.5488,-25.7753 21.3356,-24.3975 13.6687,-19.2391 8.8217,-10.9919 6.423,-2.3609 5.7342,1.1484 A5.8481,5.8481 0 0 1 -5.7342,-1.1484 Z\" stroke-linecap=\"round\"/></g></g></svg>\n javascript\n get link() {\n return \"https://wws.scroll.pub\"\n }\nabstractTextLinkParser\n extends abstractAftertextParser\n cueFromId\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildTxt() {\n return this.text\n }\n buildHtml() {\n return `<div class=\"abstractTextLinkParser\"><a href=\"${this.link}\">${this.text}</a></div>`\n }\neditLinkParser\n popularity 0.001206\n extends abstractTextLinkParser\n description Print \"Edit\" link.\n string text Edit\n javascript\n get link() {\n return this.root.editUrl || \"\"\n }\nscrollVersionLinkParser\n popularity 0.006294\n extends abstractTextLinkParser\n string link https://scroll.pub\n description Print Scroll version.\n javascript\n get text() {\n return `Built with Scroll v${this.root.scrollVersion}`\n }\nclassicFormParser\n cue classicForm\n popularity 0.006391\n description Generate input form for ScrollSet.\n extends abstractAftertextParser\n atoms cueAtom\n catchAllAtomType stringAtom\n string script\n <script>\n sendFormViaEmail = form => {\n const mailto = new URL(\"mailto:\")\n const params = []\n const { value, title } = form.querySelector('button[type=\"submit\"]')\n params.push(`subject=${encodeURIComponent(value)}`)\n params.push(`to=${encodeURIComponent(title)}`)\n const oneTextarea = form.querySelector('textarea[title=\"oneTextarea\"]')\n const body = oneTextarea ? codeMirrorInstance.getValue() : Array.from(new FormData(form)).map(([name, value]) => `${name} ${value}`).join(\"\\\\n\")\n params.push(`body=${encodeURIComponent(body)}`)\n mailto.search = params.join(\"&\")\n window.open(mailto.href, '_blank')\n }\n </script>\n string style\n <style> .scrollFormParser {\n font-family: \"Gill Sans\", \"Bitstream Vera Sans\", sans-serif;\n }\n .scrollFormParser input , .scrollFormParser textarea{\n padding: 10px;\n margin-bottom: 10px;\n width: 100%;\n box-sizing: border-box;\n } .scrollFormParser label {\n display: block;\n margin-bottom: 5px;\n }\n </style>\n javascript\n get inputs() {\n return this.root.measures.filter(measure => !measure.IsComputed).map((measure, index) => {\n const {Name, Question, IsRequired, Type} = measure\n const type = Type || \"text\"\n const placeholder = Question\n const ucFirst = Name.substr(0, 1).toUpperCase() + Name.substr(1)\n // ${index ? \"\" : \"autofocus\"}\n let tag = \"\"\n if (Type === \"textarea\")\n tag = `<textarea placeholder=\"${placeholder}\" id=\"${Name}\" name=\"${Name}\" ${IsRequired ? \"required\" : \"\"}></textarea>`\n else\n tag = `<input placeholder=\"${placeholder}\" type=\"${type}\" id=\"${Name}\" name=\"${Name}\" ${IsRequired ? \"required\" : \"\"}>`\n return `<div><label for=\"${Name}\" title=\"${IsRequired ? \"Required\" : \"\"}\">${ucFirst}${IsRequired ? \"*\" : \"\"}:</label>${tag}</div>`\n }).join(\"\\n\")\n }\n buildHtml() {\n const {isEmail, formDestination, callToAction, subject} = this\n return `${this.script}${this.style}<form ${isEmail ? \"onsubmit='sendFormViaEmail(this); return false;'\" : ` method='post' action='${formDestination}'`} class=\"scrollFormParser\">${this.inputs}<button value=\"${subject}\" title=\"${formDestination}\" class=\"scrollButton\" type=\"submit\">${callToAction}</button>${this.footer}</form>`\n }\n get callToAction() {\n return (this.isEmail ? \"Submit via email\" : (this.subject || \"Post\"))\n }\n get isEmail() {\n return this.formDestination.includes(\"@\")\n }\n get formDestination() {\n return this.getAtom(1) || \"\"\n }\n get subject() {\n return this.getAtomsFrom(2)?.join(\" \") || \"\"\n }\n get footer() {\n return \"\"\n }\nscrollFormParser\n extends classicFormParser\n cue scrollForm\n placeholderParser\n atoms cueAtom\n baseParser blobParser\n cueFromId\n single\n valueParser\n atoms cueAtom\n baseParser blobParser\n cueFromId\n single\n nameParser\n description Name for the post submission.\n atoms cueAtom stringAtom\n cueFromId\n single\n description Generate a Scroll Form.\n string copyFromExternal .codeMirror.css .scrollLibs.js .constants.js\n string requireOnce\n <link rel=\"stylesheet\" href=\".codeMirror.css\">\n <script src=\".scrollLibs.js\"></script>\n <script src=\".constants.js\"></script>\n javascript\n get placeholder() {\n return this.getParticle(\"placeholder\")?.subparticlesToString() || \"\"\n }\n get value() {\n return this.getParticle(\"value\")?.subparticlesToString() || \"\"\n }\n get footer() {\n return \"\"\n }\n get name() {\n return this.get(\"name\") || \"particles\"\n }\n get parsersBundle() {\n const parserRegex = /^[a-zA-Z0-9_]+Parser$/gm\n const clone = this.root.clone()\n const parsers = clone.filter(line => parserRegex.test(line.getLine()))\n return \"\\n\" + parsers.map(particle => {\n particle.prependLine(\"boolean suggestInAutocomplete true\")\n return particle.toString()\n }).join(\"\\n\")\n }\n get inputs() {\n const Name = this.name\n return `<textarea title=\"oneTextarea\" rows=\"${Math.min(this.root.measures.length * 2, 30)}\" placeholder=\"${this.placeholder}\" id=\"${Name}\" name=\"${Name}\"></textarea>\n <script id=\"${Name}Parsers\" type=\"text/plain\">${this.parsersBundle}</script>\n <script>{\n const parserRegex = /^[a-zA-Z0-9_]+Parser$/gm\n let {width, height} = document.getElementById('${Name}').getBoundingClientRect();\n const sp = new Particle(AppConstants.parsers)\n sp.filter(particle => particle.getLine().match(parserRegex)).forEach(part => {\n part.appendLine(\"boolean suggestInAutocomplete false\")\n })\n const customScrollParser = new HandParsersProgram(sp.toString() + document.getElementById(\"${Name}Parsers\").textContent).compileAndReturnRootParser()\n codeMirrorInstance = new ParsersCodeMirrorMode(\"custom\", () => customScrollParser, undefined, CodeMirror).register().fromTextAreaWithAutocomplete(document.getElementById(\"${Name}\"), {\n lineWrapping: false,\n lineNumbers: false\n })\n codeMirrorInstance.setSize(width, height);\n codeMirrorInstance.setValue(\\`${this.value}\\`); }</script>`\n }\n buildHtml(buildSettings) {\n return this.getHtmlRequirements(buildSettings) + super.buildHtml()\n }\nloremIpsumParser\n extends abstractAftertextParser\n cueFromId\n description Generate dummy text.\n catchAllAtomType integerAtom\n string placeholder Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n javascript\n get originalText() {\n return this.placeholder.repeat(this.howMany)\n }\n get howMany() {\n return this.getAtom(1) ? parseInt(this.getAtom(1)) : 1\n }\nnickelbackIpsumParser\n extends loremIpsumParser\n string placeholder And one day, I’ll be at the door. And lose your wings to fall in love? To the bottom of every bottle. I’m on the ledge of the eighteenth story. Why must the blind always lead the blind?\nscrollModalParser\n description A modal dialog overlay.\n extends abstractAftertextParser\n boolean isHtml true\n cue modal\n string requireOnce\n <style>\n .scrollModal {\n display: none;\n position: fixed;\n background: transparent;\n padding: 20px;\n left: 3rem;\n top: 3rem;\n right: 3rem;\n bottom: 3rem;\n z-index: 1000;\n font-family: \"IBM Plex Mono\", monospace;\n /* Frosted glass effect */\n background: rgba(0, 0, 0, 0.2);\n backdrop-filter: blur(8px);\n -webkit-backdrop-filter: blur(8px);\n border: 1px solid rgba(255, 255, 255, 0.1);\n box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);\n border-radius: 8px;\n overflow: hidden;\n }\n .scrollModal .closeButton {\n position: absolute;\n top: 10px;\n right: 10px;\n width: 30px;\n height: 30px;\n border: none;\n background: rgba(255, 255, 255, 0.1);\n color: rgba(255, 255, 255, 0.8);\n border-radius: 4px;\n cursor: pointer;\n font-family: \"IBM Plex Mono\", monospace;\n font-size: 18px;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all 0.2s ease;\n }\n .scrollModal .closeButton:hover {\n background: rgba(255, 255, 255, 0.2);\n color: white;\n }\n </style>\n <script>{\n window.closeModal = modal => {\n modal.style.display = 'none';\n history.pushState(\"\", document.title, window.location.pathname + window.location.search);\n };\n window.openModal = (id, event) => {\n if (event) event.modalJustOpened = true;\n document.querySelector(\"#\" + id).style.display = 'block';\n };\n window.addEventListener('hashchange', () => {\n const modalId = location.hash.slice(1); window.openModal(modalId);\n });\n document.addEventListener('keydown', e => {\n if (e.key === 'Escape') \n document.querySelectorAll('.scrollModal').forEach(closeModal);\n });\n // Check hash on initial load\n document.addEventListener(\"DOMContentLoaded\", e => {\n if (location.hash) \n window.openModal(location.hash.slice(1));\n });\n // Close on outside click\n document.addEventListener('click', e => {\n if (e.modalJustOpened) return;\n const modals = document.querySelectorAll('.scrollModal');\n modals.forEach(modal => {\n if (modal.style.display === 'block' && !modal.contains(e.target)) {\n closeModal(modal);\n }\n });\n });\n }</script>\n javascript\n buildHtml(buildSettings) {\n this.parent.sectionStack.push(\"</div>\")\n return this.getHtmlRequirements(buildSettings) + `<div class=\"scrollModal\" id=\"${this.htmlId}\"><button class=\"closeButton\" onclick=\"closeModal(this.parentElement)\">×</button>`\n }\nprintSnippetsParser\n popularity 0.000338\n // todo: why are we extending AT here and not loops? Is it for class/id etc?\n extends abstractAftertextParser\n cueFromId\n atoms cueAtom\n catchAllAtomType tagWithOptionalFolderAtom\n description Prints snippets matching tag(s).\n example\n printSnippets index\n javascript\n makeSnippet(scrollProgram, buildSettings) {\n const {endSnippetIndex} = scrollProgram\n if (endSnippetIndex === -1) return scrollProgram.buildHtmlSnippet(buildSettings) + scrollProgram.editHtml\n const linkRelativeToCompileTarget = buildSettings.relativePath + scrollProgram.permalink\n const joinChar = \"\\n\"\n const html = scrollProgram\n .map((subparticle, index) => (index >= endSnippetIndex ? \"\" : subparticle.buildHtmlSnippet ? subparticle.buildHtmlSnippet(buildSettings) : subparticle.buildHtml(buildSettings)))\n .filter(i => i)\n .join(joinChar)\n .trim() +\n `<a class=\"scrollContinueReadingLink\" href=\"${linkRelativeToCompileTarget}\">Continue reading...</a>`\n return html\n }\n get files() {\n const thisFile = this.parent.file\n const files = this.root.getFilesByTags(this.content, this.has(\"limit\") ? parseInt(this.get(\"limit\")) : undefined).filter(file => file.file !== thisFile)\n // allow sortBy lastCommit Time\n if (this.get(\"sortBy\") === \"commitTime\") {\n return this.root.sortBy(files, file => file.scrollProgram.lastCommitTime).reverse()\n }\n return files\n }\n buildHtml() {\n const alreadyRequired = this.root.alreadyRequired\n const snippets = this.files.map(file => {\n const buildSettings = {relativePath: file.relativePath, alreadyRequired }\n return `<div class=\"scrollSnippetContainer\">${this.makeSnippet(file.file.scrollProgram, buildSettings)}</div>`\n }).join(\"\\n\\n\")\n return `<div class=\"scrollColumns\" style=\"column-width:35ch;\">${snippets}</div>`\n }\n buildTxt() {\n return this.files.map(file => {\n const {scrollProgram} = file.file\n const {title, date, absoluteLink} = scrollProgram\n const ruler = \"=\".repeat(title.length)\n // Note: I tried to print the description here but the description generating code needs work.\n return `${title}\\n${ruler}\\n${date}\\n${absoluteLink}`\n }).join(\"\\n\\n\")\n }\nscrollNavParser\n popularity 0.000048\n extends printSnippetsParser\n cue fileNav\n description Titles and links in group(s).\n joinParser\n boolean allowTrailingWhitespace true\n cueFromId\n atoms cueAtom\n catchAllAtomType stringAtom\n javascript\n buildHtml() {\n return `<nav class=\"scrollNavParser\">` + this.root.getFilesByTags(this.content).map(file => {\n const { linkTitle, permalink } = file.file.scrollProgram\n return `<a href=\"${permalink}\">${linkTitle}</a>` \n }).join(this.get(\"join\") || \" \") + `</nav>`\n }\nprintFullSnippetsParser\n popularity 0.000048\n extends printSnippetsParser\n cueFromId\n description Print full pages in group(s).\n javascript\n makeSnippet(scrollProgram, buildSettings) {\n return scrollProgram.buildHtmlSnippet(buildSettings) + scrollProgram.editHtml\n }\nprintShortSnippetsParser\n popularity 0.000048\n extends printSnippetsParser\n cueFromId\n description Titles and descriptions in group(s).\n javascript\n makeSnippet(scrollProgram, buildSettings) {\n const { title, permalink, description, timestamp } = scrollProgram\n return `<div><a href=\"${permalink}\">${title}</a><div>${description}...</div><div class=\"subdued\" style=\"text-align:right;\">${this.root.dayjs(timestamp * 1000).format(`MMMM D, YYYY`)}</div></div>`\n }\nprintRelatedParser\n popularity 0.001182\n description Print links to related posts.\n extends printSnippetsParser\n cueFromId\n javascript\n buildHtml() {\n const alreadyRequired = this.root.alreadyRequired\n const list = this.files.map(fileWrapper => {\n const {relativePath, file} = fileWrapper\n const {title, permalink, year} = file.scrollProgram\n return `- ${title}${year ? \" (\" + year + \")\" : \"\"}\\n link ${relativePath + permalink}`\n }).join(\"\\n\")\n const items = this.parent.concat(list)\n const html = items.map(item => item.buildHtml()).join(\"\\n\")\n items.forEach(item => item.destroy())\n return html\n }\nscrollNoticesParser\n extends abstractAftertextParser\n description Display messages in URL query parameters.\n cue notices\n javascript\n buildHtml() {\n const id = this.htmlId\n return `<div id=\"${id}\" class=\"scrollNoticesParser\" style=\"display:none;\"></div><script>(function(){\n const params = new URLSearchParams(window.location.search)\n if (!params.size) return\n document.getElementById('${id}').innerHTML = Array.from(params.entries()).map(([key, value]) => {\n if (key === \"error\") \n return '<div style=\"color:red\">Error: ' + value + '</div>'\n if (key === \"success\")\n return '<div style=\"color:green\">Success: ' + value + '</div>'\n return '<div>' + key + ': ' + value + '</div>'\n }).join(\"\") || \"No query parameters found\"\n document.getElementById('${id}').style.display = \"block\"\n })()</script>`\n }\nabstractAssertionParser\n description Test above particle's output.\n extends abstractScrollParser\n string bindTo previous\n catchAllAtomType codeAtom\n cueFromId\n javascript\n buildHtml() {\n return ``\n }\n get particleToTest() {\n // If the previous particle is also an assertion particle, use the one before that.\n return this.previous.particleToTest ? this.previous.particleToTest : this.previous\n }\n get actual() {return this.particleToTest.buildHtml()}\n getErrors() {\n const {actual, expected} = this\n const errors = super.getErrors()\n if (this.areEqual(actual, expected))\n return errors\n return errors.concat(this.makeError(`'${actual}' did not ${this.kind} '${expected}'`))\n }\n get expected() {\n return this.length ? this.subparticlesToString() : (this.content ? this.content : \"\")\n }\n catchAllParser htmlLineParser\nassertHtmlEqualsParser\n extends abstractAssertionParser\n string kind equal\n example\n <b></b>\n assertHtmlEquals <b></b>\n javascript\n areEqual(actual, expected) {\n return actual === expected\n }\n // todo: why are we having to super here?\n getErrors() { return super.getErrors()}\nassertBuildIncludesParser\n extends abstractAssertionParser\n string kind include\n example\n buildCsv\n assertBuildIncludes virginica\n javascript\n areEqual(actual, expected) {\n return actual.includes(expected)\n }\n get actual() { return this.particleToTest.buildOutput()}\n getErrors() { return super.getErrors()}\nassertHtmlIncludesParser\n extends abstractAssertionParser\n string kind include\n javascript\n areEqual(actual, expected) {\n return actual.includes(expected)\n }\n getErrors() { return super.getErrors()}\nassertHtmlExcludesParser\n extends abstractAssertionParser\n string kind exclude\n javascript\n areEqual(actual, expected) {\n return !actual.includes(expected)\n }\n getErrors() { return super.getErrors()}\nassertIgnoreBelowErrorsParser\n description If you want to ignore any errors in the below particle in automated tests.\n extends abstractScrollParser\n string bindTo next\n cueFromId\nabstractPrintMetaParser\n extends abstractScrollParser\n cueFromId\nprintAuthorsParser\n popularity 0.001664\n description Prints author(s) byline.\n boolean isPopular true\n extends abstractPrintMetaParser\n // todo: we need pattern matching added to sdk to support having no params or a url and personNameAtom\n catchAllAtomType stringAtom\n example\n authors Breck Yunits\n https://breckyunits.com\n printAuthors\n javascript\n buildHtml() {\n return this.parent.getParticle(\"authors\")?.buildHtmlForPrint()\n }\n buildTxt() {\n return this.parent.getParticle(\"authors\")?.buildTxtForPrint()\n }\nprintDateParser\n popularity 0.000434\n extends abstractPrintMetaParser\n // If not present computes the date from the file's ctime.\n description Print published date.\n boolean isPopular true\n example\n date 1/11/2019\n printDate\n javascript\n buildHtml() {\n return `<div class=\"printDateParser\">${this.day}</div>`\n }\n get day() {\n let day = this.content || this.root.date\n if (!day) return \"\"\n return this.root.dayjs(day).format(`MMMM D, YYYY`)\n }\n buildTxt() {\n return this.day\n }\nprintFormatLinksParser\n description Prints links to other formats.\n extends abstractPrintMetaParser\n example\n printFormatLinks\n javascript\n buildHtml() {\n const permalink = this.root.permalink.replace(\".html\", \"\")\n // hacky\n const particle = this.appendSibling(`HTML | TXT`, `class printDateParser\\nlink ${permalink}.html HTML\\nlink ${permalink}.txt TXT\\nstyle text-align:center;`)\n const html = particle.buildHtml()\n particle.destroy()\n return html\n }\n buildTxt() {\n const permalink = this.root.permalink.replace(\".html\", \"\")\n return `HTML | TXT\\n link ${permalink}.html HTML\\n link ${permalink}.txt TXT`\n }\nabstractBuildCommandParser\n extends abstractScrollParser\n cueFromId\n atoms buildCommandAtom\n catchAllAtomType filePathAtom\n inScope slashCommentParser\n javascript\n isTopMatter = true\n buildHtml() {\n return \"\"\n }\n get extension() {\n return this.cue.replace(\"build\", \"\")\n }\n buildOutput() {\n return this.root.compileTo(this.extension)\n }\n get outputFileNames() {\n return this.content?.split(\" \") || [this.root.permalink.replace(\".html\", \".\" + this.extension.toLowerCase())]\n }\n async _buildFileType(extension, options) {\n const {root} = this\n const { fileSystem, folderPath, filename, filePath, path, lodash } = root\n const capitalized = lodash.capitalize(extension)\n const buildKeyword = \"build\" + capitalized\n const {outputFileNames} = this\n for (let name of outputFileNames) {\n try {\n await fileSystem.writeProduct(path.join(folderPath, name), root.compileTo(capitalized))\n root.log(`💾 Built ${name} from ${filename}`)\n } catch (err) {\n console.error(`Error while building '${filePath}' with extension '${extension}'`)\n throw err\n }\n }\n }\nabstractBuildOneCommandParser\n // buildOne and buildTwo are just a dumb/temporary way to have CSVs/JSONs/TSVs build first. Will be merged at some point.\n extends abstractBuildCommandParser\n javascript\n async buildOne(options) { await this._buildFileType(this.extension, options) }\nbuildParsersParser\n popularity 0.000096\n description Compile to Parsers file.\n extends abstractBuildOneCommandParser\nbuildCsvParser\n popularity 0.000096\n example\n buildCsv\n description Compile to CSV file.\n extends abstractBuildOneCommandParser\nbuildTsvParser\n popularity 0.000096\n description Compile to TSV file.\n extends abstractBuildOneCommandParser\nbuildJsonParser\n popularity 0.000096\n description Compile to JSON file.\n extends abstractBuildOneCommandParser\nabstractBuildTwoCommandParser\n extends abstractBuildCommandParser\n javascript\n async buildTwo(options) {\n await this._buildFileType(this.extension, options)\n }\nbuildCssParser\n popularity 0.000048\n description Compile to CSS file.\n extends abstractBuildTwoCommandParser\n example\n buildCss\nbuildHtmlParser\n popularity 0.007645\n description Compile to HTML file.\n extends abstractBuildTwoCommandParser\n boolean isPopular true\n javascript\n async buildTwo(options) {\n await this._copyExternalFiles(options)\n await super.buildTwo(options)\n }\n async _copyExternalFiles(options) {\n if (!this.isNodeJs()) return\n const {root} = this\n const externalFilesCopied = options.externalFilesCopied || {}\n // If this file uses a parser that has external requirements,\n // copy those from external folder into the destination folder.\n const { parsersRequiringExternals, folderPath, fileSystem, filename, parserIdIndex, path, Disk, externalsPath } = root\n if (!externalFilesCopied[folderPath]) externalFilesCopied[folderPath] = {}\n parsersRequiringExternals.forEach(parserId => {\n if (externalFilesCopied[folderPath][parserId]) return\n if (!parserIdIndex[parserId]) return\n parserIdIndex[parserId].map(particle => {\n const externalFiles = particle.copyFromExternal.split(\" \")\n externalFiles.forEach(name => {\n const newPath = path.join(folderPath, name)\n fileSystem.writeProduct(newPath, Disk.read(path.join(externalsPath, name)))\n root.log(`💾 Copied external file needed by ${filename} to ${name}`)\n })\n })\n if (parserId !== \"scrollThemeParser\")\n // todo: generalize when not to cache\n externalFilesCopied[folderPath][parserId] = true\n })\n }\nbuildJsParser\n description Compile to JS file.\n extends abstractBuildTwoCommandParser\nbuildRssParser\n popularity 0.000048\n description Compile to RSS file.\n extends abstractBuildTwoCommandParser\nbuildTxtParser\n popularity 0.007596\n description Compile to TXT file.\n extends abstractBuildTwoCommandParser\n boolean isPopular true\nloadConceptsParser\n // todo: clean this up. just add smarter imports with globs?\n // this currently removes any \"import\" statements.\n description Import all concepts in a folder.\n extends abstractBuildCommandParser\n cueFromId\n atoms preBuildCommandAtom filePathAtom\n javascript\n async load() {\n const { Disk, path, importRegex } = this.root\n const folder = path.join(this.root.folderPath, this.getAtom(1))\n const ONE_BIG_FILE = Disk.getFiles(folder).filter(file => file.endsWith(\".scroll\")).map(Disk.read).join(\"\\n\\n\").replace(importRegex, \"\")\n this.parent.concat(ONE_BIG_FILE)\n //console.log(ONE_BIG_FILE)\n }\n buildHtml() {\n return \"\"\n }\nbuildConceptsParser\n popularity 0.000024\n cueFromId\n description Compile concepts to delimited files.\n extends abstractBuildCommandParser\n sortByParser\n cueFromId\n atoms cueAtom columnNameAtom\n javascript\n async buildOne() {\n const {root} = this\n const { fileSystem, folderPath, filename, path, permalink } = root\n const files = this.getAtomsFrom(1)\n if (!files.length) files.push(permalink.replace(\".html\", \".csv\"))\n const sortBy = this.get(\"sortBy\")\n for (let link of files) {\n await fileSystem.writeProduct(path.join(folderPath, link), root.compileConcepts(link, sortBy))\n root.log(`💾 Built concepts in ${filename} to ${link}`)\n }\n }\nfetchParser\n description Download URL to disk.\n extends abstractBuildCommandParser\n cueFromId\n atoms preBuildCommandAtom urlAtom\n example\n fetch https://breckyunits.com/posts.csv\n fetch https://breckyunits.com/posts.csv renamed.csv\n javascript\n get url() {\n return this.getAtom(1)\n }\n get filename() {\n return this.getAtom(2)\n }\n async load() {\n await this.root.fetch(this.url, this.filename)\n }\n buildHtml() {\n return \"\"\n }\nbuildMeasuresParser\n popularity 0.000024\n cueFromId\n description Compile measures to delimited files.\n extends abstractBuildCommandParser\n sortByParser\n cueFromId\n atoms cueAtom columnNameAtom\n javascript\n async buildOne() {\n const {root} = this\n const { fileSystem, folderPath, filename, path, permalink } = root\n const files = this.getAtomsFrom(1)\n if (!files.length) files.push(permalink.replace(\".html\", \".csv\"))\n const sortBy = this.get(\"sortBy\")\n for (let link of files) {\n await fileSystem.writeProduct(path.join(folderPath, link), root.compileMeasures(link, sortBy))\n root.log(`💾 Built measures in ${filename} to ${link}`)\n }\n }\nbuildPdfParser\n popularity 0.000096\n description Compile to PDF file.\n extends abstractBuildCommandParser\n javascript\n async buildTwo(options) {\n if (!this.isNodeJs()) return \"Only works in Node currently.\"\n const {root} = this\n const { filename } = root\n const outputFile = root.filenameNoExtension + \".pdf\"\n // relevant source code for chrome: https://github.com/chromium/chromium/blob/a56ef4a02086c6c09770446733700312c86f7623/components/headless/command_handler/headless_command_switches.cc#L22\n const command = `/Applications/Google\\\\ Chrome.app/Contents/MacOS/Google\\\\ Chrome --headless --disable-gpu --no-pdf-header-footer --default-background-color=00000000 --no-pdf-background --print-to-pdf=\"${outputFile}\" \"${root.permalink}\"`\n // console.log(`Node.js is running on architecture: ${process.arch}`)\n try {\n const output = require(\"child_process\").execSync(command, { stdio: \"ignore\" })\n root.log(`💾 Built ${outputFile} from ${filename}`)\n } catch (error) {\n console.error(error)\n }\n }\nabstractInlineFileParser\n extends abstractScrollParser\n catchAllAtomType filePathAtom\n catchAllParser scrollFileAddressParser\n string joinChar ;\\n\\n\n string htmlTag script\n javascript\n get files() {\n const inline = this.atoms.slice(1)\n const children = this.map(particle => particle.cue)\n return inline.concat(children)\n }\n get contents() {\n return this.files.map(filename => this.root.readFile(filename)).join(this.joinChar)\n }\n buildHtml() {\n return `<${this.htmlTag}>/* ${this.files.join(\" \")} */\\n${this.contents}</${this.htmlTag}>`\n }\nscrollInlineCssParser\n description Inline CSS from files.\n popularity 0.007211\n extends abstractInlineFileParser\n cue inlineCss\n string joinChar \\n\\n\n string htmlTag style\n javascript\n buildCss() {\n return this.contents\n }\nscrollInlineJsParser\n description Inline JS from files.\n popularity 0.007211\n extends abstractInlineFileParser\n cue inlineJs\n javascript\n buildJs() {\n return this.contents\n }\nabstractTopLevelSingleMetaParser\n description Use these parsers once per file.\n extends abstractScrollParser\n inScope slashCommentParser\n cueFromId\n atoms metaCommandAtom\n javascript\n isTopMatter = true\n isSetterParser = true\n buildHtml() {\n return \"\"\n }\ntestStrictParser\n description Make catchAllParagraphParser = error.\n extends abstractTopLevelSingleMetaParser\nscrollDateParser\n cue date\n popularity 0.006680\n catchAllAtomType dateAtom\n description Set published date.\n extends abstractTopLevelSingleMetaParser\n boolean isPopular true\n example\n date 1/11/2019\n printDate\n Hello world\n dateline\nabstractUrlSettingParser\n extends abstractTopLevelSingleMetaParser\n atoms metaCommandAtom urlAtom\n cueFromId\neditBaseUrlParser\n popularity 0.007838\n description Override edit link baseUrl.\n extends abstractUrlSettingParser\ncanonicalUrlParser\n description Override canonical URL.\n extends abstractUrlSettingParser\nopenGraphImageParser\n popularity 0.000796\n // https://ogp.me/\n // If not defined, Scroll will try to generate it's own using the first image tag on your page.\n description Override Open Graph Image.\n extends abstractUrlSettingParser\nbaseUrlParser\n popularity 0.009188\n description Required for RSS and OpenGraph.\n extends abstractUrlSettingParser\n example\n baseUrl https://hub.scroll.pub/\nrssFeedUrlParser\n popularity 0.008850\n description Set RSS feed URL.\n extends abstractUrlSettingParser\neditUrlParser\n catchAllAtomType urlAtom\n description Override edit link.\n extends abstractTopLevelSingleMetaParser\nsiteOwnerEmailParser\n popularity 0.001302\n description Set email address for site contact.\n extends abstractTopLevelSingleMetaParser\n cue email\n atoms metaCommandAtom emailAddressAtom\nfaviconParser\n popularity 0.001688\n catchAllAtomType stringAtom\n cue favicon\n description Favicon file.\n example\n favicon logo.png\n metatags\n buildHtml\n extends abstractTopLevelSingleMetaParser\nimportOnlyParser\n popularity 0.033569\n // This line will be not be imported into the importing file.\n description Don't build this file.\n cueFromId\n atoms preBuildCommandAtom\n extends abstractTopLevelSingleMetaParser\n javascript\n buildHtml() {\n return \"\"\n }\ninlineMarkupsParser\n popularity 0.000024\n description Set global inline markups.\n extends abstractTopLevelSingleMetaParser\n cueFromId\n example\n inlineMarkups\n * \n // Disable * for bold\n _ u\n // Make _ underline\nhtmlLangParser\n atoms metaCommandAtom stringAtom\n // for the <html lang=\"\"> tag. If not specified will be \"en\". See https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang\n description Override HTML lang attribute.\n extends abstractTopLevelSingleMetaParser\nopenGraphDescriptionParser\n popularity 0.001688\n catchAllAtomType stringAtom\n cue description\n description Description for SEO meta tag.\n extends abstractTopLevelSingleMetaParser\nopenGraphKeywordsParser\n popularity 0.001688\n catchAllAtomType stringAtom\n cue keywords\n description Keywords for SEO meta tag.\n extends abstractTopLevelSingleMetaParser\npermalinkParser\n popularity 0.000265\n description Override output filename.\n extends abstractTopLevelSingleMetaParser\n atoms metaCommandAtom permalinkAtom\nscrollTagsParser\n popularity 0.006801\n cue tags\n description Set tags.\n example\n tags All\n extends abstractTopLevelSingleMetaParser\n catchAllAtomType tagAtom\nscrollTitleParser\n popularity 0.007524\n catchAllAtomType stringAtom\n cue title\n description Set title.\n example\n title Eureka\n printTitle\n extends abstractTopLevelSingleMetaParser\n boolean isPopular true\nscrollLinkTitleParser\n popularity 0.007524\n catchAllAtomType stringAtom\n cue linkTitle\n description Text for links.\n example\n title My blog - Eureka\n linkTitle Eureka\n extends abstractTopLevelSingleMetaParser\nscrollChatParser\n popularity 0.000362\n description A faux text chat conversation.\n catchAllParser chatLineParser\n cue chat\n extends abstractScrollParser\n example\n chat\n Hi\n 👋\n javascript\n buildHtml() {\n return this.map((line, index) => line.asString ? `<div style=\"text-align: ${index % 2 ? \"right\" : \"left\"};\" class=\"scrollChat ${index % 2 ? \"scrollChatRight\" : \"scrollChatLeft\"}\"><span>${line.asString}</span></div>` : \"\").join(\"\")\n }\n buildTxt() {\n return this.subparticlesToString()\n }\nabstractDatatableProviderParser\n description A datatable.\n extends abstractScrollParser\n inScope scrollTableDataParser scrollTableDelimiterParser abstractTableVisualizationParser abstractTableTransformParser h1Parser h2Parser scrollQuestionParser htmlInlineParser scrollBrParser slashCommentParser\n javascript\n get visualizations() {\n return this.topDownArray.filter(particle => particle.isTableVisualization || particle.isHeader || particle.isHtml)\n }\n buildHtml(buildSettings) {\n return this.visualizations.map(particle => particle.buildHtml(buildSettings))\n .join(\"\\n\")\n .trim()\n }\n buildTxt() {\n return this.visualizations.map(particle => particle.buildTxt())\n .join(\"\\n\")\n .trim()\n }\n _coreTable\n get coreTable() {\n if (this._coreTable) return this._coreTable\n const {delimiter, delimitedData} = this\n return []\n }\n get columnNames() {\n return []\n }\nscrollTableParser\n extends abstractDatatableProviderParser\n popularity 0.002133\n cue table\n example\n table\n printTable\n data\n year,count\n 1900,10\n 2000,122\n 2020,23\n catchAllAtomType filePathAtom\n int atomIndex 1\n javascript\n get delimiter() {\n const {filename} = this\n let delimiter = \"\"\n if (filename) {\n const extension = filename.split('?')[0].split(\".\").pop()\n if (extension === \"json\") delimiter = \"json\"\n if (extension === \"particles\") delimiter = \"particles\"\n if (extension === \"csv\") delimiter = \",\"\n if (extension === \"tsv\") delimiter = \"\\t\"\n if (extension === \"ssv\") delimiter = \" \"\n if (extension === \"psv\") delimiter = \"|\"\n }\n if (this.get(\"delimiter\"))\n delimiter = this.get(\"delimiter\")\n else if (!delimiter) {\n const header = this.delimitedData.split(\"\\n\")[0]\n if (header.includes(\"\\t\"))\n delimiter = \"\\t\"\n else if (header.includes(\",\"))\n delimiter = \",\"\n else\n delimiter = \" \"\n }\n return delimiter\n }\n get filename() {\n return this.getAtom(this.atomIndex)\n }\n get coreTable() {\n if (this._coreTable) return this._coreTable\n const {delimiter, delimitedData} = this\n if (delimiter === \"json\") {\n const obj = JSON.parse(delimitedData)\n let rows = []\n // Optimal case: Array of objects\n if (Array.isArray(obj)) { rows = obj}\n else if (!Array.isArray(obj) && typeof obj === \"object\") {\n // Case 2: Nested array under a key\n const arrayKey = Object.keys(obj).find(key => Array.isArray(obj[key]))\n if (arrayKey) rows = obj[arrayKey]\n }\n // Case 3: Array of primitive values\n else if (Array.isArray(obj) && obj.length && typeof obj[0] !== \"object\") {\n rows = obj.map(value => ({ value }))\n }\n this._columnNames = rows.length ? Object.keys(rows[0]) : []\n this._coreTable = rows\n return rows\n }\n else if (delimiter === \"particles\") {\n const d3lib = this.root.d3\n this._coreTable = d3lib.dsvFormat(\",\").parse(new Particle(delimitedData).asCsv, d3lib.autoType)\n } else {\n const d3lib = this.root.d3\n this._coreTable = d3lib.dsvFormat(delimiter).parse(delimitedData, d3lib.autoType)\n }\n this._columnNames = this._coreTable.columns\n delete this._coreTable.columns\n return this._coreTable\n }\n get columnNames() {\n // init coreTable to set columns\n const coreTable = this.coreTable\n return this._columnNames\n }\n async load() {\n if (this.filename)\n await this.root.fetch(this.filename)\n }\n get fileContent() {\n return this.root.readSyncFromFileOrUrl(this.filename)\n }\n get delimitedData() {\n // json csv tsv\n if (this.filename)\n return this.fileContent\n const dataParticle = this.getParticle(\"data\")\n if (dataParticle)\n return dataParticle.subparticlesToString()\n // if not dataparticle and no filename, check [permalink].csv\n if (this.isNodeJs())\n return this.root.readFile(this.root.permalink.replace(\".html\", \"\") + \".csv\")\n return \"\"\n }\nclocParser\n extends scrollTableParser\n description Output results of cloc as table.\n cue cloc\n string copyFromExternal .clocLangs.txt\n javascript\n delimiter = \",\"\n get delimitedData() {\n const { execSync } = require(\"child_process\")\n const results = execSync(this.command).toString().trim()\n const csv = results.split(\"\\n\\n\").pop().replace(/,\\\"github\\.com\\/AlDanial.+/, \"\") // cleanup output\n return csv\n }\n get command(){\n return `cloc --vcs git . --csv --read-lang-def=.clocLangs.txt ${this.content || \"\"}`\n }\nscrollDependenciesParser\n extends scrollTableParser\n description Get files this file depends on.\n cue dependencies\n javascript\n delimiter = \",\"\n get delimitedData() {\n return `file\\n` + this.root.dependencies.join(\"\\n\")\n }\nscrollDiskParser\n extends scrollTableParser\n description Output file into as table.\n cue disk\n javascript\n delimiter = \"json\"\n get delimitedData() {\n return this.isNodeJs() ? this.delimitedDataNodeJs : \"\"\n }\n get delimitedDataNodeJs() {\n const fs = require('fs');\n const path = require('path');\n const {folderPath} = this.root\n const folder = this.content ? path.join(folderPath, this.content) : folderPath\n function getDirectoryContents(dirPath) {\n const directoryContents = [];\n const items = fs.readdirSync(dirPath);\n items.forEach((item) => {\n const itemPath = path.join(dirPath, item);\n const stats = fs.statSync(itemPath);\n directoryContents.push({\n name: item,\n type: stats.isDirectory() ? 'directory' : 'file',\n size: stats.size,\n lastModified: stats.mtime\n });\n });\n return directoryContents;\n }\n return JSON.stringify(getDirectoryContents(folder))\n }\nscrollIrisParser\n extends scrollTableParser\n description Iris dataset from R.A. Fisher.\n cue iris\n example\n iris\n printTable\n scatter\n x SepalLength\n y SepalWidth\n javascript\n delimitedData = this.constructor.iris\nvegaSampleDataParser\n extends scrollTableParser\n description Sample dataset from Vega.\n cue sampleData\n atoms cueAtom vegaDataSetAtom\n example\n sampleData zipcodes.csv\n printTable\n javascript\n get filename() {\n return \"https://ohayo.scroll.pub/ohayo/packages/vega/datasets/\" + this.content\n }\nquickTableParser\n popularity 0.000024\n extends scrollTableParser\n atoms urlAtom\n pattern ^[^\\s]+\\.(tsv|csv|ssv|psv|json)[^\\s]*$\n int atomIndex 0\n javascript\n get dependencies() { return [this.cue]}\nscrollConceptsParser\n description Load concepts as table.\n extends abstractDatatableProviderParser\n cue concepts\n atoms cueAtom\n example\n concepts\n printTable\n javascript\n get coreTable() {\n return this.root.concepts\n }\n get columnNames() {\n return this.root.measures.map(col => col.Name)\n }\nabstractPostsParser\n description Load posts as table.\n extends abstractDatatableProviderParser\n cueFromId\n atoms cueAtom\n catchAllAtomType tagWithOptionalFolderAtom\n javascript\n async load() {\n const dependsOn = this.tags.map(tag => this.root.parseNestedTag(tag)).filter(i => i).map(i => i.folderPath)\n const {fileSystem} = this.root\n for (let folderPath of dependsOn) {\n // console.log(`${this.root.filePath} is loading: ${folderPath} in id '${fileSystem.fusionId}'`)\n await fileSystem.getLoadedFilesInFolder(folderPath, \".scroll\")\n }\n }\n get tags() {\n return this.content?.split(\" \") || []\n }\n get files() {\n const thisFile = this.root.file\n // todo: we can include this file, but just not run asTxt\n const files = this.root.getFilesByTags(this.tags).filter(file => file.file !== thisFile)\n return files\n }\n get coreTable() {\n if (this._coreTable) return this._coreTable\n this._coreTable = this.files.map(file => this.postToRow(file))\n return this._coreTable\n }\n postToRow(file) {\n const {relativePath} = file\n const {scrollProgram} = file.file\n const {title, permalink, asTxt, date, wordCount, minutes} = scrollProgram\n const text = asTxt.replace(/(\\t|\\n)/g, \" \").replace(/</g, \"&lt;\")\n return {\n title, titleLink: relativePath + permalink, text, date, wordCount, minutes\n }\n }\n columnNames = \"title titleLink text date wordCount minutes\".split(\" \")\nscrollPostsParser\n popularity 0.000024\n cue posts\n description Posts as table.\n extends abstractPostsParser\n example\n // Print a search table:\n posts\n printTable\n tableSearch\n // Dump a CSV of blog:\n buildHtml\n buildCsv\n buildJson\nscrollPostsMetaParser\n popularity 0.000024\n cue postsMeta\n description Post meta as table.\n extends abstractPostsParser\n javascript\n columnNames = [\"date\", \"year\", \"title\", \"permalink\", \"authors\", \"tags\", \"wordCount\", \"minutes\"]\n postToRow(file) {\n const {date, year, title, permalink, authors, tags, wordCount, minutes} = file.file.scrollProgram\n return {\n date, year, title, permalink, authors, tags, wordCount, minutes\n }\n }\nprintFeedParser\n popularity 0.000048\n description Print group to RSS.\n extends abstractPostsParser\n example\n printFeed index\n printFeed cars/index\n buildRss\n javascript\n buildRss() {\n const {dayjs} = this.root\n const scrollPrograms = this.files.map(file => file.file.scrollProgram)\n const { title, baseUrl, description } = this.root\n return `<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n <rss version=\"2.0\">\n <channel>\n <title>${title}</title>\n <link>${baseUrl}</link>\n <description>${description}</description>\n <lastBuildDate>${dayjs().format(\"ddd, DD MMM YYYY HH:mm:ss ZZ\")}</lastBuildDate>\n <language>en-us</language>\n ${scrollPrograms.map(program => program.toRss()).join(\"\\n\")}\n </channel>\n </rss>`\n }\n buildTxt() {\n return this.buildRss()\n }\nprintSourceParser\n popularity 0.000024\n description Print source for files in group(s).\n extends printFeedParser\n example\n printSource index\n buildTxt source.txt\n javascript\n buildHtml() {\n const files = this.root.getFilesByTags(this.content).map(file => file.file)\n return `${files.map(file => file.filePath + \"\\n \" + file.codeAtStart.replace(/\\n/g, \"\\n \") ).join(\"\\n\")}`\n }\nprintSiteMapParser\n popularity 0.000072\n extends abstractPostsParser\n description Print text sitemap.\n example\n baseUrl http://test.com\n printSiteMap\n javascript\n buildHtml() {\n const { baseUrl } = this.root\n return this.files.map(file => baseUrl + file.relativePath + file.file.scrollProgram.permalink).join(\"\\n\")\n }\n buildTxt() {\n return this.buildHtml()\n }\n get dependencies() { return this.files}\ncodeParser\n popularity 0.001929\n description A code block.\n catchAllParser lineOfCodeParser\n extends abstractScrollParser\n boolean isPopular true\n example\n code\n two = 1 + 1\n javascript\n buildHtml() {\n return `<code class=\"scrollCodeBlock\">${this.code.replace(/\\</g, \"&lt;\")}</code>`\n }\n buildTxt() {\n return \"```\\n\" + this.code + \"\\n```\"\n }\n get code() {\n return this.subparticlesToString()\n }\n cueFromId\ncodeWithHeaderParser\n popularity 0.000169\n cueFromId\n catchAllAtomType stringAtom\n extends codeParser\n example\n codeWithHeader math.py\n two = 1 + 1\n javascript\n buildHtml() {\n return `<div class=\"codeWithHeader\"><div class=\"codeHeader\">${this.content}</div>${super.buildHtml()}</div>`\n }\n buildTxt() {\n return \"```\" + this.content + \"\\n\" + this.code + \"\\n```\"\n }\ncodeFromFileParser\n popularity 0.000169\n cueFromId\n atoms cueAtom urlAtom\n extends codeWithHeaderParser\n example\n codeFromFile math.py\n javascript\n get code() {\n return this.root.readSyncFromFileOrUrl(this.content)\n }\ncodeWithLanguageParser\n popularity 0.000458\n description Use this to specify the language of the code block, such as csvCode or rustCode.\n extends codeParser\n pattern ^[a-zA-Z0-9_]+Code$\ndebugParsersParser\n description Print the parsers used.\n extends codeParser\n cueFromId\n javascript\n buildParsers() { return this.code}\n get code() {\n let code = new Particle(this.root.definition.toString())\n // Remove comments\n code.filter((line) => line.getLine().startsWith(\"//\")).forEach((particle) => particle.destroy())\n // Remove blank lines\n code = code.toString().replace(/^\\n/gm, \"\")\n return code\n }\nabstractScrollWithRequirementsParser\n extends abstractScrollParser\n cueFromId\n javascript\n buildHtml(buildSettings) {\n return this.getHtmlRequirements(buildSettings) + this.buildInstance()\n }\ncopyButtonsParser\n popularity 0.001471\n extends abstractScrollWithRequirementsParser\n description Copy code widget.\n javascript\n buildInstance() {\n return \"\"\n }\n string requireOnce\n <script>\n document.addEventListener(\"DOMContentLoaded\", () => document.querySelectorAll(\".scrollCodeBlock\").forEach(block =>\n {\n if (!navigator.clipboard) return\n const button = document.createElement(\"span\")\n button.classList.add(\"scrollCopyButton\")\n block.appendChild(button)\n button.addEventListener(\"click\", async () => {\n await navigator.clipboard.writeText(block.innerText)\n button.classList.add(\"scrollCopiedButton\")\n })\n }\n ))\n </script>\nabstractTableVisualizationParser\n extends abstractScrollWithRequirementsParser\n boolean isTableVisualization true\n javascript\n get columnNames() {\n return this.parent.columnNames\n }\nheatrixParser\n cueFromId\n example\n heatrix\n '2007 '2008 '2009 '2010 '2011 '2012 '2013 '2014 '2015 '2016 '2017 '2018 '2019 '2020 '2021 '2022 '2023 '2024\n 4 11 23 37 3 14 12 0 0 0 5 1 2 11 15 10 12 56\n description A heatmap matrix data visualization.\n catchAllParser heatrixCatchAllParser\n extends abstractTableVisualizationParser\n javascript\n buildHtml() {\n // A hacky but simple way to do this for now.\n const advanced = new Particle(\"heatrixAdvanced\")\n advanced.appendLineAndSubparticles(\"table\", \"\\n \" + this.tableData.replace(/\\n/g, \"\\n \"))\n const particle = this.appendSibling(\"heatrixAdvanced\", advanced.subparticlesToString())\n const html = particle.buildHtml()\n particle.destroy()\n return html\n }\n get tableData() {\n const {coreTable} = this.parent\n if (!coreTable)\n return this.subparticlesToString()\n let table = new Particle(coreTable).asSsv\n if (this.parent.cue === \"transpose\") {\n // drop first line after transpose\n const lines = table.split(\"\\n\")\n lines.shift()\n table = lines.join(\"\\n\")\n }\n // detect years and make strings\n const lines = table.split(\"\\n\")\n const yearLine = / \\d{4}(\\s+\\d{4})+$/\n if (yearLine.test(lines[0])) {\n lines[0] = lines[0].replace(/ /g, \" '\")\n table = lines.join(\"\\n\")\n }\n return table\n }\nheatrixAdvancedParser\n popularity 0.000048\n cueFromId\n catchAllParser heatrixCatchAllParser\n extends abstractTableVisualizationParser\n description Advanced heatrix.\n example\n heatrix\n table\n \n %h10; '2007 '2008 '2009\n 12 4 323\n scale\n #ebedf0 0\n #c7e9c0 100\n #a1d99b 400\n #74c476 1600\n javascript\n buildHtml() {\n class Heatrix {\n static HeatrixId = 0\n uid = Heatrix.HeatrixId++\n constructor(program) {\n const isDirective = atom => /^(f|l|w|h)\\d+$/.test(atom) || atom === \"right\" || atom === \"left\" || atom.startsWith(\"http://\") || atom.startsWith(\"https://\") || atom.endsWith(\".html\")\n const particle = new Particle(program)\n this.program = particle\n const generateColorBinningString = (data, colors) => {\n const sortedData = [...data].sort((a, b) => a - b);\n const n = sortedData.length;\n const numBins = colors.length;\n // Calculate the indices for each quantile\n const indices = [];\n for (let i = 1; i < numBins; i++) {\n indices.push(Math.floor((i / numBins) * n));\n }\n // Get the quantile values and round them\n const thresholds = indices.map(index => Math.round(sortedData[index]));\n // Generate the string\n let result = '';\n colors.forEach((color, index) => {\n const threshold = index === colors.length - 1 ? thresholds[index - 1] * 2 : thresholds[index];\n result += `${color} ${threshold}\\n`;\n });\n return result.trim();\n }\n const buildScale = (table) => {\n const numbers = table.split(\"\\n\").map(line => line.split(\" \")).flat().filter(atom => !isDirective(atom)).map(atom => parseFloat(atom)).filter(number => !isNaN(number))\n const colors = ['#ebedf0', '#c7e9c0', '#a1d99b', '#74c476', '#41ab5d', '#238b45', '#005a32'];\n numbers.unshift(0)\n return generateColorBinningString(numbers, colors);\n }\n const table = particle.getParticle(\"table\").subparticlesToString()\n const scale = particle.getParticle(\"scale\")?.subparticlesToString() || buildScale(table)\n const thresholds = []\n const colors = []\n scale.split(\"\\n\").map((line) => {\n const parts = line.split(\" \")\n thresholds.push(parseFloat(parts[1]))\n colors.push(parts[0])\n })\n const colorCount = colors.length\n const colorFunction = (value) => {\n if (isNaN(value)) return \"\" // #ebedf0\n for (let index = 0; index < colorCount; index++) {\n const threshold = thresholds[index]\n if (value <= threshold) return colors[index]\n }\n return colors[colorCount - 1]\n }\n const directiveDelimiter = \";\"\n const getSize = (directives, letter) =>\n directives\n .filter((directive) => directive.startsWith(letter))\n .map((dir) => dir.replace(letter, \"\") + \"px\")[0] ?? \"\"\n this.table = table.split(\"\\n\").map((line) =>\n line\n .trimEnd()\n .split(\" \")\n .map((atom) => {\n const atoms = atom.split(directiveDelimiter).filter((atom) => !isDirective(atom)).join(\"\")\n const directivesInThisAtom = atom\n .split(directiveDelimiter)\n .filter(isDirective)\n const value = parseFloat(atoms)\n const label = atoms.includes(\"'\") ? atoms.split(\"'\")[1] : atoms\n const alignment = directivesInThisAtom.includes(\"right\")\n ? \"right\"\n : directivesInThisAtom.includes(\"left\")\n ? \"left\"\n : \"\"\n const color = colorFunction(value)\n const width = getSize(directivesInThisAtom, \"w\")\n const height = getSize(directivesInThisAtom, \"h\")\n const fontSize = getSize(directivesInThisAtom, \"f\")\n const lineHeight = getSize(directivesInThisAtom, \"l\") || height\n const link = directivesInThisAtom.filter(i => i.startsWith(\"http\") || i.endsWith(\".html\"))[0]\n const style = {\n \"background-color\": color,\n width,\n height,\n \"font-size\": fontSize,\n \"line-height\": lineHeight,\n \"text-align\": alignment,\n }\n Object.keys(style).filter(key => !style[key]).forEach((key) => delete style[key])\n return {\n value,\n label,\n style,\n link,\n }\n })\n )\n }\n get html() {\n const { program } = this\n const cssId = `#heatrix${this.uid}`\n const defaultWidth = \"40px\"\n const defaultHeight = \"40px\"\n const fontSize = \"10px\"\n const lineHeight = defaultHeight\n const style = `<style>\n .heatrixContainer {\n margin: auto;\n }.heatrixRow {white-space: nowrap;}\n ${cssId} .heatrixAtom {\n font-family: arial;\n border-radius: 2px;\n border: 1px solid transparent;\n display: inline-block;\n margin: 1px;\n text-align: center;\n vertical-align: middle;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n .heatrixAtom a {\n color: black;\n }\n ${cssId} .heatrixAtom{\n width: ${defaultWidth};\n height: ${defaultHeight};\n font-size: ${fontSize};\n line-height: ${lineHeight};\n }\n </style>`\n const firstRow = this.table[0]\n return (\n `<div class=\"heatrixContainer\" id=\"heatrix${this.uid}\">${style}` +\n this.table\n .map((row, rowIndex) => {\n if (!rowIndex) return \"\"\n const rowStyle = row[0].style\n return `<div class=\"heatrixRow heatrixRow${rowIndex}\">${row\n .map((atom, columnIndex) => {\n if (!columnIndex) return \"\"\n const columnStyle = firstRow[columnIndex]?.style || {}\n let { value, label, style, link } = atom\n const extendedStyle = Object.assign(\n {},\n rowStyle,\n columnStyle,\n style\n )\n const inlineStyle = Object.keys(extendedStyle)\n .map((key) => `${key}:${extendedStyle[key]};`)\n .join(\"\")\n let valueClass = value ? \" valueAtom\" : \"\"\n const href = link ? ` href=\"${link}\"` : \"\"\n return `<div class=\"heatrixAtom heatrixColumn${columnIndex}${valueClass}\" style=\"${inlineStyle}\"><a title=\"${label}\" ${href}>${label}</a></div>`\n })\n .join(\"\")}</div>`\n })\n .join(\"\\n\") +\n \"</div>\"\n ).replace(/\\n/g, \"\")\n }\n }\n return new Heatrix(this.subparticlesToString().trim()).html\n }\nmapParser\n latParser\n atoms cueAtom floatAtom\n cueFromId\n single\n longParser\n atoms cueAtom floatAtom\n cueFromId\n single\n tilesParser\n atoms cueAtom tileOptionAtom\n cueFromId\n single\n zoomParser\n atoms cueAtom integerAtom\n cueFromId\n single\n geolocateParser\n description Geolocate user.\n atoms cueAtom\n cueFromId\n single\n radiusParser\n atoms cueAtom floatAtom\n cueFromId\n single\n fillOpacityParser\n atoms cueAtom floatAtom\n cueFromId\n single\n fillColorParser\n atoms cueAtom colorAtom\n cueFromId\n single\n colorParser\n atoms cueAtom colorAtom\n cueFromId\n single\n heightParser\n atoms cueAtom floatAtom\n cueFromId\n single\n hoverParser\n atoms cueAtom\n catchAllAtomType colorAtom\n cueFromId\n single\n extends abstractTableVisualizationParser\n description Map widget.\n string copyFromExternal .leaflet.css .leaflet.js .scrollLibs.js\n string requireOnce\n <link rel=\"stylesheet\" href=\".leaflet.css\">\n <script src=\".leaflet.js\"></script>\n <script src=\".scrollLibs.js\"></script>\n javascript\n buildInstance() {\n const height = this.get(\"height\") || 500\n const id = this._getUid()\n const obj = this.toObject()\n const template = {}\n const style = height !== \"full\" ? `height: ${height}px;` : `height: 100%; position: fixed; z-index: -1; left: 0; top: 0; width: 100%;`\n const strs = [\"color\", \"fillColor\"]\n const nums = [\"radius\", \"fillOpacity\"]\n strs.filter(i => obj[i]).forEach(i => template[i] = obj[i])\n nums.filter(i => obj[i]).forEach(i => template[i] = parseFloat(obj[i]))\n const mapId = `map${id}`\n return `<div id=\"${mapId}\" style=\"${style}\"></div>\n <script>\n {\n if (!window.maps) window.maps = {}\n const moveToMyLocation = () => {\n if (!navigator.geolocation) return\n navigator.geolocation.getCurrentPosition((position) => {\n const { latitude, longitude } = position.coords\n window.maps.${mapId}.setView([latitude, longitude])\n L.circleMarker([latitude, longitude], {\n fillOpacity: 0.8,\n radius: 20,\n weight: 4\n })\n .addTo(window.maps.${mapId})\n }, () => {})\n }\n const lat = ${this.get(\"lat\") ?? 37.8}\n const long = ${this.get(\"long\") ?? 4}\n if (${this.has(\"geolocate\")}){\n moveToMyLocation()\n }\n const zoomLevel = ${this.get(\"zoom\") ?? 4}\n const hover = '${this.get(\"hover\") || \"<b>{title}</b><br>{description}\"}'\n const template = ${JSON.stringify(template)}\n const points = ${JSON.stringify((this.parent.coreTable || []).filter(point => point.lat && point.long), undefined, 2)}\n window.maps.${mapId} = L.map(\"map${id}\").setView([lat, long], zoomLevel)\n const map = window.maps.${mapId}\n const tileOptions = {\n \"default\": {\n baseLayer: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',\n attribution: '<a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors'\n },\n light: {\n baseLayer: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png',\n attribution: '<a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors <a href=\"https://carto.com/ attributions\">CARTO</a>'\n },\n }\n const {baseLayer, attribution} = tileOptions.${this.get(\"tiles\") || \"default\"}\n L.tileLayer(baseLayer, {\n attribution,\n maxZoom: 19\n }).addTo(map);\n points.forEach(point => {\n L.circleMarker([point.lat, point.long], {...template, ...Object.fromEntries(\n Object.entries(point).filter(([key, value]) => value !== null)\n )})\n .addTo(map)\n .bindPopup(new Particle(point).evalTemplateString(hover))\n })\n }\n </script>`\n }\nabstractPlotParser\n // Observablehq\n extends abstractTableVisualizationParser\n string copyFromExternal .d3.js .plot.js\n string requireOnce\n <script src=\".d3.js\"></script>\n <script src=\".plot.js\"></script>\n example\n plot\n inScope abstractColumnNameParser\n widthParser\n cueFromId\n atoms cueAtom integerAtom\n heightParser\n cueFromId\n atoms cueAtom integerAtom\n titleParser\n extends abstractPlotLabelParser\n subtitleParser\n extends abstractPlotLabelParser\n captionParser\n extends abstractPlotLabelParser\n javascript\n buildInstance() {\n const id = \"plot\" + this._getUid()\n return `<div id=\"${id}\"></div><script>\n {\n let loadChart = async () => {\n const data = ${this.dataCode}\n const get = (col, index ) => col !== \"undefined\" ? col : (index === undefined ? undefined : Object.keys(data[0])[index])\n document.querySelector(\"#${id}\").append(Plot.plot(${this.plotOptions}))\n }\n loadChart()\n }\n </script>`\n }\n get sortExpression() {\n const sort = this.get(\"sort\")\n if (!sort) return \"\"\n let sort_expr = \"\"\n if (sort.startsWith(\"-\")) {\n // Sort by a value descending\n const sortCol = sort.slice(1)\n sort_expr = `, sort: {x: \"y\", reverse: true}`\n } else if (sort.includes(\" \")) {\n // Fixed order specified\n const order = sort.split(\" \")\n sort_expr = `, sort: {x: (a,b) => {\n const order = ${JSON.stringify(order)};\n return order.indexOf(a) - order.indexOf(b)\n }}`\n } else if (sort === \"asc\") {\n sort_expr = `, sort: {x: \"x\"}`\n } else if (sort === \"desc\") {\n sort_expr = `, sort: {x: \"x\", reverse: true}`\n }\n return sort_expr\n }\n get marks() {\n // just for testing purposes\n return `Plot.rectY({length: 10000}, Plot.binX({y: \"count\"}, {x: d3.randomNormal()}))`\n }\n get dataCode() {\n const {coreTable} = this.parent\n return `d3.csvParse(\\`${new Particle(coreTable).asCsv}\\`, d3.autoType)`\n }\n get plotOptions() {\n return `{\n title: \"${this.get(\"title\") || \"\"}\",\n subtitle: \"${this.get(\"subtitle\") || \"\"}\",\n caption: \"${this.get(\"caption\") || \"\"}\",\n symbol: {legend: ${this.has(\"symbol\")}},\n color: {legend: ${this.has(\"fill\") || this.has(\"stroke\")}},\n grid: ${this.get(\"grid\") !== \"false\"},\n marks: [${this.marks}],\n width: ${this.get(\"width\") || 640},\n height: ${this.get(\"height\") || 400},\n }`\n }\nplotScatterplotParser\n cue scatterplot\n extends abstractPlotParser\n description Scatterplot Widget.\n example\n iris\n scatterplot\n javascript\n get marks() {\n const x = this.get(\"x\")\n const y = this.get(\"y\")\n const text = this.get(\"label\")\n return `Plot.dot(data, {\n x: get(\"${x}\", 0),\n y: get(\"${y}\", 1),\n r: get(\"${this.get(\"radius\")}\"),\n fill: get(\"${this.get(\"fill\")}\"),\n tip: true${this.sortExpression},\n symbol: get(\"${this.get(\"symbol\")}\")} ), Plot.text(data, {x: get(\"${x}\",0), y: get(\"${y}\", 1), text: \"${text}\", dy: -6, lineAnchor: \"bottom\"})`\n }\nplotBarchartParser\n cue barchart\n extends abstractPlotParser\n description Bar chart widget.\n example\n iris\n barchart\n javascript\n get marks() {\n const x = this.get(\"x\")\n const y = this.get(\"y\")\n const text = this.get(\"label\")\n const fill = this.get(\"fill\")\n return `Plot.barY(data, {\n x: get(\"${x}\", 0),\n y: get(\"${y}\", 1),\n fill: get(\"${fill}\"),\n tip: true${this.sortExpression}\n }), Plot.ruleY([0])`\n }\nplotLineChartParser\n cue linechart\n extends abstractPlotParser\n description Line chart widget.\n example\n iris\n linechart\n x SepalLength\n y SepalWidth\n javascript\n get marks() {\n const x = this.get(\"x\")\n const y = this.get(\"y\")\n const stroke = this.get(\"stroke\") || \"steelblue\"\n const strokeWidth = this.get(\"strokeWidth\") || 2\n const strokeLinecap = this.get(\"strokeLinecap\") || \"round\"\n const fill = this.get(\"fill\")\n return `Plot.line(data, {\n x: get(\"${x}\", 0),\n y: get(\"${y}\", 1),\n stroke: \"${stroke}\",\n fill: get(\"${fill}\"),\n strokeWidth: ${strokeWidth},\n strokeLinecap: \"${strokeLinecap}\"${this.sortExpression}\n })`\n }\nsparklineParser\n popularity 0.000024\n description Sparkline widget.\n extends abstractTableVisualizationParser\n example\n sparkline 1 2 3 4 5\n string copyFromExternal .sparkline.js\n string requireOnce <script src=\".sparkline.js\"></script>\n catchAllAtomType numberAtom\n // we need pattern matching\n inScope scrollYParser\n javascript\n buildInstance() {\n const id = \"spark\" + this._getUid()\n const {columnValues} = this\n const start = this.has(\"start\") ? parseInt(this.get(\"start\")) : 0\n const width = this.get(\"width\") || 100\n const height = this.get(\"height\") || 30\n const lineColor = this.get(\"color\") || \"black\"\n return `<span id=\"${id}\"></span><script>new Sparkline(document.getElementById(\"${id}\"), {dotRadius: 0, width: ${width}, height: ${height}, lineColor: \"${lineColor}\", tooltip: (value,index) => ${start} + index + \": \" + value}).draw(${JSON.stringify(columnValues)})</script>`\n }\n get columnValues() {\n if (this.content)\n return this.content.split(\" \").map(str => parseFloat(str))\n const {coreTable} = this.parent\n if (coreTable) {\n const columnName = this.get(\"y\") || Object.keys(coreTable[0]).find(key => typeof coreTable[0][key] === 'number')\n return coreTable.map(row => row[columnName])\n }\n }\nprintColumnParser\n popularity 0.000024\n description Print one column\n extends abstractTableVisualizationParser\n example\n printColumn tags\n catchAllAtomType columnNameAtom\n joinParser\n boolean allowTrailingWhitespace true\n cueFromId\n atoms cueAtom\n catchAllAtomType stringAtom\n javascript\n buildHtml() {\n return this.columnValues.join(this.join)\n }\n buildTxt() {\n return this.columnValues.join(this.join)\n }\n get join() {\n return this.get(\"join\") || \"\\n\"\n }\n get columnName() {\n return this.atoms[1]\n }\n get columnValues() {\n return this.parent.coreTable.map(row => row[this.columnName])\n }\nprintTableParser\n popularity 0.001085\n cueFromId\n description Print table.\n extends abstractTableVisualizationParser\n javascript\n get tableHeader() {\n return this.columns.filter(col => !col.isLink).map(column => `<th>${column.name}</th>\\n`)\n }\n get columnNames() {\n return this.parent.columnNames\n }\n buildJson() {\n return JSON.stringify(this.coreTable, undefined, 2)\n }\n buildCsv() {\n return new Particle(this.coreTable).asCsv\n }\n buildTsv() {\n return new Particle(this.coreTable).asTsv\n }\n get columns() {\n const {columnNames} = this\n return columnNames.map((name, index) => {\n const isLink = name.endsWith(\"Link\")\n const linkIndex = columnNames.indexOf(name + \"Link\")\n return {\n name,\n isLink,\n linkIndex\n }\n })\n }\n toRow(row) {\n const {columns} = this\n const atoms = columns.map(col => row[col.name])\n let str = \"\"\n let column = 0\n const columnCount = columns.length\n while (column < columnCount) {\n const col = columns[column]\n column++\n const content = ((columnCount === column ? atoms.slice(columnCount - 1).join(\" \") : atoms[column - 1]) ?? \"\").toString()\n if (col.isLink) continue\n const isTimestamp = col.name.toLowerCase().includes(\"time\") && /^\\d{10}(\\d{3})?$/.test(content)\n const text = isTimestamp ? new Date(parseInt(content.length === 10 ? content * 1000 : content)).toLocaleString() : content\n let tagged = text\n const link = atoms[col.linkIndex]\n const isUrl = content.match(/^https?\\:[^ ]+$/)\n if (col.linkIndex > -1 && link) tagged = `<a href=\"${link}\">${text}</a>`\n else if (col.name.endsWith(\"Url\")) tagged = `<a href=\"${content}\">${col.name.replace(\"Url\", \"\")}</a>`\n else if (isUrl) tagged = `<a href=\"${content}\">${text}</a>`\n str += `<td>${tagged}</td>\\n`\n }\n return str\n }\n get coreTable() {\n return this.parent.coreTable\n }\n get tableBody() {\n return this.coreTable\n .map(row => `<tr>${this.toRow(row)}</tr>`)\n .join(\"\\n\")\n }\n buildHtml() {\n return `<table id=\"table${this._getUid()}\" class=\"scrollTable\">\n <thead><tr>${this.tableHeader.join(\"\\n\")}</tr></thead>\n <tbody>${this.tableBody}</tbody>\n </table>`\n }\n buildTxt() {\n return this.parent.delimitedData || new Particle(this.coreTable).asCsv\n }\nkatexParser\n popularity 0.001592\n extends abstractScrollWithRequirementsParser\n catchAllAtomType codeAtom\n catchAllParser lineOfCodeParser\n example\n katex\n \\text{E} = \\text{T} / \\text{A}!\n description KaTex widget for typeset math.\n string copyFromExternal .katex.min.css .katex.min.js\n string requireOnce\n <link rel=\"stylesheet\" href=\".katex.min.css\">\n <script defer src=\".katex.min.js\"></script>\n <script>\n document.addEventListener(\"DOMContentLoaded\", () => document.querySelectorAll(\".scrollKatex\").forEach(el =>\n {\n katex.render(el.innerText, el, {\n throwOnError: false\n });\n }\n ))\n </script>\n javascript\n buildInstance() {\n const id = this._getUid()\n const content = this.content === undefined ? \"\" : this.content\n return `<div class=\"scrollKatex\" id=\"${id}\">${content + this.subparticlesToString()}</div>`\n }\n buildTxt() {\n return ( this.content ? this.content : \"\" )+ this.subparticlesToString()\n }\nhelpfulNotFoundParser\n popularity 0.000048\n extends abstractScrollWithRequirementsParser\n catchAllAtomType filePathAtom\n string copyFromExternal .helpfulNotFound.js\n description Helpful not found widget.\n javascript\n buildInstance() {\n return `<style>#helpfulNotFound{margin: 100px 0;}</style><h1 id=\"helpfulNotFound\"></h1><script defer src=\"/.helpfulNotFound.js\"></script><script>document.addEventListener(\"DOMContentLoaded\", () => new NotFoundApp('${this.content}'))</script>`\n }\nslideshowParser\n // Left and right arrows navigate.\n description Slideshow widget. *** delimits slides.\n extends abstractScrollWithRequirementsParser\n string copyFromExternal .jquery-3.7.1.min.js .slideshow.js\n example\n slideshow\n Why did the cow cross the road?\n ***\n Because it wanted to go to the MOOOO-vies.\n ***\n THE END\n ****\n javascript\n buildHtml() {\n return `<style>html {font-size: var(--scrollBaseFontSize, 28px);} body {margin: auto; width: 500px;}.slideshowNav{text-align: center; margin-bottom:20px; font-size: 24px;color: rgba(204,204,204,.8);} a{text-decoration: none; color: rgba(204,204,204,.8);}</style><script defer src=\".jquery-3.7.1.min.js\"></script><div class=\"slideshowNav\"></div><script defer src=\".slideshow.js\"></script>`\n }\ntableSearchParser\n popularity 0.000072\n extends abstractScrollWithRequirementsParser\n string copyFromExternal .jquery-3.7.1.min.js .datatables.css .dayjs.min.js .datatables.js .tableSearch.js\n string requireOnce\n <script defer src=\".jquery-3.7.1.min.js\"></script>\n <style>.dt-search{font-family: \"SF Pro\", \"Helvetica Neue\", \"Segoe UI\", \"Arial\";}</style>\n <link rel=\"stylesheet\" href=\".datatables.css\">\n <script defer src=\".datatables.js\"></script>\n <script defer src=\".dayjs.min.js\"></script>\n <script defer src=\".tableSearch.js\"></script>\n // adds to all tables on page\n description Table search and sort widget.\n javascript\n buildInstance() {\n return \"\"\n }\nabstractCommentParser\n description Prints nothing.\n catchAllAtomType commentAtom\n atoms commentAtom\n extends abstractScrollParser\n baseParser blobParser\n string bindTo next\n javascript\n buildHtml() {\n return ``\n }\n catchAllParser commentLineParser\ncommentParser\n popularity 0.000193\n extends abstractCommentParser\n cueFromId\ncounterpointParser\n description Counterpoint comment. Prints nothing.\n extends commentParser\n cue !\nslashCommentParser\n popularity 0.005643\n extends abstractCommentParser\n cue //\n boolean isPopular true\n description A comment. Prints nothing.\nthanksToParser\n description Acknowledgements comment. Prints nothing.\n extends abstractCommentParser\n cueFromId\nscrollClearStackParser\n popularity 0.000096\n cue clearStack\n description Clear body stack.\n extends abstractScrollParser\n boolean isHtml true\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n return this.root.clearBodyStack().trim()\n }\ncssParser\n popularity 0.007211\n extends abstractScrollParser\n description A style tag.\n example\n css\n body { color: red;}\n cueFromId\n catchAllParser cssLineParser\n catchAllAtomType cssAnyAtom\n javascript\n buildHtml() {\n return `<style>${this.css}</style>`\n }\n get css() {\n return this.content ?? this.subparticlesToString()\n }\n buildCss() {\n return this.css\n }\nscrollBackgroundColorParser\n description Quickly set CSS background.\n popularity 0.007211\n extends abstractScrollParser\n cue background\n catchAllAtomType cssAnyAtom\n example\n background red\n javascript\n buildHtml() {\n return `<style>html, body { background: ${this.content};}</style>`\n }\nscrollFontColorParser\n description Quickly set CSS font-color.\n popularity 0.007211\n extends abstractScrollParser\n cue color\n catchAllAtomType cssAnyAtom\n javascript\n buildHtml() {\n return `<style>html, body { color: ${this.content};}</style>`\n }\nscrollFontParser\n description Quickly set font family.\n popularity 0.007211\n extends abstractScrollParser\n cue font\n atoms cueAtom fontFamilyAtom\n catchAllAtomType cssAnyAtom\n example\n font Slim\n javascript\n buildHtml() {\n const font = this.content === \"Slim\" ? \"Helvetica Neue; font-weight:100;\" : this.content\n return `<style>html, body, h1,h2,h3 { font-family: ${font};}</style>`\n }\nabstractQuickIncludeParser\n popularity 0.007524\n extends abstractScrollParser\n atoms urlAtom\n javascript\n get dependencies() { return [this.filename]}\n get filename() {\n return this.getAtom(0)\n }\nquickCssParser\n popularity 0.007524\n description Make a CSS tag.\n extends abstractQuickIncludeParser\n example\n style.css\n atoms urlAtom\n pattern ^[^\\s]+\\.(css)$\n javascript\n buildHtml() {\n return `<link rel=\"stylesheet\" type=\"text/css\" href=\"${this.filename}\">`\n }\n buildHtmlSnippet() {\n return \"\"\n }\nquickIncludeHtmlParser\n popularity 0.007524\n description Include an HTML file.\n extends abstractQuickIncludeParser\n example\n body.html\n atoms urlAtom\n pattern ^[^\\s]+\\.(html|htm)$\n javascript\n buildHtml() {\n return this.root.readFile(this.filename)\n }\nquickScriptParser\n popularity 0.007524\n description Make a Javascript tag.\n extends abstractQuickIncludeParser\n atoms urlAtom\n example\n script.js\n pattern ^[^\\s]+\\.(js)$\n javascript\n attr = \"\"\n buildHtml() {\n return `<script ${this.attr} src=\"${this.filename}\"></script>`\n }\n buildHtmlSnippet() {\n return \"\"\n }\nquickModuleScriptParser\n description Make a Javascript module tag.\n extends quickScriptParser\n example\n script.mjs\n pattern ^[^\\s]+\\.(mjs)$\n javascript\n attr = 'type=\"module\"'\nscrollDashboardParser\n popularity 0.000145\n description Key stats in large font.\n catchAllParser lineOfCodeParser\n cue dashboard\n extends abstractScrollParser\n example\n dashboard\n #2 Popularity\n 30 Years Old\n $456 Revenue\n javascript\n get tableBody() {\n const items = this.topDownArray\n let str = \"\"\n for (let i = 0; i < items.length; i = i + 3) {\n str += this.makeRow(items.slice(i, i + 3))\n }\n return str\n }\n makeRow(items) {\n return `<tr>` + items.map(particle => `<td>${particle.cue}<span>${particle.content}</span></td>`).join(\"\\n\") + `</tr>\\n`\n }\n buildHtml() {\n return `<table class=\"scrollDashboard\">${this.tableBody}</table>`\n }\n buildTxt() {\n return this.subparticlesToString()\n }\nbelowAsCodeParser\n popularity 0.000651\n description Print code below.\n string bindTo next\n extends abstractScrollParser\n catchAllAtomType integerAtom\n example\n belowAsCode\n iris\n printTable\n cueFromId\n javascript\n method = \"next\"\n get selectedParticles() {\n const { method } = this\n let code = \"\"\n let particles = []\n let next = this[method]\n let {howMany} = this\n while (howMany) {\n particles.push(next)\n next = next[method]\n howMany--\n }\n if (this.reverse) particles.reverse()\n return particles\n }\n get code() {\n return this.selectedParticles.map(particle => particle.asString).join(\"\\n\")\n }\n reverse = false\n buildHtml() {\n return `<code class=\"scrollCodeBlock\">${this.code.replace(/\\</g, \"&lt;\")}</code>`\n }\n get howMany() {\n let howMany = parseInt(this.getAtom(1))\n if (!howMany || isNaN(howMany)) howMany = 1\n return howMany\n }\ndebugBelowParser\n description Inspect particle below.\n extends belowAsCodeParser\n string copyFromExternal .debug.css\n javascript\n get code() {\n const mapFn = particle => {\n const atomTypes = particle.lineAtomTypes.split(\" \")\n return `<div class=\"debugParticle\"><span class=\"debugParticleId\">${particle.constructor.name}</span>${particle.atoms.map((atom, index) => `<span class=\"debugAtom\">${atom}<span class=\"debugAtomType\">${atomTypes[index]}</span></span>`).join(\" \")}${(particle.length ? `<br><div class=\"debugSubparticles\">` + particle.map(mapFn).join(\"<br>\") + `</div>` : \"\")}</div>`}\n return this.selectedParticles.map(mapFn).join(\"<br>\")\n }\n buildHtml() {\n return `<link rel=\"stylesheet\" href=\".debug.css\">` + this.code\n }\n buildTxt() {\n const mapFn = particle => {\n const atomTypes = particle.lineAtomTypes.split(\" \")\n return `${particle.constructor.name} ${particle.atoms.map((atom, index) => `${atomTypes[index]}:${atom}`).join(\" \")}${(particle.length ? `\\n ` + particle.map(mapFn).join(\"\\n\") + `` : \"\")}`}\n return this.selectedParticles.map(mapFn).join(\"\\n\")\n }\n buildParsers() {return this.buildTxt()}\ndebugAboveParser\n description Inspect particle above.\n extends debugBelowParser\n string bindTo previous\n javascript\n method = \"previous\"\n reverse = true\ndebugAllParser\n description Inspect entire document.\n extends debugBelowParser\n javascript\n get selectedParticles() { return this.root.getSubparticles()}\nbelowAsCodeUntilParser\n description Print code above until match.\n extends belowAsCodeParser\n catchAllAtomType codeAtom\n example\n belowAsCode\n counter 1 second\n javascript\n get howMany() {\n let howMany = 1\n const query = this.content\n let particle = this.next\n while (particle !== this) {\n if (particle.getLine().startsWith(query))\n return howMany\n particle = particle.next\n howMany++\n }\n return howMany\n }\naboveAsCodeParser\n popularity 0.000482\n string bindTo previous\n description Print code above.\n example\n counter 1 second\n aboveAsCode\n extends belowAsCodeParser\n javascript\n method = \"previous\"\n reverse = true\nbelowAsHtmlParser\n extends belowAsCodeParser\n description Displays html output of next particle in a code block.\n cueFromId\n example\n belowAsHtml\n # Hello world\n javascript\n get code() {\n return this.selectedParticles.filter(p => p.buildHtml).map(p => p.buildHtml()).join(\"\\n\")\n }\naboveAsHtmlParser\n description Displays html output of previous particle in a code block.\n extends belowAsHtmlParser\n example\n # Hello world\n aboveAsHtml\n javascript\n method = \"previous\"\n reverse = true\nscrollDefParser\n popularity 0.004244\n description Parser short form.\n pattern ^[a-zA-Z0-9_]+Def\n extends abstractScrollParser\n catchAllAtomType stringAtom\n example\n urlDef What is the URL?\n javascript\n buildParsers(index) {\n const idStuff = index ? \"\" : `boolean isMeasure true\n boolean isMeasureRequired true\n boolean isConceptDelimiter true`\n const description = this.content\n const cue = this.cue.replace(\"Def\", \"\")\n const sortIndex = 1 + index/10\n return `${cue}DefParser\n cue ${cue}\n extends abstractStringMeasureParser\n description ${description}\n float sortIndex ${sortIndex}\n ${idStuff}`.trim()\n }\nhakonParser\n cueFromId\n extends abstractScrollParser\n description Compile Hakon to CSS.\n catchAllParser hakonContentParser\n javascript\n buildHtml() {\n return `<style>${this.css}</style>`\n }\n get css() {\n const {hakonParser} = this.root\n return new hakonParser(this.subparticlesToString()).compile()\n }\n buildCss() {\n return this.css\n }\nhamlParser\n popularity 0.007524\n description HTML tag via HAML syntax.\n extends abstractScrollParser\n atoms urlAtom\n catchAllAtomType stringAtom\n pattern ^%?[\\w\\.]+#[\\w\\.]+ *\n javascript\n get tag() {\n return this.atoms[0].split(/[#\\.]/).shift().replace(\"%\", \"\")\n }\n get htmlId() {\n const idMatch = this.atoms[0].match(/#([\\w-]+)/)\n return idMatch ? idMatch[1] : \"\"\n }\n get htmlClasses() {\n return this.atoms[0].match(/\\.([\\w-]+)/g)?.map(cls => cls.slice(1)) || [];\n }\n buildHtml() {\n const {htmlId, htmlClasses, content, tag} = this\n this.parent.sectionStack.unshift(`</${tag}>`)\n const attrs = [htmlId ? ' id=\"' + htmlId + '\"' : \"\", htmlClasses.length ? ' class=\"' + htmlClasses.join(\" \") + '\"' : \"\"].join(\" \").trim()\n return `<${tag}${attrs ? \" \" + attrs : \"\"}>${content || \"\"}`\n }\n buildTxt() {\n return this.content\n }\nhamlTagParser\n // Match plain tags like %h1\n extends hamlParser\n pattern ^%[^#]+$\nabstractHtmlParser\n extends abstractScrollParser\n catchAllParser htmlLineParser\n catchAllAtomType htmlAnyAtom\n javascript\n buildHtml() {\n return `${this.content ?? \"\"}${this.subparticlesToString()}`\n }\n buildTxt() {\n return \"\"\n }\nhtmlParser\n popularity 0.000048\n extends abstractHtmlParser\n description HTML one liners or blocks.\n cueFromId\nhtmlInlineParser\n popularity 0.005788\n extends abstractHtmlParser\n atoms htmlAnyAtom\n boolean isHtml true\n example\n <h1>Inline HTML</h1>\n pattern ^<\n description Inline HTML.\n boolean isPopular true\n javascript\n buildHtml() {\n return `${this.getLine() ?? \"\"}${this.subparticlesToString()}`\n }\nscrollBrParser\n popularity 0.000096\n cue br\n example\n br 2\n description A break.\n extends abstractScrollParser\n catchAllAtomType integerAtom\n boolean isHtml true\n javascript\n buildHtml() {\n return `<br>`.repeat(parseInt(this.getAtom(1) || 1))\n }\niframesParser\n popularity 0.000121\n cueFromId\n catchAllAtomType urlAtom\n extends abstractScrollParser\n description An iframe(s).\n example\n iframes frame.html\n javascript\n buildHtml() {\n return this.atoms.slice(1).map(url => `<iframe src=\"${url}\" frameborder=\"0\"></iframe>`).join(\"\\n\")\n }\nabstractCaptionedParser\n extends abstractScrollParser\n atoms cueAtom urlAtom\n inScope captionAftertextParser slashCommentParser\n cueFromId\n javascript\n buildHtml(buildSettings) {\n const caption = this.getParticle(\"caption\")\n const captionFig = caption ? `<figcaption>${caption.buildHtml()}</figcaption>` : \"\"\n const {figureWidth} = this\n const widthStyle = figureWidth ? `width:${figureWidth}px; margin: auto;` : \"\"\n const float = this.has(\"float\") ? `margin: 20px; float: ${this.get(\"float\")};` : \"\"\n return `<figure class=\"scrollCaptionedFigure\" style=\"${widthStyle + float}\">${this.getFigureContent(buildSettings)}${captionFig}</figure>`\n }\n get figureWidth() {\n return this.get(\"width\")\n }\nscrollImageParser\n cue image\n popularity 0.005908\n description An img tag.\n boolean isPopular true\n extends abstractCaptionedParser\n int atomIndex 1\n example\n image screenshot.png\n caption A caption.\n inScope addClassMarkupParser aftertextIdParser scrollLinkParser linkTargetParser openGraphParser\n javascript\n get dimensions() {\n const width = this.get(\"width\")\n const height = this.get(\"height\")\n if (width || height)\n return {width, height}\n if (!this.isNodeJs())\n return {}\n const src = this.filename\n // If its a local image, get the dimensions and put them in the HTML\n // to avoid flicker\n if (src.startsWith(\"http:\") || src.startsWith(\"https:\")) return {}\n if (this._dimensions)\n return this._dimensions\n try {\n const sizeOf = require(\"image-size\")\n const path = require(\"path\")\n const fullImagePath = path.join(this.root.folderPath, src)\n this._dimensions = sizeOf(fullImagePath)\n return this._dimensions\n } catch (err) {\n console.error(err)\n }\n return {}\n }\n get figureWidth() {\n return this.dimensions.width\n }\n get filename() {\n return this.getAtom(this.atomIndex)\n }\n get dependencies() { return [this.filename]}\n getFigureContent(buildSettings) {\n const linkRelativeToCompileTarget = (buildSettings ? (buildSettings.relativePath ?? \"\") : \"\") + this.filename\n const {width, height} = this.dimensions\n let dimensionAttributes = width || height ? `width=\"${width}\" height=\"${height}\" ` : \"\"\n // Todo: can we reuse more code from aftertext?\n const className = this.has(\"class\") ? ` class=\"${this.get(\"class\")}\" ` : \"\"\n const id = this.has(\"id\") ? ` id=\"${this.get(\"id\")}\" ` : \"\"\n const clickLink = this.find(particle => particle.definition.isOrExtendsAParserInScope([\"scrollLinkParser\"])) || linkRelativeToCompileTarget \n const target = this.has(\"target\") ? this.get(\"target\") : (this.has(\"link\") ? \"\" : \"_blank\")\n return `<a href=\"${clickLink}\" target=\"${target}\" ${className} ${id}><img src=\"${linkRelativeToCompileTarget}\" ${dimensionAttributes}loading=\"lazy\"></a>`\n }\n buildTxt() {\n const subparticles = this.filter(particle => particle.buildTxt).map(particle => particle.buildTxt()).filter(i => i).join(\"\\n\")\n return \"[Image Omitted]\" + (subparticles ? \"\\n \" + subparticles.replace(/\\n/g, \"\\n \") : \"\")\n }\nquickImageParser\n popularity 0.005788\n extends scrollImageParser\n example\n screenshot.png\n atoms urlAtom\n pattern ^[^\\s]+\\.(jpg|jpeg|png|gif|webp|svg|bmp)\n int atomIndex 0\nqrcodeParser\n extends abstractCaptionedParser\n description Make a QR code from a link.\n example\n qrcode https://scroll.pub\n javascript\n getFigureContent() {\n const url = this.atoms[1]\n const isNode = this.isNodeJs()\n if (isNode) {\n const {externalsPath} = this.root\n const path = require(\"path\")\n const {qrcodegen, toSvgString} = require(path.join(externalsPath, \".qrcodegen.js\"))\n const QRC = qrcodegen.QrCode;\n const qr0 = QRC.encodeText(url, QRC.Ecc.MEDIUM);\n const svg = toSvgString(qr0, 4); // See qrcodegen-input-demo\n return svg\n }\n return `Not yet supported in browser.`\n }\nyoutubeParser\n popularity 0.000121\n extends abstractCaptionedParser\n // Include the YouTube embed URL such as https://www.youtube.com/embed/CYPYZnVQoLg\n description A YouTube video widget.\n example\n youtube https://www.youtube.com/watch?v=lO8blNtYYBA\n javascript\n getFigureContent() {\n const url = this.getAtom(1).replace(\"youtube.com/watch?v=\", \"youtube.com/embed/\")\n return `<div class=\"scrollYouTubeHolder\"><iframe class=\"scrollYouTubeEmbed\" src=\"${url}\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe></div>`\n }\nyouTubeParser\n extends youtubeParser\n tags deprecate\n // Deprecated. You youtube all lowercase.\nimportParser\n description Import a file.\n popularity 0.007524\n cueFromId\n atoms preBuildCommandAtom\n extends abstractScrollParser\n catchAllAtomType filePathAtom\n javascript\n buildHtml() {\n return \"\"\n }\n example\n import header.scroll\nscrollImportedParser\n description Inserted at import pass.\n boolean suggestInAutocomplete false\n cue imported\n atoms preBuildCommandAtom\n extends abstractScrollParser\n baseParser blobParser\n catchAllAtomType filePathAtom\n javascript\n buildHtml() {\n return \"\"\n }\n getErrors() {\n if (this.get(\"exists\") === \"false\" && this.previous.getLine() !== \"// optional\")\n return [this.makeError(`File '${this.atoms[1]}' does not exist.`)]\n return []\n }\nquickImportParser\n popularity 0.007524\n description Import a Scroll or Parsers file.\n extends abstractScrollParser\n boolean isPopular true\n inScope importToFooterParser abstractCommentParser\n atoms urlAtom\n pattern ^[^\\s]+\\.(scroll|parsers)$\n javascript\n buildHtml() {\n return \"\"\n }\n example\n header.scroll\nscriptParser\n extends abstractScrollParser\n description Print script tag.\n cueFromId\n catchAllParser scriptLineParser\n catchAllAtomType javascriptAnyAtom\n javascript\n buildHtml() {\n return `<script>${this.scriptContent}</script>`\n }\n get scriptContent() {\n return this.content ?? this.subparticlesToString()\n }\n buildJs() {\n return this.scriptContent\n }\njsonScriptParser\n popularity 0.007524\n cueFromId\n description Include JSON and assign to window.\n extends abstractScrollParser\n atoms cueAtom urlAtom\n javascript\n buildHtml() {\n const varName = this.filename.split(\"/\").pop().replace(\".json\", \"\")\n return `<script>window.${varName} = ${this.root.readFile(this.filename)}</script>`\n }\n get filename() {\n return this.getAtom(1)\n }\nscrollLeftRightButtonsParser\n popularity 0.006342\n cue leftRightButtons\n description Previous and next nav buttons.\n extends abstractScrollParser\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n const { linkToPrevious, linkToNext } = this.root\n if (!linkToPrevious) return \"\"\n const style = `a.keyboardNav {display:block;position:absolute;top:0.25rem; color: rgba(204,204,204,.8); font-size: 1.875rem; line-height: 1.7rem;}a.keyboardNav:hover{color: #333;text-decoration: none;}`\n return `<style>${style}</style><a class=\"keyboardNav doNotPrint\" style=\"left:.5rem;\" href=\"${linkToPrevious}\">&lt;</a><a class=\"keyboardNav doNotPrint\" style=\"right:.5rem;\" href=\"${linkToNext}\">&gt;</a>`\n }\nkeyboardNavParser\n popularity 0.007476\n description Make left and right navigate files.\n extends abstractScrollParser\n cueFromId\n catchAllAtomType urlAtom\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n const {root} = this\n const linkToPrevious = this.getAtom(1) ?? root.linkToPrevious\n const linkToNext = this.getAtom(2) ?? root.linkToNext\n const script = `<script>document.addEventListener('keydown', function(event) {\n if (document.activeElement !== document.body) return\n if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return // dont interfere with keyboard back button shortcut\n const getLinks = () => document.getElementsByClassName(\"scrollKeyboardNav\")[0].getElementsByTagName(\"a\")\n if (event.key === \"ArrowLeft\")\n getLinks()[0].click()\n else if (event.key === \"ArrowRight\")\n getLinks()[1].click()\n });</script>`\n return `<div class=\"scrollKeyboardNav\" style=\"display:none;\"><a href=\"${linkToPrevious}\">${linkToPrevious}</a> · ${root.permalink} · <a href=\"${linkToNext}\">${linkToNext}</a>${script}</div>`\n }\nprintUsageStatsParser\n popularity 0.000096\n // todo: if we include the atom \"Parser\" in a cue, bad things seem to happen.\n description Parser usage stats for folder.\n extends abstractScrollParser\n cueFromId\n javascript\n get stats() {\n const input = this.root.allScrollFiles.map(file => file.scrollProgram).map(program => program.parserIds.join(\"\\n\")).join(\"\\n\")\n const result = input.split('\\n').reduce((acc, atom) => (acc[atom] = (acc[atom] || 0) + 1, acc), {})\n const rows = Object.entries(result).map(([atom, count]) => { return {atom, count}})\n const sorted = this.root.lodash.sortBy(rows, \"count\").reverse()\n return \"parserId uses\\n\" + sorted.map(row => `${row.atom} ${row.count}`).join('\\n')\n }\n buildHtml() {\n // A hacky but simple way to do this for now.\n const particle = this.appendSibling(\"table\")\n particle.appendLine(\"delimiter \")\n particle.appendLine(\"printTable\")\n const dataParticle = particle.appendLine(\"data\")\n dataParticle.setSubparticles(this.stats)\n const html = particle.buildHtml()\n particle.destroy()\n return html\n }\n buildTxt() {\n return this.stats\n }\n buildCsv() {\n return this.stats.replace(/ /g, \",\")\n }\nprintScrollLeetSheetParser\n popularity 0.000024\n description Print Scroll parser leet sheet.\n extends abstractScrollParser\n tags experimental\n cueFromId\n javascript\n get parsersToDocument() {\n const clone = this.root.clone()\n clone.setSubparticles(\"\")\n const atoms = clone.getAutocompleteResultsAt(0,0).matches.map(a => a.text)\n atoms.push(\"blankline\") // manually add blank line\n atoms.push(\"Catch All Paragraph.\") // manually add catch all paragraph\n atoms.push(\"<h></h>\") // manually add html\n atoms.sort()\n clone.setSubparticles(atoms.join(\"\\n\").replace(/blankline/, \"\")) // insert blank line in right spot\n return clone\n }\n sortDocs(docs) {\n return docs.map(particle => {\n const {definition} = particle\n const {id, description, isPopular, examples, popularity} = definition\n const tags = definition.get(\"tags\") || \"\"\n if (tags.includes(\"deprecate\") || tags.includes(\"experimental\"))\n return null\n const category = this.getCategory(tags)\n const note = this.getNote(category)\n return {id: definition.cueIfAny || id, description, isPopular, examples, note, popularity: Math.ceil(parseFloat(popularity) * 100000)}\n }).filter(i => i).sort((a, b) => a.id.localeCompare(b.id))\n }\n makeLink(examples, cue) {\n // if (!examples.length) console.log(cue) // find particles that need docs\n const example = examples.length ? examples[0].subparticlesToString() : cue\n const base = `https://try.scroll.pub/`\n const particle = new Particle()\n particle.appendLineAndSubparticles(\"scroll\", \"theme gazette\\n\" + example)\n return base + \"#\" + encodeURIComponent(particle.asString)\n }\n docToHtml(doc) {\n const css = `#scrollLeetSheet {color: grey;} #scrollLeetSheet a {color: #3498db; }`\n return `<style>${css}</style><div id=\"scrollLeetSheet\">` + doc.map(obj => `<div class=\"${obj.category}\"><a href=\"${this.makeLink(obj.examples, obj.id)}\">${obj.isPopular ? \"<b>\" : \"\"}${obj.id}</a> ${obj.description}${obj.isPopular ? \"</b>\" : \"\"}${obj.note}</div>`).join(\"\\n\") + \"</div>\"\n }\n buildHtml() {\n return this.docToHtml(this.sortDocs(this.parsersToDocument))\n }\n buildTxt() {\n return this.sortDocs(this.parsersToDocument).map(obj => `${obj.id} - ${obj.description}`).join(\"\\n\")\n }\n getCategory(input) {\n return \"\"\n }\n getNote() {\n return \"\"\n }\n get docs() {\n const rows = this.sortDocs(this.parsersToDocument).map(obj => {\n const {id, isPopular, description, popularity, category, examples, cue} = obj\n const example = examples.length ? examples[0].subparticlesToString() : cue\n return {\n id,\n isPopular,\n description,\n popularity,\n example,\n category\n }\n })\n return this.root.lodash.sortBy(rows, \"isPopular\")\n }\n buildJson() {\n return JSON.stringify(this.docs, undefined, 2)\n }\n buildCsv() {\n return new Particle(this.docs).asCsv\n }\nprintparsersLeetSheetParser\n popularity 0.000024\n // todo: fix parse bug when atom Parser appears in parserId\n extends printScrollLeetSheetParser\n tags experimental\n description Parsers leetsheet.\n javascript\n buildHtml() {\n return \"<p><b>Parser Definition Parsers</b> define parsers that acquire, analyze and act on code.</p>\" + this.docToHtml(this.sortDocs(this.parsersToDocument)) + \"<p><b>Atom Definition Parsers</b> analyze the atoms in a line.</p>\" + this.docToHtml(this.sortDocs(this.atomParsersToDocument))\n }\n makeLink() {\n return \"\"\n }\n categories = \"assemblePhase acquirePhase analyzePhase actPhase\".split(\" \")\n getCategory(tags) {\n return tags.split(\" \").filter(w => w.endsWith(\"Phase\"))[0]\n }\n getNote(category) {\n return ` <span class=\"note\">A${category.replace(\"Phase\", \"\").substr(1)}Time.</span>`\n }\n get atomParsersToDocument() {\n const parsersParser = require(\"scrollsdk/products/parsers.nodejs.js\")\n const clone = new parsersParser(\"anyAtom\\n \").clone()\n const parserParticle = clone.getParticle(\"anyAtom\")\n const atoms = clone.getAutocompleteResultsAt(1,1).matches.map(a => a.text)\n atoms.sort()\n parserParticle.setSubparticles(atoms.join(\"\\n\"))\n return parserParticle\n }\n get parsersToDocument() {\n const parsersParser = require(\"scrollsdk/products/parsers.nodejs.js\")\n const clone = new parsersParser(\"latinParser\\n \").clone()\n const parserParticle = clone.getParticle(\"latinParser\")\n const atoms = clone.getAutocompleteResultsAt(1,1).matches.map(a => a.text)\n atoms.sort()\n parserParticle.setSubparticles(atoms.join(\"\\n\"))\n clone.appendLine(\"myParser\")\n clone.appendLine(\"myAtom\")\n return parserParticle\n }\nabstractMeasureParser\n atoms measureNameAtom\n description Base parser all measures extend.\n cueFromId\n boolean isMeasure true\n float sortIndex 1.9\n boolean isComputed false\n string typeForWebForms text\n extends abstractScrollParser\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n return \"\"\n }\n get measureValue() {\n return this.content ?? \"\"\n }\n get measureName() {\n return this.getCuePath().replace(/ /g, \"_\")\n }\nabstractAtomMeasureParser\n description Contains a single word.\n atoms measureNameAtom atomAtom\n example\n nicknameParser\n extends abstractAtomMeasureParser\n id Breck\n nickname breck\n extends abstractMeasureParser\nabstractEmailMeasureParser\n description Email address.\n example\n emailParser\n extends abstractEmailMeasureParser\n id Breck\n email breck7@gmail.com\n string typeForWebForms email\n atoms measureNameAtom emailAddressAtom\n extends abstractAtomMeasureParser\nabstractUrlMeasureParser\n description A single url.\n example\n homepageParser\n extends abstractUrlMeasureParser\n id Breck\n homepage https://breckyunits.com\n string typeForWebForms url\n atoms measureNameAtom urlAtom\n extends abstractAtomMeasureParser\nabstractStringMeasureParser\n description General text data with no specific format.\n catchAllAtomType stringAtom\n example\n titleParser\n extends abstractStringMeasureParser\n id Breck\n title I build languages for scientists of all ages\n extends abstractMeasureParser\nabstractIdParser\n cue id\n description What is the ID of this concept?\n extends abstractStringMeasureParser\n example\n idParser\n extends abstractIdParser\n id breck\n float sortIndex 1\n boolean isMeasureRequired true\n boolean isConceptDelimiter true\n javascript\n getErrors() {\n const errors = super.getErrors()\n let requiredMeasureNames = this.root.measures.filter(measure => measure.isMeasureRequired).map(measure => measure.Name).filter(name => name !== \"id\")\n if (!requiredMeasureNames.length) return errors\n let next = this.next\n while (requiredMeasureNames.length && next.cue !== \"id\" && next.index !== 0) {\n requiredMeasureNames = requiredMeasureNames.filter(i => i !== next.cue)\n next = next.next\n }\n requiredMeasureNames.forEach(name =>\n errors.push(this.makeError(`Concept \"${this.content}\" is missing required measure \"${name}\".`))\n )\n return errors\n }\nabstractIdMeasureParser\n description Alias for abstractIdParser.\n extends abstractIdParser\nabstractTextareaMeasureParser\n string typeForWebForms textarea\n example\n bioParser\n extends abstractTextareaMeasureParser\n id Breck\n bio\n I build languages for scientists of all ages\n description Long-form text content with preserved line breaks.\n extends abstractMeasureParser\n baseParser blobParser\n javascript\n get measureValue() {\n return this.subparticlesToString().replace(/\\n/g, \"\\\\n\")\n }\nabstractNumericMeasureParser\n string typeForWebForms number\n description Base number type.\n extends abstractMeasureParser\n javascript\n get measureValue() {\n const {content} = this\n return content === undefined ? \"\" : parseFloat(content)\n }\nabstractNumberMeasureParser\n description Alias to abstractNumericMeasureParser.\n extends abstractNumericMeasureParser\nabstractIntegerMeasureParser\n description An integer.\n example\n ageParser\n extends abstractIntegerMeasureParser\n id Breck\n age 40\n atoms measureNameAtom integerAtom\n extends abstractNumericMeasureParser\n javascript\n get measureValue() {\n const {content} = this\n return content === undefined ? \"\" : parseInt(content)\n }\nabstractIntMeasureParser\n description Alias to abstractIntegerMeasureParser.\n extends abstractIntegerMeasureParser\nabstractFloatMeasureParser\n description A float.\n example\n temperatureParser\n extends abstractFloatMeasureParser\n id Breck\n temperature 31.8\n atoms measureNameAtom floatAtom\n extends abstractNumericMeasureParser\nabstractPercentageMeasureParser\n description A percentage.\n atoms measureNameAtom percentAtom\n extends abstractNumericMeasureParser\n example\n ownershipParser\n extends abstractPercentageMeasureParser\n id Breck\n ownership 31.8\n javascript\n get measureValue() {\n const {content} = this\n return content === undefined ? \"\" : parseFloat(content)\n }\nabstractEnumMeasureParser\n description A single enum.\n atoms measureNameAtom enumAtom\n extends abstractMeasureParser\n example\n favoriteHtmlTagParser\n extends abstractEnumMeasureParser\n atoms measureNameAtom htmlTagAtom\n id Breck\n favoriteHtmlTag 2020\nabstractBooleanMeasureParser\n description A single boolean.\n atoms measureNameAtom booleanAtom\n extends abstractMeasureParser\n example\n hasBillOfRightsParser\n extends abstractBooleanMeasureParser\n id USA\n hasBillOfRights true\n javascript\n get measureValue() {\n const {content} = this\n return content === undefined ? \"\" : content == \"true\"\n }\nabstractDateMeasureParser\n description Year/month/day in ISO 8601, US, European formats.\n atoms measureNameAtom dateAtom\n extends abstractMeasureParser\n string typeForWebForms date\n javascript\n get measureValue() {\n const {content} = this\n if (!content) return \"\"\n const {dayjs} = this.root\n try {\n // First try parsing with dayjs\n const parsed = dayjs(content)\n if (parsed.isValid())\n return parsed.format(\"YYYY-MM-DD\")\n // Try parsing other common formats\n const formats = [\n \"MM/DD/YYYY\",\n \"DD/MM/YYYY\", \n \"YYYY/MM/DD\",\n \"MM-DD-YYYY\",\n \"DD-MM-YYYY\",\n \"YYYY-MM-DD\",\n \"DD.MM.YYYY\",\n \"YYYY.MM.DD\"\n ]\n for (const format of formats) {\n const attempt = dayjs(content, format)\n if (attempt.isValid())\n return attempt.format(\"YYYY-MM-DD\")\n }\n } catch (err) {\n console.error(err)\n return \"\"\n }\n return \"\"\n }\n get valueAsTimestamp() {\n const {measureValue} = this\n return measureValue ? this.root.dayjs(measureValue).unix() : \"\"\n }\nmetaTagsParser\n popularity 0.007693\n cueFromId\n extends abstractScrollParser\n description Print meta tags including title.\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n const {root} = this\n const { title, description, canonicalUrl, gitRepo, scrollVersion, openGraphImage, keywords } = root\n const rssFeedUrl = root.get(\"rssFeedUrl\")\n const favicon = root.get(\"favicon\")\n const faviconTag = favicon ? `<link rel=\"icon\" href=\"${favicon}\">` : \"\"\n const keywordsTag = keywords ? `<meta name=\"keywords\" content=\"${keywords}\">` : \"\"\n const rssTag = rssFeedUrl ? `<link rel=\"alternate\" type=\"application/rss+xml\" title=\"${title}\" href=\"${rssFeedUrl}\">` : \"\"\n const gitTag = gitRepo ? `<link rel=\"source\" type=\"application/git\" title=\"Source Code Repository\" href=\"${gitRepo}\">` : \"\"\n return `<head>\n <meta charset=\"utf-8\">\n <title>${title}</title>\n <script>/* This HTML was generated by 📜 Scroll v${scrollVersion}. https://scroll.pub */</script>\n <style>@media print {.doNotPrint {display: none !important;}}</style>\n <link rel=\"canonical\" href=\"${canonicalUrl}\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n <meta name=\"description\" content=\"${description}\">\n ${keywordsTag}\n <meta name=\"generator\" content=\"Scroll v${scrollVersion}\">\n <meta property=\"og:title\" content=\"${title}\">\n <meta property=\"og:description\" content=\"${description}\">\n <meta property=\"og:image\" content=\"${openGraphImage}\">\n ${faviconTag}\n ${gitTag}\n ${rssTag}\n <meta name=\"twitter:card\" content=\"summary_large_image\">\n </head>\n <body>`\n }\nquoteParser\n popularity 0.001471\n cueFromId\n description A quote.\n catchAllParser quoteLineParser\n extends abstractScrollParser\n javascript\n buildHtml() {\n return `<blockquote class=\"scrollQuote\">${this.subparticlesToString()}</blockquote>`\n }\n buildTxt() {\n return this.subparticlesToString()\n }\nredirectToParser\n popularity 0.000072\n description HTML redirect tag.\n extends abstractScrollParser\n atoms cueAtom urlAtom\n cueFromId\n example\n redirectTo https://scroll.pub/releaseNotes.html\n javascript\n buildHtml() {\n return `<meta http-equiv=\"Refresh\" content=\"0; url='${this.getAtom(1)}'\" />`\n }\nabstractVariableParser\n extends abstractScrollParser\n catchAllAtomType stringAtom\n atoms preBuildCommandAtom\n cueFromId\n javascript\n isTopMatter = true\n buildHtml() {\n return \"\"\n }\nreplaceParser\n description Replace this with that.\n extends abstractVariableParser\n baseParser blobParser\n example\n replace YEAR 2022\nreplaceJsParser\n description Replace this with evaled JS.\n extends replaceParser\n catchAllAtomType javascriptAnyAtom\n example\n replaceJs SUM 1+1\n * 1+1 = SUM\nreplaceNodejsParser\n description Replace with evaled Node.JS.\n extends abstractVariableParser\n catchAllAtomType javascriptAnyAtom\n baseParser blobParser\n example\n replaceNodejs\n module.exports = {SCORE : 1 + 2}\n * The score is SCORE\ntoFooterParser\n extends abstractScrollParser\n description Experimental way to move a section to the footer.\n atoms preBuildCommandAtom\n cueFromId\nrunScriptParser\n popularity 0.000024\n description Run script and dump stdout.\n extends abstractScrollParser\n atoms cueAtom urlAtom\n cue run\n int filenameIndex 1\n javascript\n get dependencies() { return [this.filename]}\n results = \"Not yet run\"\n async execute() {\n if (!this.filename) return\n await this.root.fetch(this.filename)\n // todo: make async\n const { execSync } = require(\"child_process\")\n this.results = execSync(this.command)\n }\n get command() {\n const path = this.root.path\n const {filename }= this\n const fullPath = this.root.makeFullPath(filename)\n const ext = path.extname(filename).slice(1)\n const interpreterMap = {\n php: \"php\",\n py: \"python3\",\n rb: \"ruby\",\n pl: \"perl\",\n sh: \"sh\"\n }\n return [interpreterMap[ext], fullPath].join(\" \")\n }\n buildHtml() {\n return this.buildTxt()\n }\n get filename() {\n return this.getAtom(this.filenameIndex)\n }\n buildTxt() {\n return this.results.toString().trim()\n }\nquickRunScriptParser\n extends runScriptParser\n atoms urlAtom\n pattern ^[^\\s]+\\.(py|pl|sh|rb|php)$\n int filenameIndex 0\nendSnippetParser\n popularity 0.004293\n description Cut for snippet here.\n extends abstractScrollParser\n cueFromId\n javascript\n buildHtml() {\n return \"\"\n }\ntoStampParser\n description Print a directory to stamp.\n extends abstractScrollParser\n catchAllAtomType filePathAtom\n cueFromId\n javascript\n buildTxt() {\n return this.makeStamp(this.content)\n }\n buildHtml() {\n return `<pre>${this.buildTxt()}</pre>`\n }\n makeStamp(dir) {\n const fs = require('fs');\n const path = require('path');\n const { execSync } = require('child_process');\n let stamp = 'stamp\\n';\n const handleFile = (indentation, relativePath, itemPath, ) => {\n stamp += `${indentation}${relativePath}\\n`;\n const content = fs.readFileSync(itemPath, 'utf8');\n stamp += `${indentation} ${content.replace(/\\n/g, `\\n${indentation} `)}\\n`;\n }\n let gitTrackedFiles\n function processDirectory(currentPath, depth) {\n const items = fs.readdirSync(currentPath);\n items.forEach(item => {\n const itemPath = path.join(currentPath, item);\n const relativePath = path.relative(dir, itemPath);\n //if (!gitTrackedFiles.has(item)) return\n const stats = fs.statSync(itemPath);\n const indentation = ' '.repeat(depth);\n if (stats.isDirectory()) {\n stamp += `${indentation}${relativePath}/\\n`;\n processDirectory(itemPath, depth + 1);\n } else if (stats.isFile())\n handleFile(indentation, relativePath, itemPath)\n });\n }\n const stats = fs.statSync(dir);\n if (stats.isDirectory()) {\n // Get list of git-tracked files\n gitTrackedFiles = new Set(execSync('git ls-files', { cwd: dir, encoding: 'utf-8' })\n .split('\\n')\n .filter(Boolean))\n processDirectory(dir, 1)\n }\n else\n handleFile(\" \", dir, dir)\n return stamp.trim();\n }\nstampParser\n description Expand project template to disk.\n extends abstractScrollParser\n inScope stampFolderParser\n catchAllParser stampFileParser\n example\n stamp\n .gitignore\n *.html\n readme.scroll\n # Hello world\n <script src=\"scripts/nested/hello.js\"></script>\n scripts/\n nested/\n hello.js\n console.log(\"Hello world\")\n cueFromId\n atoms preBuildCommandAtom\n javascript\n execute() {\n const dir = this.root.folderPath\n this.forEach(particle => particle.execute(dir))\n }\nscrollStumpParser\n cue stump\n extends abstractScrollParser\n description Compile Stump to HTML.\n catchAllParser stumpContentParser\n javascript\n buildHtml() {\n const {stumpParser} = this\n return new stumpParser(this.subparticlesToString()).compile()\n }\n get stumpParser() {\n return this.isNodeJs() ? require(\"scrollsdk/products/stump.nodejs.js\") : stumpParser\n }\nstumpNoSnippetParser\n popularity 0.010177\n // todo: make noSnippets an aftertext directive?\n extends scrollStumpParser\n description Compile Stump unless snippet.\n cueFromId\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\nplainTextParser\n description Plain text oneliner or block.\n cueFromId\n extends abstractScrollParser\n catchAllParser plainTextLineParser\n catchAllAtomType stringAtom\n javascript\n buildHtml() {\n return this.buildTxt()\n }\n buildTxt() {\n return `${this.content ?? \"\"}${this.subparticlesToString()}`\n }\nplainTextOnlyParser\n popularity 0.000072\n extends plainTextParser\n description Only print for buildTxt.\n javascript\n buildHtml() {\n return \"\"\n }\nscrollThemeParser\n popularity 0.007524\n boolean isPopular true\n cue theme\n example\n theme gazette\n extends abstractScrollParser\n catchAllAtomType scrollThemeAtom\n description A collection of simple themes.\n string copyFromExternal .gazette.css\n // Note this will be replaced at runtime\n javascript\n get copyFromExternal() {\n return this.files.join(\" \")\n }\n get files() {\n return this.atoms.slice(1).map(name => `.${name}.css`).concat([\".scroll.css\"])\n }\n buildHtml() {\n return this.files.map(name => `<link rel=\"stylesheet\" type=\"text/css\" href=\"${name}\">`).join(\"\\n\")\n }\nabstractAftertextAttributeParser\n atoms cueAtom\n boolean isAttribute true\n javascript\n get htmlAttributes() {\n return `${this.cue}=\"${this.content}\"`\n }\n buildHtml() {\n return \"\"\n }\naftertextIdParser\n popularity 0.000145\n cue id\n description Provide an ID to be output in the generated HTML tag.\n extends abstractAftertextAttributeParser\n atoms cueAtom htmlIdAtom\n single\naftertextStyleParser\n popularity 0.000217\n cue style\n description Set HTML style attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType cssAnyAtom\n javascript\n htmlAttributes = \"\" // special case this one\n get css() { return `${this.property}:${this.content};` }\naftertextFontParser\n popularity 0.000217\n cue font\n description Set font.\n extends aftertextStyleParser\n atoms cueAtom fontFamilyAtom\n catchAllAtomType cssAnyAtom\n string property font-family\n javascript\n get css() {\n if (this.content === \"Slim\") return \"font-family:Helvetica Neue; font-weight:100;\"\n return super.css\n }\naftertextColorParser\n popularity 0.000217\n cue color\n description Set font color.\n extends aftertextStyleParser\n catchAllAtomType cssAnyAtom\n string property color\n example\n color blue\naftertextHrefParser\n popularity 0.000217\n cue href\n description Set HTML href attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom urlAtom\naftertextSrcParser\n extends aftertextHrefParser\n cue src\n description Set HTML src attribute.\naftertextOnclickParser\n popularity 0.000217\n cue onclick\n description Set HTML onclick attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType javascriptAnyAtom\naftertextHiddenParser\n cue hidden\n atoms cueAtom\n description Do not compile this particle to HTML.\n extends abstractAftertextAttributeParser\n single\naftertextValueParser\n popularity 0.000217\n cue value\n description Set HTML value attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextForParser\n popularity 0.000217\n cue for\n description Set HTML for attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom htmlAnyAtom\naftertextPlaceholderParser\n popularity 0.000217\n cue placeholder\n description Set HTML placeholder attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextRowsParser\n popularity 0.000217\n cue rows\n description Set HTML rows attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom integerAtom\naftertextTypeParser\n popularity 0.000217\n cue type\n description Set HTML type attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom htmlTypeAtom\naftertextAltParser\n popularity 0.000217\n cue alt\n description Set HTML alt attribute for images.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextTitleParser\n popularity 0.000217\n cue title\n description Set HTML title attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextNameParser\n popularity 0.000217\n cue name\n description Set HTML name attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextOnsubmitParser\n popularity 0.000217\n cue onsubmit\n description Set HTML onsubmit attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType javascriptAnyAtom\naftertextClassParser\n popularity 0.000217\n cue class\n description Set HTML class attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType classNameAtom\naftertextMaxlengthParser\n popularity 0.000217\n cue maxlength\n description Set HTML maxlength attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom integerAtom\naftertextPatternParser\n popularity 0.000217\n cue pattern\n description Set HTML pattern attribute for input validation.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextRequiredParser\n popularity 0.000217\n cue required\n description Set HTML required attribute.\n extends abstractAftertextAttributeParser\n single\naftertextDisabledParser\n popularity 0.000217\n cue disabled\n description Set HTML disabled attribute.\n extends abstractAftertextAttributeParser\n single\naftertextReadonlyParser\n popularity 0.000217\n cue readonly\n description Set HTML readonly attribute.\n extends abstractAftertextAttributeParser\n single\naftertextAriaLabelParser\n popularity 0.000217\n cue aria-label\n description Set ARIA label for accessibility.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextTargetParser\n popularity 0.000217\n cue target\n description Set HTML target attribute for links.\n extends abstractAftertextAttributeParser\n atoms cueAtom htmlAnyAtom\naftertextTagParser\n atoms cueAtom htmlTagAtom\n description Override the HTML tag that the compiled particle will use.\n cue tag\n javascript\n buildHtml() {\n return \"\"\n }\nabstractAftertextDirectiveParser\n atoms cueAtom\n catchAllAtomType stringAtom\n javascript\n isMarkup = true\n buildHtml() {\n return \"\"\n }\n getErrors() {\n const errors = super.getErrors()\n if (!this.isMarkup || this.matchWholeLine) return errors\n const inserts = this.getInserts(this.parent.originalTextPostLinkify)\n // todo: make AbstractParticleError class exported by sdk to allow Parsers to define their own error types.\n // todo: also need to be able to map lines back to their line in source (pre-imports)\n if (!inserts.length)\n errors.push(this.makeError(`No match found for \"${this.getLine()}\".`))\n return errors\n }\n get pattern() {\n return this.getAtomsFrom(1).join(\" \")\n }\n get shouldMatchAll() {\n return this.has(\"matchAll\")\n }\n getMatches(text) {\n const { pattern } = this\n const escapedPattern = pattern.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\")\n return [...text.matchAll(new RegExp(escapedPattern, \"g\"))].map(match => {\n const { index } = match\n const endIndex = index + pattern.length\n return [\n { index, string: `<${this.openTag}${this.allAttributes}>`, endIndex },\n { index: endIndex, endIndex, string: `</${this.closeTag}>` }\n ]\n })\n }\n getInserts(text) {\n const matches = this.getMatches(text)\n if (!matches.length) return false\n if (this.shouldMatchAll) return matches.flat()\n const match = this.getParticle(\"match\")\n if (match)\n return match.indexes\n .map(index => matches[index])\n .filter(i => i)\n .flat()\n return matches[0]\n }\n get allAttributes() {\n const attr = this.attributes.join(\" \")\n return attr ? \" \" + attr : \"\"\n }\n get attributes() {\n return []\n }\n get openTag() {\n return this.tag\n }\n get closeTag() {\n return this.tag\n }\nabstractMarkupParser\n extends abstractAftertextDirectiveParser\n inScope abstractMarkupParameterParser\n javascript\n get matchWholeLine() {\n return this.getAtomsFrom(this.patternStartsAtAtom).length === 0\n }\n get pattern() {\n return this.matchWholeLine ? this.parent.originalText : this.getAtomsFrom(this.patternStartsAtAtom).join(\" \")\n }\n patternStartsAtAtom = 1\nboldParser\n popularity 0.000096\n cueFromId\n description Bold matching text.\n extends abstractMarkupParser\n javascript\n tag = \"b\"\nitalicsParser\n popularity 0.000241\n cueFromId\n description Italicize matching text.\n extends abstractMarkupParser\n javascript\n tag = \"i\"\nunderlineParser\n popularity 0.000024\n description Underline matching text.\n cueFromId\n extends abstractMarkupParser\n javascript\n tag = \"u\"\nafterTextCenterParser\n popularity 0.000193\n description Center paragraph.\n cue center\n extends abstractMarkupParser\n javascript\n tag = \"center\"\naftertextCodeParser\n popularity 0.000145\n description Wrap matching text in code span.\n cue code\n extends abstractMarkupParser\n javascript\n tag = \"code\"\naftertextStrikeParser\n popularity 0.000048\n description Wrap matching text in s span.\n cue strike\n extends abstractMarkupParser\n javascript\n tag = \"s\"\naddClassMarkupParser\n popularity 0.000772\n description Add a custom class to parent element. Provide query to add span matching text.\n extends abstractMarkupParser\n atoms cueAtom classNameAtom\n cue addClass\n javascript\n tag = \"span\"\n get applyToParentElement() {\n return this.atoms.length === 2\n }\n getInserts(text) {\n // If no select text is added, set the class on the parent element.\n if (this.applyToParentElement) return []\n return super.getInserts(text)\n }\n get className() {\n return this.getAtom(1)\n }\n get attributes() {\n return [`class=\"${this.className}\"`]\n }\n get matchWholeLine() {\n return this.applyToParentElement\n }\n get pattern() {\n return this.matchWholeLine ? this.parent.content : this.getAtomsFrom(2).join(\" \")\n }\nhoverNoteParser\n popularity 0.000265\n description Add a caveat viewable on hover on matching text. When you want to be sure you've thoroughly addressed obvious concerns but ones that don't warrant to distract from the main argument of the text.\n cueFromId\n extends addClassMarkupParser\n catchAllParser lineOfTextParser\n atoms cueAtom\n javascript\n get pattern() {\n return this.getAtomsFrom(1).join(\" \")\n }\n get attributes() {\n return [`class=\"scrollHoverNote\"`, `title=\"${this.hoverNoteText}\"`]\n }\n get hoverNoteText() {\n return this.subparticlesToString().replace(/\\n/g, \" \")\n }\nscrollLinkParser\n popularity 0.008706\n extends abstractMarkupParser\n description Put the matching text in an <a> tag.\n atoms cueAtom urlAtom\n inScope linkTitleParser linkTargetParser abstractCommentParser\n programParser\n description Anything here will be URI encoded and then appended to the link.\n cueFromId\n atoms cueAtom\n catchAllParser programLinkParser\n javascript\n get encoded() {\n return encodeURIComponent(this.subparticlesToString())\n }\n cue link\n javascript\n tag = \"a\"\n buildTxt() {\n return this.root.ensureAbsoluteLink(this.link) + \" \" + this.pattern\n }\n get link() {\n const {baseLink} = this\n if (this.has(\"program\"))\n return baseLink + this.getParticle(\"program\").encoded\n return baseLink\n }\n get baseLink() {\n const link = this.getAtom(1)\n const isAbsoluteLink = link.includes(\"://\")\n if (isAbsoluteLink) return link\n const relativePath = this.parent.buildSettings?.relativePath || \"\"\n return relativePath + link\n }\n get linkAttribute() {\n return \"href\"\n }\n get attributes() {\n const attrs = [`${this.linkAttribute}=\"${this.link}\"`]\n const options = [\"title\", \"target\"]\n options.forEach(option => {\n const particle = this.getParticle(option)\n if (particle) attrs.push(`${option}=\"${particle.content}\"`)\n })\n return attrs\n }\n patternStartsAtAtom = 2\nscrollClickParser\n extends scrollLinkParser\n description An a tag with an onclick.\n cue click\n javascript\n get linkAttribute() {\n return \"onclick\"\n }\nemailLinkParser\n popularity 0.000048\n description A mailto link\n cue email\n extends scrollLinkParser\n javascript\n get attributes() {\n return [`href=\"mailto:${this.link}\"`]\n }\nquickLinkParser\n popularity 0.029228\n pattern ^https?\\:\n extends scrollLinkParser\n atoms urlAtom\n javascript\n get link() {\n return this.cue\n }\n patternStartsAtAtom = 1\nquickRelativeLinkParser\n popularity 0.029228\n description Relative links.\n // note: only works if relative link ends in .html\n pattern ^[^\\s]+\\.(html|htm)\n extends scrollLinkParser\n atoms urlAtom\n javascript\n get link() {\n return this.cue\n }\n patternStartsAtAtom = 1\ndatelineParser\n popularity 0.006005\n cueFromId\n description Gives your paragraph a dateline like \"December 15, 2021 — The...\"\n extends abstractAftertextDirectiveParser\n javascript\n getInserts() {\n const {day} = this\n if (!day) return false\n return [{ index: 0, string: `<span class=\"scrollDateline\">${day} — </span>` }]\n }\n matchWholeLine = true\n get day() {\n let day = this.content || this.root.date\n if (!day) return \"\"\n return this.root.dayjs(day).format(`MMMM D, YYYY`)\n }\ndayjsParser\n description Advanced directive that evals some Javascript code in an environment including \"dayjs\".\n cueFromId\n extends abstractAftertextDirectiveParser\n javascript\n getInserts() {\n const dayjs = this.root.dayjs\n const days = eval(this.content)\n const index = this.parent.originalTextPostLinkify.indexOf(\"days\")\n return [{ index, string: `${days} ` }]\n }\ninlineMarkupsOnParser\n popularity 0.000024\n cueFromId\n description Enable these inline markups only.\n example\n Hello *world*!\n inlineMarkupsOn bold\n extends abstractAftertextDirectiveParser\n catchAllAtomType inlineMarkupNameAtom\n javascript\n get shouldMatchAll() {\n return true\n }\n get markups() {\n const {root} = this\n let markups = [{delimiter: \"`\", tag: \"code\", exclusive: true, name: \"code\"},{delimiter: \"*\", tag: \"strong\", name: \"bold\"}, {delimiter: \"_\", tag: \"em\", name: \"italics\"}]\n // only add katex markup if the root doc has katex.\n if (root.has(\"katex\"))\n markups.unshift({delimiter: \"$\", tag: \"span\", attributes: ' class=\"scrollKatex\"', exclusive: true, name: \"katex\"})\n if (this.content)\n return markups.filter(markup => this.content.includes(markup.name))\n if (root.has(\"inlineMarkups\")) {\n root.getParticle(\"inlineMarkups\").forEach(markup => {\n const delimiter = markup.getAtom(0)\n const tag = markup.getAtom(1)\n // todo: add support for providing custom functions for inline markups?\n // for example, !2+2! could run eval, or :about: could search a link map.\n const attributes = markup.getAtomsFrom(2).join(\" \")\n markups = markups.filter(mu => mu.delimiter !== delimiter) // Remove any overridden markups\n if (tag)\n markups.push({delimiter, tag, attributes})\n })\n }\n return markups\n }\n matchWholeLine = true\n getMatches(text) {\n const exclusives = []\n return this.markups.map(markup => this.applyMarkup(text, markup, exclusives)).filter(i => i).flat()\n }\n applyMarkup(text, markup, exclusives = []) {\n const {delimiter, tag, attributes} = markup\n const escapedDelimiter = delimiter.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\")\n const pattern = new RegExp(`${escapedDelimiter}[^${escapedDelimiter}]+${escapedDelimiter}`, \"g\")\n const delimiterLength = delimiter.length\n return [...text.matchAll(pattern)].map(match => {\n const { index } = match\n const endIndex = index + match[0].length\n // I'm too lazy to clean up sdk to write a proper inline markup parser so doing this for now.\n // The exclusive idea is to not try and apply bold or italic styles inside a TeX or code inline style.\n // Note that the way this is currently implemented any TeX in an inline code will get rendered, but code\n // inline of TeX will not. Seems like an okay tradeoff until a proper refactor and cleanup can be done.\n if (exclusives.some(exclusive => index >= exclusive[0] && index <= exclusive[1]))\n return undefined\n if (markup.exclusive)\n exclusives.push([index, endIndex])\n return [\n { index, string: `<${tag + (attributes ? \" \" + attributes : \"\")}>`, endIndex, consumeStartCharacters: delimiterLength },\n { index: endIndex, endIndex, string: `</${tag}>`, consumeEndCharacters: delimiterLength }\n ]\n }).filter(i => i)\n }\ninlineMarkupParser\n popularity 0.000169\n cueFromId\n atoms cueAtom delimiterAtom tagOrUrlAtom\n catchAllAtomType htmlAttributesAtom\n extends inlineMarkupsOnParser\n description Custom inline markup. for\n example\n @This@ will be in italics.\n inlineMarkup @ em\n javascript\n getMatches(text) {\n try {\n const delimiter = this.getAtom(1)\n const tag = this.getAtom(2)\n const attributes = this.getAtomsFrom(3).join(\" \")\n return this.applyMarkup(text, {delimiter, tag, attributes})\n } catch (err) {\n console.error(err)\n return []\n }\n // Note: doubling up doesn't work because of the consumption characters.\n }\nlinkifyParser\n description Use this to disable linkify on the text.\n extends abstractAftertextDirectiveParser\n cueFromId\n atoms cueAtom booleanAtom\nabstractMarkupParameterParser\n atoms cueAtom\n cueFromId\nmatchAllParser\n popularity 0.000024\n description Use this to match all occurrences of the text.\n extends abstractMarkupParameterParser\nmatchParser\n popularity 0.000048\n catchAllAtomType integerAtom\n description Use this to specify which index(es) to match.\n javascript\n get indexes() {\n return this.getAtomsFrom(1).map(num => parseInt(num))\n }\n example\n aftertext\n hello ello ello\n bold ello\n match 0 2\n extends abstractMarkupParameterParser\nabstractHtmlAttributeParser\n javascript\n buildHtml() {\n return \"\"\n }\nlinkTargetParser\n popularity 0.000024\n extends abstractHtmlAttributeParser\n description If you want to set the target of the link. To \"_blank\", for example.\n cue target\n atoms cueAtom codeAtom\nblankLineParser\n popularity 0.308149\n description Print nothing. Break section.\n atoms blankAtom\n boolean isPopular true\n javascript\n buildHtml() {\n return this.parent.clearSectionStack()\n }\n pattern ^$\n tags doNotSynthesize\nscrollFileAddressParser\n catchAllAtomType filePathAtom\n catchAllParser scrollFileAddressParser\nchatLineParser\n popularity 0.009887\n catchAllAtomType stringAtom\n catchAllParser chatLineParser\nlineOfCodeParser\n popularity 0.018665\n catchAllAtomType codeAtom\n catchAllParser lineOfCodeParser\ncommentLineParser\n catchAllAtomType commentAtom\ncssLineParser\n popularity 0.002870\n catchAllAtomType cssAnyAtom\n catchAllParser cssLineParser\nabstractTableTransformParser\n atoms cueAtom\n inScope abstractTableVisualizationParser abstractTableTransformParser h1Parser h2Parser scrollQuestionParser htmlInlineParser scrollBrParser slashCommentParser\n javascript\n get coreTable() {\n return this.parent.coreTable\n }\n get columnNames() {\n return this.parent.columnNames\n }\n connectColumnNames(userColumnNames, availableColumnNames = this.parent.columnNames) {\n const result = {}\n const normalize = str => str.toLowerCase().trim()\n userColumnNames.forEach(userColumn => {\n // Strategy 1: Exact match\n const exactMatch = availableColumnNames.find(col => col === userColumn)\n if (exactMatch) {\n result[userColumn] = exactMatch\n return\n }\n // Strategy 2: Case-insensitive match\n const normalizedUserColumn = normalize(userColumn)\n const caseInsensitiveMatch = availableColumnNames.find(col => normalize(col) === normalizedUserColumn)\n if (caseInsensitiveMatch) {\n result[userColumn] = caseInsensitiveMatch\n return\n }\n // Strategy 3: Levenshtein distance match\n const THRESHOLD = 2 // Consider matches with distance <= 2 as \"very close\"\n let bestMatch = null\n let bestDistance = Infinity\n availableColumnNames.forEach(col => {\n const distance = this.root.levenshteinDistance(userColumn, col)\n if (distance < bestDistance) {\n bestDistance = distance\n bestMatch = col\n }\n })\n // Only use Levenshtein match if it's very close\n if (bestDistance <= THRESHOLD) {\n result[userColumn] = bestMatch\n return\n }\n // Strategy 4: Fallback - use original unmatched name\n result[userColumn] = userColumn\n })\n return result\n }\n connectColumnName(name) {\n return this.connectColumnNames([name])[name]\n }\n getErrors() {\n const errors = super.getErrors()\n if (errors.length && this.previous.cue !== \"assertIgnoreBelowErrors\")\n return errors\n return []\n }\n getRunTimeEnumOptions(atom) {\n if (atom.atomTypeId === \"columnNameAtom\")\n return this.parent.columnNames\n return super.getRunTimeEnumOptions(atom)\n }\n getRunTimeEnumOptionsForValidation(atom) {\n // Note: this will fail if the CSV file hasnt been built yet.\n if (atom.atomTypeId === \"columnNameAtom\")\n return this.parent.columnNames.concat(this.parent.columnNames.map(c => \"-\" + c)) // Add reverse names\n return super.getRunTimeEnumOptions(atom)\n }\nabstractDateSplitTransformParser\n extends abstractTableTransformParser\n atoms cueAtom\n catchAllAtomType columnNameAtom\n javascript\n get coreTable() {\n const columnName = this.getAtom(1) || this.detectDateColumn()\n if (!columnName) return this.parent.coreTable\n return this.parent.coreTable.map(row => {\n const newRow = {...row}\n try {\n const date = this.root.dayjs(row[columnName])\n if (date.isValid())\n newRow[this.newColumnName] = this.transformDate(date)\n } catch (err) {}\n return newRow\n })\n }\n detectDateColumn() {\n const columns = this.parent.columnNames\n const dateColumns = ['date', 'created', 'published', 'timestamp']\n for (const col of dateColumns) {\n if (columns.includes(col)) return col\n }\n for (const col of columns) {\n const sample = this.parent.coreTable[0][col]\n if (sample && this.root.dayjs(sample).isValid())\n return col\n }\n return null\n }\n get columnNames() {\n return [...this.parent.columnNames, this.newColumnName]\n }\n transformDate(date) {\n const formatted = date.format(this.dateFormat)\n const isInt = !this.cue.includes(\"Name\")\n return isInt ? parseInt(formatted) : formatted\n }\nscrollSplitYearParser\n extends abstractDateSplitTransformParser\n description Extract year into new column.\n cue splitYear\n string newColumnName year\n string dateFormat YYYY\nscrollSplitDayNameParser\n extends abstractDateSplitTransformParser\n description Extract day name into new column.\n cue splitDayName\n string newColumnName dayName\n string dateFormat dddd\nscrollSplitMonthNameParser\n extends abstractDateSplitTransformParser\n description Extract month name into new column.\n cue splitMonthName\n string newColumnName monthName\n string dateFormat MMMM\nscrollSplitMonthParser\n extends abstractDateSplitTransformParser\n description Extract month number (1-12) into new column.\n cue splitMonth\n string newColumnName month\n string dateFormat M\nscrollSplitDayOfMonthParser\n extends abstractDateSplitTransformParser\n description Extract day of month (1-31) into new column.\n cue splitDayOfMonth\n string newColumnName dayOfMonth\n string dateFormat D\nscrollSplitDayOfWeekParser\n extends abstractDateSplitTransformParser\n description Extract day of week (0-6) into new column.\n cue splitDay\n string newColumnName day\n string dateFormat d\nscrollParseDateParser\n extends abstractTableTransformParser\n description Parse dates in a column into standard format.\n cue parseDate\n atoms cueAtom columnNameAtom\n example\n sampleData stocks.csv\n parseDate date\n linechart\n x date\n y price\n javascript\n get coreTable() {\n const columnName = this.connectColumnName(this.getAtom(1))\n const formatOut = this.get(\"format\") || \"YYYY-MM-DD\"\n const {dayjs} = this.root\n return this.parent.coreTable.map(row => {\n const newRow = {...row}\n try {\n const value = row[columnName]\n if (value) {\n const date = dayjs(value)\n if (date.isValid())\n newRow[columnName] = date.format(formatOut)\n }\n } catch (err) {\n console.error(`Error parsing date in column ${columnName}:`, err)\n }\n return newRow\n })\n }\n formatParser\n description Specify output date format\n atoms cueAtom stringAtom\n cueFromId\n single\nscrollGroupByParser\n catchAllAtomType columnNameAtom\n extends abstractTableTransformParser\n reduceParser\n description Specify how to aggregate a column when grouping data\n atoms cueAtom columnNameAtom reductionTypeAtom newColumnNameAtom\n cue reduce\n example\n data.csv\n groupBy year\n reduce score sum totalScore\n reduce name concat names\n printTable\n javascript\n get reduction() {\n return {\n source: this.getAtom(1),\n reduction: this.getAtom(2),\n name: this.getAtom(3) || this.getAtomsFrom(1).join(\"_\")\n }\n }\n description Combine rows with matching values into groups.\n example\n tables posts.csv\n groupBy year\n printTable\n cue groupBy\n javascript\n get coreTable() {\n if (this._coreTable) return this._coreTable\n const groupByColNames = this.getAtomsFrom(1)\n const {coreTable} = this.parent\n if (!groupByColNames.length) return coreTable\n const newCols = this.findParticles(\"reduce\").map(particle => particle.reduction)\n // Pivot is shorthand for group and reduce?\n const makePivotTable = (rows, groupByColumnNames, inputColumnNames, newCols) => {\n const colMap = {}\n inputColumnNames.forEach((col) => (colMap[col] = true))\n const groupByCols = groupByColumnNames.filter((col) => colMap[col])\n return new PivotTable(rows, inputColumnNames.map(c => {return {name: c}}), newCols).getNewRows(groupByCols)\n }\n class PivotTable {\n constructor(rows, inputColumns, outputColumns) {\n this._columns = {}\n this._rows = rows\n inputColumns.forEach((col) => (this._columns[col.name] = col))\n outputColumns.forEach((col) => (this._columns[col.name] = col))\n }\n _getGroups(allRows, groupByColNames) {\n const rowsInGroups = new Map()\n allRows.forEach((row) => {\n const groupKey = groupByColNames.map((col) => row[col]?.toString().replace(/ /g, \"\") || \"\").join(\" \")\n if (!rowsInGroups.has(groupKey)) rowsInGroups.set(groupKey, [])\n rowsInGroups.get(groupKey).push(row)\n })\n return rowsInGroups\n }\n getNewRows(groupByCols) {\n // make new particles\n const rowsInGroups = this._getGroups(this._rows, groupByCols)\n // Any column in the group should be reused by the children\n const columns = [\n {\n name: \"count\",\n type: \"number\",\n min: 0,\n },\n ]\n groupByCols.forEach((colName) => columns.push(this._columns[colName]))\n const colsToReduce = Object.values(this._columns).filter((col) => !!col.reduction)\n colsToReduce.forEach((col) => columns.push(col))\n // for each group\n const rows = []\n const totalGroups = rowsInGroups.size\n for (let [groupId, group] of rowsInGroups) {\n const firstRow = group[0]\n const newRow = {}\n groupByCols.forEach((col) =>\n newRow[col] = firstRow ? firstRow[col] : 0\n )\n newRow.count = group.length\n // todo: add more reductions? count, stddev, median, variance.\n colsToReduce.forEach((col) => {\n const sourceColName = col.source\n const reduction = col.reduction\n const newColName = col.name\n if (reduction === \"concat\") {\n newRow[newColName] = group.map((row) => row[sourceColName]).join(\" \")\n return \n }\n if (reduction === \"first\") {\n newRow[newColName] = group.find((row) => row[sourceColName] !== \"\")?.[sourceColName]\n return \n }\n const values = group.map((row) => row[sourceColName]).filter((val) => typeof val === \"number\" && !isNaN(val))\n let reducedValue = firstRow[sourceColName]\n if (reduction === \"sum\") reducedValue = values.reduce((prev, current) => prev + current, 0)\n if (reduction === \"max\") reducedValue = Math.max(...values)\n if (reduction === \"min\") reducedValue = Math.min(...values)\n if (reduction === \"mean\") reducedValue = values.reduce((prev, current) => prev + current, 0) / values.length\n newRow[newColName] = reducedValue\n })\n rows.push(newRow)\n }\n // todo: add tests. figure out this api better.\n Object.values(columns).forEach((col) => {\n // For pivot columns, remove the source and reduction info for now. Treat things as immutable.\n delete col.source\n delete col.reduction\n })\n return {\n rows,\n columns,\n }\n }\n }\n const pivotTable = makePivotTable(coreTable, groupByColNames, this.parent.columnNames, newCols)\n this._coreTable = pivotTable.rows\n this._columnNames = pivotTable.columns.map(col => col.name)\n return pivotTable.rows\n }\n get columnNames() {\n const {coreTable} = this\n return this._columnNames || this.parent.columnNames\n }\nscrollWhereParser\n extends abstractTableTransformParser\n description Filter rows by condition.\n cue where\n atoms cueAtom columnNameAtom comparisonAtom\n catchAllAtomType constantAtom\n example\n table iris.csv\n where Species = setosa\n javascript\n get coreTable() {\n // todo: use atoms here.\n const columnName = this.connectColumnName(this.getAtom(1))\n const operator = this.getAtom(2)\n let untypedComparisonValue = this.getAtom(3)\n const typedComparisonValue = isNaN(parseFloat(untypedComparisonValue)) ? untypedComparisonValue : parseFloat(untypedComparisonValue)\n const coreTable = this.parent.coreTable\n if (!columnName || !operator || (untypedComparisonValue === undefined && !operator.includes(\"mpty\"))) return coreTable\n const filterFn = row => {\n const atom = row[columnName]\n const typedAtom = atom === null ? undefined : atom // convert nulls to undefined\n if (operator === \"=\") return typedComparisonValue === typedAtom\n else if (operator === \"!=\") return typedComparisonValue !== typedAtom\n else if (operator === \"includes\") return typedAtom !== undefined && typedAtom.includes(typedComparisonValue)\n else if (operator === \"startsWith\") return typedAtom !== undefined && typedAtom.toString().startsWith(typedComparisonValue)\n else if (operator === \"endsWith\") return typedAtom !== undefined && typedAtom.toString().endsWith(typedComparisonValue)\n else if (operator === \"doesNotInclude\") return typedAtom === undefined || !typedAtom.includes(typedComparisonValue)\n else if (operator === \">\") return typedAtom > typedComparisonValue\n else if (operator === \"<\") return typedAtom < typedComparisonValue\n else if (operator === \">=\") return typedAtom >= typedComparisonValue\n else if (operator === \"<=\") return typedAtom <= typedComparisonValue\n else if (operator === \"empty\") return typedAtom === \"\" || typedAtom === undefined\n else if (operator === \"notEmpty\") return typedAtom !== \"\" && typedAtom !== undefined\n }\n return coreTable.filter(filterFn)\n }\nscrollSelectParser\n catchAllAtomType columnNameAtom\n extends abstractTableTransformParser\n description Drop all columns except these.\n example\n tables\n data\n name,year,count\n index,2022,2\n about,2023,4\n select name year\n printTable\n cue select\n javascript\n get coreTable() {\n const {coreTable} = this.parent\n const {columnNames} = this\n if (!columnNames.length) return coreTable\n return coreTable.map(row => Object.fromEntries(columnNames.map(colName => [colName, row[colName]])))\n }\n get columnNames() {\n if (!this._columnNames) {\n const names = this.getAtomsFrom(1)\n this._columnNamesMap = this.connectColumnNames(names)\n this._columnNames = names.map(name => this._columnNamesMap[name])\n }\n return this._columnNames\n }\nscrollReverseParser\n extends abstractTableTransformParser\n description Reverse rows.\n cue reverse\n javascript\n get coreTable() {\n return this.parent.coreTable.slice().reverse()\n }\nscrollComposeParser\n extends abstractTableTransformParser\n description Add column using format string.\n catchAllAtomType codeAtom\n cue compose\n atoms cueAtom newColumnNameAtom\n example\n table\n compose sentence My name is {name}\n printTable\n javascript\n get coreTable() {\n const {newColumnName} = this\n const formatString = this.getAtomsFrom(2).join(\" \")\n return this.parent.coreTable.map((row, index) => {\n const newRow = Object.assign({}, row)\n newRow[newColumnName] = this.evaluate(new Particle(row).evalTemplateString(formatString), index)\n return newRow\n })\n }\n evaluate(str) {\n return str\n }\n get newColumnName() {\n return this.atoms[1]\n }\n get columnNames() {\n return this.parent.columnNames.concat(this.newColumnName)\n }\nscrollComputeParser\n extends scrollComposeParser\n description Add column by evaling format string.\n cue compute\n javascript\n evaluate(str) {\n return parseFloat(eval(str))\n }\nscrollEvalParser\n extends scrollComputeParser\n description Add column by evaling format string.\n cue eval\n javascript\n evaluate(str) {\n return eval(str)\n }\nscrollRankParser\n extends scrollComposeParser\n description Add rank column.\n atoms cueAtom\n string newColumnName rank\n cue rank\n javascript\n evaluate(str, index) { return index + 1 }\nscrollLinksParser\n extends abstractTableTransformParser\n description Add column with links.\n cue links\n catchAllAtomType columnNameAtom\n javascript\n get coreTable() {\n const {newColumnName, linkColumns} = this\n return this.parent.coreTable.map(row => {\n const newRow = Object.assign({}, row)\n let newValue = []\n linkColumns.forEach(name => {\n const value = newRow[name]\n delete newRow[name]\n if (value) newValue.push(`<a href=\"${value.includes(\"@\") ? \"mailto:\" : \"\"}${value}\">${name}</a>`)\n })\n newRow[newColumnName] = newValue.join(\" \")\n return newRow\n })\n }\n get newColumnName() {\n return \"links\"\n }\n get linkColumns() {\n return this.getAtomsFrom(1)\n }\n get columnNames() {\n const {linkColumns} = this\n return this.parent.columnNames.filter(name => !linkColumns.includes(name)).concat(this.newColumnName)\n }\nscrollLimitParser\n extends abstractTableTransformParser\n description Select a subset.\n cue limit\n atoms cueAtom integerAtom integerAtom\n javascript\n get coreTable() {\n let start = this.getAtom(1)\n let end = this.getAtom(2)\n if (end === undefined) {\n end = start\n start = 0\n }\n return this.parent.coreTable.slice(parseInt(start), parseInt(end))\n }\nscrollShuffleParser\n extends abstractTableTransformParser\n description Randomly reorder rows.\n cue shuffle\n example\n table data.csv\n shuffle\n printTable\n javascript\n get coreTable() {\n // Create a copy of the table to avoid modifying original\n const rows = this.parent.coreTable.slice()\n // Fisher-Yates shuffle algorithm\n for (let i = rows.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * (i + 1))\n ;[rows[i], rows[j]] = [rows[j], rows[i]]\n }\n return rows\n }\nscrollTransposeParser\n extends abstractTableTransformParser\n description Tranpose table.\n cue transpose\n javascript\n get coreTable() {\n // todo: we need to switch to column based coreTable, instead of row based\n const transpose = arr => Object.keys(arr[0]).map(key => [key, ...arr.map(row => row[key])]);\n return transpose(this.parent.coreTable)\n }\nscrollImputeParser\n extends abstractTableTransformParser\n description Impute missing values of a columm.\n atoms cueAtom columnNameAtom\n cue impute\n javascript\n get coreTable() {\n const {columnName} = this\n const sorted = this.root.lodash.orderBy(this.parent.coreTable.slice(), columnName)\n // ascending\n const imputed = []\n let lastInserted = sorted[0][columnName]\n sorted.forEach(row => {\n const measuredTime = row[columnName]\n while (measuredTime > lastInserted + 1) {\n lastInserted++\n // synthesize rows\n const imputedRow = {}\n imputedRow[columnName] = lastInserted\n imputedRow.count = 0\n imputed.push(imputedRow)\n }\n lastInserted = measuredTime\n imputed.push(row)\n })\n return imputed\n }\n get columnName() {\n return this.connectColumnName(this.getAtom(1))\n }\nscrollOrderByParser\n extends abstractTableTransformParser\n description Sort rows by column(s).\n catchAllAtomType columnNameAtom\n cue orderBy\n javascript\n get coreTable() {\n const makeLodashOrderByParams = str => {\n const part1 = str.split(\" \")\n const part2 = part1.map(col => (col.startsWith(\"-\") ? \"desc\" : \"asc\"))\n return [part1.map(col => this.connectColumnName(col.replace(/^\\-/, \"\"))), part2]\n }\n const orderBy = makeLodashOrderByParams(this.content)\n return this.root.lodash.orderBy(this.parent.coreTable.slice(), orderBy[0], orderBy[1])\n }\nassertRowCountParser\n extends abstractTableTransformParser\n description Test row count is expected value.\n atoms cueAtom integerAtom\n cueFromId\n javascript\n getErrors() {\n const errors = super.getErrors()\n const actualRows = this.coreTable.length\n const expectedRows = parseInt(this.content)\n if (actualRows !== expectedRows)\n return errors.concat(this.makeError(`Expected '${expectedRows}' rows but got '${actualRows}'.`))\n return errors\n }\nscrollRenameParser\n // todo: add support in Parsers for tuple catch alls\n catchAllAtomType columnNameAtom newColumnNameAtom\n catchAllAtomType newColumnNameAtom\n extends abstractTableTransformParser\n description Rename columns.\n example\n tables\n data\n name,year,count\n index,2022,2\n rename name Name year Year\n printTable\n cue rename\n javascript\n get coreTable() {\n const {coreTable} = this.parent\n const {renameMap} = this\n if (!Object.keys(renameMap).length) return coreTable\n return coreTable.map(row => {\n const newRow = {}\n Object.keys(row).forEach(key => {\n const name = renameMap[key] || key\n newRow[name] = row[key]\n })\n return newRow\n })\n }\n get renameMap() {\n const map = {}\n const pairs = this.getAtomsFrom(1)\n let oldName\n while (oldName = pairs.shift()) {\n map[oldName] = pairs.shift()\n }\n return map\n }\n _renamed\n get columnNames() {\n if (this._renamed)\n return this._renamed\n const {renameMap} = this\n this._renamed = this.parent.columnNames.map(name => renameMap[name] || name )\n return this._renamed\n }\nscrollSummarizeParser\n extends abstractTableTransformParser\n description Generate summary statistics for each column.\n cue summarize\n example\n table data.csv\n summarize\n printTable\n javascript\n get coreTable() {\n const {lodash} = this.root\n const sourceData = this.parent.coreTable\n if (!sourceData.length) return []\n return this.parent.columnNames.map(colName => {\n const values = sourceData.map(row => row[colName]).filter(val => val !== undefined && val !== null)\n const numericValues = values.filter(val => typeof val === \"number\" && !isNaN(val))\n const sorted = [...numericValues].sort((a, b) => a - b)\n // Calculate mode\n const frequency = {}\n values.forEach(val => {\n frequency[val] = (frequency[val] || 0) + 1\n })\n const mode = Object.entries(frequency)\n .sort((a, b) => b[1] - a[1])\n .map(entry => entry[0])[0]\n // Calculate median for numeric values\n const median = sorted.length ? \n sorted.length % 2 === 0 \n ? (sorted[sorted.length/2 - 1] + sorted[sorted.length/2]) / 2\n : sorted[Math.floor(sorted.length/2)]\n : null\n const sum = numericValues.length ? numericValues.reduce((a, b) => a + b, 0) : null\n const theType = typeof values[0]\n const count = values.length\n const mean = theType === \"number\" ? sum/count : \"\"\n return {\n name: colName,\n type: theType,\n incompleteCount: sourceData.length - values.length,\n uniqueCount: new Set(values).size,\n count,\n sum,\n median,\n mean,\n min: sorted.length ? sorted[0] : null,\n max: sorted.length ? sorted[sorted.length - 1] : null,\n mode\n }\n })\n }\n get columnNames() {\n return [\"name\", \"type\", \"incompleteCount\", \"uniqueCount\", \"count\", \"sum\", \"median\", \"mean\", \"min\", \"max\", \"mode\"]\n }\nerrorParser\n baseParser errorParser\nhakonContentParser\n popularity 0.102322\n catchAllAtomType codeAtom\nheatrixCatchAllParser\n popularity 0.000193\n // todo Fill this out\n catchAllAtomType stringAtom\nlineOfTextParser\n popularity 0.000289\n catchAllAtomType stringAtom\n boolean isTextParser true\nhtmlLineParser\n popularity 0.005209\n catchAllAtomType htmlAnyAtom\n catchAllParser htmlLineParser\nopenGraphParser\n // todo: fix Parsers scope issue so we can move this parser def under scrollImageParser\n description Add this line to make this the open graph image.\n cueFromId\n atoms cueAtom\nimportToFooterParser\n description Import to bottom of file.\n atoms preBuildCommandAtom\n cue footer\nscriptLineParser\n catchAllAtomType javascriptAnyAtom\n catchAllParser scriptLineParser\nlinkTitleParser\n popularity 0.000048\n description If you want to set the title of the link.\n cue title\n atoms cueAtom\n catchAllAtomType stringAtom\n example\n * This report showed the treatment had a big impact.\n https://example.com/report This report.\n title The average growth in the treatment group was 14.2x higher than the control group.\nprogramLinkParser\n popularity 0.000531\n catchAllAtomType codeAtom\nscrollMediaLoopParser\n popularity 0.000048\n cue loop\n atoms cueAtom\nscrollAutoplayParser\n cue autoplay\n atoms cueAtom\nabstractCompilerRuleParser\n catchAllAtomType anyAtom\n atoms cueAtom\ncloseSubparticlesParser\n extends abstractCompilerRuleParser\n description When compiling a parent particle to a string, this string is appended to the compiled and joined subparticles. Default is blank.\n cueFromId\nindentCharacterParser\n extends abstractCompilerRuleParser\n description You can change the indent character for compiled subparticles. Default is a space.\n cueFromId\ncatchAllAtomDelimiterParser\n description If a particle has a catchAllAtom, this is the string delimiter that will be used to join those atoms. Default is comma.\n extends abstractCompilerRuleParser\n cueFromId\nopenSubparticlesParser\n extends abstractCompilerRuleParser\n description When compiling a parent particle to a string, this string is prepended to the compiled and joined subparticles. Default is blank.\n cueFromId\nstringTemplateParser\n extends abstractCompilerRuleParser\n description This template string is used to compile this line, and accepts strings of the format: const var = {someAtomId}\n cueFromId\njoinSubparticlesWithParser\n description When compiling a parent particle to a string, subparticles are compiled to strings and joined by this character. Default is a newline.\n extends abstractCompilerRuleParser\n cueFromId\nabstractConstantParser\n description A constant.\n atoms cueAtom\n cueFromId\n // todo: make tags inherit\n tags actPhase\nparsersBooleanParser\n cue boolean\n atoms cueAtom constantIdentifierAtom\n catchAllAtomType booleanAtom\n extends abstractConstantParser\n tags actPhase\nparsersFloatParser\n cue float\n atoms cueAtom constantIdentifierAtom\n catchAllAtomType floatAtom\n extends abstractConstantParser\n tags actPhase\nparsersIntParser\n cue int\n atoms cueAtom constantIdentifierAtom\n catchAllAtomType integerAtom\n tags actPhase\n extends abstractConstantParser\nparsersStringParser\n cue string\n atoms cueAtom constantIdentifierAtom\n catchAllAtomType stringAtom\n catchAllParser catchAllMultilineStringConstantParser\n extends abstractConstantParser\n tags actPhase\nabstractParserRuleParser\n single\n atoms cueAtom\nabstractNonTerminalParserRuleParser\n extends abstractParserRuleParser\nparsersBaseParserParser\n atoms cueAtom baseParsersAtom\n description Set for blobs or errors. \n // In rare cases with untyped content you can use a blobParser, for now, to skip parsing for performance gains. The base errorParser will report errors when parsed. Use that if you don't want to implement your own error parser.\n extends abstractParserRuleParser\n cue baseParser\n tags analyzePhase\ncatchAllAtomTypeParser\n atoms cueAtom atomTypeIdAtom\n description Use for lists.\n // Aka 'listAtomType'. Use this when the value in a key/value pair is a list. If there are extra atoms in the particle's line, parse these atoms as this type. Often used with `listDelimiterParser`.\n extends abstractParserRuleParser\n cueFromId\n tags analyzePhase\natomParserParser\n atoms cueAtom atomParserAtom\n description Set parsing strategy.\n // prefix/postfix/omnifix parsing strategy. If missing, defaults to prefix.\n extends abstractParserRuleParser\n cueFromId\n tags experimental analyzePhase\ncatchAllParserParser\n description Attach this to unmatched lines.\n // If a parser is not found in the inScope list, instantiate this type of particle instead.\n atoms cueAtom parserIdAtom\n extends abstractParserRuleParser\n cueFromId\n tags acquirePhase\nparsersAtomsParser\n catchAllAtomType atomTypeIdAtom\n description Set required atomTypes.\n extends abstractParserRuleParser\n cue atoms\n tags analyzePhase\nparsersCompilerParser\n // todo Remove this and its subparticles?\n description Deprecated. For simple compilers.\n inScope stringTemplateParser catchAllAtomDelimiterParser openSubparticlesParser closeSubparticlesParser indentCharacterParser joinSubparticlesWithParser\n extends abstractParserRuleParser\n cue compiler\n tags deprecate\n boolean suggestInAutocomplete false\nparserDescriptionParser\n description Parser description.\n catchAllAtomType stringAtom\n extends abstractParserRuleParser\n cue description\n tags assemblePhase\nparsersExampleParser\n // todo Should this just be a \"string\" constant on particles?\n description Set example for docs and tests.\n catchAllAtomType exampleAnyAtom\n catchAllParser catchAllExampleLineParser\n extends abstractParserRuleParser\n cue example\n tags assemblePhase\nextendsParserParser\n cue extends\n tags assemblePhase\n description Extend another parser.\n // todo: add a catchall that is used for mixins\n atoms cueAtom parserIdAtom\n extends abstractParserRuleParser\nparsersPopularityParser\n // todo Remove this parser. Switch to conditional frequencies.\n description Parser popularity.\n atoms cueAtom floatAtom\n extends abstractParserRuleParser\n cue popularity\n tags assemblePhase\ninScopeParser\n description Parsers in scope.\n catchAllAtomType parserIdAtom\n extends abstractParserRuleParser\n cueFromId\n tags acquirePhase\nparsersJavascriptParser\n // todo Urgently need to get submode syntax highlighting running! (And eventually LSP)\n description Javascript code for Parser Actions.\n catchAllParser catchAllJavascriptCodeLineParser\n extends abstractParserRuleParser\n tags actPhase\n javascript\n format() {\n if (this.isNodeJs()) {\n const template = `class FOO{ ${this.subparticlesToString()}}`\n this.setSubparticles(\n require(\"prettier\")\n .format(template, { semi: false, useTabs: true, parser: \"babel\", printWidth: 240 })\n .replace(/class FOO \\{\\s+/, \"\")\n .replace(/\\s+\\}\\s+$/, \"\")\n .replace(/\\n\\t/g, \"\\n\") // drop one level of indent\n .replace(/\\t/g, \" \") // we used tabs instead of spaces to be able to dedent without breaking literals.\n )\n }\n return this\n }\n cue javascript\nabstractParseRuleParser\n // Each particle should have a pattern that it matches on unless it's a catch all particle.\n extends abstractParserRuleParser\n cueFromId\nparsersCueParser\n atoms cueAtom stringAtom\n description Attach by matching first atom.\n extends abstractParseRuleParser\n tags acquirePhase\n cue cue\ncueFromIdParser\n atoms cueAtom\n description Derive cue from parserId.\n // for example 'fooParser' would have cue of 'foo'.\n extends abstractParseRuleParser\n tags acquirePhase\nparsersPatternParser\n catchAllAtomType regexAtom\n description Attach via regex.\n extends abstractParseRuleParser\n tags acquirePhase\n cue pattern\nparsersRequiredParser\n description Assert is present at least once.\n extends abstractParserRuleParser\n cue required\n tags analyzePhase\nabstractValidationRuleParser\n extends abstractParserRuleParser\n cueFromId\n catchAllAtomType booleanAtom\nparsersSingleParser\n description Assert used once.\n // Can be overridden by a child class by setting to false.\n extends abstractValidationRuleParser\n tags analyzePhase\n cue single\nuniqueLineParser\n description Assert unique lines. For pattern parsers.\n // Can be overridden by a child class by setting to false.\n extends abstractValidationRuleParser\n tags analyzePhase\nuniqueCueParser\n description Assert unique first atoms. For pattern parsers.\n // For catch all parsers or pattern particles, use this to indicate the \n extends abstractValidationRuleParser\n tags analyzePhase\nlistDelimiterParser\n description Split content by this delimiter.\n extends abstractParserRuleParser\n cueFromId\n catchAllAtomType stringAtom\n tags analyzePhase\ncontentKeyParser\n description Deprecated. For to/from JSON.\n // Advanced keyword to help with isomorphic JSON serialization/deserialization. If present will serialize the particle to an object and set a property with this key and the value set to the particle's content.\n extends abstractParserRuleParser\n cueFromId\n catchAllAtomType stringAtom\n tags deprecate\n boolean suggestInAutocomplete false\nsubparticlesKeyParser\n // todo: deprecate?\n description Deprecated. For to/from JSON.\n // Advanced keyword to help with serialization/deserialization of blobs. If present will serialize the particle to an object and set a property with this key and the value set to the particle's subparticles.\n extends abstractParserRuleParser\n cueFromId\n catchAllAtomType stringAtom\n tags deprecate\n boolean suggestInAutocomplete false\nparsersTagsParser\n catchAllAtomType stringAtom\n extends abstractParserRuleParser\n description Custom metadata.\n cue tags\n tags assemblePhase\natomTypeDescriptionParser\n description Atom Type description.\n catchAllAtomType stringAtom\n cue description\n tags assemblePhase\ncatchAllErrorParser\n baseParser errorParser\ncatchAllExampleLineParser\n catchAllAtomType exampleAnyAtom\n catchAllParser catchAllExampleLineParser\n atoms exampleAnyAtom\ncatchAllJavascriptCodeLineParser\n catchAllAtomType javascriptCodeAtom\n catchAllParser catchAllJavascriptCodeLineParser\ncatchAllMultilineStringConstantParser\n description String constants can span multiple lines.\n catchAllAtomType stringAtom\n catchAllParser catchAllMultilineStringConstantParser\n atoms stringAtom\natomTypeDefinitionParser\n // todo Generate a class for each atom type?\n // todo Allow abstract atom types?\n // todo Change pattern to postfix.\n pattern ^[a-zA-Z0-9_]+Atom$\n inScope parsersPaintParser parsersRegexParser reservedAtomsParser enumFromAtomTypesParser atomTypeDescriptionParser parsersEnumParser slashCommentParser extendsAtomTypeParser parsersExamplesParser atomMinParser atomMaxParser\n atoms atomTypeIdAtom\n tags assemblePhase\n javascript\n buildHtml() {return \"\"}\nenumFromAtomTypesParser\n description Runtime enum options.\n catchAllAtomType atomTypeIdAtom\n atoms atomPropertyNameAtom\n cueFromId\n tags analyzePhase\nparsersEnumParser\n description Set enum options.\n cue enum\n catchAllAtomType enumOptionAtom\n atoms atomPropertyNameAtom\n tags analyzePhase\nparsersExamplesParser\n description Examples for documentation and tests.\n // If the domain of possible atom values is large, such as a string type, it can help certain methods—such as program synthesis—to provide a few examples.\n cue examples\n catchAllAtomType atomExampleAtom\n atoms atomPropertyNameAtom\n tags assemblePhase\natomMinParser\n description Specify a min if numeric.\n cue min\n atoms atomPropertyNameAtom numberAtom\n tags analyzePhase\natomMaxParser\n description Specify a max if numeric.\n cue max\n atoms atomPropertyNameAtom numberAtom\n tags analyzePhase\nparsersPaintParser\n atoms cueAtom paintTypeAtom\n description Instructor editor how to color these.\n single\n cue paint\n tags analyzePhase\nparserDefinitionParser\n // todo Add multiple dispatch?\n pattern ^[a-zA-Z0-9_]+Parser$\n description Parser types are a core unit of your language. They translate to 1 class per parser. Examples of parser would be \"header\", \"person\", \"if\", \"+\", \"define\", etc.\n catchAllParser catchAllErrorParser\n inScope abstractParserRuleParser abstractConstantParser slashCommentParser parserDefinitionParser\n atoms parserIdAtom\n tags assemblePhase\n javascript\n buildHtml() { return \"\"}\nparsersRegexParser\n catchAllAtomType regexAtom\n description Atoms must match this.\n single\n atoms atomPropertyNameAtom\n cue regex\n tags analyzePhase\nreservedAtomsParser\n single\n description Atoms can't be any of these.\n catchAllAtomType reservedAtomAtom\n atoms atomPropertyNameAtom\n cueFromId\n tags analyzePhase\nextendsAtomTypeParser\n cue extends\n description Extend another atomType.\n // todo Add mixin support in addition to extends?\n atoms cueAtom atomTypeIdAtom\n tags assemblePhase\n single\nabstractColumnNameParser\n atoms cueAtom columnNameAtom\n javascript\n getRunTimeEnumOptions(atom) {\n if (atom.atomTypeId === \"columnNameAtom\")\n return this.parent.columnNames\n return super.getRunTimeEnumOptions(atom)\n }\nscrollRadiusParser\n cue radius\n extends abstractColumnNameParser\nscrollSymbolParser\n cue symbol\n extends abstractColumnNameParser\nabstractColumnNameOrColorParser\n extends abstractColumnNameParser\n atoms cueAtom columnNameOrColorAtom\n javascript\n //todo: cleanup\n colorOptions = \"aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkkhaki darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray darkturquoise darkviolet deeppink deepskyblue dimgray dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow honeydew hotpink indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgoldenrodyellow lightgray lightgreen lightpink lightsalmon lightseagreen lightskyblue lightslategray lightsteelblue lightyellow lime limegreen linen magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell sienna silver skyblue slateblue slategray snow springgreen steelblue tan teal thistle tomato turquoise violet wheat white whitesmoke yellow yellowgreen\".split(\" \")\n getRunTimeEnumOptions(atom) {\n if (atom.atomTypeId === \"columnNameOrColorAtom\")\n return this.parent.columnNames.join(this.colorOptions)\n return super.getRunTimeEnumOptions(atom)\n }\nscrollFillParser\n cue fill\n extends abstractColumnNameOrColorParser\nscrollStrokeParser\n cue stroke\n extends abstractColumnNameOrColorParser\nscrollLabelParser\n cue label\n extends abstractColumnNameParser\nscrollSortParser\n cue sort\n extends abstractColumnNameParser\nscrollXParser\n cue x\n extends abstractColumnNameParser\nscrollYParser\n cue y\n extends abstractColumnNameParser\nabstractPlotLabelParser\n cueFromId\n atoms cueAtom\n catchAllAtomType stringAtom\nquoteLineParser\n popularity 0.004172\n catchAllAtomType stringAtom\n catchAllParser quoteLineParser\nscrollParser\n description Scroll is a language for scientists of all ages. Refine, share and collaborate on ideas.\n root\n inScope abstractScrollParser blankLineParser atomTypeDefinitionParser parserDefinitionParser\n catchAllParser catchAllParagraphParser\n javascript\n setFile(file) {\n this.file = file\n const date = this.get(\"date\")\n if (date) this.file.timestamp = this.dayjs(this.get(\"date\")).unix()\n return this\n }\n buildHtml(buildSettings) {\n this.sectionStack = []\n return this.filter(subparticle => subparticle.buildHtml).map(subparticle => { try {return subparticle.buildHtml(buildSettings)} catch (err) {console.error(err); return \"\"} }).filter(i => i).join(\"\\n\") + this.clearSectionStack()\n }\n sectionStack = []\n clearSectionStack() {\n const result = this.sectionStack.join(\"\\n\")\n this.sectionStack = []\n return result\n }\n bodyStack = []\n clearBodyStack() {\n const result = this.bodyStack.join(\"\")\n this.bodyStack = []\n return result\n }\n get hakonParser() {\n if (this.isNodeJs())\n return require(\"scrollsdk/products/hakon.nodejs.js\")\n return hakonParser\n }\n readSyncFromFileOrUrl(fileOrUrl) {\n if (!this.isNodeJs()) return this.getInBrowser(fileOrUrl)\n const isUrl = fileOrUrl.match(/^https?\\:[^ ]+$/)\n if (!isUrl) return this.root.readFile(fileOrUrl)\n return this.readFile(this.makeFullPath(new URL(fileOrUrl).pathname.split('/').pop()))\n }\n getInBrowser(key) {\n return localStorage.getItem(key) || (window.inMemStorage ? window.inMemStorage[key] : \"\") || \"\"\n }\n async fetch(url, filename) {\n const isUrl = url.match(/^https?\\:[^ ]+$/)\n if (!isUrl) return\n return this.isNodeJs() ? this.fetchNode(url, filename) : this.fetchBrowser(url)\n }\n get path() {\n return require(\"path\")\n }\n makeFullPath(filename) {\n return this.path.join(this.folderPath, filename)\n }\n _nextAndPrevious(arr, index) {\n const nextIndex = index + 1\n const previousIndex = index - 1\n return {\n previous: arr[previousIndex] ?? arr[arr.length - 1],\n next: arr[nextIndex] ?? arr[0]\n }\n }\n // keyboard nav is always in the same folder. does not currently support cross folder\n includeFileInKeyboardNav(file) {\n const { scrollProgram } = file\n return scrollProgram.buildsHtml && scrollProgram.hasKeyboardNav && scrollProgram.tags.includes(this.primaryTag)\n }\n get timeIndex() {\n return this.file.timeIndex || 0\n }\n get linkToPrevious() {\n if (!this.hasKeyboardNav)\n // Dont provide link to next unless keyboard nav is on\n return undefined\n const {allScrollFiles} = this\n let file = this._nextAndPrevious(allScrollFiles, this.timeIndex).previous\n while (!this.includeFileInKeyboardNav(file)) {\n file = this._nextAndPrevious(allScrollFiles, file.timeIndex).previous\n }\n return file.scrollProgram.permalink\n }\n importRegex = /^(import |[a-zA-Z\\_\\-\\.0-9\\/]+\\.(scroll|parsers)$|https?:\\/\\/.+\\.(scroll|parsers)$)/gm\n get linkToNext() {\n if (!this.hasKeyboardNav)\n // Dont provide link to next unless keyboard nav is on\n return undefined\n const {allScrollFiles} = this\n let file = this._nextAndPrevious(allScrollFiles, this.timeIndex).next\n while (!this.includeFileInKeyboardNav(file)) {\n file = this._nextAndPrevious(allScrollFiles, file.timeIndex).next\n }\n return file.scrollProgram.permalink\n }\n // todo: clean up this naming pattern and add a parser instead of special casing 404.html\n get allHtmlFiles() {\n return this.allScrollFiles.filter(file => file.scrollProgram.buildsHtml && file.scrollProgram.permalink !== \"404.html\")\n }\n parseNestedTag(tag) {\n if (!tag.includes(\"/\")) return;\n const {path} = this\n const parts = tag.split(\"/\")\n const group = parts.pop()\n const relativePath = parts.join(\"/\")\n return {\n group,\n relativePath,\n folderPath: path.join(this.folderPath, path.normalize(relativePath))\n }\n }\n getFilesByTags(tags, limit) {\n // todo: tags is currently matching partial substrings\n const getFilesWithTag = (tag, files) => files.filter(file => file.scrollProgram.buildsHtml && file.scrollProgram.tags.includes(tag))\n if (typeof tags === \"string\") tags = tags.split(\" \")\n if (!tags || !tags.length)\n return this.allHtmlFiles\n .filter(file => file !== this) // avoid infinite loops. todo: think this through better.\n .map(file => {\n return { file, relativePath: \"\" }\n })\n .slice(0, limit)\n let arr = []\n tags.forEach(tag => {\n if (!tag.includes(\"/\"))\n return (arr = arr.concat(\n getFilesWithTag(tag, this.allScrollFiles)\n .map(file => {\n return { file, relativePath: \"\" }\n })\n .slice(0, limit)\n ))\n const {folderPath, group, relativePath} = this.parseNestedTag(tag)\n let files = []\n try {\n files = this.fileSystem.getCachedLoadedFilesInFolder(folderPath, this)\n } catch (err) {\n console.error(err)\n }\n const filtered = getFilesWithTag(group, files).map(file => {\n return { file, relativePath: relativePath + \"/\" }\n })\n arr = arr.concat(filtered.slice(0, limit))\n })\n return this.lodash.sortBy(arr, file => file.file.timestamp).reverse()\n }\n async fetchNode(url, filename) {\n filename = filename || new URL(url).pathname.split('/').pop()\n const fullpath = this.makeFullPath(filename)\n if (require(\"fs\").existsSync(fullpath)) return this.readFile(fullpath)\n this.log(`🛜 fetching ${url} to ${fullpath} `)\n await this.downloadToDisk(url, fullpath)\n return this.readFile(fullpath)\n }\n log(message) {\n if (this.logger) this.logger.log(message)\n }\n async fetchBrowser(url) {\n const content = this.getInBrowser(url)\n if (content) return content\n return this.downloadToLocalStorage(url)\n }\n async downloadToDisk(url, destination) {\n const { writeFile } = require('fs').promises\n const response = await fetch(url)\n const fileBuffer = await response.arrayBuffer()\n await writeFile(destination, Buffer.from(fileBuffer))\n return this.readFile(destination)\n }\n async downloadToLocalStorage(url) {\n const response = await fetch(url)\n const blob = await response.blob()\n const text = await blob.text()\n try {\n localStorage.setItem(url, text)\n return localStorage.getItem(url)\n } catch (err) {\n if (!window.inMemStorage) window.inMemStorage = {}\n window.inMemStorage[url] = text\n console.error(err)\n return text\n }\n }\n readFile(filename) {\n const {path} = this\n const fs = require(\"fs\")\n const fullPath = path.join(this.folderPath, filename.replace(this.folderPath, \"\"))\n try {\n if (fs.existsSync(fullPath))\n return fs.readFileSync(fullPath, \"utf8\")\n console.error(`File '${filename}' not found`)\n return \"\"\n } catch (err) {\n console.error(`Error in '${this.filePath}' reading file: '${fullPath}'`)\n console.error(err)\n return \"\"\n }\n }\n alreadyRequired = new Set()\n buildHtmlSnippet(buildSettings) {\n this.sectionStack = []\n return this.map(subparticle => (subparticle.buildHtmlSnippet ? subparticle.buildHtmlSnippet(buildSettings) : subparticle.buildHtml(buildSettings)))\n .filter(i => i)\n .join(\"\\n\")\n .trim() + this.clearSectionStack()\n }\n get footnotes() {\n if (this._footnotes === undefined) this._footnotes = this.filter(particle => particle.isFootnote)\n return this._footnotes\n }\n get authors() {\n return this.get(\"authors\")\n }\n get allScrollFiles() {\n try {\n return this.fileSystem.getCachedLoadedFilesInFolder(this.folderPath, this)\n } catch (err) {\n console.error(err)\n return []\n }\n }\n async doThing(thing) {\n await Promise.all(this.filter(particle => particle[thing]).map(async particle => particle[thing]()))\n }\n async load() {\n await this.doThing(\"load\")\n }\n async execute() {\n await this.doThing(\"execute\")\n }\n file = {}\n getFromParserId(parserId) {\n return this.parserIdIndex[parserId]?.[0].content\n }\n get fileSystem() {\n return this.file.fileSystem\n }\n get filePath() {\n return this.file.filePath\n }\n get folderPath() {\n return this.file.folderPath\n }\n get filename() {\n return this.file.filename || \"\"\n }\n get hasKeyboardNav() {\n return this.has(\"keyboardNav\")\n }\n get editHtml() {\n return `<a href=\"${this.editUrl}\" class=\"abstractTextLinkParser\">Edit</a>`\n }\n get externalsPath() {\n return this.file.EXTERNALS_PATH\n }\n get endSnippetIndex() {\n // Get the line number that the snippet should stop at.\n // First if its hard coded, use that\n if (this.has(\"endSnippet\")) return this.getParticle(\"endSnippet\").index\n // Next look for a dinkus\n const snippetBreak = this.find(particle => particle.isDinkus)\n if (snippetBreak) return snippetBreak.index\n return -1\n }\n get parserIds() {\n return this.topDownArray.map(particle => particle.definition.id)\n }\n get tags() {\n return this.get(\"tags\") || \"\"\n }\n get primaryTag() {\n return this.tags.split(\" \")[0]\n }\n get filenameNoExtension() {\n return this.filename.replace(\".scroll\", \"\")\n }\n // todo: rename publishedUrl? Or something to indicate that this is only for stuff on the web (not localhost)\n // BaseUrl must be provided for RSS Feeds and OpenGraph tags to work\n get baseUrl() {\n const baseUrl = (this.get(\"baseUrl\") || \"\").replace(/\\/$/, \"\")\n return baseUrl + \"/\"\n }\n get canonicalUrl() {\n return this.get(\"canonicalUrl\") || this.baseUrl + this.permalink\n }\n get openGraphImage() {\n const openGraphImage = this.get(\"openGraphImage\")\n if (openGraphImage !== undefined) return this.ensureAbsoluteLink(openGraphImage)\n const images = this.filter(particle => particle.doesExtend(\"scrollImageParser\"))\n const hit = images.find(particle => particle.has(\"openGraph\")) || images[0]\n if (!hit) return \"\"\n return this.ensureAbsoluteLink(hit.filename)\n }\n get absoluteLink() {\n return this.ensureAbsoluteLink(this.permalink)\n }\n ensureAbsoluteLink(link) {\n if (link.includes(\"://\")) return link\n return this.baseUrl + link.replace(/^\\//, \"\")\n }\n get editUrl() {\n const editUrl = this.get(\"editUrl\")\n if (editUrl) return editUrl\n const editBaseUrl = this.get(\"editBaseUrl\")\n return (editBaseUrl ? editBaseUrl.replace(/\\/$/, \"\") + \"/\" : \"\") + this.filename\n }\n get gitRepo() {\n // given https://github.com/breck7/breckyunits.com/blob/main/four-tips-to-improve-communication.scroll\n // return https://github.com/breck7/breckyunits.com\n return this.editUrl.split(\"/\").slice(0, 5).join(\"/\")\n }\n get scrollVersion() {\n // currently manually updated\n return \"168.0.0\"\n }\n // Use the first paragraph for the description\n // todo: add a particle method version of get that gets you the first particle. (actulaly make get return array?)\n // would speed up a lot.\n get description() {\n const description = this.getFromParserId(\"openGraphDescriptionParser\")\n if (description) return description\n return this.generatedDescription\n }\n get keywords() {\n if (this.has(\"keywords\"))\n return this.get(\"keywords\")\n const tags = this.get(\"tags\")\n if (tags)\n return tags.split(\" \").join(\", \")\n return \"\"\n }\n get generatedDescription() {\n const firstParagraph = this.find(particle => particle.isArticleContent)\n return firstParagraph ? firstParagraph.originalText.substr(0, 100).replace(/[&\"<>']/g, \"\") : \"\"\n }\n get titleFromFilename() {\n const unCamelCase = str => str.replace(/([a-z])([A-Z])/g, \"$1 $2\").replace(/^./, match => match.toUpperCase())\n return unCamelCase(this.filenameNoExtension)\n }\n get title() {\n return this.getFromParserId(\"scrollTitleParser\") || this.titleFromFilename\n }\n get linkTitle() {\n return this.getFromParserId(\"scrollLinkTitleParser\") || this.title\n }\n get permalink() {\n return this.get(\"permalink\") || (this.filename ? this.filenameNoExtension + \".html\" : \"\")\n }\n compileTo(extensionCapitalized) {\n if (extensionCapitalized === \"Txt\")\n return this.asTxt\n if (extensionCapitalized === \"Html\")\n return this.asHtml\n const methodName = \"build\" + extensionCapitalized\n return this.topDownArray\n .filter(particle => particle[methodName])\n .map((particle, index) => particle[methodName](index))\n .join(\"\\n\")\n .trim()\n }\n get asTxt() {\n return (\n this.map(particle => {\n const text = particle.buildTxt ? particle.buildTxt() : \"\"\n if (text) return text + \"\\n\"\n if (!particle.getLine().length) return \"\\n\"\n return \"\"\n })\n .join(\"\")\n .replace(/<[^>]*>/g, \"\")\n .replace(/\\n\\n\\n+/g, \"\\n\\n\") // Maximum 2 newlines in a row\n .trim() + \"\\n\" // Always end in a newline, Posix style\n )\n }\n get dependencies() {\n const dependencies = this.file.dependencies?.slice() || []\n const files = this.topDownArray.filter(particle => particle.dependencies).map(particle => particle.dependencies).flat()\n return dependencies.concat(files)\n }\n get buildsHtml() {\n const { permalink } = this\n return !this.file.importOnly && (permalink.endsWith(\".html\") || permalink.endsWith(\".htm\"))\n }\n // Without specifying the language hyphenation will not work.\n get lang() {\n return this.get(\"htmlLang\") || \"en\"\n }\n _compiledHtml = \"\"\n get asHtml() {\n if (!this._compiledHtml) {\n const { permalink, buildsHtml } = this\n const content = (this.buildHtml() + this.clearBodyStack()).trim()\n // Don't add html tags to CSV feeds. A little hacky as calling a getter named _html_ to get _xml_ is not ideal. But\n // <1% of use case so might be good enough.\n const wrapWithHtmlTags = buildsHtml\n const bodyTag = this.has(\"metaTags\") ? \"\" : \"<body>\\n\"\n this._compiledHtml = wrapWithHtmlTags ? `<!DOCTYPE html>\\n<html lang=\"${this.lang}\">\\n${bodyTag}${content}\\n</body>\\n</html>` : content\n }\n return this._compiledHtml\n }\n get wordCount() {\n return this.asTxt.match(/\\b\\w+\\b/g)?.length || 0\n }\n get minutes() {\n return parseFloat((this.wordCount / 200).toFixed(1))\n }\n get date() {\n const date = this.get(\"date\") || (this.file.timestamp ? this.file.timestamp : 0)\n return this.dayjs(date).format(`MM/DD/YYYY`)\n }\n get year() {\n return parseInt(this.dayjs(this.date).format(`YYYY`))\n }\n get dayjs() {\n if (!this.isNodeJs()) return dayjs\n const lib = require(\"dayjs\")\n const relativeTime = require(\"dayjs/plugin/relativeTime\")\n lib.extend(relativeTime)\n return lib\n }\n get lodash() {\n return this.isNodeJs() ? require(\"lodash\") : lodash\n }\n get d3() {\n return this.isNodeJs() ? require('d3') : d3\n }\n getConcepts(parsed) {\n const concepts = []\n let currentConcept\n parsed.forEach(particle => {\n if (particle.isConceptDelimiter) {\n if (currentConcept) concepts.push(currentConcept)\n currentConcept = []\n }\n if (currentConcept && particle.isMeasure) currentConcept.push(particle)\n })\n if (currentConcept) concepts.push(currentConcept)\n return concepts\n }\n _formatConcepts(parsed) {\n const concepts = this.getConcepts(parsed)\n if (!concepts.length) return false\n const {lodash} = this\n // does a destructive sort in place on the parsed program\n concepts.forEach(concept => {\n let currentSection\n const newCode = lodash\n .sortBy(concept, [\"sortIndex\"])\n .map(particle => {\n let newLines = \"\"\n const section = particle.sortIndex.toString().split(\".\")[0]\n if (section !== currentSection) {\n currentSection = section\n newLines = \"\\n\"\n }\n return newLines + particle.toString()\n })\n .join(\"\\n\")\n concept.forEach((particle, index) => (index ? particle.destroy() : \"\"))\n concept[0].replaceParticle(() => newCode)\n })\n }\n get formatted() {\n return this.getFormatted(this.file.codeAtStart)\n }\n get lastCommitTime() {\n // todo: speed this up and do a proper release. also could add more metrics like this.\n if (this._lastCommitTime === undefined) {\n try {\n this._lastCommitTime = require(\"child_process\").execSync(`git log -1 --format=\"%at\" -- \"${this.filePath}\"`).toString().trim()\n } catch (err) {\n this._lastCommitTime = 0\n }\n }\n return this._lastCommitTime\n }\n getFormatted(codeAtStart = this.toString()) {\n let formatted = codeAtStart.replace(/\\r/g, \"\") // remove all carriage returns if there are any\n const parsed = new this.constructor(formatted)\n parsed.topDownArray.forEach(subparticle => {\n subparticle.format()\n const original = subparticle.getLine()\n const trimmed = original.replace(/(\\S.*?)[ \\t]*$/gm, \"$1\")\n // Trim trailing whitespace unless parser allows it\n if (original !== trimmed && !subparticle.allowTrailingWhitespace) subparticle.setLine(trimmed)\n })\n this._formatConcepts(parsed)\n let importOnlys = []\n let topMatter = []\n let allElse = []\n // Create any bindings\n parsed.forEach(particle => {\n if (particle.bindTo === \"next\") particle.binding = particle.next\n if (particle.bindTo === \"previous\") particle.binding = particle.previous\n })\n parsed.forEach(particle => {\n if (particle.getLine() === \"importOnly\") importOnlys.push(particle)\n else if (particle.isTopMatter) topMatter.push(particle)\n else allElse.push(particle)\n })\n const combined = importOnlys.concat(topMatter, allElse)\n // Move any bound particles\n combined\n .filter(particle => particle.bindTo)\n .forEach(particle => {\n // First remove the particle from its current position\n const originalIndex = combined.indexOf(particle)\n combined.splice(originalIndex, 1)\n // Then insert it at the new position\n // We need to find the binding index again after removal\n const bindingIndex = combined.indexOf(particle.binding)\n if (particle.bindTo === \"next\") combined.splice(bindingIndex, 0, particle)\n else combined.splice(bindingIndex + 1, 0, particle)\n })\n const trimmed = combined\n .map(particle => particle.toString())\n .join(\"\\n\")\n .replace(/^\\n*/, \"\") // Remove leading newlines\n .replace(/\\n\\n\\n+/g, \"\\n\\n\") // Maximum 2 newlines in a row\n .replace(/\\n+$/, \"\")\n return trimmed === \"\" ? trimmed : trimmed + \"\\n\" // End non blank Scroll files in a newline character POSIX style for better working with tools like git\n }\n get parser() {\n return this.constructor\n }\n get parsersRequiringExternals() {\n const { parser } = this\n // todo: could be cleaned up a bit\n if (!parser.parsersRequiringExternals) parser.parsersRequiringExternals = parser.cachedHandParsersProgramRoot.filter(particle => particle.copyFromExternal).map(particle => particle.atoms[0])\n return parser.parsersRequiringExternals\n }\n get Disk() { return this.isNodeJs() ? require(\"scrollsdk/products/Disk.node.js\").Disk : {}}\n async buildAll(options = {}) {\n await this.load()\n await this.buildOne(options)\n await this.buildTwo(options)\n }\n async buildOne(options) {\n await this.execute()\n const toBuild = this.filter(particle => particle.buildOne)\n for (let particle of toBuild) {\n await particle.buildOne(options)\n }\n }\n async buildTwo(options) {\n const toBuild = this.filter(particle => particle.buildTwo)\n for (let particle of toBuild) {\n await particle.buildTwo(options)\n }\n }\n get outputFileNames() {\n return this.filter(p => p.outputFileNames).map(p => p.outputFileNames).flat()\n }\n _compileArray(filename, arr) {\n const removeBlanks = data => data.map(obj => Object.fromEntries(Object.entries(obj).filter(([_, value]) => value !== \"\")))\n const parts = filename.split(\".\")\n const format = parts.pop()\n if (format === \"json\") return JSON.stringify(removeBlanks(arr), null, 2)\n if (format === \"js\") return `const ${parts[0]} = ` + JSON.stringify(removeBlanks(arr), null, 2)\n if (format === \"csv\") return this.arrayToCSV(arr)\n if (format === \"tsv\") return this.arrayToCSV(arr, \"\\t\")\n if (format === \"particles\") return particles.toString()\n return particles.toString()\n }\n levenshteinDistance(a, b) {\n const m = a.length\n const n = b.length\n const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0))\n for (let i = 0; i <= m; i++) {\n dp[i][0] = i\n }\n for (let j = 0; j <= n; j++) {\n dp[0][j] = j\n }\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1\n dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost)\n }\n }\n return dp[m][n]\n }\n makeLodashOrderByParams(str) {\n const part1 = str.split(\" \")\n const part2 = part1.map(col => (col.startsWith(\"-\") ? \"desc\" : \"asc\"))\n return [part1.map(col => col.replace(/^\\-/, \"\")), part2]\n }\n arrayToCSV(data, delimiter = \",\") {\n if (!data.length) return \"\"\n // Extract headers\n const headers = Object.keys(data[0])\n const csv = data.map(row =>\n headers\n .map(fieldName => {\n const fieldValue = row[fieldName]\n // Escape commas if the value is a string\n if (typeof fieldValue === \"string\" && fieldValue.includes(delimiter)) {\n return `\"${fieldValue.replace(/\"/g, '\"\"')}\"` // Escape double quotes and wrap in double quotes\n }\n return fieldValue\n })\n .join(delimiter)\n )\n csv.unshift(headers.join(delimiter)) // Add header row at the top\n return csv.join(\"\\n\")\n }\n compileConcepts(filename = \"csv\", sortBy = \"\") {\n const {lodash} = this\n if (!sortBy) return this._compileArray(filename, this.concepts)\n const orderBy = this.makeLodashOrderByParams(sortBy)\n return this._compileArray(filename, lodash.orderBy(this.concepts, orderBy[0], orderBy[1]))\n }\n _withStats\n get measuresWithStats() {\n if (!this._withStats) this._withStats = this.addMeasureStats(this.concepts, this.measures)\n return this._withStats\n }\n addMeasureStats(concepts, measures){\n return measures.map(measure => {\n let Type = false\n concepts.forEach(concept => {\n const value = concept[measure.Name]\n if (value === undefined || value === \"\") return\n measure.Values++\n if (!Type) {\n measure.Example = value.toString().replace(/\\n/g, \" \")\n measure.Type = typeof value\n Type = true\n }\n })\n measure.Coverage = Math.floor((100 * measure.Values) / concepts.length) + \"%\"\n return measure\n })\n }\n parseMeasures(parser) {\n if (!Particle.measureCache)\n Particle.measureCache = new Map()\n const measureCache = Particle.measureCache\n if (measureCache.get(parser)) return measureCache.get(parser)\n const {lodash} = this\n // todo: clean this up\n const getCueAtoms = rootParserProgram =>\n rootParserProgram\n .filter(particle => particle.getLine().endsWith(\"Parser\") && !particle.getLine().startsWith(\"abstract\"))\n .map(particle => particle.get(\"cue\") || particle.getLine())\n .map(line => line.replace(/Parser$/, \"\"))\n // Generate a fake program with one of every of the available parsers. Then parse it. Then we can easily access the meta data on the parsers\n const dummyProgram = new parser(\n Array.from(\n new Set(\n getCueAtoms(parser.cachedHandParsersProgramRoot) // is there a better method name than this?\n )\n ).join(\"\\n\")\n )\n // Delete any particles that are not measures\n dummyProgram.filter(particle => !particle.isMeasure).forEach(particle => particle.destroy())\n dummyProgram.forEach(particle => {\n // add nested measures\n Object.keys(particle.definition.cueMapWithDefinitions).forEach(key => particle.appendLine(key))\n })\n // Delete any nested particles that are not measures\n dummyProgram.topDownArray.filter(particle => !particle.isMeasure).forEach(particle => particle.destroy())\n const measures = dummyProgram.topDownArray.map(particle => {\n return {\n Name: particle.measureName,\n Values: 0,\n Coverage: 0,\n Question: particle.definition.description,\n Example: particle.definition.getParticle(\"example\")?.subparticlesToString() || \"\",\n Type: particle.typeForWebForms,\n Source: particle.sourceDomain,\n //Definition: parsedProgram.root.filename + \":\" + particle.lineNumber\n SortIndex: particle.sortIndex,\n IsComputed: particle.isComputed,\n IsRequired: particle.isMeasureRequired,\n IsConceptDelimiter: particle.isConceptDelimiter,\n Cue: particle.definition.get(\"cue\")\n }\n })\n measureCache.set(parser, lodash.sortBy(measures, \"SortIndex\"))\n return measureCache.get(parser)\n }\n _concepts\n get concepts() {\n if (this._concepts) return this._concepts\n this._concepts = this.parseConcepts(this, this.measures)\n return this._concepts\n }\n _measures\n get measures() {\n if (this._measures) return this._measures\n this._measures = this.parseMeasures(this.parser)\n return this._measures\n }\n parseConcepts(parsedProgram, measures){\n // Todo: might be a perf/memory/simplicity win to have a \"segment\" method in ScrollSDK, where you could\n // virtually split a Particle into multiple segments, and then query on those segments.\n // So we would \"segment\" on \"id \", and then not need to create a bunch of new objects, and the original\n // already parsed lines could then learn about/access to their respective segments.\n const conceptDelimiter = measures.filter(measure => measure.IsConceptDelimiter)[0]\n if (!conceptDelimiter) return []\n const concepts = parsedProgram.split(conceptDelimiter.Cue || conceptDelimiter.Name)\n concepts.shift() // Remove the part before \"id\"\n return concepts.map(concept => {\n const row = {}\n measures.forEach(measure => {\n const measureName = measure.Name\n const measureKey = measure.Cue || measureName.replace(/_/g, \" \")\n if (!measure.IsComputed) row[measureName] = concept.getParticle(measureKey)?.measureValue ?? \"\"\n else row[measureName] = this.computeMeasure(parsedProgram, measureName, concept, concepts)\n })\n return row\n })\n }\n computeMeasure(parsedProgram, measureName, concept, concepts){\n // note that this is currently global, assuming there wont be. name conflicts in computed measures in a single scroll\n if (!Particle.measureFnCache) Particle.measureFnCache = {}\n const measureFnCache = Particle.measureFnCache\n if (!measureFnCache[measureName]) {\n // a bit hacky but works??\n const particle = parsedProgram.appendLine(measureName)\n measureFnCache[measureName] = particle.computeValue\n particle.destroy()\n }\n return measureFnCache[measureName](concept, measureName, parsedProgram, concepts)\n }\n compileMeasures(filename = \"csv\", sortBy = \"\") {\n const withStats = this.measuresWithStats\n if (!sortBy) return this._compileArray(filename, withStats)\n const orderBy = this.makeLodashOrderByParams(sortBy)\n return this._compileArray(filename, this.lodash.orderBy(withStats, orderBy[0], orderBy[1]))\n }\n evalNodeJsMacros(value, macroMap, filePath) {\n const tempPath = filePath + \".js\"\n const {Disk} = this\n if (Disk.exists(tempPath)) throw new Error(`Failed to write/require replaceNodejs snippet since '${tempPath}' already exists.`)\n try {\n Disk.write(tempPath, value)\n const results = require(tempPath)\n Object.keys(results).forEach(key => (macroMap[key] = results[key]))\n } catch (err) {\n console.error(`Error in evalMacros in file '${filePath}'`)\n console.error(err)\n } finally {\n Disk.rm(tempPath)\n }\n }\n evalMacros(fusedFile) {\n const {fusedCode, codeAtStart, filePath} = fusedFile\n let code = fusedCode\n const absolutePath = filePath\n // note: the 2 params above are not used in this method, but may be used in user eval code. (todo: cleanup)\n const regex = /^(replace|toFooter$)/gm\n if (!regex.test(code)) return code\n const particle = new Particle(code) // todo: this can be faster. a more lightweight particle class?\n // Process macros\n const macroMap = {}\n particle\n .filter(particle => {\n const parserAtom = particle.cue\n return parserAtom === \"replace\" || parserAtom === \"replaceJs\" || parserAtom === \"replaceNodejs\"\n })\n .forEach(particle => {\n let value = particle.length ? particle.subparticlesToString() : particle.getAtomsFrom(2).join(\" \")\n const kind = particle.cue\n try {\n if (kind === \"replaceJs\") value = eval(value)\n if (this.isNodeJs() && kind === \"replaceNodejs\")\n this.evalNodeJsMacros(value, macroMap, absolutePath)\n else macroMap[particle.getAtom(1)] = value\n } catch (err) {\n console.error(err)\n }\n particle.destroy() // Destroy definitions after eval\n })\n if (particle.has(\"toFooter\")) {\n const pushes = particle.getParticles(\"toFooter\")\n const append = pushes.map(push => push.section.join(\"\\n\")).join(\"\\n\")\n pushes.forEach(push => {\n push.section.forEach(particle => particle.destroy())\n push.destroy()\n })\n code = particle.asString + append\n }\n const keys = Object.keys(macroMap)\n if (!keys.length) return code\n let codeAfterMacroSubstitution = particle.asString\n // Todo: speed up. build a template?\n Object.keys(macroMap).forEach(key => (codeAfterMacroSubstitution = codeAfterMacroSubstitution.replace(new RegExp(key, \"g\"), macroMap[key])))\n return codeAfterMacroSubstitution\n }\n toRss() {\n const { title, canonicalUrl } = this\n return ` <item>\n <title>${title}</title>\n <link>${canonicalUrl}</link>\n <pubDate>${this.dayjs(this.timestamp * 1000).format(\"ddd, DD MMM YYYY HH:mm:ss ZZ\")}</pubDate>\n </item>`\n }\n example\n # Hello world\n ## This is Scroll\n * It compiles to HTML.\n \n code\n // You can add code as well.\n print(\"Hello world\")\nstampFileParser\n catchAllAtomType stringAtom\n description Create a file.\n javascript\n execute(parentDir) {\n const fs = require(\"fs\")\n const path = require(\"path\")\n const fullPath = path.join(parentDir, this.getLine())\n this.root.log(`Creating file ${fullPath}`)\n fs.mkdirSync(path.dirname(fullPath), {recursive: true})\n const content = this.subparticlesToString()\n fs.writeFileSync(fullPath, content, \"utf8\")\n const isExecutable = content.startsWith(\"#!\")\n if (isExecutable) fs.chmodSync(fullPath, \"755\")\n }\nstampFolderParser\n catchAllAtomType stringAtom\n description Create a folder.\n inScope stampFolderParser\n catchAllParser stampFileParser\n pattern \\/$\n javascript\n execute(parentDir) {\n const fs = require(\"fs\")\n const path = require(\"path\")\n const newPath = path.join(parentDir, this.getLine())\n this.root.log(`Creating folder ${newPath}`)\n fs.mkdirSync(newPath, {recursive: true})\n this.forEach(particle => particle.execute(newPath))\n }\nstumpContentParser\n popularity 0.102322\n catchAllAtomType codeAtom\nscrollTableDataParser\n popularity 0.001061\n cue data\n atoms cueAtom\n description Table from inline delimited data.\n baseParser blobParser\nscrollTableDelimiterParser\n popularity 0.001037\n description Set the delimiter.\n cue delimiter\n atoms cueAtom stringAtom\n javascript\n buildHtml() {\n return \"\"\n }\nplainTextLineParser\n popularity 0.000121\n catchAllAtomType stringAtom\n catchAllParser plainTextLineParser"} \ No newline at end of file +const AppConstants = {"parsers":"columnNameAtom\n paint constant\nnewColumnNameAtom\n description Name a derived column.\n paint variable\nconstantAtom\n paint constant\npercentAtom\n paint constant.numeric.float\n extends stringAtom\n // todo: this currently extends from stringAtom b/c scrollsdk needs to be fixed. seems like if extending from number then the hard coded number typescript regex takes precedence over a custom regex\ncountAtom\n extends integerAtom\nyearAtom\n extends integerAtom\npreBuildCommandAtom\n extends cueAtom\n description Give build command atoms their own color.\n paint constant.character.escape\ndelimiterAtom\n description String to use as a delimiter.\n paint string\nbulletPointAtom\n description Any token used as a bullet point such as \"-\" or \"1.\" or \">\"\n paint keyword\ncomparisonAtom\n enum < > <= >= = != includes doesNotInclude empty notEmpty startsWith endsWith\n paint constant\npersonNameAtom\n extends stringAtom\nurlAtom\n paint constant.language\nabsoluteUrlAtom\n paint constant.language\n regex (ftp|https?)://.+\nemailAddressAtom\n extends stringAtom\n paint constant.language\npermalinkAtom\n paint string\n description A string that doesn't contain characters that might interfere with most filesystems. No slashes, for instance.\nfilePathAtom\n paint constant.language\ntagOrUrlAtom\n description An HTML tag or a url.\n paint constant.language\nhtmlAttributesAtom\n paint constant\nhtmlTagAtom\n paint constant.language\n enum div span p a img ul ol li h1 h2 h3 h4 h5 h6 header nav section article aside main footer input button form label select option textarea table tr td th tbody thead tfoot br hr meta link script style title code\nhtmlTypeAtom\n extends stringAtom\n paint constant.language\n enum text password email number tel url search date time datetime-local week month color checkbox radio file submit reset button hidden range\n description HTML input type attribute values.\nclassNameAtom\n paint constant\nhtmlIdAtom\n paint constant\nfontFamilyAtom\n enum Arial Helvetica Verdana Georgia Impact Tahoma Slim\n paint constant\njavascriptAnyAtom\n extends codeAtom\nhtmlAnyAtom\n extends codeAtom\ncolorAtom\n extends codeAtom\nnamedColorAtom\n extends colorAtom\n enum aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkkhaki darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray darkturquoise darkviolet deeppink deepskyblue dimgray dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow honeydew hotpink indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgoldenrodyellow lightgray lightgreen lightpink lightsalmon lightseagreen lightskyblue lightslategray lightsteelblue lightyellow lime limegreen linen magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell sienna silver skyblue slateblue slategray snow springgreen steelblue tan teal thistle tomato turquoise violet wheat white whitesmoke yellow yellowgreen\nbuildCommandAtom\n extends cueAtom\n description Give build command atoms their own color.\n paint constant\ncssAnyAtom\n extends codeAtom\ncssLengthAtom\n extends codeAtom\nreductionTypeAtom\n enum sum mean max min concat first\n paint keyword\ninlineMarkupNameAtom\n description Options to turn on some inline markups.\n enum bold italics code katex none\ntileOptionAtom\n enum default light\nmeasureNameAtom\n extends cueAtom\n // A regex for column names for max compatibility with a broad range of data science tools:\n regex [a-zA-Z][a-zA-Z0-9]*\nabstractConstantAtom\n paint entity.name.tag\njavascriptSafeAlphaNumericIdentifierAtom\n regex [a-zA-Z0-9_]+\n reservedAtoms enum extends function static if while export return class for default require var let const new\nanyAtom\nbaseParsersAtom\n description There are a few classes of special parsers. BlobParsers don't have their subparticles parsed. Error particles always report an error.\n // todo Remove?\n enum blobParser errorParser\n paint variable.parameter\nenumAtom\n paint constant.language\nbooleanAtom\n enum true false\n extends enumAtom\natomParserAtom\n enum prefix postfix omnifix\n paint constant.numeric\natomPropertyNameAtom\n paint variable.parameter\natomTypeIdAtom\n examples integerAtom cueAtom someCustomAtom\n extends javascriptSafeAlphaNumericIdentifierAtom\n enumFromAtomTypes atomTypeIdAtom\n paint storage\nconstantIdentifierAtom\n examples someId myVar\n // todo Extend javascriptSafeAlphaNumericIdentifier\n regex [a-zA-Z]\\w+\n paint constant.other\n description A atom that can be assigned to the parser in the target language.\nconstructorFilePathAtom\nenumOptionAtom\n // todo Add an enumOption top level type, so we can add data to an enum option such as a description.\n paint string\natomExampleAtom\n description Holds an example for a atom with a wide range of options.\n paint string\nextraAtom\n paint invalid\nfileExtensionAtom\n examples js txt doc exe\n regex [a-zA-Z0-9]+\n paint string\nnumberAtom\n paint constant.numeric\nfloatAtom\n extends numberAtom\n regex \\-?[0-9]*\\.?[0-9]*\n paint constant.numeric.float\nintegerAtom\n regex \\-?[0-9]+\n extends numberAtom\n paint constant.numeric.integer\ncueAtom\n description A atom that indicates a certain parser to use.\n paint keyword\njavascriptCodeAtom\nlowercaseAtom\n regex [a-z]+\nparserIdAtom\n examples commentParser addParser\n description This doubles as the class name in Javascript. If this begins with `abstract`, then the parser will be considered an abstract parser, which cannot be used by itself but provides common functionality to parsers that extend it.\n paint variable.parameter\n extends javascriptSafeAlphaNumericIdentifierAtom\n enumFromAtomTypes parserIdAtom\ncueAtom\n paint constant.language\nregexAtom\n paint string.regexp\nreservedAtomAtom\n description A atom that a atom cannot contain.\n paint string\npaintTypeAtom\n enum comment comment.block comment.block.documentation comment.line constant constant.character.escape constant.language constant.numeric constant.numeric.complex constant.numeric.complex.imaginary constant.numeric.complex.real constant.numeric.float constant.numeric.float.binary constant.numeric.float.decimal constant.numeric.float.hexadecimal constant.numeric.float.octal constant.numeric.float.other constant.numeric.integer constant.numeric.integer.binary constant.numeric.integer.decimal constant.numeric.integer.hexadecimal constant.numeric.integer.octal constant.numeric.integer.other constant.other constant.other.placeholder entity entity.name entity.name.class entity.name.class.forward-decl entity.name.constant entity.name.enum entity.name.function entity.name.function.constructor entity.name.function.destructor entity.name.impl entity.name.interface entity.name.label entity.name.namespace entity.name.section entity.name.struct entity.name.tag entity.name.trait entity.name.type entity.name.union entity.other.attribute-name entity.other.inherited-class invalid invalid.deprecated invalid.illegal keyword keyword.control keyword.control.conditional keyword.control.import keyword.declaration keyword.operator keyword.operator.arithmetic keyword.operator.assignment keyword.operator.bitwise keyword.operator.logical keyword.operator.atom keyword.other markup markup.bold markup.deleted markup.heading markup.inserted markup.italic markup.list.numbered markup.list.unnumbered markup.other markup.quote markup.raw.block markup.raw.inline markup.underline markup.underline.link meta meta.annotation meta.annotation.identifier meta.annotation.parameters meta.block meta.braces meta.brackets meta.class meta.enum meta.function meta.function-call meta.function.parameters meta.function.return-type meta.generic meta.group meta.impl meta.interface meta.interpolation meta.namespace meta.paragraph meta.parens meta.path meta.preprocessor meta.string meta.struct meta.tag meta.toc-list meta.trait meta.type meta.union punctuation punctuation.accessor punctuation.definition.annotation punctuation.definition.comment punctuation.definition.generic.begin punctuation.definition.generic.end punctuation.definition.keyword punctuation.definition.string.begin punctuation.definition.string.end punctuation.definition.variable punctuation.section.block.begin punctuation.section.block.end punctuation.section.braces.begin punctuation.section.braces.end punctuation.section.brackets.begin punctuation.section.brackets.end punctuation.section.group.begin punctuation.section.group.end punctuation.section.interpolation.begin punctuation.section.interpolation.end punctuation.section.parens.begin punctuation.section.parens.end punctuation.separator punctuation.separator.continuation punctuation.terminator source source.language-suffix.embedded storage storage.modifier storage.type storage.type keyword.declaration.type storage.type.class keyword.declaration.class storage.type.enum keyword.declaration.enum storage.type.function keyword.declaration.function storage.type.impl keyword.declaration.impl storage.type.interface keyword.declaration.interface storage.type.struct keyword.declaration.struct storage.type.trait keyword.declaration.trait storage.type.union keyword.declaration.union string string.quoted.double string.quoted.other string.quoted.single string.quoted.triple string.regexp string.unquoted support support.class support.constant support.function support.module support.type text text.html text.xml variable variable.annotation variable.function variable.language variable.other variable.other.constant variable.other.member variable.other.readwrite variable.parameter\n paint string\nscriptUrlAtom\nsemanticVersionAtom\n examples 1.0.0 2.2.1\n regex [0-9]+\\.[0-9]+\\.[0-9]+\n paint constant.numeric\ndateAtom\n paint string\nstringAtom\n paint string\natomAtom\n paint constant\n description A non-empty single atom string.\n regex .+\nexampleAnyAtom\n examples lorem ipsem\n // todo Eventually we want to be able to parse correctly the examples.\n paint comment\n extends stringAtom\nblankAtom\ncommentAtom\n paint comment\ncodeAtom\n paint comment\ncolumnNameOrColorAtom\n extends columnNameAtom\nmetaCommandAtom\n extends cueAtom\n description Give meta command atoms their own color.\n paint constant.numeric\n // Obviously this is not numeric. But I like the green color for now.\n We need a better design to replace this \"paint\" concept\n https://github.com/breck7/scrollsdk/issues/186\nvegaDataSetAtom\n paint constant.numeric\n enum airports.csv anscombe.json barley.json birdstrikes.json budget.json budgets.json burtin.json cars.json climate.json co2-concentration.csv countries.json crimea.json descriptions.json disasters.csv driving.json earthquakes.json flare-dependencies.json flare.json flights-10k.json flights-200k.json flights-20k.json flights-2k.json flights-3m.csv flights-5k.json flights-airport.csv gapminder-health-income.csv gapminder.json github.csv graticule.json income.json iowa-electricity.csv iris.json jobs.json la-riots.csv londonBoroughs.json londonCentroids.json londonTubeLines.json lookup_groups.csv lookup_people.csv miserables.json monarchs.json movies.json normal-2d.json obesity.json points.json population.json population_engineers_hurricanes.csv seattle-temps.csv seattle-weather.csv sf-temps.csv sp500.csv stocks.csv udistrict.json unemployment-across-industries.json unemployment.tsv us-10m.json us-employment.csv us-state-capitals.json weather.csv weather.json weball26.json wheat.json windvectors.csv world-110m.json zipcodes.csv\ntagAtom\n extends permalinkAtom\ntagWithOptionalFolderAtom\n description A group name optionally combined with a folder path. Only used when referencing tags, not in posts.\n extends stringAtom\nscrollThemeAtom\n enum roboto gazette dark tufte prestige\n paint constant\nabstractScrollParser\n atoms cueAtom\n javascript\n buildHtmlSnippet(buildSettings) {\n return this.buildHtml(buildSettings)\n }\n buildTxt() {\n return \"\"\n }\n getHtmlRequirements(buildSettings) {\n const {requireOnce} = this\n if (!requireOnce)\n return \"\"\n const set = buildSettings?.alreadyRequired || this.root.alreadyRequired\n if (set.has(requireOnce))\n return \"\"\n set.add(requireOnce)\n return requireOnce + \"\\n\\n\"\n }\nabstractAftertextParser\n description Text followed by markup commands.\n extends abstractScrollParser\n inScope abstractAftertextDirectiveParser abstractAftertextAttributeParser aftertextTagParser abstractCommentParser\n javascript\n get markupInserts() {\n const { originalTextPostLinkify } = this\n return this.filter(particle => particle.isMarkup)\n .map(particle => particle.getInserts(originalTextPostLinkify))\n .filter(i => i)\n .flat()\n }\n get originalText() {\n return this.content ?? \"\"\n }\n get originalTextPostLinkify() {\n const { originalText } = this\n const shouldLinkify = this.get(\"linkify\") === \"false\" || originalText.includes(\"<a \") ? false : true\n return shouldLinkify ? this.replaceNotes(Utils.linkify(originalText)) : originalText\n }\n replaceNotes(originalText) {\n // Skip the replacements if there are no footnotes or the text has none.\n if (!this.root.footnotes.length || !originalText.includes(\"^\")) return originalText\n this.root.footnotes.forEach((note, index) => {\n const needle = note.cue\n const {linkBack} = note\n if (originalText.includes(needle)) originalText = originalText.replace(new RegExp(\"\\\\\" + needle + \"\\\\b\"), `<a href=\"#${note.htmlId}\" class=\"scrollNoteLink\" id=\"${linkBack}\"><sup>${note.label}</sup></a>`)\n })\n return originalText\n }\n get text() {\n const { originalTextPostLinkify, markupInserts } = this\n let adjustment = 0\n let newText = originalTextPostLinkify\n markupInserts.sort((a, b) => {\n if (a.index !== b.index)\n return a.index - b.index\n // If multiple tags start at same index, the tag that closes first should start last. Otherwise HTML breaks.\n if (b.index === b.endIndex) // unless the endIndex is the same as index\n return a.endIndex - b.endIndex\n return b.endIndex - a.endIndex\n })\n markupInserts.forEach(insertion => {\n insertion.index += adjustment\n const consumeStartCharacters = insertion.consumeStartCharacters ?? 0\n const consumeEndCharacters = insertion.consumeEndCharacters ?? 0\n newText = newText.slice(0, insertion.index - consumeEndCharacters) + insertion.string + newText.slice(insertion.index + consumeStartCharacters)\n adjustment += insertion.string.length - consumeEndCharacters - consumeStartCharacters\n })\n return newText\n }\n tag = \"p\"\n get className() {\n if (this.get(\"class\"))\n return this.get(\"class\")\n const classLine = this.getParticle(\"addClass\")\n if (classLine && classLine.applyToParentElement) return classLine.content\n return this.defaultClassName\n }\n defaultClassName = \"scrollParagraph\"\n get isHidden() {\n return this.has(\"hidden\")\n }\n buildHtml(buildSettings) {\n if (this.isHidden) return \"\"\n this.buildSettings = buildSettings\n const { className, styles } = this\n const classAttr = className ? `class=\"${this.className}\"` : \"\"\n const selfClose = this.isSelfClosing ? \" /\" : \"\"\n const tag = this.get(\"tag\") || this.tag\n if (tag === \"none\") // Allow no tag for aftertext in tables\n return this.text\n const id = this.has(\"id\") ? \"\" : `id=\"${this.htmlId}\" ` // always add an html id\n return this.getHtmlRequirements(buildSettings) + `<${tag} ${id}${this.htmlAttributes}${classAttr}${styles}${selfClose}>${this.htmlContents}${this.closingTag}`\n }\n get htmlContents() {\n return this.text\n }\n get closingTag() {\n if (this.isSelfClosing) return \"\"\n const tag = this.get(\"tag\") || this.tag\n return `</${tag}>`\n }\n get htmlAttributes() {\n const attrs = this.filter(particle => particle.isAttribute)\n return attrs.length ? attrs.map(particle => particle.htmlAttributes).join(\" \") + \" \" : \"\"\n }\n get styles() {\n const style = this.getParticle(\"style\")\n const fontFamily = this.getParticle(\"font\")\n const color = this.getParticle(\"color\")\n if (!style && !fontFamily && !color)\n return \"\"\n return ` style=\"${style?.content};${fontFamily?.css};${color?.css}\"`\n }\n get htmlId() {\n return this.get(\"id\") || \"particle\" + this.index\n }\nscrollParagraphParser\n // todo Perhaps rewrite this from scratch and move out of aftertext.\n extends abstractAftertextParser\n catchAllAtomType stringAtom\n description A paragraph.\n boolean suggestInAutocomplete false\n cueFromId\n javascript\n buildHtml(buildSettings) {\n if (this.isHidden) return \"\"\n // Hacky, I know.\n const newLine = this.has(\"inlineMarkupsOn\") ? undefined : this.appendLine(\"inlineMarkupsOn\")\n const compiled = super.buildHtml(buildSettings)\n if (newLine)\n newLine.destroy()\n return compiled\n }\n buildTxt() {\n const subparticles = this.filter(particle => particle.buildTxt).map(particle => particle.buildTxt()).filter(i => i).join(\"\\n\")\n const dateline = this.getParticle(\"dateline\")\n return (dateline ? dateline.day + \"\\n\\n\" : \"\") + (this.originalText || \"\") + (subparticles ? \"\\n \" + subparticles.replace(/\\n/g, \"\\n \") : \"\")\n }\nauthorsParser\n popularity 0.007379\n // multiple authors delimited by \" and \"\n boolean isPopular true\n extends scrollParagraphParser\n description Set author(s) name(s).\n example\n authors Breck Yunits\n https://breckyunits.com Breck Yunits\n // note: once we have mixins in Parsers, lets mixin the below from abstractTopLevelSingleMetaParser\n atoms metaCommandAtom\n javascript\n isTopMatter = true\n isSetterParser = true\n buildHtmlForPrint() {\n // hacky. todo: cleanup\n const originalContent = this.content\n this.setContent(`by ${originalContent}`)\n const html = super.buildHtml()\n this.setContent(originalContent)\n return html\n }\n buildTxtForPrint() {\n return 'by ' + super.buildTxt()\n }\n buildHtml() {\n return \"\"\n }\n buildTxt() {\n return \"\"\n }\n defaultClassName = \"printAuthorsParser\"\nblinkParser\n description Just for fun.\n extends scrollParagraphParser\n example\n blink Carpe diem!\n cue blink\n javascript\n buildHtml() {\n return `<span class=\"scrollBlink\">${super.buildHtml()}</span>\n <script>setInterval(()=>{ Array.from(document.getElementsByClassName(\"scrollBlink\")).forEach(el => el.style.visibility = el.style.visibility === \"hidden\" ? \"visible\" : \"hidden\") }, 500)</script>`\n }\nscrollButtonParser\n extends scrollParagraphParser\n cueFromId\n description A button.\n postParser\n description Post a particle.\n example\n scrollButton Click me\n javascript\n defaultClassName = \"scrollButton\"\n tag = \"button\"\n get htmlAttributes() {\n const link = this.getFromParser(\"scrollLinkParser\")\n const post = this.getParticle(\"post\")\n if (post) {\n const method = \"post\"\n const action = link?.link || \"\"\n const formData = new URLSearchParams({particle: post.subparticlesToString()}).toString()\n return ` onclick=\"fetch('${action}', {method: '${method}', body: '${formData}', headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).then(async (message) => {const el = document.createElement('div'); el.textContent = await message.text(); this.insertAdjacentElement('afterend', el);}); return false;\" `\n }\n return super.htmlAttributes + (link ? `onclick=\"window.location='${link.link}'\"` : \"\")\n }\n getFromParser(parserId) {\n return this.find(particle => particle.doesExtend(parserId))\n }\ncatchAllParagraphParser\n popularity 0.115562\n description A paragraph.\n extends scrollParagraphParser\n boolean suggestInAutocomplete false\n boolean isPopular true\n boolean isArticleContent true\n atoms stringAtom\n javascript\n getErrors() {\n const errors = super.getErrors() || []\n return this.parent.has(\"testStrict\") ? errors.concat(this.makeError(`catchAllParagraphParser should not have any matches when testing with testStrict.`)) : errors\n }\n get originalText() {\n return this.getLine() || \"\"\n }\nscrollCenterParser\n popularity 0.006415\n cue center\n description A centered section.\n extends scrollParagraphParser\n example\n center\n This paragraph is centered.\n javascript\n buildHtml() {\n this.parent.sectionStack.push(\"</center>\")\n return `<center>${super.buildHtml()}`\n }\n buildTxt() {\n return this.content\n }\nabstractIndentableParagraphParser\n extends scrollParagraphParser\n inScope abstractAftertextDirectiveParser abstractAftertextAttributeParser abstractIndentableParagraphParser scrollParagraphParser\n javascript\n get htmlContents() {\n return this.text + this.map(particle => particle.buildHtml())\n .join(\"\\n\")\n .trim()\n }\n buildTxt() {\n return this.getAtom(0) + \" \" + super.buildTxt()\n }\nchecklistTodoParser\n popularity 0.000193\n extends abstractIndentableParagraphParser\n example\n [] Get milk\n description A task todo.\n cue []\n string checked \n javascript\n get text() {\n return `<div style=\"text-indent:${(this.getIndentLevel() - 1) * 20}px;\"><input type=\"checkbox\" ${this.checked} id=\"${this.id}\"><label for=\"${this.id}\">` + super.text + `</label></div>`\n }\n get id() {\n return this.get(\"id\") || \"item\" + this._getUid()\n }\nchecklistDoneParser\n popularity 0.000072\n extends checklistTodoParser\n description A completed task.\n string checked checked\n cue [x]\n example\n [x] get milk\nscrollDivParser\n popularity 0.007524\n description HTML div tag.\n extends abstractIndentableParagraphParser\n cue div\n example\n div\n # Hello world\n p This is a test\n div\n # Deeper\n javascript\n tag = \"div\"\nabstractHtmlElementParser\n extends abstractIndentableParagraphParser\n javascript\n defaultClassName = \"\"\nhtmlSectionParser\n description HTML section tag.\n extends abstractHtmlElementParser\n cue section\n example\n section\n # Hello world\n p This is a test\n section\n # Deeper\n javascript\n tag = \"section\"\nhtmlHeaderParser\n description HTML header tag.\n extends abstractHtmlElementParser\n cue header\n example\n header\n # Title\n javascript\n tag = \"header\"\nhtmlFooterParser\n description HTML footer tag.\n extends abstractHtmlElementParser\n cue footer\n example\n footer\n p Made with love\n javascript\n tag = \"footer\"\nhtmlAsideParser\n description HTML aside tag.\n extends abstractHtmlElementParser\n cue aside\n example\n aside\n h1 Some notes\n javascript\n tag = \"aside\"\nhtmlArticleParser\n description HTML article tag.\n extends abstractHtmlElementParser\n cue article\n example\n article\n h1 My article\n javascript\n tag = \"article\"\nhtmlMainParser\n description HTML main tag.\n extends abstractHtmlElementParser\n cue main\n example\n main\n # Title\n javascript\n tag = \"main\"\nhtmlNavParser\n description HTML nav tag.\n extends abstractHtmlElementParser\n cue nav\n example\n nav\n a Home\n href /\n javascript\n tag = \"nav\"\nhtmlPreParser\n description HTML pre tag.\n extends abstractHtmlElementParser\n cue pre\n example\n pre\n javascript\n tag = \"pre\"\nhtmlUlParser\n description HTML ul tag.\n extends abstractHtmlElementParser\n cue ul\n example\n ul\n li A list\n javascript\n tag = \"ul\"\nhtmlOlParser\n description HTML ol tag.\n extends abstractHtmlElementParser\n cue ol\n example\n ol\n li A list\n javascript\n tag = \"ol\"\nhtmlLiParser\n description HTML li tag.\n extends abstractHtmlElementParser\n cue li\n example\n ol\n li A list\n javascript\n tag = \"li\"\nhtmlImgParser\n description HTML img tag.\n extends abstractHtmlElementParser\n cue img\n example\n img foo.png\n javascript\n tag = \"img\"\n isSelfClosing = true\nhtmlAParser\n description HTML a tag.\n extends abstractHtmlElementParser\n cue a\n example\n a Home\n href /\n javascript\n tag = \"a\"\nhtmlFormParser\n description HTML form tag.\n extends abstractHtmlElementParser\n cue form\n example\n form\n input\n javascript\n tag = \"form\"\nhtmlInputParser\n description HTML input tag.\n extends abstractHtmlElementParser\n cue input\n example\n input\n type text\n placeholder Enter your name\n javascript\n tag = \"input\"\n isSelfClosing = true\nhtmlSelectParser\n description HTML select tag.\n extends abstractHtmlElementParser\n cue select\n example\n select\n option Value 1\n option Value 2\n javascript\n tag = \"select\"\nhtmlOptionParser\n description HTML option tag.\n extends abstractHtmlElementParser\n cue option\n example\n select\n option Choose an option\n option First Option\n javascript\n tag = \"option\"\nhtmlTextareaParser\n description HTML textarea tag.\n extends abstractHtmlElementParser\n cue textarea\n example\n textarea\n placeholder Enter your message\n rows 4\n javascript\n tag = \"textarea\"\nhtmlButtonParser\n description HTML button tag.\n extends abstractHtmlElementParser\n cue button\n example\n button Submit\n type submit\n javascript\n tag = \"button\"\nhtmlLabelParser\n description HTML label tag.\n extends abstractHtmlElementParser\n cue label\n example\n label Name\n for username\n javascript\n tag = \"label\"\nhtmlSpanParser\n description HTML span tag.\n extends abstractHtmlElementParser\n cue span\n example\n span Hello\n javascript\n tag = \"span\"\nhtmlCanvasParser\n description HTML canvas tag.\n extends abstractHtmlElementParser\n cue canvas\n example\n canvas\n javascript\n tag = \"canvas\"\nhtmlIframeParser\n description HTML iframe tag.\n extends abstractHtmlElementParser\n cue iframe\n example\n iframe\n javascript\n tag = \"iframe\"\nh1LiteralParser\n description HTML h1 tag.\n extends abstractHtmlElementParser\n cue h1\n example\n main\n h1 Title\n javascript\n tag = \"h1\"\nh2LiteralParser\n description HTML h2 tag.\n extends abstractHtmlElementParser\n cue h2\n example\n main\n h2 Title\n javascript\n tag = \"h2\"\nh3LiteralParser\n description HTML h3 tag.\n extends abstractHtmlElementParser\n cue h3\n example\n main\n h3 Title\n javascript\n tag = \"h3\"\nh4LiteralParser\n description HTML h4 tag.\n extends abstractHtmlElementParser\n cue h4\n example\n main\n h4 Title\n javascript\n tag = \"h4\"\nhtmlMetaTagParser\n description HTML meta tag.\n extends abstractHtmlElementParser\n cue meta\n example\n meta\n name description\n content A great page about meta tags\n javascript\n tag = \"meta\"\n isSelfClosing = true\nlistAftertextParser\n popularity 0.014325\n extends abstractIndentableParagraphParser\n example\n - I had a _new_ thought.\n description A list item.\n cue -\n javascript\n defaultClassName = \"\"\n buildHtml() {\n const {index, parent} = this\n const particleClass = this.constructor\n const isStartOfList = index === 0 || !(parent.particleAt(index - 1) instanceof particleClass)\n const isEndOfList = parent.length === index + 1 || !(parent.particleAt(index + 1) instanceof particleClass)\n const { listType } = this\n return (isStartOfList ? `<${listType} ${this.attributes}>` : \"\") + `${super.buildHtml()}` + (isEndOfList ? `</${listType}>` : \"\")\n }\n get attributes() {\n return \"\"\n }\n tag = \"li\"\n listType = \"ul\"\nabstractCustomListItemParser\n extends listAftertextParser\n javascript\n get requireOnce() {\n return `<style>\\n.${this.constructor.name} li::marker {content: \"${this.cue} \";}\\n</style>`\n }\n get attributes() {\n return `class=\"${this.constructor.name}\"`\n }\norderedListAftertextParser\n popularity 0.004485\n extends listAftertextParser\n description A list item.\n example\n 1. Hello world\n pattern ^\\d+\\. \n javascript\n listType = \"ol\"\n get attributes() { return ` start=\"${this.getAtom(0)}\"`}\npParagraphParser\n popularity 0.001881\n cue p\n extends abstractIndentableParagraphParser\n description A paragraph.\n boolean isArticleContent true\n example\n p I had a _new_ idea.\nquickQuoteParser\n popularity 0.000482\n cue >\n example\n > The only thing we have to fear is fear itself. - FDR\n boolean isPopular true\n extends abstractIndentableParagraphParser\n description A quote.\n javascript\n defaultClassName = \"scrollQuote\"\n tag = \"blockquote\"\nscrollCounterParser\n description Visualize the speed of something.\n extends scrollParagraphParser\n cue counter\n example\n counter 4.5 Babies Born\n atoms cueAtom numberAtom\n javascript\n buildHtml() {\n const line = this.getLine()\n const atoms = line.split(\" \")\n atoms.shift() // drop the counter atom\n const perSecond = parseFloat(atoms.shift()) // get number\n const increment = perSecond/10\n const id = this._getUid()\n this.setLine(`* <span id=\"counter${id}\" title=\"0\">0</span><script>setInterval(()=>{ const el = document.getElementById('counter${id}'); el.title = parseFloat(el.title) + ${increment}; el.textContent = Math.floor(parseFloat(el.title)).toLocaleString()}, 100)</script> ` + atoms.join(\" \"))\n const html = super.buildHtml()\n this.setLine(line)\n return html\n }\nexpanderParser\n popularity 0.000072\n cueFromId\n description An collapsible HTML details tag.\n extends scrollParagraphParser\n example\n expander Knock Knock\n Who's there?\n javascript\n buildHtml() {\n this.parent.sectionStack.push(\"</details>\")\n return `<details>${super.buildHtml()}`\n }\n buildTxt() {\n return this.content\n }\n tag = \"summary\"\n defaultClassName = \"\"\nfootnoteDefinitionParser\n popularity 0.001953\n description A footnote. Can also be used as section notes.\n extends scrollParagraphParser\n boolean isFootnote true\n pattern ^\\^.+$\n // We need to quickLinks back in scope because there is currently a bug in ScrollSDK/parsers where if a parser extending a parent class has a child parser defined, then any regex parsers in the parent class will not be tested unless explicitly included in scope again.\n inScope quickLinkParser\n labelParser\n description If you want to show a custom label for a footnote. Default label is the note definition index.\n cueFromId\n atoms cueAtom\n catchAllAtomType stringAtom\n javascript\n get htmlId() {\n return `note${this.noteDefinitionIndex}`\n }\n get label() {\n // In the future we could allow common practices like author name\n return this.get(\"label\") || `[${this.noteDefinitionIndex}]`\n }\n get linkBack() {\n return `noteUsage${this.noteDefinitionIndex}`\n }\n get text() {\n return `<a class=\"scrollFootNoteUsageLink\" href=\"#noteUsage${this.noteDefinitionIndex}\">${this.label}</a> ${super.text}`\n }\n get noteDefinitionIndex() {\n return this.parent.footnotes.indexOf(this) + 1\n }\n buildTxt() {\n return this.getAtom(0) + \": \" + super.buildTxt()\n }\nabstractHeaderParser\n extends scrollParagraphParser\n example\n # Hello world\n javascript\n buildHtml(buildSettings) {\n if (this.isHidden) return \"\"\n if (this.parent.sectionStack)\n this.parent.sectionStack.push(\"</div>\")\n return `<div class=\"scrollSection\">` + super.buildHtml(buildSettings)\n }\n buildTxt() {\n const line = super.buildTxt()\n return line + \"\\n\" + \"=\".repeat(line.length)\n }\n isHeader = true\nh1Parser\n popularity 0.017918\n description An html h1 tag.\n extends abstractHeaderParser\n example\n # Hello world\n boolean isArticleContent true\n cue #\n boolean isPopular true\n javascript\n tag = \"h1\"\nh2Parser\n popularity 0.005257\n description An html h2 tag.\n extends abstractHeaderParser\n example\n ## Hello world\n boolean isArticleContent true\n cue ##\n boolean isPopular true\n javascript\n tag = \"h2\"\nh3Parser\n popularity 0.001085\n description An html h3 tag.\n extends abstractHeaderParser\n example\n ### Hello world\n boolean isArticleContent true\n cue ###\n javascript\n tag = \"h3\"\nh4Parser\n popularity 0.000289\n description An html h4 tag.\n example\n #### Hello world\n extends abstractHeaderParser\n cue ####\n javascript\n tag = \"h4\"\nscrollQuestionParser\n popularity 0.004244\n description A question.\n extends h4Parser\n cue ?\n example\n ? Why is the sky blue?\n javascript\n defaultClassName = \"scrollQuestion\"\nh5Parser\n description An html h5 tag.\n extends abstractHeaderParser\n example\n ##### Hello world\n cue #####\n javascript\n tag = \"h5\"\nprintTitleParser\n popularity 0.007572\n description Print title.\n extends abstractHeaderParser\n boolean isPopular true\n example\n title Eureka\n printTitle\n cueFromId\n javascript\n buildHtml(buildSettings) {\n // Hacky, I know.\n const {content} = this\n if (content === undefined)\n this.setContent(this.root.title)\n const { permalink } = this.root\n if (!permalink) {\n this.setContent(content) // Restore it as it was.\n return super.buildHtml(buildSettings)\n }\n const newLine = this.appendLine(`link ${permalink}`)\n const compiled = super.buildHtml(buildSettings)\n newLine.destroy()\n this.setContent(content) // Restore it as it was.\n return compiled\n }\n get originalText() {\n return this.content ?? this.root.title ?? \"\"\n }\n defaultClassName = \"printTitleParser\"\n tag = \"h1\"\ncaptionAftertextParser\n popularity 0.003207\n description An image caption.\n cue caption\n example\n map.png\n caption A map.\n extends scrollParagraphParser\n boolean isPopular true\nabstractMediaParser\n extends scrollParagraphParser\n inScope scrollMediaLoopParser scrollAutoplayParser\n int atomIndex 1\n javascript\n buildTxt() {\n return \"\"\n }\n get filename() {\n return this.getAtom(this.atomIndex)\n }\n getAsHtmlAttribute(attr) {\n if (!this.has(attr)) return \"\"\n const value = this.get(attr)\n return value ? `${attr}=\"${value}\"` : attr\n }\n getAsHtmlAttributes(list) {\n return list.map(atom => this.getAsHtmlAttribute(atom)).filter(i => i).join(\" \")\n }\n buildHtml() {\n return `<${this.tag} src=\"${this.filename}\" controls ${this.getAsHtmlAttributes(\"width height loop autoplay\".split(\" \"))}></${this.tag}>`\n }\nscrollMusicParser\n popularity 0.000024\n extends abstractMediaParser\n cue music\n description Play sound files.\n example\n music sipOfCoffee.m4a\n javascript\n buildHtml() {\n return `<audio controls ${this.getAsHtmlAttributes(\"loop autoplay\".split(\" \"))}><source src=\"${this.filename}\" type=\"audio/mpeg\"></audio>`\n }\nquickSoundParser\n popularity 0.000024\n extends scrollMusicParser\n atoms urlAtom\n pattern ^[^\\s]+\\.(mp3|wav|ogg|aac|m4a|flac)\n int atomIndex 0\n example\n sipOfCoffee.m4a\nscrollVideoParser\n popularity 0.000024\n extends abstractMediaParser\n cue video\n example\n video spirit.mp4\n description Play video files.\n widthParser\n cueFromId\n atoms cueAtom integerAtom\n heightParser\n cueFromId\n atoms cueAtom integerAtom\n javascript\n tag = \"video\"\nquickVideoParser\n popularity 0.000024\n extends scrollVideoParser\n example\n spirit.mp4\n atoms urlAtom\n pattern ^[^\\s]+\\.(mp4|webm|avi|mov)\n int atomIndex 0\nquickParagraphParser\n popularity 0.001881\n cue *\n extends scrollParagraphParser\n description A paragraph.\n boolean isArticleContent true\n example\n * I had a _new_ idea.\nscrollStopwatchParser\n description A stopwatch.\n extends scrollParagraphParser\n cue stopwatch\n example\n stopwatch\n atoms cueAtom\n catchAllAtomType numberAtom\n javascript\n buildHtml() {\n const line = this.getLine()\n const id = this._getUid()\n this.setLine(`* <span class=\"scrollStopwatchParser\" id=\"stopwatch${id}\">0.0</span><script>{let startTime = parseFloat(new URLSearchParams(window.location.search).get('start') || 0); document.getElementById('stopwatch${id}').title = startTime; setInterval(()=>{ const el = document.getElementById('stopwatch${id}'); el.title = parseFloat(el.title) + .1; el.textContent = (parseFloat(el.title)).toFixed(1)}, 100)}</script> `)\n const html = super.buildHtml()\n this.setLine(line)\n return html\n }\nthinColumnsParser\n popularity 0.003690\n extends abstractAftertextParser\n cueFromId\n catchAllAtomType integerAtom\n description Thin columns.\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n columnWidth = 35\n columnGap = 20\n buildHtml() {\n const {columnWidth, columnGap, maxColumns} = this\n const maxTotalWidth = maxColumns * columnWidth + (maxColumns - 1) * columnGap\n const stackContents = this.parent.clearSectionStack() // Starting columns always first clears the section stack.\n if (this.singleColumn) this.parent.sectionStack.push(\"</div>\") // Single columns are self-closing after section break.\n return stackContents + `<div class=\"scrollColumns\" style=\"column-width:${columnWidth}ch;column-count:${maxColumns};max-width:${maxTotalWidth}ch;\">`\n }\n get maxColumns() {\n return this.singleColumn ? 1 : parseInt(this.getAtom(1) ?? 10)\n }\nwideColumnsParser\n popularity 0.000386\n extends thinColumnsParser\n description Wide columns.\n javascript\n columnWidth = 90\nwideColumnParser\n popularity 0.003376\n extends wideColumnsParser\n description A wide column section.\n boolean singleColumn true\nmediumColumnsParser\n popularity 0.003376\n extends thinColumnsParser\n description Medium width columns.\n javascript\n columnWidth = 65\nmediumColumnParser\n popularity 0.003376\n extends mediumColumnsParser\n description A medium column section.\n boolean singleColumn true\nthinColumnParser\n popularity 0.003376\n extends thinColumnsParser\n description A thin column section.\n boolean singleColumn true\nendColumnsParser\n popularity 0.007789\n extends abstractAftertextParser\n cueFromId\n description End columns.\n javascript\n buildHtml() {\n return \"</div>\"\n }\n buildHtmlSnippet() {\n return \"\"\n }\nscrollContainerParser\n popularity 0.000096\n cue container\n description A centered HTML div.\n example\n container 600px\n catchAllAtomType cssLengthAtom\n extends abstractAftertextParser\n boolean isHtml true\n javascript\n get maxWidth() {\n return this.atoms[1] || \"1200px\"\n }\n buildHtmlSnippet() {\n return \"\"\n }\n tag = \"div\"\n defaultClassName = \"scrollContainerParser\"\n buildHtml() {\n this.parent.bodyStack.push(\"</div>\")\n return `<style>.scrollContainerParser{width: 100%; box-sizing: border-box; max-width: ${this.maxWidth}; margin: 0 auto;}</style>` + super.buildHtml()\n }\n get text() { return \"\"}\n get closingTag() { return \"\"}\ndebugSourceStackParser\n // useful for debugging\n description Print compilation steps.\n extends abstractAftertextParser\n cueFromId\n example\n printOriginalSource\n javascript\n get sources() {\n const {file} = this.root\n const passNames = [\"codeAtStart\", \"fusedCode\", \"codeAfterMacroPass\"]\n let lastCode = \"\"\n return passNames.map(name => {\n let code = file[name]\n if (lastCode === code)\n code = \"[Unchanged]\"\n lastCode = file[name]\n return {\n name,\n code\n }})\n }\n buildHtml() {\n return `<code class=\"scrollCodeBlock\">${this.buildTxt().replace(/\\</g, \"&lt;\")}</code>`\n }\n buildTxt() {\n return this.sources.map((pass, index) => `Pass ${index + 1} - ${pass.name}\\n========\\n${pass.code}`).join(\"\\n\\n\\n\")\n }\nabstractDinkusParser\n extends abstractAftertextParser\n boolean isDinkus true\n javascript\n buildHtml() {\n return `<div class=\"${this.defaultClass}\"><span>${this.dinkus}</span></div>`\n }\n defaultClass = \"abstractDinkusParser\"\n buildTxt() {\n return this.dinkus\n }\n get dinkus() {\n return this.content || this.getLine()\n }\nhorizontalRuleParser\n popularity 0.000362\n cue ---\n description A horizontal rule.\n extends abstractDinkusParser\n example\n ---\n javascript\n buildHtml() {\n return `<hr>`\n }\nscrollDinkusParser\n popularity 0.010828\n cue ***\n description A dinkus. Breaks section.\n boolean isPopular true\n example\n ***\n extends abstractDinkusParser\n javascript\n dinkus = \"*\"\ncustomDinkusParser\n cue dinkus\n description A custom dinkus.\n extends abstractDinkusParser\nendOfPostDinkusParser\n popularity 0.005740\n extends abstractDinkusParser\n description End of post dinkus.\n boolean isPopular true\n cue ****\n example\n ****\n javascript\n dinkus = \"⁂\"\nabstractIconButtonParser\n extends abstractAftertextParser\n cueFromId\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n return `<style>.abstractIconButtonParser {position:absolute;top:0.25rem; }.abstractIconButtonParser svg {fill: rgba(204,204,204,.8);width:1.875rem;height:1.875rem; padding: 0 7px;} .abstractIconButtonParser:hover svg{fill: #333;}</style><a href=\"${this.link}\" class=\"doNotPrint abstractIconButtonParser\" style=\"${this.style}\">${this.svg}</a>`\n }\ndownloadButtonParser\n popularity 0.006294\n description Link to download/WWS page.\n extends abstractIconButtonParser\n catchAllAtomType urlAtom\n string style position:relative;\n string svg <svg fill=\"#000000\" xmlns=\"http://www.w3.org/2000/svg\" width=\"800px\" height=\"800px\" viewBox=\"0 0 52 52\" enable-background=\"new 0 0 52 52\" xml:space=\"preserve\"><path d=\"M38.6,20.4c-1-6.5-6.7-11.5-13.5-11.5c-7.6,0-13.7,6.1-13.7,13.7c0,0.3,0,0.7,0.1,1c-5,0.4-8.9,4.6-8.9,9.6 c0,5.4,4.3,9.7,9.7,9.7h11.5c-0.8-0.8-8.1-8.1-8.1-8.1c-0.4-0.4-0.4-0.9,0-1.3l1.3-1.3c0.4-0.4,0.9-0.4,1.3,0l3.5,3.5 c0.4,0.4,1.1,0.1,1.1-0.4V21.8c0-0.4,0.5-0.9,1-0.9h1.9c0.5,0,0.9,0.4,0.9,0.9v13.4c0,0.6,0.8,0.8,1.1,0.4l3.5-3.5 c0.4-0.4,0.9-0.4,1.3,0l1.3,1.3c0.4,0.4,0.4,0.9,0,1.3L26,42.9h12.3v0c6.1-0.1,11-5.1,11-11.3C49.4,25.5,44.6,20.6,38.6,20.4z\"/></svg><!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->\n javascript\n get link() {\n return this.content\n }\neditButtonParser\n popularity 0.013963\n description Print badge top right.\n extends abstractIconButtonParser\n catchAllAtomType urlAtom\n // SVG from https://github.com/32pixelsCo/zest-icons\n string svg <svg width=\"800px\" height=\"800px\" viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\"><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M21.1213 2.70705C19.9497 1.53548 18.0503 1.53547 16.8787 2.70705L15.1989 4.38685L7.29289 12.2928C7.16473 12.421 7.07382 12.5816 7.02986 12.7574L6.02986 16.7574C5.94466 17.0982 6.04451 17.4587 6.29289 17.707C6.54127 17.9554 6.90176 18.0553 7.24254 17.9701L11.2425 16.9701C11.4184 16.9261 11.5789 16.8352 11.7071 16.707L19.5556 8.85857L21.2929 7.12126C22.4645 5.94969 22.4645 4.05019 21.2929 2.87862L21.1213 2.70705ZM18.2929 4.12126C18.6834 3.73074 19.3166 3.73074 19.7071 4.12126L19.8787 4.29283C20.2692 4.68336 20.2692 5.31653 19.8787 5.70705L18.8622 6.72357L17.3068 5.10738L18.2929 4.12126ZM15.8923 6.52185L17.4477 8.13804L10.4888 15.097L8.37437 15.6256L8.90296 13.5112L15.8923 6.52185ZM4 7.99994C4 7.44766 4.44772 6.99994 5 6.99994H10C10.5523 6.99994 11 6.55223 11 5.99994C11 5.44766 10.5523 4.99994 10 4.99994H5C3.34315 4.99994 2 6.34309 2 7.99994V18.9999C2 20.6568 3.34315 21.9999 5 21.9999H16C17.6569 21.9999 19 20.6568 19 18.9999V13.9999C19 13.4477 18.5523 12.9999 18 12.9999C17.4477 12.9999 17 13.4477 17 13.9999V18.9999C17 19.5522 16.5523 19.9999 16 19.9999H5C4.44772 19.9999 4 19.5522 4 18.9999V7.99994Z\"/></svg>\n javascript\n get link() {\n return this.content || this.root.editUrl || \"\"\n }\n get style() {\n return this.parent.findParticles(\"editButton\")[0] === this ? \"right:2rem;\": \"position:relative;\"\n }\nemailButtonParser\n popularity 0.006294\n description Email button.\n extends abstractIconButtonParser\n catchAllAtomType emailAddressAtom\n // todo: should just be \"optionalAtomType\"\n string style position:relative;\n string svg <svg viewBox=\"3 5 24 20\" width=\"24\" height=\"20\" xmlns=\"http://www.w3.org/2000/svg\"><g transform=\"matrix(1, 0, 0, 1, 0, -289.0625)\"><path style=\"opacity:1;stroke:none;stroke-width:0.49999997;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1\" d=\"M 5 5 C 4.2955948 5 3.6803238 5.3628126 3.3242188 5.9101562 L 14.292969 16.878906 C 14.696939 17.282876 15.303061 17.282876 15.707031 16.878906 L 26.675781 5.9101562 C 26.319676 5.3628126 25.704405 5 25 5 L 5 5 z M 3 8.4140625 L 3 23 C 3 24.108 3.892 25 5 25 L 25 25 C 26.108 25 27 24.108 27 23 L 27 8.4140625 L 17.121094 18.292969 C 15.958108 19.455959 14.041892 19.455959 12.878906 18.292969 L 3 8.4140625 z \" transform=\"translate(0,289.0625)\" id=\"rect4592\"/></g></svg>\n javascript\n get link() {\n const email = this.content || this.parent.get(\"email\")\n return email ? `mailto:${email}` : \"\"\n }\nhomeButtonParser\n popularity 0.006391\n description Home button.\n extends abstractIconButtonParser\n catchAllAtomType urlAtom\n string style left:2rem;\n string svg <svg role=\"img\" viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M12.7166 3.79541C12.2835 3.49716 11.7165 3.49716 11.2834 3.79541L4.14336 8.7121C3.81027 8.94146 3.60747 9.31108 3.59247 9.70797C3.54064 11.0799 3.4857 13.4824 3.63658 15.1877C3.7504 16.4742 4.05336 18.1747 4.29944 19.4256C4.41371 20.0066 4.91937 20.4284 5.52037 20.4284H8.84433C8.98594 20.4284 9.10074 20.3111 9.10074 20.1665V15.9754C9.10074 14.9627 9.90433 14.1417 10.8956 14.1417H13.4091C14.4004 14.1417 15.204 14.9627 15.204 15.9754V20.1665C15.204 20.3111 15.3188 20.4284 15.4604 20.4284H18.4796C19.0806 20.4284 19.5863 20.0066 19.7006 19.4256C19.9466 18.1747 20.2496 16.4742 20.3634 15.1877C20.5143 13.4824 20.4594 11.0799 20.4075 9.70797C20.3925 9.31108 20.1897 8.94146 19.8566 8.7121L12.7166 3.79541ZM10.4235 2.49217C11.3764 1.83602 12.6236 1.83602 13.5765 2.49217L20.7165 7.40886C21.4457 7.91098 21.9104 8.73651 21.9448 9.64736C21.9966 11.0178 22.0564 13.5119 21.8956 15.3292C21.7738 16.7067 21.4561 18.4786 21.2089 19.7353C20.9461 21.0711 19.7924 22.0001 18.4796 22.0001H15.4604C14.4691 22.0001 13.6655 21.1791 13.6655 20.1665V15.9754C13.6655 15.8307 13.5507 15.7134 13.4091 15.7134H10.8956C10.754 15.7134 10.6392 15.8307 10.6392 15.9754V20.1665C10.6392 21.1791 9.83561 22.0001 8.84433 22.0001H5.52037C4.20761 22.0001 3.05389 21.0711 2.79113 19.7353C2.54392 18.4786 2.22624 16.7067 2.10437 15.3292C1.94358 13.5119 2.00338 11.0178 2.05515 9.64736C2.08957 8.73652 2.55427 7.91098 3.28346 7.40886L10.4235 2.49217Z\"/></svg>\n javascript\n get link() {\n return this.content || this.get(\"link\") || \"index.html\"\n }\ntheScrollButtonParser\n popularity 0.006294\n description WWS button.\n extends abstractIconButtonParser\n string style position:relative;\n string svg <svg xmlns=\"http://www.w3.org/2000/svg\" direction=\"ltr\" width=\"231.52568231268793\" height=\"249.33156169975996\" viewBox=\"297.27169239534896 1273.121785992385 231.52568231268793 249.33156169975996\" stroke-linecap=\"round\" stroke-linejoin=\"round\" data-color-mode=\"dark\" class=\"tl-container tl-theme__force-sRGB tl-theme__dark\" ><defs/><g transform=\"matrix(1, 0, 0, 1, 395.9682, 1413.3618)\" opacity=\"1\"><g transform=\"scale(1)\"><path d=\"M-5.7342,-1.1484 T-5.0182,-4.6536 -2.6672,-12.9768 1.7374,-22.3903 8.4597,-30.0892 16.5455,-35.2796 25.3478,-37.8247 34.4641,-37.2199 43.0676,-33.4606 50.27,-27.1118 55.7861,-19.7972 59.8042,-11.6764 61.6844,-2.3157 60.8049,7.9615 57.3259,17.5954 51.2605,25.5515 41.9451,31.9237 30.6489,36.2084 18.9812,37.6038 8.4915,36.637 -1.3063,34.5174 -10.6869,31.6604 -19.0463,27.0252 -26.0612,20.1562 -31.864,11.1271 -35.2772,1.0066 -35.7963,-9.1933 -35.203,-19.2337 -32.52,-28.3259 -27.3388,-37.4245 -20.2857,-45.7085 -11.787,-53.0395 -2.4314,-58.4864 7.1724,-61.8739 17.5002,-65.6025 28.2859,-68.1034 38.514,-69.1081 48.1844,-69.9134 57.9136,-70.1787 67.4056,-69.5971 76.297,-67.7446 84.5233,-63.97 92.0158,-57.5003 98.1976,-48.5614 102.8839,-38.056 105.9936,-27.6097 107.074,-18.168 107.175,-8.2882 106.6452,1.9768 105.4734,11.7698 104.0279,21.1013 101.7439,31.0445 98.0977,40.6386 92.7822,49.1039 86.2847,57.2337 78.6099,64.7113 69.8339,70.974 61.2863,75.092 52.4283,78.2186 42.5338,80.7945 32.7733,82.6629 22.8568,83.6574 12.2803,83.3538 2.4971,81.4828 -6.3367,78.789 -15.1061,75.8011 -24.259,72.3779 -33.2286,68.991 -41.5707,64.8363 -49.153,59.1909 -55.8375,52.2938 -62.9311,43.9553 -68.4604,34.4882 -71.2761,23.5855 -72.748,12.7452 -73.7673,2.0453 -74.1187,-8.7386 -72.293,-19.3856 -68.7376,-30.4053 -64.12,-39.7852 -59.1825,-47.8931 -53.7695,-56.4512 -48.1998,-65.7676 -43.1389,-74.401 -36.9006,-81.0179 -28.4317,-86.2639 -18.3342,-90.3521 -8.9259,-93.9355 0.1927,-98.7179 9.3551,-103.3537 18.7651,-106.7552 29.7482,-110.3584 40.9287,-113.446 50.87,-115.2231 57.8279,-116.0074 60.4065,-116.0632 A7.8326,7.8326 0 0 1 61.1735,-100.4168 T58.6018,-100.2201 51.1634,-99.3008 41.695,-96.884 32.4044,-94.0187 22.65,-91.382 13.4974,-87.3756 5.0519,-83.1026 -5.0443,-78.6175 -15.7236,-74.4743 -24.6193,-70.2681 -31.274,-62.5903 -36.3827,-53.9362 -41.2833,-46.2905 -46.0679,-38.5161 -50.639,-30.6576 -54.6876,-22.4063 -57.6038,-12.3346 -58.5104,-1.8678 -57.6022,9.4969 -56.0628,20.477 -53.6434,29.0487 -48.8908,36.7517 -42.4075,43.9784 -35.3064,50.6236 -27.3553,55.2062 -17.6884,59.4064 -7.6442,63.6638 2.4427,67.0449 12.7308,69.4843 22.9294,70.2171 33.2547,69.3921 42.4972,67.7384 52.2753,64.8425 61.8649,60.9142 69.5292,56.0828 76.3604,49.5927 82.431,42.3194 87.219,34.619 90.6076,25.5217 92.547,16.0352 93.8703,7.1315 94.4972,-2.5268 94.3672,-13.3681 93.3204,-24.4252 90.5377,-34.1656 85.7321,-43.6441 78.7334,-51.8057 68.7542,-56.0559 57.9857,-57.2713 48.079,-57.0198 38.4535,-56.3204 28.5246,-55.0036 18.6104,-52.4796 9.6402,-49.559 0.7193,-46.2981 -7.1531,-41.3715 -13.708,-34.8957 -19.5435,-26.853 -22.8356,-17.0622 -23.363,-6.5446 -21.9969,3.1439 -17.1086,11.9113 -9.276,18.744 -0.0685,22.6058 9.3636,24.796 19.2422,25.8817 29.052,25.0411 37.9338,21.3502 45.6819,13.8498 49.6675,4.5228 49.2802,-5.1854 45.3277,-14.4455 38.8603,-21.7879 30.5488,-25.7753 21.3356,-24.3975 13.6687,-19.2391 8.8217,-10.9919 6.423,-2.3609 5.7342,1.1484 A5.8481,5.8481 0 0 1 -5.7342,-1.1484 Z\" stroke-linecap=\"round\"/></g></g></svg>\n javascript\n get link() {\n return \"https://wws.scroll.pub\"\n }\nabstractTextLinkParser\n extends abstractAftertextParser\n cueFromId\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildTxt() {\n return this.text\n }\n buildHtml() {\n return `<div class=\"abstractTextLinkParser\"><a href=\"${this.link}\">${this.text}</a></div>`\n }\neditLinkParser\n popularity 0.001206\n extends abstractTextLinkParser\n description Print \"Edit\" link.\n string text Edit\n javascript\n get link() {\n return this.root.editUrl || \"\"\n }\nscrollVersionLinkParser\n popularity 0.006294\n extends abstractTextLinkParser\n string link https://scroll.pub\n description Print Scroll version.\n javascript\n get text() {\n return `Built with Scroll v${this.root.scrollVersion}`\n }\nclassicFormParser\n cue classicForm\n popularity 0.006391\n description Generate input form for ScrollSet.\n extends abstractAftertextParser\n atoms cueAtom\n catchAllAtomType stringAtom\n string script\n <script>\n sendFormViaEmail = form => {\n const mailto = new URL(\"mailto:\")\n const params = []\n const { value, title } = form.querySelector('button[type=\"submit\"]')\n params.push(`subject=${encodeURIComponent(value)}`)\n params.push(`to=${encodeURIComponent(title)}`)\n const oneTextarea = form.querySelector('textarea[title=\"oneTextarea\"]')\n const body = oneTextarea ? codeMirrorInstance.getValue() : Array.from(new FormData(form)).map(([name, value]) => `${name} ${value}`).join(\"\\\\n\")\n params.push(`body=${encodeURIComponent(body)}`)\n mailto.search = params.join(\"&\")\n window.open(mailto.href, '_blank')\n }\n </script>\n string style\n <style> .scrollFormParser {\n font-family: \"Gill Sans\", \"Bitstream Vera Sans\", sans-serif;\n }\n .scrollFormParser input , .scrollFormParser textarea{\n padding: 10px;\n margin-bottom: 10px;\n width: 100%;\n box-sizing: border-box;\n } .scrollFormParser label {\n display: block;\n margin-bottom: 5px;\n }\n </style>\n javascript\n get inputs() {\n return this.root.measures.filter(measure => !measure.IsComputed).map((measure, index) => {\n const {Name, Question, IsRequired, Type} = measure\n const type = Type || \"text\"\n const placeholder = Question\n const ucFirst = Name.substr(0, 1).toUpperCase() + Name.substr(1)\n // ${index ? \"\" : \"autofocus\"}\n let tag = \"\"\n if (Type === \"textarea\")\n tag = `<textarea placeholder=\"${placeholder}\" id=\"${Name}\" name=\"${Name}\" ${IsRequired ? \"required\" : \"\"}></textarea>`\n else\n tag = `<input placeholder=\"${placeholder}\" type=\"${type}\" id=\"${Name}\" name=\"${Name}\" ${IsRequired ? \"required\" : \"\"}>`\n return `<div><label for=\"${Name}\" title=\"${IsRequired ? \"Required\" : \"\"}\">${ucFirst}${IsRequired ? \"*\" : \"\"}:</label>${tag}</div>`\n }).join(\"\\n\")\n }\n buildHtml() {\n const {isEmail, formDestination, callToAction, subject} = this\n return `${this.script}${this.style}<form ${isEmail ? \"onsubmit='sendFormViaEmail(this); return false;'\" : ` method='post' action='${formDestination}'`} class=\"scrollFormParser\">${this.inputs}<button value=\"${subject}\" title=\"${formDestination}\" class=\"scrollButton\" type=\"submit\">${callToAction}</button>${this.footer}</form>`\n }\n get callToAction() {\n return (this.isEmail ? \"Submit via email\" : (this.subject || \"Post\"))\n }\n get isEmail() {\n return this.formDestination.includes(\"@\")\n }\n get formDestination() {\n return this.getAtom(1) || \"\"\n }\n get subject() {\n return this.getAtomsFrom(2)?.join(\" \") || \"\"\n }\n get footer() {\n return \"\"\n }\nscrollFormParser\n extends classicFormParser\n cue scrollForm\n placeholderParser\n atoms cueAtom\n baseParser blobParser\n cueFromId\n single\n valueParser\n atoms cueAtom\n baseParser blobParser\n cueFromId\n single\n nameParser\n description Name for the post submission.\n atoms cueAtom stringAtom\n cueFromId\n single\n description Generate a Scroll Form.\n string copyFromExternal .codeMirror.css .scrollLibs.js .constants.js\n string requireOnce\n <link rel=\"stylesheet\" href=\".codeMirror.css\">\n <script src=\".scrollLibs.js\"></script>\n <script src=\".constants.js\"></script>\n javascript\n get placeholder() {\n return this.getParticle(\"placeholder\")?.subparticlesToString() || \"\"\n }\n get value() {\n return this.getParticle(\"value\")?.subparticlesToString() || \"\"\n }\n get footer() {\n return \"\"\n }\n get name() {\n return this.get(\"name\") || \"particles\"\n }\n get parsersBundle() {\n const parserRegex = /^[a-zA-Z0-9_]+Parser$/gm\n const clone = this.root.clone()\n const parsers = clone.filter(line => parserRegex.test(line.getLine()))\n return \"\\n\" + parsers.map(particle => {\n particle.prependLine(\"boolean suggestInAutocomplete true\")\n return particle.toString()\n }).join(\"\\n\")\n }\n get inputs() {\n const Name = this.name\n return `<textarea title=\"oneTextarea\" rows=\"${Math.min(this.root.measures.length * 2, 30)}\" placeholder=\"${this.placeholder}\" id=\"${Name}\" name=\"${Name}\"></textarea>\n <script id=\"${Name}Parsers\" type=\"text/plain\">${this.parsersBundle}</script>\n <script>{\n const parserRegex = /^[a-zA-Z0-9_]+Parser$/gm\n let {width, height} = document.getElementById('${Name}').getBoundingClientRect();\n const sp = new Particle(AppConstants.parsers)\n sp.filter(particle => particle.getLine().match(parserRegex)).forEach(part => {\n part.appendLine(\"boolean suggestInAutocomplete false\")\n })\n const customScrollParser = new HandParsersProgram(sp.toString() + document.getElementById(\"${Name}Parsers\").textContent).compileAndReturnRootParser()\n codeMirrorInstance = new ParsersCodeMirrorMode(\"custom\", () => customScrollParser, undefined, CodeMirror).register().fromTextAreaWithAutocomplete(document.getElementById(\"${Name}\"), {\n lineWrapping: false,\n lineNumbers: false\n })\n codeMirrorInstance.setSize(width, height);\n codeMirrorInstance.setValue(\\`${this.value}\\`); }</script>`\n }\n buildHtml(buildSettings) {\n return this.getHtmlRequirements(buildSettings) + super.buildHtml()\n }\nloremIpsumParser\n extends abstractAftertextParser\n cueFromId\n description Generate dummy text.\n catchAllAtomType integerAtom\n string placeholder Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n javascript\n get originalText() {\n return this.placeholder.repeat(this.howMany)\n }\n get howMany() {\n return this.getAtom(1) ? parseInt(this.getAtom(1)) : 1\n }\nnickelbackIpsumParser\n extends loremIpsumParser\n string placeholder And one day, I’ll be at the door. And lose your wings to fall in love? To the bottom of every bottle. I’m on the ledge of the eighteenth story. Why must the blind always lead the blind?\nscrollModalParser\n description A modal dialog overlay.\n extends abstractAftertextParser\n boolean isHtml true\n cue modal\n string requireOnce\n <style>\n .scrollModal {\n display: none;\n position: fixed;\n background: transparent;\n padding: 20px;\n left: 3rem;\n top: 3rem;\n right: 3rem;\n bottom: 3rem;\n z-index: 1000;\n font-family: \"IBM Plex Mono\", monospace;\n /* Frosted glass effect */\n background: rgba(0, 0, 0, 0.2);\n backdrop-filter: blur(8px);\n -webkit-backdrop-filter: blur(8px);\n border: 1px solid rgba(255, 255, 255, 0.1);\n box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);\n border-radius: 8px;\n overflow: hidden;\n }\n .scrollModal .closeButton {\n position: absolute;\n top: 10px;\n right: 10px;\n width: 30px;\n height: 30px;\n border: none;\n background: rgba(255, 255, 255, 0.1);\n color: rgba(255, 255, 255, 0.8);\n border-radius: 4px;\n cursor: pointer;\n font-family: \"IBM Plex Mono\", monospace;\n font-size: 18px;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all 0.2s ease;\n }\n .scrollModal .closeButton:hover {\n background: rgba(255, 255, 255, 0.2);\n color: white;\n }\n </style>\n <script>{\n window.closeModal = modal => {\n modal.style.display = 'none';\n history.pushState(\"\", document.title, window.location.pathname + window.location.search);\n };\n window.openModal = (id, event) => {\n if (event) event.modalJustOpened = true;\n document.querySelector(\"#\" + id).style.display = 'block';\n };\n window.addEventListener('hashchange', () => {\n const modalId = location.hash.slice(1); window.openModal(modalId);\n });\n document.addEventListener('keydown', e => {\n if (e.key === 'Escape') \n document.querySelectorAll('.scrollModal').forEach(closeModal);\n });\n // Check hash on initial load\n document.addEventListener(\"DOMContentLoaded\", e => {\n if (location.hash) \n window.openModal(location.hash.slice(1));\n });\n // Close on outside click\n document.addEventListener('click', e => {\n if (e.modalJustOpened) return;\n const modals = document.querySelectorAll('.scrollModal');\n modals.forEach(modal => {\n if (modal.style.display === 'block' && !modal.contains(e.target)) {\n closeModal(modal);\n }\n });\n });\n }</script>\n javascript\n buildHtml(buildSettings) {\n this.parent.sectionStack.push(\"</div>\")\n return this.getHtmlRequirements(buildSettings) + `<div class=\"scrollModal\" id=\"${this.htmlId}\"><button class=\"closeButton\" onclick=\"closeModal(this.parentElement)\">×</button>`\n }\nprintSnippetsParser\n popularity 0.000338\n // todo: why are we extending AT here and not loops? Is it for class/id etc?\n extends abstractAftertextParser\n cueFromId\n atoms cueAtom\n catchAllAtomType tagWithOptionalFolderAtom\n description Prints snippets matching tag(s).\n example\n printSnippets index\n javascript\n makeSnippet(scrollProgram, buildSettings) {\n const {endSnippetIndex} = scrollProgram\n if (endSnippetIndex === -1) return scrollProgram.buildHtmlSnippet(buildSettings) + scrollProgram.editHtml\n const linkRelativeToCompileTarget = buildSettings.relativePath + scrollProgram.permalink\n const joinChar = \"\\n\"\n const html = scrollProgram\n .map((subparticle, index) => (index >= endSnippetIndex ? \"\" : subparticle.buildHtmlSnippet ? subparticle.buildHtmlSnippet(buildSettings) : subparticle.buildHtml(buildSettings)))\n .filter(i => i)\n .join(joinChar)\n .trim() +\n `<a class=\"scrollContinueReadingLink\" href=\"${linkRelativeToCompileTarget}\">Continue reading...</a>`\n return html\n }\n get files() {\n const thisFile = this.parent.file\n const files = this.root.getFilesByTags(this.content, this.has(\"limit\") ? parseInt(this.get(\"limit\")) : undefined).filter(file => file.file !== thisFile)\n // allow sortBy lastCommit Time\n if (this.get(\"sortBy\") === \"commitTime\") {\n return this.root.sortBy(files, file => file.scrollProgram.lastCommitTime).reverse()\n }\n return files\n }\n buildHtml() {\n const alreadyRequired = this.root.alreadyRequired\n const snippets = this.files.map(file => {\n const buildSettings = {relativePath: file.relativePath, alreadyRequired }\n return `<div class=\"scrollSnippetContainer\">${this.makeSnippet(file.file.scrollProgram, buildSettings)}</div>`\n }).join(\"\\n\\n\")\n return `<div class=\"scrollColumns\" style=\"column-width:35ch;\">${snippets}</div>`\n }\n buildTxt() {\n return this.files.map(file => {\n const {scrollProgram} = file.file\n const {title, date, absoluteLink} = scrollProgram\n const ruler = \"=\".repeat(title.length)\n // Note: I tried to print the description here but the description generating code needs work.\n return `${title}\\n${ruler}\\n${date}\\n${absoluteLink}`\n }).join(\"\\n\\n\")\n }\nscrollNavParser\n popularity 0.000048\n extends printSnippetsParser\n cue fileNav\n description Titles and links in group(s).\n joinParser\n boolean allowTrailingWhitespace true\n cueFromId\n atoms cueAtom\n catchAllAtomType stringAtom\n javascript\n buildHtml() {\n return `<nav class=\"scrollNavParser\">` + this.root.getFilesByTags(this.content).map(file => {\n const { linkTitle, permalink } = file.file.scrollProgram\n return `<a href=\"${permalink}\">${linkTitle}</a>` \n }).join(this.get(\"join\") || \" \") + `</nav>`\n }\nprintFullSnippetsParser\n popularity 0.000048\n extends printSnippetsParser\n cueFromId\n description Print full pages in group(s).\n javascript\n makeSnippet(scrollProgram, buildSettings) {\n return scrollProgram.buildHtmlSnippet(buildSettings) + scrollProgram.editHtml\n }\nprintShortSnippetsParser\n popularity 0.000048\n extends printSnippetsParser\n cueFromId\n description Titles and descriptions in group(s).\n javascript\n makeSnippet(scrollProgram, buildSettings) {\n const { title, permalink, description, timestamp } = scrollProgram\n return `<div><a href=\"${permalink}\">${title}</a><div>${description}...</div><div class=\"subdued\" style=\"text-align:right;\">${this.root.dayjs(timestamp * 1000).format(`MMMM D, YYYY`)}</div></div>`\n }\nprintRelatedParser\n popularity 0.001182\n description Print links to related posts.\n extends printSnippetsParser\n cueFromId\n javascript\n buildHtml() {\n const alreadyRequired = this.root.alreadyRequired\n const list = this.files.map(fileWrapper => {\n const {relativePath, file} = fileWrapper\n const {title, permalink, year} = file.scrollProgram\n return `- ${title}${year ? \" (\" + year + \")\" : \"\"}\\n link ${relativePath + permalink}`\n }).join(\"\\n\")\n const items = this.parent.concat(list)\n const html = items.map(item => item.buildHtml()).join(\"\\n\")\n items.forEach(item => item.destroy())\n return html\n }\nscrollNoticesParser\n extends abstractAftertextParser\n description Display messages in URL query parameters.\n cue notices\n javascript\n buildHtml() {\n const id = this.htmlId\n return `<div id=\"${id}\" class=\"scrollNoticesParser\" style=\"display:none;\"></div><script>(function(){\n const params = new URLSearchParams(window.location.search)\n if (!params.size) return\n document.getElementById('${id}').innerHTML = Array.from(params.entries()).map(([key, value]) => {\n if (key === \"error\") \n return '<div style=\"color:red\">Error: ' + value + '</div>'\n if (key === \"success\")\n return '<div style=\"color:green\">Success: ' + value + '</div>'\n return '<div>' + key + ': ' + value + '</div>'\n }).join(\"\") || \"No query parameters found\"\n document.getElementById('${id}').style.display = \"block\"\n })()</script>`\n }\nabstractAssertionParser\n description Test above particle's output.\n extends abstractScrollParser\n string bindTo previous\n catchAllAtomType codeAtom\n cueFromId\n javascript\n buildHtml() {\n return ``\n }\n get particleToTest() {\n // If the previous particle is also an assertion particle, use the one before that.\n return this.previous.particleToTest ? this.previous.particleToTest : this.previous\n }\n get actual() {return this.particleToTest.buildHtml()}\n getErrors() {\n const {actual, expected} = this\n const errors = super.getErrors()\n if (this.areEqual(actual, expected))\n return errors\n return errors.concat(this.makeError(`'${actual}' did not ${this.kind} '${expected}'`))\n }\n get expected() {\n return this.length ? this.subparticlesToString() : (this.content ? this.content : \"\")\n }\n catchAllParser htmlLineParser\nassertHtmlEqualsParser\n extends abstractAssertionParser\n string kind equal\n example\n <b></b>\n assertHtmlEquals <b></b>\n javascript\n areEqual(actual, expected) {\n return actual === expected\n }\n // todo: why are we having to super here?\n getErrors() { return super.getErrors()}\nassertBuildIncludesParser\n extends abstractAssertionParser\n string kind include\n example\n buildCsv\n assertBuildIncludes virginica\n javascript\n areEqual(actual, expected) {\n return actual.includes(expected)\n }\n get actual() { return this.particleToTest.buildOutput()}\n getErrors() { return super.getErrors()}\nassertHtmlIncludesParser\n extends abstractAssertionParser\n string kind include\n javascript\n areEqual(actual, expected) {\n return actual.includes(expected)\n }\n getErrors() { return super.getErrors()}\nassertHtmlExcludesParser\n extends abstractAssertionParser\n string kind exclude\n javascript\n areEqual(actual, expected) {\n return !actual.includes(expected)\n }\n getErrors() { return super.getErrors()}\nassertIgnoreBelowErrorsParser\n description If you want to ignore any errors in the below particle in automated tests.\n extends abstractScrollParser\n string bindTo next\n cueFromId\nabstractPrintMetaParser\n extends abstractScrollParser\n cueFromId\nprintAuthorsParser\n popularity 0.001664\n description Prints author(s) byline.\n boolean isPopular true\n extends abstractPrintMetaParser\n // todo: we need pattern matching added to sdk to support having no params or a url and personNameAtom\n catchAllAtomType stringAtom\n example\n authors Breck Yunits\n https://breckyunits.com\n printAuthors\n javascript\n buildHtml() {\n return this.parent.getParticle(\"authors\")?.buildHtmlForPrint()\n }\n buildTxt() {\n return this.parent.getParticle(\"authors\")?.buildTxtForPrint()\n }\nprintDateParser\n popularity 0.000434\n extends abstractPrintMetaParser\n // If not present computes the date from the file's ctime.\n description Print published date.\n boolean isPopular true\n example\n date 1/11/2019\n printDate\n javascript\n buildHtml() {\n return `<div class=\"printDateParser\">${this.day}</div>`\n }\n get day() {\n let day = this.content || this.root.date\n if (!day) return \"\"\n return this.root.dayjs(day).format(`MMMM D, YYYY`)\n }\n buildTxt() {\n return this.day\n }\nprintFormatLinksParser\n description Prints links to other formats.\n extends abstractPrintMetaParser\n example\n printFormatLinks\n javascript\n buildHtml() {\n const permalink = this.root.permalink.replace(\".html\", \"\")\n // hacky\n const particle = this.appendSibling(`HTML | TXT`, `class printDateParser\\nlink ${permalink}.html HTML\\nlink ${permalink}.txt TXT\\nstyle text-align:center;`)\n const html = particle.buildHtml()\n particle.destroy()\n return html\n }\n buildTxt() {\n const permalink = this.root.permalink.replace(\".html\", \"\")\n return `HTML | TXT\\n link ${permalink}.html HTML\\n link ${permalink}.txt TXT`\n }\nabstractBuildCommandParser\n extends abstractScrollParser\n cueFromId\n atoms buildCommandAtom\n catchAllAtomType filePathAtom\n inScope slashCommentParser\n javascript\n isTopMatter = true\n buildHtml() {\n return \"\"\n }\n get extension() {\n return this.cue.replace(\"build\", \"\")\n }\n buildOutput() {\n return this.root.compileTo(this.extension)\n }\n get outputFileNames() {\n return this.content?.split(\" \") || [this.root.permalink.replace(\".html\", \".\" + this.extension.toLowerCase())]\n }\n async _buildFileType(extension, options) {\n const {root} = this\n const { fileSystem, folderPath, filename, filePath, path, lodash } = root\n const capitalized = lodash.capitalize(extension)\n const buildKeyword = \"build\" + capitalized\n const {outputFileNames} = this\n for (let name of outputFileNames) {\n try {\n await fileSystem.writeProduct(path.join(folderPath, name), root.compileTo(capitalized))\n root.log(`💾 Built ${name} from ${filename}`)\n } catch (err) {\n console.error(`Error while building '${filePath}' with extension '${extension}'`)\n throw err\n }\n }\n }\nabstractBuildOneCommandParser\n // buildOne and buildTwo are just a dumb/temporary way to have CSVs/JSONs/TSVs build first. Will be merged at some point.\n extends abstractBuildCommandParser\n javascript\n async buildOne(options) { await this._buildFileType(this.extension, options) }\nbuildParsersParser\n popularity 0.000096\n description Compile to Parsers file.\n extends abstractBuildOneCommandParser\nbuildCsvParser\n popularity 0.000096\n example\n buildCsv\n description Compile to CSV file.\n extends abstractBuildOneCommandParser\nbuildTsvParser\n popularity 0.000096\n description Compile to TSV file.\n extends abstractBuildOneCommandParser\nbuildJsonParser\n popularity 0.000096\n description Compile to JSON file.\n extends abstractBuildOneCommandParser\nabstractBuildTwoCommandParser\n extends abstractBuildCommandParser\n javascript\n async buildTwo(options) {\n await this._buildFileType(this.extension, options)\n }\nbuildCssParser\n popularity 0.000048\n description Compile to CSS file.\n extends abstractBuildTwoCommandParser\n example\n buildCss\nbuildHtmlParser\n popularity 0.007645\n description Compile to HTML file.\n extends abstractBuildTwoCommandParser\n boolean isPopular true\n javascript\n async buildTwo(options) {\n await this._copyExternalFiles(options)\n await super.buildTwo(options)\n }\n async _copyExternalFiles(options) {\n if (!this.isNodeJs()) return\n const {root} = this\n const externalFilesCopied = options.externalFilesCopied || {}\n // If this file uses a parser that has external requirements,\n // copy those from external folder into the destination folder.\n const { parsersRequiringExternals, folderPath, fileSystem, filename, parserIdIndex, path, Disk, externalsPath } = root\n if (!externalFilesCopied[folderPath]) externalFilesCopied[folderPath] = {}\n parsersRequiringExternals.forEach(parserId => {\n if (externalFilesCopied[folderPath][parserId]) return\n if (!parserIdIndex[parserId]) return\n parserIdIndex[parserId].map(particle => {\n const externalFiles = particle.copyFromExternal.split(\" \")\n externalFiles.forEach(name => {\n const newPath = path.join(folderPath, name)\n fileSystem.writeProduct(newPath, Disk.read(path.join(externalsPath, name)))\n root.log(`💾 Copied external file needed by ${filename} to ${name}`)\n })\n })\n if (parserId !== \"scrollThemeParser\")\n // todo: generalize when not to cache\n externalFilesCopied[folderPath][parserId] = true\n })\n }\nbuildJsParser\n description Compile to JS file.\n extends abstractBuildTwoCommandParser\nbuildRssParser\n popularity 0.000048\n description Compile to RSS file.\n extends abstractBuildTwoCommandParser\nbuildTxtParser\n popularity 0.007596\n description Compile to TXT file.\n extends abstractBuildTwoCommandParser\n boolean isPopular true\nloadConceptsParser\n // todo: clean this up. just add smarter imports with globs?\n // this currently removes any \"import\" statements.\n description Import all concepts in a folder.\n extends abstractBuildCommandParser\n cueFromId\n atoms preBuildCommandAtom filePathAtom\n javascript\n async load() {\n const { Disk, path, importRegex } = this.root\n const folder = path.join(this.root.folderPath, this.getAtom(1))\n const ONE_BIG_FILE = Disk.getFiles(folder).filter(file => file.endsWith(\".scroll\")).map(Disk.read).join(\"\\n\\n\").replace(importRegex, \"\")\n this.parent.concat(ONE_BIG_FILE)\n //console.log(ONE_BIG_FILE)\n }\n buildHtml() {\n return \"\"\n }\nbuildConceptsParser\n popularity 0.000024\n cueFromId\n description Compile concepts to delimited files.\n extends abstractBuildCommandParser\n sortByParser\n cueFromId\n atoms cueAtom columnNameAtom\n javascript\n async buildOne() {\n const {root} = this\n const { fileSystem, folderPath, filename, path, permalink } = root\n const files = this.getAtomsFrom(1)\n if (!files.length) files.push(permalink.replace(\".html\", \".csv\"))\n const sortBy = this.get(\"sortBy\")\n for (let link of files) {\n await fileSystem.writeProduct(path.join(folderPath, link), root.compileConcepts(link, sortBy))\n root.log(`💾 Built concepts in ${filename} to ${link}`)\n }\n }\nfetchParser\n description Download URL to disk.\n extends abstractBuildCommandParser\n cueFromId\n atoms preBuildCommandAtom urlAtom\n example\n fetch https://breckyunits.com/posts.csv\n fetch https://breckyunits.com/posts.csv renamed.csv\n javascript\n get url() {\n return this.getAtom(1)\n }\n get filename() {\n return this.getAtom(2)\n }\n async load() {\n await this.root.fetch(this.url, this.filename)\n }\n buildHtml() {\n return \"\"\n }\nbuildMeasuresParser\n popularity 0.000024\n cueFromId\n description Compile measures to delimited files.\n extends abstractBuildCommandParser\n sortByParser\n cueFromId\n atoms cueAtom columnNameAtom\n javascript\n async buildOne() {\n const {root} = this\n const { fileSystem, folderPath, filename, path, permalink } = root\n const files = this.getAtomsFrom(1)\n if (!files.length) files.push(permalink.replace(\".html\", \".csv\"))\n const sortBy = this.get(\"sortBy\")\n for (let link of files) {\n await fileSystem.writeProduct(path.join(folderPath, link), root.compileMeasures(link, sortBy))\n root.log(`💾 Built measures in ${filename} to ${link}`)\n }\n }\nbuildPdfParser\n popularity 0.000096\n description Compile to PDF file.\n extends abstractBuildCommandParser\n javascript\n async buildTwo(options) {\n if (!this.isNodeJs()) return \"Only works in Node currently.\"\n const {root} = this\n const { filename } = root\n const outputFile = root.filenameNoExtension + \".pdf\"\n // relevant source code for chrome: https://github.com/chromium/chromium/blob/a56ef4a02086c6c09770446733700312c86f7623/components/headless/command_handler/headless_command_switches.cc#L22\n const command = `/Applications/Google\\\\ Chrome.app/Contents/MacOS/Google\\\\ Chrome --headless --disable-gpu --no-pdf-header-footer --default-background-color=00000000 --no-pdf-background --print-to-pdf=\"${outputFile}\" \"${root.permalink}\"`\n // console.log(`Node.js is running on architecture: ${process.arch}`)\n try {\n const output = require(\"child_process\").execSync(command, { stdio: \"ignore\" })\n root.log(`💾 Built ${outputFile} from ${filename}`)\n } catch (error) {\n console.error(error)\n }\n }\nabstractInlineFileParser\n extends abstractScrollParser\n catchAllAtomType filePathAtom\n catchAllParser scrollFileAddressParser\n string joinChar ;\\n\\n\n string htmlTag script\n javascript\n get files() {\n const inline = this.atoms.slice(1)\n const children = this.map(particle => particle.cue)\n return inline.concat(children)\n }\n get contents() {\n return this.files.map(filename => this.root.readFile(filename)).join(this.joinChar)\n }\n buildHtml() {\n return `<${this.htmlTag}>/* ${this.files.join(\" \")} */\\n${this.contents}</${this.htmlTag}>`\n }\nscrollInlineCssParser\n description Inline CSS from files.\n popularity 0.007211\n extends abstractInlineFileParser\n cue inlineCss\n string joinChar \\n\\n\n string htmlTag style\n javascript\n buildCss() {\n return this.contents\n }\nscrollInlineJsParser\n description Inline JS from files.\n popularity 0.007211\n extends abstractInlineFileParser\n cue inlineJs\n javascript\n buildJs() {\n return this.contents\n }\nabstractTopLevelSingleMetaParser\n description Use these parsers once per file.\n extends abstractScrollParser\n inScope slashCommentParser\n cueFromId\n atoms metaCommandAtom\n javascript\n isTopMatter = true\n isSetterParser = true\n buildHtml() {\n return \"\"\n }\ntestStrictParser\n description Make catchAllParagraphParser = error.\n extends abstractTopLevelSingleMetaParser\nscrollDateParser\n cue date\n popularity 0.006680\n catchAllAtomType dateAtom\n description Set published date.\n extends abstractTopLevelSingleMetaParser\n boolean isPopular true\n example\n date 1/11/2019\n printDate\n Hello world\n dateline\nabstractUrlSettingParser\n extends abstractTopLevelSingleMetaParser\n atoms metaCommandAtom urlAtom\n cueFromId\neditBaseUrlParser\n popularity 0.007838\n description Override edit link baseUrl.\n extends abstractUrlSettingParser\ncanonicalUrlParser\n description Override canonical URL.\n extends abstractUrlSettingParser\nopenGraphImageParser\n popularity 0.000796\n // https://ogp.me/\n // If not defined, Scroll will try to generate it's own using the first image tag on your page.\n description Override Open Graph Image.\n extends abstractUrlSettingParser\nbaseUrlParser\n popularity 0.009188\n description Required for RSS and OpenGraph.\n extends abstractUrlSettingParser\n example\n baseUrl https://hub.scroll.pub/\nrssFeedUrlParser\n popularity 0.008850\n description Set RSS feed URL.\n extends abstractUrlSettingParser\neditUrlParser\n catchAllAtomType urlAtom\n description Override edit link.\n extends abstractTopLevelSingleMetaParser\nsiteOwnerEmailParser\n popularity 0.001302\n description Set email address for site contact.\n extends abstractTopLevelSingleMetaParser\n cue email\n atoms metaCommandAtom emailAddressAtom\nfaviconParser\n popularity 0.001688\n catchAllAtomType stringAtom\n cue favicon\n description Favicon file.\n example\n favicon logo.png\n metatags\n buildHtml\n extends abstractTopLevelSingleMetaParser\nimportOnlyParser\n popularity 0.033569\n // This line will be not be imported into the importing file.\n description Don't build this file.\n cueFromId\n atoms preBuildCommandAtom\n extends abstractTopLevelSingleMetaParser\n javascript\n buildHtml() {\n return \"\"\n }\ninlineMarkupsParser\n popularity 0.000024\n description Set global inline markups.\n extends abstractTopLevelSingleMetaParser\n cueFromId\n example\n inlineMarkups\n * \n // Disable * for bold\n _ u\n // Make _ underline\nhtmlLangParser\n atoms metaCommandAtom stringAtom\n // for the <html lang=\"\"> tag. If not specified will be \"en\". See https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang\n description Override HTML lang attribute.\n extends abstractTopLevelSingleMetaParser\nopenGraphDescriptionParser\n popularity 0.001688\n catchAllAtomType stringAtom\n cue description\n description Description for SEO meta tag.\n extends abstractTopLevelSingleMetaParser\nopenGraphKeywordsParser\n popularity 0.001688\n catchAllAtomType stringAtom\n cue keywords\n description Keywords for SEO meta tag.\n extends abstractTopLevelSingleMetaParser\npermalinkParser\n popularity 0.000265\n description Override output filename.\n extends abstractTopLevelSingleMetaParser\n atoms metaCommandAtom permalinkAtom\nscrollTagsParser\n popularity 0.006801\n cue tags\n description Set tags.\n example\n tags All\n extends abstractTopLevelSingleMetaParser\n catchAllAtomType tagAtom\nscrollTitleParser\n popularity 0.007524\n catchAllAtomType stringAtom\n cue title\n description Set title.\n example\n title Eureka\n printTitle\n extends abstractTopLevelSingleMetaParser\n boolean isPopular true\nscrollLinkTitleParser\n popularity 0.007524\n catchAllAtomType stringAtom\n cue linkTitle\n description Text for links.\n example\n title My blog - Eureka\n linkTitle Eureka\n extends abstractTopLevelSingleMetaParser\nscrollChatParser\n popularity 0.000362\n description A faux text chat conversation.\n catchAllParser chatLineParser\n cue chat\n extends abstractScrollParser\n example\n chat\n Hi\n 👋\n javascript\n buildHtml() {\n return this.map((line, index) => line.asString ? `<div style=\"text-align: ${index % 2 ? \"right\" : \"left\"};\" class=\"scrollChat ${index % 2 ? \"scrollChatRight\" : \"scrollChatLeft\"}\"><span>${line.asString}</span></div>` : \"\").join(\"\")\n }\n buildTxt() {\n return this.subparticlesToString()\n }\nabstractDatatableProviderParser\n description A datatable.\n extends abstractScrollParser\n inScope scrollTableDataParser scrollTableDelimiterParser abstractTableVisualizationParser abstractTableTransformParser h1Parser h2Parser scrollQuestionParser htmlInlineParser scrollBrParser slashCommentParser\n javascript\n get visualizations() {\n return this.topDownArray.filter(particle => particle.isTableVisualization || particle.isHeader || particle.isHtml)\n }\n buildHtml(buildSettings) {\n return this.visualizations.map(particle => particle.buildHtml(buildSettings))\n .join(\"\\n\")\n .trim()\n }\n buildTxt() {\n return this.visualizations.map(particle => particle.buildTxt())\n .join(\"\\n\")\n .trim()\n }\n _coreTable\n get coreTable() {\n if (this._coreTable) return this._coreTable\n const {delimiter, delimitedData} = this\n return []\n }\n get columnNames() {\n return []\n }\nscrollTableParser\n extends abstractDatatableProviderParser\n popularity 0.002133\n cue table\n example\n table\n printTable\n data\n year,count\n 1900,10\n 2000,122\n 2020,23\n catchAllAtomType filePathAtom\n int atomIndex 1\n javascript\n get delimiter() {\n const {filename} = this\n let delimiter = \"\"\n if (filename) {\n const extension = filename.split('?')[0].split(\".\").pop()\n if (extension === \"json\") delimiter = \"json\"\n if (extension === \"particles\") delimiter = \"particles\"\n if (extension === \"csv\") delimiter = \",\"\n if (extension === \"tsv\") delimiter = \"\\t\"\n if (extension === \"ssv\") delimiter = \" \"\n if (extension === \"psv\") delimiter = \"|\"\n }\n if (this.get(\"delimiter\"))\n delimiter = this.get(\"delimiter\")\n else if (!delimiter) {\n const header = this.delimitedData.split(\"\\n\")[0]\n if (header.includes(\"\\t\"))\n delimiter = \"\\t\"\n else if (header.includes(\",\"))\n delimiter = \",\"\n else\n delimiter = \" \"\n }\n return delimiter\n }\n get filename() {\n return this.getAtom(this.atomIndex)\n }\n get coreTable() {\n if (this._coreTable) return this._coreTable\n const {delimiter, delimitedData} = this\n if (delimiter === \"json\") {\n const obj = JSON.parse(delimitedData)\n let rows = []\n // Optimal case: Array of objects\n if (Array.isArray(obj)) { rows = obj}\n else if (!Array.isArray(obj) && typeof obj === \"object\") {\n // Case 2: Nested array under a key\n const arrayKey = Object.keys(obj).find(key => Array.isArray(obj[key]))\n if (arrayKey) rows = obj[arrayKey]\n }\n // Case 3: Array of primitive values\n else if (Array.isArray(obj) && obj.length && typeof obj[0] !== \"object\") {\n rows = obj.map(value => ({ value }))\n }\n this._columnNames = rows.length ? Object.keys(rows[0]) : []\n this._coreTable = rows\n return rows\n }\n else if (delimiter === \"particles\") {\n const d3lib = this.root.d3\n this._coreTable = d3lib.dsvFormat(\",\").parse(new Particle(delimitedData).asCsv, d3lib.autoType)\n } else {\n const d3lib = this.root.d3\n this._coreTable = d3lib.dsvFormat(delimiter).parse(delimitedData, d3lib.autoType)\n }\n this._columnNames = this._coreTable.columns\n delete this._coreTable.columns\n return this._coreTable\n }\n get columnNames() {\n // init coreTable to set columns\n const coreTable = this.coreTable\n return this._columnNames\n }\n async load() {\n if (this.filename)\n await this.root.fetch(this.filename)\n }\n get fileContent() {\n return this.root.readSyncFromFileOrUrl(this.filename)\n }\n get delimitedData() {\n // json csv tsv\n if (this.filename)\n return this.fileContent\n const dataParticle = this.getParticle(\"data\")\n if (dataParticle)\n return dataParticle.subparticlesToString()\n // if not dataparticle and no filename, check [permalink].csv\n if (this.isNodeJs())\n return this.root.readFile(this.root.permalink.replace(\".html\", \"\") + \".csv\")\n return \"\"\n }\nclocParser\n extends scrollTableParser\n description Output results of cloc as table.\n cue cloc\n string copyFromExternal .clocLangs.txt\n javascript\n delimiter = \",\"\n get delimitedData() {\n const { execSync } = require(\"child_process\")\n const results = execSync(this.command).toString().trim()\n const csv = results.split(\"\\n\\n\").pop().replace(/,\\\"github\\.com\\/AlDanial.+/, \"\") // cleanup output\n return csv\n }\n get command(){\n return `cloc --vcs git . --csv --read-lang-def=.clocLangs.txt ${this.content || \"\"}`\n }\nscrollDependenciesParser\n extends scrollTableParser\n description Get files this file depends on.\n cue dependencies\n javascript\n delimiter = \",\"\n get delimitedData() {\n return `file\\n` + this.root.dependencies.join(\"\\n\")\n }\nscrollDiskParser\n extends scrollTableParser\n description Output file into as table.\n cue disk\n javascript\n delimiter = \"json\"\n get delimitedData() {\n return this.isNodeJs() ? this.delimitedDataNodeJs : \"\"\n }\n get delimitedDataNodeJs() {\n const fs = require('fs');\n const path = require('path');\n const {folderPath} = this.root\n const folder = this.content ? path.join(folderPath, this.content) : folderPath\n function getDirectoryContents(dirPath) {\n const directoryContents = [];\n const items = fs.readdirSync(dirPath);\n items.forEach((item) => {\n const itemPath = path.join(dirPath, item);\n const stats = fs.statSync(itemPath);\n directoryContents.push({\n name: item,\n type: stats.isDirectory() ? 'directory' : 'file',\n size: stats.size,\n lastModified: stats.mtime\n });\n });\n return directoryContents;\n }\n return JSON.stringify(getDirectoryContents(folder))\n }\nscrollIrisParser\n extends scrollTableParser\n description Iris dataset from R.A. Fisher.\n cue iris\n example\n iris\n printTable\n scatter\n x SepalLength\n y SepalWidth\n javascript\n delimitedData = this.constructor.iris\nvegaSampleDataParser\n extends scrollTableParser\n description Sample dataset from Vega.\n cue sampleData\n atoms cueAtom vegaDataSetAtom\n example\n sampleData zipcodes.csv\n printTable\n javascript\n get filename() {\n return \"https://ohayo.scroll.pub/ohayo/packages/vega/datasets/\" + this.content\n }\nquickTableParser\n popularity 0.000024\n extends scrollTableParser\n atoms urlAtom\n pattern ^[^\\s]+\\.(tsv|csv|ssv|psv|json)[^\\s]*$\n int atomIndex 0\n javascript\n get dependencies() { return [this.cue]}\nscrollConceptsParser\n description Load concepts as table.\n extends abstractDatatableProviderParser\n cue concepts\n atoms cueAtom\n example\n concepts\n printTable\n javascript\n get coreTable() {\n return this.root.concepts\n }\n get columnNames() {\n return this.root.measures.map(col => col.Name)\n }\nabstractPostsParser\n description Load posts as table.\n extends abstractDatatableProviderParser\n cueFromId\n atoms cueAtom\n catchAllAtomType tagWithOptionalFolderAtom\n javascript\n async load() {\n const dependsOn = this.tags.map(tag => this.root.parseNestedTag(tag)).filter(i => i).map(i => i.folderPath)\n const {fileSystem} = this.root\n for (let folderPath of dependsOn) {\n // console.log(`${this.root.filePath} is loading: ${folderPath} in id '${fileSystem.fusionId}'`)\n await fileSystem.getLoadedFilesInFolder(folderPath, \".scroll\")\n }\n }\n get tags() {\n return this.content?.split(\" \") || []\n }\n get files() {\n const thisFile = this.root.file\n // todo: we can include this file, but just not run asTxt\n const files = this.root.getFilesByTags(this.tags).filter(file => file.file !== thisFile)\n return files\n }\n get coreTable() {\n if (this._coreTable) return this._coreTable\n this._coreTable = this.files.map(file => this.postToRow(file))\n return this._coreTable\n }\n postToRow(file) {\n const {relativePath} = file\n const {scrollProgram} = file.file\n const {title, permalink, asTxt, date, wordCount, minutes} = scrollProgram\n const text = asTxt.replace(/(\\t|\\n)/g, \" \").replace(/</g, \"&lt;\")\n return {\n title, titleLink: relativePath + permalink, text, date, wordCount, minutes\n }\n }\n columnNames = \"title titleLink text date wordCount minutes\".split(\" \")\nscrollPostsParser\n popularity 0.000024\n cue posts\n description Posts as table.\n extends abstractPostsParser\n example\n // Print a search table:\n posts\n printTable\n tableSearch\n // Dump a CSV of blog:\n buildHtml\n buildCsv\n buildJson\nscrollPostsMetaParser\n popularity 0.000024\n cue postsMeta\n description Post meta as table.\n extends abstractPostsParser\n javascript\n columnNames = [\"date\", \"year\", \"title\", \"permalink\", \"authors\", \"tags\", \"wordCount\", \"minutes\"]\n postToRow(file) {\n const {date, year, title, permalink, authors, tags, wordCount, minutes} = file.file.scrollProgram\n return {\n date, year, title, permalink, authors, tags, wordCount, minutes\n }\n }\nprintFeedParser\n popularity 0.000048\n description Print group to RSS.\n extends abstractPostsParser\n example\n printFeed index\n printFeed cars/index\n buildRss\n javascript\n buildRss() {\n const {dayjs} = this.root\n const scrollPrograms = this.files.map(file => file.file.scrollProgram)\n const { title, baseUrl, description } = this.root\n return `<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n <rss version=\"2.0\">\n <channel>\n <title>${title}</title>\n <link>${baseUrl}</link>\n <description>${description}</description>\n <lastBuildDate>${dayjs().format(\"ddd, DD MMM YYYY HH:mm:ss ZZ\")}</lastBuildDate>\n <language>en-us</language>\n ${scrollPrograms.map(program => program.toRss()).join(\"\\n\")}\n </channel>\n </rss>`\n }\n buildTxt() {\n return this.buildRss()\n }\nprintSourceParser\n popularity 0.000024\n description Print source for files in group(s).\n extends printFeedParser\n example\n printSource index\n buildTxt source.txt\n javascript\n buildHtml() {\n const files = this.root.getFilesByTags(this.content).map(file => file.file)\n return `${files.map(file => file.filePath + \"\\n \" + file.codeAtStart.replace(/\\n/g, \"\\n \") ).join(\"\\n\")}`\n }\nprintSiteMapParser\n popularity 0.000072\n extends abstractPostsParser\n description Print text sitemap.\n example\n baseUrl http://test.com\n printSiteMap\n javascript\n buildHtml() {\n const { baseUrl } = this.root\n return this.files.map(file => baseUrl + file.relativePath + file.file.scrollProgram.permalink).join(\"\\n\")\n }\n buildTxt() {\n return this.buildHtml()\n }\n get dependencies() { return this.files}\ncodeParser\n popularity 0.001929\n description A code block.\n catchAllParser lineOfCodeParser\n extends abstractScrollParser\n boolean isPopular true\n example\n code\n two = 1 + 1\n javascript\n buildHtml() {\n return `<code class=\"scrollCodeBlock\">${this.code.replace(/\\</g, \"&lt;\")}</code>`\n }\n buildTxt() {\n return \"```\\n\" + this.code + \"\\n```\"\n }\n get code() {\n return this.subparticlesToString()\n }\n cueFromId\ncodeWithHeaderParser\n popularity 0.000169\n cueFromId\n catchAllAtomType stringAtom\n extends codeParser\n example\n codeWithHeader math.py\n two = 1 + 1\n javascript\n buildHtml() {\n return `<div class=\"codeWithHeader\"><div class=\"codeHeader\">${this.content}</div>${super.buildHtml()}</div>`\n }\n buildTxt() {\n return \"```\" + this.content + \"\\n\" + this.code + \"\\n```\"\n }\ncodeFromFileParser\n popularity 0.000169\n cueFromId\n atoms cueAtom urlAtom\n extends codeWithHeaderParser\n example\n codeFromFile math.py\n javascript\n get code() {\n return this.root.readSyncFromFileOrUrl(this.content)\n }\ncodeWithLanguageParser\n popularity 0.000458\n description Use this to specify the language of the code block, such as csvCode or rustCode.\n extends codeParser\n pattern ^[a-zA-Z0-9_]+Code$\ndebugParsersParser\n description Print the parsers used.\n extends codeParser\n cueFromId\n javascript\n buildParsers() { return this.code}\n get code() {\n let code = new Particle(this.root.definition.toString())\n // Remove comments\n code.filter((line) => line.getLine().startsWith(\"//\")).forEach((particle) => particle.destroy())\n // Remove blank lines\n code = code.toString().replace(/^\\n/gm, \"\")\n return code\n }\nabstractScrollWithRequirementsParser\n extends abstractScrollParser\n cueFromId\n javascript\n buildHtml(buildSettings) {\n return this.getHtmlRequirements(buildSettings) + this.buildInstance()\n }\ncopyButtonsParser\n popularity 0.001471\n extends abstractScrollWithRequirementsParser\n description Copy code widget.\n javascript\n buildInstance() {\n return \"\"\n }\n string requireOnce\n <script>\n document.addEventListener(\"DOMContentLoaded\", () => document.querySelectorAll(\".scrollCodeBlock\").forEach(block =>\n {\n if (!navigator.clipboard) return\n const button = document.createElement(\"span\")\n button.classList.add(\"scrollCopyButton\")\n block.appendChild(button)\n button.addEventListener(\"click\", async () => {\n await navigator.clipboard.writeText(block.innerText)\n button.classList.add(\"scrollCopiedButton\")\n })\n }\n ))\n </script>\nabstractTableVisualizationParser\n extends abstractScrollWithRequirementsParser\n boolean isTableVisualization true\n javascript\n get columnNames() {\n return this.parent.columnNames\n }\nheatrixParser\n cueFromId\n example\n heatrix\n '2007 '2008 '2009 '2010 '2011 '2012 '2013 '2014 '2015 '2016 '2017 '2018 '2019 '2020 '2021 '2022 '2023 '2024\n 4 11 23 37 3 14 12 0 0 0 5 1 2 11 15 10 12 56\n description A heatmap matrix data visualization.\n catchAllParser heatrixCatchAllParser\n extends abstractTableVisualizationParser\n javascript\n buildHtml() {\n // A hacky but simple way to do this for now.\n const advanced = new Particle(\"heatrixAdvanced\")\n advanced.appendLineAndSubparticles(\"table\", \"\\n \" + this.tableData.replace(/\\n/g, \"\\n \"))\n const particle = this.appendSibling(\"heatrixAdvanced\", advanced.subparticlesToString())\n const html = particle.buildHtml()\n particle.destroy()\n return html\n }\n get tableData() {\n const {coreTable} = this.parent\n if (!coreTable)\n return this.subparticlesToString()\n let table = new Particle(coreTable).asSsv\n if (this.parent.cue === \"transpose\") {\n // drop first line after transpose\n const lines = table.split(\"\\n\")\n lines.shift()\n table = lines.join(\"\\n\")\n }\n // detect years and make strings\n const lines = table.split(\"\\n\")\n const yearLine = / \\d{4}(\\s+\\d{4})+$/\n if (yearLine.test(lines[0])) {\n lines[0] = lines[0].replace(/ /g, \" '\")\n table = lines.join(\"\\n\")\n }\n return table\n }\nheatrixAdvancedParser\n popularity 0.000048\n cueFromId\n catchAllParser heatrixCatchAllParser\n extends abstractTableVisualizationParser\n description Advanced heatrix.\n example\n heatrix\n table\n \n %h10; '2007 '2008 '2009\n 12 4 323\n scale\n #ebedf0 0\n #c7e9c0 100\n #a1d99b 400\n #74c476 1600\n javascript\n buildHtml() {\n class Heatrix {\n static HeatrixId = 0\n uid = Heatrix.HeatrixId++\n constructor(program) {\n const isDirective = atom => /^(f|l|w|h)\\d+$/.test(atom) || atom === \"right\" || atom === \"left\" || atom.startsWith(\"http://\") || atom.startsWith(\"https://\") || atom.endsWith(\".html\")\n const particle = new Particle(program)\n this.program = particle\n const generateColorBinningString = (data, colors) => {\n const sortedData = [...data].sort((a, b) => a - b);\n const n = sortedData.length;\n const numBins = colors.length;\n // Calculate the indices for each quantile\n const indices = [];\n for (let i = 1; i < numBins; i++) {\n indices.push(Math.floor((i / numBins) * n));\n }\n // Get the quantile values and round them\n const thresholds = indices.map(index => Math.round(sortedData[index]));\n // Generate the string\n let result = '';\n colors.forEach((color, index) => {\n const threshold = index === colors.length - 1 ? thresholds[index - 1] * 2 : thresholds[index];\n result += `${color} ${threshold}\\n`;\n });\n return result.trim();\n }\n const buildScale = (table) => {\n const numbers = table.split(\"\\n\").map(line => line.split(\" \")).flat().filter(atom => !isDirective(atom)).map(atom => parseFloat(atom)).filter(number => !isNaN(number))\n const colors = ['#ebedf0', '#c7e9c0', '#a1d99b', '#74c476', '#41ab5d', '#238b45', '#005a32'];\n numbers.unshift(0)\n return generateColorBinningString(numbers, colors);\n }\n const table = particle.getParticle(\"table\").subparticlesToString()\n const scale = particle.getParticle(\"scale\")?.subparticlesToString() || buildScale(table)\n const thresholds = []\n const colors = []\n scale.split(\"\\n\").map((line) => {\n const parts = line.split(\" \")\n thresholds.push(parseFloat(parts[1]))\n colors.push(parts[0])\n })\n const colorCount = colors.length\n const colorFunction = (value) => {\n if (isNaN(value)) return \"\" // #ebedf0\n for (let index = 0; index < colorCount; index++) {\n const threshold = thresholds[index]\n if (value <= threshold) return colors[index]\n }\n return colors[colorCount - 1]\n }\n const directiveDelimiter = \";\"\n const getSize = (directives, letter) =>\n directives\n .filter((directive) => directive.startsWith(letter))\n .map((dir) => dir.replace(letter, \"\") + \"px\")[0] ?? \"\"\n this.table = table.split(\"\\n\").map((line) =>\n line\n .trimEnd()\n .split(\" \")\n .map((atom) => {\n const atoms = atom.split(directiveDelimiter).filter((atom) => !isDirective(atom)).join(\"\")\n const directivesInThisAtom = atom\n .split(directiveDelimiter)\n .filter(isDirective)\n const value = parseFloat(atoms)\n const label = atoms.includes(\"'\") ? atoms.split(\"'\")[1] : atoms\n const alignment = directivesInThisAtom.includes(\"right\")\n ? \"right\"\n : directivesInThisAtom.includes(\"left\")\n ? \"left\"\n : \"\"\n const color = colorFunction(value)\n const width = getSize(directivesInThisAtom, \"w\")\n const height = getSize(directivesInThisAtom, \"h\")\n const fontSize = getSize(directivesInThisAtom, \"f\")\n const lineHeight = getSize(directivesInThisAtom, \"l\") || height\n const link = directivesInThisAtom.filter(i => i.startsWith(\"http\") || i.endsWith(\".html\"))[0]\n const style = {\n \"background-color\": color,\n width,\n height,\n \"font-size\": fontSize,\n \"line-height\": lineHeight,\n \"text-align\": alignment,\n }\n Object.keys(style).filter(key => !style[key]).forEach((key) => delete style[key])\n return {\n value,\n label,\n style,\n link,\n }\n })\n )\n }\n get html() {\n const { program } = this\n const cssId = `#heatrix${this.uid}`\n const defaultWidth = \"40px\"\n const defaultHeight = \"40px\"\n const fontSize = \"10px\"\n const lineHeight = defaultHeight\n const style = `<style>\n .heatrixContainer {\n margin: auto;\n }.heatrixRow {white-space: nowrap;}\n ${cssId} .heatrixAtom {\n font-family: arial;\n border-radius: 2px;\n border: 1px solid transparent;\n display: inline-block;\n margin: 1px;\n text-align: center;\n vertical-align: middle;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n .heatrixAtom a {\n color: black;\n }\n ${cssId} .heatrixAtom{\n width: ${defaultWidth};\n height: ${defaultHeight};\n font-size: ${fontSize};\n line-height: ${lineHeight};\n }\n </style>`\n const firstRow = this.table[0]\n return (\n `<div class=\"heatrixContainer\" id=\"heatrix${this.uid}\">${style}` +\n this.table\n .map((row, rowIndex) => {\n if (!rowIndex) return \"\"\n const rowStyle = row[0].style\n return `<div class=\"heatrixRow heatrixRow${rowIndex}\">${row\n .map((atom, columnIndex) => {\n if (!columnIndex) return \"\"\n const columnStyle = firstRow[columnIndex]?.style || {}\n let { value, label, style, link } = atom\n const extendedStyle = Object.assign(\n {},\n rowStyle,\n columnStyle,\n style\n )\n const inlineStyle = Object.keys(extendedStyle)\n .map((key) => `${key}:${extendedStyle[key]};`)\n .join(\"\")\n let valueClass = value ? \" valueAtom\" : \"\"\n const href = link ? ` href=\"${link}\"` : \"\"\n return `<div class=\"heatrixAtom heatrixColumn${columnIndex}${valueClass}\" style=\"${inlineStyle}\"><a title=\"${label}\" ${href}>${label}</a></div>`\n })\n .join(\"\")}</div>`\n })\n .join(\"\\n\") +\n \"</div>\"\n ).replace(/\\n/g, \"\")\n }\n }\n return new Heatrix(this.subparticlesToString().trim()).html\n }\nmapParser\n latParser\n atoms cueAtom floatAtom\n cueFromId\n single\n longParser\n atoms cueAtom floatAtom\n cueFromId\n single\n tilesParser\n atoms cueAtom tileOptionAtom\n cueFromId\n single\n zoomParser\n atoms cueAtom integerAtom\n cueFromId\n single\n geolocateParser\n description Geolocate user.\n atoms cueAtom\n cueFromId\n single\n radiusParser\n atoms cueAtom floatAtom\n cueFromId\n single\n fillOpacityParser\n atoms cueAtom floatAtom\n cueFromId\n single\n fillColorParser\n atoms cueAtom colorAtom\n cueFromId\n single\n colorParser\n atoms cueAtom colorAtom\n cueFromId\n single\n heightParser\n atoms cueAtom floatAtom\n cueFromId\n single\n hoverParser\n atoms cueAtom\n catchAllAtomType colorAtom\n cueFromId\n single\n extends abstractTableVisualizationParser\n description Map widget.\n string copyFromExternal .leaflet.css .leaflet.js .scrollLibs.js\n string requireOnce\n <link rel=\"stylesheet\" href=\".leaflet.css\">\n <script src=\".leaflet.js\"></script>\n <script src=\".scrollLibs.js\"></script>\n javascript\n buildInstance() {\n const height = this.get(\"height\") || 500\n const id = this._getUid()\n const obj = this.toObject()\n const template = {}\n const style = height !== \"full\" ? `height: ${height}px;` : `height: 100%; position: fixed; z-index: -1; left: 0; top: 0; width: 100%;`\n const strs = [\"color\", \"fillColor\"]\n const nums = [\"radius\", \"fillOpacity\"]\n strs.filter(i => obj[i]).forEach(i => template[i] = obj[i])\n nums.filter(i => obj[i]).forEach(i => template[i] = parseFloat(obj[i]))\n const mapId = `map${id}`\n return `<div id=\"${mapId}\" style=\"${style}\"></div>\n <script>\n {\n if (!window.maps) window.maps = {}\n const moveToMyLocation = () => {\n if (!navigator.geolocation) return\n navigator.geolocation.getCurrentPosition((position) => {\n const { latitude, longitude } = position.coords\n window.maps.${mapId}.setView([latitude, longitude])\n L.circleMarker([latitude, longitude], {\n fillOpacity: 0.8,\n radius: 20,\n weight: 4\n })\n .addTo(window.maps.${mapId})\n }, () => {})\n }\n const lat = ${this.get(\"lat\") ?? 37.8}\n const long = ${this.get(\"long\") ?? 4}\n if (${this.has(\"geolocate\")}){\n moveToMyLocation()\n }\n const zoomLevel = ${this.get(\"zoom\") ?? 4}\n const hover = '${this.get(\"hover\") || \"<b>{title}</b><br>{description}\"}'\n const template = ${JSON.stringify(template)}\n const points = ${JSON.stringify((this.parent.coreTable || []).filter(point => point.lat && point.long), undefined, 2)}\n window.maps.${mapId} = L.map(\"map${id}\").setView([lat, long], zoomLevel)\n const map = window.maps.${mapId}\n const tileOptions = {\n \"default\": {\n baseLayer: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',\n attribution: '<a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors'\n },\n light: {\n baseLayer: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png',\n attribution: '<a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors <a href=\"https://carto.com/ attributions\">CARTO</a>'\n },\n }\n const {baseLayer, attribution} = tileOptions.${this.get(\"tiles\") || \"default\"}\n L.tileLayer(baseLayer, {\n attribution,\n maxZoom: 19\n }).addTo(map);\n points.forEach(point => {\n L.circleMarker([point.lat, point.long], {...template, ...Object.fromEntries(\n Object.entries(point).filter(([key, value]) => value !== null)\n )})\n .addTo(map)\n .bindPopup(new Particle(point).evalTemplateString(hover))\n })\n }\n </script>`\n }\nabstractPlotParser\n // Observablehq\n extends abstractTableVisualizationParser\n string copyFromExternal .d3.js .plot.js\n string requireOnce\n <script src=\".d3.js\"></script>\n <script src=\".plot.js\"></script>\n example\n plot\n inScope abstractColumnNameParser\n widthParser\n cueFromId\n atoms cueAtom integerAtom\n heightParser\n cueFromId\n atoms cueAtom integerAtom\n titleParser\n extends abstractPlotLabelParser\n subtitleParser\n extends abstractPlotLabelParser\n captionParser\n extends abstractPlotLabelParser\n javascript\n buildInstance() {\n const id = \"plot\" + this._getUid()\n return `<div id=\"${id}\"></div><script>\n {\n let loadChart = async () => {\n const data = ${this.dataCode}\n const get = (col, index ) => col !== \"undefined\" ? col : (index === undefined ? undefined : Object.keys(data[0])[index])\n document.querySelector(\"#${id}\").append(Plot.plot(${this.plotOptions}))\n }\n loadChart()\n }\n </script>`\n }\n get sortExpression() {\n const sort = this.get(\"sort\")\n if (!sort) return \"\"\n let sort_expr = \"\"\n if (sort.startsWith(\"-\")) {\n // Sort by a value descending\n const sortCol = sort.slice(1)\n sort_expr = `, sort: {x: \"y\", reverse: true}`\n } else if (sort.includes(\" \")) {\n // Fixed order specified\n const order = sort.split(\" \")\n sort_expr = `, sort: {x: (a,b) => {\n const order = ${JSON.stringify(order)};\n return order.indexOf(a) - order.indexOf(b)\n }}`\n } else if (sort === \"asc\") {\n sort_expr = `, sort: {x: \"x\"}`\n } else if (sort === \"desc\") {\n sort_expr = `, sort: {x: \"x\", reverse: true}`\n }\n return sort_expr\n }\n get marks() {\n // just for testing purposes\n return `Plot.rectY({length: 10000}, Plot.binX({y: \"count\"}, {x: d3.randomNormal()}))`\n }\n get dataCode() {\n const {coreTable} = this.parent\n return `d3.csvParse(\\`${new Particle(coreTable).asCsv}\\`, d3.autoType)`\n }\n get plotOptions() {\n return `{\n title: \"${this.get(\"title\") || \"\"}\",\n subtitle: \"${this.get(\"subtitle\") || \"\"}\",\n caption: \"${this.get(\"caption\") || \"\"}\",\n symbol: {legend: ${this.has(\"symbol\")}},\n color: {legend: ${this.has(\"fill\") || this.has(\"stroke\")}},\n grid: ${this.get(\"grid\") !== \"false\"},\n marks: [${this.marks}],\n width: ${this.get(\"width\") || 640},\n height: ${this.get(\"height\") || 400},\n }`\n }\nplotScatterplotParser\n cue scatterplot\n extends abstractPlotParser\n description Scatterplot Widget.\n example\n iris\n scatterplot\n javascript\n get marks() {\n const x = this.get(\"x\")\n const y = this.get(\"y\")\n const text = this.get(\"label\")\n return `Plot.dot(data, {\n x: get(\"${x}\", 0),\n y: get(\"${y}\", 1),\n r: get(\"${this.get(\"radius\")}\"),\n fill: get(\"${this.get(\"fill\")}\"),\n tip: true${this.sortExpression},\n symbol: get(\"${this.get(\"symbol\")}\")} ), Plot.text(data, {x: get(\"${x}\",0), y: get(\"${y}\", 1), text: \"${text}\", dy: -6, lineAnchor: \"bottom\"})`\n }\nplotBarchartParser\n cue barchart\n extends abstractPlotParser\n description Bar chart widget.\n example\n iris\n barchart\n javascript\n get marks() {\n const x = this.get(\"x\")\n const y = this.get(\"y\")\n const text = this.get(\"label\")\n const fill = this.get(\"fill\")\n return `Plot.barY(data, {\n x: get(\"${x}\", 0),\n y: get(\"${y}\", 1),\n fill: get(\"${fill}\"),\n tip: true${this.sortExpression}\n }), Plot.ruleY([0])`\n }\nplotLineChartParser\n cue linechart\n extends abstractPlotParser\n description Line chart widget.\n example\n iris\n linechart\n x SepalLength\n y SepalWidth\n javascript\n get marks() {\n const x = this.get(\"x\")\n const y = this.get(\"y\")\n const stroke = this.get(\"stroke\") || \"steelblue\"\n const strokeWidth = this.get(\"strokeWidth\") || 2\n const strokeLinecap = this.get(\"strokeLinecap\") || \"round\"\n const fill = this.get(\"fill\")\n return `Plot.line(data, {\n x: get(\"${x}\", 0),\n y: get(\"${y}\", 1),\n stroke: \"${stroke}\",\n fill: get(\"${fill}\"),\n strokeWidth: ${strokeWidth},\n strokeLinecap: \"${strokeLinecap}\"${this.sortExpression}\n })`\n }\nsparklineParser\n popularity 0.000024\n description Sparkline widget.\n extends abstractTableVisualizationParser\n example\n sparkline 1 2 3 4 5\n string copyFromExternal .sparkline.js\n string requireOnce <script src=\".sparkline.js\"></script>\n catchAllAtomType numberAtom\n // we need pattern matching\n inScope scrollYParser\n javascript\n buildInstance() {\n const id = \"spark\" + this._getUid()\n const {columnValues} = this\n const start = this.has(\"start\") ? parseInt(this.get(\"start\")) : 0\n const width = this.get(\"width\") || 100\n const height = this.get(\"height\") || 30\n const lineColor = this.get(\"color\") || \"black\"\n return `<span id=\"${id}\"></span><script>new Sparkline(document.getElementById(\"${id}\"), {dotRadius: 0, width: ${width}, height: ${height}, lineColor: \"${lineColor}\", tooltip: (value,index) => ${start} + index + \": \" + value}).draw(${JSON.stringify(columnValues)})</script>`\n }\n get columnValues() {\n if (this.content)\n return this.content.split(\" \").map(str => parseFloat(str))\n const {coreTable} = this.parent\n if (coreTable) {\n const columnName = this.get(\"y\") || Object.keys(coreTable[0]).find(key => typeof coreTable[0][key] === 'number')\n return coreTable.map(row => row[columnName])\n }\n }\nprintColumnParser\n popularity 0.000024\n description Print one column\n extends abstractTableVisualizationParser\n example\n printColumn tags\n catchAllAtomType columnNameAtom\n joinParser\n boolean allowTrailingWhitespace true\n cueFromId\n atoms cueAtom\n catchAllAtomType stringAtom\n javascript\n buildHtml() {\n return this.columnValues.join(this.join)\n }\n buildTxt() {\n return this.columnValues.join(this.join)\n }\n get join() {\n return this.get(\"join\") || \"\\n\"\n }\n get columnName() {\n return this.atoms[1]\n }\n get columnValues() {\n return this.parent.coreTable.map(row => row[this.columnName])\n }\nprintTableParser\n popularity 0.001085\n cueFromId\n description Print table.\n extends abstractTableVisualizationParser\n javascript\n get tableHeader() {\n return this.columns.filter(col => !col.isLink).map(column => `<th>${column.name}</th>\\n`)\n }\n get columnNames() {\n return this.parent.columnNames\n }\n buildJson() {\n return JSON.stringify(this.coreTable, undefined, 2)\n }\n buildCsv() {\n return new Particle(this.coreTable).asCsv\n }\n buildTsv() {\n return new Particle(this.coreTable).asTsv\n }\n get columns() {\n const {columnNames} = this\n return columnNames.map((name, index) => {\n const isLink = name.endsWith(\"Link\")\n const linkIndex = columnNames.indexOf(name + \"Link\")\n return {\n name,\n isLink,\n linkIndex\n }\n })\n }\n toRow(row) {\n const {columns} = this\n const atoms = columns.map(col => row[col.name])\n let str = \"\"\n let column = 0\n const columnCount = columns.length\n while (column < columnCount) {\n const col = columns[column]\n column++\n const content = ((columnCount === column ? atoms.slice(columnCount - 1).join(\" \") : atoms[column - 1]) ?? \"\").toString()\n if (col.isLink) continue\n const isTimestamp = col.name.toLowerCase().includes(\"time\") && /^\\d{10}(\\d{3})?$/.test(content)\n const text = isTimestamp ? new Date(parseInt(content.length === 10 ? content * 1000 : content)).toLocaleString() : content\n let tagged = text\n const link = atoms[col.linkIndex]\n const isUrl = content.match(/^https?\\:[^ ]+$/)\n if (col.linkIndex > -1 && link) tagged = `<a href=\"${link}\">${text}</a>`\n else if (col.name.endsWith(\"Url\")) tagged = `<a href=\"${content}\">${col.name.replace(\"Url\", \"\")}</a>`\n else if (isUrl) tagged = `<a href=\"${content}\">${text}</a>`\n str += `<td>${tagged}</td>\\n`\n }\n return str\n }\n get coreTable() {\n return this.parent.coreTable\n }\n get tableBody() {\n return this.coreTable\n .map(row => `<tr>${this.toRow(row)}</tr>`)\n .join(\"\\n\")\n }\n buildHtml() {\n return `<table id=\"table${this._getUid()}\" class=\"scrollTable\">\n <thead><tr>${this.tableHeader.join(\"\\n\")}</tr></thead>\n <tbody>${this.tableBody}</tbody>\n </table>`\n }\n buildTxt() {\n return this.parent.delimitedData || new Particle(this.coreTable).asCsv\n }\nkatexParser\n popularity 0.001592\n extends abstractScrollWithRequirementsParser\n catchAllAtomType codeAtom\n catchAllParser lineOfCodeParser\n example\n katex\n \\text{E} = \\text{T} / \\text{A}!\n description KaTex widget for typeset math.\n string copyFromExternal .katex.min.css .katex.min.js\n string requireOnce\n <link rel=\"stylesheet\" href=\".katex.min.css\">\n <script defer src=\".katex.min.js\"></script>\n <script>\n document.addEventListener(\"DOMContentLoaded\", () => document.querySelectorAll(\".scrollKatex\").forEach(el =>\n {\n katex.render(el.innerText, el, {\n throwOnError: false\n });\n }\n ))\n </script>\n javascript\n buildInstance() {\n const id = this._getUid()\n const content = this.content === undefined ? \"\" : this.content\n return `<div class=\"scrollKatex\" id=\"${id}\">${content + this.subparticlesToString()}</div>`\n }\n buildTxt() {\n return ( this.content ? this.content : \"\" )+ this.subparticlesToString()\n }\nhelpfulNotFoundParser\n popularity 0.000048\n extends abstractScrollWithRequirementsParser\n catchAllAtomType filePathAtom\n string copyFromExternal .helpfulNotFound.js\n description Helpful not found widget.\n javascript\n buildInstance() {\n return `<style>#helpfulNotFound{margin: 100px 0;}</style><h1 id=\"helpfulNotFound\"></h1><script defer src=\"/.helpfulNotFound.js\"></script><script>document.addEventListener(\"DOMContentLoaded\", () => new NotFoundApp('${this.content}'))</script>`\n }\nslideshowParser\n // Left and right arrows navigate.\n description Slideshow widget. *** delimits slides.\n extends abstractScrollWithRequirementsParser\n string copyFromExternal .jquery-3.7.1.min.js .slideshow.js\n example\n slideshow\n Why did the cow cross the road?\n ***\n Because it wanted to go to the MOOOO-vies.\n ***\n THE END\n ****\n javascript\n buildHtml() {\n return `<style>html {font-size: var(--scrollBaseFontSize, 28px);} body {margin: auto; width: 500px;}.slideshowNav{text-align: center; margin-bottom:20px; font-size: 24px;color: rgba(204,204,204,.8);} a{text-decoration: none; color: rgba(204,204,204,.8);}</style><script defer src=\".jquery-3.7.1.min.js\"></script><div class=\"slideshowNav\"></div><script defer src=\".slideshow.js\"></script>`\n }\ntableSearchParser\n popularity 0.000072\n extends abstractScrollWithRequirementsParser\n string copyFromExternal .jquery-3.7.1.min.js .datatables.css .dayjs.min.js .datatables.js .tableSearch.js\n string requireOnce\n <script defer src=\".jquery-3.7.1.min.js\"></script>\n <style>.dt-search{font-family: \"SF Pro\", \"Helvetica Neue\", \"Segoe UI\", \"Arial\";}</style>\n <link rel=\"stylesheet\" href=\".datatables.css\">\n <script defer src=\".datatables.js\"></script>\n <script defer src=\".dayjs.min.js\"></script>\n <script defer src=\".tableSearch.js\"></script>\n // adds to all tables on page\n description Table search and sort widget.\n javascript\n buildInstance() {\n return \"\"\n }\nabstractCommentParser\n description Prints nothing.\n catchAllAtomType commentAtom\n atoms commentAtom\n extends abstractScrollParser\n baseParser blobParser\n string bindTo next\n javascript\n buildHtml() {\n return ``\n }\n catchAllParser commentLineParser\ncommentParser\n popularity 0.000193\n extends abstractCommentParser\n cueFromId\ncounterpointParser\n description Counterpoint comment. Prints nothing.\n extends commentParser\n cue !\nslashCommentParser\n popularity 0.005643\n extends abstractCommentParser\n cue //\n boolean isPopular true\n description A comment. Prints nothing.\nthanksToParser\n description Acknowledgements comment. Prints nothing.\n extends abstractCommentParser\n cueFromId\nscrollClearStackParser\n popularity 0.000096\n cue clearStack\n description Clear body stack.\n extends abstractScrollParser\n boolean isHtml true\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n return this.root.clearBodyStack().trim()\n }\ncssParser\n popularity 0.007211\n extends abstractScrollParser\n description A style tag.\n example\n css\n body { color: red;}\n cueFromId\n catchAllParser cssLineParser\n catchAllAtomType cssAnyAtom\n javascript\n buildHtml() {\n return `<style>${this.css}</style>`\n }\n get css() {\n return this.content ?? this.subparticlesToString()\n }\n buildCss() {\n return this.css\n }\nscrollBackgroundColorParser\n description Quickly set CSS background.\n popularity 0.007211\n extends abstractScrollParser\n cue background\n catchAllAtomType cssAnyAtom\n example\n background red\n javascript\n buildHtml() {\n return `<style>html, body { background: ${this.content};}</style>`\n }\nscrollFontColorParser\n description Quickly set CSS font-color.\n popularity 0.007211\n extends abstractScrollParser\n cue color\n catchAllAtomType cssAnyAtom\n javascript\n buildHtml() {\n return `<style>html, body { color: ${this.content};}</style>`\n }\nscrollFontParser\n description Quickly set font family.\n popularity 0.007211\n extends abstractScrollParser\n cue font\n atoms cueAtom fontFamilyAtom\n catchAllAtomType cssAnyAtom\n example\n font Slim\n javascript\n buildHtml() {\n const font = this.content === \"Slim\" ? \"Helvetica Neue; font-weight:100;\" : this.content\n return `<style>html, body, h1,h2,h3 { font-family: ${font};}</style>`\n }\nabstractQuickIncludeParser\n popularity 0.007524\n extends abstractScrollParser\n atoms urlAtom\n javascript\n get dependencies() { return [this.filename]}\n get filename() {\n return this.getAtom(0)\n }\nquickCssParser\n popularity 0.007524\n description Make a CSS tag.\n extends abstractQuickIncludeParser\n example\n style.css\n atoms urlAtom\n pattern ^[^\\s]+\\.(css)$\n javascript\n buildHtml() {\n return `<link rel=\"stylesheet\" type=\"text/css\" href=\"${this.filename}\">`\n }\n buildHtmlSnippet() {\n return \"\"\n }\nquickIncludeHtmlParser\n popularity 0.007524\n description Include an HTML file.\n extends abstractQuickIncludeParser\n example\n body.html\n atoms urlAtom\n pattern ^[^\\s]+\\.(html|htm)$\n javascript\n buildHtml() {\n return this.root.readFile(this.filename)\n }\nquickScriptParser\n popularity 0.007524\n description Make a Javascript tag.\n extends abstractQuickIncludeParser\n atoms urlAtom\n example\n script.js\n pattern ^[^\\s]+\\.(js)$\n javascript\n attr = \"\"\n buildHtml() {\n return `<script ${this.attr} src=\"${this.filename}\"></script>`\n }\n buildHtmlSnippet() {\n return \"\"\n }\nquickModuleScriptParser\n description Make a Javascript module tag.\n extends quickScriptParser\n example\n script.mjs\n pattern ^[^\\s]+\\.(mjs)$\n javascript\n attr = 'type=\"module\"'\nscrollDashboardParser\n popularity 0.000145\n description Key stats in large font.\n catchAllParser lineOfCodeParser\n cue dashboard\n extends abstractScrollParser\n example\n dashboard\n #2 Popularity\n 30 Years Old\n $456 Revenue\n javascript\n get tableBody() {\n const items = this.topDownArray\n let str = \"\"\n for (let i = 0; i < items.length; i = i + 3) {\n str += this.makeRow(items.slice(i, i + 3))\n }\n return str\n }\n makeRow(items) {\n return `<tr>` + items.map(particle => `<td>${particle.cue}<span>${particle.content}</span></td>`).join(\"\\n\") + `</tr>\\n`\n }\n buildHtml() {\n return `<table class=\"scrollDashboard\">${this.tableBody}</table>`\n }\n buildTxt() {\n return this.subparticlesToString()\n }\nbelowAsCodeParser\n popularity 0.000651\n description Print code below.\n string bindTo next\n extends abstractScrollParser\n catchAllAtomType integerAtom\n example\n belowAsCode\n iris\n printTable\n cueFromId\n javascript\n method = \"next\"\n get selectedParticles() {\n const { method } = this\n let code = \"\"\n let particles = []\n let next = this[method]\n let {howMany} = this\n while (howMany) {\n particles.push(next)\n next = next[method]\n howMany--\n }\n if (this.reverse) particles.reverse()\n return particles\n }\n get code() {\n return this.selectedParticles.map(particle => particle.asString).join(\"\\n\")\n }\n reverse = false\n buildHtml() {\n return `<code class=\"scrollCodeBlock\">${this.code.replace(/\\</g, \"&lt;\")}</code>`\n }\n get howMany() {\n let howMany = parseInt(this.getAtom(1))\n if (!howMany || isNaN(howMany)) howMany = 1\n return howMany\n }\ndebugBelowParser\n description Inspect particle below.\n extends belowAsCodeParser\n string copyFromExternal .debug.css\n javascript\n get code() {\n const mapFn = particle => {\n const atomTypes = particle.lineAtomTypes.split(\" \")\n return `<div class=\"debugParticle\"><span class=\"debugParticleId\">${particle.constructor.name}</span>${particle.atoms.map((atom, index) => `<span class=\"debugAtom\">${atom}<span class=\"debugAtomType\">${atomTypes[index]}</span></span>`).join(\" \")}${(particle.length ? `<br><div class=\"debugSubparticles\">` + particle.map(mapFn).join(\"<br>\") + `</div>` : \"\")}</div>`}\n return this.selectedParticles.map(mapFn).join(\"<br>\")\n }\n buildHtml() {\n return `<link rel=\"stylesheet\" href=\".debug.css\">` + this.code\n }\n buildTxt() {\n const mapFn = particle => {\n const atomTypes = particle.lineAtomTypes.split(\" \")\n return `${particle.constructor.name} ${particle.atoms.map((atom, index) => `${atomTypes[index]}:${atom}`).join(\" \")}${(particle.length ? `\\n ` + particle.map(mapFn).join(\"\\n\") + `` : \"\")}`}\n return this.selectedParticles.map(mapFn).join(\"\\n\")\n }\n buildParsers() {return this.buildTxt()}\ndebugAboveParser\n description Inspect particle above.\n extends debugBelowParser\n string bindTo previous\n javascript\n method = \"previous\"\n reverse = true\ndebugAllParser\n description Inspect entire document.\n extends debugBelowParser\n javascript\n get selectedParticles() { return this.root.getSubparticles()}\nbelowAsCodeUntilParser\n description Print code above until match.\n extends belowAsCodeParser\n catchAllAtomType codeAtom\n example\n belowAsCode\n counter 1 second\n javascript\n get howMany() {\n let howMany = 1\n const query = this.content\n let particle = this.next\n while (particle !== this) {\n if (particle.getLine().startsWith(query))\n return howMany\n particle = particle.next\n howMany++\n }\n return howMany\n }\naboveAsCodeParser\n popularity 0.000482\n string bindTo previous\n description Print code above.\n example\n counter 1 second\n aboveAsCode\n extends belowAsCodeParser\n javascript\n method = \"previous\"\n reverse = true\nbelowAsHtmlParser\n extends belowAsCodeParser\n description Displays html output of next particle in a code block.\n cueFromId\n example\n belowAsHtml\n # Hello world\n javascript\n get code() {\n return this.selectedParticles.filter(p => p.buildHtml).map(p => p.buildHtml()).join(\"\\n\")\n }\naboveAsHtmlParser\n description Displays html output of previous particle in a code block.\n extends belowAsHtmlParser\n example\n # Hello world\n aboveAsHtml\n javascript\n method = \"previous\"\n reverse = true\nscrollDefParser\n popularity 0.004244\n description Parser short form.\n pattern ^[a-zA-Z0-9_]+Def\n extends abstractScrollParser\n catchAllAtomType stringAtom\n example\n urlDef What is the URL?\n javascript\n buildParsers(index) {\n const idStuff = index ? \"\" : `boolean isMeasure true\n boolean isMeasureRequired true\n boolean isConceptDelimiter true`\n const description = this.content\n const cue = this.cue.replace(\"Def\", \"\")\n const sortIndex = 1 + index/10\n return `${cue}DefParser\n cue ${cue}\n extends abstractStringMeasureParser\n description ${description}\n float sortIndex ${sortIndex}\n ${idStuff}`.trim()\n }\nhakonParser\n cueFromId\n extends abstractScrollParser\n description Compile Hakon to CSS.\n catchAllParser hakonContentParser\n javascript\n buildHtml() {\n return `<style>${this.css}</style>`\n }\n get css() {\n const {hakonParser} = this.root\n return new hakonParser(this.subparticlesToString()).compile()\n }\n buildCss() {\n return this.css\n }\nhamlParser\n popularity 0.007524\n description HTML tag via HAML syntax.\n extends abstractScrollParser\n atoms urlAtom\n catchAllAtomType stringAtom\n pattern ^%?[\\w\\.]+#[\\w\\.]+ *\n javascript\n get tag() {\n return this.atoms[0].split(/[#\\.]/).shift().replace(\"%\", \"\")\n }\n get htmlId() {\n const idMatch = this.atoms[0].match(/#([\\w-]+)/)\n return idMatch ? idMatch[1] : \"\"\n }\n get htmlClasses() {\n return this.atoms[0].match(/\\.([\\w-]+)/g)?.map(cls => cls.slice(1)) || [];\n }\n buildHtml() {\n const {htmlId, htmlClasses, content, tag} = this\n this.parent.sectionStack.unshift(`</${tag}>`)\n const attrs = [htmlId ? ' id=\"' + htmlId + '\"' : \"\", htmlClasses.length ? ' class=\"' + htmlClasses.join(\" \") + '\"' : \"\"].join(\" \").trim()\n return `<${tag}${attrs ? \" \" + attrs : \"\"}>${content || \"\"}`\n }\n buildTxt() {\n return this.content\n }\nhamlTagParser\n // Match plain tags like %h1\n extends hamlParser\n pattern ^%[^#]+$\nabstractHtmlParser\n extends abstractScrollParser\n catchAllParser htmlLineParser\n catchAllAtomType htmlAnyAtom\n javascript\n buildHtml() {\n return `${this.content ?? \"\"}${this.subparticlesToString()}`\n }\n buildTxt() {\n return \"\"\n }\nhtmlParser\n popularity 0.000048\n extends abstractHtmlParser\n description HTML one liners or blocks.\n cueFromId\nhtmlInlineParser\n popularity 0.005788\n extends abstractHtmlParser\n atoms htmlAnyAtom\n boolean isHtml true\n example\n <h1>Inline HTML</h1>\n pattern ^<\n description Inline HTML.\n boolean isPopular true\n javascript\n buildHtml() {\n return `${this.getLine() ?? \"\"}${this.subparticlesToString()}`\n }\nscrollBrParser\n popularity 0.000096\n cue br\n example\n br 2\n description A break.\n extends abstractScrollParser\n catchAllAtomType integerAtom\n boolean isHtml true\n javascript\n buildHtml() {\n return `<br>`.repeat(parseInt(this.getAtom(1) || 1))\n }\niframesParser\n popularity 0.000121\n cueFromId\n catchAllAtomType urlAtom\n extends abstractScrollParser\n description An iframe(s).\n example\n iframes frame.html\n javascript\n buildHtml() {\n return this.atoms.slice(1).map(url => `<iframe src=\"${url}\" frameborder=\"0\"></iframe>`).join(\"\\n\")\n }\nabstractCaptionedParser\n extends abstractScrollParser\n atoms cueAtom urlAtom\n inScope captionAftertextParser slashCommentParser\n cueFromId\n javascript\n buildHtml(buildSettings) {\n const caption = this.getParticle(\"caption\")\n const captionFig = caption ? `<figcaption>${caption.buildHtml()}</figcaption>` : \"\"\n const {figureWidth} = this\n const widthStyle = figureWidth ? `width:${figureWidth}px; margin: auto;` : \"\"\n const float = this.has(\"float\") ? `margin: 20px; float: ${this.get(\"float\")};` : \"\"\n return `<figure class=\"scrollCaptionedFigure\" style=\"${widthStyle + float}\">${this.getFigureContent(buildSettings)}${captionFig}</figure>`\n }\n get figureWidth() {\n return this.get(\"width\")\n }\nscrollImageParser\n cue image\n popularity 0.005908\n description An img tag.\n boolean isPopular true\n extends abstractCaptionedParser\n int atomIndex 1\n example\n image screenshot.png\n caption A caption.\n inScope addClassMarkupParser aftertextIdParser scrollLinkParser linkTargetParser openGraphParser\n javascript\n get dimensions() {\n const width = this.get(\"width\")\n const height = this.get(\"height\")\n if (width || height)\n return {width, height}\n if (!this.isNodeJs())\n return {}\n const src = this.filename\n // If its a local image, get the dimensions and put them in the HTML\n // to avoid flicker\n if (src.startsWith(\"http:\") || src.startsWith(\"https:\")) return {}\n if (this._dimensions)\n return this._dimensions\n try {\n const sizeOf = require(\"image-size\")\n const path = require(\"path\")\n const fullImagePath = path.join(this.root.folderPath, src)\n this._dimensions = sizeOf(fullImagePath)\n return this._dimensions\n } catch (err) {\n console.error(err)\n }\n return {}\n }\n get figureWidth() {\n return this.dimensions.width\n }\n get filename() {\n return this.getAtom(this.atomIndex)\n }\n get dependencies() { return [this.filename]}\n getFigureContent(buildSettings) {\n const linkRelativeToCompileTarget = (buildSettings ? (buildSettings.relativePath ?? \"\") : \"\") + this.filename\n const {width, height} = this.dimensions\n let dimensionAttributes = width || height ? `width=\"${width}\" height=\"${height}\" ` : \"\"\n // Todo: can we reuse more code from aftertext?\n const className = this.has(\"class\") ? ` class=\"${this.get(\"class\")}\" ` : \"\"\n const id = this.has(\"id\") ? ` id=\"${this.get(\"id\")}\" ` : \"\"\n const clickLink = this.find(particle => particle.definition.isOrExtendsAParserInScope([\"scrollLinkParser\"])) || linkRelativeToCompileTarget \n const target = this.has(\"target\") ? this.get(\"target\") : (this.has(\"link\") ? \"\" : \"_blank\")\n return `<a href=\"${clickLink}\" target=\"${target}\" ${className} ${id}><img src=\"${linkRelativeToCompileTarget}\" ${dimensionAttributes}loading=\"lazy\"></a>`\n }\n buildTxt() {\n const subparticles = this.filter(particle => particle.buildTxt).map(particle => particle.buildTxt()).filter(i => i).join(\"\\n\")\n return \"[Image Omitted]\" + (subparticles ? \"\\n \" + subparticles.replace(/\\n/g, \"\\n \") : \"\")\n }\nquickImageParser\n popularity 0.005788\n extends scrollImageParser\n example\n screenshot.png\n atoms urlAtom\n pattern ^[^\\s]+\\.(jpg|jpeg|png|gif|webp|svg|bmp)\n int atomIndex 0\nqrcodeParser\n extends abstractCaptionedParser\n description Make a QR code from a link.\n example\n qrcode https://scroll.pub\n javascript\n getFigureContent() {\n const url = this.atoms[1]\n const isNode = this.isNodeJs()\n if (isNode) {\n const {externalsPath} = this.root\n const path = require(\"path\")\n const {qrcodegen, toSvgString} = require(path.join(externalsPath, \".qrcodegen.js\"))\n const QRC = qrcodegen.QrCode;\n const qr0 = QRC.encodeText(url, QRC.Ecc.MEDIUM);\n const svg = toSvgString(qr0, 4); // See qrcodegen-input-demo\n return svg\n }\n return `Not yet supported in browser.`\n }\nyoutubeParser\n popularity 0.000121\n extends abstractCaptionedParser\n // Include the YouTube embed URL such as https://www.youtube.com/embed/CYPYZnVQoLg\n description A YouTube video widget.\n example\n youtube https://www.youtube.com/watch?v=lO8blNtYYBA\n javascript\n getFigureContent() {\n const url = this.getAtom(1).replace(\"youtube.com/watch?v=\", \"youtube.com/embed/\")\n return `<div class=\"scrollYouTubeHolder\"><iframe class=\"scrollYouTubeEmbed\" src=\"${url}\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe></div>`\n }\nyouTubeParser\n extends youtubeParser\n tags deprecate\n // Deprecated. You youtube all lowercase.\nimportParser\n description Import a file.\n popularity 0.007524\n cueFromId\n atoms preBuildCommandAtom\n extends abstractScrollParser\n catchAllAtomType filePathAtom\n javascript\n buildHtml() {\n return \"\"\n }\n example\n import header.scroll\nscrollImportedParser\n description Inserted at import pass.\n boolean suggestInAutocomplete false\n cue imported\n atoms preBuildCommandAtom\n extends abstractScrollParser\n baseParser blobParser\n catchAllAtomType filePathAtom\n javascript\n buildHtml() {\n return \"\"\n }\n getErrors() {\n if (this.get(\"exists\") === \"false\" && this.previous.getLine() !== \"// optional\")\n return [this.makeError(`File '${this.atoms[1]}' does not exist.`)]\n return []\n }\nquickImportParser\n popularity 0.007524\n description Import a Scroll or Parsers file.\n extends abstractScrollParser\n boolean isPopular true\n inScope importToFooterParser abstractCommentParser\n atoms urlAtom\n pattern ^[^\\s]+\\.(scroll|parsers)$\n javascript\n buildHtml() {\n return \"\"\n }\n example\n header.scroll\nscriptParser\n extends abstractScrollParser\n description Print script tag.\n cueFromId\n catchAllParser scriptLineParser\n catchAllAtomType javascriptAnyAtom\n javascript\n buildHtml() {\n return `<script>${this.scriptContent}</script>`\n }\n get scriptContent() {\n return this.content ?? this.subparticlesToString()\n }\n buildJs() {\n return this.scriptContent\n }\njsonScriptParser\n popularity 0.007524\n cueFromId\n description Include JSON and assign to window.\n extends abstractScrollParser\n atoms cueAtom urlAtom\n javascript\n buildHtml() {\n const varName = this.filename.split(\"/\").pop().replace(\".json\", \"\")\n return `<script>window.${varName} = ${this.root.readFile(this.filename)}</script>`\n }\n get filename() {\n return this.getAtom(1)\n }\nscrollLeftRightButtonsParser\n popularity 0.006342\n cue leftRightButtons\n description Previous and next nav buttons.\n extends abstractScrollParser\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n const { linkToPrevious, linkToNext } = this.root\n if (!linkToPrevious) return \"\"\n const style = `a.keyboardNav {display:block;position:absolute;top:0.25rem; color: rgba(204,204,204,.8); font-size: 1.875rem; line-height: 1.7rem;}a.keyboardNav:hover{color: #333;text-decoration: none;}`\n return `<style>${style}</style><a class=\"keyboardNav doNotPrint\" style=\"left:.5rem;\" href=\"${linkToPrevious}\">&lt;</a><a class=\"keyboardNav doNotPrint\" style=\"right:.5rem;\" href=\"${linkToNext}\">&gt;</a>`\n }\nkeyboardNavParser\n popularity 0.007476\n description Make left and right navigate files.\n extends abstractScrollParser\n cueFromId\n catchAllAtomType urlAtom\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n const {root} = this\n const linkToPrevious = this.getAtom(1) ?? root.linkToPrevious\n const linkToNext = this.getAtom(2) ?? root.linkToNext\n const script = `<script>document.addEventListener('keydown', function(event) {\n if (document.activeElement !== document.body) return\n if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return // dont interfere with keyboard back button shortcut\n const getLinks = () => document.getElementsByClassName(\"scrollKeyboardNav\")[0].getElementsByTagName(\"a\")\n if (event.key === \"ArrowLeft\")\n getLinks()[0].click()\n else if (event.key === \"ArrowRight\")\n getLinks()[1].click()\n });</script>`\n return `<div class=\"scrollKeyboardNav\" style=\"display:none;\"><a href=\"${linkToPrevious}\">${linkToPrevious}</a> · ${root.permalink} · <a href=\"${linkToNext}\">${linkToNext}</a>${script}</div>`\n }\nprintUsageStatsParser\n popularity 0.000096\n // todo: if we include the atom \"Parser\" in a cue, bad things seem to happen.\n description Parser usage stats for folder.\n extends abstractScrollParser\n cueFromId\n javascript\n get stats() {\n const input = this.root.allScrollFiles.map(file => file.scrollProgram).map(program => program.parserIds.join(\"\\n\")).join(\"\\n\")\n const result = input.split('\\n').reduce((acc, atom) => (acc[atom] = (acc[atom] || 0) + 1, acc), {})\n const rows = Object.entries(result).map(([atom, count]) => { return {atom, count}})\n const sorted = this.root.lodash.sortBy(rows, \"count\").reverse()\n return \"parserId uses\\n\" + sorted.map(row => `${row.atom} ${row.count}`).join('\\n')\n }\n buildHtml() {\n // A hacky but simple way to do this for now.\n const particle = this.appendSibling(\"table\")\n particle.appendLine(\"delimiter \")\n particle.appendLine(\"printTable\")\n const dataParticle = particle.appendLine(\"data\")\n dataParticle.setSubparticles(this.stats)\n const html = particle.buildHtml()\n particle.destroy()\n return html\n }\n buildTxt() {\n return this.stats\n }\n buildCsv() {\n return this.stats.replace(/ /g, \",\")\n }\nprintScrollLeetSheetParser\n popularity 0.000024\n description Print Scroll parser leet sheet.\n extends abstractScrollParser\n tags experimental\n cueFromId\n javascript\n get parsersToDocument() {\n const clone = this.root.clone()\n clone.setSubparticles(\"\")\n const atoms = clone.getAutocompleteResultsAt(0,0).matches.map(a => a.text)\n atoms.push(\"blankline\") // manually add blank line\n atoms.push(\"Catch All Paragraph.\") // manually add catch all paragraph\n atoms.push(\"<h></h>\") // manually add html\n atoms.sort()\n clone.setSubparticles(atoms.join(\"\\n\").replace(/blankline/, \"\")) // insert blank line in right spot\n return clone\n }\n sortDocs(docs) {\n return docs.map(particle => {\n const {definition} = particle\n const {id, description, isPopular, examples, popularity} = definition\n const tags = definition.get(\"tags\") || \"\"\n if (tags.includes(\"deprecate\") || tags.includes(\"experimental\"))\n return null\n const category = this.getCategory(tags)\n const note = this.getNote(category)\n return {id: definition.cueIfAny || id, description, isPopular, examples, note, popularity: Math.ceil(parseFloat(popularity) * 100000)}\n }).filter(i => i).sort((a, b) => a.id.localeCompare(b.id))\n }\n makeLink(examples, cue) {\n // if (!examples.length) console.log(cue) // find particles that need docs\n const example = examples.length ? examples[0].subparticlesToString() : cue\n const base = `https://try.scroll.pub/`\n const particle = new Particle()\n particle.appendLineAndSubparticles(\"scroll\", \"theme gazette\\n\" + example)\n return base + \"#\" + encodeURIComponent(particle.asString)\n }\n docToHtml(doc) {\n const css = `#scrollLeetSheet {color: grey;} #scrollLeetSheet a {color: #3498db; }`\n return `<style>${css}</style><div id=\"scrollLeetSheet\">` + doc.map(obj => `<div class=\"${obj.category}\"><a href=\"${this.makeLink(obj.examples, obj.id)}\">${obj.isPopular ? \"<b>\" : \"\"}${obj.id}</a> ${obj.description}${obj.isPopular ? \"</b>\" : \"\"}${obj.note}</div>`).join(\"\\n\") + \"</div>\"\n }\n buildHtml() {\n return this.docToHtml(this.sortDocs(this.parsersToDocument))\n }\n buildTxt() {\n return this.sortDocs(this.parsersToDocument).map(obj => `${obj.id} - ${obj.description}`).join(\"\\n\")\n }\n getCategory(input) {\n return \"\"\n }\n getNote() {\n return \"\"\n }\n get docs() {\n const rows = this.sortDocs(this.parsersToDocument).map(obj => {\n const {id, isPopular, description, popularity, category, examples, cue} = obj\n const example = examples.length ? examples[0].subparticlesToString() : cue\n return {\n id,\n isPopular,\n description,\n popularity,\n example,\n category\n }\n })\n return this.root.lodash.sortBy(rows, \"isPopular\")\n }\n buildJson() {\n return JSON.stringify(this.docs, undefined, 2)\n }\n buildCsv() {\n return new Particle(this.docs).asCsv\n }\nprintparsersLeetSheetParser\n popularity 0.000024\n // todo: fix parse bug when atom Parser appears in parserId\n extends printScrollLeetSheetParser\n tags experimental\n description Parsers leetsheet.\n javascript\n buildHtml() {\n return \"<p><b>Parser Definition Parsers</b> define parsers that acquire, analyze and act on code.</p>\" + this.docToHtml(this.sortDocs(this.parsersToDocument)) + \"<p><b>Atom Definition Parsers</b> analyze the atoms in a line.</p>\" + this.docToHtml(this.sortDocs(this.atomParsersToDocument))\n }\n makeLink() {\n return \"\"\n }\n categories = \"assemblePhase acquirePhase analyzePhase actPhase\".split(\" \")\n getCategory(tags) {\n return tags.split(\" \").filter(w => w.endsWith(\"Phase\"))[0]\n }\n getNote(category) {\n return ` <span class=\"note\">A${category.replace(\"Phase\", \"\").substr(1)}Time.</span>`\n }\n get atomParsersToDocument() {\n const parsersParser = require(\"scrollsdk/products/parsers.nodejs.js\")\n const clone = new parsersParser(\"anyAtom\\n \").clone()\n const parserParticle = clone.getParticle(\"anyAtom\")\n const atoms = clone.getAutocompleteResultsAt(1,1).matches.map(a => a.text)\n atoms.sort()\n parserParticle.setSubparticles(atoms.join(\"\\n\"))\n return parserParticle\n }\n get parsersToDocument() {\n const parsersParser = require(\"scrollsdk/products/parsers.nodejs.js\")\n const clone = new parsersParser(\"latinParser\\n \").clone()\n const parserParticle = clone.getParticle(\"latinParser\")\n const atoms = clone.getAutocompleteResultsAt(1,1).matches.map(a => a.text)\n atoms.sort()\n parserParticle.setSubparticles(atoms.join(\"\\n\"))\n clone.appendLine(\"myParser\")\n clone.appendLine(\"myAtom\")\n return parserParticle\n }\nabstractMeasureParser\n atoms measureNameAtom\n description Base parser all measures extend.\n cueFromId\n boolean isMeasure true\n float sortIndex 1.9\n boolean isComputed false\n string typeForWebForms text\n extends abstractScrollParser\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n return \"\"\n }\n get measureValue() {\n return this.content ?? \"\"\n }\n get measureName() {\n return this.getCuePath().replace(/ /g, \"_\")\n }\nabstractAtomMeasureParser\n description Contains a single word.\n atoms measureNameAtom atomAtom\n example\n nicknameParser\n extends abstractAtomMeasureParser\n id Breck\n nickname breck\n extends abstractMeasureParser\nabstractEmailMeasureParser\n description Email address.\n example\n emailParser\n extends abstractEmailMeasureParser\n id Breck\n email breck7@gmail.com\n string typeForWebForms email\n atoms measureNameAtom emailAddressAtom\n extends abstractAtomMeasureParser\nabstractUrlMeasureParser\n description A single url.\n example\n homepageParser\n extends abstractUrlMeasureParser\n id Breck\n homepage https://breckyunits.com\n string typeForWebForms url\n atoms measureNameAtom urlAtom\n extends abstractAtomMeasureParser\nabstractStringMeasureParser\n description General text data with no specific format.\n catchAllAtomType stringAtom\n example\n titleParser\n extends abstractStringMeasureParser\n id Breck\n title I build languages for scientists of all ages\n extends abstractMeasureParser\nabstractIdParser\n cue id\n description What is the ID of this concept?\n extends abstractStringMeasureParser\n example\n idParser\n extends abstractIdParser\n id breck\n float sortIndex 1\n boolean isMeasureRequired true\n boolean isConceptDelimiter true\n javascript\n getErrors() {\n const errors = super.getErrors()\n let requiredMeasureNames = this.root.measures.filter(measure => measure.isMeasureRequired).map(measure => measure.Name).filter(name => name !== \"id\")\n if (!requiredMeasureNames.length) return errors\n let next = this.next\n while (requiredMeasureNames.length && next.cue !== \"id\" && next.index !== 0) {\n requiredMeasureNames = requiredMeasureNames.filter(i => i !== next.cue)\n next = next.next\n }\n requiredMeasureNames.forEach(name =>\n errors.push(this.makeError(`Concept \"${this.content}\" is missing required measure \"${name}\".`))\n )\n return errors\n }\nabstractIdMeasureParser\n description Alias for abstractIdParser.\n extends abstractIdParser\nabstractTextareaMeasureParser\n string typeForWebForms textarea\n example\n bioParser\n extends abstractTextareaMeasureParser\n id Breck\n bio\n I build languages for scientists of all ages\n description Long-form text content with preserved line breaks.\n extends abstractMeasureParser\n baseParser blobParser\n javascript\n get measureValue() {\n return this.subparticlesToString().replace(/\\n/g, \"\\\\n\")\n }\nabstractNumericMeasureParser\n string typeForWebForms number\n description Base number type.\n extends abstractMeasureParser\n javascript\n get measureValue() {\n const {content} = this\n return content === undefined ? \"\" : parseFloat(content)\n }\nabstractNumberMeasureParser\n description Alias to abstractNumericMeasureParser.\n extends abstractNumericMeasureParser\nabstractIntegerMeasureParser\n description An integer.\n example\n ageParser\n extends abstractIntegerMeasureParser\n id Breck\n age 40\n atoms measureNameAtom integerAtom\n extends abstractNumericMeasureParser\n javascript\n get measureValue() {\n const {content} = this\n return content === undefined ? \"\" : parseInt(content)\n }\nabstractIntMeasureParser\n description Alias to abstractIntegerMeasureParser.\n extends abstractIntegerMeasureParser\nabstractFloatMeasureParser\n description A float.\n example\n temperatureParser\n extends abstractFloatMeasureParser\n id Breck\n temperature 31.8\n atoms measureNameAtom floatAtom\n extends abstractNumericMeasureParser\nabstractPercentageMeasureParser\n description A percentage.\n atoms measureNameAtom percentAtom\n extends abstractNumericMeasureParser\n example\n ownershipParser\n extends abstractPercentageMeasureParser\n id Breck\n ownership 31.8\n javascript\n get measureValue() {\n const {content} = this\n return content === undefined ? \"\" : parseFloat(content)\n }\nabstractEnumMeasureParser\n description A single enum.\n atoms measureNameAtom enumAtom\n extends abstractMeasureParser\n example\n favoriteHtmlTagParser\n extends abstractEnumMeasureParser\n atoms measureNameAtom htmlTagAtom\n id Breck\n favoriteHtmlTag 2020\nabstractBooleanMeasureParser\n description A single boolean.\n atoms measureNameAtom booleanAtom\n extends abstractMeasureParser\n example\n hasBillOfRightsParser\n extends abstractBooleanMeasureParser\n id USA\n hasBillOfRights true\n javascript\n get measureValue() {\n const {content} = this\n return content === undefined ? \"\" : content == \"true\"\n }\nabstractDateMeasureParser\n description Year/month/day in ISO 8601, US, European formats.\n atoms measureNameAtom dateAtom\n extends abstractMeasureParser\n string typeForWebForms date\n javascript\n get measureValue() {\n const {content} = this\n if (!content) return \"\"\n const {dayjs} = this.root\n try {\n // First try parsing with dayjs\n const parsed = dayjs(content)\n if (parsed.isValid())\n return parsed.format(\"YYYY-MM-DD\")\n // Try parsing other common formats\n const formats = [\n \"MM/DD/YYYY\",\n \"DD/MM/YYYY\", \n \"YYYY/MM/DD\",\n \"MM-DD-YYYY\",\n \"DD-MM-YYYY\",\n \"YYYY-MM-DD\",\n \"DD.MM.YYYY\",\n \"YYYY.MM.DD\"\n ]\n for (const format of formats) {\n const attempt = dayjs(content, format)\n if (attempt.isValid())\n return attempt.format(\"YYYY-MM-DD\")\n }\n } catch (err) {\n console.error(err)\n return \"\"\n }\n return \"\"\n }\n get valueAsTimestamp() {\n const {measureValue} = this\n return measureValue ? this.root.dayjs(measureValue).unix() : \"\"\n }\nmetaTagsParser\n popularity 0.007693\n cueFromId\n extends abstractScrollParser\n description Print meta tags including title.\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n const {root} = this\n const { title, description, canonicalUrl, gitRepo, scrollVersion, openGraphImage, keywords } = root\n const rssFeedUrl = root.get(\"rssFeedUrl\")\n const favicon = root.get(\"favicon\")\n const faviconTag = favicon ? `<link rel=\"icon\" href=\"${favicon}\">` : \"\"\n const keywordsTag = keywords ? `<meta name=\"keywords\" content=\"${keywords}\">` : \"\"\n const rssTag = rssFeedUrl ? `<link rel=\"alternate\" type=\"application/rss+xml\" title=\"${title}\" href=\"${rssFeedUrl}\">` : \"\"\n const gitTag = gitRepo ? `<link rel=\"source\" type=\"application/git\" title=\"Source Code Repository\" href=\"${gitRepo}\">` : \"\"\n return `<head>\n <meta charset=\"utf-8\">\n <title>${title}</title>\n <script>/* This HTML was generated by 📜 Scroll v${scrollVersion}. https://scroll.pub */</script>\n <style>@media print {.doNotPrint {display: none !important;}}</style>\n <link rel=\"canonical\" href=\"${canonicalUrl}\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n <meta name=\"description\" content=\"${description}\">\n ${keywordsTag}\n <meta name=\"generator\" content=\"Scroll v${scrollVersion}\">\n <meta property=\"og:title\" content=\"${title}\">\n <meta property=\"og:description\" content=\"${description}\">\n <meta property=\"og:image\" content=\"${openGraphImage}\">\n ${faviconTag}\n ${gitTag}\n ${rssTag}\n <meta name=\"twitter:card\" content=\"summary_large_image\">\n </head>\n <body>`\n }\nquoteParser\n popularity 0.001471\n cueFromId\n description A quote.\n catchAllParser quoteLineParser\n extends abstractScrollParser\n javascript\n buildHtml() {\n return `<blockquote class=\"scrollQuote\">${this.subparticlesToString()}</blockquote>`\n }\n buildTxt() {\n return this.subparticlesToString()\n }\nredirectToParser\n popularity 0.000072\n description HTML redirect tag.\n extends abstractScrollParser\n atoms cueAtom urlAtom\n cueFromId\n example\n redirectTo https://scroll.pub/releaseNotes.html\n javascript\n buildHtml() {\n return `<meta http-equiv=\"Refresh\" content=\"0; url='${this.getAtom(1)}'\" />`\n }\nabstractVariableParser\n extends abstractScrollParser\n catchAllAtomType stringAtom\n atoms preBuildCommandAtom\n cueFromId\n javascript\n isTopMatter = true\n buildHtml() {\n return \"\"\n }\nreplaceParser\n description Replace this with that.\n extends abstractVariableParser\n baseParser blobParser\n example\n replace YEAR 2022\nreplaceJsParser\n description Replace this with evaled JS.\n extends replaceParser\n catchAllAtomType javascriptAnyAtom\n example\n replaceJs SUM 1+1\n * 1+1 = SUM\nreplaceNodejsParser\n description Replace with evaled Node.JS.\n extends abstractVariableParser\n catchAllAtomType javascriptAnyAtom\n baseParser blobParser\n example\n replaceNodejs\n module.exports = {SCORE : 1 + 2}\n * The score is SCORE\ntoFooterParser\n extends abstractScrollParser\n description Experimental way to move a section to the footer.\n atoms preBuildCommandAtom\n cueFromId\nrunScriptParser\n popularity 0.000024\n description Run script and dump stdout.\n extends abstractScrollParser\n atoms cueAtom urlAtom\n cue run\n int filenameIndex 1\n javascript\n get dependencies() { return [this.filename]}\n results = \"Not yet run\"\n async execute() {\n if (!this.filename) return\n await this.root.fetch(this.filename)\n // todo: make async\n const { execSync } = require(\"child_process\")\n this.results = execSync(this.command)\n }\n get command() {\n const path = this.root.path\n const {filename }= this\n const fullPath = this.root.makeFullPath(filename)\n const ext = path.extname(filename).slice(1)\n const interpreterMap = {\n php: \"php\",\n py: \"python3\",\n rb: \"ruby\",\n pl: \"perl\",\n sh: \"sh\"\n }\n return [interpreterMap[ext], fullPath].join(\" \")\n }\n buildHtml() {\n return this.buildTxt()\n }\n get filename() {\n return this.getAtom(this.filenameIndex)\n }\n buildTxt() {\n return this.results.toString().trim()\n }\nquickRunScriptParser\n extends runScriptParser\n atoms urlAtom\n pattern ^[^\\s]+\\.(py|pl|sh|rb|php)$\n int filenameIndex 0\nendSnippetParser\n popularity 0.004293\n description Cut for snippet here.\n extends abstractScrollParser\n cueFromId\n javascript\n buildHtml() {\n return \"\"\n }\ntoStampParser\n description Print a directory to stamp.\n extends abstractScrollParser\n catchAllAtomType filePathAtom\n cueFromId\n javascript\n buildTxt() {\n return this.makeStamp(this.content)\n }\n buildHtml() {\n return `<pre>${this.buildTxt()}</pre>`\n }\n makeStamp(dir) {\n const fs = require('fs');\n const path = require('path');\n const { execSync } = require('child_process');\n let stamp = 'stamp\\n';\n const handleFile = (indentation, relativePath, itemPath, ) => {\n stamp += `${indentation}${relativePath}\\n`;\n const content = fs.readFileSync(itemPath, 'utf8');\n stamp += `${indentation} ${content.replace(/\\n/g, `\\n${indentation} `)}\\n`;\n }\n let gitTrackedFiles\n function processDirectory(currentPath, depth) {\n const items = fs.readdirSync(currentPath);\n items.forEach(item => {\n const itemPath = path.join(currentPath, item);\n const relativePath = path.relative(dir, itemPath);\n //if (!gitTrackedFiles.has(item)) return\n const stats = fs.statSync(itemPath);\n const indentation = ' '.repeat(depth);\n if (stats.isDirectory()) {\n stamp += `${indentation}${relativePath}/\\n`;\n processDirectory(itemPath, depth + 1);\n } else if (stats.isFile())\n handleFile(indentation, relativePath, itemPath)\n });\n }\n const stats = fs.statSync(dir);\n if (stats.isDirectory()) {\n // Get list of git-tracked files\n gitTrackedFiles = new Set(execSync('git ls-files', { cwd: dir, encoding: 'utf-8' })\n .split('\\n')\n .filter(Boolean))\n processDirectory(dir, 1)\n }\n else\n handleFile(\" \", dir, dir)\n return stamp.trim();\n }\nstampParser\n description Expand project template to disk.\n extends abstractScrollParser\n inScope stampFolderParser\n catchAllParser stampFileParser\n example\n stamp\n .gitignore\n *.html\n readme.scroll\n # Hello world\n <script src=\"scripts/nested/hello.js\"></script>\n scripts/\n nested/\n hello.js\n console.log(\"Hello world\")\n cueFromId\n atoms preBuildCommandAtom\n javascript\n execute() {\n const dir = this.root.folderPath\n this.forEach(particle => particle.execute(dir))\n }\nscrollStumpParser\n cue stump\n extends abstractScrollParser\n description Compile Stump to HTML.\n catchAllParser stumpContentParser\n javascript\n buildHtml() {\n const {stumpParser} = this\n return new stumpParser(this.subparticlesToString()).compile()\n }\n get stumpParser() {\n return this.isNodeJs() ? require(\"scrollsdk/products/stump.nodejs.js\") : stumpParser\n }\nstumpNoSnippetParser\n popularity 0.010177\n // todo: make noSnippets an aftertext directive?\n extends scrollStumpParser\n description Compile Stump unless snippet.\n cueFromId\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\nplainTextParser\n description Plain text oneliner or block.\n cueFromId\n extends abstractScrollParser\n catchAllParser plainTextLineParser\n catchAllAtomType stringAtom\n javascript\n buildHtml() {\n return this.buildTxt()\n }\n buildTxt() {\n return `${this.content ?? \"\"}${this.subparticlesToString()}`\n }\nplainTextOnlyParser\n popularity 0.000072\n extends plainTextParser\n description Only print for buildTxt.\n javascript\n buildHtml() {\n return \"\"\n }\nscrollThemeParser\n popularity 0.007524\n boolean isPopular true\n cue theme\n example\n theme gazette\n extends abstractScrollParser\n catchAllAtomType scrollThemeAtom\n description A collection of simple themes.\n string copyFromExternal .gazette.css\n // Note this will be replaced at runtime\n javascript\n get copyFromExternal() {\n return this.files.join(\" \")\n }\n get files() {\n return this.atoms.slice(1).map(name => `.${name}.css`).concat([\".scroll.css\"])\n }\n buildHtml() {\n return this.files.map(name => `<link rel=\"stylesheet\" type=\"text/css\" href=\"${name}\">`).join(\"\\n\")\n }\nabstractAftertextAttributeParser\n atoms cueAtom\n boolean isAttribute true\n javascript\n get htmlAttributes() {\n return `${this.cue}=\"${this.content}\"`\n }\n buildHtml() {\n return \"\"\n }\naftertextIdParser\n popularity 0.000145\n cue id\n description Provide an ID to be output in the generated HTML tag.\n extends abstractAftertextAttributeParser\n atoms cueAtom htmlIdAtom\n single\naftertextStyleParser\n popularity 0.000217\n cue style\n description Set HTML style attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType cssAnyAtom\n javascript\n htmlAttributes = \"\" // special case this one\n get css() { return `${this.property}:${this.content};` }\naftertextFontParser\n popularity 0.000217\n cue font\n description Set font.\n extends aftertextStyleParser\n atoms cueAtom fontFamilyAtom\n catchAllAtomType cssAnyAtom\n string property font-family\n javascript\n get css() {\n if (this.content === \"Slim\") return \"font-family:Helvetica Neue; font-weight:100;\"\n return super.css\n }\naftertextColorParser\n popularity 0.000217\n cue color\n description Set font color.\n extends aftertextStyleParser\n catchAllAtomType cssAnyAtom\n string property color\n example\n color blue\naftertextHrefParser\n popularity 0.000217\n cue href\n description Set HTML href attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom urlAtom\naftertextSrcParser\n extends aftertextHrefParser\n cue src\n description Set HTML src attribute.\naftertextOnclickParser\n popularity 0.000217\n cue onclick\n description Set HTML onclick attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType javascriptAnyAtom\naftertextHiddenParser\n cue hidden\n atoms cueAtom\n description Do not compile this particle to HTML.\n extends abstractAftertextAttributeParser\n single\naftertextValueParser\n popularity 0.000217\n cue value\n description Set HTML value attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextForParser\n popularity 0.000217\n cue for\n description Set HTML for attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom htmlAnyAtom\naftertextPlaceholderParser\n popularity 0.000217\n cue placeholder\n description Set HTML placeholder attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextRowsParser\n popularity 0.000217\n cue rows\n description Set HTML rows attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom integerAtom\naftertextTypeParser\n popularity 0.000217\n cue type\n description Set HTML type attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom htmlTypeAtom\naftertextAltParser\n popularity 0.000217\n cue alt\n description Set HTML alt attribute for images.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextTitleParser\n popularity 0.000217\n cue title\n description Set HTML title attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextNameParser\n popularity 0.000217\n cue name\n description Set HTML name attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextOnsubmitParser\n popularity 0.000217\n cue onsubmit\n description Set HTML onsubmit attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType javascriptAnyAtom\naftertextClassParser\n popularity 0.000217\n cue class\n description Set HTML class attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType classNameAtom\naftertextMaxlengthParser\n popularity 0.000217\n cue maxlength\n description Set HTML maxlength attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom integerAtom\naftertextPatternParser\n popularity 0.000217\n cue pattern\n description Set HTML pattern attribute for input validation.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextRequiredParser\n popularity 0.000217\n cue required\n description Set HTML required attribute.\n extends abstractAftertextAttributeParser\n single\naftertextDisabledParser\n popularity 0.000217\n cue disabled\n description Set HTML disabled attribute.\n extends abstractAftertextAttributeParser\n single\naftertextReadonlyParser\n popularity 0.000217\n cue readonly\n description Set HTML readonly attribute.\n extends abstractAftertextAttributeParser\n single\naftertextAriaLabelParser\n popularity 0.000217\n cue aria-label\n description Set ARIA label for accessibility.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextTargetParser\n popularity 0.000217\n cue target\n description Set HTML target attribute for links.\n extends abstractAftertextAttributeParser\n atoms cueAtom htmlAnyAtom\naftertextContentParser\n popularity 0.000217\n cue content\n description Set HTML content attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextTagParser\n atoms cueAtom htmlTagAtom\n description Override the HTML tag that the compiled particle will use.\n cue tag\n javascript\n buildHtml() {\n return \"\"\n }\nabstractAftertextDirectiveParser\n atoms cueAtom\n catchAllAtomType stringAtom\n javascript\n isMarkup = true\n buildHtml() {\n return \"\"\n }\n getErrors() {\n const errors = super.getErrors()\n if (!this.isMarkup || this.matchWholeLine) return errors\n const inserts = this.getInserts(this.parent.originalTextPostLinkify)\n // todo: make AbstractParticleError class exported by sdk to allow Parsers to define their own error types.\n // todo: also need to be able to map lines back to their line in source (pre-imports)\n if (!inserts.length)\n errors.push(this.makeError(`No match found for \"${this.getLine()}\".`))\n return errors\n }\n get pattern() {\n return this.getAtomsFrom(1).join(\" \")\n }\n get shouldMatchAll() {\n return this.has(\"matchAll\")\n }\n getMatches(text) {\n const { pattern } = this\n const escapedPattern = pattern.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\")\n return [...text.matchAll(new RegExp(escapedPattern, \"g\"))].map(match => {\n const { index } = match\n const endIndex = index + pattern.length\n return [\n { index, string: `<${this.openTag}${this.allAttributes}>`, endIndex },\n { index: endIndex, endIndex, string: `</${this.closeTag}>` }\n ]\n })\n }\n getInserts(text) {\n const matches = this.getMatches(text)\n if (!matches.length) return false\n if (this.shouldMatchAll) return matches.flat()\n const match = this.getParticle(\"match\")\n if (match)\n return match.indexes\n .map(index => matches[index])\n .filter(i => i)\n .flat()\n return matches[0]\n }\n get allAttributes() {\n const attr = this.attributes.join(\" \")\n return attr ? \" \" + attr : \"\"\n }\n get attributes() {\n return []\n }\n get openTag() {\n return this.tag\n }\n get closeTag() {\n return this.tag\n }\nabstractMarkupParser\n extends abstractAftertextDirectiveParser\n inScope abstractMarkupParameterParser\n javascript\n get matchWholeLine() {\n return this.getAtomsFrom(this.patternStartsAtAtom).length === 0\n }\n get pattern() {\n return this.matchWholeLine ? this.parent.originalText : this.getAtomsFrom(this.patternStartsAtAtom).join(\" \")\n }\n patternStartsAtAtom = 1\nboldParser\n popularity 0.000096\n cueFromId\n description Bold matching text.\n extends abstractMarkupParser\n javascript\n tag = \"b\"\nitalicsParser\n popularity 0.000241\n cueFromId\n description Italicize matching text.\n extends abstractMarkupParser\n javascript\n tag = \"i\"\nunderlineParser\n popularity 0.000024\n description Underline matching text.\n cueFromId\n extends abstractMarkupParser\n javascript\n tag = \"u\"\nafterTextCenterParser\n popularity 0.000193\n description Center paragraph.\n cue center\n extends abstractMarkupParser\n javascript\n tag = \"center\"\naftertextCodeParser\n popularity 0.000145\n description Wrap matching text in code span.\n cue code\n extends abstractMarkupParser\n javascript\n tag = \"code\"\naftertextStrikeParser\n popularity 0.000048\n description Wrap matching text in s span.\n cue strike\n extends abstractMarkupParser\n javascript\n tag = \"s\"\naddClassMarkupParser\n popularity 0.000772\n description Add a custom class to parent element. Provide query to add span matching text.\n extends abstractMarkupParser\n atoms cueAtom classNameAtom\n cue addClass\n javascript\n tag = \"span\"\n get applyToParentElement() {\n return this.atoms.length === 2\n }\n getInserts(text) {\n // If no select text is added, set the class on the parent element.\n if (this.applyToParentElement) return []\n return super.getInserts(text)\n }\n get className() {\n return this.getAtom(1)\n }\n get attributes() {\n return [`class=\"${this.className}\"`]\n }\n get matchWholeLine() {\n return this.applyToParentElement\n }\n get pattern() {\n return this.matchWholeLine ? this.parent.content : this.getAtomsFrom(2).join(\" \")\n }\nhoverNoteParser\n popularity 0.000265\n description Add a caveat viewable on hover on matching text. When you want to be sure you've thoroughly addressed obvious concerns but ones that don't warrant to distract from the main argument of the text.\n cueFromId\n extends addClassMarkupParser\n catchAllParser lineOfTextParser\n atoms cueAtom\n javascript\n get pattern() {\n return this.getAtomsFrom(1).join(\" \")\n }\n get attributes() {\n return [`class=\"scrollHoverNote\"`, `title=\"${this.hoverNoteText}\"`]\n }\n get hoverNoteText() {\n return this.subparticlesToString().replace(/\\n/g, \" \")\n }\nscrollLinkParser\n popularity 0.008706\n extends abstractMarkupParser\n description Put the matching text in an <a> tag.\n atoms cueAtom urlAtom\n inScope linkTitleParser linkTargetParser abstractCommentParser\n programParser\n description Anything here will be URI encoded and then appended to the link.\n cueFromId\n atoms cueAtom\n catchAllParser programLinkParser\n javascript\n get encoded() {\n return encodeURIComponent(this.subparticlesToString())\n }\n cue link\n javascript\n tag = \"a\"\n buildTxt() {\n return this.root.ensureAbsoluteLink(this.link) + \" \" + this.pattern\n }\n get link() {\n const {baseLink} = this\n if (this.has(\"program\"))\n return baseLink + this.getParticle(\"program\").encoded\n return baseLink\n }\n get baseLink() {\n const link = this.getAtom(1)\n const isAbsoluteLink = link.includes(\"://\")\n if (isAbsoluteLink) return link\n const relativePath = this.parent.buildSettings?.relativePath || \"\"\n return relativePath + link\n }\n get linkAttribute() {\n return \"href\"\n }\n get attributes() {\n const attrs = [`${this.linkAttribute}=\"${this.link}\"`]\n const options = [\"title\", \"target\"]\n options.forEach(option => {\n const particle = this.getParticle(option)\n if (particle) attrs.push(`${option}=\"${particle.content}\"`)\n })\n return attrs\n }\n patternStartsAtAtom = 2\nscrollClickParser\n extends scrollLinkParser\n description An a tag with an onclick.\n cue click\n javascript\n get linkAttribute() {\n return \"onclick\"\n }\nemailLinkParser\n popularity 0.000048\n description A mailto link\n cue email\n extends scrollLinkParser\n javascript\n get attributes() {\n return [`href=\"mailto:${this.link}\"`]\n }\nquickLinkParser\n popularity 0.029228\n pattern ^https?\\:\n extends scrollLinkParser\n atoms urlAtom\n javascript\n get link() {\n return this.cue\n }\n patternStartsAtAtom = 1\nquickRelativeLinkParser\n popularity 0.029228\n description Relative links.\n // note: only works if relative link ends in .html\n pattern ^[^\\s]+\\.(html|htm)\n extends scrollLinkParser\n atoms urlAtom\n javascript\n get link() {\n return this.cue\n }\n patternStartsAtAtom = 1\ndatelineParser\n popularity 0.006005\n cueFromId\n description Gives your paragraph a dateline like \"December 15, 2021 — The...\"\n extends abstractAftertextDirectiveParser\n javascript\n getInserts() {\n const {day} = this\n if (!day) return false\n return [{ index: 0, string: `<span class=\"scrollDateline\">${day} — </span>` }]\n }\n matchWholeLine = true\n get day() {\n let day = this.content || this.root.date\n if (!day) return \"\"\n return this.root.dayjs(day).format(`MMMM D, YYYY`)\n }\ndayjsParser\n description Advanced directive that evals some Javascript code in an environment including \"dayjs\".\n cueFromId\n extends abstractAftertextDirectiveParser\n javascript\n getInserts() {\n const dayjs = this.root.dayjs\n const days = eval(this.content)\n const index = this.parent.originalTextPostLinkify.indexOf(\"days\")\n return [{ index, string: `${days} ` }]\n }\ninlineMarkupsOnParser\n popularity 0.000024\n cueFromId\n description Enable these inline markups only.\n example\n Hello *world*!\n inlineMarkupsOn bold\n extends abstractAftertextDirectiveParser\n catchAllAtomType inlineMarkupNameAtom\n javascript\n get shouldMatchAll() {\n return true\n }\n get markups() {\n const {root} = this\n let markups = [{delimiter: \"`\", tag: \"code\", exclusive: true, name: \"code\"},{delimiter: \"*\", tag: \"strong\", name: \"bold\"}, {delimiter: \"_\", tag: \"em\", name: \"italics\"}]\n // only add katex markup if the root doc has katex.\n if (root.has(\"katex\"))\n markups.unshift({delimiter: \"$\", tag: \"span\", attributes: ' class=\"scrollKatex\"', exclusive: true, name: \"katex\"})\n if (this.content)\n return markups.filter(markup => this.content.includes(markup.name))\n if (root.has(\"inlineMarkups\")) {\n root.getParticle(\"inlineMarkups\").forEach(markup => {\n const delimiter = markup.getAtom(0)\n const tag = markup.getAtom(1)\n // todo: add support for providing custom functions for inline markups?\n // for example, !2+2! could run eval, or :about: could search a link map.\n const attributes = markup.getAtomsFrom(2).join(\" \")\n markups = markups.filter(mu => mu.delimiter !== delimiter) // Remove any overridden markups\n if (tag)\n markups.push({delimiter, tag, attributes})\n })\n }\n return markups\n }\n matchWholeLine = true\n getMatches(text) {\n const exclusives = []\n return this.markups.map(markup => this.applyMarkup(text, markup, exclusives)).filter(i => i).flat()\n }\n applyMarkup(text, markup, exclusives = []) {\n const {delimiter, tag, attributes} = markup\n const escapedDelimiter = delimiter.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\")\n const pattern = new RegExp(`${escapedDelimiter}[^${escapedDelimiter}]+${escapedDelimiter}`, \"g\")\n const delimiterLength = delimiter.length\n return [...text.matchAll(pattern)].map(match => {\n const { index } = match\n const endIndex = index + match[0].length\n // I'm too lazy to clean up sdk to write a proper inline markup parser so doing this for now.\n // The exclusive idea is to not try and apply bold or italic styles inside a TeX or code inline style.\n // Note that the way this is currently implemented any TeX in an inline code will get rendered, but code\n // inline of TeX will not. Seems like an okay tradeoff until a proper refactor and cleanup can be done.\n if (exclusives.some(exclusive => index >= exclusive[0] && index <= exclusive[1]))\n return undefined\n if (markup.exclusive)\n exclusives.push([index, endIndex])\n return [\n { index, string: `<${tag + (attributes ? \" \" + attributes : \"\")}>`, endIndex, consumeStartCharacters: delimiterLength },\n { index: endIndex, endIndex, string: `</${tag}>`, consumeEndCharacters: delimiterLength }\n ]\n }).filter(i => i)\n }\ninlineMarkupParser\n popularity 0.000169\n cueFromId\n atoms cueAtom delimiterAtom tagOrUrlAtom\n catchAllAtomType htmlAttributesAtom\n extends inlineMarkupsOnParser\n description Custom inline markup. for\n example\n @This@ will be in italics.\n inlineMarkup @ em\n javascript\n getMatches(text) {\n try {\n const delimiter = this.getAtom(1)\n const tag = this.getAtom(2)\n const attributes = this.getAtomsFrom(3).join(\" \")\n return this.applyMarkup(text, {delimiter, tag, attributes})\n } catch (err) {\n console.error(err)\n return []\n }\n // Note: doubling up doesn't work because of the consumption characters.\n }\nlinkifyParser\n description Use this to disable linkify on the text.\n extends abstractAftertextDirectiveParser\n cueFromId\n atoms cueAtom booleanAtom\nabstractMarkupParameterParser\n atoms cueAtom\n cueFromId\nmatchAllParser\n popularity 0.000024\n description Use this to match all occurrences of the text.\n extends abstractMarkupParameterParser\nmatchParser\n popularity 0.000048\n catchAllAtomType integerAtom\n description Use this to specify which index(es) to match.\n javascript\n get indexes() {\n return this.getAtomsFrom(1).map(num => parseInt(num))\n }\n example\n aftertext\n hello ello ello\n bold ello\n match 0 2\n extends abstractMarkupParameterParser\nabstractHtmlAttributeParser\n javascript\n buildHtml() {\n return \"\"\n }\nlinkTargetParser\n popularity 0.000024\n extends abstractHtmlAttributeParser\n description If you want to set the target of the link. To \"_blank\", for example.\n cue target\n atoms cueAtom codeAtom\nblankLineParser\n popularity 0.308149\n description Print nothing. Break section.\n atoms blankAtom\n boolean isPopular true\n javascript\n buildHtml() {\n return this.parent.clearSectionStack()\n }\n pattern ^$\n tags doNotSynthesize\nscrollFileAddressParser\n catchAllAtomType filePathAtom\n catchAllParser scrollFileAddressParser\nchatLineParser\n popularity 0.009887\n catchAllAtomType stringAtom\n catchAllParser chatLineParser\nlineOfCodeParser\n popularity 0.018665\n catchAllAtomType codeAtom\n catchAllParser lineOfCodeParser\ncommentLineParser\n catchAllAtomType commentAtom\ncssLineParser\n popularity 0.002870\n catchAllAtomType cssAnyAtom\n catchAllParser cssLineParser\nabstractTableTransformParser\n atoms cueAtom\n inScope abstractTableVisualizationParser abstractTableTransformParser h1Parser h2Parser scrollQuestionParser htmlInlineParser scrollBrParser slashCommentParser\n javascript\n get coreTable() {\n return this.parent.coreTable\n }\n get columnNames() {\n return this.parent.columnNames\n }\n connectColumnNames(userColumnNames, availableColumnNames = this.parent.columnNames) {\n const result = {}\n const normalize = str => str.toLowerCase().trim()\n userColumnNames.forEach(userColumn => {\n // Strategy 1: Exact match\n const exactMatch = availableColumnNames.find(col => col === userColumn)\n if (exactMatch) {\n result[userColumn] = exactMatch\n return\n }\n // Strategy 2: Case-insensitive match\n const normalizedUserColumn = normalize(userColumn)\n const caseInsensitiveMatch = availableColumnNames.find(col => normalize(col) === normalizedUserColumn)\n if (caseInsensitiveMatch) {\n result[userColumn] = caseInsensitiveMatch\n return\n }\n // Strategy 3: Levenshtein distance match\n const THRESHOLD = 2 // Consider matches with distance <= 2 as \"very close\"\n let bestMatch = null\n let bestDistance = Infinity\n availableColumnNames.forEach(col => {\n const distance = this.root.levenshteinDistance(userColumn, col)\n if (distance < bestDistance) {\n bestDistance = distance\n bestMatch = col\n }\n })\n // Only use Levenshtein match if it's very close\n if (bestDistance <= THRESHOLD) {\n result[userColumn] = bestMatch\n return\n }\n // Strategy 4: Fallback - use original unmatched name\n result[userColumn] = userColumn\n })\n return result\n }\n connectColumnName(name) {\n return this.connectColumnNames([name])[name]\n }\n getErrors() {\n const errors = super.getErrors()\n if (errors.length && this.previous.cue !== \"assertIgnoreBelowErrors\")\n return errors\n return []\n }\n getRunTimeEnumOptions(atom) {\n if (atom.atomTypeId === \"columnNameAtom\")\n return this.parent.columnNames\n return super.getRunTimeEnumOptions(atom)\n }\n getRunTimeEnumOptionsForValidation(atom) {\n // Note: this will fail if the CSV file hasnt been built yet.\n if (atom.atomTypeId === \"columnNameAtom\")\n return this.parent.columnNames.concat(this.parent.columnNames.map(c => \"-\" + c)) // Add reverse names\n return super.getRunTimeEnumOptions(atom)\n }\nabstractDateSplitTransformParser\n extends abstractTableTransformParser\n atoms cueAtom\n catchAllAtomType columnNameAtom\n javascript\n get coreTable() {\n const columnName = this.getAtom(1) || this.detectDateColumn()\n if (!columnName) return this.parent.coreTable\n return this.parent.coreTable.map(row => {\n const newRow = {...row}\n try {\n const date = this.root.dayjs(row[columnName])\n if (date.isValid())\n newRow[this.newColumnName] = this.transformDate(date)\n } catch (err) {}\n return newRow\n })\n }\n detectDateColumn() {\n const columns = this.parent.columnNames\n const dateColumns = ['date', 'created', 'published', 'timestamp']\n for (const col of dateColumns) {\n if (columns.includes(col)) return col\n }\n for (const col of columns) {\n const sample = this.parent.coreTable[0][col]\n if (sample && this.root.dayjs(sample).isValid())\n return col\n }\n return null\n }\n get columnNames() {\n return [...this.parent.columnNames, this.newColumnName]\n }\n transformDate(date) {\n const formatted = date.format(this.dateFormat)\n const isInt = !this.cue.includes(\"Name\")\n return isInt ? parseInt(formatted) : formatted\n }\nscrollSplitYearParser\n extends abstractDateSplitTransformParser\n description Extract year into new column.\n cue splitYear\n string newColumnName year\n string dateFormat YYYY\nscrollSplitDayNameParser\n extends abstractDateSplitTransformParser\n description Extract day name into new column.\n cue splitDayName\n string newColumnName dayName\n string dateFormat dddd\nscrollSplitMonthNameParser\n extends abstractDateSplitTransformParser\n description Extract month name into new column.\n cue splitMonthName\n string newColumnName monthName\n string dateFormat MMMM\nscrollSplitMonthParser\n extends abstractDateSplitTransformParser\n description Extract month number (1-12) into new column.\n cue splitMonth\n string newColumnName month\n string dateFormat M\nscrollSplitDayOfMonthParser\n extends abstractDateSplitTransformParser\n description Extract day of month (1-31) into new column.\n cue splitDayOfMonth\n string newColumnName dayOfMonth\n string dateFormat D\nscrollSplitDayOfWeekParser\n extends abstractDateSplitTransformParser\n description Extract day of week (0-6) into new column.\n cue splitDay\n string newColumnName day\n string dateFormat d\nscrollParseDateParser\n extends abstractTableTransformParser\n description Parse dates in a column into standard format.\n cue parseDate\n atoms cueAtom columnNameAtom\n example\n sampleData stocks.csv\n parseDate date\n linechart\n x date\n y price\n javascript\n get coreTable() {\n const columnName = this.connectColumnName(this.getAtom(1))\n const formatOut = this.get(\"format\") || \"YYYY-MM-DD\"\n const {dayjs} = this.root\n return this.parent.coreTable.map(row => {\n const newRow = {...row}\n try {\n const value = row[columnName]\n if (value) {\n const date = dayjs(value)\n if (date.isValid())\n newRow[columnName] = date.format(formatOut)\n }\n } catch (err) {\n console.error(`Error parsing date in column ${columnName}:`, err)\n }\n return newRow\n })\n }\n formatParser\n description Specify output date format\n atoms cueAtom stringAtom\n cueFromId\n single\nscrollGroupByParser\n catchAllAtomType columnNameAtom\n extends abstractTableTransformParser\n reduceParser\n description Specify how to aggregate a column when grouping data\n atoms cueAtom columnNameAtom reductionTypeAtom newColumnNameAtom\n cue reduce\n example\n data.csv\n groupBy year\n reduce score sum totalScore\n reduce name concat names\n printTable\n javascript\n get reduction() {\n return {\n source: this.getAtom(1),\n reduction: this.getAtom(2),\n name: this.getAtom(3) || this.getAtomsFrom(1).join(\"_\")\n }\n }\n description Combine rows with matching values into groups.\n example\n tables posts.csv\n groupBy year\n printTable\n cue groupBy\n javascript\n get coreTable() {\n if (this._coreTable) return this._coreTable\n const groupByColNames = this.getAtomsFrom(1)\n const {coreTable} = this.parent\n if (!groupByColNames.length) return coreTable\n const newCols = this.findParticles(\"reduce\").map(particle => particle.reduction)\n // Pivot is shorthand for group and reduce?\n const makePivotTable = (rows, groupByColumnNames, inputColumnNames, newCols) => {\n const colMap = {}\n inputColumnNames.forEach((col) => (colMap[col] = true))\n const groupByCols = groupByColumnNames.filter((col) => colMap[col])\n return new PivotTable(rows, inputColumnNames.map(c => {return {name: c}}), newCols).getNewRows(groupByCols)\n }\n class PivotTable {\n constructor(rows, inputColumns, outputColumns) {\n this._columns = {}\n this._rows = rows\n inputColumns.forEach((col) => (this._columns[col.name] = col))\n outputColumns.forEach((col) => (this._columns[col.name] = col))\n }\n _getGroups(allRows, groupByColNames) {\n const rowsInGroups = new Map()\n allRows.forEach((row) => {\n const groupKey = groupByColNames.map((col) => row[col]?.toString().replace(/ /g, \"\") || \"\").join(\" \")\n if (!rowsInGroups.has(groupKey)) rowsInGroups.set(groupKey, [])\n rowsInGroups.get(groupKey).push(row)\n })\n return rowsInGroups\n }\n getNewRows(groupByCols) {\n // make new particles\n const rowsInGroups = this._getGroups(this._rows, groupByCols)\n // Any column in the group should be reused by the children\n const columns = [\n {\n name: \"count\",\n type: \"number\",\n min: 0,\n },\n ]\n groupByCols.forEach((colName) => columns.push(this._columns[colName]))\n const colsToReduce = Object.values(this._columns).filter((col) => !!col.reduction)\n colsToReduce.forEach((col) => columns.push(col))\n // for each group\n const rows = []\n const totalGroups = rowsInGroups.size\n for (let [groupId, group] of rowsInGroups) {\n const firstRow = group[0]\n const newRow = {}\n groupByCols.forEach((col) =>\n newRow[col] = firstRow ? firstRow[col] : 0\n )\n newRow.count = group.length\n // todo: add more reductions? count, stddev, median, variance.\n colsToReduce.forEach((col) => {\n const sourceColName = col.source\n const reduction = col.reduction\n const newColName = col.name\n if (reduction === \"concat\") {\n newRow[newColName] = group.map((row) => row[sourceColName]).join(\" \")\n return \n }\n if (reduction === \"first\") {\n newRow[newColName] = group.find((row) => row[sourceColName] !== \"\")?.[sourceColName]\n return \n }\n const values = group.map((row) => row[sourceColName]).filter((val) => typeof val === \"number\" && !isNaN(val))\n let reducedValue = firstRow[sourceColName]\n if (reduction === \"sum\") reducedValue = values.reduce((prev, current) => prev + current, 0)\n if (reduction === \"max\") reducedValue = Math.max(...values)\n if (reduction === \"min\") reducedValue = Math.min(...values)\n if (reduction === \"mean\") reducedValue = values.reduce((prev, current) => prev + current, 0) / values.length\n newRow[newColName] = reducedValue\n })\n rows.push(newRow)\n }\n // todo: add tests. figure out this api better.\n Object.values(columns).forEach((col) => {\n // For pivot columns, remove the source and reduction info for now. Treat things as immutable.\n delete col.source\n delete col.reduction\n })\n return {\n rows,\n columns,\n }\n }\n }\n const pivotTable = makePivotTable(coreTable, groupByColNames, this.parent.columnNames, newCols)\n this._coreTable = pivotTable.rows\n this._columnNames = pivotTable.columns.map(col => col.name)\n return pivotTable.rows\n }\n get columnNames() {\n const {coreTable} = this\n return this._columnNames || this.parent.columnNames\n }\nscrollWhereParser\n extends abstractTableTransformParser\n description Filter rows by condition.\n cue where\n atoms cueAtom columnNameAtom comparisonAtom\n catchAllAtomType constantAtom\n example\n table iris.csv\n where Species = setosa\n javascript\n get coreTable() {\n // todo: use atoms here.\n const columnName = this.connectColumnName(this.getAtom(1))\n const operator = this.getAtom(2)\n let untypedComparisonValue = this.getAtom(3)\n const typedComparisonValue = isNaN(parseFloat(untypedComparisonValue)) ? untypedComparisonValue : parseFloat(untypedComparisonValue)\n const coreTable = this.parent.coreTable\n if (!columnName || !operator || (untypedComparisonValue === undefined && !operator.includes(\"mpty\"))) return coreTable\n const filterFn = row => {\n const atom = row[columnName]\n const typedAtom = atom === null ? undefined : atom // convert nulls to undefined\n if (operator === \"=\") return typedComparisonValue === typedAtom\n else if (operator === \"!=\") return typedComparisonValue !== typedAtom\n else if (operator === \"includes\") return typedAtom !== undefined && typedAtom.includes(typedComparisonValue)\n else if (operator === \"startsWith\") return typedAtom !== undefined && typedAtom.toString().startsWith(typedComparisonValue)\n else if (operator === \"endsWith\") return typedAtom !== undefined && typedAtom.toString().endsWith(typedComparisonValue)\n else if (operator === \"doesNotInclude\") return typedAtom === undefined || !typedAtom.includes(typedComparisonValue)\n else if (operator === \">\") return typedAtom > typedComparisonValue\n else if (operator === \"<\") return typedAtom < typedComparisonValue\n else if (operator === \">=\") return typedAtom >= typedComparisonValue\n else if (operator === \"<=\") return typedAtom <= typedComparisonValue\n else if (operator === \"empty\") return typedAtom === \"\" || typedAtom === undefined\n else if (operator === \"notEmpty\") return typedAtom !== \"\" && typedAtom !== undefined\n }\n return coreTable.filter(filterFn)\n }\nscrollSelectParser\n catchAllAtomType columnNameAtom\n extends abstractTableTransformParser\n description Drop all columns except these.\n example\n tables\n data\n name,year,count\n index,2022,2\n about,2023,4\n select name year\n printTable\n cue select\n javascript\n get coreTable() {\n const {coreTable} = this.parent\n const {columnNames} = this\n if (!columnNames.length) return coreTable\n return coreTable.map(row => Object.fromEntries(columnNames.map(colName => [colName, row[colName]])))\n }\n get columnNames() {\n if (!this._columnNames) {\n const names = this.getAtomsFrom(1)\n this._columnNamesMap = this.connectColumnNames(names)\n this._columnNames = names.map(name => this._columnNamesMap[name])\n }\n return this._columnNames\n }\nscrollReverseParser\n extends abstractTableTransformParser\n description Reverse rows.\n cue reverse\n javascript\n get coreTable() {\n return this.parent.coreTable.slice().reverse()\n }\nscrollComposeParser\n extends abstractTableTransformParser\n description Add column using format string.\n catchAllAtomType codeAtom\n cue compose\n atoms cueAtom newColumnNameAtom\n example\n table\n compose sentence My name is {name}\n printTable\n javascript\n get coreTable() {\n const {newColumnName} = this\n const formatString = this.getAtomsFrom(2).join(\" \")\n return this.parent.coreTable.map((row, index) => {\n const newRow = Object.assign({}, row)\n newRow[newColumnName] = this.evaluate(new Particle(row).evalTemplateString(formatString), index)\n return newRow\n })\n }\n evaluate(str) {\n return str\n }\n get newColumnName() {\n return this.atoms[1]\n }\n get columnNames() {\n return this.parent.columnNames.concat(this.newColumnName)\n }\nscrollComputeParser\n extends scrollComposeParser\n description Add column by evaling format string.\n cue compute\n javascript\n evaluate(str) {\n return parseFloat(eval(str))\n }\nscrollEvalParser\n extends scrollComputeParser\n description Add column by evaling format string.\n cue eval\n javascript\n evaluate(str) {\n return eval(str)\n }\nscrollRankParser\n extends scrollComposeParser\n description Add rank column.\n atoms cueAtom\n string newColumnName rank\n cue rank\n javascript\n evaluate(str, index) { return index + 1 }\nscrollLinksParser\n extends abstractTableTransformParser\n description Add column with links.\n cue links\n catchAllAtomType columnNameAtom\n javascript\n get coreTable() {\n const {newColumnName, linkColumns} = this\n return this.parent.coreTable.map(row => {\n const newRow = Object.assign({}, row)\n let newValue = []\n linkColumns.forEach(name => {\n const value = newRow[name]\n delete newRow[name]\n if (value) newValue.push(`<a href=\"${value.includes(\"@\") ? \"mailto:\" : \"\"}${value}\">${name}</a>`)\n })\n newRow[newColumnName] = newValue.join(\" \")\n return newRow\n })\n }\n get newColumnName() {\n return \"links\"\n }\n get linkColumns() {\n return this.getAtomsFrom(1)\n }\n get columnNames() {\n const {linkColumns} = this\n return this.parent.columnNames.filter(name => !linkColumns.includes(name)).concat(this.newColumnName)\n }\nscrollLimitParser\n extends abstractTableTransformParser\n description Select a subset.\n cue limit\n atoms cueAtom integerAtom integerAtom\n javascript\n get coreTable() {\n let start = this.getAtom(1)\n let end = this.getAtom(2)\n if (end === undefined) {\n end = start\n start = 0\n }\n return this.parent.coreTable.slice(parseInt(start), parseInt(end))\n }\nscrollShuffleParser\n extends abstractTableTransformParser\n description Randomly reorder rows.\n cue shuffle\n example\n table data.csv\n shuffle\n printTable\n javascript\n get coreTable() {\n // Create a copy of the table to avoid modifying original\n const rows = this.parent.coreTable.slice()\n // Fisher-Yates shuffle algorithm\n for (let i = rows.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * (i + 1))\n ;[rows[i], rows[j]] = [rows[j], rows[i]]\n }\n return rows\n }\nscrollTransposeParser\n extends abstractTableTransformParser\n description Tranpose table.\n cue transpose\n javascript\n get coreTable() {\n // todo: we need to switch to column based coreTable, instead of row based\n const transpose = arr => Object.keys(arr[0]).map(key => [key, ...arr.map(row => row[key])]);\n return transpose(this.parent.coreTable)\n }\nscrollImputeParser\n extends abstractTableTransformParser\n description Impute missing values of a columm.\n atoms cueAtom columnNameAtom\n cue impute\n javascript\n get coreTable() {\n const {columnName} = this\n const sorted = this.root.lodash.orderBy(this.parent.coreTable.slice(), columnName)\n // ascending\n const imputed = []\n let lastInserted = sorted[0][columnName]\n sorted.forEach(row => {\n const measuredTime = row[columnName]\n while (measuredTime > lastInserted + 1) {\n lastInserted++\n // synthesize rows\n const imputedRow = {}\n imputedRow[columnName] = lastInserted\n imputedRow.count = 0\n imputed.push(imputedRow)\n }\n lastInserted = measuredTime\n imputed.push(row)\n })\n return imputed\n }\n get columnName() {\n return this.connectColumnName(this.getAtom(1))\n }\nscrollOrderByParser\n extends abstractTableTransformParser\n description Sort rows by column(s).\n catchAllAtomType columnNameAtom\n cue orderBy\n javascript\n get coreTable() {\n const makeLodashOrderByParams = str => {\n const part1 = str.split(\" \")\n const part2 = part1.map(col => (col.startsWith(\"-\") ? \"desc\" : \"asc\"))\n return [part1.map(col => this.connectColumnName(col.replace(/^\\-/, \"\"))), part2]\n }\n const orderBy = makeLodashOrderByParams(this.content)\n return this.root.lodash.orderBy(this.parent.coreTable.slice(), orderBy[0], orderBy[1])\n }\nassertRowCountParser\n extends abstractTableTransformParser\n description Test row count is expected value.\n atoms cueAtom integerAtom\n cueFromId\n javascript\n getErrors() {\n const errors = super.getErrors()\n const actualRows = this.coreTable.length\n const expectedRows = parseInt(this.content)\n if (actualRows !== expectedRows)\n return errors.concat(this.makeError(`Expected '${expectedRows}' rows but got '${actualRows}'.`))\n return errors\n }\nscrollRenameParser\n // todo: add support in Parsers for tuple catch alls\n catchAllAtomType columnNameAtom newColumnNameAtom\n catchAllAtomType newColumnNameAtom\n extends abstractTableTransformParser\n description Rename columns.\n example\n tables\n data\n name,year,count\n index,2022,2\n rename name Name year Year\n printTable\n cue rename\n javascript\n get coreTable() {\n const {coreTable} = this.parent\n const {renameMap} = this\n if (!Object.keys(renameMap).length) return coreTable\n return coreTable.map(row => {\n const newRow = {}\n Object.keys(row).forEach(key => {\n const name = renameMap[key] || key\n newRow[name] = row[key]\n })\n return newRow\n })\n }\n get renameMap() {\n const map = {}\n const pairs = this.getAtomsFrom(1)\n let oldName\n while (oldName = pairs.shift()) {\n map[oldName] = pairs.shift()\n }\n return map\n }\n _renamed\n get columnNames() {\n if (this._renamed)\n return this._renamed\n const {renameMap} = this\n this._renamed = this.parent.columnNames.map(name => renameMap[name] || name )\n return this._renamed\n }\nscrollSummarizeParser\n extends abstractTableTransformParser\n description Generate summary statistics for each column.\n cue summarize\n example\n table data.csv\n summarize\n printTable\n javascript\n get coreTable() {\n const {lodash} = this.root\n const sourceData = this.parent.coreTable\n if (!sourceData.length) return []\n return this.parent.columnNames.map(colName => {\n const values = sourceData.map(row => row[colName]).filter(val => val !== undefined && val !== null)\n const numericValues = values.filter(val => typeof val === \"number\" && !isNaN(val))\n const sorted = [...numericValues].sort((a, b) => a - b)\n // Calculate mode\n const frequency = {}\n values.forEach(val => {\n frequency[val] = (frequency[val] || 0) + 1\n })\n const mode = Object.entries(frequency)\n .sort((a, b) => b[1] - a[1])\n .map(entry => entry[0])[0]\n // Calculate median for numeric values\n const median = sorted.length ? \n sorted.length % 2 === 0 \n ? (sorted[sorted.length/2 - 1] + sorted[sorted.length/2]) / 2\n : sorted[Math.floor(sorted.length/2)]\n : null\n const sum = numericValues.length ? numericValues.reduce((a, b) => a + b, 0) : null\n const theType = typeof values[0]\n const count = values.length\n const mean = theType === \"number\" ? sum/count : \"\"\n return {\n name: colName,\n type: theType,\n incompleteCount: sourceData.length - values.length,\n uniqueCount: new Set(values).size,\n count,\n sum,\n median,\n mean,\n min: sorted.length ? sorted[0] : null,\n max: sorted.length ? sorted[sorted.length - 1] : null,\n mode\n }\n })\n }\n get columnNames() {\n return [\"name\", \"type\", \"incompleteCount\", \"uniqueCount\", \"count\", \"sum\", \"median\", \"mean\", \"min\", \"max\", \"mode\"]\n }\nerrorParser\n baseParser errorParser\nhakonContentParser\n popularity 0.102322\n catchAllAtomType codeAtom\nheatrixCatchAllParser\n popularity 0.000193\n // todo Fill this out\n catchAllAtomType stringAtom\nlineOfTextParser\n popularity 0.000289\n catchAllAtomType stringAtom\n boolean isTextParser true\nhtmlLineParser\n popularity 0.005209\n catchAllAtomType htmlAnyAtom\n catchAllParser htmlLineParser\nopenGraphParser\n // todo: fix Parsers scope issue so we can move this parser def under scrollImageParser\n description Add this line to make this the open graph image.\n cueFromId\n atoms cueAtom\nimportToFooterParser\n description Import to bottom of file.\n atoms preBuildCommandAtom\n cue footer\nscriptLineParser\n catchAllAtomType javascriptAnyAtom\n catchAllParser scriptLineParser\nlinkTitleParser\n popularity 0.000048\n description If you want to set the title of the link.\n cue title\n atoms cueAtom\n catchAllAtomType stringAtom\n example\n * This report showed the treatment had a big impact.\n https://example.com/report This report.\n title The average growth in the treatment group was 14.2x higher than the control group.\nprogramLinkParser\n popularity 0.000531\n catchAllAtomType codeAtom\nscrollMediaLoopParser\n popularity 0.000048\n cue loop\n atoms cueAtom\nscrollAutoplayParser\n cue autoplay\n atoms cueAtom\nabstractCompilerRuleParser\n catchAllAtomType anyAtom\n atoms cueAtom\ncloseSubparticlesParser\n extends abstractCompilerRuleParser\n description When compiling a parent particle to a string, this string is appended to the compiled and joined subparticles. Default is blank.\n cueFromId\nindentCharacterParser\n extends abstractCompilerRuleParser\n description You can change the indent character for compiled subparticles. Default is a space.\n cueFromId\ncatchAllAtomDelimiterParser\n description If a particle has a catchAllAtom, this is the string delimiter that will be used to join those atoms. Default is comma.\n extends abstractCompilerRuleParser\n cueFromId\nopenSubparticlesParser\n extends abstractCompilerRuleParser\n description When compiling a parent particle to a string, this string is prepended to the compiled and joined subparticles. Default is blank.\n cueFromId\nstringTemplateParser\n extends abstractCompilerRuleParser\n description This template string is used to compile this line, and accepts strings of the format: const var = {someAtomId}\n cueFromId\njoinSubparticlesWithParser\n description When compiling a parent particle to a string, subparticles are compiled to strings and joined by this character. Default is a newline.\n extends abstractCompilerRuleParser\n cueFromId\nabstractConstantParser\n description A constant.\n atoms cueAtom\n cueFromId\n // todo: make tags inherit\n tags actPhase\nparsersBooleanParser\n cue boolean\n atoms cueAtom constantIdentifierAtom\n catchAllAtomType booleanAtom\n extends abstractConstantParser\n tags actPhase\nparsersFloatParser\n cue float\n atoms cueAtom constantIdentifierAtom\n catchAllAtomType floatAtom\n extends abstractConstantParser\n tags actPhase\nparsersIntParser\n cue int\n atoms cueAtom constantIdentifierAtom\n catchAllAtomType integerAtom\n tags actPhase\n extends abstractConstantParser\nparsersStringParser\n cue string\n atoms cueAtom constantIdentifierAtom\n catchAllAtomType stringAtom\n catchAllParser catchAllMultilineStringConstantParser\n extends abstractConstantParser\n tags actPhase\nabstractParserRuleParser\n single\n atoms cueAtom\nabstractNonTerminalParserRuleParser\n extends abstractParserRuleParser\nparsersBaseParserParser\n atoms cueAtom baseParsersAtom\n description Set for blobs or errors. \n // In rare cases with untyped content you can use a blobParser, for now, to skip parsing for performance gains. The base errorParser will report errors when parsed. Use that if you don't want to implement your own error parser.\n extends abstractParserRuleParser\n cue baseParser\n tags analyzePhase\ncatchAllAtomTypeParser\n atoms cueAtom atomTypeIdAtom\n description Use for lists.\n // Aka 'listAtomType'. Use this when the value in a key/value pair is a list. If there are extra atoms in the particle's line, parse these atoms as this type. Often used with `listDelimiterParser`.\n extends abstractParserRuleParser\n cueFromId\n tags analyzePhase\natomParserParser\n atoms cueAtom atomParserAtom\n description Set parsing strategy.\n // prefix/postfix/omnifix parsing strategy. If missing, defaults to prefix.\n extends abstractParserRuleParser\n cueFromId\n tags experimental analyzePhase\ncatchAllParserParser\n description Attach this to unmatched lines.\n // If a parser is not found in the inScope list, instantiate this type of particle instead.\n atoms cueAtom parserIdAtom\n extends abstractParserRuleParser\n cueFromId\n tags acquirePhase\nparsersAtomsParser\n catchAllAtomType atomTypeIdAtom\n description Set required atomTypes.\n extends abstractParserRuleParser\n cue atoms\n tags analyzePhase\nparsersCompilerParser\n // todo Remove this and its subparticles?\n description Deprecated. For simple compilers.\n inScope stringTemplateParser catchAllAtomDelimiterParser openSubparticlesParser closeSubparticlesParser indentCharacterParser joinSubparticlesWithParser\n extends abstractParserRuleParser\n cue compiler\n tags deprecate\n boolean suggestInAutocomplete false\nparserDescriptionParser\n description Parser description.\n catchAllAtomType stringAtom\n extends abstractParserRuleParser\n cue description\n tags assemblePhase\nparsersExampleParser\n // todo Should this just be a \"string\" constant on particles?\n description Set example for docs and tests.\n catchAllAtomType exampleAnyAtom\n catchAllParser catchAllExampleLineParser\n extends abstractParserRuleParser\n cue example\n tags assemblePhase\nextendsParserParser\n cue extends\n tags assemblePhase\n description Extend another parser.\n // todo: add a catchall that is used for mixins\n atoms cueAtom parserIdAtom\n extends abstractParserRuleParser\nparsersPopularityParser\n // todo Remove this parser. Switch to conditional frequencies.\n description Parser popularity.\n atoms cueAtom floatAtom\n extends abstractParserRuleParser\n cue popularity\n tags assemblePhase\ninScopeParser\n description Parsers in scope.\n catchAllAtomType parserIdAtom\n extends abstractParserRuleParser\n cueFromId\n tags acquirePhase\nparsersJavascriptParser\n // todo Urgently need to get submode syntax highlighting running! (And eventually LSP)\n description Javascript code for Parser Actions.\n catchAllParser catchAllJavascriptCodeLineParser\n extends abstractParserRuleParser\n tags actPhase\n javascript\n format() {\n if (this.isNodeJs()) {\n const template = `class FOO{ ${this.subparticlesToString()}}`\n this.setSubparticles(\n require(\"prettier\")\n .format(template, { semi: false, useTabs: true, parser: \"babel\", printWidth: 240 })\n .replace(/class FOO \\{\\s+/, \"\")\n .replace(/\\s+\\}\\s+$/, \"\")\n .replace(/\\n\\t/g, \"\\n\") // drop one level of indent\n .replace(/\\t/g, \" \") // we used tabs instead of spaces to be able to dedent without breaking literals.\n )\n }\n return this\n }\n cue javascript\nabstractParseRuleParser\n // Each particle should have a pattern that it matches on unless it's a catch all particle.\n extends abstractParserRuleParser\n cueFromId\nparsersCueParser\n atoms cueAtom stringAtom\n description Attach by matching first atom.\n extends abstractParseRuleParser\n tags acquirePhase\n cue cue\ncueFromIdParser\n atoms cueAtom\n description Derive cue from parserId.\n // for example 'fooParser' would have cue of 'foo'.\n extends abstractParseRuleParser\n tags acquirePhase\nparsersPatternParser\n catchAllAtomType regexAtom\n description Attach via regex.\n extends abstractParseRuleParser\n tags acquirePhase\n cue pattern\nparsersRequiredParser\n description Assert is present at least once.\n extends abstractParserRuleParser\n cue required\n tags analyzePhase\nabstractValidationRuleParser\n extends abstractParserRuleParser\n cueFromId\n catchAllAtomType booleanAtom\nparsersSingleParser\n description Assert used once.\n // Can be overridden by a child class by setting to false.\n extends abstractValidationRuleParser\n tags analyzePhase\n cue single\nuniqueLineParser\n description Assert unique lines. For pattern parsers.\n // Can be overridden by a child class by setting to false.\n extends abstractValidationRuleParser\n tags analyzePhase\nuniqueCueParser\n description Assert unique first atoms. For pattern parsers.\n // For catch all parsers or pattern particles, use this to indicate the \n extends abstractValidationRuleParser\n tags analyzePhase\nlistDelimiterParser\n description Split content by this delimiter.\n extends abstractParserRuleParser\n cueFromId\n catchAllAtomType stringAtom\n tags analyzePhase\ncontentKeyParser\n description Deprecated. For to/from JSON.\n // Advanced keyword to help with isomorphic JSON serialization/deserialization. If present will serialize the particle to an object and set a property with this key and the value set to the particle's content.\n extends abstractParserRuleParser\n cueFromId\n catchAllAtomType stringAtom\n tags deprecate\n boolean suggestInAutocomplete false\nsubparticlesKeyParser\n // todo: deprecate?\n description Deprecated. For to/from JSON.\n // Advanced keyword to help with serialization/deserialization of blobs. If present will serialize the particle to an object and set a property with this key and the value set to the particle's subparticles.\n extends abstractParserRuleParser\n cueFromId\n catchAllAtomType stringAtom\n tags deprecate\n boolean suggestInAutocomplete false\nparsersTagsParser\n catchAllAtomType stringAtom\n extends abstractParserRuleParser\n description Custom metadata.\n cue tags\n tags assemblePhase\natomTypeDescriptionParser\n description Atom Type description.\n catchAllAtomType stringAtom\n cue description\n tags assemblePhase\ncatchAllErrorParser\n baseParser errorParser\ncatchAllExampleLineParser\n catchAllAtomType exampleAnyAtom\n catchAllParser catchAllExampleLineParser\n atoms exampleAnyAtom\ncatchAllJavascriptCodeLineParser\n catchAllAtomType javascriptCodeAtom\n catchAllParser catchAllJavascriptCodeLineParser\ncatchAllMultilineStringConstantParser\n description String constants can span multiple lines.\n catchAllAtomType stringAtom\n catchAllParser catchAllMultilineStringConstantParser\n atoms stringAtom\natomTypeDefinitionParser\n // todo Generate a class for each atom type?\n // todo Allow abstract atom types?\n // todo Change pattern to postfix.\n pattern ^[a-zA-Z0-9_]+Atom$\n inScope parsersPaintParser parsersRegexParser reservedAtomsParser enumFromAtomTypesParser atomTypeDescriptionParser parsersEnumParser slashCommentParser extendsAtomTypeParser parsersExamplesParser atomMinParser atomMaxParser\n atoms atomTypeIdAtom\n tags assemblePhase\n javascript\n buildHtml() {return \"\"}\nenumFromAtomTypesParser\n description Runtime enum options.\n catchAllAtomType atomTypeIdAtom\n atoms atomPropertyNameAtom\n cueFromId\n tags analyzePhase\nparsersEnumParser\n description Set enum options.\n cue enum\n catchAllAtomType enumOptionAtom\n atoms atomPropertyNameAtom\n tags analyzePhase\nparsersExamplesParser\n description Examples for documentation and tests.\n // If the domain of possible atom values is large, such as a string type, it can help certain methods—such as program synthesis—to provide a few examples.\n cue examples\n catchAllAtomType atomExampleAtom\n atoms atomPropertyNameAtom\n tags assemblePhase\natomMinParser\n description Specify a min if numeric.\n cue min\n atoms atomPropertyNameAtom numberAtom\n tags analyzePhase\natomMaxParser\n description Specify a max if numeric.\n cue max\n atoms atomPropertyNameAtom numberAtom\n tags analyzePhase\nparsersPaintParser\n atoms cueAtom paintTypeAtom\n description Instructor editor how to color these.\n single\n cue paint\n tags analyzePhase\nparserDefinitionParser\n // todo Add multiple dispatch?\n pattern ^[a-zA-Z0-9_]+Parser$\n description Parser types are a core unit of your language. They translate to 1 class per parser. Examples of parser would be \"header\", \"person\", \"if\", \"+\", \"define\", etc.\n catchAllParser catchAllErrorParser\n inScope abstractParserRuleParser abstractConstantParser slashCommentParser parserDefinitionParser\n atoms parserIdAtom\n tags assemblePhase\n javascript\n buildHtml() { return \"\"}\nparsersRegexParser\n catchAllAtomType regexAtom\n description Atoms must match this.\n single\n atoms atomPropertyNameAtom\n cue regex\n tags analyzePhase\nreservedAtomsParser\n single\n description Atoms can't be any of these.\n catchAllAtomType reservedAtomAtom\n atoms atomPropertyNameAtom\n cueFromId\n tags analyzePhase\nextendsAtomTypeParser\n cue extends\n description Extend another atomType.\n // todo Add mixin support in addition to extends?\n atoms cueAtom atomTypeIdAtom\n tags assemblePhase\n single\nabstractColumnNameParser\n atoms cueAtom columnNameAtom\n javascript\n getRunTimeEnumOptions(atom) {\n if (atom.atomTypeId === \"columnNameAtom\")\n return this.parent.columnNames\n return super.getRunTimeEnumOptions(atom)\n }\nscrollRadiusParser\n cue radius\n extends abstractColumnNameParser\nscrollSymbolParser\n cue symbol\n extends abstractColumnNameParser\nabstractColumnNameOrColorParser\n extends abstractColumnNameParser\n atoms cueAtom columnNameOrColorAtom\n javascript\n //todo: cleanup\n colorOptions = \"aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkkhaki darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray darkturquoise darkviolet deeppink deepskyblue dimgray dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow honeydew hotpink indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgoldenrodyellow lightgray lightgreen lightpink lightsalmon lightseagreen lightskyblue lightslategray lightsteelblue lightyellow lime limegreen linen magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell sienna silver skyblue slateblue slategray snow springgreen steelblue tan teal thistle tomato turquoise violet wheat white whitesmoke yellow yellowgreen\".split(\" \")\n getRunTimeEnumOptions(atom) {\n if (atom.atomTypeId === \"columnNameOrColorAtom\")\n return this.parent.columnNames.join(this.colorOptions)\n return super.getRunTimeEnumOptions(atom)\n }\nscrollFillParser\n cue fill\n extends abstractColumnNameOrColorParser\nscrollStrokeParser\n cue stroke\n extends abstractColumnNameOrColorParser\nscrollLabelParser\n cue label\n extends abstractColumnNameParser\nscrollSortParser\n cue sort\n extends abstractColumnNameParser\nscrollXParser\n cue x\n extends abstractColumnNameParser\nscrollYParser\n cue y\n extends abstractColumnNameParser\nabstractPlotLabelParser\n cueFromId\n atoms cueAtom\n catchAllAtomType stringAtom\nquoteLineParser\n popularity 0.004172\n catchAllAtomType stringAtom\n catchAllParser quoteLineParser\nscrollParser\n description Scroll is a language for scientists of all ages. Refine, share and collaborate on ideas.\n root\n inScope abstractScrollParser blankLineParser atomTypeDefinitionParser parserDefinitionParser\n catchAllParser catchAllParagraphParser\n javascript\n setFile(file) {\n this.file = file\n const date = this.get(\"date\")\n if (date) this.file.timestamp = this.dayjs(this.get(\"date\")).unix()\n return this\n }\n buildHtml(buildSettings) {\n this.sectionStack = []\n return this.filter(subparticle => subparticle.buildHtml).map(subparticle => { try {return subparticle.buildHtml(buildSettings)} catch (err) {console.error(err); return \"\"} }).filter(i => i).join(\"\\n\") + this.clearSectionStack()\n }\n sectionStack = []\n clearSectionStack() {\n const result = this.sectionStack.join(\"\\n\")\n this.sectionStack = []\n return result\n }\n bodyStack = []\n clearBodyStack() {\n const result = this.bodyStack.join(\"\")\n this.bodyStack = []\n return result\n }\n get hakonParser() {\n if (this.isNodeJs())\n return require(\"scrollsdk/products/hakon.nodejs.js\")\n return hakonParser\n }\n readSyncFromFileOrUrl(fileOrUrl) {\n if (!this.isNodeJs()) return this.getInBrowser(fileOrUrl)\n const isUrl = fileOrUrl.match(/^https?\\:[^ ]+$/)\n if (!isUrl) return this.root.readFile(fileOrUrl)\n return this.readFile(this.makeFullPath(new URL(fileOrUrl).pathname.split('/').pop()))\n }\n getInBrowser(key) {\n return localStorage.getItem(key) || (window.inMemStorage ? window.inMemStorage[key] : \"\") || \"\"\n }\n async fetch(url, filename) {\n const isUrl = url.match(/^https?\\:[^ ]+$/)\n if (!isUrl) return\n return this.isNodeJs() ? this.fetchNode(url, filename) : this.fetchBrowser(url)\n }\n get path() {\n return require(\"path\")\n }\n makeFullPath(filename) {\n return this.path.join(this.folderPath, filename)\n }\n _nextAndPrevious(arr, index) {\n const nextIndex = index + 1\n const previousIndex = index - 1\n return {\n previous: arr[previousIndex] ?? arr[arr.length - 1],\n next: arr[nextIndex] ?? arr[0]\n }\n }\n // keyboard nav is always in the same folder. does not currently support cross folder\n includeFileInKeyboardNav(file) {\n const { scrollProgram } = file\n return scrollProgram.buildsHtml && scrollProgram.hasKeyboardNav && scrollProgram.tags.includes(this.primaryTag)\n }\n get timeIndex() {\n return this.file.timeIndex || 0\n }\n get linkToPrevious() {\n if (!this.hasKeyboardNav)\n // Dont provide link to next unless keyboard nav is on\n return undefined\n const {allScrollFiles} = this\n let file = this._nextAndPrevious(allScrollFiles, this.timeIndex).previous\n while (!this.includeFileInKeyboardNav(file)) {\n file = this._nextAndPrevious(allScrollFiles, file.timeIndex).previous\n }\n return file.scrollProgram.permalink\n }\n importRegex = /^(import |[a-zA-Z\\_\\-\\.0-9\\/]+\\.(scroll|parsers)$|https?:\\/\\/.+\\.(scroll|parsers)$)/gm\n get linkToNext() {\n if (!this.hasKeyboardNav)\n // Dont provide link to next unless keyboard nav is on\n return undefined\n const {allScrollFiles} = this\n let file = this._nextAndPrevious(allScrollFiles, this.timeIndex).next\n while (!this.includeFileInKeyboardNav(file)) {\n file = this._nextAndPrevious(allScrollFiles, file.timeIndex).next\n }\n return file.scrollProgram.permalink\n }\n // todo: clean up this naming pattern and add a parser instead of special casing 404.html\n get allHtmlFiles() {\n return this.allScrollFiles.filter(file => file.scrollProgram.buildsHtml && file.scrollProgram.permalink !== \"404.html\")\n }\n parseNestedTag(tag) {\n if (!tag.includes(\"/\")) return;\n const {path} = this\n const parts = tag.split(\"/\")\n const group = parts.pop()\n const relativePath = parts.join(\"/\")\n return {\n group,\n relativePath,\n folderPath: path.join(this.folderPath, path.normalize(relativePath))\n }\n }\n getFilesByTags(tags, limit) {\n // todo: tags is currently matching partial substrings\n const getFilesWithTag = (tag, files) => files.filter(file => file.scrollProgram.buildsHtml && file.scrollProgram.tags.includes(tag))\n if (typeof tags === \"string\") tags = tags.split(\" \")\n if (!tags || !tags.length)\n return this.allHtmlFiles\n .filter(file => file !== this) // avoid infinite loops. todo: think this through better.\n .map(file => {\n return { file, relativePath: \"\" }\n })\n .slice(0, limit)\n let arr = []\n tags.forEach(tag => {\n if (!tag.includes(\"/\"))\n return (arr = arr.concat(\n getFilesWithTag(tag, this.allScrollFiles)\n .map(file => {\n return { file, relativePath: \"\" }\n })\n .slice(0, limit)\n ))\n const {folderPath, group, relativePath} = this.parseNestedTag(tag)\n let files = []\n try {\n files = this.fileSystem.getCachedLoadedFilesInFolder(folderPath, this)\n } catch (err) {\n console.error(err)\n }\n const filtered = getFilesWithTag(group, files).map(file => {\n return { file, relativePath: relativePath + \"/\" }\n })\n arr = arr.concat(filtered.slice(0, limit))\n })\n return this.lodash.sortBy(arr, file => file.file.timestamp).reverse()\n }\n async fetchNode(url, filename) {\n filename = filename || new URL(url).pathname.split('/').pop()\n const fullpath = this.makeFullPath(filename)\n if (require(\"fs\").existsSync(fullpath)) return this.readFile(fullpath)\n this.log(`🛜 fetching ${url} to ${fullpath} `)\n await this.downloadToDisk(url, fullpath)\n return this.readFile(fullpath)\n }\n log(message) {\n if (this.logger) this.logger.log(message)\n }\n async fetchBrowser(url) {\n const content = this.getInBrowser(url)\n if (content) return content\n return this.downloadToLocalStorage(url)\n }\n async downloadToDisk(url, destination) {\n const { writeFile } = require('fs').promises\n const response = await fetch(url)\n const fileBuffer = await response.arrayBuffer()\n await writeFile(destination, Buffer.from(fileBuffer))\n return this.readFile(destination)\n }\n async downloadToLocalStorage(url) {\n const response = await fetch(url)\n const blob = await response.blob()\n const text = await blob.text()\n try {\n localStorage.setItem(url, text)\n return localStorage.getItem(url)\n } catch (err) {\n if (!window.inMemStorage) window.inMemStorage = {}\n window.inMemStorage[url] = text\n console.error(err)\n return text\n }\n }\n readFile(filename) {\n const {path} = this\n const fs = require(\"fs\")\n const fullPath = path.join(this.folderPath, filename.replace(this.folderPath, \"\"))\n try {\n if (fs.existsSync(fullPath))\n return fs.readFileSync(fullPath, \"utf8\")\n console.error(`File '${filename}' not found`)\n return \"\"\n } catch (err) {\n console.error(`Error in '${this.filePath}' reading file: '${fullPath}'`)\n console.error(err)\n return \"\"\n }\n }\n alreadyRequired = new Set()\n buildHtmlSnippet(buildSettings) {\n this.sectionStack = []\n return this.map(subparticle => (subparticle.buildHtmlSnippet ? subparticle.buildHtmlSnippet(buildSettings) : subparticle.buildHtml(buildSettings)))\n .filter(i => i)\n .join(\"\\n\")\n .trim() + this.clearSectionStack()\n }\n get footnotes() {\n if (this._footnotes === undefined) this._footnotes = this.filter(particle => particle.isFootnote)\n return this._footnotes\n }\n get authors() {\n return this.get(\"authors\")\n }\n get allScrollFiles() {\n try {\n return this.fileSystem.getCachedLoadedFilesInFolder(this.folderPath, this)\n } catch (err) {\n console.error(err)\n return []\n }\n }\n async doThing(thing) {\n await Promise.all(this.filter(particle => particle[thing]).map(async particle => particle[thing]()))\n }\n async load() {\n await this.doThing(\"load\")\n }\n async execute() {\n await this.doThing(\"execute\")\n }\n file = {}\n getFromParserId(parserId) {\n return this.parserIdIndex[parserId]?.[0].content\n }\n get fileSystem() {\n return this.file.fileSystem\n }\n get filePath() {\n return this.file.filePath\n }\n get folderPath() {\n return this.file.folderPath\n }\n get filename() {\n return this.file.filename || \"\"\n }\n get hasKeyboardNav() {\n return this.has(\"keyboardNav\")\n }\n get editHtml() {\n return `<a href=\"${this.editUrl}\" class=\"abstractTextLinkParser\">Edit</a>`\n }\n get externalsPath() {\n return this.file.EXTERNALS_PATH\n }\n get endSnippetIndex() {\n // Get the line number that the snippet should stop at.\n // First if its hard coded, use that\n if (this.has(\"endSnippet\")) return this.getParticle(\"endSnippet\").index\n // Next look for a dinkus\n const snippetBreak = this.find(particle => particle.isDinkus)\n if (snippetBreak) return snippetBreak.index\n return -1\n }\n get parserIds() {\n return this.topDownArray.map(particle => particle.definition.id)\n }\n get tags() {\n return this.get(\"tags\") || \"\"\n }\n get primaryTag() {\n return this.tags.split(\" \")[0]\n }\n get filenameNoExtension() {\n return this.filename.replace(\".scroll\", \"\")\n }\n // todo: rename publishedUrl? Or something to indicate that this is only for stuff on the web (not localhost)\n // BaseUrl must be provided for RSS Feeds and OpenGraph tags to work\n get baseUrl() {\n const baseUrl = (this.get(\"baseUrl\") || \"\").replace(/\\/$/, \"\")\n return baseUrl + \"/\"\n }\n get canonicalUrl() {\n return this.get(\"canonicalUrl\") || this.baseUrl + this.permalink\n }\n get openGraphImage() {\n const openGraphImage = this.get(\"openGraphImage\")\n if (openGraphImage !== undefined) return this.ensureAbsoluteLink(openGraphImage)\n const images = this.filter(particle => particle.doesExtend(\"scrollImageParser\"))\n const hit = images.find(particle => particle.has(\"openGraph\")) || images[0]\n if (!hit) return \"\"\n return this.ensureAbsoluteLink(hit.filename)\n }\n get absoluteLink() {\n return this.ensureAbsoluteLink(this.permalink)\n }\n ensureAbsoluteLink(link) {\n if (link.includes(\"://\")) return link\n return this.baseUrl + link.replace(/^\\//, \"\")\n }\n get editUrl() {\n const editUrl = this.get(\"editUrl\")\n if (editUrl) return editUrl\n const editBaseUrl = this.get(\"editBaseUrl\")\n return (editBaseUrl ? editBaseUrl.replace(/\\/$/, \"\") + \"/\" : \"\") + this.filename\n }\n get gitRepo() {\n // given https://github.com/breck7/breckyunits.com/blob/main/four-tips-to-improve-communication.scroll\n // return https://github.com/breck7/breckyunits.com\n return this.editUrl.split(\"/\").slice(0, 5).join(\"/\")\n }\n get scrollVersion() {\n // currently manually updated\n return \"168.1.0\"\n }\n // Use the first paragraph for the description\n // todo: add a particle method version of get that gets you the first particle. (actulaly make get return array?)\n // would speed up a lot.\n get description() {\n const description = this.getFromParserId(\"openGraphDescriptionParser\")\n if (description) return description\n return this.generatedDescription\n }\n get keywords() {\n if (this.has(\"keywords\"))\n return this.get(\"keywords\")\n const tags = this.get(\"tags\")\n if (tags)\n return tags.split(\" \").join(\", \")\n return \"\"\n }\n get generatedDescription() {\n const firstParagraph = this.find(particle => particle.isArticleContent)\n return firstParagraph ? firstParagraph.originalText.substr(0, 100).replace(/[&\"<>']/g, \"\") : \"\"\n }\n get titleFromFilename() {\n const unCamelCase = str => str.replace(/([a-z])([A-Z])/g, \"$1 $2\").replace(/^./, match => match.toUpperCase())\n return unCamelCase(this.filenameNoExtension)\n }\n get title() {\n return this.getFromParserId(\"scrollTitleParser\") || this.titleFromFilename\n }\n get linkTitle() {\n return this.getFromParserId(\"scrollLinkTitleParser\") || this.title\n }\n get permalink() {\n return this.get(\"permalink\") || (this.filename ? this.filenameNoExtension + \".html\" : \"\")\n }\n compileTo(extensionCapitalized) {\n if (extensionCapitalized === \"Txt\")\n return this.asTxt\n if (extensionCapitalized === \"Html\")\n return this.asHtml\n const methodName = \"build\" + extensionCapitalized\n return this.topDownArray\n .filter(particle => particle[methodName])\n .map((particle, index) => particle[methodName](index))\n .join(\"\\n\")\n .trim()\n }\n get asTxt() {\n return (\n this.map(particle => {\n const text = particle.buildTxt ? particle.buildTxt() : \"\"\n if (text) return text + \"\\n\"\n if (!particle.getLine().length) return \"\\n\"\n return \"\"\n })\n .join(\"\")\n .replace(/<[^>]*>/g, \"\")\n .replace(/\\n\\n\\n+/g, \"\\n\\n\") // Maximum 2 newlines in a row\n .trim() + \"\\n\" // Always end in a newline, Posix style\n )\n }\n get dependencies() {\n const dependencies = this.file.dependencies?.slice() || []\n const files = this.topDownArray.filter(particle => particle.dependencies).map(particle => particle.dependencies).flat()\n return dependencies.concat(files)\n }\n get buildsHtml() {\n const { permalink } = this\n return !this.file.importOnly && (permalink.endsWith(\".html\") || permalink.endsWith(\".htm\"))\n }\n // Without specifying the language hyphenation will not work.\n get lang() {\n return this.get(\"htmlLang\") || \"en\"\n }\n _compiledHtml = \"\"\n get asHtml() {\n if (!this._compiledHtml) {\n const { permalink, buildsHtml } = this\n const content = (this.buildHtml() + this.clearBodyStack()).trim()\n // Don't add html tags to CSV feeds. A little hacky as calling a getter named _html_ to get _xml_ is not ideal. But\n // <1% of use case so might be good enough.\n const wrapWithHtmlTags = buildsHtml\n const bodyTag = this.has(\"metaTags\") ? \"\" : \"<body>\\n\"\n this._compiledHtml = wrapWithHtmlTags ? `<!DOCTYPE html>\\n<html lang=\"${this.lang}\">\\n${bodyTag}${content}\\n</body>\\n</html>` : content\n }\n return this._compiledHtml\n }\n get wordCount() {\n return this.asTxt.match(/\\b\\w+\\b/g)?.length || 0\n }\n get minutes() {\n return parseFloat((this.wordCount / 200).toFixed(1))\n }\n get date() {\n const date = this.get(\"date\") || (this.file.timestamp ? this.file.timestamp : 0)\n return this.dayjs(date).format(`MM/DD/YYYY`)\n }\n get year() {\n return parseInt(this.dayjs(this.date).format(`YYYY`))\n }\n get dayjs() {\n if (!this.isNodeJs()) return dayjs\n const lib = require(\"dayjs\")\n const relativeTime = require(\"dayjs/plugin/relativeTime\")\n lib.extend(relativeTime)\n return lib\n }\n get lodash() {\n return this.isNodeJs() ? require(\"lodash\") : lodash\n }\n get d3() {\n return this.isNodeJs() ? require('d3') : d3\n }\n getConcepts(parsed) {\n const concepts = []\n let currentConcept\n parsed.forEach(particle => {\n if (particle.isConceptDelimiter) {\n if (currentConcept) concepts.push(currentConcept)\n currentConcept = []\n }\n if (currentConcept && particle.isMeasure) currentConcept.push(particle)\n })\n if (currentConcept) concepts.push(currentConcept)\n return concepts\n }\n _formatConcepts(parsed) {\n const concepts = this.getConcepts(parsed)\n if (!concepts.length) return false\n const {lodash} = this\n // does a destructive sort in place on the parsed program\n concepts.forEach(concept => {\n let currentSection\n const newCode = lodash\n .sortBy(concept, [\"sortIndex\"])\n .map(particle => {\n let newLines = \"\"\n const section = particle.sortIndex.toString().split(\".\")[0]\n if (section !== currentSection) {\n currentSection = section\n newLines = \"\\n\"\n }\n return newLines + particle.toString()\n })\n .join(\"\\n\")\n concept.forEach((particle, index) => (index ? particle.destroy() : \"\"))\n concept[0].replaceParticle(() => newCode)\n })\n }\n get formatted() {\n return this.getFormatted(this.file.codeAtStart)\n }\n get lastCommitTime() {\n // todo: speed this up and do a proper release. also could add more metrics like this.\n if (this._lastCommitTime === undefined) {\n try {\n this._lastCommitTime = require(\"child_process\").execSync(`git log -1 --format=\"%at\" -- \"${this.filePath}\"`).toString().trim()\n } catch (err) {\n this._lastCommitTime = 0\n }\n }\n return this._lastCommitTime\n }\n getFormatted(codeAtStart = this.toString()) {\n let formatted = codeAtStart.replace(/\\r/g, \"\") // remove all carriage returns if there are any\n const parsed = new this.constructor(formatted)\n parsed.topDownArray.forEach(subparticle => {\n subparticle.format()\n const original = subparticle.getLine()\n const trimmed = original.replace(/(\\S.*?)[ \\t]*$/gm, \"$1\")\n // Trim trailing whitespace unless parser allows it\n if (original !== trimmed && !subparticle.allowTrailingWhitespace) subparticle.setLine(trimmed)\n })\n this._formatConcepts(parsed)\n let importOnlys = []\n let topMatter = []\n let allElse = []\n // Create any bindings\n parsed.forEach(particle => {\n if (particle.bindTo === \"next\") particle.binding = particle.next\n if (particle.bindTo === \"previous\") particle.binding = particle.previous\n })\n parsed.forEach(particle => {\n if (particle.getLine() === \"importOnly\") importOnlys.push(particle)\n else if (particle.isTopMatter) topMatter.push(particle)\n else allElse.push(particle)\n })\n const combined = importOnlys.concat(topMatter, allElse)\n // Move any bound particles\n combined\n .filter(particle => particle.bindTo)\n .forEach(particle => {\n // First remove the particle from its current position\n const originalIndex = combined.indexOf(particle)\n combined.splice(originalIndex, 1)\n // Then insert it at the new position\n // We need to find the binding index again after removal\n const bindingIndex = combined.indexOf(particle.binding)\n if (particle.bindTo === \"next\") combined.splice(bindingIndex, 0, particle)\n else combined.splice(bindingIndex + 1, 0, particle)\n })\n const trimmed = combined\n .map(particle => particle.toString())\n .join(\"\\n\")\n .replace(/^\\n*/, \"\") // Remove leading newlines\n .replace(/\\n\\n\\n+/g, \"\\n\\n\") // Maximum 2 newlines in a row\n .replace(/\\n+$/, \"\")\n return trimmed === \"\" ? trimmed : trimmed + \"\\n\" // End non blank Scroll files in a newline character POSIX style for better working with tools like git\n }\n get parser() {\n return this.constructor\n }\n get parsersRequiringExternals() {\n const { parser } = this\n // todo: could be cleaned up a bit\n if (!parser.parsersRequiringExternals) parser.parsersRequiringExternals = parser.cachedHandParsersProgramRoot.filter(particle => particle.copyFromExternal).map(particle => particle.atoms[0])\n return parser.parsersRequiringExternals\n }\n get Disk() { return this.isNodeJs() ? require(\"scrollsdk/products/Disk.node.js\").Disk : {}}\n async buildAll(options = {}) {\n await this.load()\n await this.buildOne(options)\n await this.buildTwo(options)\n }\n async buildOne(options) {\n await this.execute()\n const toBuild = this.filter(particle => particle.buildOne)\n for (let particle of toBuild) {\n await particle.buildOne(options)\n }\n }\n async buildTwo(options) {\n const toBuild = this.filter(particle => particle.buildTwo)\n for (let particle of toBuild) {\n await particle.buildTwo(options)\n }\n }\n get outputFileNames() {\n return this.filter(p => p.outputFileNames).map(p => p.outputFileNames).flat()\n }\n _compileArray(filename, arr) {\n const removeBlanks = data => data.map(obj => Object.fromEntries(Object.entries(obj).filter(([_, value]) => value !== \"\")))\n const parts = filename.split(\".\")\n const format = parts.pop()\n if (format === \"json\") return JSON.stringify(removeBlanks(arr), null, 2)\n if (format === \"js\") return `const ${parts[0]} = ` + JSON.stringify(removeBlanks(arr), null, 2)\n if (format === \"csv\") return this.arrayToCSV(arr)\n if (format === \"tsv\") return this.arrayToCSV(arr, \"\\t\")\n if (format === \"particles\") return particles.toString()\n return particles.toString()\n }\n levenshteinDistance(a, b) {\n const m = a.length\n const n = b.length\n const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0))\n for (let i = 0; i <= m; i++) {\n dp[i][0] = i\n }\n for (let j = 0; j <= n; j++) {\n dp[0][j] = j\n }\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1\n dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost)\n }\n }\n return dp[m][n]\n }\n makeLodashOrderByParams(str) {\n const part1 = str.split(\" \")\n const part2 = part1.map(col => (col.startsWith(\"-\") ? \"desc\" : \"asc\"))\n return [part1.map(col => col.replace(/^\\-/, \"\")), part2]\n }\n arrayToCSV(data, delimiter = \",\") {\n if (!data.length) return \"\"\n // Extract headers\n const headers = Object.keys(data[0])\n const csv = data.map(row =>\n headers\n .map(fieldName => {\n const fieldValue = row[fieldName]\n // Escape commas if the value is a string\n if (typeof fieldValue === \"string\" && fieldValue.includes(delimiter)) {\n return `\"${fieldValue.replace(/\"/g, '\"\"')}\"` // Escape double quotes and wrap in double quotes\n }\n return fieldValue\n })\n .join(delimiter)\n )\n csv.unshift(headers.join(delimiter)) // Add header row at the top\n return csv.join(\"\\n\")\n }\n compileConcepts(filename = \"csv\", sortBy = \"\") {\n const {lodash} = this\n if (!sortBy) return this._compileArray(filename, this.concepts)\n const orderBy = this.makeLodashOrderByParams(sortBy)\n return this._compileArray(filename, lodash.orderBy(this.concepts, orderBy[0], orderBy[1]))\n }\n _withStats\n get measuresWithStats() {\n if (!this._withStats) this._withStats = this.addMeasureStats(this.concepts, this.measures)\n return this._withStats\n }\n addMeasureStats(concepts, measures){\n return measures.map(measure => {\n let Type = false\n concepts.forEach(concept => {\n const value = concept[measure.Name]\n if (value === undefined || value === \"\") return\n measure.Values++\n if (!Type) {\n measure.Example = value.toString().replace(/\\n/g, \" \")\n measure.Type = typeof value\n Type = true\n }\n })\n measure.Coverage = Math.floor((100 * measure.Values) / concepts.length) + \"%\"\n return measure\n })\n }\n parseMeasures(parser) {\n if (!Particle.measureCache)\n Particle.measureCache = new Map()\n const measureCache = Particle.measureCache\n if (measureCache.get(parser)) return measureCache.get(parser)\n const {lodash} = this\n // todo: clean this up\n const getCueAtoms = rootParserProgram =>\n rootParserProgram\n .filter(particle => particle.getLine().endsWith(\"Parser\") && !particle.getLine().startsWith(\"abstract\"))\n .map(particle => particle.get(\"cue\") || particle.getLine())\n .map(line => line.replace(/Parser$/, \"\"))\n // Generate a fake program with one of every of the available parsers. Then parse it. Then we can easily access the meta data on the parsers\n const dummyProgram = new parser(\n Array.from(\n new Set(\n getCueAtoms(parser.cachedHandParsersProgramRoot) // is there a better method name than this?\n )\n ).join(\"\\n\")\n )\n // Delete any particles that are not measures\n dummyProgram.filter(particle => !particle.isMeasure).forEach(particle => particle.destroy())\n dummyProgram.forEach(particle => {\n // add nested measures\n Object.keys(particle.definition.cueMapWithDefinitions).forEach(key => particle.appendLine(key))\n })\n // Delete any nested particles that are not measures\n dummyProgram.topDownArray.filter(particle => !particle.isMeasure).forEach(particle => particle.destroy())\n const measures = dummyProgram.topDownArray.map(particle => {\n return {\n Name: particle.measureName,\n Values: 0,\n Coverage: 0,\n Question: particle.definition.description,\n Example: particle.definition.getParticle(\"example\")?.subparticlesToString() || \"\",\n Type: particle.typeForWebForms,\n Source: particle.sourceDomain,\n //Definition: parsedProgram.root.filename + \":\" + particle.lineNumber\n SortIndex: particle.sortIndex,\n IsComputed: particle.isComputed,\n IsRequired: particle.isMeasureRequired,\n IsConceptDelimiter: particle.isConceptDelimiter,\n Cue: particle.definition.get(\"cue\")\n }\n })\n measureCache.set(parser, lodash.sortBy(measures, \"SortIndex\"))\n return measureCache.get(parser)\n }\n _concepts\n get concepts() {\n if (this._concepts) return this._concepts\n this._concepts = this.parseConcepts(this, this.measures)\n return this._concepts\n }\n _measures\n get measures() {\n if (this._measures) return this._measures\n this._measures = this.parseMeasures(this.parser)\n return this._measures\n }\n parseConcepts(parsedProgram, measures){\n // Todo: might be a perf/memory/simplicity win to have a \"segment\" method in ScrollSDK, where you could\n // virtually split a Particle into multiple segments, and then query on those segments.\n // So we would \"segment\" on \"id \", and then not need to create a bunch of new objects, and the original\n // already parsed lines could then learn about/access to their respective segments.\n const conceptDelimiter = measures.filter(measure => measure.IsConceptDelimiter)[0]\n if (!conceptDelimiter) return []\n const concepts = parsedProgram.split(conceptDelimiter.Cue || conceptDelimiter.Name)\n concepts.shift() // Remove the part before \"id\"\n return concepts.map(concept => {\n const row = {}\n measures.forEach(measure => {\n const measureName = measure.Name\n const measureKey = measure.Cue || measureName.replace(/_/g, \" \")\n if (!measure.IsComputed) row[measureName] = concept.getParticle(measureKey)?.measureValue ?? \"\"\n else row[measureName] = this.computeMeasure(parsedProgram, measureName, concept, concepts)\n })\n return row\n })\n }\n computeMeasure(parsedProgram, measureName, concept, concepts){\n // note that this is currently global, assuming there wont be. name conflicts in computed measures in a single scroll\n if (!Particle.measureFnCache) Particle.measureFnCache = {}\n const measureFnCache = Particle.measureFnCache\n if (!measureFnCache[measureName]) {\n // a bit hacky but works??\n const particle = parsedProgram.appendLine(measureName)\n measureFnCache[measureName] = particle.computeValue\n particle.destroy()\n }\n return measureFnCache[measureName](concept, measureName, parsedProgram, concepts)\n }\n compileMeasures(filename = \"csv\", sortBy = \"\") {\n const withStats = this.measuresWithStats\n if (!sortBy) return this._compileArray(filename, withStats)\n const orderBy = this.makeLodashOrderByParams(sortBy)\n return this._compileArray(filename, this.lodash.orderBy(withStats, orderBy[0], orderBy[1]))\n }\n evalNodeJsMacros(value, macroMap, filePath) {\n const tempPath = filePath + \".js\"\n const {Disk} = this\n if (Disk.exists(tempPath)) throw new Error(`Failed to write/require replaceNodejs snippet since '${tempPath}' already exists.`)\n try {\n Disk.write(tempPath, value)\n const results = require(tempPath)\n Object.keys(results).forEach(key => (macroMap[key] = results[key]))\n } catch (err) {\n console.error(`Error in evalMacros in file '${filePath}'`)\n console.error(err)\n } finally {\n Disk.rm(tempPath)\n }\n }\n evalMacros(fusedFile) {\n const {fusedCode, codeAtStart, filePath} = fusedFile\n let code = fusedCode\n const absolutePath = filePath\n // note: the 2 params above are not used in this method, but may be used in user eval code. (todo: cleanup)\n const regex = /^(replace|toFooter$)/gm\n if (!regex.test(code)) return code\n const particle = new Particle(code) // todo: this can be faster. a more lightweight particle class?\n // Process macros\n const macroMap = {}\n particle\n .filter(particle => {\n const parserAtom = particle.cue\n return parserAtom === \"replace\" || parserAtom === \"replaceJs\" || parserAtom === \"replaceNodejs\"\n })\n .forEach(particle => {\n let value = particle.length ? particle.subparticlesToString() : particle.getAtomsFrom(2).join(\" \")\n const kind = particle.cue\n try {\n if (kind === \"replaceJs\") value = eval(value)\n if (this.isNodeJs() && kind === \"replaceNodejs\")\n this.evalNodeJsMacros(value, macroMap, absolutePath)\n else macroMap[particle.getAtom(1)] = value\n } catch (err) {\n console.error(err)\n }\n particle.destroy() // Destroy definitions after eval\n })\n if (particle.has(\"toFooter\")) {\n const pushes = particle.getParticles(\"toFooter\")\n const append = pushes.map(push => push.section.join(\"\\n\")).join(\"\\n\")\n pushes.forEach(push => {\n push.section.forEach(particle => particle.destroy())\n push.destroy()\n })\n code = particle.asString + append\n }\n const keys = Object.keys(macroMap)\n if (!keys.length) return code\n let codeAfterMacroSubstitution = particle.asString\n // Todo: speed up. build a template?\n Object.keys(macroMap).forEach(key => (codeAfterMacroSubstitution = codeAfterMacroSubstitution.replace(new RegExp(key, \"g\"), macroMap[key])))\n return codeAfterMacroSubstitution\n }\n toRss() {\n const { title, canonicalUrl } = this\n return ` <item>\n <title>${title}</title>\n <link>${canonicalUrl}</link>\n <pubDate>${this.dayjs(this.timestamp * 1000).format(\"ddd, DD MMM YYYY HH:mm:ss ZZ\")}</pubDate>\n </item>`\n }\n example\n # Hello world\n ## This is Scroll\n * It compiles to HTML.\n \n code\n // You can add code as well.\n print(\"Hello world\")\nstampFileParser\n catchAllAtomType stringAtom\n description Create a file.\n javascript\n execute(parentDir) {\n const fs = require(\"fs\")\n const path = require(\"path\")\n const fullPath = path.join(parentDir, this.getLine())\n this.root.log(`Creating file ${fullPath}`)\n fs.mkdirSync(path.dirname(fullPath), {recursive: true})\n const content = this.subparticlesToString()\n fs.writeFileSync(fullPath, content, \"utf8\")\n const isExecutable = content.startsWith(\"#!\")\n if (isExecutable) fs.chmodSync(fullPath, \"755\")\n }\nstampFolderParser\n catchAllAtomType stringAtom\n description Create a folder.\n inScope stampFolderParser\n catchAllParser stampFileParser\n pattern \\/$\n javascript\n execute(parentDir) {\n const fs = require(\"fs\")\n const path = require(\"path\")\n const newPath = path.join(parentDir, this.getLine())\n this.root.log(`Creating folder ${newPath}`)\n fs.mkdirSync(newPath, {recursive: true})\n this.forEach(particle => particle.execute(newPath))\n }\nstumpContentParser\n popularity 0.102322\n catchAllAtomType codeAtom\nscrollTableDataParser\n popularity 0.001061\n cue data\n atoms cueAtom\n description Table from inline delimited data.\n baseParser blobParser\nscrollTableDelimiterParser\n popularity 0.001037\n description Set the delimiter.\n cue delimiter\n atoms cueAtom stringAtom\n javascript\n buildHtml() {\n return \"\"\n }\nplainTextLineParser\n popularity 0.000121\n catchAllAtomType stringAtom\n catchAllParser plainTextLineParser"} \ No newline at end of file
commit 8539788935987d20039fd312d616c8679aede7d4
Author: Breck Yunits <breck7@gmail.com> Date: 2025-01-16 14:05:03 -0800 Subject: diff --git a/public/ai.scroll b/public/ai.scroll index 700da34..0cee6ae 100644 --- a/public/ai.scroll +++ b/public/ai.scroll @@ -3,4 +3,5 @@ replace AGENT Claude replace TEMPLATE website replace TLD scroll.pub createFromPrompt.scroll +promptSettings.scroll indexBottom.scroll \ No newline at end of file diff --git a/public/createFromPrompt.scroll b/public/createFromPrompt.scroll index 2b21017..3667e6c 100644 --- a/public/createFromPrompt.scroll +++ b/public/createFromPrompt.scroll @@ -68,6 +68,3 @@ script document.getElementById('loadingModal').style.display = 'flex'; return true; }; - - -promptSettings.scroll \ No newline at end of file diff --git a/public/nodes.js b/public/nodes.js index 4663ca3..9f5238a 100644 --- a/public/nodes.js +++ b/public/nodes.js @@ -4,7 +4,8 @@ class Node { this.y = y this.vx = ((Math.random() > 0.5 ? 1 : -1) * Math.log10(folderData.revisions)) / 10 this.vy = ((Math.random() > 0.5 ? 1 : -1) * Math.log10(folderData.revisions)) / 10 - this.radius = Math.min(folderData.revisions, 1) + //this.radius = Math.min(folderData.revisions, 1) + this.radius = Math.max(Math.log2(folderData.revisions), 3) this.folder = folderData.folder this.folderLink = folderData.folderLink this.created = new Date(folderData.created) diff --git a/public/nodes.scroll b/public/nodes.scroll index 9153a62..f324fc7 100644 --- a/public/nodes.scroll +++ b/public/nodes.scroll @@ -1,4 +1,3 @@ -// <canvas id="nodesCanvas"></canvas> css :root { --primary-color: #1a2b4d; @@ -27,4 +26,5 @@ css height: 100%; z-index: -1; } +// <canvas id="nodesCanvas"></canvas> // nodes.js \ No newline at end of file
commit 1c52fe98162d21fa1400610fe1af65d19ef85126
Author: Breck Yunits <breck7@gmail.com> Date: 2025-01-16 13:33:25 -0800 Subject: Create from files method diff --git a/ScrollHub.js b/ScrollHub.js index eaa217e..12193ea 100644 --- a/ScrollHub.js +++ b/ScrollHub.js @@ -1018,6 +1018,51 @@ If you'd like to create this folder, visit our main site to get started. } }) + app.post("/createFolderFromFiles.htm", checkWritePermissions, async (req, res) => { + if (!req.files || !req.files["files[]"]) return res.status(400).send("No files were uploaded.") + + try { + // Generate a unique folder name + const folderName = await this.findAvailableFolderName() + const folderPath = path.join(this.rootFolder, folderName) + + // Create the folder + await fsp.mkdir(folderPath, { recursive: true }) + + // Handle multiple files + const uploadedFiles = Array.isArray(req.files["files[]"]) ? req.files["files[]"] : [req.files["files[]"]] + + // Process each file + for (const file of uploadedFiles) { + const filePath = path.join(folderPath, file.name) + + // Create necessary subdirectories + await fsp.mkdir(path.dirname(filePath), { recursive: true }) + + // Move the file to its destination + await file.mv(filePath) + } + + // Initialize git repository + await execAsync("git init", { cwd: folderPath }) + await execAsync("git add .", { cwd: folderPath }) + await execAsync('git commit -m "Initial commit from uploaded files"', { cwd: folderPath }) + + // Add to story and update caches + this.addStory(req, `created ${folderName} from uploaded files`) + await this.updateFolderAndBuildList(folderName) + + // Build the folder + await this.buildFolder(folderName) + + // Send the folder name back + res.send(folderName) + } catch (error) { + console.error(`Error creating folder from files:`, error) + res.status(500).send(`An error occurred while creating folder from files: ${error.toString().replace(/</g, "&lt;")}`) + } + }) + // In the initFileRoutes method, add this new route: app.post("/createFolderFromZip.htm", checkWritePermissions, async (req, res) => { if (!req.files || !req.files.zipFile) return res.status(400).send("No zip file was uploaded.") @@ -1266,6 +1311,17 @@ If you'd like to create this folder, visit our main site to get started. }) } + async findAvailableFolderName(prefix = "files") { + const { folderCache } = this + let counter = 1 + let folderName + do { + folderName = `${prefix}${counter}` + counter++ + } while (folderCache[folderName]) + return folderName + } + initCommandRoutes() { const { app } = this const checkWritePermissions = this.checkWritePermissions.bind(this) diff --git a/public/create.js b/public/create.js index 0fb1fc7..ca05631 100644 --- a/public/create.js +++ b/public/create.js @@ -39,53 +39,75 @@ class CreateFromZipper { if (files.length > 0) this.uploadFiles(files) } - showSpinner(message, style) { + showSpinner(message, style = "") { document.querySelector("#spinner").innerHTML = `<span${style}>${message}</span>` document.querySelector("#spinner").style.display = "block" } + hideSpinner() { document.querySelector("#spinner").style.display = "none" } - // New method to handle multiple file uploads - uploadFiles(files) { + async uploadFiles(files) { this.showSpinner("Uploading...") - const uploadPromises = Array.from(files).map(file => this.uploadFile(file)) - - Promise.all(uploadPromises) - .then(() => { - console.log("All files uploaded successfully") - this.hideSpinner() - }) - .catch(error => { - console.error("Error uploading files:", error) - // todo: show error to user - alert("Error uploading files:" + error) - }) + + try { + // Check if it's a single zip file + if (files.length === 1 && files[0].name.toLowerCase().endsWith(".zip")) { + await this.uploadZipFile(files[0]) + } else { + // Handle multiple files or single non-zip file + await this.uploadMultipleFiles(files) + } + + this.hideSpinner() + } catch (error) { + console.error("Error uploading files:", error) + alert("Error uploading files: " + error) + this.hideSpinner() + } } - // Modified uploadFile method to return a Promise - async uploadFile(file) { + async uploadZipFile(file) { const formData = new FormData() formData.append("zipFile", file) - try { - const response = await fetch("/createFolderFromZip.htm", { - method: "POST", - body: formData - }) - - if (!response.ok) { - const errorText = await response.text() - throw new Error(errorText || "Network response was not ok") - } + const response = await fetch("/createFolderFromZip.htm", { + method: "POST", + body: formData + }) - const data = await response.text() - window.location = `/edit.html?folderName=${data}&command=showWelcomeMessageCommand` - } catch (error) { - console.error("Error uploading file:", error.message) - throw error // Re-throw the error if you want calling code to handle it + if (!response.ok) { + const errorText = await response.text() + throw new Error(errorText || "Network response was not ok") } + + const data = await response.text() + window.location = `/edit.html?folderName=${data}&command=showWelcomeMessageCommand` + } + + async uploadMultipleFiles(files) { + const formData = new FormData() + + // Append all files to the form data + Array.from(files).forEach(file => { + // Use the full path if available (for folders), otherwise just the file name + const filePath = file.webkitRelativePath || file.name + formData.append("files[]", file, filePath) + }) + + const response = await fetch("/createFolderFromFiles.htm", { + method: "POST", + body: formData + }) + + if (!response.ok) { + const errorText = await response.text() + throw new Error(errorText || "Network response was not ok") + } + + const data = await response.text() + window.location = `/edit.html?folderName=${data}&command=showWelcomeMessageCommand` } }
commit b7edbb52d494d433e53adf137031c54d395a68f5
Author: Breck Yunits <breck7@gmail.com> Date: 2025-01-16 12:32:05 -0800 Subject: Serve mjs files correctly diff --git a/ScriptRunner.js b/ScriptRunner.js index 65c3adb..61a6fd8 100644 --- a/ScriptRunner.js +++ b/ScriptRunner.js @@ -4,7 +4,7 @@ const path = require("path") // Map of file extensions to their interpreters const interpreterMap = { - mjs: "node", + nodejs: "node", php: "php", py: "python3", sh: "bash", diff --git a/package.json b/package.json index 0204867..3852e15 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,7 @@ "openai": "^4.77.0", "prettier": "^3.3.3", "rss-parser": "^3.13.0", - "scroll-cli": "^168.0.0", + "scroll-cli": "^168.1.0", "scrollsdk": "^100.1.1" }, "bin": { diff --git a/public/ide/parsers.js b/public/ide/parsers.js index 2f439db..4d78553 100644 --- a/public/ide/parsers.js +++ b/public/ide/parsers.js @@ -1 +1 @@ -const AppConstants = {"parsers":"columnNameAtom\n paint constant\nnewColumnNameAtom\n description Name a derived column.\n paint variable\nconstantAtom\n paint constant\npercentAtom\n paint constant.numeric.float\n extends stringAtom\n // todo: this currently extends from stringAtom b/c scrollsdk needs to be fixed. seems like if extending from number then the hard coded number typescript regex takes precedence over a custom regex\ncountAtom\n extends integerAtom\nyearAtom\n extends integerAtom\npreBuildCommandAtom\n extends cueAtom\n description Give build command atoms their own color.\n paint constant.character.escape\ndelimiterAtom\n description String to use as a delimiter.\n paint string\nbulletPointAtom\n description Any token used as a bullet point such as \"-\" or \"1.\" or \">\"\n paint keyword\ncomparisonAtom\n enum < > <= >= = != includes doesNotInclude empty notEmpty startsWith endsWith\n paint constant\npersonNameAtom\n extends stringAtom\nurlAtom\n paint constant.language\nabsoluteUrlAtom\n paint constant.language\n regex (ftp|https?)://.+\nemailAddressAtom\n extends stringAtom\n paint constant.language\npermalinkAtom\n paint string\n description A string that doesn't contain characters that might interfere with most filesystems. No slashes, for instance.\nfilePathAtom\n paint constant.language\ntagOrUrlAtom\n description An HTML tag or a url.\n paint constant.language\nhtmlAttributesAtom\n paint constant\nhtmlTagAtom\n paint constant.language\n enum div span p a img ul ol li h1 h2 h3 h4 h5 h6 header nav section article aside main footer input button form label select option textarea table tr td th tbody thead tfoot br hr meta link script style title code\nhtmlTypeAtom\n extends stringAtom\n paint constant.language\n enum text password email number tel url search date time datetime-local week month color checkbox radio file submit reset button hidden range\n description HTML input type attribute values.\nclassNameAtom\n paint constant\nhtmlIdAtom\n paint constant\nfontFamilyAtom\n enum Arial Helvetica Verdana Georgia Impact Tahoma Slim\n paint constant\njavascriptAnyAtom\n extends codeAtom\nhtmlAnyAtom\n extends codeAtom\ncolorAtom\n extends codeAtom\nnamedColorAtom\n extends colorAtom\n enum aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkkhaki darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray darkturquoise darkviolet deeppink deepskyblue dimgray dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow honeydew hotpink indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgoldenrodyellow lightgray lightgreen lightpink lightsalmon lightseagreen lightskyblue lightslategray lightsteelblue lightyellow lime limegreen linen magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell sienna silver skyblue slateblue slategray snow springgreen steelblue tan teal thistle tomato turquoise violet wheat white whitesmoke yellow yellowgreen\nbuildCommandAtom\n extends cueAtom\n description Give build command atoms their own color.\n paint constant\ncssAnyAtom\n extends codeAtom\ncssLengthAtom\n extends codeAtom\nreductionTypeAtom\n enum sum mean max min concat first\n paint keyword\ninlineMarkupNameAtom\n description Options to turn on some inline markups.\n enum bold italics code katex none\ntileOptionAtom\n enum default light\nmeasureNameAtom\n extends cueAtom\n // A regex for column names for max compatibility with a broad range of data science tools:\n regex [a-zA-Z][a-zA-Z0-9]*\nabstractConstantAtom\n paint entity.name.tag\njavascriptSafeAlphaNumericIdentifierAtom\n regex [a-zA-Z0-9_]+\n reservedAtoms enum extends function static if while export return class for default require var let const new\nanyAtom\nbaseParsersAtom\n description There are a few classes of special parsers. BlobParsers don't have their subparticles parsed. Error particles always report an error.\n // todo Remove?\n enum blobParser errorParser\n paint variable.parameter\nenumAtom\n paint constant.language\nbooleanAtom\n enum true false\n extends enumAtom\natomParserAtom\n enum prefix postfix omnifix\n paint constant.numeric\natomPropertyNameAtom\n paint variable.parameter\natomTypeIdAtom\n examples integerAtom cueAtom someCustomAtom\n extends javascriptSafeAlphaNumericIdentifierAtom\n enumFromAtomTypes atomTypeIdAtom\n paint storage\nconstantIdentifierAtom\n examples someId myVar\n // todo Extend javascriptSafeAlphaNumericIdentifier\n regex [a-zA-Z]\\w+\n paint constant.other\n description A atom that can be assigned to the parser in the target language.\nconstructorFilePathAtom\nenumOptionAtom\n // todo Add an enumOption top level type, so we can add data to an enum option such as a description.\n paint string\natomExampleAtom\n description Holds an example for a atom with a wide range of options.\n paint string\nextraAtom\n paint invalid\nfileExtensionAtom\n examples js txt doc exe\n regex [a-zA-Z0-9]+\n paint string\nnumberAtom\n paint constant.numeric\nfloatAtom\n extends numberAtom\n regex \\-?[0-9]*\\.?[0-9]*\n paint constant.numeric.float\nintegerAtom\n regex \\-?[0-9]+\n extends numberAtom\n paint constant.numeric.integer\ncueAtom\n description A atom that indicates a certain parser to use.\n paint keyword\njavascriptCodeAtom\nlowercaseAtom\n regex [a-z]+\nparserIdAtom\n examples commentParser addParser\n description This doubles as the class name in Javascript. If this begins with `abstract`, then the parser will be considered an abstract parser, which cannot be used by itself but provides common functionality to parsers that extend it.\n paint variable.parameter\n extends javascriptSafeAlphaNumericIdentifierAtom\n enumFromAtomTypes parserIdAtom\ncueAtom\n paint constant.language\nregexAtom\n paint string.regexp\nreservedAtomAtom\n description A atom that a atom cannot contain.\n paint string\npaintTypeAtom\n enum comment comment.block comment.block.documentation comment.line constant constant.character.escape constant.language constant.numeric constant.numeric.complex constant.numeric.complex.imaginary constant.numeric.complex.real constant.numeric.float constant.numeric.float.binary constant.numeric.float.decimal constant.numeric.float.hexadecimal constant.numeric.float.octal constant.numeric.float.other constant.numeric.integer constant.numeric.integer.binary constant.numeric.integer.decimal constant.numeric.integer.hexadecimal constant.numeric.integer.octal constant.numeric.integer.other constant.other constant.other.placeholder entity entity.name entity.name.class entity.name.class.forward-decl entity.name.constant entity.name.enum entity.name.function entity.name.function.constructor entity.name.function.destructor entity.name.impl entity.name.interface entity.name.label entity.name.namespace entity.name.section entity.name.struct entity.name.tag entity.name.trait entity.name.type entity.name.union entity.other.attribute-name entity.other.inherited-class invalid invalid.deprecated invalid.illegal keyword keyword.control keyword.control.conditional keyword.control.import keyword.declaration keyword.operator keyword.operator.arithmetic keyword.operator.assignment keyword.operator.bitwise keyword.operator.logical keyword.operator.atom keyword.other markup markup.bold markup.deleted markup.heading markup.inserted markup.italic markup.list.numbered markup.list.unnumbered markup.other markup.quote markup.raw.block markup.raw.inline markup.underline markup.underline.link meta meta.annotation meta.annotation.identifier meta.annotation.parameters meta.block meta.braces meta.brackets meta.class meta.enum meta.function meta.function-call meta.function.parameters meta.function.return-type meta.generic meta.group meta.impl meta.interface meta.interpolation meta.namespace meta.paragraph meta.parens meta.path meta.preprocessor meta.string meta.struct meta.tag meta.toc-list meta.trait meta.type meta.union punctuation punctuation.accessor punctuation.definition.annotation punctuation.definition.comment punctuation.definition.generic.begin punctuation.definition.generic.end punctuation.definition.keyword punctuation.definition.string.begin punctuation.definition.string.end punctuation.definition.variable punctuation.section.block.begin punctuation.section.block.end punctuation.section.braces.begin punctuation.section.braces.end punctuation.section.brackets.begin punctuation.section.brackets.end punctuation.section.group.begin punctuation.section.group.end punctuation.section.interpolation.begin punctuation.section.interpolation.end punctuation.section.parens.begin punctuation.section.parens.end punctuation.separator punctuation.separator.continuation punctuation.terminator source source.language-suffix.embedded storage storage.modifier storage.type storage.type keyword.declaration.type storage.type.class keyword.declaration.class storage.type.enum keyword.declaration.enum storage.type.function keyword.declaration.function storage.type.impl keyword.declaration.impl storage.type.interface keyword.declaration.interface storage.type.struct keyword.declaration.struct storage.type.trait keyword.declaration.trait storage.type.union keyword.declaration.union string string.quoted.double string.quoted.other string.quoted.single string.quoted.triple string.regexp string.unquoted support support.class support.constant support.function support.module support.type text text.html text.xml variable variable.annotation variable.function variable.language variable.other variable.other.constant variable.other.member variable.other.readwrite variable.parameter\n paint string\nscriptUrlAtom\nsemanticVersionAtom\n examples 1.0.0 2.2.1\n regex [0-9]+\\.[0-9]+\\.[0-9]+\n paint constant.numeric\ndateAtom\n paint string\nstringAtom\n paint string\natomAtom\n paint constant\n description A non-empty single atom string.\n regex .+\nexampleAnyAtom\n examples lorem ipsem\n // todo Eventually we want to be able to parse correctly the examples.\n paint comment\n extends stringAtom\nblankAtom\ncommentAtom\n paint comment\ncodeAtom\n paint comment\ncolumnNameOrColorAtom\n extends columnNameAtom\nmetaCommandAtom\n extends cueAtom\n description Give meta command atoms their own color.\n paint constant.numeric\n // Obviously this is not numeric. But I like the green color for now.\n We need a better design to replace this \"paint\" concept\n https://github.com/breck7/scrollsdk/issues/186\nvegaDataSetAtom\n paint constant.numeric\n enum airports.csv anscombe.json barley.json birdstrikes.json budget.json budgets.json burtin.json cars.json climate.json co2-concentration.csv countries.json crimea.json descriptions.json disasters.csv driving.json earthquakes.json flare-dependencies.json flare.json flights-10k.json flights-200k.json flights-20k.json flights-2k.json flights-3m.csv flights-5k.json flights-airport.csv gapminder-health-income.csv gapminder.json github.csv graticule.json income.json iowa-electricity.csv iris.json jobs.json la-riots.csv londonBoroughs.json londonCentroids.json londonTubeLines.json lookup_groups.csv lookup_people.csv miserables.json monarchs.json movies.json normal-2d.json obesity.json points.json population.json population_engineers_hurricanes.csv seattle-temps.csv seattle-weather.csv sf-temps.csv sp500.csv stocks.csv udistrict.json unemployment-across-industries.json unemployment.tsv us-10m.json us-employment.csv us-state-capitals.json weather.csv weather.json weball26.json wheat.json windvectors.csv world-110m.json zipcodes.csv\ntagAtom\n extends permalinkAtom\ntagWithOptionalFolderAtom\n description A group name optionally combined with a folder path. Only used when referencing tags, not in posts.\n extends stringAtom\nscrollThemeAtom\n enum roboto gazette dark tufte prestige\n paint constant\nabstractScrollParser\n atoms cueAtom\n javascript\n buildHtmlSnippet(buildSettings) {\n return this.buildHtml(buildSettings)\n }\n buildTxt() {\n return \"\"\n }\n getHtmlRequirements(buildSettings) {\n const {requireOnce} = this\n if (!requireOnce)\n return \"\"\n const set = buildSettings?.alreadyRequired || this.root.alreadyRequired\n if (set.has(requireOnce))\n return \"\"\n set.add(requireOnce)\n return requireOnce + \"\\n\\n\"\n }\nabstractAftertextParser\n description Text followed by markup commands.\n extends abstractScrollParser\n inScope abstractAftertextDirectiveParser abstractAftertextAttributeParser aftertextTagParser abstractCommentParser\n javascript\n get markupInserts() {\n const { originalTextPostLinkify } = this\n return this.filter(particle => particle.isMarkup)\n .map(particle => particle.getInserts(originalTextPostLinkify))\n .filter(i => i)\n .flat()\n }\n get originalText() {\n return this.content ?? \"\"\n }\n get originalTextPostLinkify() {\n const { originalText } = this\n const shouldLinkify = this.get(\"linkify\") === \"false\" || originalText.includes(\"<a \") ? false : true\n return shouldLinkify ? this.replaceNotes(Utils.linkify(originalText)) : originalText\n }\n replaceNotes(originalText) {\n // Skip the replacements if there are no footnotes or the text has none.\n if (!this.root.footnotes.length || !originalText.includes(\"^\")) return originalText\n this.root.footnotes.forEach((note, index) => {\n const needle = note.cue\n const {linkBack} = note\n if (originalText.includes(needle)) originalText = originalText.replace(new RegExp(\"\\\\\" + needle + \"\\\\b\"), `<a href=\"#${note.htmlId}\" class=\"scrollNoteLink\" id=\"${linkBack}\"><sup>${note.label}</sup></a>`)\n })\n return originalText\n }\n get text() {\n const { originalTextPostLinkify, markupInserts } = this\n let adjustment = 0\n let newText = originalTextPostLinkify\n markupInserts.sort((a, b) => {\n if (a.index !== b.index)\n return a.index - b.index\n // If multiple tags start at same index, the tag that closes first should start last. Otherwise HTML breaks.\n if (b.index === b.endIndex) // unless the endIndex is the same as index\n return a.endIndex - b.endIndex\n return b.endIndex - a.endIndex\n })\n markupInserts.forEach(insertion => {\n insertion.index += adjustment\n const consumeStartCharacters = insertion.consumeStartCharacters ?? 0\n const consumeEndCharacters = insertion.consumeEndCharacters ?? 0\n newText = newText.slice(0, insertion.index - consumeEndCharacters) + insertion.string + newText.slice(insertion.index + consumeStartCharacters)\n adjustment += insertion.string.length - consumeEndCharacters - consumeStartCharacters\n })\n return newText\n }\n tag = \"p\"\n get className() {\n if (this.get(\"class\"))\n return this.get(\"class\")\n const classLine = this.getParticle(\"addClass\")\n if (classLine && classLine.applyToParentElement) return classLine.content\n return this.defaultClassName\n }\n defaultClassName = \"scrollParagraph\"\n get isHidden() {\n return this.has(\"hidden\")\n }\n buildHtml(buildSettings) {\n if (this.isHidden) return \"\"\n this.buildSettings = buildSettings\n const { className, styles } = this\n const classAttr = className ? `class=\"${this.className}\"` : \"\"\n const selfClose = this.isSelfClosing ? \" /\" : \"\"\n const tag = this.get(\"tag\") || this.tag\n if (tag === \"none\") // Allow no tag for aftertext in tables\n return this.text\n const id = this.has(\"id\") ? \"\" : `id=\"${this.htmlId}\" ` // always add an html id\n return this.getHtmlRequirements(buildSettings) + `<${tag} ${id}${this.htmlAttributes}${classAttr}${styles}${selfClose}>${this.htmlContents}${this.closingTag}`\n }\n get htmlContents() {\n return this.text\n }\n get closingTag() {\n if (this.isSelfClosing) return \"\"\n const tag = this.get(\"tag\") || this.tag\n return `</${tag}>`\n }\n get htmlAttributes() {\n const attrs = this.filter(particle => particle.isAttribute)\n return attrs.length ? attrs.map(particle => particle.htmlAttributes).join(\" \") + \" \" : \"\"\n }\n get styles() {\n const style = this.getParticle(\"style\")\n const fontFamily = this.getParticle(\"font\")\n const color = this.getParticle(\"color\")\n if (!style && !fontFamily && !color)\n return \"\"\n return ` style=\"${style?.content};${fontFamily?.css};${color?.css}\"`\n }\n get htmlId() {\n return this.get(\"id\") || \"particle\" + this.index\n }\nscrollParagraphParser\n // todo Perhaps rewrite this from scratch and move out of aftertext.\n extends abstractAftertextParser\n catchAllAtomType stringAtom\n description A paragraph.\n boolean suggestInAutocomplete false\n cueFromId\n javascript\n buildHtml(buildSettings) {\n if (this.isHidden) return \"\"\n // Hacky, I know.\n const newLine = this.has(\"inlineMarkupsOn\") ? undefined : this.appendLine(\"inlineMarkupsOn\")\n const compiled = super.buildHtml(buildSettings)\n if (newLine)\n newLine.destroy()\n return compiled\n }\n buildTxt() {\n const subparticles = this.filter(particle => particle.buildTxt).map(particle => particle.buildTxt()).filter(i => i).join(\"\\n\")\n const dateline = this.getParticle(\"dateline\")\n return (dateline ? dateline.day + \"\\n\\n\" : \"\") + (this.originalText || \"\") + (subparticles ? \"\\n \" + subparticles.replace(/\\n/g, \"\\n \") : \"\")\n }\nauthorsParser\n popularity 0.007379\n // multiple authors delimited by \" and \"\n boolean isPopular true\n extends scrollParagraphParser\n description Set author(s) name(s).\n example\n authors Breck Yunits\n https://breckyunits.com Breck Yunits\n // note: once we have mixins in Parsers, lets mixin the below from abstractTopLevelSingleMetaParser\n atoms metaCommandAtom\n javascript\n isTopMatter = true\n isSetterParser = true\n buildHtmlForPrint() {\n // hacky. todo: cleanup\n const originalContent = this.content\n this.setContent(`by ${originalContent}`)\n const html = super.buildHtml()\n this.setContent(originalContent)\n return html\n }\n buildTxtForPrint() {\n return 'by ' + super.buildTxt()\n }\n buildHtml() {\n return \"\"\n }\n buildTxt() {\n return \"\"\n }\n defaultClassName = \"printAuthorsParser\"\nblinkParser\n description Just for fun.\n extends scrollParagraphParser\n example\n blink Carpe diem!\n cue blink\n javascript\n buildHtml() {\n return `<span class=\"scrollBlink\">${super.buildHtml()}</span>\n <script>setInterval(()=>{ Array.from(document.getElementsByClassName(\"scrollBlink\")).forEach(el => el.style.visibility = el.style.visibility === \"hidden\" ? \"visible\" : \"hidden\") }, 500)</script>`\n }\nscrollButtonParser\n extends scrollParagraphParser\n cueFromId\n description A button.\n postParser\n description Post a particle.\n example\n scrollButton Click me\n javascript\n defaultClassName = \"scrollButton\"\n tag = \"button\"\n get htmlAttributes() {\n const link = this.getFromParser(\"scrollLinkParser\")\n const post = this.getParticle(\"post\")\n if (post) {\n const method = \"post\"\n const action = link?.link || \"\"\n const formData = new URLSearchParams({particle: post.subparticlesToString()}).toString()\n return ` onclick=\"fetch('${action}', {method: '${method}', body: '${formData}', headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).then(async (message) => {const el = document.createElement('div'); el.textContent = await message.text(); this.insertAdjacentElement('afterend', el);}); return false;\" `\n }\n return super.htmlAttributes + (link ? `onclick=\"window.location='${link.link}'\"` : \"\")\n }\n getFromParser(parserId) {\n return this.find(particle => particle.doesExtend(parserId))\n }\ncatchAllParagraphParser\n popularity 0.115562\n description A paragraph.\n extends scrollParagraphParser\n boolean suggestInAutocomplete false\n boolean isPopular true\n boolean isArticleContent true\n atoms stringAtom\n javascript\n getErrors() {\n const errors = super.getErrors() || []\n return this.parent.has(\"testStrict\") ? errors.concat(this.makeError(`catchAllParagraphParser should not have any matches when testing with testStrict.`)) : errors\n }\n get originalText() {\n return this.getLine() || \"\"\n }\nscrollCenterParser\n popularity 0.006415\n cue center\n description A centered section.\n extends scrollParagraphParser\n example\n center\n This paragraph is centered.\n javascript\n buildHtml() {\n this.parent.sectionStack.push(\"</center>\")\n return `<center>${super.buildHtml()}`\n }\n buildTxt() {\n return this.content\n }\nabstractIndentableParagraphParser\n extends scrollParagraphParser\n inScope abstractAftertextDirectiveParser abstractAftertextAttributeParser abstractIndentableParagraphParser scrollParagraphParser\n javascript\n get htmlContents() {\n return this.text + this.map(particle => particle.buildHtml())\n .join(\"\\n\")\n .trim()\n }\n buildTxt() {\n return this.getAtom(0) + \" \" + super.buildTxt()\n }\nchecklistTodoParser\n popularity 0.000193\n extends abstractIndentableParagraphParser\n example\n [] Get milk\n description A task todo.\n cue []\n string checked \n javascript\n get text() {\n return `<div style=\"text-indent:${(this.getIndentLevel() - 1) * 20}px;\"><input type=\"checkbox\" ${this.checked} id=\"${this.id}\"><label for=\"${this.id}\">` + super.text + `</label></div>`\n }\n get id() {\n return this.get(\"id\") || \"item\" + this._getUid()\n }\nchecklistDoneParser\n popularity 0.000072\n extends checklistTodoParser\n description A completed task.\n string checked checked\n cue [x]\n example\n [x] get milk\nscrollDivParser\n popularity 0.007524\n description HTML div tag.\n extends abstractIndentableParagraphParser\n cue div\n example\n div\n # Hello world\n p This is a test\n div\n # Deeper\n javascript\n tag = \"div\"\nabstractHtmlElementParser\n extends abstractIndentableParagraphParser\n javascript\n defaultClassName = \"\"\nhtmlSectionParser\n description HTML section tag.\n extends abstractHtmlElementParser\n cue section\n example\n section\n # Hello world\n p This is a test\n section\n # Deeper\n javascript\n tag = \"section\"\nhtmlHeaderParser\n description HTML header tag.\n extends abstractHtmlElementParser\n cue header\n example\n header\n # Title\n javascript\n tag = \"header\"\nhtmlFooterParser\n description HTML footer tag.\n extends abstractHtmlElementParser\n cue footer\n example\n footer\n p Made with love\n javascript\n tag = \"footer\"\nhtmlAsideParser\n description HTML aside tag.\n extends abstractHtmlElementParser\n cue aside\n example\n aside\n h1 Some notes\n javascript\n tag = \"aside\"\nhtmlArticleParser\n description HTML article tag.\n extends abstractHtmlElementParser\n cue article\n example\n article\n h1 My article\n javascript\n tag = \"article\"\nhtmlMainParser\n description HTML main tag.\n extends abstractHtmlElementParser\n cue main\n example\n main\n # Title\n javascript\n tag = \"main\"\nhtmlNavParser\n description HTML nav tag.\n extends abstractHtmlElementParser\n cue nav\n example\n nav\n a Home\n href /\n javascript\n tag = \"nav\"\nhtmlPreParser\n description HTML pre tag.\n extends abstractHtmlElementParser\n cue pre\n example\n pre\n javascript\n tag = \"pre\"\nhtmlUlParser\n description HTML ul tag.\n extends abstractHtmlElementParser\n cue ul\n example\n ul\n li A list\n javascript\n tag = \"ul\"\nhtmlOlParser\n description HTML ol tag.\n extends abstractHtmlElementParser\n cue ol\n example\n ol\n li A list\n javascript\n tag = \"ol\"\nhtmlLiParser\n description HTML li tag.\n extends abstractHtmlElementParser\n cue li\n example\n ol\n li A list\n javascript\n tag = \"li\"\nhtmlImgParser\n description HTML img tag.\n extends abstractHtmlElementParser\n cue img\n example\n img foo.png\n javascript\n tag = \"img\"\n isSelfClosing = true\nhtmlAParser\n description HTML a tag.\n extends abstractHtmlElementParser\n cue a\n example\n a Home\n href /\n javascript\n tag = \"a\"\nhtmlFormParser\n description HTML form tag.\n extends abstractHtmlElementParser\n cue form\n example\n form\n input\n javascript\n tag = \"form\"\nhtmlInputParser\n description HTML input tag.\n extends abstractHtmlElementParser\n cue input\n example\n input\n type text\n placeholder Enter your name\n javascript\n tag = \"input\"\n isSelfClosing = true\nhtmlSelectParser\n description HTML select tag.\n extends abstractHtmlElementParser\n cue select\n example\n select\n option Value 1\n option Value 2\n javascript\n tag = \"select\"\nhtmlOptionParser\n description HTML option tag.\n extends abstractHtmlElementParser\n cue option\n example\n select\n option Choose an option\n option First Option\n javascript\n tag = \"option\"\nhtmlTextareaParser\n description HTML textarea tag.\n extends abstractHtmlElementParser\n cue textarea\n example\n textarea\n placeholder Enter your message\n rows 4\n javascript\n tag = \"textarea\"\nhtmlButtonParser\n description HTML button tag.\n extends abstractHtmlElementParser\n cue button\n example\n button Submit\n type submit\n javascript\n tag = \"button\"\nhtmlLabelParser\n description HTML label tag.\n extends abstractHtmlElementParser\n cue label\n example\n label Name\n for username\n javascript\n tag = \"label\"\nhtmlSpanParser\n description HTML span tag.\n extends abstractHtmlElementParser\n cue span\n example\n span Hello\n javascript\n tag = \"span\"\nhtmlCanvasParser\n description HTML canvas tag.\n extends abstractHtmlElementParser\n cue canvas\n example\n canvas\n javascript\n tag = \"canvas\"\nhtmlIframeParser\n description HTML iframe tag.\n extends abstractHtmlElementParser\n cue iframe\n example\n iframe\n javascript\n tag = \"iframe\"\nh1LiteralParser\n description HTML h1 tag.\n extends abstractHtmlElementParser\n cue h1\n example\n main\n h1 Title\n javascript\n tag = \"h1\"\nh2LiteralParser\n description HTML h2 tag.\n extends abstractHtmlElementParser\n cue h2\n example\n main\n h2 Title\n javascript\n tag = \"h2\"\nh3LiteralParser\n description HTML h3 tag.\n extends abstractHtmlElementParser\n cue h3\n example\n main\n h3 Title\n javascript\n tag = \"h3\"\nh4LiteralParser\n description HTML h4 tag.\n extends abstractHtmlElementParser\n cue h4\n example\n main\n h4 Title\n javascript\n tag = \"h4\"\nlistAftertextParser\n popularity 0.014325\n extends abstractIndentableParagraphParser\n example\n - I had a _new_ thought.\n description A list item.\n cue -\n javascript\n defaultClassName = \"\"\n buildHtml() {\n const {index, parent} = this\n const particleClass = this.constructor\n const isStartOfList = index === 0 || !(parent.particleAt(index - 1) instanceof particleClass)\n const isEndOfList = parent.length === index + 1 || !(parent.particleAt(index + 1) instanceof particleClass)\n const { listType } = this\n return (isStartOfList ? `<${listType} ${this.attributes}>` : \"\") + `${super.buildHtml()}` + (isEndOfList ? `</${listType}>` : \"\")\n }\n get attributes() {\n return \"\"\n }\n tag = \"li\"\n listType = \"ul\"\nabstractCustomListItemParser\n extends listAftertextParser\n javascript\n get requireOnce() {\n return `<style>\\n.${this.constructor.name} li::marker {content: \"${this.cue} \";}\\n</style>`\n }\n get attributes() {\n return `class=\"${this.constructor.name}\"`\n }\norderedListAftertextParser\n popularity 0.004485\n extends listAftertextParser\n description A list item.\n example\n 1. Hello world\n pattern ^\\d+\\. \n javascript\n listType = \"ol\"\n get attributes() { return ` start=\"${this.getAtom(0)}\"`}\npParagraphParser\n popularity 0.001881\n cue p\n extends abstractIndentableParagraphParser\n description A paragraph.\n boolean isArticleContent true\n example\n p I had a _new_ idea.\nquickQuoteParser\n popularity 0.000482\n cue >\n example\n > The only thing we have to fear is fear itself. - FDR\n boolean isPopular true\n extends abstractIndentableParagraphParser\n description A quote.\n javascript\n defaultClassName = \"scrollQuote\"\n tag = \"blockquote\"\nscrollCounterParser\n description Visualize the speed of something.\n extends scrollParagraphParser\n cue counter\n example\n counter 4.5 Babies Born\n atoms cueAtom numberAtom\n javascript\n buildHtml() {\n const line = this.getLine()\n const atoms = line.split(\" \")\n atoms.shift() // drop the counter atom\n const perSecond = parseFloat(atoms.shift()) // get number\n const increment = perSecond/10\n const id = this._getUid()\n this.setLine(`* <span id=\"counter${id}\" title=\"0\">0</span><script>setInterval(()=>{ const el = document.getElementById('counter${id}'); el.title = parseFloat(el.title) + ${increment}; el.textContent = Math.floor(parseFloat(el.title)).toLocaleString()}, 100)</script> ` + atoms.join(\" \"))\n const html = super.buildHtml()\n this.setLine(line)\n return html\n }\nexpanderParser\n popularity 0.000072\n cueFromId\n description An collapsible HTML details tag.\n extends scrollParagraphParser\n example\n expander Knock Knock\n Who's there?\n javascript\n buildHtml() {\n this.parent.sectionStack.push(\"</details>\")\n return `<details>${super.buildHtml()}`\n }\n buildTxt() {\n return this.content\n }\n tag = \"summary\"\n defaultClassName = \"\"\nfootnoteDefinitionParser\n popularity 0.001953\n description A footnote. Can also be used as section notes.\n extends scrollParagraphParser\n boolean isFootnote true\n pattern ^\\^.+$\n // We need to quickLinks back in scope because there is currently a bug in ScrollSDK/parsers where if a parser extending a parent class has a child parser defined, then any regex parsers in the parent class will not be tested unless explicitly included in scope again.\n inScope quickLinkParser\n labelParser\n description If you want to show a custom label for a footnote. Default label is the note definition index.\n cueFromId\n atoms cueAtom\n catchAllAtomType stringAtom\n javascript\n get htmlId() {\n return `note${this.noteDefinitionIndex}`\n }\n get label() {\n // In the future we could allow common practices like author name\n return this.get(\"label\") || `[${this.noteDefinitionIndex}]`\n }\n get linkBack() {\n return `noteUsage${this.noteDefinitionIndex}`\n }\n get text() {\n return `<a class=\"scrollFootNoteUsageLink\" href=\"#noteUsage${this.noteDefinitionIndex}\">${this.label}</a> ${super.text}`\n }\n get noteDefinitionIndex() {\n return this.parent.footnotes.indexOf(this) + 1\n }\n buildTxt() {\n return this.getAtom(0) + \": \" + super.buildTxt()\n }\nabstractHeaderParser\n extends scrollParagraphParser\n example\n # Hello world\n javascript\n buildHtml(buildSettings) {\n if (this.isHidden) return \"\"\n if (this.parent.sectionStack)\n this.parent.sectionStack.push(\"</div>\")\n return `<div class=\"scrollSection\">` + super.buildHtml(buildSettings)\n }\n buildTxt() {\n const line = super.buildTxt()\n return line + \"\\n\" + \"=\".repeat(line.length)\n }\n isHeader = true\nh1Parser\n popularity 0.017918\n description An html h1 tag.\n extends abstractHeaderParser\n example\n # Hello world\n boolean isArticleContent true\n cue #\n boolean isPopular true\n javascript\n tag = \"h1\"\nh2Parser\n popularity 0.005257\n description An html h2 tag.\n extends abstractHeaderParser\n example\n ## Hello world\n boolean isArticleContent true\n cue ##\n boolean isPopular true\n javascript\n tag = \"h2\"\nh3Parser\n popularity 0.001085\n description An html h3 tag.\n extends abstractHeaderParser\n example\n ### Hello world\n boolean isArticleContent true\n cue ###\n javascript\n tag = \"h3\"\nh4Parser\n popularity 0.000289\n description An html h4 tag.\n example\n #### Hello world\n extends abstractHeaderParser\n cue ####\n javascript\n tag = \"h4\"\nscrollQuestionParser\n popularity 0.004244\n description A question.\n extends h4Parser\n cue ?\n example\n ? Why is the sky blue?\n javascript\n defaultClassName = \"scrollQuestion\"\nh5Parser\n description An html h5 tag.\n extends abstractHeaderParser\n example\n ##### Hello world\n cue #####\n javascript\n tag = \"h5\"\nprintTitleParser\n popularity 0.007572\n description Print title.\n extends abstractHeaderParser\n boolean isPopular true\n example\n title Eureka\n printTitle\n cueFromId\n javascript\n buildHtml(buildSettings) {\n // Hacky, I know.\n const {content} = this\n if (content === undefined)\n this.setContent(this.root.title)\n const { permalink } = this.root\n if (!permalink) {\n this.setContent(content) // Restore it as it was.\n return super.buildHtml(buildSettings)\n }\n const newLine = this.appendLine(`link ${permalink}`)\n const compiled = super.buildHtml(buildSettings)\n newLine.destroy()\n this.setContent(content) // Restore it as it was.\n return compiled\n }\n get originalText() {\n return this.content ?? this.root.title ?? \"\"\n }\n defaultClassName = \"printTitleParser\"\n tag = \"h1\"\ncaptionAftertextParser\n popularity 0.003207\n description An image caption.\n cue caption\n example\n map.png\n caption A map.\n extends scrollParagraphParser\n boolean isPopular true\nabstractMediaParser\n extends scrollParagraphParser\n inScope scrollMediaLoopParser scrollAutoplayParser\n int atomIndex 1\n javascript\n buildTxt() {\n return \"\"\n }\n get filename() {\n return this.getAtom(this.atomIndex)\n }\n getAsHtmlAttribute(attr) {\n if (!this.has(attr)) return \"\"\n const value = this.get(attr)\n return value ? `${attr}=\"${value}\"` : attr\n }\n getAsHtmlAttributes(list) {\n return list.map(atom => this.getAsHtmlAttribute(atom)).filter(i => i).join(\" \")\n }\n buildHtml() {\n return `<${this.tag} src=\"${this.filename}\" controls ${this.getAsHtmlAttributes(\"width height loop autoplay\".split(\" \"))}></${this.tag}>`\n }\nscrollMusicParser\n popularity 0.000024\n extends abstractMediaParser\n cue music\n description Play sound files.\n example\n music sipOfCoffee.m4a\n javascript\n buildHtml() {\n return `<audio controls ${this.getAsHtmlAttributes(\"loop autoplay\".split(\" \"))}><source src=\"${this.filename}\" type=\"audio/mpeg\"></audio>`\n }\nquickSoundParser\n popularity 0.000024\n extends scrollMusicParser\n atoms urlAtom\n pattern ^[^\\s]+\\.(mp3|wav|ogg|aac|m4a|flac)\n int atomIndex 0\n example\n sipOfCoffee.m4a\nscrollVideoParser\n popularity 0.000024\n extends abstractMediaParser\n cue video\n example\n video spirit.mp4\n description Play video files.\n widthParser\n cueFromId\n atoms cueAtom integerAtom\n heightParser\n cueFromId\n atoms cueAtom integerAtom\n javascript\n tag = \"video\"\nquickVideoParser\n popularity 0.000024\n extends scrollVideoParser\n example\n spirit.mp4\n atoms urlAtom\n pattern ^[^\\s]+\\.(mp4|webm|avi|mov)\n int atomIndex 0\nquickParagraphParser\n popularity 0.001881\n cue *\n extends scrollParagraphParser\n description A paragraph.\n boolean isArticleContent true\n example\n * I had a _new_ idea.\nscrollStopwatchParser\n description A stopwatch.\n extends scrollParagraphParser\n cue stopwatch\n example\n stopwatch\n atoms cueAtom\n catchAllAtomType numberAtom\n javascript\n buildHtml() {\n const line = this.getLine()\n const id = this._getUid()\n this.setLine(`* <span class=\"scrollStopwatchParser\" id=\"stopwatch${id}\">0.0</span><script>{let startTime = parseFloat(new URLSearchParams(window.location.search).get('start') || 0); document.getElementById('stopwatch${id}').title = startTime; setInterval(()=>{ const el = document.getElementById('stopwatch${id}'); el.title = parseFloat(el.title) + .1; el.textContent = (parseFloat(el.title)).toFixed(1)}, 100)}</script> `)\n const html = super.buildHtml()\n this.setLine(line)\n return html\n }\nthinColumnsParser\n popularity 0.003690\n extends abstractAftertextParser\n cueFromId\n catchAllAtomType integerAtom\n description Thin columns.\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n columnWidth = 35\n columnGap = 20\n buildHtml() {\n const {columnWidth, columnGap, maxColumns} = this\n const maxTotalWidth = maxColumns * columnWidth + (maxColumns - 1) * columnGap\n const stackContents = this.parent.clearSectionStack() // Starting columns always first clears the section stack.\n if (this.singleColumn) this.parent.sectionStack.push(\"</div>\") // Single columns are self-closing after section break.\n return stackContents + `<div class=\"scrollColumns\" style=\"column-width:${columnWidth}ch;column-count:${maxColumns};max-width:${maxTotalWidth}ch;\">`\n }\n get maxColumns() {\n return this.singleColumn ? 1 : parseInt(this.getAtom(1) ?? 10)\n }\nwideColumnsParser\n popularity 0.000386\n extends thinColumnsParser\n description Wide columns.\n javascript\n columnWidth = 90\nwideColumnParser\n popularity 0.003376\n extends wideColumnsParser\n description A wide column section.\n boolean singleColumn true\nmediumColumnsParser\n popularity 0.003376\n extends thinColumnsParser\n description Medium width columns.\n javascript\n columnWidth = 65\nmediumColumnParser\n popularity 0.003376\n extends mediumColumnsParser\n description A medium column section.\n boolean singleColumn true\nthinColumnParser\n popularity 0.003376\n extends thinColumnsParser\n description A thin column section.\n boolean singleColumn true\nendColumnsParser\n popularity 0.007789\n extends abstractAftertextParser\n cueFromId\n description End columns.\n javascript\n buildHtml() {\n return \"</div>\"\n }\n buildHtmlSnippet() {\n return \"\"\n }\nscrollContainerParser\n popularity 0.000096\n cue container\n description A centered HTML div.\n example\n container 600px\n catchAllAtomType cssLengthAtom\n extends abstractAftertextParser\n boolean isHtml true\n javascript\n get maxWidth() {\n return this.atoms[1] || \"1200px\"\n }\n buildHtmlSnippet() {\n return \"\"\n }\n tag = \"div\"\n defaultClassName = \"scrollContainerParser\"\n buildHtml() {\n this.parent.bodyStack.push(\"</div>\")\n return `<style>.scrollContainerParser{width: 100%; box-sizing: border-box; max-width: ${this.maxWidth}; margin: 0 auto;}</style>` + super.buildHtml()\n }\n get text() { return \"\"}\n get closingTag() { return \"\"}\ndebugSourceStackParser\n // useful for debugging\n description Print compilation steps.\n extends abstractAftertextParser\n cueFromId\n example\n printOriginalSource\n javascript\n get sources() {\n const {file} = this.root\n const passNames = [\"codeAtStart\", \"fusedCode\", \"codeAfterMacroPass\"]\n let lastCode = \"\"\n return passNames.map(name => {\n let code = file[name]\n if (lastCode === code)\n code = \"[Unchanged]\"\n lastCode = file[name]\n return {\n name,\n code\n }})\n }\n buildHtml() {\n return `<code class=\"scrollCodeBlock\">${this.buildTxt().replace(/\\</g, \"&lt;\")}</code>`\n }\n buildTxt() {\n return this.sources.map((pass, index) => `Pass ${index + 1} - ${pass.name}\\n========\\n${pass.code}`).join(\"\\n\\n\\n\")\n }\nabstractDinkusParser\n extends abstractAftertextParser\n boolean isDinkus true\n javascript\n buildHtml() {\n return `<div class=\"${this.defaultClass}\"><span>${this.dinkus}</span></div>`\n }\n defaultClass = \"abstractDinkusParser\"\n buildTxt() {\n return this.dinkus\n }\n get dinkus() {\n return this.content || this.getLine()\n }\nhorizontalRuleParser\n popularity 0.000362\n cue ---\n description A horizontal rule.\n extends abstractDinkusParser\n example\n ---\n javascript\n buildHtml() {\n return `<hr>`\n }\nscrollDinkusParser\n popularity 0.010828\n cue ***\n description A dinkus. Breaks section.\n boolean isPopular true\n example\n ***\n extends abstractDinkusParser\n javascript\n dinkus = \"*\"\ncustomDinkusParser\n cue dinkus\n description A custom dinkus.\n extends abstractDinkusParser\nendOfPostDinkusParser\n popularity 0.005740\n extends abstractDinkusParser\n description End of post dinkus.\n boolean isPopular true\n cue ****\n example\n ****\n javascript\n dinkus = \"⁂\"\nabstractIconButtonParser\n extends abstractAftertextParser\n cueFromId\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n return `<style>.abstractIconButtonParser {position:absolute;top:0.25rem; }.abstractIconButtonParser svg {fill: rgba(204,204,204,.8);width:1.875rem;height:1.875rem; padding: 0 7px;} .abstractIconButtonParser:hover svg{fill: #333;}</style><a href=\"${this.link}\" class=\"doNotPrint abstractIconButtonParser\" style=\"${this.style}\">${this.svg}</a>`\n }\ndownloadButtonParser\n popularity 0.006294\n description Link to download/WWS page.\n extends abstractIconButtonParser\n catchAllAtomType urlAtom\n string style position:relative;\n string svg <svg fill=\"#000000\" xmlns=\"http://www.w3.org/2000/svg\" width=\"800px\" height=\"800px\" viewBox=\"0 0 52 52\" enable-background=\"new 0 0 52 52\" xml:space=\"preserve\"><path d=\"M38.6,20.4c-1-6.5-6.7-11.5-13.5-11.5c-7.6,0-13.7,6.1-13.7,13.7c0,0.3,0,0.7,0.1,1c-5,0.4-8.9,4.6-8.9,9.6 c0,5.4,4.3,9.7,9.7,9.7h11.5c-0.8-0.8-8.1-8.1-8.1-8.1c-0.4-0.4-0.4-0.9,0-1.3l1.3-1.3c0.4-0.4,0.9-0.4,1.3,0l3.5,3.5 c0.4,0.4,1.1,0.1,1.1-0.4V21.8c0-0.4,0.5-0.9,1-0.9h1.9c0.5,0,0.9,0.4,0.9,0.9v13.4c0,0.6,0.8,0.8,1.1,0.4l3.5-3.5 c0.4-0.4,0.9-0.4,1.3,0l1.3,1.3c0.4,0.4,0.4,0.9,0,1.3L26,42.9h12.3v0c6.1-0.1,11-5.1,11-11.3C49.4,25.5,44.6,20.6,38.6,20.4z\"/></svg><!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->\n javascript\n get link() {\n return this.content\n }\neditButtonParser\n popularity 0.013963\n description Print badge top right.\n extends abstractIconButtonParser\n catchAllAtomType urlAtom\n // SVG from https://github.com/32pixelsCo/zest-icons\n string svg <svg width=\"800px\" height=\"800px\" viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\"><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M21.1213 2.70705C19.9497 1.53548 18.0503 1.53547 16.8787 2.70705L15.1989 4.38685L7.29289 12.2928C7.16473 12.421 7.07382 12.5816 7.02986 12.7574L6.02986 16.7574C5.94466 17.0982 6.04451 17.4587 6.29289 17.707C6.54127 17.9554 6.90176 18.0553 7.24254 17.9701L11.2425 16.9701C11.4184 16.9261 11.5789 16.8352 11.7071 16.707L19.5556 8.85857L21.2929 7.12126C22.4645 5.94969 22.4645 4.05019 21.2929 2.87862L21.1213 2.70705ZM18.2929 4.12126C18.6834 3.73074 19.3166 3.73074 19.7071 4.12126L19.8787 4.29283C20.2692 4.68336 20.2692 5.31653 19.8787 5.70705L18.8622 6.72357L17.3068 5.10738L18.2929 4.12126ZM15.8923 6.52185L17.4477 8.13804L10.4888 15.097L8.37437 15.6256L8.90296 13.5112L15.8923 6.52185ZM4 7.99994C4 7.44766 4.44772 6.99994 5 6.99994H10C10.5523 6.99994 11 6.55223 11 5.99994C11 5.44766 10.5523 4.99994 10 4.99994H5C3.34315 4.99994 2 6.34309 2 7.99994V18.9999C2 20.6568 3.34315 21.9999 5 21.9999H16C17.6569 21.9999 19 20.6568 19 18.9999V13.9999C19 13.4477 18.5523 12.9999 18 12.9999C17.4477 12.9999 17 13.4477 17 13.9999V18.9999C17 19.5522 16.5523 19.9999 16 19.9999H5C4.44772 19.9999 4 19.5522 4 18.9999V7.99994Z\"/></svg>\n javascript\n get link() {\n return this.content || this.root.editUrl || \"\"\n }\n get style() {\n return this.parent.findParticles(\"editButton\")[0] === this ? \"right:2rem;\": \"position:relative;\"\n }\nemailButtonParser\n popularity 0.006294\n description Email button.\n extends abstractIconButtonParser\n catchAllAtomType emailAddressAtom\n // todo: should just be \"optionalAtomType\"\n string style position:relative;\n string svg <svg viewBox=\"3 5 24 20\" width=\"24\" height=\"20\" xmlns=\"http://www.w3.org/2000/svg\"><g transform=\"matrix(1, 0, 0, 1, 0, -289.0625)\"><path style=\"opacity:1;stroke:none;stroke-width:0.49999997;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1\" d=\"M 5 5 C 4.2955948 5 3.6803238 5.3628126 3.3242188 5.9101562 L 14.292969 16.878906 C 14.696939 17.282876 15.303061 17.282876 15.707031 16.878906 L 26.675781 5.9101562 C 26.319676 5.3628126 25.704405 5 25 5 L 5 5 z M 3 8.4140625 L 3 23 C 3 24.108 3.892 25 5 25 L 25 25 C 26.108 25 27 24.108 27 23 L 27 8.4140625 L 17.121094 18.292969 C 15.958108 19.455959 14.041892 19.455959 12.878906 18.292969 L 3 8.4140625 z \" transform=\"translate(0,289.0625)\" id=\"rect4592\"/></g></svg>\n javascript\n get link() {\n const email = this.content || this.parent.get(\"email\")\n return email ? `mailto:${email}` : \"\"\n }\nhomeButtonParser\n popularity 0.006391\n description Home button.\n extends abstractIconButtonParser\n catchAllAtomType urlAtom\n string style left:2rem;\n string svg <svg role=\"img\" viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M12.7166 3.79541C12.2835 3.49716 11.7165 3.49716 11.2834 3.79541L4.14336 8.7121C3.81027 8.94146 3.60747 9.31108 3.59247 9.70797C3.54064 11.0799 3.4857 13.4824 3.63658 15.1877C3.7504 16.4742 4.05336 18.1747 4.29944 19.4256C4.41371 20.0066 4.91937 20.4284 5.52037 20.4284H8.84433C8.98594 20.4284 9.10074 20.3111 9.10074 20.1665V15.9754C9.10074 14.9627 9.90433 14.1417 10.8956 14.1417H13.4091C14.4004 14.1417 15.204 14.9627 15.204 15.9754V20.1665C15.204 20.3111 15.3188 20.4284 15.4604 20.4284H18.4796C19.0806 20.4284 19.5863 20.0066 19.7006 19.4256C19.9466 18.1747 20.2496 16.4742 20.3634 15.1877C20.5143 13.4824 20.4594 11.0799 20.4075 9.70797C20.3925 9.31108 20.1897 8.94146 19.8566 8.7121L12.7166 3.79541ZM10.4235 2.49217C11.3764 1.83602 12.6236 1.83602 13.5765 2.49217L20.7165 7.40886C21.4457 7.91098 21.9104 8.73651 21.9448 9.64736C21.9966 11.0178 22.0564 13.5119 21.8956 15.3292C21.7738 16.7067 21.4561 18.4786 21.2089 19.7353C20.9461 21.0711 19.7924 22.0001 18.4796 22.0001H15.4604C14.4691 22.0001 13.6655 21.1791 13.6655 20.1665V15.9754C13.6655 15.8307 13.5507 15.7134 13.4091 15.7134H10.8956C10.754 15.7134 10.6392 15.8307 10.6392 15.9754V20.1665C10.6392 21.1791 9.83561 22.0001 8.84433 22.0001H5.52037C4.20761 22.0001 3.05389 21.0711 2.79113 19.7353C2.54392 18.4786 2.22624 16.7067 2.10437 15.3292C1.94358 13.5119 2.00338 11.0178 2.05515 9.64736C2.08957 8.73652 2.55427 7.91098 3.28346 7.40886L10.4235 2.49217Z\"/></svg>\n javascript\n get link() {\n return this.content || this.get(\"link\") || \"index.html\"\n }\ntheScrollButtonParser\n popularity 0.006294\n description WWS button.\n extends abstractIconButtonParser\n string style position:relative;\n string svg <svg xmlns=\"http://www.w3.org/2000/svg\" direction=\"ltr\" width=\"231.52568231268793\" height=\"249.33156169975996\" viewBox=\"297.27169239534896 1273.121785992385 231.52568231268793 249.33156169975996\" stroke-linecap=\"round\" stroke-linejoin=\"round\" data-color-mode=\"dark\" class=\"tl-container tl-theme__force-sRGB tl-theme__dark\" ><defs/><g transform=\"matrix(1, 0, 0, 1, 395.9682, 1413.3618)\" opacity=\"1\"><g transform=\"scale(1)\"><path d=\"M-5.7342,-1.1484 T-5.0182,-4.6536 -2.6672,-12.9768 1.7374,-22.3903 8.4597,-30.0892 16.5455,-35.2796 25.3478,-37.8247 34.4641,-37.2199 43.0676,-33.4606 50.27,-27.1118 55.7861,-19.7972 59.8042,-11.6764 61.6844,-2.3157 60.8049,7.9615 57.3259,17.5954 51.2605,25.5515 41.9451,31.9237 30.6489,36.2084 18.9812,37.6038 8.4915,36.637 -1.3063,34.5174 -10.6869,31.6604 -19.0463,27.0252 -26.0612,20.1562 -31.864,11.1271 -35.2772,1.0066 -35.7963,-9.1933 -35.203,-19.2337 -32.52,-28.3259 -27.3388,-37.4245 -20.2857,-45.7085 -11.787,-53.0395 -2.4314,-58.4864 7.1724,-61.8739 17.5002,-65.6025 28.2859,-68.1034 38.514,-69.1081 48.1844,-69.9134 57.9136,-70.1787 67.4056,-69.5971 76.297,-67.7446 84.5233,-63.97 92.0158,-57.5003 98.1976,-48.5614 102.8839,-38.056 105.9936,-27.6097 107.074,-18.168 107.175,-8.2882 106.6452,1.9768 105.4734,11.7698 104.0279,21.1013 101.7439,31.0445 98.0977,40.6386 92.7822,49.1039 86.2847,57.2337 78.6099,64.7113 69.8339,70.974 61.2863,75.092 52.4283,78.2186 42.5338,80.7945 32.7733,82.6629 22.8568,83.6574 12.2803,83.3538 2.4971,81.4828 -6.3367,78.789 -15.1061,75.8011 -24.259,72.3779 -33.2286,68.991 -41.5707,64.8363 -49.153,59.1909 -55.8375,52.2938 -62.9311,43.9553 -68.4604,34.4882 -71.2761,23.5855 -72.748,12.7452 -73.7673,2.0453 -74.1187,-8.7386 -72.293,-19.3856 -68.7376,-30.4053 -64.12,-39.7852 -59.1825,-47.8931 -53.7695,-56.4512 -48.1998,-65.7676 -43.1389,-74.401 -36.9006,-81.0179 -28.4317,-86.2639 -18.3342,-90.3521 -8.9259,-93.9355 0.1927,-98.7179 9.3551,-103.3537 18.7651,-106.7552 29.7482,-110.3584 40.9287,-113.446 50.87,-115.2231 57.8279,-116.0074 60.4065,-116.0632 A7.8326,7.8326 0 0 1 61.1735,-100.4168 T58.6018,-100.2201 51.1634,-99.3008 41.695,-96.884 32.4044,-94.0187 22.65,-91.382 13.4974,-87.3756 5.0519,-83.1026 -5.0443,-78.6175 -15.7236,-74.4743 -24.6193,-70.2681 -31.274,-62.5903 -36.3827,-53.9362 -41.2833,-46.2905 -46.0679,-38.5161 -50.639,-30.6576 -54.6876,-22.4063 -57.6038,-12.3346 -58.5104,-1.8678 -57.6022,9.4969 -56.0628,20.477 -53.6434,29.0487 -48.8908,36.7517 -42.4075,43.9784 -35.3064,50.6236 -27.3553,55.2062 -17.6884,59.4064 -7.6442,63.6638 2.4427,67.0449 12.7308,69.4843 22.9294,70.2171 33.2547,69.3921 42.4972,67.7384 52.2753,64.8425 61.8649,60.9142 69.5292,56.0828 76.3604,49.5927 82.431,42.3194 87.219,34.619 90.6076,25.5217 92.547,16.0352 93.8703,7.1315 94.4972,-2.5268 94.3672,-13.3681 93.3204,-24.4252 90.5377,-34.1656 85.7321,-43.6441 78.7334,-51.8057 68.7542,-56.0559 57.9857,-57.2713 48.079,-57.0198 38.4535,-56.3204 28.5246,-55.0036 18.6104,-52.4796 9.6402,-49.559 0.7193,-46.2981 -7.1531,-41.3715 -13.708,-34.8957 -19.5435,-26.853 -22.8356,-17.0622 -23.363,-6.5446 -21.9969,3.1439 -17.1086,11.9113 -9.276,18.744 -0.0685,22.6058 9.3636,24.796 19.2422,25.8817 29.052,25.0411 37.9338,21.3502 45.6819,13.8498 49.6675,4.5228 49.2802,-5.1854 45.3277,-14.4455 38.8603,-21.7879 30.5488,-25.7753 21.3356,-24.3975 13.6687,-19.2391 8.8217,-10.9919 6.423,-2.3609 5.7342,1.1484 A5.8481,5.8481 0 0 1 -5.7342,-1.1484 Z\" stroke-linecap=\"round\"/></g></g></svg>\n javascript\n get link() {\n return \"https://wws.scroll.pub\"\n }\nabstractTextLinkParser\n extends abstractAftertextParser\n cueFromId\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildTxt() {\n return this.text\n }\n buildHtml() {\n return `<div class=\"abstractTextLinkParser\"><a href=\"${this.link}\">${this.text}</a></div>`\n }\neditLinkParser\n popularity 0.001206\n extends abstractTextLinkParser\n description Print \"Edit\" link.\n string text Edit\n javascript\n get link() {\n return this.root.editUrl || \"\"\n }\nscrollVersionLinkParser\n popularity 0.006294\n extends abstractTextLinkParser\n string link https://scroll.pub\n description Print Scroll version.\n javascript\n get text() {\n return `Built with Scroll v${this.root.scrollVersion}`\n }\nclassicFormParser\n cue classicForm\n popularity 0.006391\n description Generate input form for ScrollSet.\n extends abstractAftertextParser\n atoms cueAtom\n catchAllAtomType stringAtom\n string script\n <script>\n sendFormViaEmail = form => {\n const mailto = new URL(\"mailto:\")\n const params = []\n const { value, title } = form.querySelector('button[type=\"submit\"]')\n params.push(`subject=${encodeURIComponent(value)}`)\n params.push(`to=${encodeURIComponent(title)}`)\n const oneTextarea = form.querySelector('textarea[title=\"oneTextarea\"]')\n const body = oneTextarea ? codeMirrorInstance.getValue() : Array.from(new FormData(form)).map(([name, value]) => `${name} ${value}`).join(\"\\\\n\")\n params.push(`body=${encodeURIComponent(body)}`)\n mailto.search = params.join(\"&\")\n window.open(mailto.href, '_blank')\n }\n </script>\n string style\n <style> .scrollFormParser {\n font-family: \"Gill Sans\", \"Bitstream Vera Sans\", sans-serif;\n }\n .scrollFormParser input , .scrollFormParser textarea{\n padding: 10px;\n margin-bottom: 10px;\n width: 100%;\n box-sizing: border-box;\n } .scrollFormParser label {\n display: block;\n margin-bottom: 5px;\n }\n </style>\n javascript\n get inputs() {\n return this.root.measures.filter(measure => !measure.IsComputed).map((measure, index) => {\n const {Name, Question, IsRequired, Type} = measure\n const type = Type || \"text\"\n const placeholder = Question\n const ucFirst = Name.substr(0, 1).toUpperCase() + Name.substr(1)\n // ${index ? \"\" : \"autofocus\"}\n let tag = \"\"\n if (Type === \"textarea\")\n tag = `<textarea placeholder=\"${placeholder}\" id=\"${Name}\" name=\"${Name}\" ${IsRequired ? \"required\" : \"\"}></textarea>`\n else\n tag = `<input placeholder=\"${placeholder}\" type=\"${type}\" id=\"${Name}\" name=\"${Name}\" ${IsRequired ? \"required\" : \"\"}>`\n return `<div><label for=\"${Name}\" title=\"${IsRequired ? \"Required\" : \"\"}\">${ucFirst}${IsRequired ? \"*\" : \"\"}:</label>${tag}</div>`\n }).join(\"\\n\")\n }\n buildHtml() {\n const {isEmail, formDestination, callToAction, subject} = this\n return `${this.script}${this.style}<form ${isEmail ? \"onsubmit='sendFormViaEmail(this); return false;'\" : ` method='post' action='${formDestination}'`} class=\"scrollFormParser\">${this.inputs}<button value=\"${subject}\" title=\"${formDestination}\" class=\"scrollButton\" type=\"submit\">${callToAction}</button>${this.footer}</form>`\n }\n get callToAction() {\n return (this.isEmail ? \"Submit via email\" : (this.subject || \"Post\"))\n }\n get isEmail() {\n return this.formDestination.includes(\"@\")\n }\n get formDestination() {\n return this.getAtom(1) || \"\"\n }\n get subject() {\n return this.getAtomsFrom(2)?.join(\" \") || \"\"\n }\n get footer() {\n return \"\"\n }\nscrollFormParser\n extends classicFormParser\n cue scrollForm\n placeholderParser\n atoms cueAtom\n baseParser blobParser\n cueFromId\n single\n valueParser\n atoms cueAtom\n baseParser blobParser\n cueFromId\n single\n nameParser\n description Name for the post submission.\n atoms cueAtom stringAtom\n cueFromId\n single\n description Generate a Scroll Form.\n string copyFromExternal .codeMirror.css .scrollLibs.js .constants.js\n string requireOnce\n <link rel=\"stylesheet\" href=\".codeMirror.css\">\n <script src=\".scrollLibs.js\"></script>\n <script src=\".constants.js\"></script>\n javascript\n get placeholder() {\n return this.getParticle(\"placeholder\")?.subparticlesToString() || \"\"\n }\n get value() {\n return this.getParticle(\"value\")?.subparticlesToString() || \"\"\n }\n get footer() {\n return \"\"\n }\n get name() {\n return this.get(\"name\") || \"particles\"\n }\n get parsersBundle() {\n const parserRegex = /^[a-zA-Z0-9_]+Parser$/gm\n const clone = this.root.clone()\n const parsers = clone.filter(line => parserRegex.test(line.getLine()))\n return \"\\n\" + parsers.map(particle => {\n particle.prependLine(\"boolean suggestInAutocomplete true\")\n return particle.toString()\n }).join(\"\\n\")\n }\n get inputs() {\n const Name = this.name\n return `<textarea title=\"oneTextarea\" rows=\"${Math.min(this.root.measures.length * 2, 30)}\" placeholder=\"${this.placeholder}\" id=\"${Name}\" name=\"${Name}\"></textarea>\n <script id=\"${Name}Parsers\" type=\"text/plain\">${this.parsersBundle}</script>\n <script>{\n const parserRegex = /^[a-zA-Z0-9_]+Parser$/gm\n let {width, height} = document.getElementById('${Name}').getBoundingClientRect();\n const sp = new Particle(AppConstants.parsers)\n sp.filter(particle => particle.getLine().match(parserRegex)).forEach(part => {\n part.appendLine(\"boolean suggestInAutocomplete false\")\n })\n const customScrollParser = new HandParsersProgram(sp.toString() + document.getElementById(\"${Name}Parsers\").textContent).compileAndReturnRootParser()\n codeMirrorInstance = new ParsersCodeMirrorMode(\"custom\", () => customScrollParser, undefined, CodeMirror).register().fromTextAreaWithAutocomplete(document.getElementById(\"${Name}\"), {\n lineWrapping: false,\n lineNumbers: false\n })\n codeMirrorInstance.setSize(width, height);\n codeMirrorInstance.setValue(\\`${this.value}\\`); }</script>`\n }\n buildHtml(buildSettings) {\n return this.getHtmlRequirements(buildSettings) + super.buildHtml()\n }\nloremIpsumParser\n extends abstractAftertextParser\n cueFromId\n description Generate dummy text.\n catchAllAtomType integerAtom\n string placeholder Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n javascript\n get originalText() {\n return this.placeholder.repeat(this.howMany)\n }\n get howMany() {\n return this.getAtom(1) ? parseInt(this.getAtom(1)) : 1\n }\nnickelbackIpsumParser\n extends loremIpsumParser\n string placeholder And one day, I’ll be at the door. And lose your wings to fall in love? To the bottom of every bottle. I’m on the ledge of the eighteenth story. Why must the blind always lead the blind?\nscrollModalParser\n description A modal dialog overlay.\n extends abstractAftertextParser\n boolean isHtml true\n cue modal\n string requireOnce\n <style>\n .scrollModal {\n display: none;\n position: fixed;\n background: transparent;\n padding: 20px;\n left: 3rem;\n top: 3rem;\n right: 3rem;\n bottom: 3rem;\n z-index: 1000;\n font-family: \"IBM Plex Mono\", monospace;\n /* Frosted glass effect */\n background: rgba(0, 0, 0, 0.2);\n backdrop-filter: blur(8px);\n -webkit-backdrop-filter: blur(8px);\n border: 1px solid rgba(255, 255, 255, 0.1);\n box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);\n border-radius: 8px;\n overflow: hidden;\n }\n .scrollModal .closeButton {\n position: absolute;\n top: 10px;\n right: 10px;\n width: 30px;\n height: 30px;\n border: none;\n background: rgba(255, 255, 255, 0.1);\n color: rgba(255, 255, 255, 0.8);\n border-radius: 4px;\n cursor: pointer;\n font-family: \"IBM Plex Mono\", monospace;\n font-size: 18px;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all 0.2s ease;\n }\n .scrollModal .closeButton:hover {\n background: rgba(255, 255, 255, 0.2);\n color: white;\n }\n </style>\n <script>{\n window.closeModal = modal => {\n modal.style.display = 'none';\n history.pushState(\"\", document.title, window.location.pathname + window.location.search);\n };\n window.openModal = (id, event) => {\n if (event) event.modalJustOpened = true;\n document.querySelector(\"#\" + id).style.display = 'block';\n };\n window.addEventListener('hashchange', () => {\n const modalId = location.hash.slice(1); window.openModal(modalId);\n });\n document.addEventListener('keydown', e => {\n if (e.key === 'Escape') \n document.querySelectorAll('.scrollModal').forEach(closeModal);\n });\n // Check hash on initial load\n document.addEventListener(\"DOMContentLoaded\", e => {\n if (location.hash) \n window.openModal(location.hash.slice(1));\n });\n // Close on outside click\n document.addEventListener('click', e => {\n if (e.modalJustOpened) return;\n const modals = document.querySelectorAll('.scrollModal');\n modals.forEach(modal => {\n if (modal.style.display === 'block' && !modal.contains(e.target)) {\n closeModal(modal);\n }\n });\n });\n }</script>\n javascript\n buildHtml(buildSettings) {\n this.parent.sectionStack.push(\"</div>\")\n return this.getHtmlRequirements(buildSettings) + `<div class=\"scrollModal\" id=\"${this.htmlId}\"><button class=\"closeButton\" onclick=\"closeModal(this.parentElement)\">×</button>`\n }\nprintSnippetsParser\n popularity 0.000338\n // todo: why are we extending AT here and not loops? Is it for class/id etc?\n extends abstractAftertextParser\n cueFromId\n atoms cueAtom\n catchAllAtomType tagWithOptionalFolderAtom\n description Prints snippets matching tag(s).\n example\n printSnippets index\n javascript\n makeSnippet(scrollProgram, buildSettings) {\n const {endSnippetIndex} = scrollProgram\n if (endSnippetIndex === -1) return scrollProgram.buildHtmlSnippet(buildSettings) + scrollProgram.editHtml\n const linkRelativeToCompileTarget = buildSettings.relativePath + scrollProgram.permalink\n const joinChar = \"\\n\"\n const html = scrollProgram\n .map((subparticle, index) => (index >= endSnippetIndex ? \"\" : subparticle.buildHtmlSnippet ? subparticle.buildHtmlSnippet(buildSettings) : subparticle.buildHtml(buildSettings)))\n .filter(i => i)\n .join(joinChar)\n .trim() +\n `<a class=\"scrollContinueReadingLink\" href=\"${linkRelativeToCompileTarget}\">Continue reading...</a>`\n return html\n }\n get files() {\n const thisFile = this.parent.file\n const files = this.root.getFilesByTags(this.content, this.has(\"limit\") ? parseInt(this.get(\"limit\")) : undefined).filter(file => file.file !== thisFile)\n // allow sortBy lastCommit Time\n if (this.get(\"sortBy\") === \"commitTime\") {\n return this.root.sortBy(files, file => file.scrollProgram.lastCommitTime).reverse()\n }\n return files\n }\n buildHtml() {\n const alreadyRequired = this.root.alreadyRequired\n const snippets = this.files.map(file => {\n const buildSettings = {relativePath: file.relativePath, alreadyRequired }\n return `<div class=\"scrollSnippetContainer\">${this.makeSnippet(file.file.scrollProgram, buildSettings)}</div>`\n }).join(\"\\n\\n\")\n return `<div class=\"scrollColumns\" style=\"column-width:35ch;\">${snippets}</div>`\n }\n buildTxt() {\n return this.files.map(file => {\n const {scrollProgram} = file.file\n const {title, date, absoluteLink} = scrollProgram\n const ruler = \"=\".repeat(title.length)\n // Note: I tried to print the description here but the description generating code needs work.\n return `${title}\\n${ruler}\\n${date}\\n${absoluteLink}`\n }).join(\"\\n\\n\")\n }\nscrollNavParser\n popularity 0.000048\n extends printSnippetsParser\n cue fileNav\n description Titles and links in group(s).\n joinParser\n boolean allowTrailingWhitespace true\n cueFromId\n atoms cueAtom\n catchAllAtomType stringAtom\n javascript\n buildHtml() {\n return `<nav class=\"scrollNavParser\">` + this.root.getFilesByTags(this.content).map(file => {\n const { linkTitle, permalink } = file.file.scrollProgram\n return `<a href=\"${permalink}\">${linkTitle}</a>` \n }).join(this.get(\"join\") || \" \") + `</nav>`\n }\nprintFullSnippetsParser\n popularity 0.000048\n extends printSnippetsParser\n cueFromId\n description Print full pages in group(s).\n javascript\n makeSnippet(scrollProgram, buildSettings) {\n return scrollProgram.buildHtmlSnippet(buildSettings) + scrollProgram.editHtml\n }\nprintShortSnippetsParser\n popularity 0.000048\n extends printSnippetsParser\n cueFromId\n description Titles and descriptions in group(s).\n javascript\n makeSnippet(scrollProgram, buildSettings) {\n const { title, permalink, description, timestamp } = scrollProgram\n return `<div><a href=\"${permalink}\">${title}</a><div>${description}...</div><div class=\"subdued\" style=\"text-align:right;\">${this.root.dayjs(timestamp * 1000).format(`MMMM D, YYYY`)}</div></div>`\n }\nprintRelatedParser\n popularity 0.001182\n description Print links to related posts.\n extends printSnippetsParser\n cueFromId\n javascript\n buildHtml() {\n const alreadyRequired = this.root.alreadyRequired\n const list = this.files.map(fileWrapper => {\n const {relativePath, file} = fileWrapper\n const {title, permalink, year} = file.scrollProgram\n return `- ${title}${year ? \" (\" + year + \")\" : \"\"}\\n link ${relativePath + permalink}`\n }).join(\"\\n\")\n const items = this.parent.concat(list)\n const html = items.map(item => item.buildHtml()).join(\"\\n\")\n items.forEach(item => item.destroy())\n return html\n }\nscrollNoticesParser\n extends abstractAftertextParser\n description Display messages in URL query parameters.\n cue notices\n javascript\n buildHtml() {\n const id = this.htmlId\n return `<div id=\"${id}\" class=\"scrollNoticesParser\" style=\"display:none;\"></div><script>(function(){\n const params = new URLSearchParams(window.location.search)\n if (!params.size) return\n document.getElementById('${id}').innerHTML = Array.from(params.entries()).map(([key, value]) => {\n if (key === \"error\") \n return '<div style=\"color:red\">Error: ' + value + '</div>'\n if (key === \"success\")\n return '<div style=\"color:green\">Success: ' + value + '</div>'\n return '<div>' + key + ': ' + value + '</div>'\n }).join(\"\") || \"No query parameters found\"\n document.getElementById('${id}').style.display = \"block\"\n })()</script>`\n }\nabstractAssertionParser\n description Test above particle's output.\n extends abstractScrollParser\n string bindTo previous\n catchAllAtomType codeAtom\n cueFromId\n javascript\n buildHtml() {\n return ``\n }\n get particleToTest() {\n // If the previous particle is also an assertion particle, use the one before that.\n return this.previous.particleToTest ? this.previous.particleToTest : this.previous\n }\n get actual() {return this.particleToTest.buildHtml()}\n getErrors() {\n const {actual, expected} = this\n const errors = super.getErrors()\n if (this.areEqual(actual, expected))\n return errors\n return errors.concat(this.makeError(`'${actual}' did not ${this.kind} '${expected}'`))\n }\n get expected() {\n return this.length ? this.subparticlesToString() : (this.content ? this.content : \"\")\n }\n catchAllParser htmlLineParser\nassertHtmlEqualsParser\n extends abstractAssertionParser\n string kind equal\n example\n <b></b>\n assertHtmlEquals <b></b>\n javascript\n areEqual(actual, expected) {\n return actual === expected\n }\n // todo: why are we having to super here?\n getErrors() { return super.getErrors()}\nassertBuildIncludesParser\n extends abstractAssertionParser\n string kind include\n example\n buildCsv\n assertBuildIncludes virginica\n javascript\n areEqual(actual, expected) {\n return actual.includes(expected)\n }\n get actual() { return this.particleToTest.buildOutput()}\n getErrors() { return super.getErrors()}\nassertHtmlIncludesParser\n extends abstractAssertionParser\n string kind include\n javascript\n areEqual(actual, expected) {\n return actual.includes(expected)\n }\n getErrors() { return super.getErrors()}\nassertHtmlExcludesParser\n extends abstractAssertionParser\n string kind exclude\n javascript\n areEqual(actual, expected) {\n return !actual.includes(expected)\n }\n getErrors() { return super.getErrors()}\nassertIgnoreBelowErrorsParser\n description If you want to ignore any errors in the below particle in automated tests.\n extends abstractScrollParser\n string bindTo next\n cueFromId\nabstractPrintMetaParser\n extends abstractScrollParser\n cueFromId\nprintAuthorsParser\n popularity 0.001664\n description Prints author(s) byline.\n boolean isPopular true\n extends abstractPrintMetaParser\n // todo: we need pattern matching added to sdk to support having no params or a url and personNameAtom\n catchAllAtomType stringAtom\n example\n authors Breck Yunits\n https://breckyunits.com\n printAuthors\n javascript\n buildHtml() {\n return this.parent.getParticle(\"authors\")?.buildHtmlForPrint()\n }\n buildTxt() {\n return this.parent.getParticle(\"authors\")?.buildTxtForPrint()\n }\nprintDateParser\n popularity 0.000434\n extends abstractPrintMetaParser\n // If not present computes the date from the file's ctime.\n description Print published date.\n boolean isPopular true\n example\n date 1/11/2019\n printDate\n javascript\n buildHtml() {\n return `<div class=\"printDateParser\">${this.day}</div>`\n }\n get day() {\n let day = this.content || this.root.date\n if (!day) return \"\"\n return this.root.dayjs(day).format(`MMMM D, YYYY`)\n }\n buildTxt() {\n return this.day\n }\nprintFormatLinksParser\n description Prints links to other formats.\n extends abstractPrintMetaParser\n example\n printFormatLinks\n javascript\n buildHtml() {\n const permalink = this.root.permalink.replace(\".html\", \"\")\n // hacky\n const particle = this.appendSibling(`HTML | TXT`, `class printDateParser\\nlink ${permalink}.html HTML\\nlink ${permalink}.txt TXT\\nstyle text-align:center;`)\n const html = particle.buildHtml()\n particle.destroy()\n return html\n }\n buildTxt() {\n const permalink = this.root.permalink.replace(\".html\", \"\")\n return `HTML | TXT\\n link ${permalink}.html HTML\\n link ${permalink}.txt TXT`\n }\nabstractBuildCommandParser\n extends abstractScrollParser\n cueFromId\n atoms buildCommandAtom\n catchAllAtomType filePathAtom\n inScope slashCommentParser\n javascript\n isTopMatter = true\n buildHtml() {\n return \"\"\n }\n get extension() {\n return this.cue.replace(\"build\", \"\")\n }\n buildOutput() {\n return this.root.compileTo(this.extension)\n }\n get outputFileNames() {\n return this.content?.split(\" \") || [this.root.permalink.replace(\".html\", \".\" + this.extension.toLowerCase())]\n }\n async _buildFileType(extension, options) {\n const {root} = this\n const { fileSystem, folderPath, filename, filePath, path, lodash } = root\n const capitalized = lodash.capitalize(extension)\n const buildKeyword = \"build\" + capitalized\n const {outputFileNames} = this\n for (let name of outputFileNames) {\n try {\n await fileSystem.writeProduct(path.join(folderPath, name), root.compileTo(capitalized))\n root.log(`💾 Built ${name} from ${filename}`)\n } catch (err) {\n console.error(`Error while building '${filePath}' with extension '${extension}'`)\n throw err\n }\n }\n }\nabstractBuildOneCommandParser\n // buildOne and buildTwo are just a dumb/temporary way to have CSVs/JSONs/TSVs build first. Will be merged at some point.\n extends abstractBuildCommandParser\n javascript\n async buildOne(options) { await this._buildFileType(this.extension, options) }\nbuildParsersParser\n popularity 0.000096\n description Compile to Parsers file.\n extends abstractBuildOneCommandParser\nbuildCsvParser\n popularity 0.000096\n example\n buildCsv\n description Compile to CSV file.\n extends abstractBuildOneCommandParser\nbuildTsvParser\n popularity 0.000096\n description Compile to TSV file.\n extends abstractBuildOneCommandParser\nbuildJsonParser\n popularity 0.000096\n description Compile to JSON file.\n extends abstractBuildOneCommandParser\nabstractBuildTwoCommandParser\n extends abstractBuildCommandParser\n javascript\n async buildTwo(options) {\n await this._buildFileType(this.extension, options)\n }\nbuildCssParser\n popularity 0.000048\n description Compile to CSS file.\n extends abstractBuildTwoCommandParser\n example\n buildCss\nbuildHtmlParser\n popularity 0.007645\n description Compile to HTML file.\n extends abstractBuildTwoCommandParser\n boolean isPopular true\n javascript\n async buildTwo(options) {\n await this._copyExternalFiles(options)\n await super.buildTwo(options)\n }\n async _copyExternalFiles(options) {\n if (!this.isNodeJs()) return\n const {root} = this\n const externalFilesCopied = options.externalFilesCopied || {}\n // If this file uses a parser that has external requirements,\n // copy those from external folder into the destination folder.\n const { parsersRequiringExternals, folderPath, fileSystem, filename, parserIdIndex, path, Disk, externalsPath } = root\n if (!externalFilesCopied[folderPath]) externalFilesCopied[folderPath] = {}\n parsersRequiringExternals.forEach(parserId => {\n if (externalFilesCopied[folderPath][parserId]) return\n if (!parserIdIndex[parserId]) return\n parserIdIndex[parserId].map(particle => {\n const externalFiles = particle.copyFromExternal.split(\" \")\n externalFiles.forEach(name => {\n const newPath = path.join(folderPath, name)\n fileSystem.writeProduct(newPath, Disk.read(path.join(externalsPath, name)))\n root.log(`💾 Copied external file needed by ${filename} to ${name}`)\n })\n })\n if (parserId !== \"scrollThemeParser\")\n // todo: generalize when not to cache\n externalFilesCopied[folderPath][parserId] = true\n })\n }\nbuildJsParser\n description Compile to JS file.\n extends abstractBuildTwoCommandParser\nbuildRssParser\n popularity 0.000048\n description Compile to RSS file.\n extends abstractBuildTwoCommandParser\nbuildTxtParser\n popularity 0.007596\n description Compile to TXT file.\n extends abstractBuildTwoCommandParser\n boolean isPopular true\nloadConceptsParser\n // todo: clean this up. just add smarter imports with globs?\n // this currently removes any \"import\" statements.\n description Import all concepts in a folder.\n extends abstractBuildCommandParser\n cueFromId\n atoms preBuildCommandAtom filePathAtom\n javascript\n async load() {\n const { Disk, path, importRegex } = this.root\n const folder = path.join(this.root.folderPath, this.getAtom(1))\n const ONE_BIG_FILE = Disk.getFiles(folder).filter(file => file.endsWith(\".scroll\")).map(Disk.read).join(\"\\n\\n\").replace(importRegex, \"\")\n this.parent.concat(ONE_BIG_FILE)\n //console.log(ONE_BIG_FILE)\n }\n buildHtml() {\n return \"\"\n }\nbuildConceptsParser\n popularity 0.000024\n cueFromId\n description Compile concepts to delimited files.\n extends abstractBuildCommandParser\n sortByParser\n cueFromId\n atoms cueAtom columnNameAtom\n javascript\n async buildOne() {\n const {root} = this\n const { fileSystem, folderPath, filename, path, permalink } = root\n const files = this.getAtomsFrom(1)\n if (!files.length) files.push(permalink.replace(\".html\", \".csv\"))\n const sortBy = this.get(\"sortBy\")\n for (let link of files) {\n await fileSystem.writeProduct(path.join(folderPath, link), root.compileConcepts(link, sortBy))\n root.log(`💾 Built concepts in ${filename} to ${link}`)\n }\n }\nfetchParser\n description Download URL to disk.\n extends abstractBuildCommandParser\n cueFromId\n atoms preBuildCommandAtom urlAtom\n example\n fetch https://breckyunits.com/posts.csv\n fetch https://breckyunits.com/posts.csv renamed.csv\n javascript\n get url() {\n return this.getAtom(1)\n }\n get filename() {\n return this.getAtom(2)\n }\n async load() {\n await this.root.fetch(this.url, this.filename)\n }\n buildHtml() {\n return \"\"\n }\nbuildMeasuresParser\n popularity 0.000024\n cueFromId\n description Compile measures to delimited files.\n extends abstractBuildCommandParser\n sortByParser\n cueFromId\n atoms cueAtom columnNameAtom\n javascript\n async buildOne() {\n const {root} = this\n const { fileSystem, folderPath, filename, path, permalink } = root\n const files = this.getAtomsFrom(1)\n if (!files.length) files.push(permalink.replace(\".html\", \".csv\"))\n const sortBy = this.get(\"sortBy\")\n for (let link of files) {\n await fileSystem.writeProduct(path.join(folderPath, link), root.compileMeasures(link, sortBy))\n root.log(`💾 Built measures in ${filename} to ${link}`)\n }\n }\nbuildPdfParser\n popularity 0.000096\n description Compile to PDF file.\n extends abstractBuildCommandParser\n javascript\n async buildTwo(options) {\n if (!this.isNodeJs()) return \"Only works in Node currently.\"\n const {root} = this\n const { filename } = root\n const outputFile = root.filenameNoExtension + \".pdf\"\n // relevant source code for chrome: https://github.com/chromium/chromium/blob/a56ef4a02086c6c09770446733700312c86f7623/components/headless/command_handler/headless_command_switches.cc#L22\n const command = `/Applications/Google\\\\ Chrome.app/Contents/MacOS/Google\\\\ Chrome --headless --disable-gpu --no-pdf-header-footer --default-background-color=00000000 --no-pdf-background --print-to-pdf=\"${outputFile}\" \"${root.permalink}\"`\n // console.log(`Node.js is running on architecture: ${process.arch}`)\n try {\n const output = require(\"child_process\").execSync(command, { stdio: \"ignore\" })\n root.log(`💾 Built ${outputFile} from ${filename}`)\n } catch (error) {\n console.error(error)\n }\n }\nabstractInlineFileParser\n extends abstractScrollParser\n catchAllAtomType filePathAtom\n catchAllParser scrollFileAddressParser\n string joinChar ;\\n\\n\n string htmlTag script\n javascript\n get files() {\n const inline = this.atoms.slice(1)\n const children = this.map(particle => particle.cue)\n return inline.concat(children)\n }\n get contents() {\n return this.files.map(filename => this.root.readFile(filename)).join(this.joinChar)\n }\n buildHtml() {\n return `<${this.htmlTag}>/* ${this.files.join(\" \")} */\\n${this.contents}</${this.htmlTag}>`\n }\nscrollInlineCssParser\n description Inline CSS from files.\n popularity 0.007211\n extends abstractInlineFileParser\n cue inlineCss\n string joinChar \\n\\n\n string htmlTag style\n javascript\n buildCss() {\n return this.contents\n }\nscrollInlineJsParser\n description Inline JS from files.\n popularity 0.007211\n extends abstractInlineFileParser\n cue inlineJs\n javascript\n buildJs() {\n return this.contents\n }\nabstractTopLevelSingleMetaParser\n description Use these parsers once per file.\n extends abstractScrollParser\n inScope slashCommentParser\n cueFromId\n atoms metaCommandAtom\n javascript\n isTopMatter = true\n isSetterParser = true\n buildHtml() {\n return \"\"\n }\ntestStrictParser\n description Make catchAllParagraphParser = error.\n extends abstractTopLevelSingleMetaParser\nscrollDateParser\n cue date\n popularity 0.006680\n catchAllAtomType dateAtom\n description Set published date.\n extends abstractTopLevelSingleMetaParser\n boolean isPopular true\n example\n date 1/11/2019\n printDate\n Hello world\n dateline\nabstractUrlSettingParser\n extends abstractTopLevelSingleMetaParser\n atoms metaCommandAtom urlAtom\n cueFromId\neditBaseUrlParser\n popularity 0.007838\n description Override edit link baseUrl.\n extends abstractUrlSettingParser\ncanonicalUrlParser\n description Override canonical URL.\n extends abstractUrlSettingParser\nopenGraphImageParser\n popularity 0.000796\n // https://ogp.me/\n // If not defined, Scroll will try to generate it's own using the first image tag on your page.\n description Override Open Graph Image.\n extends abstractUrlSettingParser\nbaseUrlParser\n popularity 0.009188\n description Required for RSS and OpenGraph.\n extends abstractUrlSettingParser\n example\n baseUrl https://hub.scroll.pub/\nrssFeedUrlParser\n popularity 0.008850\n description Set RSS feed URL.\n extends abstractUrlSettingParser\neditUrlParser\n catchAllAtomType urlAtom\n description Override edit link.\n extends abstractTopLevelSingleMetaParser\nsiteOwnerEmailParser\n popularity 0.001302\n description Set email address for site contact.\n extends abstractTopLevelSingleMetaParser\n cue email\n atoms metaCommandAtom emailAddressAtom\nfaviconParser\n popularity 0.001688\n catchAllAtomType stringAtom\n cue favicon\n description Favicon file.\n example\n favicon logo.png\n metatags\n buildHtml\n extends abstractTopLevelSingleMetaParser\nimportOnlyParser\n popularity 0.033569\n // This line will be not be imported into the importing file.\n description Don't build this file.\n cueFromId\n atoms preBuildCommandAtom\n extends abstractTopLevelSingleMetaParser\n javascript\n buildHtml() {\n return \"\"\n }\ninlineMarkupsParser\n popularity 0.000024\n description Set global inline markups.\n extends abstractTopLevelSingleMetaParser\n cueFromId\n example\n inlineMarkups\n * \n // Disable * for bold\n _ u\n // Make _ underline\nhtmlLangParser\n atoms metaCommandAtom stringAtom\n // for the <html lang=\"\"> tag. If not specified will be \"en\". See https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang\n description Override HTML lang attribute.\n extends abstractTopLevelSingleMetaParser\nopenGraphDescriptionParser\n popularity 0.001688\n catchAllAtomType stringAtom\n cue description\n description Description for SEO meta tag.\n extends abstractTopLevelSingleMetaParser\nopenGraphKeywordsParser\n popularity 0.001688\n catchAllAtomType stringAtom\n cue keywords\n description Keywords for SEO meta tag.\n extends abstractTopLevelSingleMetaParser\npermalinkParser\n popularity 0.000265\n description Override output filename.\n extends abstractTopLevelSingleMetaParser\n atoms metaCommandAtom permalinkAtom\nscrollTagsParser\n popularity 0.006801\n cue tags\n description Set tags.\n example\n tags All\n extends abstractTopLevelSingleMetaParser\n catchAllAtomType tagAtom\nscrollTitleParser\n popularity 0.007524\n catchAllAtomType stringAtom\n cue title\n description Set title.\n example\n title Eureka\n printTitle\n extends abstractTopLevelSingleMetaParser\n boolean isPopular true\nscrollLinkTitleParser\n popularity 0.007524\n catchAllAtomType stringAtom\n cue linkTitle\n description Text for links.\n example\n title My blog - Eureka\n linkTitle Eureka\n extends abstractTopLevelSingleMetaParser\nscrollChatParser\n popularity 0.000362\n description A faux text chat conversation.\n catchAllParser chatLineParser\n cue chat\n extends abstractScrollParser\n example\n chat\n Hi\n 👋\n javascript\n buildHtml() {\n return this.map((line, index) => line.asString ? `<div style=\"text-align: ${index % 2 ? \"right\" : \"left\"};\" class=\"scrollChat ${index % 2 ? \"scrollChatRight\" : \"scrollChatLeft\"}\"><span>${line.asString}</span></div>` : \"\").join(\"\")\n }\n buildTxt() {\n return this.subparticlesToString()\n }\nabstractDatatableProviderParser\n description A datatable.\n extends abstractScrollParser\n inScope scrollTableDataParser scrollTableDelimiterParser abstractTableVisualizationParser abstractTableTransformParser h1Parser h2Parser scrollQuestionParser htmlInlineParser scrollBrParser slashCommentParser\n javascript\n get visualizations() {\n return this.topDownArray.filter(particle => particle.isTableVisualization || particle.isHeader || particle.isHtml)\n }\n buildHtml(buildSettings) {\n return this.visualizations.map(particle => particle.buildHtml(buildSettings))\n .join(\"\\n\")\n .trim()\n }\n buildTxt() {\n return this.visualizations.map(particle => particle.buildTxt())\n .join(\"\\n\")\n .trim()\n }\n _coreTable\n get coreTable() {\n if (this._coreTable) return this._coreTable\n const {delimiter, delimitedData} = this\n return []\n }\n get columnNames() {\n return []\n }\nscrollTableParser\n extends abstractDatatableProviderParser\n popularity 0.002133\n cue table\n example\n table\n printTable\n data\n year,count\n 1900,10\n 2000,122\n 2020,23\n catchAllAtomType filePathAtom\n int atomIndex 1\n javascript\n get delimiter() {\n const {filename} = this\n let delimiter = \"\"\n if (filename) {\n const extension = filename.split('?')[0].split(\".\").pop()\n if (extension === \"json\") delimiter = \"json\"\n if (extension === \"particles\") delimiter = \"particles\"\n if (extension === \"csv\") delimiter = \",\"\n if (extension === \"tsv\") delimiter = \"\\t\"\n if (extension === \"ssv\") delimiter = \" \"\n if (extension === \"psv\") delimiter = \"|\"\n }\n if (this.get(\"delimiter\"))\n delimiter = this.get(\"delimiter\")\n else if (!delimiter) {\n const header = this.delimitedData.split(\"\\n\")[0]\n if (header.includes(\"\\t\"))\n delimiter = \"\\t\"\n else if (header.includes(\",\"))\n delimiter = \",\"\n else\n delimiter = \" \"\n }\n return delimiter\n }\n get filename() {\n return this.getAtom(this.atomIndex)\n }\n get coreTable() {\n if (this._coreTable) return this._coreTable\n const {delimiter, delimitedData} = this\n if (delimiter === \"json\") {\n const obj = JSON.parse(delimitedData)\n let rows = []\n // Optimal case: Array of objects\n if (Array.isArray(obj)) { rows = obj}\n else if (!Array.isArray(obj) && typeof obj === \"object\") {\n // Case 2: Nested array under a key\n const arrayKey = Object.keys(obj).find(key => Array.isArray(obj[key]))\n if (arrayKey) rows = obj[arrayKey]\n }\n // Case 3: Array of primitive values\n else if (Array.isArray(obj) && obj.length && typeof obj[0] !== \"object\") {\n rows = obj.map(value => ({ value }))\n }\n this._columnNames = rows.length ? Object.keys(rows[0]) : []\n this._coreTable = rows\n return rows\n }\n else if (delimiter === \"particles\") {\n const d3lib = this.root.d3\n this._coreTable = d3lib.dsvFormat(\",\").parse(new Particle(delimitedData).asCsv, d3lib.autoType)\n } else {\n const d3lib = this.root.d3\n this._coreTable = d3lib.dsvFormat(delimiter).parse(delimitedData, d3lib.autoType)\n }\n this._columnNames = this._coreTable.columns\n delete this._coreTable.columns\n return this._coreTable\n }\n get columnNames() {\n // init coreTable to set columns\n const coreTable = this.coreTable\n return this._columnNames\n }\n async load() {\n if (this.filename)\n await this.root.fetch(this.filename)\n }\n get fileContent() {\n return this.root.readSyncFromFileOrUrl(this.filename)\n }\n get delimitedData() {\n // json csv tsv\n if (this.filename)\n return this.fileContent\n const dataParticle = this.getParticle(\"data\")\n if (dataParticle)\n return dataParticle.subparticlesToString()\n // if not dataparticle and no filename, check [permalink].csv\n if (this.isNodeJs())\n return this.root.readFile(this.root.permalink.replace(\".html\", \"\") + \".csv\")\n return \"\"\n }\nclocParser\n extends scrollTableParser\n description Output results of cloc as table.\n cue cloc\n string copyFromExternal .clocLangs.txt\n javascript\n delimiter = \",\"\n get delimitedData() {\n const { execSync } = require(\"child_process\")\n const results = execSync(this.command).toString().trim()\n const csv = results.split(\"\\n\\n\").pop().replace(/,\\\"github\\.com\\/AlDanial.+/, \"\") // cleanup output\n return csv\n }\n get command(){\n return `cloc --vcs git . --csv --read-lang-def=.clocLangs.txt ${this.content || \"\"}`\n }\nscrollDependenciesParser\n extends scrollTableParser\n description Get files this file depends on.\n cue dependencies\n javascript\n delimiter = \",\"\n get delimitedData() {\n return `file\\n` + this.root.dependencies.join(\"\\n\")\n }\nscrollDiskParser\n extends scrollTableParser\n description Output file into as table.\n cue disk\n javascript\n delimiter = \"json\"\n get delimitedData() {\n return this.isNodeJs() ? this.delimitedDataNodeJs : \"\"\n }\n get delimitedDataNodeJs() {\n const fs = require('fs');\n const path = require('path');\n const {folderPath} = this.root\n const folder = this.content ? path.join(folderPath, this.content) : folderPath\n function getDirectoryContents(dirPath) {\n const directoryContents = [];\n const items = fs.readdirSync(dirPath);\n items.forEach((item) => {\n const itemPath = path.join(dirPath, item);\n const stats = fs.statSync(itemPath);\n directoryContents.push({\n name: item,\n type: stats.isDirectory() ? 'directory' : 'file',\n size: stats.size,\n lastModified: stats.mtime\n });\n });\n return directoryContents;\n }\n return JSON.stringify(getDirectoryContents(folder))\n }\nscrollIrisParser\n extends scrollTableParser\n description Iris dataset from R.A. Fisher.\n cue iris\n example\n iris\n printTable\n scatter\n x SepalLength\n y SepalWidth\n javascript\n delimitedData = this.constructor.iris\nvegaSampleDataParser\n extends scrollTableParser\n description Sample dataset from Vega.\n cue sampleData\n atoms cueAtom vegaDataSetAtom\n example\n sampleData zipcodes.csv\n printTable\n javascript\n get filename() {\n return \"https://ohayo.scroll.pub/ohayo/packages/vega/datasets/\" + this.content\n }\nquickTableParser\n popularity 0.000024\n extends scrollTableParser\n atoms urlAtom\n pattern ^[^\\s]+\\.(tsv|csv|ssv|psv|json)[^\\s]*$\n int atomIndex 0\n javascript\n get dependencies() { return [this.cue]}\nscrollConceptsParser\n description Load concepts as table.\n extends abstractDatatableProviderParser\n cue concepts\n atoms cueAtom\n example\n concepts\n printTable\n javascript\n get coreTable() {\n return this.root.concepts\n }\n get columnNames() {\n return this.root.measures.map(col => col.Name)\n }\nabstractPostsParser\n description Load posts as table.\n extends abstractDatatableProviderParser\n cueFromId\n atoms cueAtom\n catchAllAtomType tagWithOptionalFolderAtom\n javascript\n async load() {\n const dependsOn = this.tags.map(tag => this.root.parseNestedTag(tag)).filter(i => i).map(i => i.folderPath)\n const {fileSystem} = this.root\n for (let folderPath of dependsOn) {\n // console.log(`${this.root.filePath} is loading: ${folderPath} in id '${fileSystem.fusionId}'`)\n await fileSystem.getLoadedFilesInFolder(folderPath, \".scroll\")\n }\n }\n get tags() {\n return this.content?.split(\" \") || []\n }\n get files() {\n const thisFile = this.root.file\n // todo: we can include this file, but just not run asTxt\n const files = this.root.getFilesByTags(this.tags).filter(file => file.file !== thisFile)\n return files\n }\n get coreTable() {\n if (this._coreTable) return this._coreTable\n this._coreTable = this.files.map(file => this.postToRow(file))\n return this._coreTable\n }\n postToRow(file) {\n const {relativePath} = file\n const {scrollProgram} = file.file\n const {title, permalink, asTxt, date, wordCount, minutes} = scrollProgram\n const text = asTxt.replace(/(\\t|\\n)/g, \" \").replace(/</g, \"&lt;\")\n return {\n title, titleLink: relativePath + permalink, text, date, wordCount, minutes\n }\n }\n columnNames = \"title titleLink text date wordCount minutes\".split(\" \")\nscrollPostsParser\n popularity 0.000024\n cue posts\n description Posts as table.\n extends abstractPostsParser\n example\n // Print a search table:\n posts\n printTable\n tableSearch\n // Dump a CSV of blog:\n buildHtml\n buildCsv\n buildJson\nscrollPostsMetaParser\n popularity 0.000024\n cue postsMeta\n description Post meta as table.\n extends abstractPostsParser\n javascript\n columnNames = [\"date\", \"year\", \"title\", \"permalink\", \"authors\", \"tags\", \"wordCount\", \"minutes\"]\n postToRow(file) {\n const {date, year, title, permalink, authors, tags, wordCount, minutes} = file.file.scrollProgram\n return {\n date, year, title, permalink, authors, tags, wordCount, minutes\n }\n }\nprintFeedParser\n popularity 0.000048\n description Print group to RSS.\n extends abstractPostsParser\n example\n printFeed index\n printFeed cars/index\n buildRss\n javascript\n buildRss() {\n const {dayjs} = this.root\n const scrollPrograms = this.files.map(file => file.file.scrollProgram)\n const { title, baseUrl, description } = this.root\n return `<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n <rss version=\"2.0\">\n <channel>\n <title>${title}</title>\n <link>${baseUrl}</link>\n <description>${description}</description>\n <lastBuildDate>${dayjs().format(\"ddd, DD MMM YYYY HH:mm:ss ZZ\")}</lastBuildDate>\n <language>en-us</language>\n ${scrollPrograms.map(program => program.toRss()).join(\"\\n\")}\n </channel>\n </rss>`\n }\n buildTxt() {\n return this.buildRss()\n }\nprintSourceParser\n popularity 0.000024\n description Print source for files in group(s).\n extends printFeedParser\n example\n printSource index\n buildTxt source.txt\n javascript\n buildHtml() {\n const files = this.root.getFilesByTags(this.content).map(file => file.file)\n return `${files.map(file => file.filePath + \"\\n \" + file.codeAtStart.replace(/\\n/g, \"\\n \") ).join(\"\\n\")}`\n }\nprintSiteMapParser\n popularity 0.000072\n extends abstractPostsParser\n description Print text sitemap.\n example\n baseUrl http://test.com\n printSiteMap\n javascript\n buildHtml() {\n const { baseUrl } = this.root\n return this.files.map(file => baseUrl + file.relativePath + file.file.scrollProgram.permalink).join(\"\\n\")\n }\n buildTxt() {\n return this.buildHtml()\n }\n get dependencies() { return this.files}\ncodeParser\n popularity 0.001929\n description A code block.\n catchAllParser lineOfCodeParser\n extends abstractScrollParser\n boolean isPopular true\n example\n code\n two = 1 + 1\n javascript\n buildHtml() {\n return `<code class=\"scrollCodeBlock\">${this.code.replace(/\\</g, \"&lt;\")}</code>`\n }\n buildTxt() {\n return \"```\\n\" + this.code + \"\\n```\"\n }\n get code() {\n return this.subparticlesToString()\n }\n cueFromId\ncodeWithHeaderParser\n popularity 0.000169\n cueFromId\n catchAllAtomType stringAtom\n extends codeParser\n example\n codeWithHeader math.py\n two = 1 + 1\n javascript\n buildHtml() {\n return `<div class=\"codeWithHeader\"><div class=\"codeHeader\">${this.content}</div>${super.buildHtml()}</div>`\n }\n buildTxt() {\n return \"```\" + this.content + \"\\n\" + this.code + \"\\n```\"\n }\ncodeFromFileParser\n popularity 0.000169\n cueFromId\n atoms cueAtom urlAtom\n extends codeWithHeaderParser\n example\n codeFromFile math.py\n javascript\n get code() {\n return this.root.readSyncFromFileOrUrl(this.content)\n }\ncodeWithLanguageParser\n popularity 0.000458\n description Use this to specify the language of the code block, such as csvCode or rustCode.\n extends codeParser\n pattern ^[a-zA-Z0-9_]+Code$\ndebugParsersParser\n description Print the parsers used.\n extends codeParser\n cueFromId\n javascript\n buildParsers() { return this.code}\n get code() {\n let code = new Particle(this.root.definition.toString())\n // Remove comments\n code.filter((line) => line.getLine().startsWith(\"//\")).forEach((particle) => particle.destroy())\n // Remove blank lines\n code = code.toString().replace(/^\\n/gm, \"\")\n return code\n }\nabstractScrollWithRequirementsParser\n extends abstractScrollParser\n cueFromId\n javascript\n buildHtml(buildSettings) {\n return this.getHtmlRequirements(buildSettings) + this.buildInstance()\n }\ncopyButtonsParser\n popularity 0.001471\n extends abstractScrollWithRequirementsParser\n description Copy code widget.\n javascript\n buildInstance() {\n return \"\"\n }\n string requireOnce\n <script>\n document.addEventListener(\"DOMContentLoaded\", () => document.querySelectorAll(\".scrollCodeBlock\").forEach(block =>\n {\n if (!navigator.clipboard) return\n const button = document.createElement(\"span\")\n button.classList.add(\"scrollCopyButton\")\n block.appendChild(button)\n button.addEventListener(\"click\", async () => {\n await navigator.clipboard.writeText(block.innerText)\n button.classList.add(\"scrollCopiedButton\")\n })\n }\n ))\n </script>\nabstractTableVisualizationParser\n extends abstractScrollWithRequirementsParser\n boolean isTableVisualization true\n javascript\n get columnNames() {\n return this.parent.columnNames\n }\nheatrixParser\n cueFromId\n example\n heatrix\n '2007 '2008 '2009 '2010 '2011 '2012 '2013 '2014 '2015 '2016 '2017 '2018 '2019 '2020 '2021 '2022 '2023 '2024\n 4 11 23 37 3 14 12 0 0 0 5 1 2 11 15 10 12 56\n description A heatmap matrix data visualization.\n catchAllParser heatrixCatchAllParser\n extends abstractTableVisualizationParser\n javascript\n buildHtml() {\n // A hacky but simple way to do this for now.\n const advanced = new Particle(\"heatrixAdvanced\")\n advanced.appendLineAndSubparticles(\"table\", \"\\n \" + this.tableData.replace(/\\n/g, \"\\n \"))\n const particle = this.appendSibling(\"heatrixAdvanced\", advanced.subparticlesToString())\n const html = particle.buildHtml()\n particle.destroy()\n return html\n }\n get tableData() {\n const {coreTable} = this.parent\n if (!coreTable)\n return this.subparticlesToString()\n let table = new Particle(coreTable).asSsv\n if (this.parent.cue === \"transpose\") {\n // drop first line after transpose\n const lines = table.split(\"\\n\")\n lines.shift()\n table = lines.join(\"\\n\")\n }\n // detect years and make strings\n const lines = table.split(\"\\n\")\n const yearLine = / \\d{4}(\\s+\\d{4})+$/\n if (yearLine.test(lines[0])) {\n lines[0] = lines[0].replace(/ /g, \" '\")\n table = lines.join(\"\\n\")\n }\n return table\n }\nheatrixAdvancedParser\n popularity 0.000048\n cueFromId\n catchAllParser heatrixCatchAllParser\n extends abstractTableVisualizationParser\n description Advanced heatrix.\n example\n heatrix\n table\n \n %h10; '2007 '2008 '2009\n 12 4 323\n scale\n #ebedf0 0\n #c7e9c0 100\n #a1d99b 400\n #74c476 1600\n javascript\n buildHtml() {\n class Heatrix {\n static HeatrixId = 0\n uid = Heatrix.HeatrixId++\n constructor(program) {\n const isDirective = atom => /^(f|l|w|h)\\d+$/.test(atom) || atom === \"right\" || atom === \"left\" || atom.startsWith(\"http://\") || atom.startsWith(\"https://\") || atom.endsWith(\".html\")\n const particle = new Particle(program)\n this.program = particle\n const generateColorBinningString = (data, colors) => {\n const sortedData = [...data].sort((a, b) => a - b);\n const n = sortedData.length;\n const numBins = colors.length;\n // Calculate the indices for each quantile\n const indices = [];\n for (let i = 1; i < numBins; i++) {\n indices.push(Math.floor((i / numBins) * n));\n }\n // Get the quantile values and round them\n const thresholds = indices.map(index => Math.round(sortedData[index]));\n // Generate the string\n let result = '';\n colors.forEach((color, index) => {\n const threshold = index === colors.length - 1 ? thresholds[index - 1] * 2 : thresholds[index];\n result += `${color} ${threshold}\\n`;\n });\n return result.trim();\n }\n const buildScale = (table) => {\n const numbers = table.split(\"\\n\").map(line => line.split(\" \")).flat().filter(atom => !isDirective(atom)).map(atom => parseFloat(atom)).filter(number => !isNaN(number))\n const colors = ['#ebedf0', '#c7e9c0', '#a1d99b', '#74c476', '#41ab5d', '#238b45', '#005a32'];\n numbers.unshift(0)\n return generateColorBinningString(numbers, colors);\n }\n const table = particle.getParticle(\"table\").subparticlesToString()\n const scale = particle.getParticle(\"scale\")?.subparticlesToString() || buildScale(table)\n const thresholds = []\n const colors = []\n scale.split(\"\\n\").map((line) => {\n const parts = line.split(\" \")\n thresholds.push(parseFloat(parts[1]))\n colors.push(parts[0])\n })\n const colorCount = colors.length\n const colorFunction = (value) => {\n if (isNaN(value)) return \"\" // #ebedf0\n for (let index = 0; index < colorCount; index++) {\n const threshold = thresholds[index]\n if (value <= threshold) return colors[index]\n }\n return colors[colorCount - 1]\n }\n const directiveDelimiter = \";\"\n const getSize = (directives, letter) =>\n directives\n .filter((directive) => directive.startsWith(letter))\n .map((dir) => dir.replace(letter, \"\") + \"px\")[0] ?? \"\"\n this.table = table.split(\"\\n\").map((line) =>\n line\n .trimEnd()\n .split(\" \")\n .map((atom) => {\n const atoms = atom.split(directiveDelimiter).filter((atom) => !isDirective(atom)).join(\"\")\n const directivesInThisAtom = atom\n .split(directiveDelimiter)\n .filter(isDirective)\n const value = parseFloat(atoms)\n const label = atoms.includes(\"'\") ? atoms.split(\"'\")[1] : atoms\n const alignment = directivesInThisAtom.includes(\"right\")\n ? \"right\"\n : directivesInThisAtom.includes(\"left\")\n ? \"left\"\n : \"\"\n const color = colorFunction(value)\n const width = getSize(directivesInThisAtom, \"w\")\n const height = getSize(directivesInThisAtom, \"h\")\n const fontSize = getSize(directivesInThisAtom, \"f\")\n const lineHeight = getSize(directivesInThisAtom, \"l\") || height\n const link = directivesInThisAtom.filter(i => i.startsWith(\"http\") || i.endsWith(\".html\"))[0]\n const style = {\n \"background-color\": color,\n width,\n height,\n \"font-size\": fontSize,\n \"line-height\": lineHeight,\n \"text-align\": alignment,\n }\n Object.keys(style).filter(key => !style[key]).forEach((key) => delete style[key])\n return {\n value,\n label,\n style,\n link,\n }\n })\n )\n }\n get html() {\n const { program } = this\n const cssId = `#heatrix${this.uid}`\n const defaultWidth = \"40px\"\n const defaultHeight = \"40px\"\n const fontSize = \"10px\"\n const lineHeight = defaultHeight\n const style = `<style>\n .heatrixContainer {\n margin: auto;\n }.heatrixRow {white-space: nowrap;}\n ${cssId} .heatrixAtom {\n font-family: arial;\n border-radius: 2px;\n border: 1px solid transparent;\n display: inline-block;\n margin: 1px;\n text-align: center;\n vertical-align: middle;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n .heatrixAtom a {\n color: black;\n }\n ${cssId} .heatrixAtom{\n width: ${defaultWidth};\n height: ${defaultHeight};\n font-size: ${fontSize};\n line-height: ${lineHeight};\n }\n </style>`\n const firstRow = this.table[0]\n return (\n `<div class=\"heatrixContainer\" id=\"heatrix${this.uid}\">${style}` +\n this.table\n .map((row, rowIndex) => {\n if (!rowIndex) return \"\"\n const rowStyle = row[0].style\n return `<div class=\"heatrixRow heatrixRow${rowIndex}\">${row\n .map((atom, columnIndex) => {\n if (!columnIndex) return \"\"\n const columnStyle = firstRow[columnIndex]?.style || {}\n let { value, label, style, link } = atom\n const extendedStyle = Object.assign(\n {},\n rowStyle,\n columnStyle,\n style\n )\n const inlineStyle = Object.keys(extendedStyle)\n .map((key) => `${key}:${extendedStyle[key]};`)\n .join(\"\")\n let valueClass = value ? \" valueAtom\" : \"\"\n const href = link ? ` href=\"${link}\"` : \"\"\n return `<div class=\"heatrixAtom heatrixColumn${columnIndex}${valueClass}\" style=\"${inlineStyle}\"><a title=\"${label}\" ${href}>${label}</a></div>`\n })\n .join(\"\")}</div>`\n })\n .join(\"\\n\") +\n \"</div>\"\n ).replace(/\\n/g, \"\")\n }\n }\n return new Heatrix(this.subparticlesToString().trim()).html\n }\nmapParser\n latParser\n atoms cueAtom floatAtom\n cueFromId\n single\n longParser\n atoms cueAtom floatAtom\n cueFromId\n single\n tilesParser\n atoms cueAtom tileOptionAtom\n cueFromId\n single\n zoomParser\n atoms cueAtom integerAtom\n cueFromId\n single\n geolocateParser\n description Geolocate user.\n atoms cueAtom\n cueFromId\n single\n radiusParser\n atoms cueAtom floatAtom\n cueFromId\n single\n fillOpacityParser\n atoms cueAtom floatAtom\n cueFromId\n single\n fillColorParser\n atoms cueAtom colorAtom\n cueFromId\n single\n colorParser\n atoms cueAtom colorAtom\n cueFromId\n single\n heightParser\n atoms cueAtom floatAtom\n cueFromId\n single\n hoverParser\n atoms cueAtom\n catchAllAtomType colorAtom\n cueFromId\n single\n extends abstractTableVisualizationParser\n description Map widget.\n string copyFromExternal .leaflet.css .leaflet.js .scrollLibs.js\n string requireOnce\n <link rel=\"stylesheet\" href=\".leaflet.css\">\n <script src=\".leaflet.js\"></script>\n <script src=\".scrollLibs.js\"></script>\n javascript\n buildInstance() {\n const height = this.get(\"height\") || 500\n const id = this._getUid()\n const obj = this.toObject()\n const template = {}\n const style = height !== \"full\" ? `height: ${height}px;` : `height: 100%; position: fixed; z-index: -1; left: 0; top: 0; width: 100%;`\n const strs = [\"color\", \"fillColor\"]\n const nums = [\"radius\", \"fillOpacity\"]\n strs.filter(i => obj[i]).forEach(i => template[i] = obj[i])\n nums.filter(i => obj[i]).forEach(i => template[i] = parseFloat(obj[i]))\n const mapId = `map${id}`\n return `<div id=\"${mapId}\" style=\"${style}\"></div>\n <script>\n {\n if (!window.maps) window.maps = {}\n const moveToMyLocation = () => {\n if (!navigator.geolocation) return\n navigator.geolocation.getCurrentPosition((position) => {\n const { latitude, longitude } = position.coords\n window.maps.${mapId}.setView([latitude, longitude])\n L.circleMarker([latitude, longitude], {\n fillOpacity: 0.8,\n radius: 20,\n weight: 4\n })\n .addTo(window.maps.${mapId})\n }, () => {})\n }\n const lat = ${this.get(\"lat\") ?? 37.8}\n const long = ${this.get(\"long\") ?? 4}\n if (${this.has(\"geolocate\")}){\n moveToMyLocation()\n }\n const zoomLevel = ${this.get(\"zoom\") ?? 4}\n const hover = '${this.get(\"hover\") || \"<b>{title}</b><br>{description}\"}'\n const template = ${JSON.stringify(template)}\n const points = ${JSON.stringify((this.parent.coreTable || []).filter(point => point.lat && point.long), undefined, 2)}\n window.maps.${mapId} = L.map(\"map${id}\").setView([lat, long], zoomLevel)\n const map = window.maps.${mapId}\n const tileOptions = {\n \"default\": {\n baseLayer: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',\n attribution: '<a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors'\n },\n light: {\n baseLayer: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png',\n attribution: '<a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors <a href=\"https://carto.com/ attributions\">CARTO</a>'\n },\n }\n const {baseLayer, attribution} = tileOptions.${this.get(\"tiles\") || \"default\"}\n L.tileLayer(baseLayer, {\n attribution,\n maxZoom: 19\n }).addTo(map);\n points.forEach(point => {\n L.circleMarker([point.lat, point.long], {...template, ...Object.fromEntries(\n Object.entries(point).filter(([key, value]) => value !== null)\n )})\n .addTo(map)\n .bindPopup(new Particle(point).evalTemplateString(hover))\n })\n }\n </script>`\n }\nabstractPlotParser\n // Observablehq\n extends abstractTableVisualizationParser\n string copyFromExternal .d3.js .plot.js\n string requireOnce\n <script src=\".d3.js\"></script>\n <script src=\".plot.js\"></script>\n example\n plot\n inScope abstractColumnNameParser\n widthParser\n cueFromId\n atoms cueAtom integerAtom\n heightParser\n cueFromId\n atoms cueAtom integerAtom\n titleParser\n extends abstractPlotLabelParser\n subtitleParser\n extends abstractPlotLabelParser\n captionParser\n extends abstractPlotLabelParser\n javascript\n buildInstance() {\n const id = \"plot\" + this._getUid()\n return `<div id=\"${id}\"></div><script>\n {\n let loadChart = async () => {\n const data = ${this.dataCode}\n const get = (col, index ) => col !== \"undefined\" ? col : (index === undefined ? undefined : Object.keys(data[0])[index])\n document.querySelector(\"#${id}\").append(Plot.plot(${this.plotOptions}))\n }\n loadChart()\n }\n </script>`\n }\n get sortExpression() {\n const sort = this.get(\"sort\")\n if (!sort) return \"\"\n let sort_expr = \"\"\n if (sort.startsWith(\"-\")) {\n // Sort by a value descending\n const sortCol = sort.slice(1)\n sort_expr = `, sort: {x: \"y\", reverse: true}`\n } else if (sort.includes(\" \")) {\n // Fixed order specified\n const order = sort.split(\" \")\n sort_expr = `, sort: {x: (a,b) => {\n const order = ${JSON.stringify(order)};\n return order.indexOf(a) - order.indexOf(b)\n }}`\n } else if (sort === \"asc\") {\n sort_expr = `, sort: {x: \"x\"}`\n } else if (sort === \"desc\") {\n sort_expr = `, sort: {x: \"x\", reverse: true}`\n }\n return sort_expr\n }\n get marks() {\n // just for testing purposes\n return `Plot.rectY({length: 10000}, Plot.binX({y: \"count\"}, {x: d3.randomNormal()}))`\n }\n get dataCode() {\n const {coreTable} = this.parent\n return `d3.csvParse(\\`${new Particle(coreTable).asCsv}\\`, d3.autoType)`\n }\n get plotOptions() {\n return `{\n title: \"${this.get(\"title\") || \"\"}\",\n subtitle: \"${this.get(\"subtitle\") || \"\"}\",\n caption: \"${this.get(\"caption\") || \"\"}\",\n symbol: {legend: ${this.has(\"symbol\")}},\n color: {legend: ${this.has(\"fill\") || this.has(\"stroke\")}},\n grid: ${this.get(\"grid\") !== \"false\"},\n marks: [${this.marks}],\n width: ${this.get(\"width\") || 640},\n height: ${this.get(\"height\") || 400},\n }`\n }\nplotScatterplotParser\n cue scatterplot\n extends abstractPlotParser\n description Scatterplot Widget.\n example\n iris\n scatterplot\n javascript\n get marks() {\n const x = this.get(\"x\")\n const y = this.get(\"y\")\n const text = this.get(\"label\")\n return `Plot.dot(data, {\n x: get(\"${x}\", 0),\n y: get(\"${y}\", 1),\n r: get(\"${this.get(\"radius\")}\"),\n fill: get(\"${this.get(\"fill\")}\"),\n tip: true${this.sortExpression},\n symbol: get(\"${this.get(\"symbol\")}\")} ), Plot.text(data, {x: get(\"${x}\",0), y: get(\"${y}\", 1), text: \"${text}\", dy: -6, lineAnchor: \"bottom\"})`\n }\nplotBarchartParser\n cue barchart\n extends abstractPlotParser\n description Bar chart widget.\n example\n iris\n barchart\n javascript\n get marks() {\n const x = this.get(\"x\")\n const y = this.get(\"y\")\n const text = this.get(\"label\")\n const fill = this.get(\"fill\")\n return `Plot.barY(data, {\n x: get(\"${x}\", 0),\n y: get(\"${y}\", 1),\n fill: get(\"${fill}\"),\n tip: true${this.sortExpression}\n }), Plot.ruleY([0])`\n }\nplotLineChartParser\n cue linechart\n extends abstractPlotParser\n description Line chart widget.\n example\n iris\n linechart\n x SepalLength\n y SepalWidth\n javascript\n get marks() {\n const x = this.get(\"x\")\n const y = this.get(\"y\")\n const stroke = this.get(\"stroke\") || \"steelblue\"\n const strokeWidth = this.get(\"strokeWidth\") || 2\n const strokeLinecap = this.get(\"strokeLinecap\") || \"round\"\n const fill = this.get(\"fill\")\n return `Plot.line(data, {\n x: get(\"${x}\", 0),\n y: get(\"${y}\", 1),\n stroke: \"${stroke}\",\n fill: get(\"${fill}\"),\n strokeWidth: ${strokeWidth},\n strokeLinecap: \"${strokeLinecap}\"${this.sortExpression}\n })`\n }\nsparklineParser\n popularity 0.000024\n description Sparkline widget.\n extends abstractTableVisualizationParser\n example\n sparkline 1 2 3 4 5\n string copyFromExternal .sparkline.js\n string requireOnce <script src=\".sparkline.js\"></script>\n catchAllAtomType numberAtom\n // we need pattern matching\n inScope scrollYParser\n javascript\n buildInstance() {\n const id = \"spark\" + this._getUid()\n const {columnValues} = this\n const start = this.has(\"start\") ? parseInt(this.get(\"start\")) : 0\n const width = this.get(\"width\") || 100\n const height = this.get(\"height\") || 30\n const lineColor = this.get(\"color\") || \"black\"\n return `<span id=\"${id}\"></span><script>new Sparkline(document.getElementById(\"${id}\"), {dotRadius: 0, width: ${width}, height: ${height}, lineColor: \"${lineColor}\", tooltip: (value,index) => ${start} + index + \": \" + value}).draw(${JSON.stringify(columnValues)})</script>`\n }\n get columnValues() {\n if (this.content)\n return this.content.split(\" \").map(str => parseFloat(str))\n const {coreTable} = this.parent\n if (coreTable) {\n const columnName = this.get(\"y\") || Object.keys(coreTable[0]).find(key => typeof coreTable[0][key] === 'number')\n return coreTable.map(row => row[columnName])\n }\n }\nprintColumnParser\n popularity 0.000024\n description Print one column\n extends abstractTableVisualizationParser\n example\n printColumn tags\n catchAllAtomType columnNameAtom\n joinParser\n boolean allowTrailingWhitespace true\n cueFromId\n atoms cueAtom\n catchAllAtomType stringAtom\n javascript\n buildHtml() {\n return this.columnValues.join(this.join)\n }\n buildTxt() {\n return this.columnValues.join(this.join)\n }\n get join() {\n return this.get(\"join\") || \"\\n\"\n }\n get columnName() {\n return this.atoms[1]\n }\n get columnValues() {\n return this.parent.coreTable.map(row => row[this.columnName])\n }\nprintTableParser\n popularity 0.001085\n cueFromId\n description Print table.\n extends abstractTableVisualizationParser\n javascript\n get tableHeader() {\n return this.columns.filter(col => !col.isLink).map(column => `<th>${column.name}</th>\\n`)\n }\n get columnNames() {\n return this.parent.columnNames\n }\n buildJson() {\n return JSON.stringify(this.coreTable, undefined, 2)\n }\n buildCsv() {\n return new Particle(this.coreTable).asCsv\n }\n buildTsv() {\n return new Particle(this.coreTable).asTsv\n }\n get columns() {\n const {columnNames} = this\n return columnNames.map((name, index) => {\n const isLink = name.endsWith(\"Link\")\n const linkIndex = columnNames.indexOf(name + \"Link\")\n return {\n name,\n isLink,\n linkIndex\n }\n })\n }\n toRow(row) {\n const {columns} = this\n const atoms = columns.map(col => row[col.name])\n let str = \"\"\n let column = 0\n const columnCount = columns.length\n while (column < columnCount) {\n const col = columns[column]\n column++\n const content = ((columnCount === column ? atoms.slice(columnCount - 1).join(\" \") : atoms[column - 1]) ?? \"\").toString()\n if (col.isLink) continue\n const isTimestamp = col.name.toLowerCase().includes(\"time\") && /^\\d{10}(\\d{3})?$/.test(content)\n const text = isTimestamp ? new Date(parseInt(content.length === 10 ? content * 1000 : content)).toLocaleString() : content\n let tagged = text\n const link = atoms[col.linkIndex]\n const isUrl = content.match(/^https?\\:[^ ]+$/)\n if (col.linkIndex > -1 && link) tagged = `<a href=\"${link}\">${text}</a>`\n else if (col.name.endsWith(\"Url\")) tagged = `<a href=\"${content}\">${col.name.replace(\"Url\", \"\")}</a>`\n else if (isUrl) tagged = `<a href=\"${content}\">${text}</a>`\n str += `<td>${tagged}</td>\\n`\n }\n return str\n }\n get coreTable() {\n return this.parent.coreTable\n }\n get tableBody() {\n return this.coreTable\n .map(row => `<tr>${this.toRow(row)}</tr>`)\n .join(\"\\n\")\n }\n buildHtml() {\n return `<table id=\"table${this._getUid()}\" class=\"scrollTable\">\n <thead><tr>${this.tableHeader.join(\"\\n\")}</tr></thead>\n <tbody>${this.tableBody}</tbody>\n </table>`\n }\n buildTxt() {\n return this.parent.delimitedData || new Particle(this.coreTable).asCsv\n }\nkatexParser\n popularity 0.001592\n extends abstractScrollWithRequirementsParser\n catchAllAtomType codeAtom\n catchAllParser lineOfCodeParser\n example\n katex\n \\text{E} = \\text{T} / \\text{A}!\n description KaTex widget for typeset math.\n string copyFromExternal .katex.min.css .katex.min.js\n string requireOnce\n <link rel=\"stylesheet\" href=\".katex.min.css\">\n <script defer src=\".katex.min.js\"></script>\n <script>\n document.addEventListener(\"DOMContentLoaded\", () => document.querySelectorAll(\".scrollKatex\").forEach(el =>\n {\n katex.render(el.innerText, el, {\n throwOnError: false\n });\n }\n ))\n </script>\n javascript\n buildInstance() {\n const id = this._getUid()\n const content = this.content === undefined ? \"\" : this.content\n return `<div class=\"scrollKatex\" id=\"${id}\">${content + this.subparticlesToString()}</div>`\n }\n buildTxt() {\n return ( this.content ? this.content : \"\" )+ this.subparticlesToString()\n }\nhelpfulNotFoundParser\n popularity 0.000048\n extends abstractScrollWithRequirementsParser\n catchAllAtomType filePathAtom\n string copyFromExternal .helpfulNotFound.js\n description Helpful not found widget.\n javascript\n buildInstance() {\n return `<style>#helpfulNotFound{margin: 100px 0;}</style><h1 id=\"helpfulNotFound\"></h1><script defer src=\"/.helpfulNotFound.js\"></script><script>document.addEventListener(\"DOMContentLoaded\", () => new NotFoundApp('${this.content}'))</script>`\n }\nslideshowParser\n // Left and right arrows navigate.\n description Slideshow widget. *** delimits slides.\n extends abstractScrollWithRequirementsParser\n string copyFromExternal .jquery-3.7.1.min.js .slideshow.js\n example\n slideshow\n Why did the cow cross the road?\n ***\n Because it wanted to go to the MOOOO-vies.\n ***\n THE END\n ****\n javascript\n buildHtml() {\n return `<style>html {font-size: var(--scrollBaseFontSize, 28px);} body {margin: auto; width: 500px;}.slideshowNav{text-align: center; margin-bottom:20px; font-size: 24px;color: rgba(204,204,204,.8);} a{text-decoration: none; color: rgba(204,204,204,.8);}</style><script defer src=\".jquery-3.7.1.min.js\"></script><div class=\"slideshowNav\"></div><script defer src=\".slideshow.js\"></script>`\n }\ntableSearchParser\n popularity 0.000072\n extends abstractScrollWithRequirementsParser\n string copyFromExternal .jquery-3.7.1.min.js .datatables.css .dayjs.min.js .datatables.js .tableSearch.js\n string requireOnce\n <script defer src=\".jquery-3.7.1.min.js\"></script>\n <style>.dt-search{font-family: \"SF Pro\", \"Helvetica Neue\", \"Segoe UI\", \"Arial\";}</style>\n <link rel=\"stylesheet\" href=\".datatables.css\">\n <script defer src=\".datatables.js\"></script>\n <script defer src=\".dayjs.min.js\"></script>\n <script defer src=\".tableSearch.js\"></script>\n // adds to all tables on page\n description Table search and sort widget.\n javascript\n buildInstance() {\n return \"\"\n }\nabstractCommentParser\n description Prints nothing.\n catchAllAtomType commentAtom\n atoms commentAtom\n extends abstractScrollParser\n baseParser blobParser\n string bindTo next\n javascript\n buildHtml() {\n return ``\n }\n catchAllParser commentLineParser\ncommentParser\n popularity 0.000193\n extends abstractCommentParser\n cueFromId\ncounterpointParser\n description Counterpoint comment. Prints nothing.\n extends commentParser\n cue !\nslashCommentParser\n popularity 0.005643\n extends abstractCommentParser\n cue //\n boolean isPopular true\n description A comment. Prints nothing.\nthanksToParser\n description Acknowledgements comment. Prints nothing.\n extends abstractCommentParser\n cueFromId\nscrollClearStackParser\n popularity 0.000096\n cue clearStack\n description Clear body stack.\n extends abstractScrollParser\n boolean isHtml true\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n return this.root.clearBodyStack().trim()\n }\ncssParser\n popularity 0.007211\n extends abstractScrollParser\n description A style tag.\n example\n css\n body { color: red;}\n cueFromId\n catchAllParser cssLineParser\n catchAllAtomType cssAnyAtom\n javascript\n buildHtml() {\n return `<style>${this.css}</style>`\n }\n get css() {\n return this.content ?? this.subparticlesToString()\n }\n buildCss() {\n return this.css\n }\nscrollBackgroundColorParser\n description Quickly set CSS background.\n popularity 0.007211\n extends abstractScrollParser\n cue background\n catchAllAtomType cssAnyAtom\n example\n background red\n javascript\n buildHtml() {\n return `<style>html, body { background: ${this.content};}</style>`\n }\nscrollFontColorParser\n description Quickly set CSS font-color.\n popularity 0.007211\n extends abstractScrollParser\n cue color\n catchAllAtomType cssAnyAtom\n javascript\n buildHtml() {\n return `<style>html, body { color: ${this.content};}</style>`\n }\nscrollFontParser\n description Quickly set font family.\n popularity 0.007211\n extends abstractScrollParser\n cue font\n atoms cueAtom fontFamilyAtom\n catchAllAtomType cssAnyAtom\n example\n font Slim\n javascript\n buildHtml() {\n const font = this.content === \"Slim\" ? \"Helvetica Neue; font-weight:100;\" : this.content\n return `<style>html, body, h1,h2,h3 { font-family: ${font};}</style>`\n }\nabstractQuickIncludeParser\n popularity 0.007524\n extends abstractScrollParser\n atoms urlAtom\n javascript\n get dependencies() { return [this.filename]}\n get filename() {\n return this.getAtom(0)\n }\nquickCssParser\n popularity 0.007524\n description Make a CSS tag.\n extends abstractQuickIncludeParser\n example\n style.css\n atoms urlAtom\n pattern ^[^\\s]+\\.(css)$\n javascript\n buildHtml() {\n return `<link rel=\"stylesheet\" type=\"text/css\" href=\"${this.filename}\">`\n }\n buildHtmlSnippet() {\n return \"\"\n }\nquickIncludeHtmlParser\n popularity 0.007524\n description Include an HTML file.\n extends abstractQuickIncludeParser\n example\n body.html\n atoms urlAtom\n pattern ^[^\\s]+\\.(html|htm)$\n javascript\n buildHtml() {\n return this.root.readFile(this.filename)\n }\nquickScriptParser\n popularity 0.007524\n description Make a Javascript tag.\n extends abstractQuickIncludeParser\n atoms urlAtom\n example\n script.js\n pattern ^[^\\s]+\\.(js)$\n javascript\n buildHtml() {\n return `<script src=\"${this.filename}\"></script>`\n }\n buildHtmlSnippet() {\n return \"\"\n }\nscrollDashboardParser\n popularity 0.000145\n description Key stats in large font.\n catchAllParser lineOfCodeParser\n cue dashboard\n extends abstractScrollParser\n example\n dashboard\n #2 Popularity\n 30 Years Old\n $456 Revenue\n javascript\n get tableBody() {\n const items = this.topDownArray\n let str = \"\"\n for (let i = 0; i < items.length; i = i + 3) {\n str += this.makeRow(items.slice(i, i + 3))\n }\n return str\n }\n makeRow(items) {\n return `<tr>` + items.map(particle => `<td>${particle.cue}<span>${particle.content}</span></td>`).join(\"\\n\") + `</tr>\\n`\n }\n buildHtml() {\n return `<table class=\"scrollDashboard\">${this.tableBody}</table>`\n }\n buildTxt() {\n return this.subparticlesToString()\n }\nbelowAsCodeParser\n popularity 0.000651\n description Print code below.\n string bindTo next\n extends abstractScrollParser\n catchAllAtomType integerAtom\n example\n belowAsCode\n iris\n printTable\n cueFromId\n javascript\n method = \"next\"\n get selectedParticles() {\n const { method } = this\n let code = \"\"\n let particles = []\n let next = this[method]\n let {howMany} = this\n while (howMany) {\n particles.push(next)\n next = next[method]\n howMany--\n }\n if (this.reverse) particles.reverse()\n return particles\n }\n get code() {\n return this.selectedParticles.map(particle => particle.asString).join(\"\\n\")\n }\n reverse = false\n buildHtml() {\n return `<code class=\"scrollCodeBlock\">${this.code.replace(/\\</g, \"&lt;\")}</code>`\n }\n get howMany() {\n let howMany = parseInt(this.getAtom(1))\n if (!howMany || isNaN(howMany)) howMany = 1\n return howMany\n }\ndebugBelowParser\n description Inspect particle below.\n extends belowAsCodeParser\n string copyFromExternal .debug.css\n javascript\n get code() {\n const mapFn = particle => {\n const atomTypes = particle.lineAtomTypes.split(\" \")\n return `<div class=\"debugParticle\"><span class=\"debugParticleId\">${particle.constructor.name}</span>${particle.atoms.map((atom, index) => `<span class=\"debugAtom\">${atom}<span class=\"debugAtomType\">${atomTypes[index]}</span></span>`).join(\" \")}${(particle.length ? `<br><div class=\"debugSubparticles\">` + particle.map(mapFn).join(\"<br>\") + `</div>` : \"\")}</div>`}\n return this.selectedParticles.map(mapFn).join(\"<br>\")\n }\n buildHtml() {\n return `<link rel=\"stylesheet\" href=\".debug.css\">` + this.code\n }\n buildTxt() {\n const mapFn = particle => {\n const atomTypes = particle.lineAtomTypes.split(\" \")\n return `${particle.constructor.name} ${particle.atoms.map((atom, index) => `${atomTypes[index]}:${atom}`).join(\" \")}${(particle.length ? `\\n ` + particle.map(mapFn).join(\"\\n\") + `` : \"\")}`}\n return this.selectedParticles.map(mapFn).join(\"\\n\")\n }\n buildParsers() {return this.buildTxt()}\ndebugAboveParser\n description Inspect particle above.\n extends debugBelowParser\n string bindTo previous\n javascript\n method = \"previous\"\n reverse = true\ndebugAllParser\n description Inspect entire document.\n extends debugBelowParser\n javascript\n get selectedParticles() { return this.root.getSubparticles()}\nbelowAsCodeUntilParser\n description Print code above until match.\n extends belowAsCodeParser\n catchAllAtomType codeAtom\n example\n belowAsCode\n counter 1 second\n javascript\n get howMany() {\n let howMany = 1\n const query = this.content\n let particle = this.next\n while (particle !== this) {\n if (particle.getLine().startsWith(query))\n return howMany\n particle = particle.next\n howMany++\n }\n return howMany\n }\naboveAsCodeParser\n popularity 0.000482\n string bindTo previous\n description Print code above.\n example\n counter 1 second\n aboveAsCode\n extends belowAsCodeParser\n javascript\n method = \"previous\"\n reverse = true\nbelowAsHtmlParser\n extends belowAsCodeParser\n description Displays html output of next particle in a code block.\n cueFromId\n example\n belowAsHtml\n # Hello world\n javascript\n get code() {\n return this.selectedParticles.filter(p => p.buildHtml).map(p => p.buildHtml()).join(\"\\n\")\n }\naboveAsHtmlParser\n description Displays html output of previous particle in a code block.\n extends belowAsHtmlParser\n example\n # Hello world\n aboveAsHtml\n javascript\n method = \"previous\"\n reverse = true\nscrollDefParser\n popularity 0.004244\n description Parser short form.\n pattern ^[a-zA-Z0-9_]+Def\n extends abstractScrollParser\n catchAllAtomType stringAtom\n example\n urlDef What is the URL?\n javascript\n buildParsers(index) {\n const idStuff = index ? \"\" : `boolean isMeasure true\n boolean isMeasureRequired true\n boolean isConceptDelimiter true`\n const description = this.content\n const cue = this.cue.replace(\"Def\", \"\")\n const sortIndex = 1 + index/10\n return `${cue}DefParser\n cue ${cue}\n extends abstractStringMeasureParser\n description ${description}\n float sortIndex ${sortIndex}\n ${idStuff}`.trim()\n }\nhakonParser\n cueFromId\n extends abstractScrollParser\n description Compile Hakon to CSS.\n catchAllParser hakonContentParser\n javascript\n buildHtml() {\n return `<style>${this.css}</style>`\n }\n get css() {\n const {hakonParser} = this.root\n return new hakonParser(this.subparticlesToString()).compile()\n }\n buildCss() {\n return this.css\n }\nhamlParser\n popularity 0.007524\n description HTML tag via HAML syntax.\n extends abstractScrollParser\n atoms urlAtom\n catchAllAtomType stringAtom\n pattern ^%?[\\w\\.]+#[\\w\\.]+ *\n javascript\n get tag() {\n return this.atoms[0].split(/[#\\.]/).shift().replace(\"%\", \"\")\n }\n get htmlId() {\n const idMatch = this.atoms[0].match(/#([\\w-]+)/)\n return idMatch ? idMatch[1] : \"\"\n }\n get htmlClasses() {\n return this.atoms[0].match(/\\.([\\w-]+)/g)?.map(cls => cls.slice(1)) || [];\n }\n buildHtml() {\n const {htmlId, htmlClasses, content, tag} = this\n this.parent.sectionStack.unshift(`</${tag}>`)\n const attrs = [htmlId ? ' id=\"' + htmlId + '\"' : \"\", htmlClasses.length ? ' class=\"' + htmlClasses.join(\" \") + '\"' : \"\"].join(\" \").trim()\n return `<${tag}${attrs ? \" \" + attrs : \"\"}>${content || \"\"}`\n }\n buildTxt() {\n return this.content\n }\nhamlTagParser\n // Match plain tags like %h1\n extends hamlParser\n pattern ^%[^#]+$\nabstractHtmlParser\n extends abstractScrollParser\n catchAllParser htmlLineParser\n catchAllAtomType htmlAnyAtom\n javascript\n buildHtml() {\n return `${this.content ?? \"\"}${this.subparticlesToString()}`\n }\n buildTxt() {\n return \"\"\n }\nhtmlParser\n popularity 0.000048\n extends abstractHtmlParser\n description HTML one liners or blocks.\n cueFromId\nhtmlInlineParser\n popularity 0.005788\n extends abstractHtmlParser\n atoms htmlAnyAtom\n boolean isHtml true\n example\n <h1>Inline HTML</h1>\n pattern ^<\n description Inline HTML.\n boolean isPopular true\n javascript\n buildHtml() {\n return `${this.getLine() ?? \"\"}${this.subparticlesToString()}`\n }\nscrollBrParser\n popularity 0.000096\n cue br\n example\n br 2\n description A break.\n extends abstractScrollParser\n catchAllAtomType integerAtom\n boolean isHtml true\n javascript\n buildHtml() {\n return `<br>`.repeat(parseInt(this.getAtom(1) || 1))\n }\niframesParser\n popularity 0.000121\n cueFromId\n catchAllAtomType urlAtom\n extends abstractScrollParser\n description An iframe(s).\n example\n iframes frame.html\n javascript\n buildHtml() {\n return this.atoms.slice(1).map(url => `<iframe src=\"${url}\" frameborder=\"0\"></iframe>`).join(\"\\n\")\n }\nabstractCaptionedParser\n extends abstractScrollParser\n atoms cueAtom urlAtom\n inScope captionAftertextParser slashCommentParser\n cueFromId\n javascript\n buildHtml(buildSettings) {\n const caption = this.getParticle(\"caption\")\n const captionFig = caption ? `<figcaption>${caption.buildHtml()}</figcaption>` : \"\"\n const {figureWidth} = this\n const widthStyle = figureWidth ? `width:${figureWidth}px; margin: auto;` : \"\"\n const float = this.has(\"float\") ? `margin: 20px; float: ${this.get(\"float\")};` : \"\"\n return `<figure class=\"scrollCaptionedFigure\" style=\"${widthStyle + float}\">${this.getFigureContent(buildSettings)}${captionFig}</figure>`\n }\n get figureWidth() {\n return this.get(\"width\")\n }\nscrollImageParser\n cue image\n popularity 0.005908\n description An img tag.\n boolean isPopular true\n extends abstractCaptionedParser\n int atomIndex 1\n example\n image screenshot.png\n caption A caption.\n inScope addClassMarkupParser aftertextIdParser scrollLinkParser linkTargetParser openGraphParser\n javascript\n get dimensions() {\n const width = this.get(\"width\")\n const height = this.get(\"height\")\n if (width || height)\n return {width, height}\n if (!this.isNodeJs())\n return {}\n const src = this.filename\n // If its a local image, get the dimensions and put them in the HTML\n // to avoid flicker\n if (src.startsWith(\"http:\") || src.startsWith(\"https:\")) return {}\n if (this._dimensions)\n return this._dimensions\n try {\n const sizeOf = require(\"image-size\")\n const path = require(\"path\")\n const fullImagePath = path.join(this.root.folderPath, src)\n this._dimensions = sizeOf(fullImagePath)\n return this._dimensions\n } catch (err) {\n console.error(err)\n }\n return {}\n }\n get figureWidth() {\n return this.dimensions.width\n }\n get filename() {\n return this.getAtom(this.atomIndex)\n }\n get dependencies() { return [this.filename]}\n getFigureContent(buildSettings) {\n const linkRelativeToCompileTarget = (buildSettings ? (buildSettings.relativePath ?? \"\") : \"\") + this.filename\n const {width, height} = this.dimensions\n let dimensionAttributes = width || height ? `width=\"${width}\" height=\"${height}\" ` : \"\"\n // Todo: can we reuse more code from aftertext?\n const className = this.has(\"class\") ? ` class=\"${this.get(\"class\")}\" ` : \"\"\n const id = this.has(\"id\") ? ` id=\"${this.get(\"id\")}\" ` : \"\"\n const clickLink = this.find(particle => particle.definition.isOrExtendsAParserInScope([\"scrollLinkParser\"])) || linkRelativeToCompileTarget \n const target = this.has(\"target\") ? this.get(\"target\") : (this.has(\"link\") ? \"\" : \"_blank\")\n return `<a href=\"${clickLink}\" target=\"${target}\" ${className} ${id}><img src=\"${linkRelativeToCompileTarget}\" ${dimensionAttributes}loading=\"lazy\"></a>`\n }\n buildTxt() {\n const subparticles = this.filter(particle => particle.buildTxt).map(particle => particle.buildTxt()).filter(i => i).join(\"\\n\")\n return \"[Image Omitted]\" + (subparticles ? \"\\n \" + subparticles.replace(/\\n/g, \"\\n \") : \"\")\n }\nquickImageParser\n popularity 0.005788\n extends scrollImageParser\n example\n screenshot.png\n atoms urlAtom\n pattern ^[^\\s]+\\.(jpg|jpeg|png|gif|webp|svg|bmp)\n int atomIndex 0\nqrcodeParser\n extends abstractCaptionedParser\n description Make a QR code from a link.\n example\n qrcode https://scroll.pub\n javascript\n getFigureContent() {\n const url = this.atoms[1]\n const isNode = this.isNodeJs()\n if (isNode) {\n const {externalsPath} = this.root\n const path = require(\"path\")\n const {qrcodegen, toSvgString} = require(path.join(externalsPath, \".qrcodegen.js\"))\n const QRC = qrcodegen.QrCode;\n const qr0 = QRC.encodeText(url, QRC.Ecc.MEDIUM);\n const svg = toSvgString(qr0, 4); // See qrcodegen-input-demo\n return svg\n }\n return `Not yet supported in browser.`\n }\nyoutubeParser\n popularity 0.000121\n extends abstractCaptionedParser\n // Include the YouTube embed URL such as https://www.youtube.com/embed/CYPYZnVQoLg\n description A YouTube video widget.\n example\n youtube https://www.youtube.com/watch?v=lO8blNtYYBA\n javascript\n getFigureContent() {\n const url = this.getAtom(1).replace(\"youtube.com/watch?v=\", \"youtube.com/embed/\")\n return `<div class=\"scrollYouTubeHolder\"><iframe class=\"scrollYouTubeEmbed\" src=\"${url}\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe></div>`\n }\nyouTubeParser\n extends youtubeParser\n tags deprecate\n // Deprecated. You youtube all lowercase.\nimportParser\n description Import a file.\n popularity 0.007524\n cueFromId\n atoms preBuildCommandAtom\n extends abstractScrollParser\n catchAllAtomType filePathAtom\n javascript\n buildHtml() {\n return \"\"\n }\n example\n import header.scroll\nscrollImportedParser\n description Inserted at import pass.\n boolean suggestInAutocomplete false\n cue imported\n atoms preBuildCommandAtom\n extends abstractScrollParser\n baseParser blobParser\n catchAllAtomType filePathAtom\n javascript\n buildHtml() {\n return \"\"\n }\n getErrors() {\n if (this.get(\"exists\") === \"false\" && this.previous.getLine() !== \"// optional\")\n return [this.makeError(`File '${this.atoms[1]}' does not exist.`)]\n return []\n }\nquickImportParser\n popularity 0.007524\n description Import a Scroll or Parsers file.\n extends abstractScrollParser\n boolean isPopular true\n inScope importToFooterParser abstractCommentParser\n atoms urlAtom\n pattern ^[^\\s]+\\.(scroll|parsers)$\n javascript\n buildHtml() {\n return \"\"\n }\n example\n header.scroll\nscriptParser\n extends abstractScrollParser\n description Print script tag.\n cueFromId\n catchAllParser scriptLineParser\n catchAllAtomType javascriptAnyAtom\n javascript\n buildHtml() {\n return `<script>${this.scriptContent}</script>`\n }\n get scriptContent() {\n return this.content ?? this.subparticlesToString()\n }\n buildJs() {\n return this.scriptContent\n }\njsonScriptParser\n popularity 0.007524\n cueFromId\n description Include JSON and assign to window.\n extends abstractScrollParser\n atoms cueAtom urlAtom\n javascript\n buildHtml() {\n const varName = this.filename.split(\"/\").pop().replace(\".json\", \"\")\n return `<script>window.${varName} = ${this.root.readFile(this.filename)}</script>`\n }\n get filename() {\n return this.getAtom(1)\n }\nscrollLeftRightButtonsParser\n popularity 0.006342\n cue leftRightButtons\n description Previous and next nav buttons.\n extends abstractScrollParser\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n const { linkToPrevious, linkToNext } = this.root\n if (!linkToPrevious) return \"\"\n const style = `a.keyboardNav {display:block;position:absolute;top:0.25rem; color: rgba(204,204,204,.8); font-size: 1.875rem; line-height: 1.7rem;}a.keyboardNav:hover{color: #333;text-decoration: none;}`\n return `<style>${style}</style><a class=\"keyboardNav doNotPrint\" style=\"left:.5rem;\" href=\"${linkToPrevious}\">&lt;</a><a class=\"keyboardNav doNotPrint\" style=\"right:.5rem;\" href=\"${linkToNext}\">&gt;</a>`\n }\nkeyboardNavParser\n popularity 0.007476\n description Make left and right navigate files.\n extends abstractScrollParser\n cueFromId\n catchAllAtomType urlAtom\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n const {root} = this\n const linkToPrevious = this.getAtom(1) ?? root.linkToPrevious\n const linkToNext = this.getAtom(2) ?? root.linkToNext\n const script = `<script>document.addEventListener('keydown', function(event) {\n if (document.activeElement !== document.body) return\n if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return // dont interfere with keyboard back button shortcut\n const getLinks = () => document.getElementsByClassName(\"scrollKeyboardNav\")[0].getElementsByTagName(\"a\")\n if (event.key === \"ArrowLeft\")\n getLinks()[0].click()\n else if (event.key === \"ArrowRight\")\n getLinks()[1].click()\n });</script>`\n return `<div class=\"scrollKeyboardNav\" style=\"display:none;\"><a href=\"${linkToPrevious}\">${linkToPrevious}</a> · ${root.permalink} · <a href=\"${linkToNext}\">${linkToNext}</a>${script}</div>`\n }\nprintUsageStatsParser\n popularity 0.000096\n // todo: if we include the atom \"Parser\" in a cue, bad things seem to happen.\n description Parser usage stats for folder.\n extends abstractScrollParser\n cueFromId\n javascript\n get stats() {\n const input = this.root.allScrollFiles.map(file => file.scrollProgram).map(program => program.parserIds.join(\"\\n\")).join(\"\\n\")\n const result = input.split('\\n').reduce((acc, atom) => (acc[atom] = (acc[atom] || 0) + 1, acc), {})\n const rows = Object.entries(result).map(([atom, count]) => { return {atom, count}})\n const sorted = this.root.lodash.sortBy(rows, \"count\").reverse()\n return \"parserId uses\\n\" + sorted.map(row => `${row.atom} ${row.count}`).join('\\n')\n }\n buildHtml() {\n // A hacky but simple way to do this for now.\n const particle = this.appendSibling(\"table\")\n particle.appendLine(\"delimiter \")\n particle.appendLine(\"printTable\")\n const dataParticle = particle.appendLine(\"data\")\n dataParticle.setSubparticles(this.stats)\n const html = particle.buildHtml()\n particle.destroy()\n return html\n }\n buildTxt() {\n return this.stats\n }\n buildCsv() {\n return this.stats.replace(/ /g, \",\")\n }\nprintScrollLeetSheetParser\n popularity 0.000024\n description Print Scroll parser leet sheet.\n extends abstractScrollParser\n tags experimental\n cueFromId\n javascript\n get parsersToDocument() {\n const clone = this.root.clone()\n clone.setSubparticles(\"\")\n const atoms = clone.getAutocompleteResultsAt(0,0).matches.map(a => a.text)\n atoms.push(\"blankline\") // manually add blank line\n atoms.push(\"Catch All Paragraph.\") // manually add catch all paragraph\n atoms.push(\"<h></h>\") // manually add html\n atoms.sort()\n clone.setSubparticles(atoms.join(\"\\n\").replace(/blankline/, \"\")) // insert blank line in right spot\n return clone\n }\n sortDocs(docs) {\n return docs.map(particle => {\n const {definition} = particle\n const {id, description, isPopular, examples, popularity} = definition\n const tags = definition.get(\"tags\") || \"\"\n if (tags.includes(\"deprecate\") || tags.includes(\"experimental\"))\n return null\n const category = this.getCategory(tags)\n const note = this.getNote(category)\n return {id: definition.cueIfAny || id, description, isPopular, examples, note, popularity: Math.ceil(parseFloat(popularity) * 100000)}\n }).filter(i => i).sort((a, b) => a.id.localeCompare(b.id))\n }\n makeLink(examples, cue) {\n // if (!examples.length) console.log(cue) // find particles that need docs\n const example = examples.length ? examples[0].subparticlesToString() : cue\n const base = `https://try.scroll.pub/`\n const particle = new Particle()\n particle.appendLineAndSubparticles(\"scroll\", \"theme gazette\\n\" + example)\n return base + \"#\" + encodeURIComponent(particle.asString)\n }\n docToHtml(doc) {\n const css = `#scrollLeetSheet {color: grey;} #scrollLeetSheet a {color: #3498db; }`\n return `<style>${css}</style><div id=\"scrollLeetSheet\">` + doc.map(obj => `<div class=\"${obj.category}\"><a href=\"${this.makeLink(obj.examples, obj.id)}\">${obj.isPopular ? \"<b>\" : \"\"}${obj.id}</a> ${obj.description}${obj.isPopular ? \"</b>\" : \"\"}${obj.note}</div>`).join(\"\\n\") + \"</div>\"\n }\n buildHtml() {\n return this.docToHtml(this.sortDocs(this.parsersToDocument))\n }\n buildTxt() {\n return this.sortDocs(this.parsersToDocument).map(obj => `${obj.id} - ${obj.description}`).join(\"\\n\")\n }\n getCategory(input) {\n return \"\"\n }\n getNote() {\n return \"\"\n }\n get docs() {\n const rows = this.sortDocs(this.parsersToDocument).map(obj => {\n const {id, isPopular, description, popularity, category, examples, cue} = obj\n const example = examples.length ? examples[0].subparticlesToString() : cue\n return {\n id,\n isPopular,\n description,\n popularity,\n example,\n category\n }\n })\n return this.root.lodash.sortBy(rows, \"isPopular\")\n }\n buildJson() {\n return JSON.stringify(this.docs, undefined, 2)\n }\n buildCsv() {\n return new Particle(this.docs).asCsv\n }\nprintparsersLeetSheetParser\n popularity 0.000024\n // todo: fix parse bug when atom Parser appears in parserId\n extends printScrollLeetSheetParser\n tags experimental\n description Parsers leetsheet.\n javascript\n buildHtml() {\n return \"<p><b>Parser Definition Parsers</b> define parsers that acquire, analyze and act on code.</p>\" + this.docToHtml(this.sortDocs(this.parsersToDocument)) + \"<p><b>Atom Definition Parsers</b> analyze the atoms in a line.</p>\" + this.docToHtml(this.sortDocs(this.atomParsersToDocument))\n }\n makeLink() {\n return \"\"\n }\n categories = \"assemblePhase acquirePhase analyzePhase actPhase\".split(\" \")\n getCategory(tags) {\n return tags.split(\" \").filter(w => w.endsWith(\"Phase\"))[0]\n }\n getNote(category) {\n return ` <span class=\"note\">A${category.replace(\"Phase\", \"\").substr(1)}Time.</span>`\n }\n get atomParsersToDocument() {\n const parsersParser = require(\"scrollsdk/products/parsers.nodejs.js\")\n const clone = new parsersParser(\"anyAtom\\n \").clone()\n const parserParticle = clone.getParticle(\"anyAtom\")\n const atoms = clone.getAutocompleteResultsAt(1,1).matches.map(a => a.text)\n atoms.sort()\n parserParticle.setSubparticles(atoms.join(\"\\n\"))\n return parserParticle\n }\n get parsersToDocument() {\n const parsersParser = require(\"scrollsdk/products/parsers.nodejs.js\")\n const clone = new parsersParser(\"latinParser\\n \").clone()\n const parserParticle = clone.getParticle(\"latinParser\")\n const atoms = clone.getAutocompleteResultsAt(1,1).matches.map(a => a.text)\n atoms.sort()\n parserParticle.setSubparticles(atoms.join(\"\\n\"))\n clone.appendLine(\"myParser\")\n clone.appendLine(\"myAtom\")\n return parserParticle\n }\nabstractMeasureParser\n atoms measureNameAtom\n description Base parser all measures extend.\n cueFromId\n boolean isMeasure true\n float sortIndex 1.9\n boolean isComputed false\n string typeForWebForms text\n extends abstractScrollParser\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n return \"\"\n }\n get measureValue() {\n return this.content ?? \"\"\n }\n get measureName() {\n return this.getCuePath().replace(/ /g, \"_\")\n }\nabstractAtomMeasureParser\n description Contains a single word.\n atoms measureNameAtom atomAtom\n example\n nicknameParser\n extends abstractAtomMeasureParser\n id Breck\n nickname breck\n extends abstractMeasureParser\nabstractEmailMeasureParser\n description Email address.\n example\n emailParser\n extends abstractEmailMeasureParser\n id Breck\n email breck7@gmail.com\n string typeForWebForms email\n atoms measureNameAtom emailAddressAtom\n extends abstractAtomMeasureParser\nabstractUrlMeasureParser\n description A single url.\n example\n homepageParser\n extends abstractUrlMeasureParser\n id Breck\n homepage https://breckyunits.com\n string typeForWebForms url\n atoms measureNameAtom urlAtom\n extends abstractAtomMeasureParser\nabstractStringMeasureParser\n description General text data with no specific format.\n catchAllAtomType stringAtom\n example\n titleParser\n extends abstractStringMeasureParser\n id Breck\n title I build languages for scientists of all ages\n extends abstractMeasureParser\nabstractIdParser\n cue id\n description What is the ID of this concept?\n extends abstractStringMeasureParser\n example\n idParser\n extends abstractIdParser\n id breck\n float sortIndex 1\n boolean isMeasureRequired true\n boolean isConceptDelimiter true\n javascript\n getErrors() {\n const errors = super.getErrors()\n let requiredMeasureNames = this.root.measures.filter(measure => measure.isMeasureRequired).map(measure => measure.Name).filter(name => name !== \"id\")\n if (!requiredMeasureNames.length) return errors\n let next = this.next\n while (requiredMeasureNames.length && next.cue !== \"id\" && next.index !== 0) {\n requiredMeasureNames = requiredMeasureNames.filter(i => i !== next.cue)\n next = next.next\n }\n requiredMeasureNames.forEach(name =>\n errors.push(this.makeError(`Concept \"${this.content}\" is missing required measure \"${name}\".`))\n )\n return errors\n }\nabstractIdMeasureParser\n description Alias for abstractIdParser.\n extends abstractIdParser\nabstractTextareaMeasureParser\n string typeForWebForms textarea\n example\n bioParser\n extends abstractTextareaMeasureParser\n id Breck\n bio\n I build languages for scientists of all ages\n description Long-form text content with preserved line breaks.\n extends abstractMeasureParser\n baseParser blobParser\n javascript\n get measureValue() {\n return this.subparticlesToString().replace(/\\n/g, \"\\\\n\")\n }\nabstractNumericMeasureParser\n string typeForWebForms number\n description Base number type.\n extends abstractMeasureParser\n javascript\n get measureValue() {\n const {content} = this\n return content === undefined ? \"\" : parseFloat(content)\n }\nabstractNumberMeasureParser\n description Alias to abstractNumericMeasureParser.\n extends abstractNumericMeasureParser\nabstractIntegerMeasureParser\n description An integer.\n example\n ageParser\n extends abstractIntegerMeasureParser\n id Breck\n age 40\n atoms measureNameAtom integerAtom\n extends abstractNumericMeasureParser\n javascript\n get measureValue() {\n const {content} = this\n return content === undefined ? \"\" : parseInt(content)\n }\nabstractIntMeasureParser\n description Alias to abstractIntegerMeasureParser.\n extends abstractIntegerMeasureParser\nabstractFloatMeasureParser\n description A float.\n example\n temperatureParser\n extends abstractFloatMeasureParser\n id Breck\n temperature 31.8\n atoms measureNameAtom floatAtom\n extends abstractNumericMeasureParser\nabstractPercentageMeasureParser\n description A percentage.\n atoms measureNameAtom percentAtom\n extends abstractNumericMeasureParser\n example\n ownershipParser\n extends abstractPercentageMeasureParser\n id Breck\n ownership 31.8\n javascript\n get measureValue() {\n const {content} = this\n return content === undefined ? \"\" : parseFloat(content)\n }\nabstractEnumMeasureParser\n description A single enum.\n atoms measureNameAtom enumAtom\n extends abstractMeasureParser\n example\n favoriteHtmlTagParser\n extends abstractEnumMeasureParser\n atoms measureNameAtom htmlTagAtom\n id Breck\n favoriteHtmlTag 2020\nabstractBooleanMeasureParser\n description A single boolean.\n atoms measureNameAtom booleanAtom\n extends abstractMeasureParser\n example\n hasBillOfRightsParser\n extends abstractBooleanMeasureParser\n id USA\n hasBillOfRights true\n javascript\n get measureValue() {\n const {content} = this\n return content === undefined ? \"\" : content == \"true\"\n }\nabstractDateMeasureParser\n description Year/month/day in ISO 8601, US, European formats.\n atoms measureNameAtom dateAtom\n extends abstractMeasureParser\n string typeForWebForms date\n javascript\n get measureValue() {\n const {content} = this\n if (!content) return \"\"\n const {dayjs} = this.root\n try {\n // First try parsing with dayjs\n const parsed = dayjs(content)\n if (parsed.isValid())\n return parsed.format(\"YYYY-MM-DD\")\n // Try parsing other common formats\n const formats = [\n \"MM/DD/YYYY\",\n \"DD/MM/YYYY\", \n \"YYYY/MM/DD\",\n \"MM-DD-YYYY\",\n \"DD-MM-YYYY\",\n \"YYYY-MM-DD\",\n \"DD.MM.YYYY\",\n \"YYYY.MM.DD\"\n ]\n for (const format of formats) {\n const attempt = dayjs(content, format)\n if (attempt.isValid())\n return attempt.format(\"YYYY-MM-DD\")\n }\n } catch (err) {\n console.error(err)\n return \"\"\n }\n return \"\"\n }\n get valueAsTimestamp() {\n const {measureValue} = this\n return measureValue ? this.root.dayjs(measureValue).unix() : \"\"\n }\nmetaTagsParser\n popularity 0.007693\n cueFromId\n extends abstractScrollParser\n description Print meta tags including title.\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n const {root} = this\n const { title, description, canonicalUrl, gitRepo, scrollVersion, openGraphImage, keywords } = root\n const rssFeedUrl = root.get(\"rssFeedUrl\")\n const favicon = root.get(\"favicon\")\n const faviconTag = favicon ? `<link rel=\"icon\" href=\"${favicon}\">` : \"\"\n const keywordsTag = keywords ? `<meta name=\"keywords\" content=\"${keywords}\">` : \"\"\n const rssTag = rssFeedUrl ? `<link rel=\"alternate\" type=\"application/rss+xml\" title=\"${title}\" href=\"${rssFeedUrl}\">` : \"\"\n const gitTag = gitRepo ? `<link rel=\"source\" type=\"application/git\" title=\"Source Code Repository\" href=\"${gitRepo}\">` : \"\"\n return `<head>\n <meta charset=\"utf-8\">\n <title>${title}</title>\n <script>/* This HTML was generated by 📜 Scroll v${scrollVersion}. https://scroll.pub */</script>\n <style>@media print {.doNotPrint {display: none !important;}}</style>\n <link rel=\"canonical\" href=\"${canonicalUrl}\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n <meta name=\"description\" content=\"${description}\">\n ${keywordsTag}\n <meta name=\"generator\" content=\"Scroll v${scrollVersion}\">\n <meta property=\"og:title\" content=\"${title}\">\n <meta property=\"og:description\" content=\"${description}\">\n <meta property=\"og:image\" content=\"${openGraphImage}\">\n ${faviconTag}\n ${gitTag}\n ${rssTag}\n <meta name=\"twitter:card\" content=\"summary_large_image\">\n </head>\n <body>`\n }\nquoteParser\n popularity 0.001471\n cueFromId\n description A quote.\n catchAllParser quoteLineParser\n extends abstractScrollParser\n javascript\n buildHtml() {\n return `<blockquote class=\"scrollQuote\">${this.subparticlesToString()}</blockquote>`\n }\n buildTxt() {\n return this.subparticlesToString()\n }\nredirectToParser\n popularity 0.000072\n description HTML redirect tag.\n extends abstractScrollParser\n atoms cueAtom urlAtom\n cueFromId\n example\n redirectTo https://scroll.pub/releaseNotes.html\n javascript\n buildHtml() {\n return `<meta http-equiv=\"Refresh\" content=\"0; url='${this.getAtom(1)}'\" />`\n }\nabstractVariableParser\n extends abstractScrollParser\n catchAllAtomType stringAtom\n atoms preBuildCommandAtom\n cueFromId\n javascript\n isTopMatter = true\n buildHtml() {\n return \"\"\n }\nreplaceParser\n description Replace this with that.\n extends abstractVariableParser\n baseParser blobParser\n example\n replace YEAR 2022\nreplaceJsParser\n description Replace this with evaled JS.\n extends replaceParser\n catchAllAtomType javascriptAnyAtom\n example\n replaceJs SUM 1+1\n * 1+1 = SUM\nreplaceNodejsParser\n description Replace with evaled Node.JS.\n extends abstractVariableParser\n catchAllAtomType javascriptAnyAtom\n baseParser blobParser\n example\n replaceNodejs\n module.exports = {SCORE : 1 + 2}\n * The score is SCORE\ntoFooterParser\n extends abstractScrollParser\n description Experimental way to move a section to the footer.\n atoms preBuildCommandAtom\n cueFromId\nrunScriptParser\n popularity 0.000024\n description Run script and dump stdout.\n extends abstractScrollParser\n atoms cueAtom urlAtom\n cue run\n int filenameIndex 1\n javascript\n get dependencies() { return [this.filename]}\n results = \"Not yet run\"\n async execute() {\n if (!this.filename) return\n await this.root.fetch(this.filename)\n // todo: make async\n const { execSync } = require(\"child_process\")\n this.results = execSync(this.command)\n }\n get command() {\n const path = this.root.path\n const {filename }= this\n const fullPath = this.root.makeFullPath(filename)\n const ext = path.extname(filename).slice(1)\n const interpreterMap = {\n php: \"php\",\n py: \"python3\",\n rb: \"ruby\",\n pl: \"perl\",\n sh: \"sh\"\n }\n return [interpreterMap[ext], fullPath].join(\" \")\n }\n buildHtml() {\n return this.buildTxt()\n }\n get filename() {\n return this.getAtom(this.filenameIndex)\n }\n buildTxt() {\n return this.results.toString().trim()\n }\nquickRunScriptParser\n extends runScriptParser\n atoms urlAtom\n pattern ^[^\\s]+\\.(py|pl|sh|rb|php)$\n int filenameIndex 0\nendSnippetParser\n popularity 0.004293\n description Cut for snippet here.\n extends abstractScrollParser\n cueFromId\n javascript\n buildHtml() {\n return \"\"\n }\ntoStampParser\n description Print a directory to stamp.\n extends abstractScrollParser\n catchAllAtomType filePathAtom\n cueFromId\n javascript\n buildTxt() {\n return this.makeStamp(this.content)\n }\n buildHtml() {\n return `<pre>${this.buildTxt()}</pre>`\n }\n makeStamp(dir) {\n const fs = require('fs');\n const path = require('path');\n const { execSync } = require('child_process');\n let stamp = 'stamp\\n';\n const handleFile = (indentation, relativePath, itemPath, ) => {\n stamp += `${indentation}${relativePath}\\n`;\n const content = fs.readFileSync(itemPath, 'utf8');\n stamp += `${indentation} ${content.replace(/\\n/g, `\\n${indentation} `)}\\n`;\n }\n let gitTrackedFiles\n function processDirectory(currentPath, depth) {\n const items = fs.readdirSync(currentPath);\n items.forEach(item => {\n const itemPath = path.join(currentPath, item);\n const relativePath = path.relative(dir, itemPath);\n //if (!gitTrackedFiles.has(item)) return\n const stats = fs.statSync(itemPath);\n const indentation = ' '.repeat(depth);\n if (stats.isDirectory()) {\n stamp += `${indentation}${relativePath}/\\n`;\n processDirectory(itemPath, depth + 1);\n } else if (stats.isFile())\n handleFile(indentation, relativePath, itemPath)\n });\n }\n const stats = fs.statSync(dir);\n if (stats.isDirectory()) {\n // Get list of git-tracked files\n gitTrackedFiles = new Set(execSync('git ls-files', { cwd: dir, encoding: 'utf-8' })\n .split('\\n')\n .filter(Boolean))\n processDirectory(dir, 1)\n }\n else\n handleFile(\" \", dir, dir)\n return stamp.trim();\n }\nstampParser\n description Expand project template to disk.\n extends abstractScrollParser\n inScope stampFolderParser\n catchAllParser stampFileParser\n example\n stamp\n .gitignore\n *.html\n readme.scroll\n # Hello world\n <script src=\"scripts/nested/hello.js\"></script>\n scripts/\n nested/\n hello.js\n console.log(\"Hello world\")\n cueFromId\n atoms preBuildCommandAtom\n javascript\n execute() {\n const dir = this.root.folderPath\n this.forEach(particle => particle.execute(dir))\n }\nscrollStumpParser\n cue stump\n extends abstractScrollParser\n description Compile Stump to HTML.\n catchAllParser stumpContentParser\n javascript\n buildHtml() {\n const {stumpParser} = this\n return new stumpParser(this.subparticlesToString()).compile()\n }\n get stumpParser() {\n return this.isNodeJs() ? require(\"scrollsdk/products/stump.nodejs.js\") : stumpParser\n }\nstumpNoSnippetParser\n popularity 0.010177\n // todo: make noSnippets an aftertext directive?\n extends scrollStumpParser\n description Compile Stump unless snippet.\n cueFromId\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\nplainTextParser\n description Plain text oneliner or block.\n cueFromId\n extends abstractScrollParser\n catchAllParser plainTextLineParser\n catchAllAtomType stringAtom\n javascript\n buildHtml() {\n return this.buildTxt()\n }\n buildTxt() {\n return `${this.content ?? \"\"}${this.subparticlesToString()}`\n }\nplainTextOnlyParser\n popularity 0.000072\n extends plainTextParser\n description Only print for buildTxt.\n javascript\n buildHtml() {\n return \"\"\n }\nscrollThemeParser\n popularity 0.007524\n boolean isPopular true\n cue theme\n example\n theme gazette\n extends abstractScrollParser\n catchAllAtomType scrollThemeAtom\n description A collection of simple themes.\n string copyFromExternal .gazette.css\n // Note this will be replaced at runtime\n javascript\n get copyFromExternal() {\n return this.files.join(\" \")\n }\n get files() {\n return this.atoms.slice(1).map(name => `.${name}.css`).concat([\".scroll.css\"])\n }\n buildHtml() {\n return this.files.map(name => `<link rel=\"stylesheet\" type=\"text/css\" href=\"${name}\">`).join(\"\\n\")\n }\nabstractAftertextAttributeParser\n atoms cueAtom\n boolean isAttribute true\n javascript\n get htmlAttributes() {\n return `${this.cue}=\"${this.content}\"`\n }\n buildHtml() {\n return \"\"\n }\naftertextIdParser\n popularity 0.000145\n cue id\n description Provide an ID to be output in the generated HTML tag.\n extends abstractAftertextAttributeParser\n atoms cueAtom htmlIdAtom\n single\naftertextStyleParser\n popularity 0.000217\n cue style\n description Set HTML style attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType cssAnyAtom\n javascript\n htmlAttributes = \"\" // special case this one\n get css() { return `${this.property}:${this.content};` }\naftertextFontParser\n popularity 0.000217\n cue font\n description Set font.\n extends aftertextStyleParser\n atoms cueAtom fontFamilyAtom\n catchAllAtomType cssAnyAtom\n string property font-family\n javascript\n get css() {\n if (this.content === \"Slim\") return \"font-family:Helvetica Neue; font-weight:100;\"\n return super.css\n }\naftertextColorParser\n popularity 0.000217\n cue color\n description Set font color.\n extends aftertextStyleParser\n catchAllAtomType cssAnyAtom\n string property color\n example\n color blue\naftertextHrefParser\n popularity 0.000217\n cue href\n description Set HTML href attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom urlAtom\naftertextSrcParser\n extends aftertextHrefParser\n cue src\n description Set HTML src attribute.\naftertextOnclickParser\n popularity 0.000217\n cue onclick\n description Set HTML onclick attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType javascriptAnyAtom\naftertextHiddenParser\n cue hidden\n atoms cueAtom\n description Do not compile this particle to HTML.\n extends abstractAftertextAttributeParser\n single\naftertextValueParser\n popularity 0.000217\n cue value\n description Set HTML value attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextForParser\n popularity 0.000217\n cue for\n description Set HTML for attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom htmlAnyAtom\naftertextPlaceholderParser\n popularity 0.000217\n cue placeholder\n description Set HTML placeholder attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextRowsParser\n popularity 0.000217\n cue rows\n description Set HTML rows attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom integerAtom\naftertextTypeParser\n popularity 0.000217\n cue type\n description Set HTML type attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom htmlTypeAtom\naftertextAltParser\n popularity 0.000217\n cue alt\n description Set HTML alt attribute for images.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextTitleParser\n popularity 0.000217\n cue title\n description Set HTML title attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextNameParser\n popularity 0.000217\n cue name\n description Set HTML name attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextOnsubmitParser\n popularity 0.000217\n cue onsubmit\n description Set HTML onsubmit attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType javascriptAnyAtom\naftertextClassParser\n popularity 0.000217\n cue class\n description Set HTML class attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType classNameAtom\naftertextMaxlengthParser\n popularity 0.000217\n cue maxlength\n description Set HTML maxlength attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom integerAtom\naftertextPatternParser\n popularity 0.000217\n cue pattern\n description Set HTML pattern attribute for input validation.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextRequiredParser\n popularity 0.000217\n cue required\n description Set HTML required attribute.\n extends abstractAftertextAttributeParser\n single\naftertextDisabledParser\n popularity 0.000217\n cue disabled\n description Set HTML disabled attribute.\n extends abstractAftertextAttributeParser\n single\naftertextReadonlyParser\n popularity 0.000217\n cue readonly\n description Set HTML readonly attribute.\n extends abstractAftertextAttributeParser\n single\naftertextAriaLabelParser\n popularity 0.000217\n cue aria-label\n description Set ARIA label for accessibility.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextTargetParser\n popularity 0.000217\n cue target\n description Set HTML target attribute for links.\n extends abstractAftertextAttributeParser\n atoms cueAtom htmlAnyAtom\naftertextTagParser\n atoms cueAtom htmlTagAtom\n description Override the HTML tag that the compiled particle will use.\n cue tag\n javascript\n buildHtml() {\n return \"\"\n }\nabstractAftertextDirectiveParser\n atoms cueAtom\n catchAllAtomType stringAtom\n javascript\n isMarkup = true\n buildHtml() {\n return \"\"\n }\n getErrors() {\n const errors = super.getErrors()\n if (!this.isMarkup || this.matchWholeLine) return errors\n const inserts = this.getInserts(this.parent.originalTextPostLinkify)\n // todo: make AbstractParticleError class exported by sdk to allow Parsers to define their own error types.\n // todo: also need to be able to map lines back to their line in source (pre-imports)\n if (!inserts.length)\n errors.push(this.makeError(`No match found for \"${this.getLine()}\".`))\n return errors\n }\n get pattern() {\n return this.getAtomsFrom(1).join(\" \")\n }\n get shouldMatchAll() {\n return this.has(\"matchAll\")\n }\n getMatches(text) {\n const { pattern } = this\n const escapedPattern = pattern.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\")\n return [...text.matchAll(new RegExp(escapedPattern, \"g\"))].map(match => {\n const { index } = match\n const endIndex = index + pattern.length\n return [\n { index, string: `<${this.openTag}${this.allAttributes}>`, endIndex },\n { index: endIndex, endIndex, string: `</${this.closeTag}>` }\n ]\n })\n }\n getInserts(text) {\n const matches = this.getMatches(text)\n if (!matches.length) return false\n if (this.shouldMatchAll) return matches.flat()\n const match = this.getParticle(\"match\")\n if (match)\n return match.indexes\n .map(index => matches[index])\n .filter(i => i)\n .flat()\n return matches[0]\n }\n get allAttributes() {\n const attr = this.attributes.join(\" \")\n return attr ? \" \" + attr : \"\"\n }\n get attributes() {\n return []\n }\n get openTag() {\n return this.tag\n }\n get closeTag() {\n return this.tag\n }\nabstractMarkupParser\n extends abstractAftertextDirectiveParser\n inScope abstractMarkupParameterParser\n javascript\n get matchWholeLine() {\n return this.getAtomsFrom(this.patternStartsAtAtom).length === 0\n }\n get pattern() {\n return this.matchWholeLine ? this.parent.originalText : this.getAtomsFrom(this.patternStartsAtAtom).join(\" \")\n }\n patternStartsAtAtom = 1\nboldParser\n popularity 0.000096\n cueFromId\n description Bold matching text.\n extends abstractMarkupParser\n javascript\n tag = \"b\"\nitalicsParser\n popularity 0.000241\n cueFromId\n description Italicize matching text.\n extends abstractMarkupParser\n javascript\n tag = \"i\"\nunderlineParser\n popularity 0.000024\n description Underline matching text.\n cueFromId\n extends abstractMarkupParser\n javascript\n tag = \"u\"\nafterTextCenterParser\n popularity 0.000193\n description Center paragraph.\n cue center\n extends abstractMarkupParser\n javascript\n tag = \"center\"\naftertextCodeParser\n popularity 0.000145\n description Wrap matching text in code span.\n cue code\n extends abstractMarkupParser\n javascript\n tag = \"code\"\naftertextStrikeParser\n popularity 0.000048\n description Wrap matching text in s span.\n cue strike\n extends abstractMarkupParser\n javascript\n tag = \"s\"\naddClassMarkupParser\n popularity 0.000772\n description Add a custom class to parent element. Provide query to add span matching text.\n extends abstractMarkupParser\n atoms cueAtom classNameAtom\n cue addClass\n javascript\n tag = \"span\"\n get applyToParentElement() {\n return this.atoms.length === 2\n }\n getInserts(text) {\n // If no select text is added, set the class on the parent element.\n if (this.applyToParentElement) return []\n return super.getInserts(text)\n }\n get className() {\n return this.getAtom(1)\n }\n get attributes() {\n return [`class=\"${this.className}\"`]\n }\n get matchWholeLine() {\n return this.applyToParentElement\n }\n get pattern() {\n return this.matchWholeLine ? this.parent.content : this.getAtomsFrom(2).join(\" \")\n }\nhoverNoteParser\n popularity 0.000265\n description Add a caveat viewable on hover on matching text. When you want to be sure you've thoroughly addressed obvious concerns but ones that don't warrant to distract from the main argument of the text.\n cueFromId\n extends addClassMarkupParser\n catchAllParser lineOfTextParser\n atoms cueAtom\n javascript\n get pattern() {\n return this.getAtomsFrom(1).join(\" \")\n }\n get attributes() {\n return [`class=\"scrollHoverNote\"`, `title=\"${this.hoverNoteText}\"`]\n }\n get hoverNoteText() {\n return this.subparticlesToString().replace(/\\n/g, \" \")\n }\nscrollLinkParser\n popularity 0.008706\n extends abstractMarkupParser\n description Put the matching text in an <a> tag.\n atoms cueAtom urlAtom\n inScope linkTitleParser linkTargetParser abstractCommentParser\n programParser\n description Anything here will be URI encoded and then appended to the link.\n cueFromId\n atoms cueAtom\n catchAllParser programLinkParser\n javascript\n get encoded() {\n return encodeURIComponent(this.subparticlesToString())\n }\n cue link\n javascript\n tag = \"a\"\n buildTxt() {\n return this.root.ensureAbsoluteLink(this.link) + \" \" + this.pattern\n }\n get link() {\n const {baseLink} = this\n if (this.has(\"program\"))\n return baseLink + this.getParticle(\"program\").encoded\n return baseLink\n }\n get baseLink() {\n const link = this.getAtom(1)\n const isAbsoluteLink = link.includes(\"://\")\n if (isAbsoluteLink) return link\n const relativePath = this.parent.buildSettings?.relativePath || \"\"\n return relativePath + link\n }\n get linkAttribute() {\n return \"href\"\n }\n get attributes() {\n const attrs = [`${this.linkAttribute}=\"${this.link}\"`]\n const options = [\"title\", \"target\"]\n options.forEach(option => {\n const particle = this.getParticle(option)\n if (particle) attrs.push(`${option}=\"${particle.content}\"`)\n })\n return attrs\n }\n patternStartsAtAtom = 2\nscrollClickParser\n extends scrollLinkParser\n description An a tag with an onclick.\n cue click\n javascript\n get linkAttribute() {\n return \"onclick\"\n }\nemailLinkParser\n popularity 0.000048\n description A mailto link\n cue email\n extends scrollLinkParser\n javascript\n get attributes() {\n return [`href=\"mailto:${this.link}\"`]\n }\nquickLinkParser\n popularity 0.029228\n pattern ^https?\\:\n extends scrollLinkParser\n atoms urlAtom\n javascript\n get link() {\n return this.cue\n }\n patternStartsAtAtom = 1\nquickRelativeLinkParser\n popularity 0.029228\n description Relative links.\n // note: only works if relative link ends in .html\n pattern ^[^\\s]+\\.(html|htm)\n extends scrollLinkParser\n atoms urlAtom\n javascript\n get link() {\n return this.cue\n }\n patternStartsAtAtom = 1\ndatelineParser\n popularity 0.006005\n cueFromId\n description Gives your paragraph a dateline like \"December 15, 2021 — The...\"\n extends abstractAftertextDirectiveParser\n javascript\n getInserts() {\n const {day} = this\n if (!day) return false\n return [{ index: 0, string: `<span class=\"scrollDateline\">${day} — </span>` }]\n }\n matchWholeLine = true\n get day() {\n let day = this.content || this.root.date\n if (!day) return \"\"\n return this.root.dayjs(day).format(`MMMM D, YYYY`)\n }\ndayjsParser\n description Advanced directive that evals some Javascript code in an environment including \"dayjs\".\n cueFromId\n extends abstractAftertextDirectiveParser\n javascript\n getInserts() {\n const dayjs = this.root.dayjs\n const days = eval(this.content)\n const index = this.parent.originalTextPostLinkify.indexOf(\"days\")\n return [{ index, string: `${days} ` }]\n }\ninlineMarkupsOnParser\n popularity 0.000024\n cueFromId\n description Enable these inline markups only.\n example\n Hello *world*!\n inlineMarkupsOn bold\n extends abstractAftertextDirectiveParser\n catchAllAtomType inlineMarkupNameAtom\n javascript\n get shouldMatchAll() {\n return true\n }\n get markups() {\n const {root} = this\n let markups = [{delimiter: \"`\", tag: \"code\", exclusive: true, name: \"code\"},{delimiter: \"*\", tag: \"strong\", name: \"bold\"}, {delimiter: \"_\", tag: \"em\", name: \"italics\"}]\n // only add katex markup if the root doc has katex.\n if (root.has(\"katex\"))\n markups.unshift({delimiter: \"$\", tag: \"span\", attributes: ' class=\"scrollKatex\"', exclusive: true, name: \"katex\"})\n if (this.content)\n return markups.filter(markup => this.content.includes(markup.name))\n if (root.has(\"inlineMarkups\")) {\n root.getParticle(\"inlineMarkups\").forEach(markup => {\n const delimiter = markup.getAtom(0)\n const tag = markup.getAtom(1)\n // todo: add support for providing custom functions for inline markups?\n // for example, !2+2! could run eval, or :about: could search a link map.\n const attributes = markup.getAtomsFrom(2).join(\" \")\n markups = markups.filter(mu => mu.delimiter !== delimiter) // Remove any overridden markups\n if (tag)\n markups.push({delimiter, tag, attributes})\n })\n }\n return markups\n }\n matchWholeLine = true\n getMatches(text) {\n const exclusives = []\n return this.markups.map(markup => this.applyMarkup(text, markup, exclusives)).filter(i => i).flat()\n }\n applyMarkup(text, markup, exclusives = []) {\n const {delimiter, tag, attributes} = markup\n const escapedDelimiter = delimiter.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\")\n const pattern = new RegExp(`${escapedDelimiter}[^${escapedDelimiter}]+${escapedDelimiter}`, \"g\")\n const delimiterLength = delimiter.length\n return [...text.matchAll(pattern)].map(match => {\n const { index } = match\n const endIndex = index + match[0].length\n // I'm too lazy to clean up sdk to write a proper inline markup parser so doing this for now.\n // The exclusive idea is to not try and apply bold or italic styles inside a TeX or code inline style.\n // Note that the way this is currently implemented any TeX in an inline code will get rendered, but code\n // inline of TeX will not. Seems like an okay tradeoff until a proper refactor and cleanup can be done.\n if (exclusives.some(exclusive => index >= exclusive[0] && index <= exclusive[1]))\n return undefined\n if (markup.exclusive)\n exclusives.push([index, endIndex])\n return [\n { index, string: `<${tag + (attributes ? \" \" + attributes : \"\")}>`, endIndex, consumeStartCharacters: delimiterLength },\n { index: endIndex, endIndex, string: `</${tag}>`, consumeEndCharacters: delimiterLength }\n ]\n }).filter(i => i)\n }\ninlineMarkupParser\n popularity 0.000169\n cueFromId\n atoms cueAtom delimiterAtom tagOrUrlAtom\n catchAllAtomType htmlAttributesAtom\n extends inlineMarkupsOnParser\n description Custom inline markup. for\n example\n @This@ will be in italics.\n inlineMarkup @ em\n javascript\n getMatches(text) {\n try {\n const delimiter = this.getAtom(1)\n const tag = this.getAtom(2)\n const attributes = this.getAtomsFrom(3).join(\" \")\n return this.applyMarkup(text, {delimiter, tag, attributes})\n } catch (err) {\n console.error(err)\n return []\n }\n // Note: doubling up doesn't work because of the consumption characters.\n }\nlinkifyParser\n description Use this to disable linkify on the text.\n extends abstractAftertextDirectiveParser\n cueFromId\n atoms cueAtom booleanAtom\nabstractMarkupParameterParser\n atoms cueAtom\n cueFromId\nmatchAllParser\n popularity 0.000024\n description Use this to match all occurrences of the text.\n extends abstractMarkupParameterParser\nmatchParser\n popularity 0.000048\n catchAllAtomType integerAtom\n description Use this to specify which index(es) to match.\n javascript\n get indexes() {\n return this.getAtomsFrom(1).map(num => parseInt(num))\n }\n example\n aftertext\n hello ello ello\n bold ello\n match 0 2\n extends abstractMarkupParameterParser\nabstractHtmlAttributeParser\n javascript\n buildHtml() {\n return \"\"\n }\nlinkTargetParser\n popularity 0.000024\n extends abstractHtmlAttributeParser\n description If you want to set the target of the link. To \"_blank\", for example.\n cue target\n atoms cueAtom codeAtom\nblankLineParser\n popularity 0.308149\n description Print nothing. Break section.\n atoms blankAtom\n boolean isPopular true\n javascript\n buildHtml() {\n return this.parent.clearSectionStack()\n }\n pattern ^$\n tags doNotSynthesize\nscrollFileAddressParser\n catchAllAtomType filePathAtom\n catchAllParser scrollFileAddressParser\nchatLineParser\n popularity 0.009887\n catchAllAtomType stringAtom\n catchAllParser chatLineParser\nlineOfCodeParser\n popularity 0.018665\n catchAllAtomType codeAtom\n catchAllParser lineOfCodeParser\ncommentLineParser\n catchAllAtomType commentAtom\ncssLineParser\n popularity 0.002870\n catchAllAtomType cssAnyAtom\n catchAllParser cssLineParser\nabstractTableTransformParser\n atoms cueAtom\n inScope abstractTableVisualizationParser abstractTableTransformParser h1Parser h2Parser scrollQuestionParser htmlInlineParser scrollBrParser slashCommentParser\n javascript\n get coreTable() {\n return this.parent.coreTable\n }\n get columnNames() {\n return this.parent.columnNames\n }\n connectColumnNames(userColumnNames, availableColumnNames = this.parent.columnNames) {\n const result = {}\n const normalize = str => str.toLowerCase().trim()\n userColumnNames.forEach(userColumn => {\n // Strategy 1: Exact match\n const exactMatch = availableColumnNames.find(col => col === userColumn)\n if (exactMatch) {\n result[userColumn] = exactMatch\n return\n }\n // Strategy 2: Case-insensitive match\n const normalizedUserColumn = normalize(userColumn)\n const caseInsensitiveMatch = availableColumnNames.find(col => normalize(col) === normalizedUserColumn)\n if (caseInsensitiveMatch) {\n result[userColumn] = caseInsensitiveMatch\n return\n }\n // Strategy 3: Levenshtein distance match\n const THRESHOLD = 2 // Consider matches with distance <= 2 as \"very close\"\n let bestMatch = null\n let bestDistance = Infinity\n availableColumnNames.forEach(col => {\n const distance = this.root.levenshteinDistance(userColumn, col)\n if (distance < bestDistance) {\n bestDistance = distance\n bestMatch = col\n }\n })\n // Only use Levenshtein match if it's very close\n if (bestDistance <= THRESHOLD) {\n result[userColumn] = bestMatch\n return\n }\n // Strategy 4: Fallback - use original unmatched name\n result[userColumn] = userColumn\n })\n return result\n }\n connectColumnName(name) {\n return this.connectColumnNames([name])[name]\n }\n getErrors() {\n const errors = super.getErrors()\n if (errors.length && this.previous.cue !== \"assertIgnoreBelowErrors\")\n return errors\n return []\n }\n getRunTimeEnumOptions(atom) {\n if (atom.atomTypeId === \"columnNameAtom\")\n return this.parent.columnNames\n return super.getRunTimeEnumOptions(atom)\n }\n getRunTimeEnumOptionsForValidation(atom) {\n // Note: this will fail if the CSV file hasnt been built yet.\n if (atom.atomTypeId === \"columnNameAtom\")\n return this.parent.columnNames.concat(this.parent.columnNames.map(c => \"-\" + c)) // Add reverse names\n return super.getRunTimeEnumOptions(atom)\n }\nabstractDateSplitTransformParser\n extends abstractTableTransformParser\n atoms cueAtom\n catchAllAtomType columnNameAtom\n javascript\n get coreTable() {\n const columnName = this.getAtom(1) || this.detectDateColumn()\n if (!columnName) return this.parent.coreTable\n return this.parent.coreTable.map(row => {\n const newRow = {...row}\n try {\n const date = this.root.dayjs(row[columnName])\n if (date.isValid())\n newRow[this.newColumnName] = this.transformDate(date)\n } catch (err) {}\n return newRow\n })\n }\n detectDateColumn() {\n const columns = this.parent.columnNames\n const dateColumns = ['date', 'created', 'published', 'timestamp']\n for (const col of dateColumns) {\n if (columns.includes(col)) return col\n }\n for (const col of columns) {\n const sample = this.parent.coreTable[0][col]\n if (sample && this.root.dayjs(sample).isValid())\n return col\n }\n return null\n }\n get columnNames() {\n return [...this.parent.columnNames, this.newColumnName]\n }\n transformDate(date) {\n const formatted = date.format(this.dateFormat)\n const isInt = !this.cue.includes(\"Name\")\n return isInt ? parseInt(formatted) : formatted\n }\nscrollSplitYearParser\n extends abstractDateSplitTransformParser\n description Extract year into new column.\n cue splitYear\n string newColumnName year\n string dateFormat YYYY\nscrollSplitDayNameParser\n extends abstractDateSplitTransformParser\n description Extract day name into new column.\n cue splitDayName\n string newColumnName dayName\n string dateFormat dddd\nscrollSplitMonthNameParser\n extends abstractDateSplitTransformParser\n description Extract month name into new column.\n cue splitMonthName\n string newColumnName monthName\n string dateFormat MMMM\nscrollSplitMonthParser\n extends abstractDateSplitTransformParser\n description Extract month number (1-12) into new column.\n cue splitMonth\n string newColumnName month\n string dateFormat M\nscrollSplitDayOfMonthParser\n extends abstractDateSplitTransformParser\n description Extract day of month (1-31) into new column.\n cue splitDayOfMonth\n string newColumnName dayOfMonth\n string dateFormat D\nscrollSplitDayOfWeekParser\n extends abstractDateSplitTransformParser\n description Extract day of week (0-6) into new column.\n cue splitDay\n string newColumnName day\n string dateFormat d\nscrollParseDateParser\n extends abstractTableTransformParser\n description Parse dates in a column into standard format.\n cue parseDate\n atoms cueAtom columnNameAtom\n example\n sampleData stocks.csv\n parseDate date\n linechart\n x date\n y price\n javascript\n get coreTable() {\n const columnName = this.connectColumnName(this.getAtom(1))\n const formatOut = this.get(\"format\") || \"YYYY-MM-DD\"\n const {dayjs} = this.root\n return this.parent.coreTable.map(row => {\n const newRow = {...row}\n try {\n const value = row[columnName]\n if (value) {\n const date = dayjs(value)\n if (date.isValid())\n newRow[columnName] = date.format(formatOut)\n }\n } catch (err) {\n console.error(`Error parsing date in column ${columnName}:`, err)\n }\n return newRow\n })\n }\n formatParser\n description Specify output date format\n atoms cueAtom stringAtom\n cueFromId\n single\nscrollGroupByParser\n catchAllAtomType columnNameAtom\n extends abstractTableTransformParser\n reduceParser\n description Specify how to aggregate a column when grouping data\n atoms cueAtom columnNameAtom reductionTypeAtom newColumnNameAtom\n cue reduce\n example\n data.csv\n groupBy year\n reduce score sum totalScore\n reduce name concat names\n printTable\n javascript\n get reduction() {\n return {\n source: this.getAtom(1),\n reduction: this.getAtom(2),\n name: this.getAtom(3) || this.getAtomsFrom(1).join(\"_\")\n }\n }\n description Combine rows with matching values into groups.\n example\n tables posts.csv\n groupBy year\n printTable\n cue groupBy\n javascript\n get coreTable() {\n if (this._coreTable) return this._coreTable\n const groupByColNames = this.getAtomsFrom(1)\n const {coreTable} = this.parent\n if (!groupByColNames.length) return coreTable\n const newCols = this.findParticles(\"reduce\").map(particle => particle.reduction)\n // Pivot is shorthand for group and reduce?\n const makePivotTable = (rows, groupByColumnNames, inputColumnNames, newCols) => {\n const colMap = {}\n inputColumnNames.forEach((col) => (colMap[col] = true))\n const groupByCols = groupByColumnNames.filter((col) => colMap[col])\n return new PivotTable(rows, inputColumnNames.map(c => {return {name: c}}), newCols).getNewRows(groupByCols)\n }\n class PivotTable {\n constructor(rows, inputColumns, outputColumns) {\n this._columns = {}\n this._rows = rows\n inputColumns.forEach((col) => (this._columns[col.name] = col))\n outputColumns.forEach((col) => (this._columns[col.name] = col))\n }\n _getGroups(allRows, groupByColNames) {\n const rowsInGroups = new Map()\n allRows.forEach((row) => {\n const groupKey = groupByColNames.map((col) => row[col]?.toString().replace(/ /g, \"\") || \"\").join(\" \")\n if (!rowsInGroups.has(groupKey)) rowsInGroups.set(groupKey, [])\n rowsInGroups.get(groupKey).push(row)\n })\n return rowsInGroups\n }\n getNewRows(groupByCols) {\n // make new particles\n const rowsInGroups = this._getGroups(this._rows, groupByCols)\n // Any column in the group should be reused by the children\n const columns = [\n {\n name: \"count\",\n type: \"number\",\n min: 0,\n },\n ]\n groupByCols.forEach((colName) => columns.push(this._columns[colName]))\n const colsToReduce = Object.values(this._columns).filter((col) => !!col.reduction)\n colsToReduce.forEach((col) => columns.push(col))\n // for each group\n const rows = []\n const totalGroups = rowsInGroups.size\n for (let [groupId, group] of rowsInGroups) {\n const firstRow = group[0]\n const newRow = {}\n groupByCols.forEach((col) =>\n newRow[col] = firstRow ? firstRow[col] : 0\n )\n newRow.count = group.length\n // todo: add more reductions? count, stddev, median, variance.\n colsToReduce.forEach((col) => {\n const sourceColName = col.source\n const reduction = col.reduction\n const newColName = col.name\n if (reduction === \"concat\") {\n newRow[newColName] = group.map((row) => row[sourceColName]).join(\" \")\n return \n }\n if (reduction === \"first\") {\n newRow[newColName] = group.find((row) => row[sourceColName] !== \"\")?.[sourceColName]\n return \n }\n const values = group.map((row) => row[sourceColName]).filter((val) => typeof val === \"number\" && !isNaN(val))\n let reducedValue = firstRow[sourceColName]\n if (reduction === \"sum\") reducedValue = values.reduce((prev, current) => prev + current, 0)\n if (reduction === \"max\") reducedValue = Math.max(...values)\n if (reduction === \"min\") reducedValue = Math.min(...values)\n if (reduction === \"mean\") reducedValue = values.reduce((prev, current) => prev + current, 0) / values.length\n newRow[newColName] = reducedValue\n })\n rows.push(newRow)\n }\n // todo: add tests. figure out this api better.\n Object.values(columns).forEach((col) => {\n // For pivot columns, remove the source and reduction info for now. Treat things as immutable.\n delete col.source\n delete col.reduction\n })\n return {\n rows,\n columns,\n }\n }\n }\n const pivotTable = makePivotTable(coreTable, groupByColNames, this.parent.columnNames, newCols)\n this._coreTable = pivotTable.rows\n this._columnNames = pivotTable.columns.map(col => col.name)\n return pivotTable.rows\n }\n get columnNames() {\n const {coreTable} = this\n return this._columnNames || this.parent.columnNames\n }\nscrollWhereParser\n extends abstractTableTransformParser\n description Filter rows by condition.\n cue where\n atoms cueAtom columnNameAtom comparisonAtom\n catchAllAtomType constantAtom\n example\n table iris.csv\n where Species = setosa\n javascript\n get coreTable() {\n // todo: use atoms here.\n const columnName = this.connectColumnName(this.getAtom(1))\n const operator = this.getAtom(2)\n let untypedComparisonValue = this.getAtom(3)\n const typedComparisonValue = isNaN(parseFloat(untypedComparisonValue)) ? untypedComparisonValue : parseFloat(untypedComparisonValue)\n const coreTable = this.parent.coreTable\n if (!columnName || !operator || (untypedComparisonValue === undefined && !operator.includes(\"mpty\"))) return coreTable\n const filterFn = row => {\n const atom = row[columnName]\n const typedAtom = atom === null ? undefined : atom // convert nulls to undefined\n if (operator === \"=\") return typedComparisonValue === typedAtom\n else if (operator === \"!=\") return typedComparisonValue !== typedAtom\n else if (operator === \"includes\") return typedAtom !== undefined && typedAtom.includes(typedComparisonValue)\n else if (operator === \"startsWith\") return typedAtom !== undefined && typedAtom.toString().startsWith(typedComparisonValue)\n else if (operator === \"endsWith\") return typedAtom !== undefined && typedAtom.toString().endsWith(typedComparisonValue)\n else if (operator === \"doesNotInclude\") return typedAtom === undefined || !typedAtom.includes(typedComparisonValue)\n else if (operator === \">\") return typedAtom > typedComparisonValue\n else if (operator === \"<\") return typedAtom < typedComparisonValue\n else if (operator === \">=\") return typedAtom >= typedComparisonValue\n else if (operator === \"<=\") return typedAtom <= typedComparisonValue\n else if (operator === \"empty\") return typedAtom === \"\" || typedAtom === undefined\n else if (operator === \"notEmpty\") return typedAtom !== \"\" && typedAtom !== undefined\n }\n return coreTable.filter(filterFn)\n }\nscrollSelectParser\n catchAllAtomType columnNameAtom\n extends abstractTableTransformParser\n description Drop all columns except these.\n example\n tables\n data\n name,year,count\n index,2022,2\n about,2023,4\n select name year\n printTable\n cue select\n javascript\n get coreTable() {\n const {coreTable} = this.parent\n const {columnNames} = this\n if (!columnNames.length) return coreTable\n return coreTable.map(row => Object.fromEntries(columnNames.map(colName => [colName, row[colName]])))\n }\n get columnNames() {\n if (!this._columnNames) {\n const names = this.getAtomsFrom(1)\n this._columnNamesMap = this.connectColumnNames(names)\n this._columnNames = names.map(name => this._columnNamesMap[name])\n }\n return this._columnNames\n }\nscrollReverseParser\n extends abstractTableTransformParser\n description Reverse rows.\n cue reverse\n javascript\n get coreTable() {\n return this.parent.coreTable.slice().reverse()\n }\nscrollComposeParser\n extends abstractTableTransformParser\n description Add column using format string.\n catchAllAtomType codeAtom\n cue compose\n atoms cueAtom newColumnNameAtom\n example\n table\n compose sentence My name is {name}\n printTable\n javascript\n get coreTable() {\n const {newColumnName} = this\n const formatString = this.getAtomsFrom(2).join(\" \")\n return this.parent.coreTable.map((row, index) => {\n const newRow = Object.assign({}, row)\n newRow[newColumnName] = this.evaluate(new Particle(row).evalTemplateString(formatString), index)\n return newRow\n })\n }\n evaluate(str) {\n return str\n }\n get newColumnName() {\n return this.atoms[1]\n }\n get columnNames() {\n return this.parent.columnNames.concat(this.newColumnName)\n }\nscrollComputeParser\n extends scrollComposeParser\n description Add column by evaling format string.\n cue compute\n javascript\n evaluate(str) {\n return parseFloat(eval(str))\n }\nscrollEvalParser\n extends scrollComputeParser\n description Add column by evaling format string.\n cue eval\n javascript\n evaluate(str) {\n return eval(str)\n }\nscrollRankParser\n extends scrollComposeParser\n description Add rank column.\n atoms cueAtom\n string newColumnName rank\n cue rank\n javascript\n evaluate(str, index) { return index + 1 }\nscrollLinksParser\n extends abstractTableTransformParser\n description Add column with links.\n cue links\n catchAllAtomType columnNameAtom\n javascript\n get coreTable() {\n const {newColumnName, linkColumns} = this\n return this.parent.coreTable.map(row => {\n const newRow = Object.assign({}, row)\n let newValue = []\n linkColumns.forEach(name => {\n const value = newRow[name]\n delete newRow[name]\n if (value) newValue.push(`<a href=\"${value.includes(\"@\") ? \"mailto:\" : \"\"}${value}\">${name}</a>`)\n })\n newRow[newColumnName] = newValue.join(\" \")\n return newRow\n })\n }\n get newColumnName() {\n return \"links\"\n }\n get linkColumns() {\n return this.getAtomsFrom(1)\n }\n get columnNames() {\n const {linkColumns} = this\n return this.parent.columnNames.filter(name => !linkColumns.includes(name)).concat(this.newColumnName)\n }\nscrollLimitParser\n extends abstractTableTransformParser\n description Select a subset.\n cue limit\n atoms cueAtom integerAtom integerAtom\n javascript\n get coreTable() {\n let start = this.getAtom(1)\n let end = this.getAtom(2)\n if (end === undefined) {\n end = start\n start = 0\n }\n return this.parent.coreTable.slice(parseInt(start), parseInt(end))\n }\nscrollShuffleParser\n extends abstractTableTransformParser\n description Randomly reorder rows.\n cue shuffle\n example\n table data.csv\n shuffle\n printTable\n javascript\n get coreTable() {\n // Create a copy of the table to avoid modifying original\n const rows = this.parent.coreTable.slice()\n // Fisher-Yates shuffle algorithm\n for (let i = rows.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * (i + 1))\n ;[rows[i], rows[j]] = [rows[j], rows[i]]\n }\n return rows\n }\nscrollTransposeParser\n extends abstractTableTransformParser\n description Tranpose table.\n cue transpose\n javascript\n get coreTable() {\n // todo: we need to switch to column based coreTable, instead of row based\n const transpose = arr => Object.keys(arr[0]).map(key => [key, ...arr.map(row => row[key])]);\n return transpose(this.parent.coreTable)\n }\nscrollImputeParser\n extends abstractTableTransformParser\n description Impute missing values of a columm.\n atoms cueAtom columnNameAtom\n cue impute\n javascript\n get coreTable() {\n const {columnName} = this\n const sorted = this.root.lodash.orderBy(this.parent.coreTable.slice(), columnName)\n // ascending\n const imputed = []\n let lastInserted = sorted[0][columnName]\n sorted.forEach(row => {\n const measuredTime = row[columnName]\n while (measuredTime > lastInserted + 1) {\n lastInserted++\n // synthesize rows\n const imputedRow = {}\n imputedRow[columnName] = lastInserted\n imputedRow.count = 0\n imputed.push(imputedRow)\n }\n lastInserted = measuredTime\n imputed.push(row)\n })\n return imputed\n }\n get columnName() {\n return this.connectColumnName(this.getAtom(1))\n }\nscrollOrderByParser\n extends abstractTableTransformParser\n description Sort rows by column(s).\n catchAllAtomType columnNameAtom\n cue orderBy\n javascript\n get coreTable() {\n const makeLodashOrderByParams = str => {\n const part1 = str.split(\" \")\n const part2 = part1.map(col => (col.startsWith(\"-\") ? \"desc\" : \"asc\"))\n return [part1.map(col => this.connectColumnName(col.replace(/^\\-/, \"\"))), part2]\n }\n const orderBy = makeLodashOrderByParams(this.content)\n return this.root.lodash.orderBy(this.parent.coreTable.slice(), orderBy[0], orderBy[1])\n }\nassertRowCountParser\n extends abstractTableTransformParser\n description Test row count is expected value.\n atoms cueAtom integerAtom\n cueFromId\n javascript\n getErrors() {\n const errors = super.getErrors()\n const actualRows = this.coreTable.length\n const expectedRows = parseInt(this.content)\n if (actualRows !== expectedRows)\n return errors.concat(this.makeError(`Expected '${expectedRows}' rows but got '${actualRows}'.`))\n return errors\n }\nscrollRenameParser\n // todo: add support in Parsers for tuple catch alls\n catchAllAtomType columnNameAtom newColumnNameAtom\n catchAllAtomType newColumnNameAtom\n extends abstractTableTransformParser\n description Rename columns.\n example\n tables\n data\n name,year,count\n index,2022,2\n rename name Name year Year\n printTable\n cue rename\n javascript\n get coreTable() {\n const {coreTable} = this.parent\n const {renameMap} = this\n if (!Object.keys(renameMap).length) return coreTable\n return coreTable.map(row => {\n const newRow = {}\n Object.keys(row).forEach(key => {\n const name = renameMap[key] || key\n newRow[name] = row[key]\n })\n return newRow\n })\n }\n get renameMap() {\n const map = {}\n const pairs = this.getAtomsFrom(1)\n let oldName\n while (oldName = pairs.shift()) {\n map[oldName] = pairs.shift()\n }\n return map\n }\n _renamed\n get columnNames() {\n if (this._renamed)\n return this._renamed\n const {renameMap} = this\n this._renamed = this.parent.columnNames.map(name => renameMap[name] || name )\n return this._renamed\n }\nscrollSummarizeParser\n extends abstractTableTransformParser\n description Generate summary statistics for each column.\n cue summarize\n example\n table data.csv\n summarize\n printTable\n javascript\n get coreTable() {\n const {lodash} = this.root\n const sourceData = this.parent.coreTable\n if (!sourceData.length) return []\n return this.parent.columnNames.map(colName => {\n const values = sourceData.map(row => row[colName]).filter(val => val !== undefined && val !== null)\n const numericValues = values.filter(val => typeof val === \"number\" && !isNaN(val))\n const sorted = [...numericValues].sort((a, b) => a - b)\n // Calculate mode\n const frequency = {}\n values.forEach(val => {\n frequency[val] = (frequency[val] || 0) + 1\n })\n const mode = Object.entries(frequency)\n .sort((a, b) => b[1] - a[1])\n .map(entry => entry[0])[0]\n // Calculate median for numeric values\n const median = sorted.length ? \n sorted.length % 2 === 0 \n ? (sorted[sorted.length/2 - 1] + sorted[sorted.length/2]) / 2\n : sorted[Math.floor(sorted.length/2)]\n : null\n const sum = numericValues.length ? numericValues.reduce((a, b) => a + b, 0) : null\n const theType = typeof values[0]\n const count = values.length\n const mean = theType === \"number\" ? sum/count : \"\"\n return {\n name: colName,\n type: theType,\n incompleteCount: sourceData.length - values.length,\n uniqueCount: new Set(values).size,\n count,\n sum,\n median,\n mean,\n min: sorted.length ? sorted[0] : null,\n max: sorted.length ? sorted[sorted.length - 1] : null,\n mode\n }\n })\n }\n get columnNames() {\n return [\"name\", \"type\", \"incompleteCount\", \"uniqueCount\", \"count\", \"sum\", \"median\", \"mean\", \"min\", \"max\", \"mode\"]\n }\nerrorParser\n baseParser errorParser\nhakonContentParser\n popularity 0.102322\n catchAllAtomType codeAtom\nheatrixCatchAllParser\n popularity 0.000193\n // todo Fill this out\n catchAllAtomType stringAtom\nlineOfTextParser\n popularity 0.000289\n catchAllAtomType stringAtom\n boolean isTextParser true\nhtmlLineParser\n popularity 0.005209\n catchAllAtomType htmlAnyAtom\n catchAllParser htmlLineParser\nopenGraphParser\n // todo: fix Parsers scope issue so we can move this parser def under scrollImageParser\n description Add this line to make this the open graph image.\n cueFromId\n atoms cueAtom\nimportToFooterParser\n description Import to bottom of file.\n atoms preBuildCommandAtom\n cue footer\nscriptLineParser\n catchAllAtomType javascriptAnyAtom\n catchAllParser scriptLineParser\nlinkTitleParser\n popularity 0.000048\n description If you want to set the title of the link.\n cue title\n atoms cueAtom\n catchAllAtomType stringAtom\n example\n * This report showed the treatment had a big impact.\n https://example.com/report This report.\n title The average growth in the treatment group was 14.2x higher than the control group.\nprogramLinkParser\n popularity 0.000531\n catchAllAtomType codeAtom\nscrollMediaLoopParser\n popularity 0.000048\n cue loop\n atoms cueAtom\nscrollAutoplayParser\n cue autoplay\n atoms cueAtom\nabstractCompilerRuleParser\n catchAllAtomType anyAtom\n atoms cueAtom\ncloseSubparticlesParser\n extends abstractCompilerRuleParser\n description When compiling a parent particle to a string, this string is appended to the compiled and joined subparticles. Default is blank.\n cueFromId\nindentCharacterParser\n extends abstractCompilerRuleParser\n description You can change the indent character for compiled subparticles. Default is a space.\n cueFromId\ncatchAllAtomDelimiterParser\n description If a particle has a catchAllAtom, this is the string delimiter that will be used to join those atoms. Default is comma.\n extends abstractCompilerRuleParser\n cueFromId\nopenSubparticlesParser\n extends abstractCompilerRuleParser\n description When compiling a parent particle to a string, this string is prepended to the compiled and joined subparticles. Default is blank.\n cueFromId\nstringTemplateParser\n extends abstractCompilerRuleParser\n description This template string is used to compile this line, and accepts strings of the format: const var = {someAtomId}\n cueFromId\njoinSubparticlesWithParser\n description When compiling a parent particle to a string, subparticles are compiled to strings and joined by this character. Default is a newline.\n extends abstractCompilerRuleParser\n cueFromId\nabstractConstantParser\n description A constant.\n atoms cueAtom\n cueFromId\n // todo: make tags inherit\n tags actPhase\nparsersBooleanParser\n cue boolean\n atoms cueAtom constantIdentifierAtom\n catchAllAtomType booleanAtom\n extends abstractConstantParser\n tags actPhase\nparsersFloatParser\n cue float\n atoms cueAtom constantIdentifierAtom\n catchAllAtomType floatAtom\n extends abstractConstantParser\n tags actPhase\nparsersIntParser\n cue int\n atoms cueAtom constantIdentifierAtom\n catchAllAtomType integerAtom\n tags actPhase\n extends abstractConstantParser\nparsersStringParser\n cue string\n atoms cueAtom constantIdentifierAtom\n catchAllAtomType stringAtom\n catchAllParser catchAllMultilineStringConstantParser\n extends abstractConstantParser\n tags actPhase\nabstractParserRuleParser\n single\n atoms cueAtom\nabstractNonTerminalParserRuleParser\n extends abstractParserRuleParser\nparsersBaseParserParser\n atoms cueAtom baseParsersAtom\n description Set for blobs or errors. \n // In rare cases with untyped content you can use a blobParser, for now, to skip parsing for performance gains. The base errorParser will report errors when parsed. Use that if you don't want to implement your own error parser.\n extends abstractParserRuleParser\n cue baseParser\n tags analyzePhase\ncatchAllAtomTypeParser\n atoms cueAtom atomTypeIdAtom\n description Use for lists.\n // Aka 'listAtomType'. Use this when the value in a key/value pair is a list. If there are extra atoms in the particle's line, parse these atoms as this type. Often used with `listDelimiterParser`.\n extends abstractParserRuleParser\n cueFromId\n tags analyzePhase\natomParserParser\n atoms cueAtom atomParserAtom\n description Set parsing strategy.\n // prefix/postfix/omnifix parsing strategy. If missing, defaults to prefix.\n extends abstractParserRuleParser\n cueFromId\n tags experimental analyzePhase\ncatchAllParserParser\n description Attach this to unmatched lines.\n // If a parser is not found in the inScope list, instantiate this type of particle instead.\n atoms cueAtom parserIdAtom\n extends abstractParserRuleParser\n cueFromId\n tags acquirePhase\nparsersAtomsParser\n catchAllAtomType atomTypeIdAtom\n description Set required atomTypes.\n extends abstractParserRuleParser\n cue atoms\n tags analyzePhase\nparsersCompilerParser\n // todo Remove this and its subparticles?\n description Deprecated. For simple compilers.\n inScope stringTemplateParser catchAllAtomDelimiterParser openSubparticlesParser closeSubparticlesParser indentCharacterParser joinSubparticlesWithParser\n extends abstractParserRuleParser\n cue compiler\n tags deprecate\n boolean suggestInAutocomplete false\nparserDescriptionParser\n description Parser description.\n catchAllAtomType stringAtom\n extends abstractParserRuleParser\n cue description\n tags assemblePhase\nparsersExampleParser\n // todo Should this just be a \"string\" constant on particles?\n description Set example for docs and tests.\n catchAllAtomType exampleAnyAtom\n catchAllParser catchAllExampleLineParser\n extends abstractParserRuleParser\n cue example\n tags assemblePhase\nextendsParserParser\n cue extends\n tags assemblePhase\n description Extend another parser.\n // todo: add a catchall that is used for mixins\n atoms cueAtom parserIdAtom\n extends abstractParserRuleParser\nparsersPopularityParser\n // todo Remove this parser. Switch to conditional frequencies.\n description Parser popularity.\n atoms cueAtom floatAtom\n extends abstractParserRuleParser\n cue popularity\n tags assemblePhase\ninScopeParser\n description Parsers in scope.\n catchAllAtomType parserIdAtom\n extends abstractParserRuleParser\n cueFromId\n tags acquirePhase\nparsersJavascriptParser\n // todo Urgently need to get submode syntax highlighting running! (And eventually LSP)\n description Javascript code for Parser Actions.\n catchAllParser catchAllJavascriptCodeLineParser\n extends abstractParserRuleParser\n tags actPhase\n javascript\n format() {\n if (this.isNodeJs()) {\n const template = `class FOO{ ${this.subparticlesToString()}}`\n this.setSubparticles(\n require(\"prettier\")\n .format(template, { semi: false, useTabs: true, parser: \"babel\", printWidth: 240 })\n .replace(/class FOO \\{\\s+/, \"\")\n .replace(/\\s+\\}\\s+$/, \"\")\n .replace(/\\n\\t/g, \"\\n\") // drop one level of indent\n .replace(/\\t/g, \" \") // we used tabs instead of spaces to be able to dedent without breaking literals.\n )\n }\n return this\n }\n cue javascript\nabstractParseRuleParser\n // Each particle should have a pattern that it matches on unless it's a catch all particle.\n extends abstractParserRuleParser\n cueFromId\nparsersCueParser\n atoms cueAtom stringAtom\n description Attach by matching first atom.\n extends abstractParseRuleParser\n tags acquirePhase\n cue cue\ncueFromIdParser\n atoms cueAtom\n description Derive cue from parserId.\n // for example 'fooParser' would have cue of 'foo'.\n extends abstractParseRuleParser\n tags acquirePhase\nparsersPatternParser\n catchAllAtomType regexAtom\n description Attach via regex.\n extends abstractParseRuleParser\n tags acquirePhase\n cue pattern\nparsersRequiredParser\n description Assert is present at least once.\n extends abstractParserRuleParser\n cue required\n tags analyzePhase\nabstractValidationRuleParser\n extends abstractParserRuleParser\n cueFromId\n catchAllAtomType booleanAtom\nparsersSingleParser\n description Assert used once.\n // Can be overridden by a child class by setting to false.\n extends abstractValidationRuleParser\n tags analyzePhase\n cue single\nuniqueLineParser\n description Assert unique lines. For pattern parsers.\n // Can be overridden by a child class by setting to false.\n extends abstractValidationRuleParser\n tags analyzePhase\nuniqueCueParser\n description Assert unique first atoms. For pattern parsers.\n // For catch all parsers or pattern particles, use this to indicate the \n extends abstractValidationRuleParser\n tags analyzePhase\nlistDelimiterParser\n description Split content by this delimiter.\n extends abstractParserRuleParser\n cueFromId\n catchAllAtomType stringAtom\n tags analyzePhase\ncontentKeyParser\n description Deprecated. For to/from JSON.\n // Advanced keyword to help with isomorphic JSON serialization/deserialization. If present will serialize the particle to an object and set a property with this key and the value set to the particle's content.\n extends abstractParserRuleParser\n cueFromId\n catchAllAtomType stringAtom\n tags deprecate\n boolean suggestInAutocomplete false\nsubparticlesKeyParser\n // todo: deprecate?\n description Deprecated. For to/from JSON.\n // Advanced keyword to help with serialization/deserialization of blobs. If present will serialize the particle to an object and set a property with this key and the value set to the particle's subparticles.\n extends abstractParserRuleParser\n cueFromId\n catchAllAtomType stringAtom\n tags deprecate\n boolean suggestInAutocomplete false\nparsersTagsParser\n catchAllAtomType stringAtom\n extends abstractParserRuleParser\n description Custom metadata.\n cue tags\n tags assemblePhase\natomTypeDescriptionParser\n description Atom Type description.\n catchAllAtomType stringAtom\n cue description\n tags assemblePhase\ncatchAllErrorParser\n baseParser errorParser\ncatchAllExampleLineParser\n catchAllAtomType exampleAnyAtom\n catchAllParser catchAllExampleLineParser\n atoms exampleAnyAtom\ncatchAllJavascriptCodeLineParser\n catchAllAtomType javascriptCodeAtom\n catchAllParser catchAllJavascriptCodeLineParser\ncatchAllMultilineStringConstantParser\n description String constants can span multiple lines.\n catchAllAtomType stringAtom\n catchAllParser catchAllMultilineStringConstantParser\n atoms stringAtom\natomTypeDefinitionParser\n // todo Generate a class for each atom type?\n // todo Allow abstract atom types?\n // todo Change pattern to postfix.\n pattern ^[a-zA-Z0-9_]+Atom$\n inScope parsersPaintParser parsersRegexParser reservedAtomsParser enumFromAtomTypesParser atomTypeDescriptionParser parsersEnumParser slashCommentParser extendsAtomTypeParser parsersExamplesParser atomMinParser atomMaxParser\n atoms atomTypeIdAtom\n tags assemblePhase\n javascript\n buildHtml() {return \"\"}\nenumFromAtomTypesParser\n description Runtime enum options.\n catchAllAtomType atomTypeIdAtom\n atoms atomPropertyNameAtom\n cueFromId\n tags analyzePhase\nparsersEnumParser\n description Set enum options.\n cue enum\n catchAllAtomType enumOptionAtom\n atoms atomPropertyNameAtom\n tags analyzePhase\nparsersExamplesParser\n description Examples for documentation and tests.\n // If the domain of possible atom values is large, such as a string type, it can help certain methods—such as program synthesis—to provide a few examples.\n cue examples\n catchAllAtomType atomExampleAtom\n atoms atomPropertyNameAtom\n tags assemblePhase\natomMinParser\n description Specify a min if numeric.\n cue min\n atoms atomPropertyNameAtom numberAtom\n tags analyzePhase\natomMaxParser\n description Specify a max if numeric.\n cue max\n atoms atomPropertyNameAtom numberAtom\n tags analyzePhase\nparsersPaintParser\n atoms cueAtom paintTypeAtom\n description Instructor editor how to color these.\n single\n cue paint\n tags analyzePhase\nparserDefinitionParser\n // todo Add multiple dispatch?\n pattern ^[a-zA-Z0-9_]+Parser$\n description Parser types are a core unit of your language. They translate to 1 class per parser. Examples of parser would be \"header\", \"person\", \"if\", \"+\", \"define\", etc.\n catchAllParser catchAllErrorParser\n inScope abstractParserRuleParser abstractConstantParser slashCommentParser parserDefinitionParser\n atoms parserIdAtom\n tags assemblePhase\n javascript\n buildHtml() { return \"\"}\nparsersRegexParser\n catchAllAtomType regexAtom\n description Atoms must match this.\n single\n atoms atomPropertyNameAtom\n cue regex\n tags analyzePhase\nreservedAtomsParser\n single\n description Atoms can't be any of these.\n catchAllAtomType reservedAtomAtom\n atoms atomPropertyNameAtom\n cueFromId\n tags analyzePhase\nextendsAtomTypeParser\n cue extends\n description Extend another atomType.\n // todo Add mixin support in addition to extends?\n atoms cueAtom atomTypeIdAtom\n tags assemblePhase\n single\nabstractColumnNameParser\n atoms cueAtom columnNameAtom\n javascript\n getRunTimeEnumOptions(atom) {\n if (atom.atomTypeId === \"columnNameAtom\")\n return this.parent.columnNames\n return super.getRunTimeEnumOptions(atom)\n }\nscrollRadiusParser\n cue radius\n extends abstractColumnNameParser\nscrollSymbolParser\n cue symbol\n extends abstractColumnNameParser\nabstractColumnNameOrColorParser\n extends abstractColumnNameParser\n atoms cueAtom columnNameOrColorAtom\n javascript\n //todo: cleanup\n colorOptions = \"aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkkhaki darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray darkturquoise darkviolet deeppink deepskyblue dimgray dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow honeydew hotpink indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgoldenrodyellow lightgray lightgreen lightpink lightsalmon lightseagreen lightskyblue lightslategray lightsteelblue lightyellow lime limegreen linen magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell sienna silver skyblue slateblue slategray snow springgreen steelblue tan teal thistle tomato turquoise violet wheat white whitesmoke yellow yellowgreen\".split(\" \")\n getRunTimeEnumOptions(atom) {\n if (atom.atomTypeId === \"columnNameOrColorAtom\")\n return this.parent.columnNames.join(this.colorOptions)\n return super.getRunTimeEnumOptions(atom)\n }\nscrollFillParser\n cue fill\n extends abstractColumnNameOrColorParser\nscrollStrokeParser\n cue stroke\n extends abstractColumnNameOrColorParser\nscrollLabelParser\n cue label\n extends abstractColumnNameParser\nscrollSortParser\n cue sort\n extends abstractColumnNameParser\nscrollXParser\n cue x\n extends abstractColumnNameParser\nscrollYParser\n cue y\n extends abstractColumnNameParser\nabstractPlotLabelParser\n cueFromId\n atoms cueAtom\n catchAllAtomType stringAtom\nquoteLineParser\n popularity 0.004172\n catchAllAtomType stringAtom\n catchAllParser quoteLineParser\nscrollParser\n description Scroll is a language for scientists of all ages. Refine, share and collaborate on ideas.\n root\n inScope abstractScrollParser blankLineParser atomTypeDefinitionParser parserDefinitionParser\n catchAllParser catchAllParagraphParser\n javascript\n setFile(file) {\n this.file = file\n const date = this.get(\"date\")\n if (date) this.file.timestamp = this.dayjs(this.get(\"date\")).unix()\n return this\n }\n buildHtml(buildSettings) {\n this.sectionStack = []\n return this.filter(subparticle => subparticle.buildHtml).map(subparticle => { try {return subparticle.buildHtml(buildSettings)} catch (err) {console.error(err); return \"\"} }).filter(i => i).join(\"\\n\") + this.clearSectionStack()\n }\n sectionStack = []\n clearSectionStack() {\n const result = this.sectionStack.join(\"\\n\")\n this.sectionStack = []\n return result\n }\n bodyStack = []\n clearBodyStack() {\n const result = this.bodyStack.join(\"\")\n this.bodyStack = []\n return result\n }\n get hakonParser() {\n if (this.isNodeJs())\n return require(\"scrollsdk/products/hakon.nodejs.js\")\n return hakonParser\n }\n readSyncFromFileOrUrl(fileOrUrl) {\n if (!this.isNodeJs()) return this.getInBrowser(fileOrUrl)\n const isUrl = fileOrUrl.match(/^https?\\:[^ ]+$/)\n if (!isUrl) return this.root.readFile(fileOrUrl)\n return this.readFile(this.makeFullPath(new URL(fileOrUrl).pathname.split('/').pop()))\n }\n getInBrowser(key) {\n return localStorage.getItem(key) || (window.inMemStorage ? window.inMemStorage[key] : \"\") || \"\"\n }\n async fetch(url, filename) {\n const isUrl = url.match(/^https?\\:[^ ]+$/)\n if (!isUrl) return\n return this.isNodeJs() ? this.fetchNode(url, filename) : this.fetchBrowser(url)\n }\n get path() {\n return require(\"path\")\n }\n makeFullPath(filename) {\n return this.path.join(this.folderPath, filename)\n }\n _nextAndPrevious(arr, index) {\n const nextIndex = index + 1\n const previousIndex = index - 1\n return {\n previous: arr[previousIndex] ?? arr[arr.length - 1],\n next: arr[nextIndex] ?? arr[0]\n }\n }\n // keyboard nav is always in the same folder. does not currently support cross folder\n includeFileInKeyboardNav(file) {\n const { scrollProgram } = file\n return scrollProgram.buildsHtml && scrollProgram.hasKeyboardNav && scrollProgram.tags.includes(this.primaryTag)\n }\n get timeIndex() {\n return this.file.timeIndex || 0\n }\n get linkToPrevious() {\n if (!this.hasKeyboardNav)\n // Dont provide link to next unless keyboard nav is on\n return undefined\n const {allScrollFiles} = this\n let file = this._nextAndPrevious(allScrollFiles, this.timeIndex).previous\n while (!this.includeFileInKeyboardNav(file)) {\n file = this._nextAndPrevious(allScrollFiles, file.timeIndex).previous\n }\n return file.scrollProgram.permalink\n }\n importRegex = /^(import |[a-zA-Z\\_\\-\\.0-9\\/]+\\.(scroll|parsers)$|https?:\\/\\/.+\\.(scroll|parsers)$)/gm\n get linkToNext() {\n if (!this.hasKeyboardNav)\n // Dont provide link to next unless keyboard nav is on\n return undefined\n const {allScrollFiles} = this\n let file = this._nextAndPrevious(allScrollFiles, this.timeIndex).next\n while (!this.includeFileInKeyboardNav(file)) {\n file = this._nextAndPrevious(allScrollFiles, file.timeIndex).next\n }\n return file.scrollProgram.permalink\n }\n // todo: clean up this naming pattern and add a parser instead of special casing 404.html\n get allHtmlFiles() {\n return this.allScrollFiles.filter(file => file.scrollProgram.buildsHtml && file.scrollProgram.permalink !== \"404.html\")\n }\n parseNestedTag(tag) {\n if (!tag.includes(\"/\")) return;\n const {path} = this\n const parts = tag.split(\"/\")\n const group = parts.pop()\n const relativePath = parts.join(\"/\")\n return {\n group,\n relativePath,\n folderPath: path.join(this.folderPath, path.normalize(relativePath))\n }\n }\n getFilesByTags(tags, limit) {\n // todo: tags is currently matching partial substrings\n const getFilesWithTag = (tag, files) => files.filter(file => file.scrollProgram.buildsHtml && file.scrollProgram.tags.includes(tag))\n if (typeof tags === \"string\") tags = tags.split(\" \")\n if (!tags || !tags.length)\n return this.allHtmlFiles\n .filter(file => file !== this) // avoid infinite loops. todo: think this through better.\n .map(file => {\n return { file, relativePath: \"\" }\n })\n .slice(0, limit)\n let arr = []\n tags.forEach(tag => {\n if (!tag.includes(\"/\"))\n return (arr = arr.concat(\n getFilesWithTag(tag, this.allScrollFiles)\n .map(file => {\n return { file, relativePath: \"\" }\n })\n .slice(0, limit)\n ))\n const {folderPath, group, relativePath} = this.parseNestedTag(tag)\n let files = []\n try {\n files = this.fileSystem.getCachedLoadedFilesInFolder(folderPath, this)\n } catch (err) {\n console.error(err)\n }\n const filtered = getFilesWithTag(group, files).map(file => {\n return { file, relativePath: relativePath + \"/\" }\n })\n arr = arr.concat(filtered.slice(0, limit))\n })\n return this.lodash.sortBy(arr, file => file.file.timestamp).reverse()\n }\n async fetchNode(url, filename) {\n filename = filename || new URL(url).pathname.split('/').pop()\n const fullpath = this.makeFullPath(filename)\n if (require(\"fs\").existsSync(fullpath)) return this.readFile(fullpath)\n this.log(`🛜 fetching ${url} to ${fullpath} `)\n await this.downloadToDisk(url, fullpath)\n return this.readFile(fullpath)\n }\n log(message) {\n if (this.logger) this.logger.log(message)\n }\n async fetchBrowser(url) {\n const content = this.getInBrowser(url)\n if (content) return content\n return this.downloadToLocalStorage(url)\n }\n async downloadToDisk(url, destination) {\n const { writeFile } = require('fs').promises\n const response = await fetch(url)\n const fileBuffer = await response.arrayBuffer()\n await writeFile(destination, Buffer.from(fileBuffer))\n return this.readFile(destination)\n }\n async downloadToLocalStorage(url) {\n const response = await fetch(url)\n const blob = await response.blob()\n const text = await blob.text()\n try {\n localStorage.setItem(url, text)\n return localStorage.getItem(url)\n } catch (err) {\n if (!window.inMemStorage) window.inMemStorage = {}\n window.inMemStorage[url] = text\n console.error(err)\n return text\n }\n }\n readFile(filename) {\n const {path} = this\n const fs = require(\"fs\")\n const fullPath = path.join(this.folderPath, filename.replace(this.folderPath, \"\"))\n try {\n if (fs.existsSync(fullPath))\n return fs.readFileSync(fullPath, \"utf8\")\n console.error(`File '${filename}' not found`)\n return \"\"\n } catch (err) {\n console.error(`Error in '${this.filePath}' reading file: '${fullPath}'`)\n console.error(err)\n return \"\"\n }\n }\n alreadyRequired = new Set()\n buildHtmlSnippet(buildSettings) {\n this.sectionStack = []\n return this.map(subparticle => (subparticle.buildHtmlSnippet ? subparticle.buildHtmlSnippet(buildSettings) : subparticle.buildHtml(buildSettings)))\n .filter(i => i)\n .join(\"\\n\")\n .trim() + this.clearSectionStack()\n }\n get footnotes() {\n if (this._footnotes === undefined) this._footnotes = this.filter(particle => particle.isFootnote)\n return this._footnotes\n }\n get authors() {\n return this.get(\"authors\")\n }\n get allScrollFiles() {\n try {\n return this.fileSystem.getCachedLoadedFilesInFolder(this.folderPath, this)\n } catch (err) {\n console.error(err)\n return []\n }\n }\n async doThing(thing) {\n await Promise.all(this.filter(particle => particle[thing]).map(async particle => particle[thing]()))\n }\n async load() {\n await this.doThing(\"load\")\n }\n async execute() {\n await this.doThing(\"execute\")\n }\n file = {}\n getFromParserId(parserId) {\n return this.parserIdIndex[parserId]?.[0].content\n }\n get fileSystem() {\n return this.file.fileSystem\n }\n get filePath() {\n return this.file.filePath\n }\n get folderPath() {\n return this.file.folderPath\n }\n get filename() {\n return this.file.filename || \"\"\n }\n get hasKeyboardNav() {\n return this.has(\"keyboardNav\")\n }\n get editHtml() {\n return `<a href=\"${this.editUrl}\" class=\"abstractTextLinkParser\">Edit</a>`\n }\n get externalsPath() {\n return this.file.EXTERNALS_PATH\n }\n get endSnippetIndex() {\n // Get the line number that the snippet should stop at.\n // First if its hard coded, use that\n if (this.has(\"endSnippet\")) return this.getParticle(\"endSnippet\").index\n // Next look for a dinkus\n const snippetBreak = this.find(particle => particle.isDinkus)\n if (snippetBreak) return snippetBreak.index\n return -1\n }\n get parserIds() {\n return this.topDownArray.map(particle => particle.definition.id)\n }\n get tags() {\n return this.get(\"tags\") || \"\"\n }\n get primaryTag() {\n return this.tags.split(\" \")[0]\n }\n get filenameNoExtension() {\n return this.filename.replace(\".scroll\", \"\")\n }\n // todo: rename publishedUrl? Or something to indicate that this is only for stuff on the web (not localhost)\n // BaseUrl must be provided for RSS Feeds and OpenGraph tags to work\n get baseUrl() {\n const baseUrl = (this.get(\"baseUrl\") || \"\").replace(/\\/$/, \"\")\n return baseUrl + \"/\"\n }\n get canonicalUrl() {\n return this.get(\"canonicalUrl\") || this.baseUrl + this.permalink\n }\n get openGraphImage() {\n const openGraphImage = this.get(\"openGraphImage\")\n if (openGraphImage !== undefined) return this.ensureAbsoluteLink(openGraphImage)\n const images = this.filter(particle => particle.doesExtend(\"scrollImageParser\"))\n const hit = images.find(particle => particle.has(\"openGraph\")) || images[0]\n if (!hit) return \"\"\n return this.ensureAbsoluteLink(hit.filename)\n }\n get absoluteLink() {\n return this.ensureAbsoluteLink(this.permalink)\n }\n ensureAbsoluteLink(link) {\n if (link.includes(\"://\")) return link\n return this.baseUrl + link.replace(/^\\//, \"\")\n }\n get editUrl() {\n const editUrl = this.get(\"editUrl\")\n if (editUrl) return editUrl\n const editBaseUrl = this.get(\"editBaseUrl\")\n return (editBaseUrl ? editBaseUrl.replace(/\\/$/, \"\") + \"/\" : \"\") + this.filename\n }\n get gitRepo() {\n // given https://github.com/breck7/breckyunits.com/blob/main/four-tips-to-improve-communication.scroll\n // return https://github.com/breck7/breckyunits.com\n return this.editUrl.split(\"/\").slice(0, 5).join(\"/\")\n }\n get scrollVersion() {\n // currently manually updated\n return \"167.7.0\"\n }\n // Use the first paragraph for the description\n // todo: add a particle method version of get that gets you the first particle. (actulaly make get return array?)\n // would speed up a lot.\n get description() {\n const description = this.getFromParserId(\"openGraphDescriptionParser\")\n if (description) return description\n return this.generatedDescription\n }\n get keywords() {\n if (this.has(\"keywords\"))\n return this.get(\"keywords\")\n const tags = this.get(\"tags\")\n if (tags)\n return tags.split(\" \").join(\", \")\n return \"\"\n }\n get generatedDescription() {\n const firstParagraph = this.find(particle => particle.isArticleContent)\n return firstParagraph ? firstParagraph.originalText.substr(0, 100).replace(/[&\"<>']/g, \"\") : \"\"\n }\n get titleFromFilename() {\n const unCamelCase = str => str.replace(/([a-z])([A-Z])/g, \"$1 $2\").replace(/^./, match => match.toUpperCase())\n return unCamelCase(this.filenameNoExtension)\n }\n get title() {\n return this.getFromParserId(\"scrollTitleParser\") || this.titleFromFilename\n }\n get linkTitle() {\n return this.getFromParserId(\"scrollLinkTitleParser\") || this.title\n }\n get permalink() {\n return this.get(\"permalink\") || (this.filename ? this.filenameNoExtension + \".html\" : \"\")\n }\n compileTo(extensionCapitalized) {\n if (extensionCapitalized === \"Txt\")\n return this.asTxt\n if (extensionCapitalized === \"Html\")\n return this.asHtml\n const methodName = \"build\" + extensionCapitalized\n return this.topDownArray\n .filter(particle => particle[methodName])\n .map((particle, index) => particle[methodName](index))\n .join(\"\\n\")\n .trim()\n }\n get asTxt() {\n return (\n this.map(particle => {\n const text = particle.buildTxt ? particle.buildTxt() : \"\"\n if (text) return text + \"\\n\"\n if (!particle.getLine().length) return \"\\n\"\n return \"\"\n })\n .join(\"\")\n .replace(/<[^>]*>/g, \"\")\n .replace(/\\n\\n\\n+/g, \"\\n\\n\") // Maximum 2 newlines in a row\n .trim() + \"\\n\" // Always end in a newline, Posix style\n )\n }\n get dependencies() {\n const dependencies = this.file.dependencies?.slice() || []\n const files = this.topDownArray.filter(particle => particle.dependencies).map(particle => particle.dependencies).flat()\n return dependencies.concat(files)\n }\n get buildsHtml() {\n const { permalink } = this\n return !this.file.importOnly && (permalink.endsWith(\".html\") || permalink.endsWith(\".htm\"))\n }\n // Without specifying the language hyphenation will not work.\n get lang() {\n return this.get(\"htmlLang\") || \"en\"\n }\n _compiledHtml = \"\"\n get asHtml() {\n if (!this._compiledHtml) {\n const { permalink, buildsHtml } = this\n const content = (this.buildHtml() + this.clearBodyStack()).trim()\n // Don't add html tags to CSV feeds. A little hacky as calling a getter named _html_ to get _xml_ is not ideal. But\n // <1% of use case so might be good enough.\n const wrapWithHtmlTags = buildsHtml\n const bodyTag = this.has(\"metaTags\") ? \"\" : \"<body>\\n\"\n this._compiledHtml = wrapWithHtmlTags ? `<!DOCTYPE html>\\n<html lang=\"${this.lang}\">\\n${bodyTag}${content}\\n</body>\\n</html>` : content\n }\n return this._compiledHtml\n }\n get wordCount() {\n return this.asTxt.match(/\\b\\w+\\b/g)?.length || 0\n }\n get minutes() {\n return parseFloat((this.wordCount / 200).toFixed(1))\n }\n get date() {\n const date = this.get(\"date\") || (this.file.timestamp ? this.file.timestamp : 0)\n return this.dayjs(date).format(`MM/DD/YYYY`)\n }\n get year() {\n return parseInt(this.dayjs(this.date).format(`YYYY`))\n }\n get dayjs() {\n if (!this.isNodeJs()) return dayjs\n const lib = require(\"dayjs\")\n const relativeTime = require(\"dayjs/plugin/relativeTime\")\n lib.extend(relativeTime)\n return lib\n }\n get lodash() {\n return this.isNodeJs() ? require(\"lodash\") : lodash\n }\n get d3() {\n return this.isNodeJs() ? require('d3') : d3\n }\n getConcepts(parsed) {\n const concepts = []\n let currentConcept\n parsed.forEach(particle => {\n if (particle.isConceptDelimiter) {\n if (currentConcept) concepts.push(currentConcept)\n currentConcept = []\n }\n if (currentConcept && particle.isMeasure) currentConcept.push(particle)\n })\n if (currentConcept) concepts.push(currentConcept)\n return concepts\n }\n _formatConcepts(parsed) {\n const concepts = this.getConcepts(parsed)\n if (!concepts.length) return false\n const {lodash} = this\n // does a destructive sort in place on the parsed program\n concepts.forEach(concept => {\n let currentSection\n const newCode = lodash\n .sortBy(concept, [\"sortIndex\"])\n .map(particle => {\n let newLines = \"\"\n const section = particle.sortIndex.toString().split(\".\")[0]\n if (section !== currentSection) {\n currentSection = section\n newLines = \"\\n\"\n }\n return newLines + particle.toString()\n })\n .join(\"\\n\")\n concept.forEach((particle, index) => (index ? particle.destroy() : \"\"))\n concept[0].replaceParticle(() => newCode)\n })\n }\n get formatted() {\n return this.getFormatted(this.file.codeAtStart)\n }\n get lastCommitTime() {\n // todo: speed this up and do a proper release. also could add more metrics like this.\n if (this._lastCommitTime === undefined) {\n try {\n this._lastCommitTime = require(\"child_process\").execSync(`git log -1 --format=\"%at\" -- \"${this.filePath}\"`).toString().trim()\n } catch (err) {\n this._lastCommitTime = 0\n }\n }\n return this._lastCommitTime\n }\n getFormatted(codeAtStart = this.toString()) {\n let formatted = codeAtStart.replace(/\\r/g, \"\") // remove all carriage returns if there are any\n const parsed = new this.constructor(formatted)\n parsed.topDownArray.forEach(subparticle => {\n subparticle.format()\n const original = subparticle.getLine()\n const trimmed = original.replace(/(\\S.*?)[ \\t]*$/gm, \"$1\")\n // Trim trailing whitespace unless parser allows it\n if (original !== trimmed && !subparticle.allowTrailingWhitespace) subparticle.setLine(trimmed)\n })\n this._formatConcepts(parsed)\n let importOnlys = []\n let topMatter = []\n let allElse = []\n // Create any bindings\n parsed.forEach(particle => {\n if (particle.bindTo === \"next\") particle.binding = particle.next\n if (particle.bindTo === \"previous\") particle.binding = particle.previous\n })\n parsed.forEach(particle => {\n if (particle.getLine() === \"importOnly\") importOnlys.push(particle)\n else if (particle.isTopMatter) topMatter.push(particle)\n else allElse.push(particle)\n })\n const combined = importOnlys.concat(topMatter, allElse)\n // Move any bound particles\n combined\n .filter(particle => particle.bindTo)\n .forEach(particle => {\n // First remove the particle from its current position\n const originalIndex = combined.indexOf(particle)\n combined.splice(originalIndex, 1)\n // Then insert it at the new position\n // We need to find the binding index again after removal\n const bindingIndex = combined.indexOf(particle.binding)\n if (particle.bindTo === \"next\") combined.splice(bindingIndex, 0, particle)\n else combined.splice(bindingIndex + 1, 0, particle)\n })\n const trimmed = combined\n .map(particle => particle.toString())\n .join(\"\\n\")\n .replace(/^\\n*/, \"\") // Remove leading newlines\n .replace(/\\n\\n\\n+/g, \"\\n\\n\") // Maximum 2 newlines in a row\n .replace(/\\n+$/, \"\")\n return trimmed === \"\" ? trimmed : trimmed + \"\\n\" // End non blank Scroll files in a newline character POSIX style for better working with tools like git\n }\n get parser() {\n return this.constructor\n }\n get parsersRequiringExternals() {\n const { parser } = this\n // todo: could be cleaned up a bit\n if (!parser.parsersRequiringExternals) parser.parsersRequiringExternals = parser.cachedHandParsersProgramRoot.filter(particle => particle.copyFromExternal).map(particle => particle.atoms[0])\n return parser.parsersRequiringExternals\n }\n get Disk() { return this.isNodeJs() ? require(\"scrollsdk/products/Disk.node.js\").Disk : {}}\n async buildAll(options = {}) {\n await this.load()\n await this.buildOne(options)\n await this.buildTwo(options)\n }\n async buildOne(options) {\n await this.execute()\n const toBuild = this.filter(particle => particle.buildOne)\n for (let particle of toBuild) {\n await particle.buildOne(options)\n }\n }\n async buildTwo(options) {\n const toBuild = this.filter(particle => particle.buildTwo)\n for (let particle of toBuild) {\n await particle.buildTwo(options)\n }\n }\n get outputFileNames() {\n return this.filter(p => p.outputFileNames).map(p => p.outputFileNames).flat()\n }\n _compileArray(filename, arr) {\n const removeBlanks = data => data.map(obj => Object.fromEntries(Object.entries(obj).filter(([_, value]) => value !== \"\")))\n const parts = filename.split(\".\")\n const format = parts.pop()\n if (format === \"json\") return JSON.stringify(removeBlanks(arr), null, 2)\n if (format === \"js\") return `const ${parts[0]} = ` + JSON.stringify(removeBlanks(arr), null, 2)\n if (format === \"csv\") return this.arrayToCSV(arr)\n if (format === \"tsv\") return this.arrayToCSV(arr, \"\\t\")\n if (format === \"particles\") return particles.toString()\n return particles.toString()\n }\n levenshteinDistance(a, b) {\n const m = a.length\n const n = b.length\n const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0))\n for (let i = 0; i <= m; i++) {\n dp[i][0] = i\n }\n for (let j = 0; j <= n; j++) {\n dp[0][j] = j\n }\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1\n dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost)\n }\n }\n return dp[m][n]\n }\n makeLodashOrderByParams(str) {\n const part1 = str.split(\" \")\n const part2 = part1.map(col => (col.startsWith(\"-\") ? \"desc\" : \"asc\"))\n return [part1.map(col => col.replace(/^\\-/, \"\")), part2]\n }\n arrayToCSV(data, delimiter = \",\") {\n if (!data.length) return \"\"\n // Extract headers\n const headers = Object.keys(data[0])\n const csv = data.map(row =>\n headers\n .map(fieldName => {\n const fieldValue = row[fieldName]\n // Escape commas if the value is a string\n if (typeof fieldValue === \"string\" && fieldValue.includes(delimiter)) {\n return `\"${fieldValue.replace(/\"/g, '\"\"')}\"` // Escape double quotes and wrap in double quotes\n }\n return fieldValue\n })\n .join(delimiter)\n )\n csv.unshift(headers.join(delimiter)) // Add header row at the top\n return csv.join(\"\\n\")\n }\n compileConcepts(filename = \"csv\", sortBy = \"\") {\n const {lodash} = this\n if (!sortBy) return this._compileArray(filename, this.concepts)\n const orderBy = this.makeLodashOrderByParams(sortBy)\n return this._compileArray(filename, lodash.orderBy(this.concepts, orderBy[0], orderBy[1]))\n }\n _withStats\n get measuresWithStats() {\n if (!this._withStats) this._withStats = this.addMeasureStats(this.concepts, this.measures)\n return this._withStats\n }\n addMeasureStats(concepts, measures){\n return measures.map(measure => {\n let Type = false\n concepts.forEach(concept => {\n const value = concept[measure.Name]\n if (value === undefined || value === \"\") return\n measure.Values++\n if (!Type) {\n measure.Example = value.toString().replace(/\\n/g, \" \")\n measure.Type = typeof value\n Type = true\n }\n })\n measure.Coverage = Math.floor((100 * measure.Values) / concepts.length) + \"%\"\n return measure\n })\n }\n parseMeasures(parser) {\n if (!Particle.measureCache)\n Particle.measureCache = new Map()\n const measureCache = Particle.measureCache\n if (measureCache.get(parser)) return measureCache.get(parser)\n const {lodash} = this\n // todo: clean this up\n const getCueAtoms = rootParserProgram =>\n rootParserProgram\n .filter(particle => particle.getLine().endsWith(\"Parser\") && !particle.getLine().startsWith(\"abstract\"))\n .map(particle => particle.get(\"cue\") || particle.getLine())\n .map(line => line.replace(/Parser$/, \"\"))\n // Generate a fake program with one of every of the available parsers. Then parse it. Then we can easily access the meta data on the parsers\n const dummyProgram = new parser(\n Array.from(\n new Set(\n getCueAtoms(parser.cachedHandParsersProgramRoot) // is there a better method name than this?\n )\n ).join(\"\\n\")\n )\n // Delete any particles that are not measures\n dummyProgram.filter(particle => !particle.isMeasure).forEach(particle => particle.destroy())\n dummyProgram.forEach(particle => {\n // add nested measures\n Object.keys(particle.definition.cueMapWithDefinitions).forEach(key => particle.appendLine(key))\n })\n // Delete any nested particles that are not measures\n dummyProgram.topDownArray.filter(particle => !particle.isMeasure).forEach(particle => particle.destroy())\n const measures = dummyProgram.topDownArray.map(particle => {\n return {\n Name: particle.measureName,\n Values: 0,\n Coverage: 0,\n Question: particle.definition.description,\n Example: particle.definition.getParticle(\"example\")?.subparticlesToString() || \"\",\n Type: particle.typeForWebForms,\n Source: particle.sourceDomain,\n //Definition: parsedProgram.root.filename + \":\" + particle.lineNumber\n SortIndex: particle.sortIndex,\n IsComputed: particle.isComputed,\n IsRequired: particle.isMeasureRequired,\n IsConceptDelimiter: particle.isConceptDelimiter,\n Cue: particle.definition.get(\"cue\")\n }\n })\n measureCache.set(parser, lodash.sortBy(measures, \"SortIndex\"))\n return measureCache.get(parser)\n }\n _concepts\n get concepts() {\n if (this._concepts) return this._concepts\n this._concepts = this.parseConcepts(this, this.measures)\n return this._concepts\n }\n _measures\n get measures() {\n if (this._measures) return this._measures\n this._measures = this.parseMeasures(this.parser)\n return this._measures\n }\n parseConcepts(parsedProgram, measures){\n // Todo: might be a perf/memory/simplicity win to have a \"segment\" method in ScrollSDK, where you could\n // virtually split a Particle into multiple segments, and then query on those segments.\n // So we would \"segment\" on \"id \", and then not need to create a bunch of new objects, and the original\n // already parsed lines could then learn about/access to their respective segments.\n const conceptDelimiter = measures.filter(measure => measure.IsConceptDelimiter)[0]\n if (!conceptDelimiter) return []\n const concepts = parsedProgram.split(conceptDelimiter.Cue || conceptDelimiter.Name)\n concepts.shift() // Remove the part before \"id\"\n return concepts.map(concept => {\n const row = {}\n measures.forEach(measure => {\n const measureName = measure.Name\n const measureKey = measure.Cue || measureName.replace(/_/g, \" \")\n if (!measure.IsComputed) row[measureName] = concept.getParticle(measureKey)?.measureValue ?? \"\"\n else row[measureName] = this.computeMeasure(parsedProgram, measureName, concept, concepts)\n })\n return row\n })\n }\n computeMeasure(parsedProgram, measureName, concept, concepts){\n // note that this is currently global, assuming there wont be. name conflicts in computed measures in a single scroll\n if (!Particle.measureFnCache) Particle.measureFnCache = {}\n const measureFnCache = Particle.measureFnCache\n if (!measureFnCache[measureName]) {\n // a bit hacky but works??\n const particle = parsedProgram.appendLine(measureName)\n measureFnCache[measureName] = particle.computeValue\n particle.destroy()\n }\n return measureFnCache[measureName](concept, measureName, parsedProgram, concepts)\n }\n compileMeasures(filename = \"csv\", sortBy = \"\") {\n const withStats = this.measuresWithStats\n if (!sortBy) return this._compileArray(filename, withStats)\n const orderBy = this.makeLodashOrderByParams(sortBy)\n return this._compileArray(filename, this.lodash.orderBy(withStats, orderBy[0], orderBy[1]))\n }\n evalNodeJsMacros(value, macroMap, filePath) {\n const tempPath = filePath + \".js\"\n const {Disk} = this\n if (Disk.exists(tempPath)) throw new Error(`Failed to write/require replaceNodejs snippet since '${tempPath}' already exists.`)\n try {\n Disk.write(tempPath, value)\n const results = require(tempPath)\n Object.keys(results).forEach(key => (macroMap[key] = results[key]))\n } catch (err) {\n console.error(`Error in evalMacros in file '${filePath}'`)\n console.error(err)\n } finally {\n Disk.rm(tempPath)\n }\n }\n evalMacros(fusedFile) {\n const {fusedCode, codeAtStart, filePath} = fusedFile\n let code = fusedCode\n const absolutePath = filePath\n // note: the 2 params above are not used in this method, but may be used in user eval code. (todo: cleanup)\n const regex = /^(replace|toFooter$)/gm\n if (!regex.test(code)) return code\n const particle = new Particle(code) // todo: this can be faster. a more lightweight particle class?\n // Process macros\n const macroMap = {}\n particle\n .filter(particle => {\n const parserAtom = particle.cue\n return parserAtom === \"replace\" || parserAtom === \"replaceJs\" || parserAtom === \"replaceNodejs\"\n })\n .forEach(particle => {\n let value = particle.length ? particle.subparticlesToString() : particle.getAtomsFrom(2).join(\" \")\n const kind = particle.cue\n try {\n if (kind === \"replaceJs\") value = eval(value)\n if (this.isNodeJs() && kind === \"replaceNodejs\")\n this.evalNodeJsMacros(value, macroMap, absolutePath)\n else macroMap[particle.getAtom(1)] = value\n } catch (err) {\n console.error(err)\n }\n particle.destroy() // Destroy definitions after eval\n })\n if (particle.has(\"toFooter\")) {\n const pushes = particle.getParticles(\"toFooter\")\n const append = pushes.map(push => push.section.join(\"\\n\")).join(\"\\n\")\n pushes.forEach(push => {\n push.section.forEach(particle => particle.destroy())\n push.destroy()\n })\n code = particle.asString + append\n }\n const keys = Object.keys(macroMap)\n if (!keys.length) return code\n let codeAfterMacroSubstitution = particle.asString\n // Todo: speed up. build a template?\n Object.keys(macroMap).forEach(key => (codeAfterMacroSubstitution = codeAfterMacroSubstitution.replace(new RegExp(key, \"g\"), macroMap[key])))\n return codeAfterMacroSubstitution\n }\n toRss() {\n const { title, canonicalUrl } = this\n return ` <item>\n <title>${title}</title>\n <link>${canonicalUrl}</link>\n <pubDate>${this.dayjs(this.timestamp * 1000).format(\"ddd, DD MMM YYYY HH:mm:ss ZZ\")}</pubDate>\n </item>`\n }\n example\n # Hello world\n ## This is Scroll\n * It compiles to HTML.\n \n code\n // You can add code as well.\n print(\"Hello world\")\nstampFileParser\n catchAllAtomType stringAtom\n description Create a file.\n javascript\n execute(parentDir) {\n const fs = require(\"fs\")\n const path = require(\"path\")\n const fullPath = path.join(parentDir, this.getLine())\n this.root.log(`Creating file ${fullPath}`)\n fs.mkdirSync(path.dirname(fullPath), {recursive: true})\n const content = this.subparticlesToString()\n fs.writeFileSync(fullPath, content, \"utf8\")\n const isExecutable = content.startsWith(\"#!\")\n if (isExecutable) fs.chmodSync(fullPath, \"755\")\n }\nstampFolderParser\n catchAllAtomType stringAtom\n description Create a folder.\n inScope stampFolderParser\n catchAllParser stampFileParser\n pattern \\/$\n javascript\n execute(parentDir) {\n const fs = require(\"fs\")\n const path = require(\"path\")\n const newPath = path.join(parentDir, this.getLine())\n this.root.log(`Creating folder ${newPath}`)\n fs.mkdirSync(newPath, {recursive: true})\n this.forEach(particle => particle.execute(newPath))\n }\nstumpContentParser\n popularity 0.102322\n catchAllAtomType codeAtom\nscrollTableDataParser\n popularity 0.001061\n cue data\n atoms cueAtom\n description Table from inline delimited data.\n baseParser blobParser\nscrollTableDelimiterParser\n popularity 0.001037\n description Set the delimiter.\n cue delimiter\n atoms cueAtom stringAtom\n javascript\n buildHtml() {\n return \"\"\n }\nplainTextLineParser\n popularity 0.000121\n catchAllAtomType stringAtom\n catchAllParser plainTextLineParser"} \ No newline at end of file +const AppConstants = {"parsers":"columnNameAtom\n paint constant\nnewColumnNameAtom\n description Name a derived column.\n paint variable\nconstantAtom\n paint constant\npercentAtom\n paint constant.numeric.float\n extends stringAtom\n // todo: this currently extends from stringAtom b/c scrollsdk needs to be fixed. seems like if extending from number then the hard coded number typescript regex takes precedence over a custom regex\ncountAtom\n extends integerAtom\nyearAtom\n extends integerAtom\npreBuildCommandAtom\n extends cueAtom\n description Give build command atoms their own color.\n paint constant.character.escape\ndelimiterAtom\n description String to use as a delimiter.\n paint string\nbulletPointAtom\n description Any token used as a bullet point such as \"-\" or \"1.\" or \">\"\n paint keyword\ncomparisonAtom\n enum < > <= >= = != includes doesNotInclude empty notEmpty startsWith endsWith\n paint constant\npersonNameAtom\n extends stringAtom\nurlAtom\n paint constant.language\nabsoluteUrlAtom\n paint constant.language\n regex (ftp|https?)://.+\nemailAddressAtom\n extends stringAtom\n paint constant.language\npermalinkAtom\n paint string\n description A string that doesn't contain characters that might interfere with most filesystems. No slashes, for instance.\nfilePathAtom\n paint constant.language\ntagOrUrlAtom\n description An HTML tag or a url.\n paint constant.language\nhtmlAttributesAtom\n paint constant\nhtmlTagAtom\n paint constant.language\n enum div span p a img ul ol li h1 h2 h3 h4 h5 h6 header nav section article aside main footer input button form label select option textarea table tr td th tbody thead tfoot br hr meta link script style title code\nhtmlTypeAtom\n extends stringAtom\n paint constant.language\n enum text password email number tel url search date time datetime-local week month color checkbox radio file submit reset button hidden range\n description HTML input type attribute values.\nclassNameAtom\n paint constant\nhtmlIdAtom\n paint constant\nfontFamilyAtom\n enum Arial Helvetica Verdana Georgia Impact Tahoma Slim\n paint constant\njavascriptAnyAtom\n extends codeAtom\nhtmlAnyAtom\n extends codeAtom\ncolorAtom\n extends codeAtom\nnamedColorAtom\n extends colorAtom\n enum aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkkhaki darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray darkturquoise darkviolet deeppink deepskyblue dimgray dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow honeydew hotpink indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgoldenrodyellow lightgray lightgreen lightpink lightsalmon lightseagreen lightskyblue lightslategray lightsteelblue lightyellow lime limegreen linen magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell sienna silver skyblue slateblue slategray snow springgreen steelblue tan teal thistle tomato turquoise violet wheat white whitesmoke yellow yellowgreen\nbuildCommandAtom\n extends cueAtom\n description Give build command atoms their own color.\n paint constant\ncssAnyAtom\n extends codeAtom\ncssLengthAtom\n extends codeAtom\nreductionTypeAtom\n enum sum mean max min concat first\n paint keyword\ninlineMarkupNameAtom\n description Options to turn on some inline markups.\n enum bold italics code katex none\ntileOptionAtom\n enum default light\nmeasureNameAtom\n extends cueAtom\n // A regex for column names for max compatibility with a broad range of data science tools:\n regex [a-zA-Z][a-zA-Z0-9]*\nabstractConstantAtom\n paint entity.name.tag\njavascriptSafeAlphaNumericIdentifierAtom\n regex [a-zA-Z0-9_]+\n reservedAtoms enum extends function static if while export return class for default require var let const new\nanyAtom\nbaseParsersAtom\n description There are a few classes of special parsers. BlobParsers don't have their subparticles parsed. Error particles always report an error.\n // todo Remove?\n enum blobParser errorParser\n paint variable.parameter\nenumAtom\n paint constant.language\nbooleanAtom\n enum true false\n extends enumAtom\natomParserAtom\n enum prefix postfix omnifix\n paint constant.numeric\natomPropertyNameAtom\n paint variable.parameter\natomTypeIdAtom\n examples integerAtom cueAtom someCustomAtom\n extends javascriptSafeAlphaNumericIdentifierAtom\n enumFromAtomTypes atomTypeIdAtom\n paint storage\nconstantIdentifierAtom\n examples someId myVar\n // todo Extend javascriptSafeAlphaNumericIdentifier\n regex [a-zA-Z]\\w+\n paint constant.other\n description A atom that can be assigned to the parser in the target language.\nconstructorFilePathAtom\nenumOptionAtom\n // todo Add an enumOption top level type, so we can add data to an enum option such as a description.\n paint string\natomExampleAtom\n description Holds an example for a atom with a wide range of options.\n paint string\nextraAtom\n paint invalid\nfileExtensionAtom\n examples js txt doc exe\n regex [a-zA-Z0-9]+\n paint string\nnumberAtom\n paint constant.numeric\nfloatAtom\n extends numberAtom\n regex \\-?[0-9]*\\.?[0-9]*\n paint constant.numeric.float\nintegerAtom\n regex \\-?[0-9]+\n extends numberAtom\n paint constant.numeric.integer\ncueAtom\n description A atom that indicates a certain parser to use.\n paint keyword\njavascriptCodeAtom\nlowercaseAtom\n regex [a-z]+\nparserIdAtom\n examples commentParser addParser\n description This doubles as the class name in Javascript. If this begins with `abstract`, then the parser will be considered an abstract parser, which cannot be used by itself but provides common functionality to parsers that extend it.\n paint variable.parameter\n extends javascriptSafeAlphaNumericIdentifierAtom\n enumFromAtomTypes parserIdAtom\ncueAtom\n paint constant.language\nregexAtom\n paint string.regexp\nreservedAtomAtom\n description A atom that a atom cannot contain.\n paint string\npaintTypeAtom\n enum comment comment.block comment.block.documentation comment.line constant constant.character.escape constant.language constant.numeric constant.numeric.complex constant.numeric.complex.imaginary constant.numeric.complex.real constant.numeric.float constant.numeric.float.binary constant.numeric.float.decimal constant.numeric.float.hexadecimal constant.numeric.float.octal constant.numeric.float.other constant.numeric.integer constant.numeric.integer.binary constant.numeric.integer.decimal constant.numeric.integer.hexadecimal constant.numeric.integer.octal constant.numeric.integer.other constant.other constant.other.placeholder entity entity.name entity.name.class entity.name.class.forward-decl entity.name.constant entity.name.enum entity.name.function entity.name.function.constructor entity.name.function.destructor entity.name.impl entity.name.interface entity.name.label entity.name.namespace entity.name.section entity.name.struct entity.name.tag entity.name.trait entity.name.type entity.name.union entity.other.attribute-name entity.other.inherited-class invalid invalid.deprecated invalid.illegal keyword keyword.control keyword.control.conditional keyword.control.import keyword.declaration keyword.operator keyword.operator.arithmetic keyword.operator.assignment keyword.operator.bitwise keyword.operator.logical keyword.operator.atom keyword.other markup markup.bold markup.deleted markup.heading markup.inserted markup.italic markup.list.numbered markup.list.unnumbered markup.other markup.quote markup.raw.block markup.raw.inline markup.underline markup.underline.link meta meta.annotation meta.annotation.identifier meta.annotation.parameters meta.block meta.braces meta.brackets meta.class meta.enum meta.function meta.function-call meta.function.parameters meta.function.return-type meta.generic meta.group meta.impl meta.interface meta.interpolation meta.namespace meta.paragraph meta.parens meta.path meta.preprocessor meta.string meta.struct meta.tag meta.toc-list meta.trait meta.type meta.union punctuation punctuation.accessor punctuation.definition.annotation punctuation.definition.comment punctuation.definition.generic.begin punctuation.definition.generic.end punctuation.definition.keyword punctuation.definition.string.begin punctuation.definition.string.end punctuation.definition.variable punctuation.section.block.begin punctuation.section.block.end punctuation.section.braces.begin punctuation.section.braces.end punctuation.section.brackets.begin punctuation.section.brackets.end punctuation.section.group.begin punctuation.section.group.end punctuation.section.interpolation.begin punctuation.section.interpolation.end punctuation.section.parens.begin punctuation.section.parens.end punctuation.separator punctuation.separator.continuation punctuation.terminator source source.language-suffix.embedded storage storage.modifier storage.type storage.type keyword.declaration.type storage.type.class keyword.declaration.class storage.type.enum keyword.declaration.enum storage.type.function keyword.declaration.function storage.type.impl keyword.declaration.impl storage.type.interface keyword.declaration.interface storage.type.struct keyword.declaration.struct storage.type.trait keyword.declaration.trait storage.type.union keyword.declaration.union string string.quoted.double string.quoted.other string.quoted.single string.quoted.triple string.regexp string.unquoted support support.class support.constant support.function support.module support.type text text.html text.xml variable variable.annotation variable.function variable.language variable.other variable.other.constant variable.other.member variable.other.readwrite variable.parameter\n paint string\nscriptUrlAtom\nsemanticVersionAtom\n examples 1.0.0 2.2.1\n regex [0-9]+\\.[0-9]+\\.[0-9]+\n paint constant.numeric\ndateAtom\n paint string\nstringAtom\n paint string\natomAtom\n paint constant\n description A non-empty single atom string.\n regex .+\nexampleAnyAtom\n examples lorem ipsem\n // todo Eventually we want to be able to parse correctly the examples.\n paint comment\n extends stringAtom\nblankAtom\ncommentAtom\n paint comment\ncodeAtom\n paint comment\ncolumnNameOrColorAtom\n extends columnNameAtom\nmetaCommandAtom\n extends cueAtom\n description Give meta command atoms their own color.\n paint constant.numeric\n // Obviously this is not numeric. But I like the green color for now.\n We need a better design to replace this \"paint\" concept\n https://github.com/breck7/scrollsdk/issues/186\nvegaDataSetAtom\n paint constant.numeric\n enum airports.csv anscombe.json barley.json birdstrikes.json budget.json budgets.json burtin.json cars.json climate.json co2-concentration.csv countries.json crimea.json descriptions.json disasters.csv driving.json earthquakes.json flare-dependencies.json flare.json flights-10k.json flights-200k.json flights-20k.json flights-2k.json flights-3m.csv flights-5k.json flights-airport.csv gapminder-health-income.csv gapminder.json github.csv graticule.json income.json iowa-electricity.csv iris.json jobs.json la-riots.csv londonBoroughs.json londonCentroids.json londonTubeLines.json lookup_groups.csv lookup_people.csv miserables.json monarchs.json movies.json normal-2d.json obesity.json points.json population.json population_engineers_hurricanes.csv seattle-temps.csv seattle-weather.csv sf-temps.csv sp500.csv stocks.csv udistrict.json unemployment-across-industries.json unemployment.tsv us-10m.json us-employment.csv us-state-capitals.json weather.csv weather.json weball26.json wheat.json windvectors.csv world-110m.json zipcodes.csv\ntagAtom\n extends permalinkAtom\ntagWithOptionalFolderAtom\n description A group name optionally combined with a folder path. Only used when referencing tags, not in posts.\n extends stringAtom\nscrollThemeAtom\n enum roboto gazette dark tufte prestige\n paint constant\nabstractScrollParser\n atoms cueAtom\n javascript\n buildHtmlSnippet(buildSettings) {\n return this.buildHtml(buildSettings)\n }\n buildTxt() {\n return \"\"\n }\n getHtmlRequirements(buildSettings) {\n const {requireOnce} = this\n if (!requireOnce)\n return \"\"\n const set = buildSettings?.alreadyRequired || this.root.alreadyRequired\n if (set.has(requireOnce))\n return \"\"\n set.add(requireOnce)\n return requireOnce + \"\\n\\n\"\n }\nabstractAftertextParser\n description Text followed by markup commands.\n extends abstractScrollParser\n inScope abstractAftertextDirectiveParser abstractAftertextAttributeParser aftertextTagParser abstractCommentParser\n javascript\n get markupInserts() {\n const { originalTextPostLinkify } = this\n return this.filter(particle => particle.isMarkup)\n .map(particle => particle.getInserts(originalTextPostLinkify))\n .filter(i => i)\n .flat()\n }\n get originalText() {\n return this.content ?? \"\"\n }\n get originalTextPostLinkify() {\n const { originalText } = this\n const shouldLinkify = this.get(\"linkify\") === \"false\" || originalText.includes(\"<a \") ? false : true\n return shouldLinkify ? this.replaceNotes(Utils.linkify(originalText)) : originalText\n }\n replaceNotes(originalText) {\n // Skip the replacements if there are no footnotes or the text has none.\n if (!this.root.footnotes.length || !originalText.includes(\"^\")) return originalText\n this.root.footnotes.forEach((note, index) => {\n const needle = note.cue\n const {linkBack} = note\n if (originalText.includes(needle)) originalText = originalText.replace(new RegExp(\"\\\\\" + needle + \"\\\\b\"), `<a href=\"#${note.htmlId}\" class=\"scrollNoteLink\" id=\"${linkBack}\"><sup>${note.label}</sup></a>`)\n })\n return originalText\n }\n get text() {\n const { originalTextPostLinkify, markupInserts } = this\n let adjustment = 0\n let newText = originalTextPostLinkify\n markupInserts.sort((a, b) => {\n if (a.index !== b.index)\n return a.index - b.index\n // If multiple tags start at same index, the tag that closes first should start last. Otherwise HTML breaks.\n if (b.index === b.endIndex) // unless the endIndex is the same as index\n return a.endIndex - b.endIndex\n return b.endIndex - a.endIndex\n })\n markupInserts.forEach(insertion => {\n insertion.index += adjustment\n const consumeStartCharacters = insertion.consumeStartCharacters ?? 0\n const consumeEndCharacters = insertion.consumeEndCharacters ?? 0\n newText = newText.slice(0, insertion.index - consumeEndCharacters) + insertion.string + newText.slice(insertion.index + consumeStartCharacters)\n adjustment += insertion.string.length - consumeEndCharacters - consumeStartCharacters\n })\n return newText\n }\n tag = \"p\"\n get className() {\n if (this.get(\"class\"))\n return this.get(\"class\")\n const classLine = this.getParticle(\"addClass\")\n if (classLine && classLine.applyToParentElement) return classLine.content\n return this.defaultClassName\n }\n defaultClassName = \"scrollParagraph\"\n get isHidden() {\n return this.has(\"hidden\")\n }\n buildHtml(buildSettings) {\n if (this.isHidden) return \"\"\n this.buildSettings = buildSettings\n const { className, styles } = this\n const classAttr = className ? `class=\"${this.className}\"` : \"\"\n const selfClose = this.isSelfClosing ? \" /\" : \"\"\n const tag = this.get(\"tag\") || this.tag\n if (tag === \"none\") // Allow no tag for aftertext in tables\n return this.text\n const id = this.has(\"id\") ? \"\" : `id=\"${this.htmlId}\" ` // always add an html id\n return this.getHtmlRequirements(buildSettings) + `<${tag} ${id}${this.htmlAttributes}${classAttr}${styles}${selfClose}>${this.htmlContents}${this.closingTag}`\n }\n get htmlContents() {\n return this.text\n }\n get closingTag() {\n if (this.isSelfClosing) return \"\"\n const tag = this.get(\"tag\") || this.tag\n return `</${tag}>`\n }\n get htmlAttributes() {\n const attrs = this.filter(particle => particle.isAttribute)\n return attrs.length ? attrs.map(particle => particle.htmlAttributes).join(\" \") + \" \" : \"\"\n }\n get styles() {\n const style = this.getParticle(\"style\")\n const fontFamily = this.getParticle(\"font\")\n const color = this.getParticle(\"color\")\n if (!style && !fontFamily && !color)\n return \"\"\n return ` style=\"${style?.content};${fontFamily?.css};${color?.css}\"`\n }\n get htmlId() {\n return this.get(\"id\") || \"particle\" + this.index\n }\nscrollParagraphParser\n // todo Perhaps rewrite this from scratch and move out of aftertext.\n extends abstractAftertextParser\n catchAllAtomType stringAtom\n description A paragraph.\n boolean suggestInAutocomplete false\n cueFromId\n javascript\n buildHtml(buildSettings) {\n if (this.isHidden) return \"\"\n // Hacky, I know.\n const newLine = this.has(\"inlineMarkupsOn\") ? undefined : this.appendLine(\"inlineMarkupsOn\")\n const compiled = super.buildHtml(buildSettings)\n if (newLine)\n newLine.destroy()\n return compiled\n }\n buildTxt() {\n const subparticles = this.filter(particle => particle.buildTxt).map(particle => particle.buildTxt()).filter(i => i).join(\"\\n\")\n const dateline = this.getParticle(\"dateline\")\n return (dateline ? dateline.day + \"\\n\\n\" : \"\") + (this.originalText || \"\") + (subparticles ? \"\\n \" + subparticles.replace(/\\n/g, \"\\n \") : \"\")\n }\nauthorsParser\n popularity 0.007379\n // multiple authors delimited by \" and \"\n boolean isPopular true\n extends scrollParagraphParser\n description Set author(s) name(s).\n example\n authors Breck Yunits\n https://breckyunits.com Breck Yunits\n // note: once we have mixins in Parsers, lets mixin the below from abstractTopLevelSingleMetaParser\n atoms metaCommandAtom\n javascript\n isTopMatter = true\n isSetterParser = true\n buildHtmlForPrint() {\n // hacky. todo: cleanup\n const originalContent = this.content\n this.setContent(`by ${originalContent}`)\n const html = super.buildHtml()\n this.setContent(originalContent)\n return html\n }\n buildTxtForPrint() {\n return 'by ' + super.buildTxt()\n }\n buildHtml() {\n return \"\"\n }\n buildTxt() {\n return \"\"\n }\n defaultClassName = \"printAuthorsParser\"\nblinkParser\n description Just for fun.\n extends scrollParagraphParser\n example\n blink Carpe diem!\n cue blink\n javascript\n buildHtml() {\n return `<span class=\"scrollBlink\">${super.buildHtml()}</span>\n <script>setInterval(()=>{ Array.from(document.getElementsByClassName(\"scrollBlink\")).forEach(el => el.style.visibility = el.style.visibility === \"hidden\" ? \"visible\" : \"hidden\") }, 500)</script>`\n }\nscrollButtonParser\n extends scrollParagraphParser\n cueFromId\n description A button.\n postParser\n description Post a particle.\n example\n scrollButton Click me\n javascript\n defaultClassName = \"scrollButton\"\n tag = \"button\"\n get htmlAttributes() {\n const link = this.getFromParser(\"scrollLinkParser\")\n const post = this.getParticle(\"post\")\n if (post) {\n const method = \"post\"\n const action = link?.link || \"\"\n const formData = new URLSearchParams({particle: post.subparticlesToString()}).toString()\n return ` onclick=\"fetch('${action}', {method: '${method}', body: '${formData}', headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).then(async (message) => {const el = document.createElement('div'); el.textContent = await message.text(); this.insertAdjacentElement('afterend', el);}); return false;\" `\n }\n return super.htmlAttributes + (link ? `onclick=\"window.location='${link.link}'\"` : \"\")\n }\n getFromParser(parserId) {\n return this.find(particle => particle.doesExtend(parserId))\n }\ncatchAllParagraphParser\n popularity 0.115562\n description A paragraph.\n extends scrollParagraphParser\n boolean suggestInAutocomplete false\n boolean isPopular true\n boolean isArticleContent true\n atoms stringAtom\n javascript\n getErrors() {\n const errors = super.getErrors() || []\n return this.parent.has(\"testStrict\") ? errors.concat(this.makeError(`catchAllParagraphParser should not have any matches when testing with testStrict.`)) : errors\n }\n get originalText() {\n return this.getLine() || \"\"\n }\nscrollCenterParser\n popularity 0.006415\n cue center\n description A centered section.\n extends scrollParagraphParser\n example\n center\n This paragraph is centered.\n javascript\n buildHtml() {\n this.parent.sectionStack.push(\"</center>\")\n return `<center>${super.buildHtml()}`\n }\n buildTxt() {\n return this.content\n }\nabstractIndentableParagraphParser\n extends scrollParagraphParser\n inScope abstractAftertextDirectiveParser abstractAftertextAttributeParser abstractIndentableParagraphParser scrollParagraphParser\n javascript\n get htmlContents() {\n return this.text + this.map(particle => particle.buildHtml())\n .join(\"\\n\")\n .trim()\n }\n buildTxt() {\n return this.getAtom(0) + \" \" + super.buildTxt()\n }\nchecklistTodoParser\n popularity 0.000193\n extends abstractIndentableParagraphParser\n example\n [] Get milk\n description A task todo.\n cue []\n string checked \n javascript\n get text() {\n return `<div style=\"text-indent:${(this.getIndentLevel() - 1) * 20}px;\"><input type=\"checkbox\" ${this.checked} id=\"${this.id}\"><label for=\"${this.id}\">` + super.text + `</label></div>`\n }\n get id() {\n return this.get(\"id\") || \"item\" + this._getUid()\n }\nchecklistDoneParser\n popularity 0.000072\n extends checklistTodoParser\n description A completed task.\n string checked checked\n cue [x]\n example\n [x] get milk\nscrollDivParser\n popularity 0.007524\n description HTML div tag.\n extends abstractIndentableParagraphParser\n cue div\n example\n div\n # Hello world\n p This is a test\n div\n # Deeper\n javascript\n tag = \"div\"\nabstractHtmlElementParser\n extends abstractIndentableParagraphParser\n javascript\n defaultClassName = \"\"\nhtmlSectionParser\n description HTML section tag.\n extends abstractHtmlElementParser\n cue section\n example\n section\n # Hello world\n p This is a test\n section\n # Deeper\n javascript\n tag = \"section\"\nhtmlHeaderParser\n description HTML header tag.\n extends abstractHtmlElementParser\n cue header\n example\n header\n # Title\n javascript\n tag = \"header\"\nhtmlFooterParser\n description HTML footer tag.\n extends abstractHtmlElementParser\n cue footer\n example\n footer\n p Made with love\n javascript\n tag = \"footer\"\nhtmlAsideParser\n description HTML aside tag.\n extends abstractHtmlElementParser\n cue aside\n example\n aside\n h1 Some notes\n javascript\n tag = \"aside\"\nhtmlArticleParser\n description HTML article tag.\n extends abstractHtmlElementParser\n cue article\n example\n article\n h1 My article\n javascript\n tag = \"article\"\nhtmlMainParser\n description HTML main tag.\n extends abstractHtmlElementParser\n cue main\n example\n main\n # Title\n javascript\n tag = \"main\"\nhtmlNavParser\n description HTML nav tag.\n extends abstractHtmlElementParser\n cue nav\n example\n nav\n a Home\n href /\n javascript\n tag = \"nav\"\nhtmlPreParser\n description HTML pre tag.\n extends abstractHtmlElementParser\n cue pre\n example\n pre\n javascript\n tag = \"pre\"\nhtmlUlParser\n description HTML ul tag.\n extends abstractHtmlElementParser\n cue ul\n example\n ul\n li A list\n javascript\n tag = \"ul\"\nhtmlOlParser\n description HTML ol tag.\n extends abstractHtmlElementParser\n cue ol\n example\n ol\n li A list\n javascript\n tag = \"ol\"\nhtmlLiParser\n description HTML li tag.\n extends abstractHtmlElementParser\n cue li\n example\n ol\n li A list\n javascript\n tag = \"li\"\nhtmlImgParser\n description HTML img tag.\n extends abstractHtmlElementParser\n cue img\n example\n img foo.png\n javascript\n tag = \"img\"\n isSelfClosing = true\nhtmlAParser\n description HTML a tag.\n extends abstractHtmlElementParser\n cue a\n example\n a Home\n href /\n javascript\n tag = \"a\"\nhtmlFormParser\n description HTML form tag.\n extends abstractHtmlElementParser\n cue form\n example\n form\n input\n javascript\n tag = \"form\"\nhtmlInputParser\n description HTML input tag.\n extends abstractHtmlElementParser\n cue input\n example\n input\n type text\n placeholder Enter your name\n javascript\n tag = \"input\"\n isSelfClosing = true\nhtmlSelectParser\n description HTML select tag.\n extends abstractHtmlElementParser\n cue select\n example\n select\n option Value 1\n option Value 2\n javascript\n tag = \"select\"\nhtmlOptionParser\n description HTML option tag.\n extends abstractHtmlElementParser\n cue option\n example\n select\n option Choose an option\n option First Option\n javascript\n tag = \"option\"\nhtmlTextareaParser\n description HTML textarea tag.\n extends abstractHtmlElementParser\n cue textarea\n example\n textarea\n placeholder Enter your message\n rows 4\n javascript\n tag = \"textarea\"\nhtmlButtonParser\n description HTML button tag.\n extends abstractHtmlElementParser\n cue button\n example\n button Submit\n type submit\n javascript\n tag = \"button\"\nhtmlLabelParser\n description HTML label tag.\n extends abstractHtmlElementParser\n cue label\n example\n label Name\n for username\n javascript\n tag = \"label\"\nhtmlSpanParser\n description HTML span tag.\n extends abstractHtmlElementParser\n cue span\n example\n span Hello\n javascript\n tag = \"span\"\nhtmlCanvasParser\n description HTML canvas tag.\n extends abstractHtmlElementParser\n cue canvas\n example\n canvas\n javascript\n tag = \"canvas\"\nhtmlIframeParser\n description HTML iframe tag.\n extends abstractHtmlElementParser\n cue iframe\n example\n iframe\n javascript\n tag = \"iframe\"\nh1LiteralParser\n description HTML h1 tag.\n extends abstractHtmlElementParser\n cue h1\n example\n main\n h1 Title\n javascript\n tag = \"h1\"\nh2LiteralParser\n description HTML h2 tag.\n extends abstractHtmlElementParser\n cue h2\n example\n main\n h2 Title\n javascript\n tag = \"h2\"\nh3LiteralParser\n description HTML h3 tag.\n extends abstractHtmlElementParser\n cue h3\n example\n main\n h3 Title\n javascript\n tag = \"h3\"\nh4LiteralParser\n description HTML h4 tag.\n extends abstractHtmlElementParser\n cue h4\n example\n main\n h4 Title\n javascript\n tag = \"h4\"\nlistAftertextParser\n popularity 0.014325\n extends abstractIndentableParagraphParser\n example\n - I had a _new_ thought.\n description A list item.\n cue -\n javascript\n defaultClassName = \"\"\n buildHtml() {\n const {index, parent} = this\n const particleClass = this.constructor\n const isStartOfList = index === 0 || !(parent.particleAt(index - 1) instanceof particleClass)\n const isEndOfList = parent.length === index + 1 || !(parent.particleAt(index + 1) instanceof particleClass)\n const { listType } = this\n return (isStartOfList ? `<${listType} ${this.attributes}>` : \"\") + `${super.buildHtml()}` + (isEndOfList ? `</${listType}>` : \"\")\n }\n get attributes() {\n return \"\"\n }\n tag = \"li\"\n listType = \"ul\"\nabstractCustomListItemParser\n extends listAftertextParser\n javascript\n get requireOnce() {\n return `<style>\\n.${this.constructor.name} li::marker {content: \"${this.cue} \";}\\n</style>`\n }\n get attributes() {\n return `class=\"${this.constructor.name}\"`\n }\norderedListAftertextParser\n popularity 0.004485\n extends listAftertextParser\n description A list item.\n example\n 1. Hello world\n pattern ^\\d+\\. \n javascript\n listType = \"ol\"\n get attributes() { return ` start=\"${this.getAtom(0)}\"`}\npParagraphParser\n popularity 0.001881\n cue p\n extends abstractIndentableParagraphParser\n description A paragraph.\n boolean isArticleContent true\n example\n p I had a _new_ idea.\nquickQuoteParser\n popularity 0.000482\n cue >\n example\n > The only thing we have to fear is fear itself. - FDR\n boolean isPopular true\n extends abstractIndentableParagraphParser\n description A quote.\n javascript\n defaultClassName = \"scrollQuote\"\n tag = \"blockquote\"\nscrollCounterParser\n description Visualize the speed of something.\n extends scrollParagraphParser\n cue counter\n example\n counter 4.5 Babies Born\n atoms cueAtom numberAtom\n javascript\n buildHtml() {\n const line = this.getLine()\n const atoms = line.split(\" \")\n atoms.shift() // drop the counter atom\n const perSecond = parseFloat(atoms.shift()) // get number\n const increment = perSecond/10\n const id = this._getUid()\n this.setLine(`* <span id=\"counter${id}\" title=\"0\">0</span><script>setInterval(()=>{ const el = document.getElementById('counter${id}'); el.title = parseFloat(el.title) + ${increment}; el.textContent = Math.floor(parseFloat(el.title)).toLocaleString()}, 100)</script> ` + atoms.join(\" \"))\n const html = super.buildHtml()\n this.setLine(line)\n return html\n }\nexpanderParser\n popularity 0.000072\n cueFromId\n description An collapsible HTML details tag.\n extends scrollParagraphParser\n example\n expander Knock Knock\n Who's there?\n javascript\n buildHtml() {\n this.parent.sectionStack.push(\"</details>\")\n return `<details>${super.buildHtml()}`\n }\n buildTxt() {\n return this.content\n }\n tag = \"summary\"\n defaultClassName = \"\"\nfootnoteDefinitionParser\n popularity 0.001953\n description A footnote. Can also be used as section notes.\n extends scrollParagraphParser\n boolean isFootnote true\n pattern ^\\^.+$\n // We need to quickLinks back in scope because there is currently a bug in ScrollSDK/parsers where if a parser extending a parent class has a child parser defined, then any regex parsers in the parent class will not be tested unless explicitly included in scope again.\n inScope quickLinkParser\n labelParser\n description If you want to show a custom label for a footnote. Default label is the note definition index.\n cueFromId\n atoms cueAtom\n catchAllAtomType stringAtom\n javascript\n get htmlId() {\n return `note${this.noteDefinitionIndex}`\n }\n get label() {\n // In the future we could allow common practices like author name\n return this.get(\"label\") || `[${this.noteDefinitionIndex}]`\n }\n get linkBack() {\n return `noteUsage${this.noteDefinitionIndex}`\n }\n get text() {\n return `<a class=\"scrollFootNoteUsageLink\" href=\"#noteUsage${this.noteDefinitionIndex}\">${this.label}</a> ${super.text}`\n }\n get noteDefinitionIndex() {\n return this.parent.footnotes.indexOf(this) + 1\n }\n buildTxt() {\n return this.getAtom(0) + \": \" + super.buildTxt()\n }\nabstractHeaderParser\n extends scrollParagraphParser\n example\n # Hello world\n javascript\n buildHtml(buildSettings) {\n if (this.isHidden) return \"\"\n if (this.parent.sectionStack)\n this.parent.sectionStack.push(\"</div>\")\n return `<div class=\"scrollSection\">` + super.buildHtml(buildSettings)\n }\n buildTxt() {\n const line = super.buildTxt()\n return line + \"\\n\" + \"=\".repeat(line.length)\n }\n isHeader = true\nh1Parser\n popularity 0.017918\n description An html h1 tag.\n extends abstractHeaderParser\n example\n # Hello world\n boolean isArticleContent true\n cue #\n boolean isPopular true\n javascript\n tag = \"h1\"\nh2Parser\n popularity 0.005257\n description An html h2 tag.\n extends abstractHeaderParser\n example\n ## Hello world\n boolean isArticleContent true\n cue ##\n boolean isPopular true\n javascript\n tag = \"h2\"\nh3Parser\n popularity 0.001085\n description An html h3 tag.\n extends abstractHeaderParser\n example\n ### Hello world\n boolean isArticleContent true\n cue ###\n javascript\n tag = \"h3\"\nh4Parser\n popularity 0.000289\n description An html h4 tag.\n example\n #### Hello world\n extends abstractHeaderParser\n cue ####\n javascript\n tag = \"h4\"\nscrollQuestionParser\n popularity 0.004244\n description A question.\n extends h4Parser\n cue ?\n example\n ? Why is the sky blue?\n javascript\n defaultClassName = \"scrollQuestion\"\nh5Parser\n description An html h5 tag.\n extends abstractHeaderParser\n example\n ##### Hello world\n cue #####\n javascript\n tag = \"h5\"\nprintTitleParser\n popularity 0.007572\n description Print title.\n extends abstractHeaderParser\n boolean isPopular true\n example\n title Eureka\n printTitle\n cueFromId\n javascript\n buildHtml(buildSettings) {\n // Hacky, I know.\n const {content} = this\n if (content === undefined)\n this.setContent(this.root.title)\n const { permalink } = this.root\n if (!permalink) {\n this.setContent(content) // Restore it as it was.\n return super.buildHtml(buildSettings)\n }\n const newLine = this.appendLine(`link ${permalink}`)\n const compiled = super.buildHtml(buildSettings)\n newLine.destroy()\n this.setContent(content) // Restore it as it was.\n return compiled\n }\n get originalText() {\n return this.content ?? this.root.title ?? \"\"\n }\n defaultClassName = \"printTitleParser\"\n tag = \"h1\"\ncaptionAftertextParser\n popularity 0.003207\n description An image caption.\n cue caption\n example\n map.png\n caption A map.\n extends scrollParagraphParser\n boolean isPopular true\nabstractMediaParser\n extends scrollParagraphParser\n inScope scrollMediaLoopParser scrollAutoplayParser\n int atomIndex 1\n javascript\n buildTxt() {\n return \"\"\n }\n get filename() {\n return this.getAtom(this.atomIndex)\n }\n getAsHtmlAttribute(attr) {\n if (!this.has(attr)) return \"\"\n const value = this.get(attr)\n return value ? `${attr}=\"${value}\"` : attr\n }\n getAsHtmlAttributes(list) {\n return list.map(atom => this.getAsHtmlAttribute(atom)).filter(i => i).join(\" \")\n }\n buildHtml() {\n return `<${this.tag} src=\"${this.filename}\" controls ${this.getAsHtmlAttributes(\"width height loop autoplay\".split(\" \"))}></${this.tag}>`\n }\nscrollMusicParser\n popularity 0.000024\n extends abstractMediaParser\n cue music\n description Play sound files.\n example\n music sipOfCoffee.m4a\n javascript\n buildHtml() {\n return `<audio controls ${this.getAsHtmlAttributes(\"loop autoplay\".split(\" \"))}><source src=\"${this.filename}\" type=\"audio/mpeg\"></audio>`\n }\nquickSoundParser\n popularity 0.000024\n extends scrollMusicParser\n atoms urlAtom\n pattern ^[^\\s]+\\.(mp3|wav|ogg|aac|m4a|flac)\n int atomIndex 0\n example\n sipOfCoffee.m4a\nscrollVideoParser\n popularity 0.000024\n extends abstractMediaParser\n cue video\n example\n video spirit.mp4\n description Play video files.\n widthParser\n cueFromId\n atoms cueAtom integerAtom\n heightParser\n cueFromId\n atoms cueAtom integerAtom\n javascript\n tag = \"video\"\nquickVideoParser\n popularity 0.000024\n extends scrollVideoParser\n example\n spirit.mp4\n atoms urlAtom\n pattern ^[^\\s]+\\.(mp4|webm|avi|mov)\n int atomIndex 0\nquickParagraphParser\n popularity 0.001881\n cue *\n extends scrollParagraphParser\n description A paragraph.\n boolean isArticleContent true\n example\n * I had a _new_ idea.\nscrollStopwatchParser\n description A stopwatch.\n extends scrollParagraphParser\n cue stopwatch\n example\n stopwatch\n atoms cueAtom\n catchAllAtomType numberAtom\n javascript\n buildHtml() {\n const line = this.getLine()\n const id = this._getUid()\n this.setLine(`* <span class=\"scrollStopwatchParser\" id=\"stopwatch${id}\">0.0</span><script>{let startTime = parseFloat(new URLSearchParams(window.location.search).get('start') || 0); document.getElementById('stopwatch${id}').title = startTime; setInterval(()=>{ const el = document.getElementById('stopwatch${id}'); el.title = parseFloat(el.title) + .1; el.textContent = (parseFloat(el.title)).toFixed(1)}, 100)}</script> `)\n const html = super.buildHtml()\n this.setLine(line)\n return html\n }\nthinColumnsParser\n popularity 0.003690\n extends abstractAftertextParser\n cueFromId\n catchAllAtomType integerAtom\n description Thin columns.\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n columnWidth = 35\n columnGap = 20\n buildHtml() {\n const {columnWidth, columnGap, maxColumns} = this\n const maxTotalWidth = maxColumns * columnWidth + (maxColumns - 1) * columnGap\n const stackContents = this.parent.clearSectionStack() // Starting columns always first clears the section stack.\n if (this.singleColumn) this.parent.sectionStack.push(\"</div>\") // Single columns are self-closing after section break.\n return stackContents + `<div class=\"scrollColumns\" style=\"column-width:${columnWidth}ch;column-count:${maxColumns};max-width:${maxTotalWidth}ch;\">`\n }\n get maxColumns() {\n return this.singleColumn ? 1 : parseInt(this.getAtom(1) ?? 10)\n }\nwideColumnsParser\n popularity 0.000386\n extends thinColumnsParser\n description Wide columns.\n javascript\n columnWidth = 90\nwideColumnParser\n popularity 0.003376\n extends wideColumnsParser\n description A wide column section.\n boolean singleColumn true\nmediumColumnsParser\n popularity 0.003376\n extends thinColumnsParser\n description Medium width columns.\n javascript\n columnWidth = 65\nmediumColumnParser\n popularity 0.003376\n extends mediumColumnsParser\n description A medium column section.\n boolean singleColumn true\nthinColumnParser\n popularity 0.003376\n extends thinColumnsParser\n description A thin column section.\n boolean singleColumn true\nendColumnsParser\n popularity 0.007789\n extends abstractAftertextParser\n cueFromId\n description End columns.\n javascript\n buildHtml() {\n return \"</div>\"\n }\n buildHtmlSnippet() {\n return \"\"\n }\nscrollContainerParser\n popularity 0.000096\n cue container\n description A centered HTML div.\n example\n container 600px\n catchAllAtomType cssLengthAtom\n extends abstractAftertextParser\n boolean isHtml true\n javascript\n get maxWidth() {\n return this.atoms[1] || \"1200px\"\n }\n buildHtmlSnippet() {\n return \"\"\n }\n tag = \"div\"\n defaultClassName = \"scrollContainerParser\"\n buildHtml() {\n this.parent.bodyStack.push(\"</div>\")\n return `<style>.scrollContainerParser{width: 100%; box-sizing: border-box; max-width: ${this.maxWidth}; margin: 0 auto;}</style>` + super.buildHtml()\n }\n get text() { return \"\"}\n get closingTag() { return \"\"}\ndebugSourceStackParser\n // useful for debugging\n description Print compilation steps.\n extends abstractAftertextParser\n cueFromId\n example\n printOriginalSource\n javascript\n get sources() {\n const {file} = this.root\n const passNames = [\"codeAtStart\", \"fusedCode\", \"codeAfterMacroPass\"]\n let lastCode = \"\"\n return passNames.map(name => {\n let code = file[name]\n if (lastCode === code)\n code = \"[Unchanged]\"\n lastCode = file[name]\n return {\n name,\n code\n }})\n }\n buildHtml() {\n return `<code class=\"scrollCodeBlock\">${this.buildTxt().replace(/\\</g, \"&lt;\")}</code>`\n }\n buildTxt() {\n return this.sources.map((pass, index) => `Pass ${index + 1} - ${pass.name}\\n========\\n${pass.code}`).join(\"\\n\\n\\n\")\n }\nabstractDinkusParser\n extends abstractAftertextParser\n boolean isDinkus true\n javascript\n buildHtml() {\n return `<div class=\"${this.defaultClass}\"><span>${this.dinkus}</span></div>`\n }\n defaultClass = \"abstractDinkusParser\"\n buildTxt() {\n return this.dinkus\n }\n get dinkus() {\n return this.content || this.getLine()\n }\nhorizontalRuleParser\n popularity 0.000362\n cue ---\n description A horizontal rule.\n extends abstractDinkusParser\n example\n ---\n javascript\n buildHtml() {\n return `<hr>`\n }\nscrollDinkusParser\n popularity 0.010828\n cue ***\n description A dinkus. Breaks section.\n boolean isPopular true\n example\n ***\n extends abstractDinkusParser\n javascript\n dinkus = \"*\"\ncustomDinkusParser\n cue dinkus\n description A custom dinkus.\n extends abstractDinkusParser\nendOfPostDinkusParser\n popularity 0.005740\n extends abstractDinkusParser\n description End of post dinkus.\n boolean isPopular true\n cue ****\n example\n ****\n javascript\n dinkus = \"⁂\"\nabstractIconButtonParser\n extends abstractAftertextParser\n cueFromId\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n return `<style>.abstractIconButtonParser {position:absolute;top:0.25rem; }.abstractIconButtonParser svg {fill: rgba(204,204,204,.8);width:1.875rem;height:1.875rem; padding: 0 7px;} .abstractIconButtonParser:hover svg{fill: #333;}</style><a href=\"${this.link}\" class=\"doNotPrint abstractIconButtonParser\" style=\"${this.style}\">${this.svg}</a>`\n }\ndownloadButtonParser\n popularity 0.006294\n description Link to download/WWS page.\n extends abstractIconButtonParser\n catchAllAtomType urlAtom\n string style position:relative;\n string svg <svg fill=\"#000000\" xmlns=\"http://www.w3.org/2000/svg\" width=\"800px\" height=\"800px\" viewBox=\"0 0 52 52\" enable-background=\"new 0 0 52 52\" xml:space=\"preserve\"><path d=\"M38.6,20.4c-1-6.5-6.7-11.5-13.5-11.5c-7.6,0-13.7,6.1-13.7,13.7c0,0.3,0,0.7,0.1,1c-5,0.4-8.9,4.6-8.9,9.6 c0,5.4,4.3,9.7,9.7,9.7h11.5c-0.8-0.8-8.1-8.1-8.1-8.1c-0.4-0.4-0.4-0.9,0-1.3l1.3-1.3c0.4-0.4,0.9-0.4,1.3,0l3.5,3.5 c0.4,0.4,1.1,0.1,1.1-0.4V21.8c0-0.4,0.5-0.9,1-0.9h1.9c0.5,0,0.9,0.4,0.9,0.9v13.4c0,0.6,0.8,0.8,1.1,0.4l3.5-3.5 c0.4-0.4,0.9-0.4,1.3,0l1.3,1.3c0.4,0.4,0.4,0.9,0,1.3L26,42.9h12.3v0c6.1-0.1,11-5.1,11-11.3C49.4,25.5,44.6,20.6,38.6,20.4z\"/></svg><!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->\n javascript\n get link() {\n return this.content\n }\neditButtonParser\n popularity 0.013963\n description Print badge top right.\n extends abstractIconButtonParser\n catchAllAtomType urlAtom\n // SVG from https://github.com/32pixelsCo/zest-icons\n string svg <svg width=\"800px\" height=\"800px\" viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\"><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M21.1213 2.70705C19.9497 1.53548 18.0503 1.53547 16.8787 2.70705L15.1989 4.38685L7.29289 12.2928C7.16473 12.421 7.07382 12.5816 7.02986 12.7574L6.02986 16.7574C5.94466 17.0982 6.04451 17.4587 6.29289 17.707C6.54127 17.9554 6.90176 18.0553 7.24254 17.9701L11.2425 16.9701C11.4184 16.9261 11.5789 16.8352 11.7071 16.707L19.5556 8.85857L21.2929 7.12126C22.4645 5.94969 22.4645 4.05019 21.2929 2.87862L21.1213 2.70705ZM18.2929 4.12126C18.6834 3.73074 19.3166 3.73074 19.7071 4.12126L19.8787 4.29283C20.2692 4.68336 20.2692 5.31653 19.8787 5.70705L18.8622 6.72357L17.3068 5.10738L18.2929 4.12126ZM15.8923 6.52185L17.4477 8.13804L10.4888 15.097L8.37437 15.6256L8.90296 13.5112L15.8923 6.52185ZM4 7.99994C4 7.44766 4.44772 6.99994 5 6.99994H10C10.5523 6.99994 11 6.55223 11 5.99994C11 5.44766 10.5523 4.99994 10 4.99994H5C3.34315 4.99994 2 6.34309 2 7.99994V18.9999C2 20.6568 3.34315 21.9999 5 21.9999H16C17.6569 21.9999 19 20.6568 19 18.9999V13.9999C19 13.4477 18.5523 12.9999 18 12.9999C17.4477 12.9999 17 13.4477 17 13.9999V18.9999C17 19.5522 16.5523 19.9999 16 19.9999H5C4.44772 19.9999 4 19.5522 4 18.9999V7.99994Z\"/></svg>\n javascript\n get link() {\n return this.content || this.root.editUrl || \"\"\n }\n get style() {\n return this.parent.findParticles(\"editButton\")[0] === this ? \"right:2rem;\": \"position:relative;\"\n }\nemailButtonParser\n popularity 0.006294\n description Email button.\n extends abstractIconButtonParser\n catchAllAtomType emailAddressAtom\n // todo: should just be \"optionalAtomType\"\n string style position:relative;\n string svg <svg viewBox=\"3 5 24 20\" width=\"24\" height=\"20\" xmlns=\"http://www.w3.org/2000/svg\"><g transform=\"matrix(1, 0, 0, 1, 0, -289.0625)\"><path style=\"opacity:1;stroke:none;stroke-width:0.49999997;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1\" d=\"M 5 5 C 4.2955948 5 3.6803238 5.3628126 3.3242188 5.9101562 L 14.292969 16.878906 C 14.696939 17.282876 15.303061 17.282876 15.707031 16.878906 L 26.675781 5.9101562 C 26.319676 5.3628126 25.704405 5 25 5 L 5 5 z M 3 8.4140625 L 3 23 C 3 24.108 3.892 25 5 25 L 25 25 C 26.108 25 27 24.108 27 23 L 27 8.4140625 L 17.121094 18.292969 C 15.958108 19.455959 14.041892 19.455959 12.878906 18.292969 L 3 8.4140625 z \" transform=\"translate(0,289.0625)\" id=\"rect4592\"/></g></svg>\n javascript\n get link() {\n const email = this.content || this.parent.get(\"email\")\n return email ? `mailto:${email}` : \"\"\n }\nhomeButtonParser\n popularity 0.006391\n description Home button.\n extends abstractIconButtonParser\n catchAllAtomType urlAtom\n string style left:2rem;\n string svg <svg role=\"img\" viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M12.7166 3.79541C12.2835 3.49716 11.7165 3.49716 11.2834 3.79541L4.14336 8.7121C3.81027 8.94146 3.60747 9.31108 3.59247 9.70797C3.54064 11.0799 3.4857 13.4824 3.63658 15.1877C3.7504 16.4742 4.05336 18.1747 4.29944 19.4256C4.41371 20.0066 4.91937 20.4284 5.52037 20.4284H8.84433C8.98594 20.4284 9.10074 20.3111 9.10074 20.1665V15.9754C9.10074 14.9627 9.90433 14.1417 10.8956 14.1417H13.4091C14.4004 14.1417 15.204 14.9627 15.204 15.9754V20.1665C15.204 20.3111 15.3188 20.4284 15.4604 20.4284H18.4796C19.0806 20.4284 19.5863 20.0066 19.7006 19.4256C19.9466 18.1747 20.2496 16.4742 20.3634 15.1877C20.5143 13.4824 20.4594 11.0799 20.4075 9.70797C20.3925 9.31108 20.1897 8.94146 19.8566 8.7121L12.7166 3.79541ZM10.4235 2.49217C11.3764 1.83602 12.6236 1.83602 13.5765 2.49217L20.7165 7.40886C21.4457 7.91098 21.9104 8.73651 21.9448 9.64736C21.9966 11.0178 22.0564 13.5119 21.8956 15.3292C21.7738 16.7067 21.4561 18.4786 21.2089 19.7353C20.9461 21.0711 19.7924 22.0001 18.4796 22.0001H15.4604C14.4691 22.0001 13.6655 21.1791 13.6655 20.1665V15.9754C13.6655 15.8307 13.5507 15.7134 13.4091 15.7134H10.8956C10.754 15.7134 10.6392 15.8307 10.6392 15.9754V20.1665C10.6392 21.1791 9.83561 22.0001 8.84433 22.0001H5.52037C4.20761 22.0001 3.05389 21.0711 2.79113 19.7353C2.54392 18.4786 2.22624 16.7067 2.10437 15.3292C1.94358 13.5119 2.00338 11.0178 2.05515 9.64736C2.08957 8.73652 2.55427 7.91098 3.28346 7.40886L10.4235 2.49217Z\"/></svg>\n javascript\n get link() {\n return this.content || this.get(\"link\") || \"index.html\"\n }\ntheScrollButtonParser\n popularity 0.006294\n description WWS button.\n extends abstractIconButtonParser\n string style position:relative;\n string svg <svg xmlns=\"http://www.w3.org/2000/svg\" direction=\"ltr\" width=\"231.52568231268793\" height=\"249.33156169975996\" viewBox=\"297.27169239534896 1273.121785992385 231.52568231268793 249.33156169975996\" stroke-linecap=\"round\" stroke-linejoin=\"round\" data-color-mode=\"dark\" class=\"tl-container tl-theme__force-sRGB tl-theme__dark\" ><defs/><g transform=\"matrix(1, 0, 0, 1, 395.9682, 1413.3618)\" opacity=\"1\"><g transform=\"scale(1)\"><path d=\"M-5.7342,-1.1484 T-5.0182,-4.6536 -2.6672,-12.9768 1.7374,-22.3903 8.4597,-30.0892 16.5455,-35.2796 25.3478,-37.8247 34.4641,-37.2199 43.0676,-33.4606 50.27,-27.1118 55.7861,-19.7972 59.8042,-11.6764 61.6844,-2.3157 60.8049,7.9615 57.3259,17.5954 51.2605,25.5515 41.9451,31.9237 30.6489,36.2084 18.9812,37.6038 8.4915,36.637 -1.3063,34.5174 -10.6869,31.6604 -19.0463,27.0252 -26.0612,20.1562 -31.864,11.1271 -35.2772,1.0066 -35.7963,-9.1933 -35.203,-19.2337 -32.52,-28.3259 -27.3388,-37.4245 -20.2857,-45.7085 -11.787,-53.0395 -2.4314,-58.4864 7.1724,-61.8739 17.5002,-65.6025 28.2859,-68.1034 38.514,-69.1081 48.1844,-69.9134 57.9136,-70.1787 67.4056,-69.5971 76.297,-67.7446 84.5233,-63.97 92.0158,-57.5003 98.1976,-48.5614 102.8839,-38.056 105.9936,-27.6097 107.074,-18.168 107.175,-8.2882 106.6452,1.9768 105.4734,11.7698 104.0279,21.1013 101.7439,31.0445 98.0977,40.6386 92.7822,49.1039 86.2847,57.2337 78.6099,64.7113 69.8339,70.974 61.2863,75.092 52.4283,78.2186 42.5338,80.7945 32.7733,82.6629 22.8568,83.6574 12.2803,83.3538 2.4971,81.4828 -6.3367,78.789 -15.1061,75.8011 -24.259,72.3779 -33.2286,68.991 -41.5707,64.8363 -49.153,59.1909 -55.8375,52.2938 -62.9311,43.9553 -68.4604,34.4882 -71.2761,23.5855 -72.748,12.7452 -73.7673,2.0453 -74.1187,-8.7386 -72.293,-19.3856 -68.7376,-30.4053 -64.12,-39.7852 -59.1825,-47.8931 -53.7695,-56.4512 -48.1998,-65.7676 -43.1389,-74.401 -36.9006,-81.0179 -28.4317,-86.2639 -18.3342,-90.3521 -8.9259,-93.9355 0.1927,-98.7179 9.3551,-103.3537 18.7651,-106.7552 29.7482,-110.3584 40.9287,-113.446 50.87,-115.2231 57.8279,-116.0074 60.4065,-116.0632 A7.8326,7.8326 0 0 1 61.1735,-100.4168 T58.6018,-100.2201 51.1634,-99.3008 41.695,-96.884 32.4044,-94.0187 22.65,-91.382 13.4974,-87.3756 5.0519,-83.1026 -5.0443,-78.6175 -15.7236,-74.4743 -24.6193,-70.2681 -31.274,-62.5903 -36.3827,-53.9362 -41.2833,-46.2905 -46.0679,-38.5161 -50.639,-30.6576 -54.6876,-22.4063 -57.6038,-12.3346 -58.5104,-1.8678 -57.6022,9.4969 -56.0628,20.477 -53.6434,29.0487 -48.8908,36.7517 -42.4075,43.9784 -35.3064,50.6236 -27.3553,55.2062 -17.6884,59.4064 -7.6442,63.6638 2.4427,67.0449 12.7308,69.4843 22.9294,70.2171 33.2547,69.3921 42.4972,67.7384 52.2753,64.8425 61.8649,60.9142 69.5292,56.0828 76.3604,49.5927 82.431,42.3194 87.219,34.619 90.6076,25.5217 92.547,16.0352 93.8703,7.1315 94.4972,-2.5268 94.3672,-13.3681 93.3204,-24.4252 90.5377,-34.1656 85.7321,-43.6441 78.7334,-51.8057 68.7542,-56.0559 57.9857,-57.2713 48.079,-57.0198 38.4535,-56.3204 28.5246,-55.0036 18.6104,-52.4796 9.6402,-49.559 0.7193,-46.2981 -7.1531,-41.3715 -13.708,-34.8957 -19.5435,-26.853 -22.8356,-17.0622 -23.363,-6.5446 -21.9969,3.1439 -17.1086,11.9113 -9.276,18.744 -0.0685,22.6058 9.3636,24.796 19.2422,25.8817 29.052,25.0411 37.9338,21.3502 45.6819,13.8498 49.6675,4.5228 49.2802,-5.1854 45.3277,-14.4455 38.8603,-21.7879 30.5488,-25.7753 21.3356,-24.3975 13.6687,-19.2391 8.8217,-10.9919 6.423,-2.3609 5.7342,1.1484 A5.8481,5.8481 0 0 1 -5.7342,-1.1484 Z\" stroke-linecap=\"round\"/></g></g></svg>\n javascript\n get link() {\n return \"https://wws.scroll.pub\"\n }\nabstractTextLinkParser\n extends abstractAftertextParser\n cueFromId\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildTxt() {\n return this.text\n }\n buildHtml() {\n return `<div class=\"abstractTextLinkParser\"><a href=\"${this.link}\">${this.text}</a></div>`\n }\neditLinkParser\n popularity 0.001206\n extends abstractTextLinkParser\n description Print \"Edit\" link.\n string text Edit\n javascript\n get link() {\n return this.root.editUrl || \"\"\n }\nscrollVersionLinkParser\n popularity 0.006294\n extends abstractTextLinkParser\n string link https://scroll.pub\n description Print Scroll version.\n javascript\n get text() {\n return `Built with Scroll v${this.root.scrollVersion}`\n }\nclassicFormParser\n cue classicForm\n popularity 0.006391\n description Generate input form for ScrollSet.\n extends abstractAftertextParser\n atoms cueAtom\n catchAllAtomType stringAtom\n string script\n <script>\n sendFormViaEmail = form => {\n const mailto = new URL(\"mailto:\")\n const params = []\n const { value, title } = form.querySelector('button[type=\"submit\"]')\n params.push(`subject=${encodeURIComponent(value)}`)\n params.push(`to=${encodeURIComponent(title)}`)\n const oneTextarea = form.querySelector('textarea[title=\"oneTextarea\"]')\n const body = oneTextarea ? codeMirrorInstance.getValue() : Array.from(new FormData(form)).map(([name, value]) => `${name} ${value}`).join(\"\\\\n\")\n params.push(`body=${encodeURIComponent(body)}`)\n mailto.search = params.join(\"&\")\n window.open(mailto.href, '_blank')\n }\n </script>\n string style\n <style> .scrollFormParser {\n font-family: \"Gill Sans\", \"Bitstream Vera Sans\", sans-serif;\n }\n .scrollFormParser input , .scrollFormParser textarea{\n padding: 10px;\n margin-bottom: 10px;\n width: 100%;\n box-sizing: border-box;\n } .scrollFormParser label {\n display: block;\n margin-bottom: 5px;\n }\n </style>\n javascript\n get inputs() {\n return this.root.measures.filter(measure => !measure.IsComputed).map((measure, index) => {\n const {Name, Question, IsRequired, Type} = measure\n const type = Type || \"text\"\n const placeholder = Question\n const ucFirst = Name.substr(0, 1).toUpperCase() + Name.substr(1)\n // ${index ? \"\" : \"autofocus\"}\n let tag = \"\"\n if (Type === \"textarea\")\n tag = `<textarea placeholder=\"${placeholder}\" id=\"${Name}\" name=\"${Name}\" ${IsRequired ? \"required\" : \"\"}></textarea>`\n else\n tag = `<input placeholder=\"${placeholder}\" type=\"${type}\" id=\"${Name}\" name=\"${Name}\" ${IsRequired ? \"required\" : \"\"}>`\n return `<div><label for=\"${Name}\" title=\"${IsRequired ? \"Required\" : \"\"}\">${ucFirst}${IsRequired ? \"*\" : \"\"}:</label>${tag}</div>`\n }).join(\"\\n\")\n }\n buildHtml() {\n const {isEmail, formDestination, callToAction, subject} = this\n return `${this.script}${this.style}<form ${isEmail ? \"onsubmit='sendFormViaEmail(this); return false;'\" : ` method='post' action='${formDestination}'`} class=\"scrollFormParser\">${this.inputs}<button value=\"${subject}\" title=\"${formDestination}\" class=\"scrollButton\" type=\"submit\">${callToAction}</button>${this.footer}</form>`\n }\n get callToAction() {\n return (this.isEmail ? \"Submit via email\" : (this.subject || \"Post\"))\n }\n get isEmail() {\n return this.formDestination.includes(\"@\")\n }\n get formDestination() {\n return this.getAtom(1) || \"\"\n }\n get subject() {\n return this.getAtomsFrom(2)?.join(\" \") || \"\"\n }\n get footer() {\n return \"\"\n }\nscrollFormParser\n extends classicFormParser\n cue scrollForm\n placeholderParser\n atoms cueAtom\n baseParser blobParser\n cueFromId\n single\n valueParser\n atoms cueAtom\n baseParser blobParser\n cueFromId\n single\n nameParser\n description Name for the post submission.\n atoms cueAtom stringAtom\n cueFromId\n single\n description Generate a Scroll Form.\n string copyFromExternal .codeMirror.css .scrollLibs.js .constants.js\n string requireOnce\n <link rel=\"stylesheet\" href=\".codeMirror.css\">\n <script src=\".scrollLibs.js\"></script>\n <script src=\".constants.js\"></script>\n javascript\n get placeholder() {\n return this.getParticle(\"placeholder\")?.subparticlesToString() || \"\"\n }\n get value() {\n return this.getParticle(\"value\")?.subparticlesToString() || \"\"\n }\n get footer() {\n return \"\"\n }\n get name() {\n return this.get(\"name\") || \"particles\"\n }\n get parsersBundle() {\n const parserRegex = /^[a-zA-Z0-9_]+Parser$/gm\n const clone = this.root.clone()\n const parsers = clone.filter(line => parserRegex.test(line.getLine()))\n return \"\\n\" + parsers.map(particle => {\n particle.prependLine(\"boolean suggestInAutocomplete true\")\n return particle.toString()\n }).join(\"\\n\")\n }\n get inputs() {\n const Name = this.name\n return `<textarea title=\"oneTextarea\" rows=\"${Math.min(this.root.measures.length * 2, 30)}\" placeholder=\"${this.placeholder}\" id=\"${Name}\" name=\"${Name}\"></textarea>\n <script id=\"${Name}Parsers\" type=\"text/plain\">${this.parsersBundle}</script>\n <script>{\n const parserRegex = /^[a-zA-Z0-9_]+Parser$/gm\n let {width, height} = document.getElementById('${Name}').getBoundingClientRect();\n const sp = new Particle(AppConstants.parsers)\n sp.filter(particle => particle.getLine().match(parserRegex)).forEach(part => {\n part.appendLine(\"boolean suggestInAutocomplete false\")\n })\n const customScrollParser = new HandParsersProgram(sp.toString() + document.getElementById(\"${Name}Parsers\").textContent).compileAndReturnRootParser()\n codeMirrorInstance = new ParsersCodeMirrorMode(\"custom\", () => customScrollParser, undefined, CodeMirror).register().fromTextAreaWithAutocomplete(document.getElementById(\"${Name}\"), {\n lineWrapping: false,\n lineNumbers: false\n })\n codeMirrorInstance.setSize(width, height);\n codeMirrorInstance.setValue(\\`${this.value}\\`); }</script>`\n }\n buildHtml(buildSettings) {\n return this.getHtmlRequirements(buildSettings) + super.buildHtml()\n }\nloremIpsumParser\n extends abstractAftertextParser\n cueFromId\n description Generate dummy text.\n catchAllAtomType integerAtom\n string placeholder Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n javascript\n get originalText() {\n return this.placeholder.repeat(this.howMany)\n }\n get howMany() {\n return this.getAtom(1) ? parseInt(this.getAtom(1)) : 1\n }\nnickelbackIpsumParser\n extends loremIpsumParser\n string placeholder And one day, I’ll be at the door. And lose your wings to fall in love? To the bottom of every bottle. I’m on the ledge of the eighteenth story. Why must the blind always lead the blind?\nscrollModalParser\n description A modal dialog overlay.\n extends abstractAftertextParser\n boolean isHtml true\n cue modal\n string requireOnce\n <style>\n .scrollModal {\n display: none;\n position: fixed;\n background: transparent;\n padding: 20px;\n left: 3rem;\n top: 3rem;\n right: 3rem;\n bottom: 3rem;\n z-index: 1000;\n font-family: \"IBM Plex Mono\", monospace;\n /* Frosted glass effect */\n background: rgba(0, 0, 0, 0.2);\n backdrop-filter: blur(8px);\n -webkit-backdrop-filter: blur(8px);\n border: 1px solid rgba(255, 255, 255, 0.1);\n box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);\n border-radius: 8px;\n overflow: hidden;\n }\n .scrollModal .closeButton {\n position: absolute;\n top: 10px;\n right: 10px;\n width: 30px;\n height: 30px;\n border: none;\n background: rgba(255, 255, 255, 0.1);\n color: rgba(255, 255, 255, 0.8);\n border-radius: 4px;\n cursor: pointer;\n font-family: \"IBM Plex Mono\", monospace;\n font-size: 18px;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: all 0.2s ease;\n }\n .scrollModal .closeButton:hover {\n background: rgba(255, 255, 255, 0.2);\n color: white;\n }\n </style>\n <script>{\n window.closeModal = modal => {\n modal.style.display = 'none';\n history.pushState(\"\", document.title, window.location.pathname + window.location.search);\n };\n window.openModal = (id, event) => {\n if (event) event.modalJustOpened = true;\n document.querySelector(\"#\" + id).style.display = 'block';\n };\n window.addEventListener('hashchange', () => {\n const modalId = location.hash.slice(1); window.openModal(modalId);\n });\n document.addEventListener('keydown', e => {\n if (e.key === 'Escape') \n document.querySelectorAll('.scrollModal').forEach(closeModal);\n });\n // Check hash on initial load\n document.addEventListener(\"DOMContentLoaded\", e => {\n if (location.hash) \n window.openModal(location.hash.slice(1));\n });\n // Close on outside click\n document.addEventListener('click', e => {\n if (e.modalJustOpened) return;\n const modals = document.querySelectorAll('.scrollModal');\n modals.forEach(modal => {\n if (modal.style.display === 'block' && !modal.contains(e.target)) {\n closeModal(modal);\n }\n });\n });\n }</script>\n javascript\n buildHtml(buildSettings) {\n this.parent.sectionStack.push(\"</div>\")\n return this.getHtmlRequirements(buildSettings) + `<div class=\"scrollModal\" id=\"${this.htmlId}\"><button class=\"closeButton\" onclick=\"closeModal(this.parentElement)\">×</button>`\n }\nprintSnippetsParser\n popularity 0.000338\n // todo: why are we extending AT here and not loops? Is it for class/id etc?\n extends abstractAftertextParser\n cueFromId\n atoms cueAtom\n catchAllAtomType tagWithOptionalFolderAtom\n description Prints snippets matching tag(s).\n example\n printSnippets index\n javascript\n makeSnippet(scrollProgram, buildSettings) {\n const {endSnippetIndex} = scrollProgram\n if (endSnippetIndex === -1) return scrollProgram.buildHtmlSnippet(buildSettings) + scrollProgram.editHtml\n const linkRelativeToCompileTarget = buildSettings.relativePath + scrollProgram.permalink\n const joinChar = \"\\n\"\n const html = scrollProgram\n .map((subparticle, index) => (index >= endSnippetIndex ? \"\" : subparticle.buildHtmlSnippet ? subparticle.buildHtmlSnippet(buildSettings) : subparticle.buildHtml(buildSettings)))\n .filter(i => i)\n .join(joinChar)\n .trim() +\n `<a class=\"scrollContinueReadingLink\" href=\"${linkRelativeToCompileTarget}\">Continue reading...</a>`\n return html\n }\n get files() {\n const thisFile = this.parent.file\n const files = this.root.getFilesByTags(this.content, this.has(\"limit\") ? parseInt(this.get(\"limit\")) : undefined).filter(file => file.file !== thisFile)\n // allow sortBy lastCommit Time\n if (this.get(\"sortBy\") === \"commitTime\") {\n return this.root.sortBy(files, file => file.scrollProgram.lastCommitTime).reverse()\n }\n return files\n }\n buildHtml() {\n const alreadyRequired = this.root.alreadyRequired\n const snippets = this.files.map(file => {\n const buildSettings = {relativePath: file.relativePath, alreadyRequired }\n return `<div class=\"scrollSnippetContainer\">${this.makeSnippet(file.file.scrollProgram, buildSettings)}</div>`\n }).join(\"\\n\\n\")\n return `<div class=\"scrollColumns\" style=\"column-width:35ch;\">${snippets}</div>`\n }\n buildTxt() {\n return this.files.map(file => {\n const {scrollProgram} = file.file\n const {title, date, absoluteLink} = scrollProgram\n const ruler = \"=\".repeat(title.length)\n // Note: I tried to print the description here but the description generating code needs work.\n return `${title}\\n${ruler}\\n${date}\\n${absoluteLink}`\n }).join(\"\\n\\n\")\n }\nscrollNavParser\n popularity 0.000048\n extends printSnippetsParser\n cue fileNav\n description Titles and links in group(s).\n joinParser\n boolean allowTrailingWhitespace true\n cueFromId\n atoms cueAtom\n catchAllAtomType stringAtom\n javascript\n buildHtml() {\n return `<nav class=\"scrollNavParser\">` + this.root.getFilesByTags(this.content).map(file => {\n const { linkTitle, permalink } = file.file.scrollProgram\n return `<a href=\"${permalink}\">${linkTitle}</a>` \n }).join(this.get(\"join\") || \" \") + `</nav>`\n }\nprintFullSnippetsParser\n popularity 0.000048\n extends printSnippetsParser\n cueFromId\n description Print full pages in group(s).\n javascript\n makeSnippet(scrollProgram, buildSettings) {\n return scrollProgram.buildHtmlSnippet(buildSettings) + scrollProgram.editHtml\n }\nprintShortSnippetsParser\n popularity 0.000048\n extends printSnippetsParser\n cueFromId\n description Titles and descriptions in group(s).\n javascript\n makeSnippet(scrollProgram, buildSettings) {\n const { title, permalink, description, timestamp } = scrollProgram\n return `<div><a href=\"${permalink}\">${title}</a><div>${description}...</div><div class=\"subdued\" style=\"text-align:right;\">${this.root.dayjs(timestamp * 1000).format(`MMMM D, YYYY`)}</div></div>`\n }\nprintRelatedParser\n popularity 0.001182\n description Print links to related posts.\n extends printSnippetsParser\n cueFromId\n javascript\n buildHtml() {\n const alreadyRequired = this.root.alreadyRequired\n const list = this.files.map(fileWrapper => {\n const {relativePath, file} = fileWrapper\n const {title, permalink, year} = file.scrollProgram\n return `- ${title}${year ? \" (\" + year + \")\" : \"\"}\\n link ${relativePath + permalink}`\n }).join(\"\\n\")\n const items = this.parent.concat(list)\n const html = items.map(item => item.buildHtml()).join(\"\\n\")\n items.forEach(item => item.destroy())\n return html\n }\nscrollNoticesParser\n extends abstractAftertextParser\n description Display messages in URL query parameters.\n cue notices\n javascript\n buildHtml() {\n const id = this.htmlId\n return `<div id=\"${id}\" class=\"scrollNoticesParser\" style=\"display:none;\"></div><script>(function(){\n const params = new URLSearchParams(window.location.search)\n if (!params.size) return\n document.getElementById('${id}').innerHTML = Array.from(params.entries()).map(([key, value]) => {\n if (key === \"error\") \n return '<div style=\"color:red\">Error: ' + value + '</div>'\n if (key === \"success\")\n return '<div style=\"color:green\">Success: ' + value + '</div>'\n return '<div>' + key + ': ' + value + '</div>'\n }).join(\"\") || \"No query parameters found\"\n document.getElementById('${id}').style.display = \"block\"\n })()</script>`\n }\nabstractAssertionParser\n description Test above particle's output.\n extends abstractScrollParser\n string bindTo previous\n catchAllAtomType codeAtom\n cueFromId\n javascript\n buildHtml() {\n return ``\n }\n get particleToTest() {\n // If the previous particle is also an assertion particle, use the one before that.\n return this.previous.particleToTest ? this.previous.particleToTest : this.previous\n }\n get actual() {return this.particleToTest.buildHtml()}\n getErrors() {\n const {actual, expected} = this\n const errors = super.getErrors()\n if (this.areEqual(actual, expected))\n return errors\n return errors.concat(this.makeError(`'${actual}' did not ${this.kind} '${expected}'`))\n }\n get expected() {\n return this.length ? this.subparticlesToString() : (this.content ? this.content : \"\")\n }\n catchAllParser htmlLineParser\nassertHtmlEqualsParser\n extends abstractAssertionParser\n string kind equal\n example\n <b></b>\n assertHtmlEquals <b></b>\n javascript\n areEqual(actual, expected) {\n return actual === expected\n }\n // todo: why are we having to super here?\n getErrors() { return super.getErrors()}\nassertBuildIncludesParser\n extends abstractAssertionParser\n string kind include\n example\n buildCsv\n assertBuildIncludes virginica\n javascript\n areEqual(actual, expected) {\n return actual.includes(expected)\n }\n get actual() { return this.particleToTest.buildOutput()}\n getErrors() { return super.getErrors()}\nassertHtmlIncludesParser\n extends abstractAssertionParser\n string kind include\n javascript\n areEqual(actual, expected) {\n return actual.includes(expected)\n }\n getErrors() { return super.getErrors()}\nassertHtmlExcludesParser\n extends abstractAssertionParser\n string kind exclude\n javascript\n areEqual(actual, expected) {\n return !actual.includes(expected)\n }\n getErrors() { return super.getErrors()}\nassertIgnoreBelowErrorsParser\n description If you want to ignore any errors in the below particle in automated tests.\n extends abstractScrollParser\n string bindTo next\n cueFromId\nabstractPrintMetaParser\n extends abstractScrollParser\n cueFromId\nprintAuthorsParser\n popularity 0.001664\n description Prints author(s) byline.\n boolean isPopular true\n extends abstractPrintMetaParser\n // todo: we need pattern matching added to sdk to support having no params or a url and personNameAtom\n catchAllAtomType stringAtom\n example\n authors Breck Yunits\n https://breckyunits.com\n printAuthors\n javascript\n buildHtml() {\n return this.parent.getParticle(\"authors\")?.buildHtmlForPrint()\n }\n buildTxt() {\n return this.parent.getParticle(\"authors\")?.buildTxtForPrint()\n }\nprintDateParser\n popularity 0.000434\n extends abstractPrintMetaParser\n // If not present computes the date from the file's ctime.\n description Print published date.\n boolean isPopular true\n example\n date 1/11/2019\n printDate\n javascript\n buildHtml() {\n return `<div class=\"printDateParser\">${this.day}</div>`\n }\n get day() {\n let day = this.content || this.root.date\n if (!day) return \"\"\n return this.root.dayjs(day).format(`MMMM D, YYYY`)\n }\n buildTxt() {\n return this.day\n }\nprintFormatLinksParser\n description Prints links to other formats.\n extends abstractPrintMetaParser\n example\n printFormatLinks\n javascript\n buildHtml() {\n const permalink = this.root.permalink.replace(\".html\", \"\")\n // hacky\n const particle = this.appendSibling(`HTML | TXT`, `class printDateParser\\nlink ${permalink}.html HTML\\nlink ${permalink}.txt TXT\\nstyle text-align:center;`)\n const html = particle.buildHtml()\n particle.destroy()\n return html\n }\n buildTxt() {\n const permalink = this.root.permalink.replace(\".html\", \"\")\n return `HTML | TXT\\n link ${permalink}.html HTML\\n link ${permalink}.txt TXT`\n }\nabstractBuildCommandParser\n extends abstractScrollParser\n cueFromId\n atoms buildCommandAtom\n catchAllAtomType filePathAtom\n inScope slashCommentParser\n javascript\n isTopMatter = true\n buildHtml() {\n return \"\"\n }\n get extension() {\n return this.cue.replace(\"build\", \"\")\n }\n buildOutput() {\n return this.root.compileTo(this.extension)\n }\n get outputFileNames() {\n return this.content?.split(\" \") || [this.root.permalink.replace(\".html\", \".\" + this.extension.toLowerCase())]\n }\n async _buildFileType(extension, options) {\n const {root} = this\n const { fileSystem, folderPath, filename, filePath, path, lodash } = root\n const capitalized = lodash.capitalize(extension)\n const buildKeyword = \"build\" + capitalized\n const {outputFileNames} = this\n for (let name of outputFileNames) {\n try {\n await fileSystem.writeProduct(path.join(folderPath, name), root.compileTo(capitalized))\n root.log(`💾 Built ${name} from ${filename}`)\n } catch (err) {\n console.error(`Error while building '${filePath}' with extension '${extension}'`)\n throw err\n }\n }\n }\nabstractBuildOneCommandParser\n // buildOne and buildTwo are just a dumb/temporary way to have CSVs/JSONs/TSVs build first. Will be merged at some point.\n extends abstractBuildCommandParser\n javascript\n async buildOne(options) { await this._buildFileType(this.extension, options) }\nbuildParsersParser\n popularity 0.000096\n description Compile to Parsers file.\n extends abstractBuildOneCommandParser\nbuildCsvParser\n popularity 0.000096\n example\n buildCsv\n description Compile to CSV file.\n extends abstractBuildOneCommandParser\nbuildTsvParser\n popularity 0.000096\n description Compile to TSV file.\n extends abstractBuildOneCommandParser\nbuildJsonParser\n popularity 0.000096\n description Compile to JSON file.\n extends abstractBuildOneCommandParser\nabstractBuildTwoCommandParser\n extends abstractBuildCommandParser\n javascript\n async buildTwo(options) {\n await this._buildFileType(this.extension, options)\n }\nbuildCssParser\n popularity 0.000048\n description Compile to CSS file.\n extends abstractBuildTwoCommandParser\n example\n buildCss\nbuildHtmlParser\n popularity 0.007645\n description Compile to HTML file.\n extends abstractBuildTwoCommandParser\n boolean isPopular true\n javascript\n async buildTwo(options) {\n await this._copyExternalFiles(options)\n await super.buildTwo(options)\n }\n async _copyExternalFiles(options) {\n if (!this.isNodeJs()) return\n const {root} = this\n const externalFilesCopied = options.externalFilesCopied || {}\n // If this file uses a parser that has external requirements,\n // copy those from external folder into the destination folder.\n const { parsersRequiringExternals, folderPath, fileSystem, filename, parserIdIndex, path, Disk, externalsPath } = root\n if (!externalFilesCopied[folderPath]) externalFilesCopied[folderPath] = {}\n parsersRequiringExternals.forEach(parserId => {\n if (externalFilesCopied[folderPath][parserId]) return\n if (!parserIdIndex[parserId]) return\n parserIdIndex[parserId].map(particle => {\n const externalFiles = particle.copyFromExternal.split(\" \")\n externalFiles.forEach(name => {\n const newPath = path.join(folderPath, name)\n fileSystem.writeProduct(newPath, Disk.read(path.join(externalsPath, name)))\n root.log(`💾 Copied external file needed by ${filename} to ${name}`)\n })\n })\n if (parserId !== \"scrollThemeParser\")\n // todo: generalize when not to cache\n externalFilesCopied[folderPath][parserId] = true\n })\n }\nbuildJsParser\n description Compile to JS file.\n extends abstractBuildTwoCommandParser\nbuildRssParser\n popularity 0.000048\n description Compile to RSS file.\n extends abstractBuildTwoCommandParser\nbuildTxtParser\n popularity 0.007596\n description Compile to TXT file.\n extends abstractBuildTwoCommandParser\n boolean isPopular true\nloadConceptsParser\n // todo: clean this up. just add smarter imports with globs?\n // this currently removes any \"import\" statements.\n description Import all concepts in a folder.\n extends abstractBuildCommandParser\n cueFromId\n atoms preBuildCommandAtom filePathAtom\n javascript\n async load() {\n const { Disk, path, importRegex } = this.root\n const folder = path.join(this.root.folderPath, this.getAtom(1))\n const ONE_BIG_FILE = Disk.getFiles(folder).filter(file => file.endsWith(\".scroll\")).map(Disk.read).join(\"\\n\\n\").replace(importRegex, \"\")\n this.parent.concat(ONE_BIG_FILE)\n //console.log(ONE_BIG_FILE)\n }\n buildHtml() {\n return \"\"\n }\nbuildConceptsParser\n popularity 0.000024\n cueFromId\n description Compile concepts to delimited files.\n extends abstractBuildCommandParser\n sortByParser\n cueFromId\n atoms cueAtom columnNameAtom\n javascript\n async buildOne() {\n const {root} = this\n const { fileSystem, folderPath, filename, path, permalink } = root\n const files = this.getAtomsFrom(1)\n if (!files.length) files.push(permalink.replace(\".html\", \".csv\"))\n const sortBy = this.get(\"sortBy\")\n for (let link of files) {\n await fileSystem.writeProduct(path.join(folderPath, link), root.compileConcepts(link, sortBy))\n root.log(`💾 Built concepts in ${filename} to ${link}`)\n }\n }\nfetchParser\n description Download URL to disk.\n extends abstractBuildCommandParser\n cueFromId\n atoms preBuildCommandAtom urlAtom\n example\n fetch https://breckyunits.com/posts.csv\n fetch https://breckyunits.com/posts.csv renamed.csv\n javascript\n get url() {\n return this.getAtom(1)\n }\n get filename() {\n return this.getAtom(2)\n }\n async load() {\n await this.root.fetch(this.url, this.filename)\n }\n buildHtml() {\n return \"\"\n }\nbuildMeasuresParser\n popularity 0.000024\n cueFromId\n description Compile measures to delimited files.\n extends abstractBuildCommandParser\n sortByParser\n cueFromId\n atoms cueAtom columnNameAtom\n javascript\n async buildOne() {\n const {root} = this\n const { fileSystem, folderPath, filename, path, permalink } = root\n const files = this.getAtomsFrom(1)\n if (!files.length) files.push(permalink.replace(\".html\", \".csv\"))\n const sortBy = this.get(\"sortBy\")\n for (let link of files) {\n await fileSystem.writeProduct(path.join(folderPath, link), root.compileMeasures(link, sortBy))\n root.log(`💾 Built measures in ${filename} to ${link}`)\n }\n }\nbuildPdfParser\n popularity 0.000096\n description Compile to PDF file.\n extends abstractBuildCommandParser\n javascript\n async buildTwo(options) {\n if (!this.isNodeJs()) return \"Only works in Node currently.\"\n const {root} = this\n const { filename } = root\n const outputFile = root.filenameNoExtension + \".pdf\"\n // relevant source code for chrome: https://github.com/chromium/chromium/blob/a56ef4a02086c6c09770446733700312c86f7623/components/headless/command_handler/headless_command_switches.cc#L22\n const command = `/Applications/Google\\\\ Chrome.app/Contents/MacOS/Google\\\\ Chrome --headless --disable-gpu --no-pdf-header-footer --default-background-color=00000000 --no-pdf-background --print-to-pdf=\"${outputFile}\" \"${root.permalink}\"`\n // console.log(`Node.js is running on architecture: ${process.arch}`)\n try {\n const output = require(\"child_process\").execSync(command, { stdio: \"ignore\" })\n root.log(`💾 Built ${outputFile} from ${filename}`)\n } catch (error) {\n console.error(error)\n }\n }\nabstractInlineFileParser\n extends abstractScrollParser\n catchAllAtomType filePathAtom\n catchAllParser scrollFileAddressParser\n string joinChar ;\\n\\n\n string htmlTag script\n javascript\n get files() {\n const inline = this.atoms.slice(1)\n const children = this.map(particle => particle.cue)\n return inline.concat(children)\n }\n get contents() {\n return this.files.map(filename => this.root.readFile(filename)).join(this.joinChar)\n }\n buildHtml() {\n return `<${this.htmlTag}>/* ${this.files.join(\" \")} */\\n${this.contents}</${this.htmlTag}>`\n }\nscrollInlineCssParser\n description Inline CSS from files.\n popularity 0.007211\n extends abstractInlineFileParser\n cue inlineCss\n string joinChar \\n\\n\n string htmlTag style\n javascript\n buildCss() {\n return this.contents\n }\nscrollInlineJsParser\n description Inline JS from files.\n popularity 0.007211\n extends abstractInlineFileParser\n cue inlineJs\n javascript\n buildJs() {\n return this.contents\n }\nabstractTopLevelSingleMetaParser\n description Use these parsers once per file.\n extends abstractScrollParser\n inScope slashCommentParser\n cueFromId\n atoms metaCommandAtom\n javascript\n isTopMatter = true\n isSetterParser = true\n buildHtml() {\n return \"\"\n }\ntestStrictParser\n description Make catchAllParagraphParser = error.\n extends abstractTopLevelSingleMetaParser\nscrollDateParser\n cue date\n popularity 0.006680\n catchAllAtomType dateAtom\n description Set published date.\n extends abstractTopLevelSingleMetaParser\n boolean isPopular true\n example\n date 1/11/2019\n printDate\n Hello world\n dateline\nabstractUrlSettingParser\n extends abstractTopLevelSingleMetaParser\n atoms metaCommandAtom urlAtom\n cueFromId\neditBaseUrlParser\n popularity 0.007838\n description Override edit link baseUrl.\n extends abstractUrlSettingParser\ncanonicalUrlParser\n description Override canonical URL.\n extends abstractUrlSettingParser\nopenGraphImageParser\n popularity 0.000796\n // https://ogp.me/\n // If not defined, Scroll will try to generate it's own using the first image tag on your page.\n description Override Open Graph Image.\n extends abstractUrlSettingParser\nbaseUrlParser\n popularity 0.009188\n description Required for RSS and OpenGraph.\n extends abstractUrlSettingParser\n example\n baseUrl https://hub.scroll.pub/\nrssFeedUrlParser\n popularity 0.008850\n description Set RSS feed URL.\n extends abstractUrlSettingParser\neditUrlParser\n catchAllAtomType urlAtom\n description Override edit link.\n extends abstractTopLevelSingleMetaParser\nsiteOwnerEmailParser\n popularity 0.001302\n description Set email address for site contact.\n extends abstractTopLevelSingleMetaParser\n cue email\n atoms metaCommandAtom emailAddressAtom\nfaviconParser\n popularity 0.001688\n catchAllAtomType stringAtom\n cue favicon\n description Favicon file.\n example\n favicon logo.png\n metatags\n buildHtml\n extends abstractTopLevelSingleMetaParser\nimportOnlyParser\n popularity 0.033569\n // This line will be not be imported into the importing file.\n description Don't build this file.\n cueFromId\n atoms preBuildCommandAtom\n extends abstractTopLevelSingleMetaParser\n javascript\n buildHtml() {\n return \"\"\n }\ninlineMarkupsParser\n popularity 0.000024\n description Set global inline markups.\n extends abstractTopLevelSingleMetaParser\n cueFromId\n example\n inlineMarkups\n * \n // Disable * for bold\n _ u\n // Make _ underline\nhtmlLangParser\n atoms metaCommandAtom stringAtom\n // for the <html lang=\"\"> tag. If not specified will be \"en\". See https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang\n description Override HTML lang attribute.\n extends abstractTopLevelSingleMetaParser\nopenGraphDescriptionParser\n popularity 0.001688\n catchAllAtomType stringAtom\n cue description\n description Description for SEO meta tag.\n extends abstractTopLevelSingleMetaParser\nopenGraphKeywordsParser\n popularity 0.001688\n catchAllAtomType stringAtom\n cue keywords\n description Keywords for SEO meta tag.\n extends abstractTopLevelSingleMetaParser\npermalinkParser\n popularity 0.000265\n description Override output filename.\n extends abstractTopLevelSingleMetaParser\n atoms metaCommandAtom permalinkAtom\nscrollTagsParser\n popularity 0.006801\n cue tags\n description Set tags.\n example\n tags All\n extends abstractTopLevelSingleMetaParser\n catchAllAtomType tagAtom\nscrollTitleParser\n popularity 0.007524\n catchAllAtomType stringAtom\n cue title\n description Set title.\n example\n title Eureka\n printTitle\n extends abstractTopLevelSingleMetaParser\n boolean isPopular true\nscrollLinkTitleParser\n popularity 0.007524\n catchAllAtomType stringAtom\n cue linkTitle\n description Text for links.\n example\n title My blog - Eureka\n linkTitle Eureka\n extends abstractTopLevelSingleMetaParser\nscrollChatParser\n popularity 0.000362\n description A faux text chat conversation.\n catchAllParser chatLineParser\n cue chat\n extends abstractScrollParser\n example\n chat\n Hi\n 👋\n javascript\n buildHtml() {\n return this.map((line, index) => line.asString ? `<div style=\"text-align: ${index % 2 ? \"right\" : \"left\"};\" class=\"scrollChat ${index % 2 ? \"scrollChatRight\" : \"scrollChatLeft\"}\"><span>${line.asString}</span></div>` : \"\").join(\"\")\n }\n buildTxt() {\n return this.subparticlesToString()\n }\nabstractDatatableProviderParser\n description A datatable.\n extends abstractScrollParser\n inScope scrollTableDataParser scrollTableDelimiterParser abstractTableVisualizationParser abstractTableTransformParser h1Parser h2Parser scrollQuestionParser htmlInlineParser scrollBrParser slashCommentParser\n javascript\n get visualizations() {\n return this.topDownArray.filter(particle => particle.isTableVisualization || particle.isHeader || particle.isHtml)\n }\n buildHtml(buildSettings) {\n return this.visualizations.map(particle => particle.buildHtml(buildSettings))\n .join(\"\\n\")\n .trim()\n }\n buildTxt() {\n return this.visualizations.map(particle => particle.buildTxt())\n .join(\"\\n\")\n .trim()\n }\n _coreTable\n get coreTable() {\n if (this._coreTable) return this._coreTable\n const {delimiter, delimitedData} = this\n return []\n }\n get columnNames() {\n return []\n }\nscrollTableParser\n extends abstractDatatableProviderParser\n popularity 0.002133\n cue table\n example\n table\n printTable\n data\n year,count\n 1900,10\n 2000,122\n 2020,23\n catchAllAtomType filePathAtom\n int atomIndex 1\n javascript\n get delimiter() {\n const {filename} = this\n let delimiter = \"\"\n if (filename) {\n const extension = filename.split('?')[0].split(\".\").pop()\n if (extension === \"json\") delimiter = \"json\"\n if (extension === \"particles\") delimiter = \"particles\"\n if (extension === \"csv\") delimiter = \",\"\n if (extension === \"tsv\") delimiter = \"\\t\"\n if (extension === \"ssv\") delimiter = \" \"\n if (extension === \"psv\") delimiter = \"|\"\n }\n if (this.get(\"delimiter\"))\n delimiter = this.get(\"delimiter\")\n else if (!delimiter) {\n const header = this.delimitedData.split(\"\\n\")[0]\n if (header.includes(\"\\t\"))\n delimiter = \"\\t\"\n else if (header.includes(\",\"))\n delimiter = \",\"\n else\n delimiter = \" \"\n }\n return delimiter\n }\n get filename() {\n return this.getAtom(this.atomIndex)\n }\n get coreTable() {\n if (this._coreTable) return this._coreTable\n const {delimiter, delimitedData} = this\n if (delimiter === \"json\") {\n const obj = JSON.parse(delimitedData)\n let rows = []\n // Optimal case: Array of objects\n if (Array.isArray(obj)) { rows = obj}\n else if (!Array.isArray(obj) && typeof obj === \"object\") {\n // Case 2: Nested array under a key\n const arrayKey = Object.keys(obj).find(key => Array.isArray(obj[key]))\n if (arrayKey) rows = obj[arrayKey]\n }\n // Case 3: Array of primitive values\n else if (Array.isArray(obj) && obj.length && typeof obj[0] !== \"object\") {\n rows = obj.map(value => ({ value }))\n }\n this._columnNames = rows.length ? Object.keys(rows[0]) : []\n this._coreTable = rows\n return rows\n }\n else if (delimiter === \"particles\") {\n const d3lib = this.root.d3\n this._coreTable = d3lib.dsvFormat(\",\").parse(new Particle(delimitedData).asCsv, d3lib.autoType)\n } else {\n const d3lib = this.root.d3\n this._coreTable = d3lib.dsvFormat(delimiter).parse(delimitedData, d3lib.autoType)\n }\n this._columnNames = this._coreTable.columns\n delete this._coreTable.columns\n return this._coreTable\n }\n get columnNames() {\n // init coreTable to set columns\n const coreTable = this.coreTable\n return this._columnNames\n }\n async load() {\n if (this.filename)\n await this.root.fetch(this.filename)\n }\n get fileContent() {\n return this.root.readSyncFromFileOrUrl(this.filename)\n }\n get delimitedData() {\n // json csv tsv\n if (this.filename)\n return this.fileContent\n const dataParticle = this.getParticle(\"data\")\n if (dataParticle)\n return dataParticle.subparticlesToString()\n // if not dataparticle and no filename, check [permalink].csv\n if (this.isNodeJs())\n return this.root.readFile(this.root.permalink.replace(\".html\", \"\") + \".csv\")\n return \"\"\n }\nclocParser\n extends scrollTableParser\n description Output results of cloc as table.\n cue cloc\n string copyFromExternal .clocLangs.txt\n javascript\n delimiter = \",\"\n get delimitedData() {\n const { execSync } = require(\"child_process\")\n const results = execSync(this.command).toString().trim()\n const csv = results.split(\"\\n\\n\").pop().replace(/,\\\"github\\.com\\/AlDanial.+/, \"\") // cleanup output\n return csv\n }\n get command(){\n return `cloc --vcs git . --csv --read-lang-def=.clocLangs.txt ${this.content || \"\"}`\n }\nscrollDependenciesParser\n extends scrollTableParser\n description Get files this file depends on.\n cue dependencies\n javascript\n delimiter = \",\"\n get delimitedData() {\n return `file\\n` + this.root.dependencies.join(\"\\n\")\n }\nscrollDiskParser\n extends scrollTableParser\n description Output file into as table.\n cue disk\n javascript\n delimiter = \"json\"\n get delimitedData() {\n return this.isNodeJs() ? this.delimitedDataNodeJs : \"\"\n }\n get delimitedDataNodeJs() {\n const fs = require('fs');\n const path = require('path');\n const {folderPath} = this.root\n const folder = this.content ? path.join(folderPath, this.content) : folderPath\n function getDirectoryContents(dirPath) {\n const directoryContents = [];\n const items = fs.readdirSync(dirPath);\n items.forEach((item) => {\n const itemPath = path.join(dirPath, item);\n const stats = fs.statSync(itemPath);\n directoryContents.push({\n name: item,\n type: stats.isDirectory() ? 'directory' : 'file',\n size: stats.size,\n lastModified: stats.mtime\n });\n });\n return directoryContents;\n }\n return JSON.stringify(getDirectoryContents(folder))\n }\nscrollIrisParser\n extends scrollTableParser\n description Iris dataset from R.A. Fisher.\n cue iris\n example\n iris\n printTable\n scatter\n x SepalLength\n y SepalWidth\n javascript\n delimitedData = this.constructor.iris\nvegaSampleDataParser\n extends scrollTableParser\n description Sample dataset from Vega.\n cue sampleData\n atoms cueAtom vegaDataSetAtom\n example\n sampleData zipcodes.csv\n printTable\n javascript\n get filename() {\n return \"https://ohayo.scroll.pub/ohayo/packages/vega/datasets/\" + this.content\n }\nquickTableParser\n popularity 0.000024\n extends scrollTableParser\n atoms urlAtom\n pattern ^[^\\s]+\\.(tsv|csv|ssv|psv|json)[^\\s]*$\n int atomIndex 0\n javascript\n get dependencies() { return [this.cue]}\nscrollConceptsParser\n description Load concepts as table.\n extends abstractDatatableProviderParser\n cue concepts\n atoms cueAtom\n example\n concepts\n printTable\n javascript\n get coreTable() {\n return this.root.concepts\n }\n get columnNames() {\n return this.root.measures.map(col => col.Name)\n }\nabstractPostsParser\n description Load posts as table.\n extends abstractDatatableProviderParser\n cueFromId\n atoms cueAtom\n catchAllAtomType tagWithOptionalFolderAtom\n javascript\n async load() {\n const dependsOn = this.tags.map(tag => this.root.parseNestedTag(tag)).filter(i => i).map(i => i.folderPath)\n const {fileSystem} = this.root\n for (let folderPath of dependsOn) {\n // console.log(`${this.root.filePath} is loading: ${folderPath} in id '${fileSystem.fusionId}'`)\n await fileSystem.getLoadedFilesInFolder(folderPath, \".scroll\")\n }\n }\n get tags() {\n return this.content?.split(\" \") || []\n }\n get files() {\n const thisFile = this.root.file\n // todo: we can include this file, but just not run asTxt\n const files = this.root.getFilesByTags(this.tags).filter(file => file.file !== thisFile)\n return files\n }\n get coreTable() {\n if (this._coreTable) return this._coreTable\n this._coreTable = this.files.map(file => this.postToRow(file))\n return this._coreTable\n }\n postToRow(file) {\n const {relativePath} = file\n const {scrollProgram} = file.file\n const {title, permalink, asTxt, date, wordCount, minutes} = scrollProgram\n const text = asTxt.replace(/(\\t|\\n)/g, \" \").replace(/</g, \"&lt;\")\n return {\n title, titleLink: relativePath + permalink, text, date, wordCount, minutes\n }\n }\n columnNames = \"title titleLink text date wordCount minutes\".split(\" \")\nscrollPostsParser\n popularity 0.000024\n cue posts\n description Posts as table.\n extends abstractPostsParser\n example\n // Print a search table:\n posts\n printTable\n tableSearch\n // Dump a CSV of blog:\n buildHtml\n buildCsv\n buildJson\nscrollPostsMetaParser\n popularity 0.000024\n cue postsMeta\n description Post meta as table.\n extends abstractPostsParser\n javascript\n columnNames = [\"date\", \"year\", \"title\", \"permalink\", \"authors\", \"tags\", \"wordCount\", \"minutes\"]\n postToRow(file) {\n const {date, year, title, permalink, authors, tags, wordCount, minutes} = file.file.scrollProgram\n return {\n date, year, title, permalink, authors, tags, wordCount, minutes\n }\n }\nprintFeedParser\n popularity 0.000048\n description Print group to RSS.\n extends abstractPostsParser\n example\n printFeed index\n printFeed cars/index\n buildRss\n javascript\n buildRss() {\n const {dayjs} = this.root\n const scrollPrograms = this.files.map(file => file.file.scrollProgram)\n const { title, baseUrl, description } = this.root\n return `<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n <rss version=\"2.0\">\n <channel>\n <title>${title}</title>\n <link>${baseUrl}</link>\n <description>${description}</description>\n <lastBuildDate>${dayjs().format(\"ddd, DD MMM YYYY HH:mm:ss ZZ\")}</lastBuildDate>\n <language>en-us</language>\n ${scrollPrograms.map(program => program.toRss()).join(\"\\n\")}\n </channel>\n </rss>`\n }\n buildTxt() {\n return this.buildRss()\n }\nprintSourceParser\n popularity 0.000024\n description Print source for files in group(s).\n extends printFeedParser\n example\n printSource index\n buildTxt source.txt\n javascript\n buildHtml() {\n const files = this.root.getFilesByTags(this.content).map(file => file.file)\n return `${files.map(file => file.filePath + \"\\n \" + file.codeAtStart.replace(/\\n/g, \"\\n \") ).join(\"\\n\")}`\n }\nprintSiteMapParser\n popularity 0.000072\n extends abstractPostsParser\n description Print text sitemap.\n example\n baseUrl http://test.com\n printSiteMap\n javascript\n buildHtml() {\n const { baseUrl } = this.root\n return this.files.map(file => baseUrl + file.relativePath + file.file.scrollProgram.permalink).join(\"\\n\")\n }\n buildTxt() {\n return this.buildHtml()\n }\n get dependencies() { return this.files}\ncodeParser\n popularity 0.001929\n description A code block.\n catchAllParser lineOfCodeParser\n extends abstractScrollParser\n boolean isPopular true\n example\n code\n two = 1 + 1\n javascript\n buildHtml() {\n return `<code class=\"scrollCodeBlock\">${this.code.replace(/\\</g, \"&lt;\")}</code>`\n }\n buildTxt() {\n return \"```\\n\" + this.code + \"\\n```\"\n }\n get code() {\n return this.subparticlesToString()\n }\n cueFromId\ncodeWithHeaderParser\n popularity 0.000169\n cueFromId\n catchAllAtomType stringAtom\n extends codeParser\n example\n codeWithHeader math.py\n two = 1 + 1\n javascript\n buildHtml() {\n return `<div class=\"codeWithHeader\"><div class=\"codeHeader\">${this.content}</div>${super.buildHtml()}</div>`\n }\n buildTxt() {\n return \"```\" + this.content + \"\\n\" + this.code + \"\\n```\"\n }\ncodeFromFileParser\n popularity 0.000169\n cueFromId\n atoms cueAtom urlAtom\n extends codeWithHeaderParser\n example\n codeFromFile math.py\n javascript\n get code() {\n return this.root.readSyncFromFileOrUrl(this.content)\n }\ncodeWithLanguageParser\n popularity 0.000458\n description Use this to specify the language of the code block, such as csvCode or rustCode.\n extends codeParser\n pattern ^[a-zA-Z0-9_]+Code$\ndebugParsersParser\n description Print the parsers used.\n extends codeParser\n cueFromId\n javascript\n buildParsers() { return this.code}\n get code() {\n let code = new Particle(this.root.definition.toString())\n // Remove comments\n code.filter((line) => line.getLine().startsWith(\"//\")).forEach((particle) => particle.destroy())\n // Remove blank lines\n code = code.toString().replace(/^\\n/gm, \"\")\n return code\n }\nabstractScrollWithRequirementsParser\n extends abstractScrollParser\n cueFromId\n javascript\n buildHtml(buildSettings) {\n return this.getHtmlRequirements(buildSettings) + this.buildInstance()\n }\ncopyButtonsParser\n popularity 0.001471\n extends abstractScrollWithRequirementsParser\n description Copy code widget.\n javascript\n buildInstance() {\n return \"\"\n }\n string requireOnce\n <script>\n document.addEventListener(\"DOMContentLoaded\", () => document.querySelectorAll(\".scrollCodeBlock\").forEach(block =>\n {\n if (!navigator.clipboard) return\n const button = document.createElement(\"span\")\n button.classList.add(\"scrollCopyButton\")\n block.appendChild(button)\n button.addEventListener(\"click\", async () => {\n await navigator.clipboard.writeText(block.innerText)\n button.classList.add(\"scrollCopiedButton\")\n })\n }\n ))\n </script>\nabstractTableVisualizationParser\n extends abstractScrollWithRequirementsParser\n boolean isTableVisualization true\n javascript\n get columnNames() {\n return this.parent.columnNames\n }\nheatrixParser\n cueFromId\n example\n heatrix\n '2007 '2008 '2009 '2010 '2011 '2012 '2013 '2014 '2015 '2016 '2017 '2018 '2019 '2020 '2021 '2022 '2023 '2024\n 4 11 23 37 3 14 12 0 0 0 5 1 2 11 15 10 12 56\n description A heatmap matrix data visualization.\n catchAllParser heatrixCatchAllParser\n extends abstractTableVisualizationParser\n javascript\n buildHtml() {\n // A hacky but simple way to do this for now.\n const advanced = new Particle(\"heatrixAdvanced\")\n advanced.appendLineAndSubparticles(\"table\", \"\\n \" + this.tableData.replace(/\\n/g, \"\\n \"))\n const particle = this.appendSibling(\"heatrixAdvanced\", advanced.subparticlesToString())\n const html = particle.buildHtml()\n particle.destroy()\n return html\n }\n get tableData() {\n const {coreTable} = this.parent\n if (!coreTable)\n return this.subparticlesToString()\n let table = new Particle(coreTable).asSsv\n if (this.parent.cue === \"transpose\") {\n // drop first line after transpose\n const lines = table.split(\"\\n\")\n lines.shift()\n table = lines.join(\"\\n\")\n }\n // detect years and make strings\n const lines = table.split(\"\\n\")\n const yearLine = / \\d{4}(\\s+\\d{4})+$/\n if (yearLine.test(lines[0])) {\n lines[0] = lines[0].replace(/ /g, \" '\")\n table = lines.join(\"\\n\")\n }\n return table\n }\nheatrixAdvancedParser\n popularity 0.000048\n cueFromId\n catchAllParser heatrixCatchAllParser\n extends abstractTableVisualizationParser\n description Advanced heatrix.\n example\n heatrix\n table\n \n %h10; '2007 '2008 '2009\n 12 4 323\n scale\n #ebedf0 0\n #c7e9c0 100\n #a1d99b 400\n #74c476 1600\n javascript\n buildHtml() {\n class Heatrix {\n static HeatrixId = 0\n uid = Heatrix.HeatrixId++\n constructor(program) {\n const isDirective = atom => /^(f|l|w|h)\\d+$/.test(atom) || atom === \"right\" || atom === \"left\" || atom.startsWith(\"http://\") || atom.startsWith(\"https://\") || atom.endsWith(\".html\")\n const particle = new Particle(program)\n this.program = particle\n const generateColorBinningString = (data, colors) => {\n const sortedData = [...data].sort((a, b) => a - b);\n const n = sortedData.length;\n const numBins = colors.length;\n // Calculate the indices for each quantile\n const indices = [];\n for (let i = 1; i < numBins; i++) {\n indices.push(Math.floor((i / numBins) * n));\n }\n // Get the quantile values and round them\n const thresholds = indices.map(index => Math.round(sortedData[index]));\n // Generate the string\n let result = '';\n colors.forEach((color, index) => {\n const threshold = index === colors.length - 1 ? thresholds[index - 1] * 2 : thresholds[index];\n result += `${color} ${threshold}\\n`;\n });\n return result.trim();\n }\n const buildScale = (table) => {\n const numbers = table.split(\"\\n\").map(line => line.split(\" \")).flat().filter(atom => !isDirective(atom)).map(atom => parseFloat(atom)).filter(number => !isNaN(number))\n const colors = ['#ebedf0', '#c7e9c0', '#a1d99b', '#74c476', '#41ab5d', '#238b45', '#005a32'];\n numbers.unshift(0)\n return generateColorBinningString(numbers, colors);\n }\n const table = particle.getParticle(\"table\").subparticlesToString()\n const scale = particle.getParticle(\"scale\")?.subparticlesToString() || buildScale(table)\n const thresholds = []\n const colors = []\n scale.split(\"\\n\").map((line) => {\n const parts = line.split(\" \")\n thresholds.push(parseFloat(parts[1]))\n colors.push(parts[0])\n })\n const colorCount = colors.length\n const colorFunction = (value) => {\n if (isNaN(value)) return \"\" // #ebedf0\n for (let index = 0; index < colorCount; index++) {\n const threshold = thresholds[index]\n if (value <= threshold) return colors[index]\n }\n return colors[colorCount - 1]\n }\n const directiveDelimiter = \";\"\n const getSize = (directives, letter) =>\n directives\n .filter((directive) => directive.startsWith(letter))\n .map((dir) => dir.replace(letter, \"\") + \"px\")[0] ?? \"\"\n this.table = table.split(\"\\n\").map((line) =>\n line\n .trimEnd()\n .split(\" \")\n .map((atom) => {\n const atoms = atom.split(directiveDelimiter).filter((atom) => !isDirective(atom)).join(\"\")\n const directivesInThisAtom = atom\n .split(directiveDelimiter)\n .filter(isDirective)\n const value = parseFloat(atoms)\n const label = atoms.includes(\"'\") ? atoms.split(\"'\")[1] : atoms\n const alignment = directivesInThisAtom.includes(\"right\")\n ? \"right\"\n : directivesInThisAtom.includes(\"left\")\n ? \"left\"\n : \"\"\n const color = colorFunction(value)\n const width = getSize(directivesInThisAtom, \"w\")\n const height = getSize(directivesInThisAtom, \"h\")\n const fontSize = getSize(directivesInThisAtom, \"f\")\n const lineHeight = getSize(directivesInThisAtom, \"l\") || height\n const link = directivesInThisAtom.filter(i => i.startsWith(\"http\") || i.endsWith(\".html\"))[0]\n const style = {\n \"background-color\": color,\n width,\n height,\n \"font-size\": fontSize,\n \"line-height\": lineHeight,\n \"text-align\": alignment,\n }\n Object.keys(style).filter(key => !style[key]).forEach((key) => delete style[key])\n return {\n value,\n label,\n style,\n link,\n }\n })\n )\n }\n get html() {\n const { program } = this\n const cssId = `#heatrix${this.uid}`\n const defaultWidth = \"40px\"\n const defaultHeight = \"40px\"\n const fontSize = \"10px\"\n const lineHeight = defaultHeight\n const style = `<style>\n .heatrixContainer {\n margin: auto;\n }.heatrixRow {white-space: nowrap;}\n ${cssId} .heatrixAtom {\n font-family: arial;\n border-radius: 2px;\n border: 1px solid transparent;\n display: inline-block;\n margin: 1px;\n text-align: center;\n vertical-align: middle;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n .heatrixAtom a {\n color: black;\n }\n ${cssId} .heatrixAtom{\n width: ${defaultWidth};\n height: ${defaultHeight};\n font-size: ${fontSize};\n line-height: ${lineHeight};\n }\n </style>`\n const firstRow = this.table[0]\n return (\n `<div class=\"heatrixContainer\" id=\"heatrix${this.uid}\">${style}` +\n this.table\n .map((row, rowIndex) => {\n if (!rowIndex) return \"\"\n const rowStyle = row[0].style\n return `<div class=\"heatrixRow heatrixRow${rowIndex}\">${row\n .map((atom, columnIndex) => {\n if (!columnIndex) return \"\"\n const columnStyle = firstRow[columnIndex]?.style || {}\n let { value, label, style, link } = atom\n const extendedStyle = Object.assign(\n {},\n rowStyle,\n columnStyle,\n style\n )\n const inlineStyle = Object.keys(extendedStyle)\n .map((key) => `${key}:${extendedStyle[key]};`)\n .join(\"\")\n let valueClass = value ? \" valueAtom\" : \"\"\n const href = link ? ` href=\"${link}\"` : \"\"\n return `<div class=\"heatrixAtom heatrixColumn${columnIndex}${valueClass}\" style=\"${inlineStyle}\"><a title=\"${label}\" ${href}>${label}</a></div>`\n })\n .join(\"\")}</div>`\n })\n .join(\"\\n\") +\n \"</div>\"\n ).replace(/\\n/g, \"\")\n }\n }\n return new Heatrix(this.subparticlesToString().trim()).html\n }\nmapParser\n latParser\n atoms cueAtom floatAtom\n cueFromId\n single\n longParser\n atoms cueAtom floatAtom\n cueFromId\n single\n tilesParser\n atoms cueAtom tileOptionAtom\n cueFromId\n single\n zoomParser\n atoms cueAtom integerAtom\n cueFromId\n single\n geolocateParser\n description Geolocate user.\n atoms cueAtom\n cueFromId\n single\n radiusParser\n atoms cueAtom floatAtom\n cueFromId\n single\n fillOpacityParser\n atoms cueAtom floatAtom\n cueFromId\n single\n fillColorParser\n atoms cueAtom colorAtom\n cueFromId\n single\n colorParser\n atoms cueAtom colorAtom\n cueFromId\n single\n heightParser\n atoms cueAtom floatAtom\n cueFromId\n single\n hoverParser\n atoms cueAtom\n catchAllAtomType colorAtom\n cueFromId\n single\n extends abstractTableVisualizationParser\n description Map widget.\n string copyFromExternal .leaflet.css .leaflet.js .scrollLibs.js\n string requireOnce\n <link rel=\"stylesheet\" href=\".leaflet.css\">\n <script src=\".leaflet.js\"></script>\n <script src=\".scrollLibs.js\"></script>\n javascript\n buildInstance() {\n const height = this.get(\"height\") || 500\n const id = this._getUid()\n const obj = this.toObject()\n const template = {}\n const style = height !== \"full\" ? `height: ${height}px;` : `height: 100%; position: fixed; z-index: -1; left: 0; top: 0; width: 100%;`\n const strs = [\"color\", \"fillColor\"]\n const nums = [\"radius\", \"fillOpacity\"]\n strs.filter(i => obj[i]).forEach(i => template[i] = obj[i])\n nums.filter(i => obj[i]).forEach(i => template[i] = parseFloat(obj[i]))\n const mapId = `map${id}`\n return `<div id=\"${mapId}\" style=\"${style}\"></div>\n <script>\n {\n if (!window.maps) window.maps = {}\n const moveToMyLocation = () => {\n if (!navigator.geolocation) return\n navigator.geolocation.getCurrentPosition((position) => {\n const { latitude, longitude } = position.coords\n window.maps.${mapId}.setView([latitude, longitude])\n L.circleMarker([latitude, longitude], {\n fillOpacity: 0.8,\n radius: 20,\n weight: 4\n })\n .addTo(window.maps.${mapId})\n }, () => {})\n }\n const lat = ${this.get(\"lat\") ?? 37.8}\n const long = ${this.get(\"long\") ?? 4}\n if (${this.has(\"geolocate\")}){\n moveToMyLocation()\n }\n const zoomLevel = ${this.get(\"zoom\") ?? 4}\n const hover = '${this.get(\"hover\") || \"<b>{title}</b><br>{description}\"}'\n const template = ${JSON.stringify(template)}\n const points = ${JSON.stringify((this.parent.coreTable || []).filter(point => point.lat && point.long), undefined, 2)}\n window.maps.${mapId} = L.map(\"map${id}\").setView([lat, long], zoomLevel)\n const map = window.maps.${mapId}\n const tileOptions = {\n \"default\": {\n baseLayer: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',\n attribution: '<a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors'\n },\n light: {\n baseLayer: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png',\n attribution: '<a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors <a href=\"https://carto.com/ attributions\">CARTO</a>'\n },\n }\n const {baseLayer, attribution} = tileOptions.${this.get(\"tiles\") || \"default\"}\n L.tileLayer(baseLayer, {\n attribution,\n maxZoom: 19\n }).addTo(map);\n points.forEach(point => {\n L.circleMarker([point.lat, point.long], {...template, ...Object.fromEntries(\n Object.entries(point).filter(([key, value]) => value !== null)\n )})\n .addTo(map)\n .bindPopup(new Particle(point).evalTemplateString(hover))\n })\n }\n </script>`\n }\nabstractPlotParser\n // Observablehq\n extends abstractTableVisualizationParser\n string copyFromExternal .d3.js .plot.js\n string requireOnce\n <script src=\".d3.js\"></script>\n <script src=\".plot.js\"></script>\n example\n plot\n inScope abstractColumnNameParser\n widthParser\n cueFromId\n atoms cueAtom integerAtom\n heightParser\n cueFromId\n atoms cueAtom integerAtom\n titleParser\n extends abstractPlotLabelParser\n subtitleParser\n extends abstractPlotLabelParser\n captionParser\n extends abstractPlotLabelParser\n javascript\n buildInstance() {\n const id = \"plot\" + this._getUid()\n return `<div id=\"${id}\"></div><script>\n {\n let loadChart = async () => {\n const data = ${this.dataCode}\n const get = (col, index ) => col !== \"undefined\" ? col : (index === undefined ? undefined : Object.keys(data[0])[index])\n document.querySelector(\"#${id}\").append(Plot.plot(${this.plotOptions}))\n }\n loadChart()\n }\n </script>`\n }\n get sortExpression() {\n const sort = this.get(\"sort\")\n if (!sort) return \"\"\n let sort_expr = \"\"\n if (sort.startsWith(\"-\")) {\n // Sort by a value descending\n const sortCol = sort.slice(1)\n sort_expr = `, sort: {x: \"y\", reverse: true}`\n } else if (sort.includes(\" \")) {\n // Fixed order specified\n const order = sort.split(\" \")\n sort_expr = `, sort: {x: (a,b) => {\n const order = ${JSON.stringify(order)};\n return order.indexOf(a) - order.indexOf(b)\n }}`\n } else if (sort === \"asc\") {\n sort_expr = `, sort: {x: \"x\"}`\n } else if (sort === \"desc\") {\n sort_expr = `, sort: {x: \"x\", reverse: true}`\n }\n return sort_expr\n }\n get marks() {\n // just for testing purposes\n return `Plot.rectY({length: 10000}, Plot.binX({y: \"count\"}, {x: d3.randomNormal()}))`\n }\n get dataCode() {\n const {coreTable} = this.parent\n return `d3.csvParse(\\`${new Particle(coreTable).asCsv}\\`, d3.autoType)`\n }\n get plotOptions() {\n return `{\n title: \"${this.get(\"title\") || \"\"}\",\n subtitle: \"${this.get(\"subtitle\") || \"\"}\",\n caption: \"${this.get(\"caption\") || \"\"}\",\n symbol: {legend: ${this.has(\"symbol\")}},\n color: {legend: ${this.has(\"fill\") || this.has(\"stroke\")}},\n grid: ${this.get(\"grid\") !== \"false\"},\n marks: [${this.marks}],\n width: ${this.get(\"width\") || 640},\n height: ${this.get(\"height\") || 400},\n }`\n }\nplotScatterplotParser\n cue scatterplot\n extends abstractPlotParser\n description Scatterplot Widget.\n example\n iris\n scatterplot\n javascript\n get marks() {\n const x = this.get(\"x\")\n const y = this.get(\"y\")\n const text = this.get(\"label\")\n return `Plot.dot(data, {\n x: get(\"${x}\", 0),\n y: get(\"${y}\", 1),\n r: get(\"${this.get(\"radius\")}\"),\n fill: get(\"${this.get(\"fill\")}\"),\n tip: true${this.sortExpression},\n symbol: get(\"${this.get(\"symbol\")}\")} ), Plot.text(data, {x: get(\"${x}\",0), y: get(\"${y}\", 1), text: \"${text}\", dy: -6, lineAnchor: \"bottom\"})`\n }\nplotBarchartParser\n cue barchart\n extends abstractPlotParser\n description Bar chart widget.\n example\n iris\n barchart\n javascript\n get marks() {\n const x = this.get(\"x\")\n const y = this.get(\"y\")\n const text = this.get(\"label\")\n const fill = this.get(\"fill\")\n return `Plot.barY(data, {\n x: get(\"${x}\", 0),\n y: get(\"${y}\", 1),\n fill: get(\"${fill}\"),\n tip: true${this.sortExpression}\n }), Plot.ruleY([0])`\n }\nplotLineChartParser\n cue linechart\n extends abstractPlotParser\n description Line chart widget.\n example\n iris\n linechart\n x SepalLength\n y SepalWidth\n javascript\n get marks() {\n const x = this.get(\"x\")\n const y = this.get(\"y\")\n const stroke = this.get(\"stroke\") || \"steelblue\"\n const strokeWidth = this.get(\"strokeWidth\") || 2\n const strokeLinecap = this.get(\"strokeLinecap\") || \"round\"\n const fill = this.get(\"fill\")\n return `Plot.line(data, {\n x: get(\"${x}\", 0),\n y: get(\"${y}\", 1),\n stroke: \"${stroke}\",\n fill: get(\"${fill}\"),\n strokeWidth: ${strokeWidth},\n strokeLinecap: \"${strokeLinecap}\"${this.sortExpression}\n })`\n }\nsparklineParser\n popularity 0.000024\n description Sparkline widget.\n extends abstractTableVisualizationParser\n example\n sparkline 1 2 3 4 5\n string copyFromExternal .sparkline.js\n string requireOnce <script src=\".sparkline.js\"></script>\n catchAllAtomType numberAtom\n // we need pattern matching\n inScope scrollYParser\n javascript\n buildInstance() {\n const id = \"spark\" + this._getUid()\n const {columnValues} = this\n const start = this.has(\"start\") ? parseInt(this.get(\"start\")) : 0\n const width = this.get(\"width\") || 100\n const height = this.get(\"height\") || 30\n const lineColor = this.get(\"color\") || \"black\"\n return `<span id=\"${id}\"></span><script>new Sparkline(document.getElementById(\"${id}\"), {dotRadius: 0, width: ${width}, height: ${height}, lineColor: \"${lineColor}\", tooltip: (value,index) => ${start} + index + \": \" + value}).draw(${JSON.stringify(columnValues)})</script>`\n }\n get columnValues() {\n if (this.content)\n return this.content.split(\" \").map(str => parseFloat(str))\n const {coreTable} = this.parent\n if (coreTable) {\n const columnName = this.get(\"y\") || Object.keys(coreTable[0]).find(key => typeof coreTable[0][key] === 'number')\n return coreTable.map(row => row[columnName])\n }\n }\nprintColumnParser\n popularity 0.000024\n description Print one column\n extends abstractTableVisualizationParser\n example\n printColumn tags\n catchAllAtomType columnNameAtom\n joinParser\n boolean allowTrailingWhitespace true\n cueFromId\n atoms cueAtom\n catchAllAtomType stringAtom\n javascript\n buildHtml() {\n return this.columnValues.join(this.join)\n }\n buildTxt() {\n return this.columnValues.join(this.join)\n }\n get join() {\n return this.get(\"join\") || \"\\n\"\n }\n get columnName() {\n return this.atoms[1]\n }\n get columnValues() {\n return this.parent.coreTable.map(row => row[this.columnName])\n }\nprintTableParser\n popularity 0.001085\n cueFromId\n description Print table.\n extends abstractTableVisualizationParser\n javascript\n get tableHeader() {\n return this.columns.filter(col => !col.isLink).map(column => `<th>${column.name}</th>\\n`)\n }\n get columnNames() {\n return this.parent.columnNames\n }\n buildJson() {\n return JSON.stringify(this.coreTable, undefined, 2)\n }\n buildCsv() {\n return new Particle(this.coreTable).asCsv\n }\n buildTsv() {\n return new Particle(this.coreTable).asTsv\n }\n get columns() {\n const {columnNames} = this\n return columnNames.map((name, index) => {\n const isLink = name.endsWith(\"Link\")\n const linkIndex = columnNames.indexOf(name + \"Link\")\n return {\n name,\n isLink,\n linkIndex\n }\n })\n }\n toRow(row) {\n const {columns} = this\n const atoms = columns.map(col => row[col.name])\n let str = \"\"\n let column = 0\n const columnCount = columns.length\n while (column < columnCount) {\n const col = columns[column]\n column++\n const content = ((columnCount === column ? atoms.slice(columnCount - 1).join(\" \") : atoms[column - 1]) ?? \"\").toString()\n if (col.isLink) continue\n const isTimestamp = col.name.toLowerCase().includes(\"time\") && /^\\d{10}(\\d{3})?$/.test(content)\n const text = isTimestamp ? new Date(parseInt(content.length === 10 ? content * 1000 : content)).toLocaleString() : content\n let tagged = text\n const link = atoms[col.linkIndex]\n const isUrl = content.match(/^https?\\:[^ ]+$/)\n if (col.linkIndex > -1 && link) tagged = `<a href=\"${link}\">${text}</a>`\n else if (col.name.endsWith(\"Url\")) tagged = `<a href=\"${content}\">${col.name.replace(\"Url\", \"\")}</a>`\n else if (isUrl) tagged = `<a href=\"${content}\">${text}</a>`\n str += `<td>${tagged}</td>\\n`\n }\n return str\n }\n get coreTable() {\n return this.parent.coreTable\n }\n get tableBody() {\n return this.coreTable\n .map(row => `<tr>${this.toRow(row)}</tr>`)\n .join(\"\\n\")\n }\n buildHtml() {\n return `<table id=\"table${this._getUid()}\" class=\"scrollTable\">\n <thead><tr>${this.tableHeader.join(\"\\n\")}</tr></thead>\n <tbody>${this.tableBody}</tbody>\n </table>`\n }\n buildTxt() {\n return this.parent.delimitedData || new Particle(this.coreTable).asCsv\n }\nkatexParser\n popularity 0.001592\n extends abstractScrollWithRequirementsParser\n catchAllAtomType codeAtom\n catchAllParser lineOfCodeParser\n example\n katex\n \\text{E} = \\text{T} / \\text{A}!\n description KaTex widget for typeset math.\n string copyFromExternal .katex.min.css .katex.min.js\n string requireOnce\n <link rel=\"stylesheet\" href=\".katex.min.css\">\n <script defer src=\".katex.min.js\"></script>\n <script>\n document.addEventListener(\"DOMContentLoaded\", () => document.querySelectorAll(\".scrollKatex\").forEach(el =>\n {\n katex.render(el.innerText, el, {\n throwOnError: false\n });\n }\n ))\n </script>\n javascript\n buildInstance() {\n const id = this._getUid()\n const content = this.content === undefined ? \"\" : this.content\n return `<div class=\"scrollKatex\" id=\"${id}\">${content + this.subparticlesToString()}</div>`\n }\n buildTxt() {\n return ( this.content ? this.content : \"\" )+ this.subparticlesToString()\n }\nhelpfulNotFoundParser\n popularity 0.000048\n extends abstractScrollWithRequirementsParser\n catchAllAtomType filePathAtom\n string copyFromExternal .helpfulNotFound.js\n description Helpful not found widget.\n javascript\n buildInstance() {\n return `<style>#helpfulNotFound{margin: 100px 0;}</style><h1 id=\"helpfulNotFound\"></h1><script defer src=\"/.helpfulNotFound.js\"></script><script>document.addEventListener(\"DOMContentLoaded\", () => new NotFoundApp('${this.content}'))</script>`\n }\nslideshowParser\n // Left and right arrows navigate.\n description Slideshow widget. *** delimits slides.\n extends abstractScrollWithRequirementsParser\n string copyFromExternal .jquery-3.7.1.min.js .slideshow.js\n example\n slideshow\n Why did the cow cross the road?\n ***\n Because it wanted to go to the MOOOO-vies.\n ***\n THE END\n ****\n javascript\n buildHtml() {\n return `<style>html {font-size: var(--scrollBaseFontSize, 28px);} body {margin: auto; width: 500px;}.slideshowNav{text-align: center; margin-bottom:20px; font-size: 24px;color: rgba(204,204,204,.8);} a{text-decoration: none; color: rgba(204,204,204,.8);}</style><script defer src=\".jquery-3.7.1.min.js\"></script><div class=\"slideshowNav\"></div><script defer src=\".slideshow.js\"></script>`\n }\ntableSearchParser\n popularity 0.000072\n extends abstractScrollWithRequirementsParser\n string copyFromExternal .jquery-3.7.1.min.js .datatables.css .dayjs.min.js .datatables.js .tableSearch.js\n string requireOnce\n <script defer src=\".jquery-3.7.1.min.js\"></script>\n <style>.dt-search{font-family: \"SF Pro\", \"Helvetica Neue\", \"Segoe UI\", \"Arial\";}</style>\n <link rel=\"stylesheet\" href=\".datatables.css\">\n <script defer src=\".datatables.js\"></script>\n <script defer src=\".dayjs.min.js\"></script>\n <script defer src=\".tableSearch.js\"></script>\n // adds to all tables on page\n description Table search and sort widget.\n javascript\n buildInstance() {\n return \"\"\n }\nabstractCommentParser\n description Prints nothing.\n catchAllAtomType commentAtom\n atoms commentAtom\n extends abstractScrollParser\n baseParser blobParser\n string bindTo next\n javascript\n buildHtml() {\n return ``\n }\n catchAllParser commentLineParser\ncommentParser\n popularity 0.000193\n extends abstractCommentParser\n cueFromId\ncounterpointParser\n description Counterpoint comment. Prints nothing.\n extends commentParser\n cue !\nslashCommentParser\n popularity 0.005643\n extends abstractCommentParser\n cue //\n boolean isPopular true\n description A comment. Prints nothing.\nthanksToParser\n description Acknowledgements comment. Prints nothing.\n extends abstractCommentParser\n cueFromId\nscrollClearStackParser\n popularity 0.000096\n cue clearStack\n description Clear body stack.\n extends abstractScrollParser\n boolean isHtml true\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n return this.root.clearBodyStack().trim()\n }\ncssParser\n popularity 0.007211\n extends abstractScrollParser\n description A style tag.\n example\n css\n body { color: red;}\n cueFromId\n catchAllParser cssLineParser\n catchAllAtomType cssAnyAtom\n javascript\n buildHtml() {\n return `<style>${this.css}</style>`\n }\n get css() {\n return this.content ?? this.subparticlesToString()\n }\n buildCss() {\n return this.css\n }\nscrollBackgroundColorParser\n description Quickly set CSS background.\n popularity 0.007211\n extends abstractScrollParser\n cue background\n catchAllAtomType cssAnyAtom\n example\n background red\n javascript\n buildHtml() {\n return `<style>html, body { background: ${this.content};}</style>`\n }\nscrollFontColorParser\n description Quickly set CSS font-color.\n popularity 0.007211\n extends abstractScrollParser\n cue color\n catchAllAtomType cssAnyAtom\n javascript\n buildHtml() {\n return `<style>html, body { color: ${this.content};}</style>`\n }\nscrollFontParser\n description Quickly set font family.\n popularity 0.007211\n extends abstractScrollParser\n cue font\n atoms cueAtom fontFamilyAtom\n catchAllAtomType cssAnyAtom\n example\n font Slim\n javascript\n buildHtml() {\n const font = this.content === \"Slim\" ? \"Helvetica Neue; font-weight:100;\" : this.content\n return `<style>html, body, h1,h2,h3 { font-family: ${font};}</style>`\n }\nabstractQuickIncludeParser\n popularity 0.007524\n extends abstractScrollParser\n atoms urlAtom\n javascript\n get dependencies() { return [this.filename]}\n get filename() {\n return this.getAtom(0)\n }\nquickCssParser\n popularity 0.007524\n description Make a CSS tag.\n extends abstractQuickIncludeParser\n example\n style.css\n atoms urlAtom\n pattern ^[^\\s]+\\.(css)$\n javascript\n buildHtml() {\n return `<link rel=\"stylesheet\" type=\"text/css\" href=\"${this.filename}\">`\n }\n buildHtmlSnippet() {\n return \"\"\n }\nquickIncludeHtmlParser\n popularity 0.007524\n description Include an HTML file.\n extends abstractQuickIncludeParser\n example\n body.html\n atoms urlAtom\n pattern ^[^\\s]+\\.(html|htm)$\n javascript\n buildHtml() {\n return this.root.readFile(this.filename)\n }\nquickScriptParser\n popularity 0.007524\n description Make a Javascript tag.\n extends abstractQuickIncludeParser\n atoms urlAtom\n example\n script.js\n pattern ^[^\\s]+\\.(js)$\n javascript\n attr = \"\"\n buildHtml() {\n return `<script ${this.attr} src=\"${this.filename}\"></script>`\n }\n buildHtmlSnippet() {\n return \"\"\n }\nquickModuleScriptParser\n description Make a Javascript module tag.\n extends quickScriptParser\n example\n script.mjs\n pattern ^[^\\s]+\\.(mjs)$\n javascript\n attr = 'type=\"module\"'\nscrollDashboardParser\n popularity 0.000145\n description Key stats in large font.\n catchAllParser lineOfCodeParser\n cue dashboard\n extends abstractScrollParser\n example\n dashboard\n #2 Popularity\n 30 Years Old\n $456 Revenue\n javascript\n get tableBody() {\n const items = this.topDownArray\n let str = \"\"\n for (let i = 0; i < items.length; i = i + 3) {\n str += this.makeRow(items.slice(i, i + 3))\n }\n return str\n }\n makeRow(items) {\n return `<tr>` + items.map(particle => `<td>${particle.cue}<span>${particle.content}</span></td>`).join(\"\\n\") + `</tr>\\n`\n }\n buildHtml() {\n return `<table class=\"scrollDashboard\">${this.tableBody}</table>`\n }\n buildTxt() {\n return this.subparticlesToString()\n }\nbelowAsCodeParser\n popularity 0.000651\n description Print code below.\n string bindTo next\n extends abstractScrollParser\n catchAllAtomType integerAtom\n example\n belowAsCode\n iris\n printTable\n cueFromId\n javascript\n method = \"next\"\n get selectedParticles() {\n const { method } = this\n let code = \"\"\n let particles = []\n let next = this[method]\n let {howMany} = this\n while (howMany) {\n particles.push(next)\n next = next[method]\n howMany--\n }\n if (this.reverse) particles.reverse()\n return particles\n }\n get code() {\n return this.selectedParticles.map(particle => particle.asString).join(\"\\n\")\n }\n reverse = false\n buildHtml() {\n return `<code class=\"scrollCodeBlock\">${this.code.replace(/\\</g, \"&lt;\")}</code>`\n }\n get howMany() {\n let howMany = parseInt(this.getAtom(1))\n if (!howMany || isNaN(howMany)) howMany = 1\n return howMany\n }\ndebugBelowParser\n description Inspect particle below.\n extends belowAsCodeParser\n string copyFromExternal .debug.css\n javascript\n get code() {\n const mapFn = particle => {\n const atomTypes = particle.lineAtomTypes.split(\" \")\n return `<div class=\"debugParticle\"><span class=\"debugParticleId\">${particle.constructor.name}</span>${particle.atoms.map((atom, index) => `<span class=\"debugAtom\">${atom}<span class=\"debugAtomType\">${atomTypes[index]}</span></span>`).join(\" \")}${(particle.length ? `<br><div class=\"debugSubparticles\">` + particle.map(mapFn).join(\"<br>\") + `</div>` : \"\")}</div>`}\n return this.selectedParticles.map(mapFn).join(\"<br>\")\n }\n buildHtml() {\n return `<link rel=\"stylesheet\" href=\".debug.css\">` + this.code\n }\n buildTxt() {\n const mapFn = particle => {\n const atomTypes = particle.lineAtomTypes.split(\" \")\n return `${particle.constructor.name} ${particle.atoms.map((atom, index) => `${atomTypes[index]}:${atom}`).join(\" \")}${(particle.length ? `\\n ` + particle.map(mapFn).join(\"\\n\") + `` : \"\")}`}\n return this.selectedParticles.map(mapFn).join(\"\\n\")\n }\n buildParsers() {return this.buildTxt()}\ndebugAboveParser\n description Inspect particle above.\n extends debugBelowParser\n string bindTo previous\n javascript\n method = \"previous\"\n reverse = true\ndebugAllParser\n description Inspect entire document.\n extends debugBelowParser\n javascript\n get selectedParticles() { return this.root.getSubparticles()}\nbelowAsCodeUntilParser\n description Print code above until match.\n extends belowAsCodeParser\n catchAllAtomType codeAtom\n example\n belowAsCode\n counter 1 second\n javascript\n get howMany() {\n let howMany = 1\n const query = this.content\n let particle = this.next\n while (particle !== this) {\n if (particle.getLine().startsWith(query))\n return howMany\n particle = particle.next\n howMany++\n }\n return howMany\n }\naboveAsCodeParser\n popularity 0.000482\n string bindTo previous\n description Print code above.\n example\n counter 1 second\n aboveAsCode\n extends belowAsCodeParser\n javascript\n method = \"previous\"\n reverse = true\nbelowAsHtmlParser\n extends belowAsCodeParser\n description Displays html output of next particle in a code block.\n cueFromId\n example\n belowAsHtml\n # Hello world\n javascript\n get code() {\n return this.selectedParticles.filter(p => p.buildHtml).map(p => p.buildHtml()).join(\"\\n\")\n }\naboveAsHtmlParser\n description Displays html output of previous particle in a code block.\n extends belowAsHtmlParser\n example\n # Hello world\n aboveAsHtml\n javascript\n method = \"previous\"\n reverse = true\nscrollDefParser\n popularity 0.004244\n description Parser short form.\n pattern ^[a-zA-Z0-9_]+Def\n extends abstractScrollParser\n catchAllAtomType stringAtom\n example\n urlDef What is the URL?\n javascript\n buildParsers(index) {\n const idStuff = index ? \"\" : `boolean isMeasure true\n boolean isMeasureRequired true\n boolean isConceptDelimiter true`\n const description = this.content\n const cue = this.cue.replace(\"Def\", \"\")\n const sortIndex = 1 + index/10\n return `${cue}DefParser\n cue ${cue}\n extends abstractStringMeasureParser\n description ${description}\n float sortIndex ${sortIndex}\n ${idStuff}`.trim()\n }\nhakonParser\n cueFromId\n extends abstractScrollParser\n description Compile Hakon to CSS.\n catchAllParser hakonContentParser\n javascript\n buildHtml() {\n return `<style>${this.css}</style>`\n }\n get css() {\n const {hakonParser} = this.root\n return new hakonParser(this.subparticlesToString()).compile()\n }\n buildCss() {\n return this.css\n }\nhamlParser\n popularity 0.007524\n description HTML tag via HAML syntax.\n extends abstractScrollParser\n atoms urlAtom\n catchAllAtomType stringAtom\n pattern ^%?[\\w\\.]+#[\\w\\.]+ *\n javascript\n get tag() {\n return this.atoms[0].split(/[#\\.]/).shift().replace(\"%\", \"\")\n }\n get htmlId() {\n const idMatch = this.atoms[0].match(/#([\\w-]+)/)\n return idMatch ? idMatch[1] : \"\"\n }\n get htmlClasses() {\n return this.atoms[0].match(/\\.([\\w-]+)/g)?.map(cls => cls.slice(1)) || [];\n }\n buildHtml() {\n const {htmlId, htmlClasses, content, tag} = this\n this.parent.sectionStack.unshift(`</${tag}>`)\n const attrs = [htmlId ? ' id=\"' + htmlId + '\"' : \"\", htmlClasses.length ? ' class=\"' + htmlClasses.join(\" \") + '\"' : \"\"].join(\" \").trim()\n return `<${tag}${attrs ? \" \" + attrs : \"\"}>${content || \"\"}`\n }\n buildTxt() {\n return this.content\n }\nhamlTagParser\n // Match plain tags like %h1\n extends hamlParser\n pattern ^%[^#]+$\nabstractHtmlParser\n extends abstractScrollParser\n catchAllParser htmlLineParser\n catchAllAtomType htmlAnyAtom\n javascript\n buildHtml() {\n return `${this.content ?? \"\"}${this.subparticlesToString()}`\n }\n buildTxt() {\n return \"\"\n }\nhtmlParser\n popularity 0.000048\n extends abstractHtmlParser\n description HTML one liners or blocks.\n cueFromId\nhtmlInlineParser\n popularity 0.005788\n extends abstractHtmlParser\n atoms htmlAnyAtom\n boolean isHtml true\n example\n <h1>Inline HTML</h1>\n pattern ^<\n description Inline HTML.\n boolean isPopular true\n javascript\n buildHtml() {\n return `${this.getLine() ?? \"\"}${this.subparticlesToString()}`\n }\nscrollBrParser\n popularity 0.000096\n cue br\n example\n br 2\n description A break.\n extends abstractScrollParser\n catchAllAtomType integerAtom\n boolean isHtml true\n javascript\n buildHtml() {\n return `<br>`.repeat(parseInt(this.getAtom(1) || 1))\n }\niframesParser\n popularity 0.000121\n cueFromId\n catchAllAtomType urlAtom\n extends abstractScrollParser\n description An iframe(s).\n example\n iframes frame.html\n javascript\n buildHtml() {\n return this.atoms.slice(1).map(url => `<iframe src=\"${url}\" frameborder=\"0\"></iframe>`).join(\"\\n\")\n }\nabstractCaptionedParser\n extends abstractScrollParser\n atoms cueAtom urlAtom\n inScope captionAftertextParser slashCommentParser\n cueFromId\n javascript\n buildHtml(buildSettings) {\n const caption = this.getParticle(\"caption\")\n const captionFig = caption ? `<figcaption>${caption.buildHtml()}</figcaption>` : \"\"\n const {figureWidth} = this\n const widthStyle = figureWidth ? `width:${figureWidth}px; margin: auto;` : \"\"\n const float = this.has(\"float\") ? `margin: 20px; float: ${this.get(\"float\")};` : \"\"\n return `<figure class=\"scrollCaptionedFigure\" style=\"${widthStyle + float}\">${this.getFigureContent(buildSettings)}${captionFig}</figure>`\n }\n get figureWidth() {\n return this.get(\"width\")\n }\nscrollImageParser\n cue image\n popularity 0.005908\n description An img tag.\n boolean isPopular true\n extends abstractCaptionedParser\n int atomIndex 1\n example\n image screenshot.png\n caption A caption.\n inScope addClassMarkupParser aftertextIdParser scrollLinkParser linkTargetParser openGraphParser\n javascript\n get dimensions() {\n const width = this.get(\"width\")\n const height = this.get(\"height\")\n if (width || height)\n return {width, height}\n if (!this.isNodeJs())\n return {}\n const src = this.filename\n // If its a local image, get the dimensions and put them in the HTML\n // to avoid flicker\n if (src.startsWith(\"http:\") || src.startsWith(\"https:\")) return {}\n if (this._dimensions)\n return this._dimensions\n try {\n const sizeOf = require(\"image-size\")\n const path = require(\"path\")\n const fullImagePath = path.join(this.root.folderPath, src)\n this._dimensions = sizeOf(fullImagePath)\n return this._dimensions\n } catch (err) {\n console.error(err)\n }\n return {}\n }\n get figureWidth() {\n return this.dimensions.width\n }\n get filename() {\n return this.getAtom(this.atomIndex)\n }\n get dependencies() { return [this.filename]}\n getFigureContent(buildSettings) {\n const linkRelativeToCompileTarget = (buildSettings ? (buildSettings.relativePath ?? \"\") : \"\") + this.filename\n const {width, height} = this.dimensions\n let dimensionAttributes = width || height ? `width=\"${width}\" height=\"${height}\" ` : \"\"\n // Todo: can we reuse more code from aftertext?\n const className = this.has(\"class\") ? ` class=\"${this.get(\"class\")}\" ` : \"\"\n const id = this.has(\"id\") ? ` id=\"${this.get(\"id\")}\" ` : \"\"\n const clickLink = this.find(particle => particle.definition.isOrExtendsAParserInScope([\"scrollLinkParser\"])) || linkRelativeToCompileTarget \n const target = this.has(\"target\") ? this.get(\"target\") : (this.has(\"link\") ? \"\" : \"_blank\")\n return `<a href=\"${clickLink}\" target=\"${target}\" ${className} ${id}><img src=\"${linkRelativeToCompileTarget}\" ${dimensionAttributes}loading=\"lazy\"></a>`\n }\n buildTxt() {\n const subparticles = this.filter(particle => particle.buildTxt).map(particle => particle.buildTxt()).filter(i => i).join(\"\\n\")\n return \"[Image Omitted]\" + (subparticles ? \"\\n \" + subparticles.replace(/\\n/g, \"\\n \") : \"\")\n }\nquickImageParser\n popularity 0.005788\n extends scrollImageParser\n example\n screenshot.png\n atoms urlAtom\n pattern ^[^\\s]+\\.(jpg|jpeg|png|gif|webp|svg|bmp)\n int atomIndex 0\nqrcodeParser\n extends abstractCaptionedParser\n description Make a QR code from a link.\n example\n qrcode https://scroll.pub\n javascript\n getFigureContent() {\n const url = this.atoms[1]\n const isNode = this.isNodeJs()\n if (isNode) {\n const {externalsPath} = this.root\n const path = require(\"path\")\n const {qrcodegen, toSvgString} = require(path.join(externalsPath, \".qrcodegen.js\"))\n const QRC = qrcodegen.QrCode;\n const qr0 = QRC.encodeText(url, QRC.Ecc.MEDIUM);\n const svg = toSvgString(qr0, 4); // See qrcodegen-input-demo\n return svg\n }\n return `Not yet supported in browser.`\n }\nyoutubeParser\n popularity 0.000121\n extends abstractCaptionedParser\n // Include the YouTube embed URL such as https://www.youtube.com/embed/CYPYZnVQoLg\n description A YouTube video widget.\n example\n youtube https://www.youtube.com/watch?v=lO8blNtYYBA\n javascript\n getFigureContent() {\n const url = this.getAtom(1).replace(\"youtube.com/watch?v=\", \"youtube.com/embed/\")\n return `<div class=\"scrollYouTubeHolder\"><iframe class=\"scrollYouTubeEmbed\" src=\"${url}\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe></div>`\n }\nyouTubeParser\n extends youtubeParser\n tags deprecate\n // Deprecated. You youtube all lowercase.\nimportParser\n description Import a file.\n popularity 0.007524\n cueFromId\n atoms preBuildCommandAtom\n extends abstractScrollParser\n catchAllAtomType filePathAtom\n javascript\n buildHtml() {\n return \"\"\n }\n example\n import header.scroll\nscrollImportedParser\n description Inserted at import pass.\n boolean suggestInAutocomplete false\n cue imported\n atoms preBuildCommandAtom\n extends abstractScrollParser\n baseParser blobParser\n catchAllAtomType filePathAtom\n javascript\n buildHtml() {\n return \"\"\n }\n getErrors() {\n if (this.get(\"exists\") === \"false\" && this.previous.getLine() !== \"// optional\")\n return [this.makeError(`File '${this.atoms[1]}' does not exist.`)]\n return []\n }\nquickImportParser\n popularity 0.007524\n description Import a Scroll or Parsers file.\n extends abstractScrollParser\n boolean isPopular true\n inScope importToFooterParser abstractCommentParser\n atoms urlAtom\n pattern ^[^\\s]+\\.(scroll|parsers)$\n javascript\n buildHtml() {\n return \"\"\n }\n example\n header.scroll\nscriptParser\n extends abstractScrollParser\n description Print script tag.\n cueFromId\n catchAllParser scriptLineParser\n catchAllAtomType javascriptAnyAtom\n javascript\n buildHtml() {\n return `<script>${this.scriptContent}</script>`\n }\n get scriptContent() {\n return this.content ?? this.subparticlesToString()\n }\n buildJs() {\n return this.scriptContent\n }\njsonScriptParser\n popularity 0.007524\n cueFromId\n description Include JSON and assign to window.\n extends abstractScrollParser\n atoms cueAtom urlAtom\n javascript\n buildHtml() {\n const varName = this.filename.split(\"/\").pop().replace(\".json\", \"\")\n return `<script>window.${varName} = ${this.root.readFile(this.filename)}</script>`\n }\n get filename() {\n return this.getAtom(1)\n }\nscrollLeftRightButtonsParser\n popularity 0.006342\n cue leftRightButtons\n description Previous and next nav buttons.\n extends abstractScrollParser\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n const { linkToPrevious, linkToNext } = this.root\n if (!linkToPrevious) return \"\"\n const style = `a.keyboardNav {display:block;position:absolute;top:0.25rem; color: rgba(204,204,204,.8); font-size: 1.875rem; line-height: 1.7rem;}a.keyboardNav:hover{color: #333;text-decoration: none;}`\n return `<style>${style}</style><a class=\"keyboardNav doNotPrint\" style=\"left:.5rem;\" href=\"${linkToPrevious}\">&lt;</a><a class=\"keyboardNav doNotPrint\" style=\"right:.5rem;\" href=\"${linkToNext}\">&gt;</a>`\n }\nkeyboardNavParser\n popularity 0.007476\n description Make left and right navigate files.\n extends abstractScrollParser\n cueFromId\n catchAllAtomType urlAtom\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n const {root} = this\n const linkToPrevious = this.getAtom(1) ?? root.linkToPrevious\n const linkToNext = this.getAtom(2) ?? root.linkToNext\n const script = `<script>document.addEventListener('keydown', function(event) {\n if (document.activeElement !== document.body) return\n if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return // dont interfere with keyboard back button shortcut\n const getLinks = () => document.getElementsByClassName(\"scrollKeyboardNav\")[0].getElementsByTagName(\"a\")\n if (event.key === \"ArrowLeft\")\n getLinks()[0].click()\n else if (event.key === \"ArrowRight\")\n getLinks()[1].click()\n });</script>`\n return `<div class=\"scrollKeyboardNav\" style=\"display:none;\"><a href=\"${linkToPrevious}\">${linkToPrevious}</a> · ${root.permalink} · <a href=\"${linkToNext}\">${linkToNext}</a>${script}</div>`\n }\nprintUsageStatsParser\n popularity 0.000096\n // todo: if we include the atom \"Parser\" in a cue, bad things seem to happen.\n description Parser usage stats for folder.\n extends abstractScrollParser\n cueFromId\n javascript\n get stats() {\n const input = this.root.allScrollFiles.map(file => file.scrollProgram).map(program => program.parserIds.join(\"\\n\")).join(\"\\n\")\n const result = input.split('\\n').reduce((acc, atom) => (acc[atom] = (acc[atom] || 0) + 1, acc), {})\n const rows = Object.entries(result).map(([atom, count]) => { return {atom, count}})\n const sorted = this.root.lodash.sortBy(rows, \"count\").reverse()\n return \"parserId uses\\n\" + sorted.map(row => `${row.atom} ${row.count}`).join('\\n')\n }\n buildHtml() {\n // A hacky but simple way to do this for now.\n const particle = this.appendSibling(\"table\")\n particle.appendLine(\"delimiter \")\n particle.appendLine(\"printTable\")\n const dataParticle = particle.appendLine(\"data\")\n dataParticle.setSubparticles(this.stats)\n const html = particle.buildHtml()\n particle.destroy()\n return html\n }\n buildTxt() {\n return this.stats\n }\n buildCsv() {\n return this.stats.replace(/ /g, \",\")\n }\nprintScrollLeetSheetParser\n popularity 0.000024\n description Print Scroll parser leet sheet.\n extends abstractScrollParser\n tags experimental\n cueFromId\n javascript\n get parsersToDocument() {\n const clone = this.root.clone()\n clone.setSubparticles(\"\")\n const atoms = clone.getAutocompleteResultsAt(0,0).matches.map(a => a.text)\n atoms.push(\"blankline\") // manually add blank line\n atoms.push(\"Catch All Paragraph.\") // manually add catch all paragraph\n atoms.push(\"<h></h>\") // manually add html\n atoms.sort()\n clone.setSubparticles(atoms.join(\"\\n\").replace(/blankline/, \"\")) // insert blank line in right spot\n return clone\n }\n sortDocs(docs) {\n return docs.map(particle => {\n const {definition} = particle\n const {id, description, isPopular, examples, popularity} = definition\n const tags = definition.get(\"tags\") || \"\"\n if (tags.includes(\"deprecate\") || tags.includes(\"experimental\"))\n return null\n const category = this.getCategory(tags)\n const note = this.getNote(category)\n return {id: definition.cueIfAny || id, description, isPopular, examples, note, popularity: Math.ceil(parseFloat(popularity) * 100000)}\n }).filter(i => i).sort((a, b) => a.id.localeCompare(b.id))\n }\n makeLink(examples, cue) {\n // if (!examples.length) console.log(cue) // find particles that need docs\n const example = examples.length ? examples[0].subparticlesToString() : cue\n const base = `https://try.scroll.pub/`\n const particle = new Particle()\n particle.appendLineAndSubparticles(\"scroll\", \"theme gazette\\n\" + example)\n return base + \"#\" + encodeURIComponent(particle.asString)\n }\n docToHtml(doc) {\n const css = `#scrollLeetSheet {color: grey;} #scrollLeetSheet a {color: #3498db; }`\n return `<style>${css}</style><div id=\"scrollLeetSheet\">` + doc.map(obj => `<div class=\"${obj.category}\"><a href=\"${this.makeLink(obj.examples, obj.id)}\">${obj.isPopular ? \"<b>\" : \"\"}${obj.id}</a> ${obj.description}${obj.isPopular ? \"</b>\" : \"\"}${obj.note}</div>`).join(\"\\n\") + \"</div>\"\n }\n buildHtml() {\n return this.docToHtml(this.sortDocs(this.parsersToDocument))\n }\n buildTxt() {\n return this.sortDocs(this.parsersToDocument).map(obj => `${obj.id} - ${obj.description}`).join(\"\\n\")\n }\n getCategory(input) {\n return \"\"\n }\n getNote() {\n return \"\"\n }\n get docs() {\n const rows = this.sortDocs(this.parsersToDocument).map(obj => {\n const {id, isPopular, description, popularity, category, examples, cue} = obj\n const example = examples.length ? examples[0].subparticlesToString() : cue\n return {\n id,\n isPopular,\n description,\n popularity,\n example,\n category\n }\n })\n return this.root.lodash.sortBy(rows, \"isPopular\")\n }\n buildJson() {\n return JSON.stringify(this.docs, undefined, 2)\n }\n buildCsv() {\n return new Particle(this.docs).asCsv\n }\nprintparsersLeetSheetParser\n popularity 0.000024\n // todo: fix parse bug when atom Parser appears in parserId\n extends printScrollLeetSheetParser\n tags experimental\n description Parsers leetsheet.\n javascript\n buildHtml() {\n return \"<p><b>Parser Definition Parsers</b> define parsers that acquire, analyze and act on code.</p>\" + this.docToHtml(this.sortDocs(this.parsersToDocument)) + \"<p><b>Atom Definition Parsers</b> analyze the atoms in a line.</p>\" + this.docToHtml(this.sortDocs(this.atomParsersToDocument))\n }\n makeLink() {\n return \"\"\n }\n categories = \"assemblePhase acquirePhase analyzePhase actPhase\".split(\" \")\n getCategory(tags) {\n return tags.split(\" \").filter(w => w.endsWith(\"Phase\"))[0]\n }\n getNote(category) {\n return ` <span class=\"note\">A${category.replace(\"Phase\", \"\").substr(1)}Time.</span>`\n }\n get atomParsersToDocument() {\n const parsersParser = require(\"scrollsdk/products/parsers.nodejs.js\")\n const clone = new parsersParser(\"anyAtom\\n \").clone()\n const parserParticle = clone.getParticle(\"anyAtom\")\n const atoms = clone.getAutocompleteResultsAt(1,1).matches.map(a => a.text)\n atoms.sort()\n parserParticle.setSubparticles(atoms.join(\"\\n\"))\n return parserParticle\n }\n get parsersToDocument() {\n const parsersParser = require(\"scrollsdk/products/parsers.nodejs.js\")\n const clone = new parsersParser(\"latinParser\\n \").clone()\n const parserParticle = clone.getParticle(\"latinParser\")\n const atoms = clone.getAutocompleteResultsAt(1,1).matches.map(a => a.text)\n atoms.sort()\n parserParticle.setSubparticles(atoms.join(\"\\n\"))\n clone.appendLine(\"myParser\")\n clone.appendLine(\"myAtom\")\n return parserParticle\n }\nabstractMeasureParser\n atoms measureNameAtom\n description Base parser all measures extend.\n cueFromId\n boolean isMeasure true\n float sortIndex 1.9\n boolean isComputed false\n string typeForWebForms text\n extends abstractScrollParser\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n return \"\"\n }\n get measureValue() {\n return this.content ?? \"\"\n }\n get measureName() {\n return this.getCuePath().replace(/ /g, \"_\")\n }\nabstractAtomMeasureParser\n description Contains a single word.\n atoms measureNameAtom atomAtom\n example\n nicknameParser\n extends abstractAtomMeasureParser\n id Breck\n nickname breck\n extends abstractMeasureParser\nabstractEmailMeasureParser\n description Email address.\n example\n emailParser\n extends abstractEmailMeasureParser\n id Breck\n email breck7@gmail.com\n string typeForWebForms email\n atoms measureNameAtom emailAddressAtom\n extends abstractAtomMeasureParser\nabstractUrlMeasureParser\n description A single url.\n example\n homepageParser\n extends abstractUrlMeasureParser\n id Breck\n homepage https://breckyunits.com\n string typeForWebForms url\n atoms measureNameAtom urlAtom\n extends abstractAtomMeasureParser\nabstractStringMeasureParser\n description General text data with no specific format.\n catchAllAtomType stringAtom\n example\n titleParser\n extends abstractStringMeasureParser\n id Breck\n title I build languages for scientists of all ages\n extends abstractMeasureParser\nabstractIdParser\n cue id\n description What is the ID of this concept?\n extends abstractStringMeasureParser\n example\n idParser\n extends abstractIdParser\n id breck\n float sortIndex 1\n boolean isMeasureRequired true\n boolean isConceptDelimiter true\n javascript\n getErrors() {\n const errors = super.getErrors()\n let requiredMeasureNames = this.root.measures.filter(measure => measure.isMeasureRequired).map(measure => measure.Name).filter(name => name !== \"id\")\n if (!requiredMeasureNames.length) return errors\n let next = this.next\n while (requiredMeasureNames.length && next.cue !== \"id\" && next.index !== 0) {\n requiredMeasureNames = requiredMeasureNames.filter(i => i !== next.cue)\n next = next.next\n }\n requiredMeasureNames.forEach(name =>\n errors.push(this.makeError(`Concept \"${this.content}\" is missing required measure \"${name}\".`))\n )\n return errors\n }\nabstractIdMeasureParser\n description Alias for abstractIdParser.\n extends abstractIdParser\nabstractTextareaMeasureParser\n string typeForWebForms textarea\n example\n bioParser\n extends abstractTextareaMeasureParser\n id Breck\n bio\n I build languages for scientists of all ages\n description Long-form text content with preserved line breaks.\n extends abstractMeasureParser\n baseParser blobParser\n javascript\n get measureValue() {\n return this.subparticlesToString().replace(/\\n/g, \"\\\\n\")\n }\nabstractNumericMeasureParser\n string typeForWebForms number\n description Base number type.\n extends abstractMeasureParser\n javascript\n get measureValue() {\n const {content} = this\n return content === undefined ? \"\" : parseFloat(content)\n }\nabstractNumberMeasureParser\n description Alias to abstractNumericMeasureParser.\n extends abstractNumericMeasureParser\nabstractIntegerMeasureParser\n description An integer.\n example\n ageParser\n extends abstractIntegerMeasureParser\n id Breck\n age 40\n atoms measureNameAtom integerAtom\n extends abstractNumericMeasureParser\n javascript\n get measureValue() {\n const {content} = this\n return content === undefined ? \"\" : parseInt(content)\n }\nabstractIntMeasureParser\n description Alias to abstractIntegerMeasureParser.\n extends abstractIntegerMeasureParser\nabstractFloatMeasureParser\n description A float.\n example\n temperatureParser\n extends abstractFloatMeasureParser\n id Breck\n temperature 31.8\n atoms measureNameAtom floatAtom\n extends abstractNumericMeasureParser\nabstractPercentageMeasureParser\n description A percentage.\n atoms measureNameAtom percentAtom\n extends abstractNumericMeasureParser\n example\n ownershipParser\n extends abstractPercentageMeasureParser\n id Breck\n ownership 31.8\n javascript\n get measureValue() {\n const {content} = this\n return content === undefined ? \"\" : parseFloat(content)\n }\nabstractEnumMeasureParser\n description A single enum.\n atoms measureNameAtom enumAtom\n extends abstractMeasureParser\n example\n favoriteHtmlTagParser\n extends abstractEnumMeasureParser\n atoms measureNameAtom htmlTagAtom\n id Breck\n favoriteHtmlTag 2020\nabstractBooleanMeasureParser\n description A single boolean.\n atoms measureNameAtom booleanAtom\n extends abstractMeasureParser\n example\n hasBillOfRightsParser\n extends abstractBooleanMeasureParser\n id USA\n hasBillOfRights true\n javascript\n get measureValue() {\n const {content} = this\n return content === undefined ? \"\" : content == \"true\"\n }\nabstractDateMeasureParser\n description Year/month/day in ISO 8601, US, European formats.\n atoms measureNameAtom dateAtom\n extends abstractMeasureParser\n string typeForWebForms date\n javascript\n get measureValue() {\n const {content} = this\n if (!content) return \"\"\n const {dayjs} = this.root\n try {\n // First try parsing with dayjs\n const parsed = dayjs(content)\n if (parsed.isValid())\n return parsed.format(\"YYYY-MM-DD\")\n // Try parsing other common formats\n const formats = [\n \"MM/DD/YYYY\",\n \"DD/MM/YYYY\", \n \"YYYY/MM/DD\",\n \"MM-DD-YYYY\",\n \"DD-MM-YYYY\",\n \"YYYY-MM-DD\",\n \"DD.MM.YYYY\",\n \"YYYY.MM.DD\"\n ]\n for (const format of formats) {\n const attempt = dayjs(content, format)\n if (attempt.isValid())\n return attempt.format(\"YYYY-MM-DD\")\n }\n } catch (err) {\n console.error(err)\n return \"\"\n }\n return \"\"\n }\n get valueAsTimestamp() {\n const {measureValue} = this\n return measureValue ? this.root.dayjs(measureValue).unix() : \"\"\n }\nmetaTagsParser\n popularity 0.007693\n cueFromId\n extends abstractScrollParser\n description Print meta tags including title.\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\n buildHtml() {\n const {root} = this\n const { title, description, canonicalUrl, gitRepo, scrollVersion, openGraphImage, keywords } = root\n const rssFeedUrl = root.get(\"rssFeedUrl\")\n const favicon = root.get(\"favicon\")\n const faviconTag = favicon ? `<link rel=\"icon\" href=\"${favicon}\">` : \"\"\n const keywordsTag = keywords ? `<meta name=\"keywords\" content=\"${keywords}\">` : \"\"\n const rssTag = rssFeedUrl ? `<link rel=\"alternate\" type=\"application/rss+xml\" title=\"${title}\" href=\"${rssFeedUrl}\">` : \"\"\n const gitTag = gitRepo ? `<link rel=\"source\" type=\"application/git\" title=\"Source Code Repository\" href=\"${gitRepo}\">` : \"\"\n return `<head>\n <meta charset=\"utf-8\">\n <title>${title}</title>\n <script>/* This HTML was generated by 📜 Scroll v${scrollVersion}. https://scroll.pub */</script>\n <style>@media print {.doNotPrint {display: none !important;}}</style>\n <link rel=\"canonical\" href=\"${canonicalUrl}\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n <meta name=\"description\" content=\"${description}\">\n ${keywordsTag}\n <meta name=\"generator\" content=\"Scroll v${scrollVersion}\">\n <meta property=\"og:title\" content=\"${title}\">\n <meta property=\"og:description\" content=\"${description}\">\n <meta property=\"og:image\" content=\"${openGraphImage}\">\n ${faviconTag}\n ${gitTag}\n ${rssTag}\n <meta name=\"twitter:card\" content=\"summary_large_image\">\n </head>\n <body>`\n }\nquoteParser\n popularity 0.001471\n cueFromId\n description A quote.\n catchAllParser quoteLineParser\n extends abstractScrollParser\n javascript\n buildHtml() {\n return `<blockquote class=\"scrollQuote\">${this.subparticlesToString()}</blockquote>`\n }\n buildTxt() {\n return this.subparticlesToString()\n }\nredirectToParser\n popularity 0.000072\n description HTML redirect tag.\n extends abstractScrollParser\n atoms cueAtom urlAtom\n cueFromId\n example\n redirectTo https://scroll.pub/releaseNotes.html\n javascript\n buildHtml() {\n return `<meta http-equiv=\"Refresh\" content=\"0; url='${this.getAtom(1)}'\" />`\n }\nabstractVariableParser\n extends abstractScrollParser\n catchAllAtomType stringAtom\n atoms preBuildCommandAtom\n cueFromId\n javascript\n isTopMatter = true\n buildHtml() {\n return \"\"\n }\nreplaceParser\n description Replace this with that.\n extends abstractVariableParser\n baseParser blobParser\n example\n replace YEAR 2022\nreplaceJsParser\n description Replace this with evaled JS.\n extends replaceParser\n catchAllAtomType javascriptAnyAtom\n example\n replaceJs SUM 1+1\n * 1+1 = SUM\nreplaceNodejsParser\n description Replace with evaled Node.JS.\n extends abstractVariableParser\n catchAllAtomType javascriptAnyAtom\n baseParser blobParser\n example\n replaceNodejs\n module.exports = {SCORE : 1 + 2}\n * The score is SCORE\ntoFooterParser\n extends abstractScrollParser\n description Experimental way to move a section to the footer.\n atoms preBuildCommandAtom\n cueFromId\nrunScriptParser\n popularity 0.000024\n description Run script and dump stdout.\n extends abstractScrollParser\n atoms cueAtom urlAtom\n cue run\n int filenameIndex 1\n javascript\n get dependencies() { return [this.filename]}\n results = \"Not yet run\"\n async execute() {\n if (!this.filename) return\n await this.root.fetch(this.filename)\n // todo: make async\n const { execSync } = require(\"child_process\")\n this.results = execSync(this.command)\n }\n get command() {\n const path = this.root.path\n const {filename }= this\n const fullPath = this.root.makeFullPath(filename)\n const ext = path.extname(filename).slice(1)\n const interpreterMap = {\n php: \"php\",\n py: \"python3\",\n rb: \"ruby\",\n pl: \"perl\",\n sh: \"sh\"\n }\n return [interpreterMap[ext], fullPath].join(\" \")\n }\n buildHtml() {\n return this.buildTxt()\n }\n get filename() {\n return this.getAtom(this.filenameIndex)\n }\n buildTxt() {\n return this.results.toString().trim()\n }\nquickRunScriptParser\n extends runScriptParser\n atoms urlAtom\n pattern ^[^\\s]+\\.(py|pl|sh|rb|php)$\n int filenameIndex 0\nendSnippetParser\n popularity 0.004293\n description Cut for snippet here.\n extends abstractScrollParser\n cueFromId\n javascript\n buildHtml() {\n return \"\"\n }\ntoStampParser\n description Print a directory to stamp.\n extends abstractScrollParser\n catchAllAtomType filePathAtom\n cueFromId\n javascript\n buildTxt() {\n return this.makeStamp(this.content)\n }\n buildHtml() {\n return `<pre>${this.buildTxt()}</pre>`\n }\n makeStamp(dir) {\n const fs = require('fs');\n const path = require('path');\n const { execSync } = require('child_process');\n let stamp = 'stamp\\n';\n const handleFile = (indentation, relativePath, itemPath, ) => {\n stamp += `${indentation}${relativePath}\\n`;\n const content = fs.readFileSync(itemPath, 'utf8');\n stamp += `${indentation} ${content.replace(/\\n/g, `\\n${indentation} `)}\\n`;\n }\n let gitTrackedFiles\n function processDirectory(currentPath, depth) {\n const items = fs.readdirSync(currentPath);\n items.forEach(item => {\n const itemPath = path.join(currentPath, item);\n const relativePath = path.relative(dir, itemPath);\n //if (!gitTrackedFiles.has(item)) return\n const stats = fs.statSync(itemPath);\n const indentation = ' '.repeat(depth);\n if (stats.isDirectory()) {\n stamp += `${indentation}${relativePath}/\\n`;\n processDirectory(itemPath, depth + 1);\n } else if (stats.isFile())\n handleFile(indentation, relativePath, itemPath)\n });\n }\n const stats = fs.statSync(dir);\n if (stats.isDirectory()) {\n // Get list of git-tracked files\n gitTrackedFiles = new Set(execSync('git ls-files', { cwd: dir, encoding: 'utf-8' })\n .split('\\n')\n .filter(Boolean))\n processDirectory(dir, 1)\n }\n else\n handleFile(\" \", dir, dir)\n return stamp.trim();\n }\nstampParser\n description Expand project template to disk.\n extends abstractScrollParser\n inScope stampFolderParser\n catchAllParser stampFileParser\n example\n stamp\n .gitignore\n *.html\n readme.scroll\n # Hello world\n <script src=\"scripts/nested/hello.js\"></script>\n scripts/\n nested/\n hello.js\n console.log(\"Hello world\")\n cueFromId\n atoms preBuildCommandAtom\n javascript\n execute() {\n const dir = this.root.folderPath\n this.forEach(particle => particle.execute(dir))\n }\nscrollStumpParser\n cue stump\n extends abstractScrollParser\n description Compile Stump to HTML.\n catchAllParser stumpContentParser\n javascript\n buildHtml() {\n const {stumpParser} = this\n return new stumpParser(this.subparticlesToString()).compile()\n }\n get stumpParser() {\n return this.isNodeJs() ? require(\"scrollsdk/products/stump.nodejs.js\") : stumpParser\n }\nstumpNoSnippetParser\n popularity 0.010177\n // todo: make noSnippets an aftertext directive?\n extends scrollStumpParser\n description Compile Stump unless snippet.\n cueFromId\n javascript\n buildHtmlSnippet() {\n return \"\"\n }\nplainTextParser\n description Plain text oneliner or block.\n cueFromId\n extends abstractScrollParser\n catchAllParser plainTextLineParser\n catchAllAtomType stringAtom\n javascript\n buildHtml() {\n return this.buildTxt()\n }\n buildTxt() {\n return `${this.content ?? \"\"}${this.subparticlesToString()}`\n }\nplainTextOnlyParser\n popularity 0.000072\n extends plainTextParser\n description Only print for buildTxt.\n javascript\n buildHtml() {\n return \"\"\n }\nscrollThemeParser\n popularity 0.007524\n boolean isPopular true\n cue theme\n example\n theme gazette\n extends abstractScrollParser\n catchAllAtomType scrollThemeAtom\n description A collection of simple themes.\n string copyFromExternal .gazette.css\n // Note this will be replaced at runtime\n javascript\n get copyFromExternal() {\n return this.files.join(\" \")\n }\n get files() {\n return this.atoms.slice(1).map(name => `.${name}.css`).concat([\".scroll.css\"])\n }\n buildHtml() {\n return this.files.map(name => `<link rel=\"stylesheet\" type=\"text/css\" href=\"${name}\">`).join(\"\\n\")\n }\nabstractAftertextAttributeParser\n atoms cueAtom\n boolean isAttribute true\n javascript\n get htmlAttributes() {\n return `${this.cue}=\"${this.content}\"`\n }\n buildHtml() {\n return \"\"\n }\naftertextIdParser\n popularity 0.000145\n cue id\n description Provide an ID to be output in the generated HTML tag.\n extends abstractAftertextAttributeParser\n atoms cueAtom htmlIdAtom\n single\naftertextStyleParser\n popularity 0.000217\n cue style\n description Set HTML style attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType cssAnyAtom\n javascript\n htmlAttributes = \"\" // special case this one\n get css() { return `${this.property}:${this.content};` }\naftertextFontParser\n popularity 0.000217\n cue font\n description Set font.\n extends aftertextStyleParser\n atoms cueAtom fontFamilyAtom\n catchAllAtomType cssAnyAtom\n string property font-family\n javascript\n get css() {\n if (this.content === \"Slim\") return \"font-family:Helvetica Neue; font-weight:100;\"\n return super.css\n }\naftertextColorParser\n popularity 0.000217\n cue color\n description Set font color.\n extends aftertextStyleParser\n catchAllAtomType cssAnyAtom\n string property color\n example\n color blue\naftertextHrefParser\n popularity 0.000217\n cue href\n description Set HTML href attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom urlAtom\naftertextSrcParser\n extends aftertextHrefParser\n cue src\n description Set HTML src attribute.\naftertextOnclickParser\n popularity 0.000217\n cue onclick\n description Set HTML onclick attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType javascriptAnyAtom\naftertextHiddenParser\n cue hidden\n atoms cueAtom\n description Do not compile this particle to HTML.\n extends abstractAftertextAttributeParser\n single\naftertextValueParser\n popularity 0.000217\n cue value\n description Set HTML value attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextForParser\n popularity 0.000217\n cue for\n description Set HTML for attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom htmlAnyAtom\naftertextPlaceholderParser\n popularity 0.000217\n cue placeholder\n description Set HTML placeholder attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextRowsParser\n popularity 0.000217\n cue rows\n description Set HTML rows attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom integerAtom\naftertextTypeParser\n popularity 0.000217\n cue type\n description Set HTML type attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom htmlTypeAtom\naftertextAltParser\n popularity 0.000217\n cue alt\n description Set HTML alt attribute for images.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextTitleParser\n popularity 0.000217\n cue title\n description Set HTML title attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextNameParser\n popularity 0.000217\n cue name\n description Set HTML name attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextOnsubmitParser\n popularity 0.000217\n cue onsubmit\n description Set HTML onsubmit attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType javascriptAnyAtom\naftertextClassParser\n popularity 0.000217\n cue class\n description Set HTML class attribute.\n extends abstractAftertextAttributeParser\n catchAllAtomType classNameAtom\naftertextMaxlengthParser\n popularity 0.000217\n cue maxlength\n description Set HTML maxlength attribute.\n extends abstractAftertextAttributeParser\n atoms cueAtom integerAtom\naftertextPatternParser\n popularity 0.000217\n cue pattern\n description Set HTML pattern attribute for input validation.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextRequiredParser\n popularity 0.000217\n cue required\n description Set HTML required attribute.\n extends abstractAftertextAttributeParser\n single\naftertextDisabledParser\n popularity 0.000217\n cue disabled\n description Set HTML disabled attribute.\n extends abstractAftertextAttributeParser\n single\naftertextReadonlyParser\n popularity 0.000217\n cue readonly\n description Set HTML readonly attribute.\n extends abstractAftertextAttributeParser\n single\naftertextAriaLabelParser\n popularity 0.000217\n cue aria-label\n description Set ARIA label for accessibility.\n extends abstractAftertextAttributeParser\n catchAllAtomType htmlAnyAtom\naftertextTargetParser\n popularity 0.000217\n cue target\n description Set HTML target attribute for links.\n extends abstractAftertextAttributeParser\n atoms cueAtom htmlAnyAtom\naftertextTagParser\n atoms cueAtom htmlTagAtom\n description Override the HTML tag that the compiled particle will use.\n cue tag\n javascript\n buildHtml() {\n return \"\"\n }\nabstractAftertextDirectiveParser\n atoms cueAtom\n catchAllAtomType stringAtom\n javascript\n isMarkup = true\n buildHtml() {\n return \"\"\n }\n getErrors() {\n const errors = super.getErrors()\n if (!this.isMarkup || this.matchWholeLine) return errors\n const inserts = this.getInserts(this.parent.originalTextPostLinkify)\n // todo: make AbstractParticleError class exported by sdk to allow Parsers to define their own error types.\n // todo: also need to be able to map lines back to their line in source (pre-imports)\n if (!inserts.length)\n errors.push(this.makeError(`No match found for \"${this.getLine()}\".`))\n return errors\n }\n get pattern() {\n return this.getAtomsFrom(1).join(\" \")\n }\n get shouldMatchAll() {\n return this.has(\"matchAll\")\n }\n getMatches(text) {\n const { pattern } = this\n const escapedPattern = pattern.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\")\n return [...text.matchAll(new RegExp(escapedPattern, \"g\"))].map(match => {\n const { index } = match\n const endIndex = index + pattern.length\n return [\n { index, string: `<${this.openTag}${this.allAttributes}>`, endIndex },\n { index: endIndex, endIndex, string: `</${this.closeTag}>` }\n ]\n })\n }\n getInserts(text) {\n const matches = this.getMatches(text)\n if (!matches.length) return false\n if (this.shouldMatchAll) return matches.flat()\n const match = this.getParticle(\"match\")\n if (match)\n return match.indexes\n .map(index => matches[index])\n .filter(i => i)\n .flat()\n return matches[0]\n }\n get allAttributes() {\n const attr = this.attributes.join(\" \")\n return attr ? \" \" + attr : \"\"\n }\n get attributes() {\n return []\n }\n get openTag() {\n return this.tag\n }\n get closeTag() {\n return this.tag\n }\nabstractMarkupParser\n extends abstractAftertextDirectiveParser\n inScope abstractMarkupParameterParser\n javascript\n get matchWholeLine() {\n return this.getAtomsFrom(this.patternStartsAtAtom).length === 0\n }\n get pattern() {\n return this.matchWholeLine ? this.parent.originalText : this.getAtomsFrom(this.patternStartsAtAtom).join(\" \")\n }\n patternStartsAtAtom = 1\nboldParser\n popularity 0.000096\n cueFromId\n description Bold matching text.\n extends abstractMarkupParser\n javascript\n tag = \"b\"\nitalicsParser\n popularity 0.000241\n cueFromId\n description Italicize matching text.\n extends abstractMarkupParser\n javascript\n tag = \"i\"\nunderlineParser\n popularity 0.000024\n description Underline matching text.\n cueFromId\n extends abstractMarkupParser\n javascript\n tag = \"u\"\nafterTextCenterParser\n popularity 0.000193\n description Center paragraph.\n cue center\n extends abstractMarkupParser\n javascript\n tag = \"center\"\naftertextCodeParser\n popularity 0.000145\n description Wrap matching text in code span.\n cue code\n extends abstractMarkupParser\n javascript\n tag = \"code\"\naftertextStrikeParser\n popularity 0.000048\n description Wrap matching text in s span.\n cue strike\n extends abstractMarkupParser\n javascript\n tag = \"s\"\naddClassMarkupParser\n popularity 0.000772\n description Add a custom class to parent element. Provide query to add span matching text.\n extends abstractMarkupParser\n atoms cueAtom classNameAtom\n cue addClass\n javascript\n tag = \"span\"\n get applyToParentElement() {\n return this.atoms.length === 2\n }\n getInserts(text) {\n // If no select text is added, set the class on the parent element.\n if (this.applyToParentElement) return []\n return super.getInserts(text)\n }\n get className() {\n return this.getAtom(1)\n }\n get attributes() {\n return [`class=\"${this.className}\"`]\n }\n get matchWholeLine() {\n return this.applyToParentElement\n }\n get pattern() {\n return this.matchWholeLine ? this.parent.content : this.getAtomsFrom(2).join(\" \")\n }\nhoverNoteParser\n popularity 0.000265\n description Add a caveat viewable on hover on matching text. When you want to be sure you've thoroughly addressed obvious concerns but ones that don't warrant to distract from the main argument of the text.\n cueFromId\n extends addClassMarkupParser\n catchAllParser lineOfTextParser\n atoms cueAtom\n javascript\n get pattern() {\n return this.getAtomsFrom(1).join(\" \")\n }\n get attributes() {\n return [`class=\"scrollHoverNote\"`, `title=\"${this.hoverNoteText}\"`]\n }\n get hoverNoteText() {\n return this.subparticlesToString().replace(/\\n/g, \" \")\n }\nscrollLinkParser\n popularity 0.008706\n extends abstractMarkupParser\n description Put the matching text in an <a> tag.\n atoms cueAtom urlAtom\n inScope linkTitleParser linkTargetParser abstractCommentParser\n programParser\n description Anything here will be URI encoded and then appended to the link.\n cueFromId\n atoms cueAtom\n catchAllParser programLinkParser\n javascript\n get encoded() {\n return encodeURIComponent(this.subparticlesToString())\n }\n cue link\n javascript\n tag = \"a\"\n buildTxt() {\n return this.root.ensureAbsoluteLink(this.link) + \" \" + this.pattern\n }\n get link() {\n const {baseLink} = this\n if (this.has(\"program\"))\n return baseLink + this.getParticle(\"program\").encoded\n return baseLink\n }\n get baseLink() {\n const link = this.getAtom(1)\n const isAbsoluteLink = link.includes(\"://\")\n if (isAbsoluteLink) return link\n const relativePath = this.parent.buildSettings?.relativePath || \"\"\n return relativePath + link\n }\n get linkAttribute() {\n return \"href\"\n }\n get attributes() {\n const attrs = [`${this.linkAttribute}=\"${this.link}\"`]\n const options = [\"title\", \"target\"]\n options.forEach(option => {\n const particle = this.getParticle(option)\n if (particle) attrs.push(`${option}=\"${particle.content}\"`)\n })\n return attrs\n }\n patternStartsAtAtom = 2\nscrollClickParser\n extends scrollLinkParser\n description An a tag with an onclick.\n cue click\n javascript\n get linkAttribute() {\n return \"onclick\"\n }\nemailLinkParser\n popularity 0.000048\n description A mailto link\n cue email\n extends scrollLinkParser\n javascript\n get attributes() {\n return [`href=\"mailto:${this.link}\"`]\n }\nquickLinkParser\n popularity 0.029228\n pattern ^https?\\:\n extends scrollLinkParser\n atoms urlAtom\n javascript\n get link() {\n return this.cue\n }\n patternStartsAtAtom = 1\nquickRelativeLinkParser\n popularity 0.029228\n description Relative links.\n // note: only works if relative link ends in .html\n pattern ^[^\\s]+\\.(html|htm)\n extends scrollLinkParser\n atoms urlAtom\n javascript\n get link() {\n return this.cue\n }\n patternStartsAtAtom = 1\ndatelineParser\n popularity 0.006005\n cueFromId\n description Gives your paragraph a dateline like \"December 15, 2021 — The...\"\n extends abstractAftertextDirectiveParser\n javascript\n getInserts() {\n const {day} = this\n if (!day) return false\n return [{ index: 0, string: `<span class=\"scrollDateline\">${day} — </span>` }]\n }\n matchWholeLine = true\n get day() {\n let day = this.content || this.root.date\n if (!day) return \"\"\n return this.root.dayjs(day).format(`MMMM D, YYYY`)\n }\ndayjsParser\n description Advanced directive that evals some Javascript code in an environment including \"dayjs\".\n cueFromId\n extends abstractAftertextDirectiveParser\n javascript\n getInserts() {\n const dayjs = this.root.dayjs\n const days = eval(this.content)\n const index = this.parent.originalTextPostLinkify.indexOf(\"days\")\n return [{ index, string: `${days} ` }]\n }\ninlineMarkupsOnParser\n popularity 0.000024\n cueFromId\n description Enable these inline markups only.\n example\n Hello *world*!\n inlineMarkupsOn bold\n extends abstractAftertextDirectiveParser\n catchAllAtomType inlineMarkupNameAtom\n javascript\n get shouldMatchAll() {\n return true\n }\n get markups() {\n const {root} = this\n let markups = [{delimiter: \"`\", tag: \"code\", exclusive: true, name: \"code\"},{delimiter: \"*\", tag: \"strong\", name: \"bold\"}, {delimiter: \"_\", tag: \"em\", name: \"italics\"}]\n // only add katex markup if the root doc has katex.\n if (root.has(\"katex\"))\n markups.unshift({delimiter: \"$\", tag: \"span\", attributes: ' class=\"scrollKatex\"', exclusive: true, name: \"katex\"})\n if (this.content)\n return markups.filter(markup => this.content.includes(markup.name))\n if (root.has(\"inlineMarkups\")) {\n root.getParticle(\"inlineMarkups\").forEach(markup => {\n const delimiter = markup.getAtom(0)\n const tag = markup.getAtom(1)\n // todo: add support for providing custom functions for inline markups?\n // for example, !2+2! could run eval, or :about: could search a link map.\n const attributes = markup.getAtomsFrom(2).join(\" \")\n markups = markups.filter(mu => mu.delimiter !== delimiter) // Remove any overridden markups\n if (tag)\n markups.push({delimiter, tag, attributes})\n })\n }\n return markups\n }\n matchWholeLine = true\n getMatches(text) {\n const exclusives = []\n return this.markups.map(markup => this.applyMarkup(text, markup, exclusives)).filter(i => i).flat()\n }\n applyMarkup(text, markup, exclusives = []) {\n const {delimiter, tag, attributes} = markup\n const escapedDelimiter = delimiter.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\")\n const pattern = new RegExp(`${escapedDelimiter}[^${escapedDelimiter}]+${escapedDelimiter}`, \"g\")\n const delimiterLength = delimiter.length\n return [...text.matchAll(pattern)].map(match => {\n const { index } = match\n const endIndex = index + match[0].length\n // I'm too lazy to clean up sdk to write a proper inline markup parser so doing this for now.\n // The exclusive idea is to not try and apply bold or italic styles inside a TeX or code inline style.\n // Note that the way this is currently implemented any TeX in an inline code will get rendered, but code\n // inline of TeX will not. Seems like an okay tradeoff until a proper refactor and cleanup can be done.\n if (exclusives.some(exclusive => index >= exclusive[0] && index <= exclusive[1]))\n return undefined\n if (markup.exclusive)\n exclusives.push([index, endIndex])\n return [\n { index, string: `<${tag + (attributes ? \" \" + attributes : \"\")}>`, endIndex, consumeStartCharacters: delimiterLength },\n { index: endIndex, endIndex, string: `</${tag}>`, consumeEndCharacters: delimiterLength }\n ]\n }).filter(i => i)\n }\ninlineMarkupParser\n popularity 0.000169\n cueFromId\n atoms cueAtom delimiterAtom tagOrUrlAtom\n catchAllAtomType htmlAttributesAtom\n extends inlineMarkupsOnParser\n description Custom inline markup. for\n example\n @This@ will be in italics.\n inlineMarkup @ em\n javascript\n getMatches(text) {\n try {\n const delimiter = this.getAtom(1)\n const tag = this.getAtom(2)\n const attributes = this.getAtomsFrom(3).join(\" \")\n return this.applyMarkup(text, {delimiter, tag, attributes})\n } catch (err) {\n console.error(err)\n return []\n }\n // Note: doubling up doesn't work because of the consumption characters.\n }\nlinkifyParser\n description Use this to disable linkify on the text.\n extends abstractAftertextDirectiveParser\n cueFromId\n atoms cueAtom booleanAtom\nabstractMarkupParameterParser\n atoms cueAtom\n cueFromId\nmatchAllParser\n popularity 0.000024\n description Use this to match all occurrences of the text.\n extends abstractMarkupParameterParser\nmatchParser\n popularity 0.000048\n catchAllAtomType integerAtom\n description Use this to specify which index(es) to match.\n javascript\n get indexes() {\n return this.getAtomsFrom(1).map(num => parseInt(num))\n }\n example\n aftertext\n hello ello ello\n bold ello\n match 0 2\n extends abstractMarkupParameterParser\nabstractHtmlAttributeParser\n javascript\n buildHtml() {\n return \"\"\n }\nlinkTargetParser\n popularity 0.000024\n extends abstractHtmlAttributeParser\n description If you want to set the target of the link. To \"_blank\", for example.\n cue target\n atoms cueAtom codeAtom\nblankLineParser\n popularity 0.308149\n description Print nothing. Break section.\n atoms blankAtom\n boolean isPopular true\n javascript\n buildHtml() {\n return this.parent.clearSectionStack()\n }\n pattern ^$\n tags doNotSynthesize\nscrollFileAddressParser\n catchAllAtomType filePathAtom\n catchAllParser scrollFileAddressParser\nchatLineParser\n popularity 0.009887\n catchAllAtomType stringAtom\n catchAllParser chatLineParser\nlineOfCodeParser\n popularity 0.018665\n catchAllAtomType codeAtom\n catchAllParser lineOfCodeParser\ncommentLineParser\n catchAllAtomType commentAtom\ncssLineParser\n popularity 0.002870\n catchAllAtomType cssAnyAtom\n catchAllParser cssLineParser\nabstractTableTransformParser\n atoms cueAtom\n inScope abstractTableVisualizationParser abstractTableTransformParser h1Parser h2Parser scrollQuestionParser htmlInlineParser scrollBrParser slashCommentParser\n javascript\n get coreTable() {\n return this.parent.coreTable\n }\n get columnNames() {\n return this.parent.columnNames\n }\n connectColumnNames(userColumnNames, availableColumnNames = this.parent.columnNames) {\n const result = {}\n const normalize = str => str.toLowerCase().trim()\n userColumnNames.forEach(userColumn => {\n // Strategy 1: Exact match\n const exactMatch = availableColumnNames.find(col => col === userColumn)\n if (exactMatch) {\n result[userColumn] = exactMatch\n return\n }\n // Strategy 2: Case-insensitive match\n const normalizedUserColumn = normalize(userColumn)\n const caseInsensitiveMatch = availableColumnNames.find(col => normalize(col) === normalizedUserColumn)\n if (caseInsensitiveMatch) {\n result[userColumn] = caseInsensitiveMatch\n return\n }\n // Strategy 3: Levenshtein distance match\n const THRESHOLD = 2 // Consider matches with distance <= 2 as \"very close\"\n let bestMatch = null\n let bestDistance = Infinity\n availableColumnNames.forEach(col => {\n const distance = this.root.levenshteinDistance(userColumn, col)\n if (distance < bestDistance) {\n bestDistance = distance\n bestMatch = col\n }\n })\n // Only use Levenshtein match if it's very close\n if (bestDistance <= THRESHOLD) {\n result[userColumn] = bestMatch\n return\n }\n // Strategy 4: Fallback - use original unmatched name\n result[userColumn] = userColumn\n })\n return result\n }\n connectColumnName(name) {\n return this.connectColumnNames([name])[name]\n }\n getErrors() {\n const errors = super.getErrors()\n if (errors.length && this.previous.cue !== \"assertIgnoreBelowErrors\")\n return errors\n return []\n }\n getRunTimeEnumOptions(atom) {\n if (atom.atomTypeId === \"columnNameAtom\")\n return this.parent.columnNames\n return super.getRunTimeEnumOptions(atom)\n }\n getRunTimeEnumOptionsForValidation(atom) {\n // Note: this will fail if the CSV file hasnt been built yet.\n if (atom.atomTypeId === \"columnNameAtom\")\n return this.parent.columnNames.concat(this.parent.columnNames.map(c => \"-\" + c)) // Add reverse names\n return super.getRunTimeEnumOptions(atom)\n }\nabstractDateSplitTransformParser\n extends abstractTableTransformParser\n atoms cueAtom\n catchAllAtomType columnNameAtom\n javascript\n get coreTable() {\n const columnName = this.getAtom(1) || this.detectDateColumn()\n if (!columnName) return this.parent.coreTable\n return this.parent.coreTable.map(row => {\n const newRow = {...row}\n try {\n const date = this.root.dayjs(row[columnName])\n if (date.isValid())\n newRow[this.newColumnName] = this.transformDate(date)\n } catch (err) {}\n return newRow\n })\n }\n detectDateColumn() {\n const columns = this.parent.columnNames\n const dateColumns = ['date', 'created', 'published', 'timestamp']\n for (const col of dateColumns) {\n if (columns.includes(col)) return col\n }\n for (const col of columns) {\n const sample = this.parent.coreTable[0][col]\n if (sample && this.root.dayjs(sample).isValid())\n return col\n }\n return null\n }\n get columnNames() {\n return [...this.parent.columnNames, this.newColumnName]\n }\n transformDate(date) {\n const formatted = date.format(this.dateFormat)\n const isInt = !this.cue.includes(\"Name\")\n return isInt ? parseInt(formatted) : formatted\n }\nscrollSplitYearParser\n extends abstractDateSplitTransformParser\n description Extract year into new column.\n cue splitYear\n string newColumnName year\n string dateFormat YYYY\nscrollSplitDayNameParser\n extends abstractDateSplitTransformParser\n description Extract day name into new column.\n cue splitDayName\n string newColumnName dayName\n string dateFormat dddd\nscrollSplitMonthNameParser\n extends abstractDateSplitTransformParser\n description Extract month name into new column.\n cue splitMonthName\n string newColumnName monthName\n string dateFormat MMMM\nscrollSplitMonthParser\n extends abstractDateSplitTransformParser\n description Extract month number (1-12) into new column.\n cue splitMonth\n string newColumnName month\n string dateFormat M\nscrollSplitDayOfMonthParser\n extends abstractDateSplitTransformParser\n description Extract day of month (1-31) into new column.\n cue splitDayOfMonth\n string newColumnName dayOfMonth\n string dateFormat D\nscrollSplitDayOfWeekParser\n extends abstractDateSplitTransformParser\n description Extract day of week (0-6) into new column.\n cue splitDay\n string newColumnName day\n string dateFormat d\nscrollParseDateParser\n extends abstractTableTransformParser\n description Parse dates in a column into standard format.\n cue parseDate\n atoms cueAtom columnNameAtom\n example\n sampleData stocks.csv\n parseDate date\n linechart\n x date\n y price\n javascript\n get coreTable() {\n const columnName = this.connectColumnName(this.getAtom(1))\n const formatOut = this.get(\"format\") || \"YYYY-MM-DD\"\n const {dayjs} = this.root\n return this.parent.coreTable.map(row => {\n const newRow = {...row}\n try {\n const value = row[columnName]\n if (value) {\n const date = dayjs(value)\n if (date.isValid())\n newRow[columnName] = date.format(formatOut)\n }\n } catch (err) {\n console.error(`Error parsing date in column ${columnName}:`, err)\n }\n return newRow\n })\n }\n formatParser\n description Specify output date format\n atoms cueAtom stringAtom\n cueFromId\n single\nscrollGroupByParser\n catchAllAtomType columnNameAtom\n extends abstractTableTransformParser\n reduceParser\n description Specify how to aggregate a column when grouping data\n atoms cueAtom columnNameAtom reductionTypeAtom newColumnNameAtom\n cue reduce\n example\n data.csv\n groupBy year\n reduce score sum totalScore\n reduce name concat names\n printTable\n javascript\n get reduction() {\n return {\n source: this.getAtom(1),\n reduction: this.getAtom(2),\n name: this.getAtom(3) || this.getAtomsFrom(1).join(\"_\")\n }\n }\n description Combine rows with matching values into groups.\n example\n tables posts.csv\n groupBy year\n printTable\n cue groupBy\n javascript\n get coreTable() {\n if (this._coreTable) return this._coreTable\n const groupByColNames = this.getAtomsFrom(1)\n const {coreTable} = this.parent\n if (!groupByColNames.length) return coreTable\n const newCols = this.findParticles(\"reduce\").map(particle => particle.reduction)\n // Pivot is shorthand for group and reduce?\n const makePivotTable = (rows, groupByColumnNames, inputColumnNames, newCols) => {\n const colMap = {}\n inputColumnNames.forEach((col) => (colMap[col] = true))\n const groupByCols = groupByColumnNames.filter((col) => colMap[col])\n return new PivotTable(rows, inputColumnNames.map(c => {return {name: c}}), newCols).getNewRows(groupByCols)\n }\n class PivotTable {\n constructor(rows, inputColumns, outputColumns) {\n this._columns = {}\n this._rows = rows\n inputColumns.forEach((col) => (this._columns[col.name] = col))\n outputColumns.forEach((col) => (this._columns[col.name] = col))\n }\n _getGroups(allRows, groupByColNames) {\n const rowsInGroups = new Map()\n allRows.forEach((row) => {\n const groupKey = groupByColNames.map((col) => row[col]?.toString().replace(/ /g, \"\") || \"\").join(\" \")\n if (!rowsInGroups.has(groupKey)) rowsInGroups.set(groupKey, [])\n rowsInGroups.get(groupKey).push(row)\n })\n return rowsInGroups\n }\n getNewRows(groupByCols) {\n // make new particles\n const rowsInGroups = this._getGroups(this._rows, groupByCols)\n // Any column in the group should be reused by the children\n const columns = [\n {\n name: \"count\",\n type: \"number\",\n min: 0,\n },\n ]\n groupByCols.forEach((colName) => columns.push(this._columns[colName]))\n const colsToReduce = Object.values(this._columns).filter((col) => !!col.reduction)\n colsToReduce.forEach((col) => columns.push(col))\n // for each group\n const rows = []\n const totalGroups = rowsInGroups.size\n for (let [groupId, group] of rowsInGroups) {\n const firstRow = group[0]\n const newRow = {}\n groupByCols.forEach((col) =>\n newRow[col] = firstRow ? firstRow[col] : 0\n )\n newRow.count = group.length\n // todo: add more reductions? count, stddev, median, variance.\n colsToReduce.forEach((col) => {\n const sourceColName = col.source\n const reduction = col.reduction\n const newColName = col.name\n if (reduction === \"concat\") {\n newRow[newColName] = group.map((row) => row[sourceColName]).join(\" \")\n return \n }\n if (reduction === \"first\") {\n newRow[newColName] = group.find((row) => row[sourceColName] !== \"\")?.[sourceColName]\n return \n }\n const values = group.map((row) => row[sourceColName]).filter((val) => typeof val === \"number\" && !isNaN(val))\n let reducedValue = firstRow[sourceColName]\n if (reduction === \"sum\") reducedValue = values.reduce((prev, current) => prev + current, 0)\n if (reduction === \"max\") reducedValue = Math.max(...values)\n if (reduction === \"min\") reducedValue = Math.min(...values)\n if (reduction === \"mean\") reducedValue = values.reduce((prev, current) => prev + current, 0) / values.length\n newRow[newColName] = reducedValue\n })\n rows.push(newRow)\n }\n // todo: add tests. figure out this api better.\n Object.values(columns).forEach((col) => {\n // For pivot columns, remove the source and reduction info for now. Treat things as immutable.\n delete col.source\n delete col.reduction\n })\n return {\n rows,\n columns,\n }\n }\n }\n const pivotTable = makePivotTable(coreTable, groupByColNames, this.parent.columnNames, newCols)\n this._coreTable = pivotTable.rows\n this._columnNames = pivotTable.columns.map(col => col.name)\n return pivotTable.rows\n }\n get columnNames() {\n const {coreTable} = this\n return this._columnNames || this.parent.columnNames\n }\nscrollWhereParser\n extends abstractTableTransformParser\n description Filter rows by condition.\n cue where\n atoms cueAtom columnNameAtom comparisonAtom\n catchAllAtomType constantAtom\n example\n table iris.csv\n where Species = setosa\n javascript\n get coreTable() {\n // todo: use atoms here.\n const columnName = this.connectColumnName(this.getAtom(1))\n const operator = this.getAtom(2)\n let untypedComparisonValue = this.getAtom(3)\n const typedComparisonValue = isNaN(parseFloat(untypedComparisonValue)) ? untypedComparisonValue : parseFloat(untypedComparisonValue)\n const coreTable = this.parent.coreTable\n if (!columnName || !operator || (untypedComparisonValue === undefined && !operator.includes(\"mpty\"))) return coreTable\n const filterFn = row => {\n const atom = row[columnName]\n const typedAtom = atom === null ? undefined : atom // convert nulls to undefined\n if (operator === \"=\") return typedComparisonValue === typedAtom\n else if (operator === \"!=\") return typedComparisonValue !== typedAtom\n else if (operator === \"includes\") return typedAtom !== undefined && typedAtom.includes(typedComparisonValue)\n else if (operator === \"startsWith\") return typedAtom !== undefined && typedAtom.toString().startsWith(typedComparisonValue)\n else if (operator === \"endsWith\") return typedAtom !== undefined && typedAtom.toString().endsWith(typedComparisonValue)\n else if (operator === \"doesNotInclude\") return typedAtom === undefined || !typedAtom.includes(typedComparisonValue)\n else if (operator === \">\") return typedAtom > typedComparisonValue\n else if (operator === \"<\") return typedAtom < typedComparisonValue\n else if (operator === \">=\") return typedAtom >= typedComparisonValue\n else if (operator === \"<=\") return typedAtom <= typedComparisonValue\n else if (operator === \"empty\") return typedAtom === \"\" || typedAtom === undefined\n else if (operator === \"notEmpty\") return typedAtom !== \"\" && typedAtom !== undefined\n }\n return coreTable.filter(filterFn)\n }\nscrollSelectParser\n catchAllAtomType columnNameAtom\n extends abstractTableTransformParser\n description Drop all columns except these.\n example\n tables\n data\n name,year,count\n index,2022,2\n about,2023,4\n select name year\n printTable\n cue select\n javascript\n get coreTable() {\n const {coreTable} = this.parent\n const {columnNames} = this\n if (!columnNames.length) return coreTable\n return coreTable.map(row => Object.fromEntries(columnNames.map(colName => [colName, row[colName]])))\n }\n get columnNames() {\n if (!this._columnNames) {\n const names = this.getAtomsFrom(1)\n this._columnNamesMap = this.connectColumnNames(names)\n this._columnNames = names.map(name => this._columnNamesMap[name])\n }\n return this._columnNames\n }\nscrollReverseParser\n extends abstractTableTransformParser\n description Reverse rows.\n cue reverse\n javascript\n get coreTable() {\n return this.parent.coreTable.slice().reverse()\n }\nscrollComposeParser\n extends abstractTableTransformParser\n description Add column using format string.\n catchAllAtomType codeAtom\n cue compose\n atoms cueAtom newColumnNameAtom\n example\n table\n compose sentence My name is {name}\n printTable\n javascript\n get coreTable() {\n const {newColumnName} = this\n const formatString = this.getAtomsFrom(2).join(\" \")\n return this.parent.coreTable.map((row, index) => {\n const newRow = Object.assign({}, row)\n newRow[newColumnName] = this.evaluate(new Particle(row).evalTemplateString(formatString), index)\n return newRow\n })\n }\n evaluate(str) {\n return str\n }\n get newColumnName() {\n return this.atoms[1]\n }\n get columnNames() {\n return this.parent.columnNames.concat(this.newColumnName)\n }\nscrollComputeParser\n extends scrollComposeParser\n description Add column by evaling format string.\n cue compute\n javascript\n evaluate(str) {\n return parseFloat(eval(str))\n }\nscrollEvalParser\n extends scrollComputeParser\n description Add column by evaling format string.\n cue eval\n javascript\n evaluate(str) {\n return eval(str)\n }\nscrollRankParser\n extends scrollComposeParser\n description Add rank column.\n atoms cueAtom\n string newColumnName rank\n cue rank\n javascript\n evaluate(str, index) { return index + 1 }\nscrollLinksParser\n extends abstractTableTransformParser\n description Add column with links.\n cue links\n catchAllAtomType columnNameAtom\n javascript\n get coreTable() {\n const {newColumnName, linkColumns} = this\n return this.parent.coreTable.map(row => {\n const newRow = Object.assign({}, row)\n let newValue = []\n linkColumns.forEach(name => {\n const value = newRow[name]\n delete newRow[name]\n if (value) newValue.push(`<a href=\"${value.includes(\"@\") ? \"mailto:\" : \"\"}${value}\">${name}</a>`)\n })\n newRow[newColumnName] = newValue.join(\" \")\n return newRow\n })\n }\n get newColumnName() {\n return \"links\"\n }\n get linkColumns() {\n return this.getAtomsFrom(1)\n }\n get columnNames() {\n const {linkColumns} = this\n return this.parent.columnNames.filter(name => !linkColumns.includes(name)).concat(this.newColumnName)\n }\nscrollLimitParser\n extends abstractTableTransformParser\n description Select a subset.\n cue limit\n atoms cueAtom integerAtom integerAtom\n javascript\n get coreTable() {\n let start = this.getAtom(1)\n let end = this.getAtom(2)\n if (end === undefined) {\n end = start\n start = 0\n }\n return this.parent.coreTable.slice(parseInt(start), parseInt(end))\n }\nscrollShuffleParser\n extends abstractTableTransformParser\n description Randomly reorder rows.\n cue shuffle\n example\n table data.csv\n shuffle\n printTable\n javascript\n get coreTable() {\n // Create a copy of the table to avoid modifying original\n const rows = this.parent.coreTable.slice()\n // Fisher-Yates shuffle algorithm\n for (let i = rows.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * (i + 1))\n ;[rows[i], rows[j]] = [rows[j], rows[i]]\n }\n return rows\n }\nscrollTransposeParser\n extends abstractTableTransformParser\n description Tranpose table.\n cue transpose\n javascript\n get coreTable() {\n // todo: we need to switch to column based coreTable, instead of row based\n const transpose = arr => Object.keys(arr[0]).map(key => [key, ...arr.map(row => row[key])]);\n return transpose(this.parent.coreTable)\n }\nscrollImputeParser\n extends abstractTableTransformParser\n description Impute missing values of a columm.\n atoms cueAtom columnNameAtom\n cue impute\n javascript\n get coreTable() {\n const {columnName} = this\n const sorted = this.root.lodash.orderBy(this.parent.coreTable.slice(), columnName)\n // ascending\n const imputed = []\n let lastInserted = sorted[0][columnName]\n sorted.forEach(row => {\n const measuredTime = row[columnName]\n while (measuredTime > lastInserted + 1) {\n lastInserted++\n // synthesize rows\n const imputedRow = {}\n imputedRow[columnName] = lastInserted\n imputedRow.count = 0\n imputed.push(imputedRow)\n }\n lastInserted = measuredTime\n imputed.push(row)\n })\n return imputed\n }\n get columnName() {\n return this.connectColumnName(this.getAtom(1))\n }\nscrollOrderByParser\n extends abstractTableTransformParser\n description Sort rows by column(s).\n catchAllAtomType columnNameAtom\n cue orderBy\n javascript\n get coreTable() {\n const makeLodashOrderByParams = str => {\n const part1 = str.split(\" \")\n const part2 = part1.map(col => (col.startsWith(\"-\") ? \"desc\" : \"asc\"))\n return [part1.map(col => this.connectColumnName(col.replace(/^\\-/, \"\"))), part2]\n }\n const orderBy = makeLodashOrderByParams(this.content)\n return this.root.lodash.orderBy(this.parent.coreTable.slice(), orderBy[0], orderBy[1])\n }\nassertRowCountParser\n extends abstractTableTransformParser\n description Test row count is expected value.\n atoms cueAtom integerAtom\n cueFromId\n javascript\n getErrors() {\n const errors = super.getErrors()\n const actualRows = this.coreTable.length\n const expectedRows = parseInt(this.content)\n if (actualRows !== expectedRows)\n return errors.concat(this.makeError(`Expected '${expectedRows}' rows but got '${actualRows}'.`))\n return errors\n }\nscrollRenameParser\n // todo: add support in Parsers for tuple catch alls\n catchAllAtomType columnNameAtom newColumnNameAtom\n catchAllAtomType newColumnNameAtom\n extends abstractTableTransformParser\n description Rename columns.\n example\n tables\n data\n name,year,count\n index,2022,2\n rename name Name year Year\n printTable\n cue rename\n javascript\n get coreTable() {\n const {coreTable} = this.parent\n const {renameMap} = this\n if (!Object.keys(renameMap).length) return coreTable\n return coreTable.map(row => {\n const newRow = {}\n Object.keys(row).forEach(key => {\n const name = renameMap[key] || key\n newRow[name] = row[key]\n })\n return newRow\n })\n }\n get renameMap() {\n const map = {}\n const pairs = this.getAtomsFrom(1)\n let oldName\n while (oldName = pairs.shift()) {\n map[oldName] = pairs.shift()\n }\n return map\n }\n _renamed\n get columnNames() {\n if (this._renamed)\n return this._renamed\n const {renameMap} = this\n this._renamed = this.parent.columnNames.map(name => renameMap[name] || name )\n return this._renamed\n }\nscrollSummarizeParser\n extends abstractTableTransformParser\n description Generate summary statistics for each column.\n cue summarize\n example\n table data.csv\n summarize\n printTable\n javascript\n get coreTable() {\n const {lodash} = this.root\n const sourceData = this.parent.coreTable\n if (!sourceData.length) return []\n return this.parent.columnNames.map(colName => {\n const values = sourceData.map(row => row[colName]).filter(val => val !== undefined && val !== null)\n const numericValues = values.filter(val => typeof val === \"number\" && !isNaN(val))\n const sorted = [...numericValues].sort((a, b) => a - b)\n // Calculate mode\n const frequency = {}\n values.forEach(val => {\n frequency[val] = (frequency[val] || 0) + 1\n })\n const mode = Object.entries(frequency)\n .sort((a, b) => b[1] - a[1])\n .map(entry => entry[0])[0]\n // Calculate median for numeric values\n const median = sorted.length ? \n sorted.length % 2 === 0 \n ? (sorted[sorted.length/2 - 1] + sorted[sorted.length/2]) / 2\n : sorted[Math.floor(sorted.length/2)]\n : null\n const sum = numericValues.length ? numericValues.reduce((a, b) => a + b, 0) : null\n const theType = typeof values[0]\n const count = values.length\n const mean = theType === \"number\" ? sum/count : \"\"\n return {\n name: colName,\n type: theType,\n incompleteCount: sourceData.length - values.length,\n uniqueCount: new Set(values).size,\n count,\n sum,\n median,\n mean,\n min: sorted.length ? sorted[0] : null,\n max: sorted.length ? sorted[sorted.length - 1] : null,\n mode\n }\n })\n }\n get columnNames() {\n return [\"name\", \"type\", \"incompleteCount\", \"uniqueCount\", \"count\", \"sum\", \"median\", \"mean\", \"min\", \"max\", \"mode\"]\n }\nerrorParser\n baseParser errorParser\nhakonContentParser\n popularity 0.102322\n catchAllAtomType codeAtom\nheatrixCatchAllParser\n popularity 0.000193\n // todo Fill this out\n catchAllAtomType stringAtom\nlineOfTextParser\n popularity 0.000289\n catchAllAtomType stringAtom\n boolean isTextParser true\nhtmlLineParser\n popularity 0.005209\n catchAllAtomType htmlAnyAtom\n catchAllParser htmlLineParser\nopenGraphParser\n // todo: fix Parsers scope issue so we can move this parser def under scrollImageParser\n description Add this line to make this the open graph image.\n cueFromId\n atoms cueAtom\nimportToFooterParser\n description Import to bottom of file.\n atoms preBuildCommandAtom\n cue footer\nscriptLineParser\n catchAllAtomType javascriptAnyAtom\n catchAllParser scriptLineParser\nlinkTitleParser\n popularity 0.000048\n description If you want to set the title of the link.\n cue title\n atoms cueAtom\n catchAllAtomType stringAtom\n example\n * This report showed the treatment had a big impact.\n https://example.com/report This report.\n title The average growth in the treatment group was 14.2x higher than the control group.\nprogramLinkParser\n popularity 0.000531\n catchAllAtomType codeAtom\nscrollMediaLoopParser\n popularity 0.000048\n cue loop\n atoms cueAtom\nscrollAutoplayParser\n cue autoplay\n atoms cueAtom\nabstractCompilerRuleParser\n catchAllAtomType anyAtom\n atoms cueAtom\ncloseSubparticlesParser\n extends abstractCompilerRuleParser\n description When compiling a parent particle to a string, this string is appended to the compiled and joined subparticles. Default is blank.\n cueFromId\nindentCharacterParser\n extends abstractCompilerRuleParser\n description You can change the indent character for compiled subparticles. Default is a space.\n cueFromId\ncatchAllAtomDelimiterParser\n description If a particle has a catchAllAtom, this is the string delimiter that will be used to join those atoms. Default is comma.\n extends abstractCompilerRuleParser\n cueFromId\nopenSubparticlesParser\n extends abstractCompilerRuleParser\n description When compiling a parent particle to a string, this string is prepended to the compiled and joined subparticles. Default is blank.\n cueFromId\nstringTemplateParser\n extends abstractCompilerRuleParser\n description This template string is used to compile this line, and accepts strings of the format: const var = {someAtomId}\n cueFromId\njoinSubparticlesWithParser\n description When compiling a parent particle to a string, subparticles are compiled to strings and joined by this character. Default is a newline.\n extends abstractCompilerRuleParser\n cueFromId\nabstractConstantParser\n description A constant.\n atoms cueAtom\n cueFromId\n // todo: make tags inherit\n tags actPhase\nparsersBooleanParser\n cue boolean\n atoms cueAtom constantIdentifierAtom\n catchAllAtomType booleanAtom\n extends abstractConstantParser\n tags actPhase\nparsersFloatParser\n cue float\n atoms cueAtom constantIdentifierAtom\n catchAllAtomType floatAtom\n extends abstractConstantParser\n tags actPhase\nparsersIntParser\n cue int\n atoms cueAtom constantIdentifierAtom\n catchAllAtomType integerAtom\n tags actPhase\n extends abstractConstantParser\nparsersStringParser\n cue string\n atoms cueAtom constantIdentifierAtom\n catchAllAtomType stringAtom\n catchAllParser catchAllMultilineStringConstantParser\n extends abstractConstantParser\n tags actPhase\nabstractParserRuleParser\n single\n atoms cueAtom\nabstractNonTerminalParserRuleParser\n extends abstractParserRuleParser\nparsersBaseParserParser\n atoms cueAtom baseParsersAtom\n description Set for blobs or errors. \n // In rare cases with untyped content you can use a blobParser, for now, to skip parsing for performance gains. The base errorParser will report errors when parsed. Use that if you don't want to implement your own error parser.\n extends abstractParserRuleParser\n cue baseParser\n tags analyzePhase\ncatchAllAtomTypeParser\n atoms cueAtom atomTypeIdAtom\n description Use for lists.\n // Aka 'listAtomType'. Use this when the value in a key/value pair is a list. If there are extra atoms in the particle's line, parse these atoms as this type. Often used with `listDelimiterParser`.\n extends abstractParserRuleParser\n cueFromId\n tags analyzePhase\natomParserParser\n atoms cueAtom atomParserAtom\n description Set parsing strategy.\n // prefix/postfix/omnifix parsing strategy. If missing, defaults to prefix.\n extends abstractParserRuleParser\n cueFromId\n tags experimental analyzePhase\ncatchAllParserParser\n description Attach this to unmatched lines.\n // If a parser is not found in the inScope list, instantiate this type of particle instead.\n atoms cueAtom parserIdAtom\n extends abstractParserRuleParser\n cueFromId\n tags acquirePhase\nparsersAtomsParser\n catchAllAtomType atomTypeIdAtom\n description Set required atomTypes.\n extends abstractParserRuleParser\n cue atoms\n tags analyzePhase\nparsersCompilerParser\n // todo Remove this and its subparticles?\n description Deprecated. For simple compilers.\n inScope stringTemplateParser catchAllAtomDelimiterParser openSubparticlesParser closeSubparticlesParser indentCharacterParser joinSubparticlesWithParser\n extends abstractParserRuleParser\n cue compiler\n tags deprecate\n boolean suggestInAutocomplete false\nparserDescriptionParser\n description Parser description.\n catchAllAtomType stringAtom\n extends abstractParserRuleParser\n cue description\n tags assemblePhase\nparsersExampleParser\n // todo Should this just be a \"string\" constant on particles?\n description Set example for docs and tests.\n catchAllAtomType exampleAnyAtom\n catchAllParser catchAllExampleLineParser\n extends abstractParserRuleParser\n cue example\n tags assemblePhase\nextendsParserParser\n cue extends\n tags assemblePhase\n description Extend another parser.\n // todo: add a catchall that is used for mixins\n atoms cueAtom parserIdAtom\n extends abstractParserRuleParser\nparsersPopularityParser\n // todo Remove this parser. Switch to conditional frequencies.\n description Parser popularity.\n atoms cueAtom floatAtom\n extends abstractParserRuleParser\n cue popularity\n tags assemblePhase\ninScopeParser\n description Parsers in scope.\n catchAllAtomType parserIdAtom\n extends abstractParserRuleParser\n cueFromId\n tags acquirePhase\nparsersJavascriptParser\n // todo Urgently need to get submode syntax highlighting running! (And eventually LSP)\n description Javascript code for Parser Actions.\n catchAllParser catchAllJavascriptCodeLineParser\n extends abstractParserRuleParser\n tags actPhase\n javascript\n format() {\n if (this.isNodeJs()) {\n const template = `class FOO{ ${this.subparticlesToString()}}`\n this.setSubparticles(\n require(\"prettier\")\n .format(template, { semi: false, useTabs: true, parser: \"babel\", printWidth: 240 })\n .replace(/class FOO \\{\\s+/, \"\")\n .replace(/\\s+\\}\\s+$/, \"\")\n .replace(/\\n\\t/g, \"\\n\") // drop one level of indent\n .replace(/\\t/g, \" \") // we used tabs instead of spaces to be able to dedent without breaking literals.\n )\n }\n return this\n }\n cue javascript\nabstractParseRuleParser\n // Each particle should have a pattern that it matches on unless it's a catch all particle.\n extends abstractParserRuleParser\n cueFromId\nparsersCueParser\n atoms cueAtom stringAtom\n description Attach by matching first atom.\n extends abstractParseRuleParser\n tags acquirePhase\n cue cue\ncueFromIdParser\n atoms cueAtom\n description Derive cue from parserId.\n // for example 'fooParser' would have cue of 'foo'.\n extends abstractParseRuleParser\n tags acquirePhase\nparsersPatternParser\n catchAllAtomType regexAtom\n description Attach via regex.\n extends abstractParseRuleParser\n tags acquirePhase\n cue pattern\nparsersRequiredParser\n description Assert is present at least once.\n extends abstractParserRuleParser\n cue required\n tags analyzePhase\nabstractValidationRuleParser\n extends abstractParserRuleParser\n cueFromId\n catchAllAtomType booleanAtom\nparsersSingleParser\n description Assert used once.\n // Can be overridden by a child class by setting to false.\n extends abstractValidationRuleParser\n tags analyzePhase\n cue single\nuniqueLineParser\n description Assert unique lines. For pattern parsers.\n // Can be overridden by a child class by setting to false.\n extends abstractValidationRuleParser\n tags analyzePhase\nuniqueCueParser\n description Assert unique first atoms. For pattern parsers.\n // For catch all parsers or pattern particles, use this to indicate the \n extends abstractValidationRuleParser\n tags analyzePhase\nlistDelimiterParser\n description Split content by this delimiter.\n extends abstractParserRuleParser\n cueFromId\n catchAllAtomType stringAtom\n tags analyzePhase\ncontentKeyParser\n description Deprecated. For to/from JSON.\n // Advanced keyword to help with isomorphic JSON serialization/deserialization. If present will serialize the particle to an object and set a property with this key and the value set to the particle's content.\n extends abstractParserRuleParser\n cueFromId\n catchAllAtomType stringAtom\n tags deprecate\n boolean suggestInAutocomplete false\nsubparticlesKeyParser\n // todo: deprecate?\n description Deprecated. For to/from JSON.\n // Advanced keyword to help with serialization/deserialization of blobs. If present will serialize the particle to an object and set a property with this key and the value set to the particle's subparticles.\n extends abstractParserRuleParser\n cueFromId\n catchAllAtomType stringAtom\n tags deprecate\n boolean suggestInAutocomplete false\nparsersTagsParser\n catchAllAtomType stringAtom\n extends abstractParserRuleParser\n description Custom metadata.\n cue tags\n tags assemblePhase\natomTypeDescriptionParser\n description Atom Type description.\n catchAllAtomType stringAtom\n cue description\n tags assemblePhase\ncatchAllErrorParser\n baseParser errorParser\ncatchAllExampleLineParser\n catchAllAtomType exampleAnyAtom\n catchAllParser catchAllExampleLineParser\n atoms exampleAnyAtom\ncatchAllJavascriptCodeLineParser\n catchAllAtomType javascriptCodeAtom\n catchAllParser catchAllJavascriptCodeLineParser\ncatchAllMultilineStringConstantParser\n description String constants can span multiple lines.\n catchAllAtomType stringAtom\n catchAllParser catchAllMultilineStringConstantParser\n atoms stringAtom\natomTypeDefinitionParser\n // todo Generate a class for each atom type?\n // todo Allow abstract atom types?\n // todo Change pattern to postfix.\n pattern ^[a-zA-Z0-9_]+Atom$\n inScope parsersPaintParser parsersRegexParser reservedAtomsParser enumFromAtomTypesParser atomTypeDescriptionParser parsersEnumParser slashCommentParser extendsAtomTypeParser parsersExamplesParser atomMinParser atomMaxParser\n atoms atomTypeIdAtom\n tags assemblePhase\n javascript\n buildHtml() {return \"\"}\nenumFromAtomTypesParser\n description Runtime enum options.\n catchAllAtomType atomTypeIdAtom\n atoms atomPropertyNameAtom\n cueFromId\n tags analyzePhase\nparsersEnumParser\n description Set enum options.\n cue enum\n catchAllAtomType enumOptionAtom\n atoms atomPropertyNameAtom\n tags analyzePhase\nparsersExamplesParser\n description Examples for documentation and tests.\n // If the domain of possible atom values is large, such as a string type, it can help certain methods—such as program synthesis—to provide a few examples.\n cue examples\n catchAllAtomType atomExampleAtom\n atoms atomPropertyNameAtom\n tags assemblePhase\natomMinParser\n description Specify a min if numeric.\n cue min\n atoms atomPropertyNameAtom numberAtom\n tags analyzePhase\natomMaxParser\n description Specify a max if numeric.\n cue max\n atoms atomPropertyNameAtom numberAtom\n tags analyzePhase\nparsersPaintParser\n atoms cueAtom paintTypeAtom\n description Instructor editor how to color these.\n single\n cue paint\n tags analyzePhase\nparserDefinitionParser\n // todo Add multiple dispatch?\n pattern ^[a-zA-Z0-9_]+Parser$\n description Parser types are a core unit of your language. They translate to 1 class per parser. Examples of parser would be \"header\", \"person\", \"if\", \"+\", \"define\", etc.\n catchAllParser catchAllErrorParser\n inScope abstractParserRuleParser abstractConstantParser slashCommentParser parserDefinitionParser\n atoms parserIdAtom\n tags assemblePhase\n javascript\n buildHtml() { return \"\"}\nparsersRegexParser\n catchAllAtomType regexAtom\n description Atoms must match this.\n single\n atoms atomPropertyNameAtom\n cue regex\n tags analyzePhase\nreservedAtomsParser\n single\n description Atoms can't be any of these.\n catchAllAtomType reservedAtomAtom\n atoms atomPropertyNameAtom\n cueFromId\n tags analyzePhase\nextendsAtomTypeParser\n cue extends\n description Extend another atomType.\n // todo Add mixin support in addition to extends?\n atoms cueAtom atomTypeIdAtom\n tags assemblePhase\n single\nabstractColumnNameParser\n atoms cueAtom columnNameAtom\n javascript\n getRunTimeEnumOptions(atom) {\n if (atom.atomTypeId === \"columnNameAtom\")\n return this.parent.columnNames\n return super.getRunTimeEnumOptions(atom)\n }\nscrollRadiusParser\n cue radius\n extends abstractColumnNameParser\nscrollSymbolParser\n cue symbol\n extends abstractColumnNameParser\nabstractColumnNameOrColorParser\n extends abstractColumnNameParser\n atoms cueAtom columnNameOrColorAtom\n javascript\n //todo: cleanup\n colorOptions = \"aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkkhaki darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray darkturquoise darkviolet deeppink deepskyblue dimgray dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow honeydew hotpink indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgoldenrodyellow lightgray lightgreen lightpink lightsalmon lightseagreen lightskyblue lightslategray lightsteelblue lightyellow lime limegreen linen magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell sienna silver skyblue slateblue slategray snow springgreen steelblue tan teal thistle tomato turquoise violet wheat white whitesmoke yellow yellowgreen\".split(\" \")\n getRunTimeEnumOptions(atom) {\n if (atom.atomTypeId === \"columnNameOrColorAtom\")\n return this.parent.columnNames.join(this.colorOptions)\n return super.getRunTimeEnumOptions(atom)\n }\nscrollFillParser\n cue fill\n extends abstractColumnNameOrColorParser\nscrollStrokeParser\n cue stroke\n extends abstractColumnNameOrColorParser\nscrollLabelParser\n cue label\n extends abstractColumnNameParser\nscrollSortParser\n cue sort\n extends abstractColumnNameParser\nscrollXParser\n cue x\n extends abstractColumnNameParser\nscrollYParser\n cue y\n extends abstractColumnNameParser\nabstractPlotLabelParser\n cueFromId\n atoms cueAtom\n catchAllAtomType stringAtom\nquoteLineParser\n popularity 0.004172\n catchAllAtomType stringAtom\n catchAllParser quoteLineParser\nscrollParser\n description Scroll is a language for scientists of all ages. Refine, share and collaborate on ideas.\n root\n inScope abstractScrollParser blankLineParser atomTypeDefinitionParser parserDefinitionParser\n catchAllParser catchAllParagraphParser\n javascript\n setFile(file) {\n this.file = file\n const date = this.get(\"date\")\n if (date) this.file.timestamp = this.dayjs(this.get(\"date\")).unix()\n return this\n }\n buildHtml(buildSettings) {\n this.sectionStack = []\n return this.filter(subparticle => subparticle.buildHtml).map(subparticle => { try {return subparticle.buildHtml(buildSettings)} catch (err) {console.error(err); return \"\"} }).filter(i => i).join(\"\\n\") + this.clearSectionStack()\n }\n sectionStack = []\n clearSectionStack() {\n const result = this.sectionStack.join(\"\\n\")\n this.sectionStack = []\n return result\n }\n bodyStack = []\n clearBodyStack() {\n const result = this.bodyStack.join(\"\")\n this.bodyStack = []\n return result\n }\n get hakonParser() {\n if (this.isNodeJs())\n return require(\"scrollsdk/products/hakon.nodejs.js\")\n return hakonParser\n }\n readSyncFromFileOrUrl(fileOrUrl) {\n if (!this.isNodeJs()) return this.getInBrowser(fileOrUrl)\n const isUrl = fileOrUrl.match(/^https?\\:[^ ]+$/)\n if (!isUrl) return this.root.readFile(fileOrUrl)\n return this.readFile(this.makeFullPath(new URL(fileOrUrl).pathname.split('/').pop()))\n }\n getInBrowser(key) {\n return localStorage.getItem(key) || (window.inMemStorage ? window.inMemStorage[key] : \"\") || \"\"\n }\n async fetch(url, filename) {\n const isUrl = url.match(/^https?\\:[^ ]+$/)\n if (!isUrl) return\n return this.isNodeJs() ? this.fetchNode(url, filename) : this.fetchBrowser(url)\n }\n get path() {\n return require(\"path\")\n }\n makeFullPath(filename) {\n return this.path.join(this.folderPath, filename)\n }\n _nextAndPrevious(arr, index) {\n const nextIndex = index + 1\n const previousIndex = index - 1\n return {\n previous: arr[previousIndex] ?? arr[arr.length - 1],\n next: arr[nextIndex] ?? arr[0]\n }\n }\n // keyboard nav is always in the same folder. does not currently support cross folder\n includeFileInKeyboardNav(file) {\n const { scrollProgram } = file\n return scrollProgram.buildsHtml && scrollProgram.hasKeyboardNav && scrollProgram.tags.includes(this.primaryTag)\n }\n get timeIndex() {\n return this.file.timeIndex || 0\n }\n get linkToPrevious() {\n if (!this.hasKeyboardNav)\n // Dont provide link to next unless keyboard nav is on\n return undefined\n const {allScrollFiles} = this\n let file = this._nextAndPrevious(allScrollFiles, this.timeIndex).previous\n while (!this.includeFileInKeyboardNav(file)) {\n file = this._nextAndPrevious(allScrollFiles, file.timeIndex).previous\n }\n return file.scrollProgram.permalink\n }\n importRegex = /^(import |[a-zA-Z\\_\\-\\.0-9\\/]+\\.(scroll|parsers)$|https?:\\/\\/.+\\.(scroll|parsers)$)/gm\n get linkToNext() {\n if (!this.hasKeyboardNav)\n // Dont provide link to next unless keyboard nav is on\n return undefined\n const {allScrollFiles} = this\n let file = this._nextAndPrevious(allScrollFiles, this.timeIndex).next\n while (!this.includeFileInKeyboardNav(file)) {\n file = this._nextAndPrevious(allScrollFiles, file.timeIndex).next\n }\n return file.scrollProgram.permalink\n }\n // todo: clean up this naming pattern and add a parser instead of special casing 404.html\n get allHtmlFiles() {\n return this.allScrollFiles.filter(file => file.scrollProgram.buildsHtml && file.scrollProgram.permalink !== \"404.html\")\n }\n parseNestedTag(tag) {\n if (!tag.includes(\"/\")) return;\n const {path} = this\n const parts = tag.split(\"/\")\n const group = parts.pop()\n const relativePath = parts.join(\"/\")\n return {\n group,\n relativePath,\n folderPath: path.join(this.folderPath, path.normalize(relativePath))\n }\n }\n getFilesByTags(tags, limit) {\n // todo: tags is currently matching partial substrings\n const getFilesWithTag = (tag, files) => files.filter(file => file.scrollProgram.buildsHtml && file.scrollProgram.tags.includes(tag))\n if (typeof tags === \"string\") tags = tags.split(\" \")\n if (!tags || !tags.length)\n return this.allHtmlFiles\n .filter(file => file !== this) // avoid infinite loops. todo: think this through better.\n .map(file => {\n return { file, relativePath: \"\" }\n })\n .slice(0, limit)\n let arr = []\n tags.forEach(tag => {\n if (!tag.includes(\"/\"))\n return (arr = arr.concat(\n getFilesWithTag(tag, this.allScrollFiles)\n .map(file => {\n return { file, relativePath: \"\" }\n })\n .slice(0, limit)\n ))\n const {folderPath, group, relativePath} = this.parseNestedTag(tag)\n let files = []\n try {\n files = this.fileSystem.getCachedLoadedFilesInFolder(folderPath, this)\n } catch (err) {\n console.error(err)\n }\n const filtered = getFilesWithTag(group, files).map(file => {\n return { file, relativePath: relativePath + \"/\" }\n })\n arr = arr.concat(filtered.slice(0, limit))\n })\n return this.lodash.sortBy(arr, file => file.file.timestamp).reverse()\n }\n async fetchNode(url, filename) {\n filename = filename || new URL(url).pathname.split('/').pop()\n const fullpath = this.makeFullPath(filename)\n if (require(\"fs\").existsSync(fullpath)) return this.readFile(fullpath)\n this.log(`🛜 fetching ${url} to ${fullpath} `)\n await this.downloadToDisk(url, fullpath)\n return this.readFile(fullpath)\n }\n log(message) {\n if (this.logger) this.logger.log(message)\n }\n async fetchBrowser(url) {\n const content = this.getInBrowser(url)\n if (content) return content\n return this.downloadToLocalStorage(url)\n }\n async downloadToDisk(url, destination) {\n const { writeFile } = require('fs').promises\n const response = await fetch(url)\n const fileBuffer = await response.arrayBuffer()\n await writeFile(destination, Buffer.from(fileBuffer))\n return this.readFile(destination)\n }\n async downloadToLocalStorage(url) {\n const response = await fetch(url)\n const blob = await response.blob()\n const text = await blob.text()\n try {\n localStorage.setItem(url, text)\n return localStorage.getItem(url)\n } catch (err) {\n if (!window.inMemStorage) window.inMemStorage = {}\n window.inMemStorage[url] = text\n console.error(err)\n return text\n }\n }\n readFile(filename) {\n const {path} = this\n const fs = require(\"fs\")\n const fullPath = path.join(this.folderPath, filename.replace(this.folderPath, \"\"))\n try {\n if (fs.existsSync(fullPath))\n return fs.readFileSync(fullPath, \"utf8\")\n console.error(`File '${filename}' not found`)\n return \"\"\n } catch (err) {\n console.error(`Error in '${this.filePath}' reading file: '${fullPath}'`)\n console.error(err)\n return \"\"\n }\n }\n alreadyRequired = new Set()\n buildHtmlSnippet(buildSettings) {\n this.sectionStack = []\n return this.map(subparticle => (subparticle.buildHtmlSnippet ? subparticle.buildHtmlSnippet(buildSettings) : subparticle.buildHtml(buildSettings)))\n .filter(i => i)\n .join(\"\\n\")\n .trim() + this.clearSectionStack()\n }\n get footnotes() {\n if (this._footnotes === undefined) this._footnotes = this.filter(particle => particle.isFootnote)\n return this._footnotes\n }\n get authors() {\n return this.get(\"authors\")\n }\n get allScrollFiles() {\n try {\n return this.fileSystem.getCachedLoadedFilesInFolder(this.folderPath, this)\n } catch (err) {\n console.error(err)\n return []\n }\n }\n async doThing(thing) {\n await Promise.all(this.filter(particle => particle[thing]).map(async particle => particle[thing]()))\n }\n async load() {\n await this.doThing(\"load\")\n }\n async execute() {\n await this.doThing(\"execute\")\n }\n file = {}\n getFromParserId(parserId) {\n return this.parserIdIndex[parserId]?.[0].content\n }\n get fileSystem() {\n return this.file.fileSystem\n }\n get filePath() {\n return this.file.filePath\n }\n get folderPath() {\n return this.file.folderPath\n }\n get filename() {\n return this.file.filename || \"\"\n }\n get hasKeyboardNav() {\n return this.has(\"keyboardNav\")\n }\n get editHtml() {\n return `<a href=\"${this.editUrl}\" class=\"abstractTextLinkParser\">Edit</a>`\n }\n get externalsPath() {\n return this.file.EXTERNALS_PATH\n }\n get endSnippetIndex() {\n // Get the line number that the snippet should stop at.\n // First if its hard coded, use that\n if (this.has(\"endSnippet\")) return this.getParticle(\"endSnippet\").index\n // Next look for a dinkus\n const snippetBreak = this.find(particle => particle.isDinkus)\n if (snippetBreak) return snippetBreak.index\n return -1\n }\n get parserIds() {\n return this.topDownArray.map(particle => particle.definition.id)\n }\n get tags() {\n return this.get(\"tags\") || \"\"\n }\n get primaryTag() {\n return this.tags.split(\" \")[0]\n }\n get filenameNoExtension() {\n return this.filename.replace(\".scroll\", \"\")\n }\n // todo: rename publishedUrl? Or something to indicate that this is only for stuff on the web (not localhost)\n // BaseUrl must be provided for RSS Feeds and OpenGraph tags to work\n get baseUrl() {\n const baseUrl = (this.get(\"baseUrl\") || \"\").replace(/\\/$/, \"\")\n return baseUrl + \"/\"\n }\n get canonicalUrl() {\n return this.get(\"canonicalUrl\") || this.baseUrl + this.permalink\n }\n get openGraphImage() {\n const openGraphImage = this.get(\"openGraphImage\")\n if (openGraphImage !== undefined) return this.ensureAbsoluteLink(openGraphImage)\n const images = this.filter(particle => particle.doesExtend(\"scrollImageParser\"))\n const hit = images.find(particle => particle.has(\"openGraph\")) || images[0]\n if (!hit) return \"\"\n return this.ensureAbsoluteLink(hit.filename)\n }\n get absoluteLink() {\n return this.ensureAbsoluteLink(this.permalink)\n }\n ensureAbsoluteLink(link) {\n if (link.includes(\"://\")) return link\n return this.baseUrl + link.replace(/^\\//, \"\")\n }\n get editUrl() {\n const editUrl = this.get(\"editUrl\")\n if (editUrl) return editUrl\n const editBaseUrl = this.get(\"editBaseUrl\")\n return (editBaseUrl ? editBaseUrl.replace(/\\/$/, \"\") + \"/\" : \"\") + this.filename\n }\n get gitRepo() {\n // given https://github.com/breck7/breckyunits.com/blob/main/four-tips-to-improve-communication.scroll\n // return https://github.com/breck7/breckyunits.com\n return this.editUrl.split(\"/\").slice(0, 5).join(\"/\")\n }\n get scrollVersion() {\n // currently manually updated\n return \"168.0.0\"\n }\n // Use the first paragraph for the description\n // todo: add a particle method version of get that gets you the first particle. (actulaly make get return array?)\n // would speed up a lot.\n get description() {\n const description = this.getFromParserId(\"openGraphDescriptionParser\")\n if (description) return description\n return this.generatedDescription\n }\n get keywords() {\n if (this.has(\"keywords\"))\n return this.get(\"keywords\")\n const tags = this.get(\"tags\")\n if (tags)\n return tags.split(\" \").join(\", \")\n return \"\"\n }\n get generatedDescription() {\n const firstParagraph = this.find(particle => particle.isArticleContent)\n return firstParagraph ? firstParagraph.originalText.substr(0, 100).replace(/[&\"<>']/g, \"\") : \"\"\n }\n get titleFromFilename() {\n const unCamelCase = str => str.replace(/([a-z])([A-Z])/g, \"$1 $2\").replace(/^./, match => match.toUpperCase())\n return unCamelCase(this.filenameNoExtension)\n }\n get title() {\n return this.getFromParserId(\"scrollTitleParser\") || this.titleFromFilename\n }\n get linkTitle() {\n return this.getFromParserId(\"scrollLinkTitleParser\") || this.title\n }\n get permalink() {\n return this.get(\"permalink\") || (this.filename ? this.filenameNoExtension + \".html\" : \"\")\n }\n compileTo(extensionCapitalized) {\n if (extensionCapitalized === \"Txt\")\n return this.asTxt\n if (extensionCapitalized === \"Html\")\n return this.asHtml\n const methodName = \"build\" + extensionCapitalized\n return this.topDownArray\n .filter(particle => particle[methodName])\n .map((particle, index) => particle[methodName](index))\n .join(\"\\n\")\n .trim()\n }\n get asTxt() {\n return (\n this.map(particle => {\n const text = particle.buildTxt ? particle.buildTxt() : \"\"\n if (text) return text + \"\\n\"\n if (!particle.getLine().length) return \"\\n\"\n return \"\"\n })\n .join(\"\")\n .replace(/<[^>]*>/g, \"\")\n .replace(/\\n\\n\\n+/g, \"\\n\\n\") // Maximum 2 newlines in a row\n .trim() + \"\\n\" // Always end in a newline, Posix style\n )\n }\n get dependencies() {\n const dependencies = this.file.dependencies?.slice() || []\n const files = this.topDownArray.filter(particle => particle.dependencies).map(particle => particle.dependencies).flat()\n return dependencies.concat(files)\n }\n get buildsHtml() {\n const { permalink } = this\n return !this.file.importOnly && (permalink.endsWith(\".html\") || permalink.endsWith(\".htm\"))\n }\n // Without specifying the language hyphenation will not work.\n get lang() {\n return this.get(\"htmlLang\") || \"en\"\n }\n _compiledHtml = \"\"\n get asHtml() {\n if (!this._compiledHtml) {\n const { permalink, buildsHtml } = this\n const content = (this.buildHtml() + this.clearBodyStack()).trim()\n // Don't add html tags to CSV feeds. A little hacky as calling a getter named _html_ to get _xml_ is not ideal. But\n // <1% of use case so might be good enough.\n const wrapWithHtmlTags = buildsHtml\n const bodyTag = this.has(\"metaTags\") ? \"\" : \"<body>\\n\"\n this._compiledHtml = wrapWithHtmlTags ? `<!DOCTYPE html>\\n<html lang=\"${this.lang}\">\\n${bodyTag}${content}\\n</body>\\n</html>` : content\n }\n return this._compiledHtml\n }\n get wordCount() {\n return this.asTxt.match(/\\b\\w+\\b/g)?.length || 0\n }\n get minutes() {\n return parseFloat((this.wordCount / 200).toFixed(1))\n }\n get date() {\n const date = this.get(\"date\") || (this.file.timestamp ? this.file.timestamp : 0)\n return this.dayjs(date).format(`MM/DD/YYYY`)\n }\n get year() {\n return parseInt(this.dayjs(this.date).format(`YYYY`))\n }\n get dayjs() {\n if (!this.isNodeJs()) return dayjs\n const lib = require(\"dayjs\")\n const relativeTime = require(\"dayjs/plugin/relativeTime\")\n lib.extend(relativeTime)\n return lib\n }\n get lodash() {\n return this.isNodeJs() ? require(\"lodash\") : lodash\n }\n get d3() {\n return this.isNodeJs() ? require('d3') : d3\n }\n getConcepts(parsed) {\n const concepts = []\n let currentConcept\n parsed.forEach(particle => {\n if (particle.isConceptDelimiter) {\n if (currentConcept) concepts.push(currentConcept)\n currentConcept = []\n }\n if (currentConcept && particle.isMeasure) currentConcept.push(particle)\n })\n if (currentConcept) concepts.push(currentConcept)\n return concepts\n }\n _formatConcepts(parsed) {\n const concepts = this.getConcepts(parsed)\n if (!concepts.length) return false\n const {lodash} = this\n // does a destructive sort in place on the parsed program\n concepts.forEach(concept => {\n let currentSection\n const newCode = lodash\n .sortBy(concept, [\"sortIndex\"])\n .map(particle => {\n let newLines = \"\"\n const section = particle.sortIndex.toString().split(\".\")[0]\n if (section !== currentSection) {\n currentSection = section\n newLines = \"\\n\"\n }\n return newLines + particle.toString()\n })\n .join(\"\\n\")\n concept.forEach((particle, index) => (index ? particle.destroy() : \"\"))\n concept[0].replaceParticle(() => newCode)\n })\n }\n get formatted() {\n return this.getFormatted(this.file.codeAtStart)\n }\n get lastCommitTime() {\n // todo: speed this up and do a proper release. also could add more metrics like this.\n if (this._lastCommitTime === undefined) {\n try {\n this._lastCommitTime = require(\"child_process\").execSync(`git log -1 --format=\"%at\" -- \"${this.filePath}\"`).toString().trim()\n } catch (err) {\n this._lastCommitTime = 0\n }\n }\n return this._lastCommitTime\n }\n getFormatted(codeAtStart = this.toString()) {\n let formatted = codeAtStart.replace(/\\r/g, \"\") // remove all carriage returns if there are any\n const parsed = new this.constructor(formatted)\n parsed.topDownArray.forEach(subparticle => {\n subparticle.format()\n const original = subparticle.getLine()\n const trimmed = original.replace(/(\\S.*?)[ \\t]*$/gm, \"$1\")\n // Trim trailing whitespace unless parser allows it\n if (original !== trimmed && !subparticle.allowTrailingWhitespace) subparticle.setLine(trimmed)\n })\n this._formatConcepts(parsed)\n let importOnlys = []\n let topMatter = []\n let allElse = []\n // Create any bindings\n parsed.forEach(particle => {\n if (particle.bindTo === \"next\") particle.binding = particle.next\n if (particle.bindTo === \"previous\") particle.binding = particle.previous\n })\n parsed.forEach(particle => {\n if (particle.getLine() === \"importOnly\") importOnlys.push(particle)\n else if (particle.isTopMatter) topMatter.push(particle)\n else allElse.push(particle)\n })\n const combined = importOnlys.concat(topMatter, allElse)\n // Move any bound particles\n combined\n .filter(particle => particle.bindTo)\n .forEach(particle => {\n // First remove the particle from its current position\n const originalIndex = combined.indexOf(particle)\n combined.splice(originalIndex, 1)\n // Then insert it at the new position\n // We need to find the binding index again after removal\n const bindingIndex = combined.indexOf(particle.binding)\n if (particle.bindTo === \"next\") combined.splice(bindingIndex, 0, particle)\n else combined.splice(bindingIndex + 1, 0, particle)\n })\n const trimmed = combined\n .map(particle => particle.toString())\n .join(\"\\n\")\n .replace(/^\\n*/, \"\") // Remove leading newlines\n .replace(/\\n\\n\\n+/g, \"\\n\\n\") // Maximum 2 newlines in a row\n .replace(/\\n+$/, \"\")\n return trimmed === \"\" ? trimmed : trimmed + \"\\n\" // End non blank Scroll files in a newline character POSIX style for better working with tools like git\n }\n get parser() {\n return this.constructor\n }\n get parsersRequiringExternals() {\n const { parser } = this\n // todo: could be cleaned up a bit\n if (!parser.parsersRequiringExternals) parser.parsersRequiringExternals = parser.cachedHandParsersProgramRoot.filter(particle => particle.copyFromExternal).map(particle => particle.atoms[0])\n return parser.parsersRequiringExternals\n }\n get Disk() { return this.isNodeJs() ? require(\"scrollsdk/products/Disk.node.js\").Disk : {}}\n async buildAll(options = {}) {\n await this.load()\n await this.buildOne(options)\n await this.buildTwo(options)\n }\n async buildOne(options) {\n await this.execute()\n const toBuild = this.filter(particle => particle.buildOne)\n for (let particle of toBuild) {\n await particle.buildOne(options)\n }\n }\n async buildTwo(options) {\n const toBuild = this.filter(particle => particle.buildTwo)\n for (let particle of toBuild) {\n await particle.buildTwo(options)\n }\n }\n get outputFileNames() {\n return this.filter(p => p.outputFileNames).map(p => p.outputFileNames).flat()\n }\n _compileArray(filename, arr) {\n const removeBlanks = data => data.map(obj => Object.fromEntries(Object.entries(obj).filter(([_, value]) => value !== \"\")))\n const parts = filename.split(\".\")\n const format = parts.pop()\n if (format === \"json\") return JSON.stringify(removeBlanks(arr), null, 2)\n if (format === \"js\") return `const ${parts[0]} = ` + JSON.stringify(removeBlanks(arr), null, 2)\n if (format === \"csv\") return this.arrayToCSV(arr)\n if (format === \"tsv\") return this.arrayToCSV(arr, \"\\t\")\n if (format === \"particles\") return particles.toString()\n return particles.toString()\n }\n levenshteinDistance(a, b) {\n const m = a.length\n const n = b.length\n const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0))\n for (let i = 0; i <= m; i++) {\n dp[i][0] = i\n }\n for (let j = 0; j <= n; j++) {\n dp[0][j] = j\n }\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1\n dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost)\n }\n }\n return dp[m][n]\n }\n makeLodashOrderByParams(str) {\n const part1 = str.split(\" \")\n const part2 = part1.map(col => (col.startsWith(\"-\") ? \"desc\" : \"asc\"))\n return [part1.map(col => col.replace(/^\\-/, \"\")), part2]\n }\n arrayToCSV(data, delimiter = \",\") {\n if (!data.length) return \"\"\n // Extract headers\n const headers = Object.keys(data[0])\n const csv = data.map(row =>\n headers\n .map(fieldName => {\n const fieldValue = row[fieldName]\n // Escape commas if the value is a string\n if (typeof fieldValue === \"string\" && fieldValue.includes(delimiter)) {\n return `\"${fieldValue.replace(/\"/g, '\"\"')}\"` // Escape double quotes and wrap in double quotes\n }\n return fieldValue\n })\n .join(delimiter)\n )\n csv.unshift(headers.join(delimiter)) // Add header row at the top\n return csv.join(\"\\n\")\n }\n compileConcepts(filename = \"csv\", sortBy = \"\") {\n const {lodash} = this\n if (!sortBy) return this._compileArray(filename, this.concepts)\n const orderBy = this.makeLodashOrderByParams(sortBy)\n return this._compileArray(filename, lodash.orderBy(this.concepts, orderBy[0], orderBy[1]))\n }\n _withStats\n get measuresWithStats() {\n if (!this._withStats) this._withStats = this.addMeasureStats(this.concepts, this.measures)\n return this._withStats\n }\n addMeasureStats(concepts, measures){\n return measures.map(measure => {\n let Type = false\n concepts.forEach(concept => {\n const value = concept[measure.Name]\n if (value === undefined || value === \"\") return\n measure.Values++\n if (!Type) {\n measure.Example = value.toString().replace(/\\n/g, \" \")\n measure.Type = typeof value\n Type = true\n }\n })\n measure.Coverage = Math.floor((100 * measure.Values) / concepts.length) + \"%\"\n return measure\n })\n }\n parseMeasures(parser) {\n if (!Particle.measureCache)\n Particle.measureCache = new Map()\n const measureCache = Particle.measureCache\n if (measureCache.get(parser)) return measureCache.get(parser)\n const {lodash} = this\n // todo: clean this up\n const getCueAtoms = rootParserProgram =>\n rootParserProgram\n .filter(particle => particle.getLine().endsWith(\"Parser\") && !particle.getLine().startsWith(\"abstract\"))\n .map(particle => particle.get(\"cue\") || particle.getLine())\n .map(line => line.replace(/Parser$/, \"\"))\n // Generate a fake program with one of every of the available parsers. Then parse it. Then we can easily access the meta data on the parsers\n const dummyProgram = new parser(\n Array.from(\n new Set(\n getCueAtoms(parser.cachedHandParsersProgramRoot) // is there a better method name than this?\n )\n ).join(\"\\n\")\n )\n // Delete any particles that are not measures\n dummyProgram.filter(particle => !particle.isMeasure).forEach(particle => particle.destroy())\n dummyProgram.forEach(particle => {\n // add nested measures\n Object.keys(particle.definition.cueMapWithDefinitions).forEach(key => particle.appendLine(key))\n })\n // Delete any nested particles that are not measures\n dummyProgram.topDownArray.filter(particle => !particle.isMeasure).forEach(particle => particle.destroy())\n const measures = dummyProgram.topDownArray.map(particle => {\n return {\n Name: particle.measureName,\n Values: 0,\n Coverage: 0,\n Question: particle.definition.description,\n Example: particle.definition.getParticle(\"example\")?.subparticlesToString() || \"\",\n Type: particle.typeForWebForms,\n Source: particle.sourceDomain,\n //Definition: parsedProgram.root.filename + \":\" + particle.lineNumber\n SortIndex: particle.sortIndex,\n IsComputed: particle.isComputed,\n IsRequired: particle.isMeasureRequired,\n IsConceptDelimiter: particle.isConceptDelimiter,\n Cue: particle.definition.get(\"cue\")\n }\n })\n measureCache.set(parser, lodash.sortBy(measures, \"SortIndex\"))\n return measureCache.get(parser)\n }\n _concepts\n get concepts() {\n if (this._concepts) return this._concepts\n this._concepts = this.parseConcepts(this, this.measures)\n return this._concepts\n }\n _measures\n get measures() {\n if (this._measures) return this._measures\n this._measures = this.parseMeasures(this.parser)\n return this._measures\n }\n parseConcepts(parsedProgram, measures){\n // Todo: might be a perf/memory/simplicity win to have a \"segment\" method in ScrollSDK, where you could\n // virtually split a Particle into multiple segments, and then query on those segments.\n // So we would \"segment\" on \"id \", and then not need to create a bunch of new objects, and the original\n // already parsed lines could then learn about/access to their respective segments.\n const conceptDelimiter = measures.filter(measure => measure.IsConceptDelimiter)[0]\n if (!conceptDelimiter) return []\n const concepts = parsedProgram.split(conceptDelimiter.Cue || conceptDelimiter.Name)\n concepts.shift() // Remove the part before \"id\"\n return concepts.map(concept => {\n const row = {}\n measures.forEach(measure => {\n const measureName = measure.Name\n const measureKey = measure.Cue || measureName.replace(/_/g, \" \")\n if (!measure.IsComputed) row[measureName] = concept.getParticle(measureKey)?.measureValue ?? \"\"\n else row[measureName] = this.computeMeasure(parsedProgram, measureName, concept, concepts)\n })\n return row\n })\n }\n computeMeasure(parsedProgram, measureName, concept, concepts){\n // note that this is currently global, assuming there wont be. name conflicts in computed measures in a single scroll\n if (!Particle.measureFnCache) Particle.measureFnCache = {}\n const measureFnCache = Particle.measureFnCache\n if (!measureFnCache[measureName]) {\n // a bit hacky but works??\n const particle = parsedProgram.appendLine(measureName)\n measureFnCache[measureName] = particle.computeValue\n particle.destroy()\n }\n return measureFnCache[measureName](concept, measureName, parsedProgram, concepts)\n }\n compileMeasures(filename = \"csv\", sortBy = \"\") {\n const withStats = this.measuresWithStats\n if (!sortBy) return this._compileArray(filename, withStats)\n const orderBy = this.makeLodashOrderByParams(sortBy)\n return this._compileArray(filename, this.lodash.orderBy(withStats, orderBy[0], orderBy[1]))\n }\n evalNodeJsMacros(value, macroMap, filePath) {\n const tempPath = filePath + \".js\"\n const {Disk} = this\n if (Disk.exists(tempPath)) throw new Error(`Failed to write/require replaceNodejs snippet since '${tempPath}' already exists.`)\n try {\n Disk.write(tempPath, value)\n const results = require(tempPath)\n Object.keys(results).forEach(key => (macroMap[key] = results[key]))\n } catch (err) {\n console.error(`Error in evalMacros in file '${filePath}'`)\n console.error(err)\n } finally {\n Disk.rm(tempPath)\n }\n }\n evalMacros(fusedFile) {\n const {fusedCode, codeAtStart, filePath} = fusedFile\n let code = fusedCode\n const absolutePath = filePath\n // note: the 2 params above are not used in this method, but may be used in user eval code. (todo: cleanup)\n const regex = /^(replace|toFooter$)/gm\n if (!regex.test(code)) return code\n const particle = new Particle(code) // todo: this can be faster. a more lightweight particle class?\n // Process macros\n const macroMap = {}\n particle\n .filter(particle => {\n const parserAtom = particle.cue\n return parserAtom === \"replace\" || parserAtom === \"replaceJs\" || parserAtom === \"replaceNodejs\"\n })\n .forEach(particle => {\n let value = particle.length ? particle.subparticlesToString() : particle.getAtomsFrom(2).join(\" \")\n const kind = particle.cue\n try {\n if (kind === \"replaceJs\") value = eval(value)\n if (this.isNodeJs() && kind === \"replaceNodejs\")\n this.evalNodeJsMacros(value, macroMap, absolutePath)\n else macroMap[particle.getAtom(1)] = value\n } catch (err) {\n console.error(err)\n }\n particle.destroy() // Destroy definitions after eval\n })\n if (particle.has(\"toFooter\")) {\n const pushes = particle.getParticles(\"toFooter\")\n const append = pushes.map(push => push.section.join(\"\\n\")).join(\"\\n\")\n pushes.forEach(push => {\n push.section.forEach(particle => particle.destroy())\n push.destroy()\n })\n code = particle.asString + append\n }\n const keys = Object.keys(macroMap)\n if (!keys.length) return code\n let codeAfterMacroSubstitution = particle.asString\n // Todo: speed up. build a template?\n Object.keys(macroMap).forEach(key => (codeAfterMacroSubstitution = codeAfterMacroSubstitution.replace(new RegExp(key, \"g\"), macroMap[key])))\n return codeAfterMacroSubstitution\n }\n toRss() {\n const { title, canonicalUrl } = this\n return ` <item>\n <title>${title}</title>\n <link>${canonicalUrl}</link>\n <pubDate>${this.dayjs(this.timestamp * 1000).format(\"ddd, DD MMM YYYY HH:mm:ss ZZ\")}</pubDate>\n </item>`\n }\n example\n # Hello world\n ## This is Scroll\n * It compiles to HTML.\n \n code\n // You can add code as well.\n print(\"Hello world\")\nstampFileParser\n catchAllAtomType stringAtom\n description Create a file.\n javascript\n execute(parentDir) {\n const fs = require(\"fs\")\n const path = require(\"path\")\n const fullPath = path.join(parentDir, this.getLine())\n this.root.log(`Creating file ${fullPath}`)\n fs.mkdirSync(path.dirname(fullPath), {recursive: true})\n const content = this.subparticlesToString()\n fs.writeFileSync(fullPath, content, \"utf8\")\n const isExecutable = content.startsWith(\"#!\")\n if (isExecutable) fs.chmodSync(fullPath, \"755\")\n }\nstampFolderParser\n catchAllAtomType stringAtom\n description Create a folder.\n inScope stampFolderParser\n catchAllParser stampFileParser\n pattern \\/$\n javascript\n execute(parentDir) {\n const fs = require(\"fs\")\n const path = require(\"path\")\n const newPath = path.join(parentDir, this.getLine())\n this.root.log(`Creating folder ${newPath}`)\n fs.mkdirSync(newPath, {recursive: true})\n this.forEach(particle => particle.execute(newPath))\n }\nstumpContentParser\n popularity 0.102322\n catchAllAtomType codeAtom\nscrollTableDataParser\n popularity 0.001061\n cue data\n atoms cueAtom\n description Table from inline delimited data.\n baseParser blobParser\nscrollTableDelimiterParser\n popularity 0.001037\n description Set the delimiter.\n cue delimiter\n atoms cueAtom stringAtom\n javascript\n buildHtml() {\n return \"\"\n }\nplainTextLineParser\n popularity 0.000121\n catchAllAtomType stringAtom\n catchAllParser plainTextLineParser"} \ No newline at end of file