{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== '免费Z-image图片生成' && linkText !== '免费Z-image图片生成' ) { link.textContent = '免费Z-image图片生成'; link.href = 'https://zimage.run'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== 'Vibevoice' ) { link.textContent = 'Vibevoice'; link.href = 'https://vibevoice.info/'; replacedLinks.add(link); } // 替换Pricing链接 - 仅替换一次 else if ( (linkHref.includes('/pricing') || linkHref === '/pricing' || linkText === 'Pricing' || linkText.match(/^s*Pricings*$/i)) && linkText !== '免费去水印' ) { link.textContent = '免费去水印'; link.href = 'https://sora2watermarkremover.net/'; replacedLinks.add(link); } // 替换Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) && linkText !== 'GitHub加速' ) { link.textContent = 'GitHub加速'; link.href = 'https://githubproxy.cc'; replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, '免费Z-image图片生成'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n \n\n## Forms\n\nTo validate data coming from users, first define a dataclass\nrepresenting the data you want to check. Here’s an example representing\na signup form.\n\n``` python\nfrom dataclasses import dataclass\n\n@dataclass\nclass Profile: email:str; phone:str; age:int\n```\n\nCreate an FT component representing an empty version of that form. Don’t\npass in any value to fill the form, that gets handled later.\n\n``` python\nprofile_form = Form(method=\"post\", action=\"/profile\")(\n Fieldset(\n Label('Email', Input(name=\"email\")),\n Label(\"Phone\", Input(name=\"phone\")),\n Label(\"Age\", Input(name=\"age\")),\n ),\n Button(\"Save\", type=\"submit\"),\n )\nprofile_form\n```\n\n``` html\n
\n
\n \n \n \n
\n \n
\n```\n\nOnce the dataclass and form function are completed, we can add data to\nthe form. To do that, instantiate the profile dataclass:\n\n``` python\nprofile = Profile(email='john@example.com', phone='123456789', age=5)\nprofile\n```\n\n Profile(email='john@example.com', phone='123456789', age=5)\n\nThen add that data to the `profile_form` using FastHTML’s\n[`fill_form`](https://AnswerDotAI.github.io/fasthtml/api/components.html#fill_form)\nclass:\n\n``` python\nfill_form(profile_form, profile)\n```\n\n``` html\n
\n
\n \n \n \n
\n \n
\n```\n\n### Forms with views\n\nThe usefulness of FastHTML forms becomes more apparent when they are\ncombined with FastHTML views. We’ll show how this works by using the\ntest client from above. First, let’s create a SQlite database:\n\n``` python\ndb = Database(\"profiles.db\")\nprofiles = db.create(Profile, pk=\"email\")\n```\n\nNow we insert a record into the database:\n\n``` python\nprofiles.insert(profile)\n```\n\n Profile(email='john@example.com', phone='123456789', age=5)\n\nAnd we can then demonstrate in the code that form is filled and\ndisplayed to the user.\n\n``` python\n@rt(\"/profile/{email}\")\ndef profile(email:str):\n profile = profiles[email]\n filled_profile_form = fill_form(profile_form, profile)\n return Titled(f'Profile for {profile.email}', filled_profile_form)\n\nprint(client.get(f\"/profile/john@example.com\").text)\n```\n\nLine 3 \nFetch the profile using the profile table’s `email` primary key\n\nLine 4 \nFill the form for display.\n\n\n \n\n \n \n Profile for john@example.com\n \n \n
\n

Profile for john@example.com

\n
\n
\n \n \n \n
\n \n
\n
\n \n \n\nAnd now let’s demonstrate making a change to the data.\n\n``` python\n@rt(\"/profile\")\ndef post(profile: Profile):\n profiles.update(profile)\n return RedirectResponse(url=f\"/profile/{profile.email}\")\n\nnew_data = dict(email='john@example.com', phone='7654321', age=25)\nprint(client.post(\"/profile\", data=new_data).text)\n```\n\nLine 2 \nWe use the `Profile` dataclass definition to set the type for the\nincoming `profile` content. This validates the field types for the\nincoming data\n\nLine 3 \nTaking our validated data, we updated the profiles table\n\nLine 4 \nWe redirect the user back to their profile view\n\nLine 7 \nThe display is of the profile form view showing the changes in data.\n\n\n \n\n \n \n Profile for john@example.com\n \n \n
\n

Profile for john@example.com

\n
\n
\n \n \n \n
\n \n
\n
\n \n \n\n## Strings and conversion order\n\nThe general rules for rendering are: - `__ft__` method will be called\n(for default components like `P`, `H2`, etc. or if you define your own\ncomponents) - If you pass a string, it will be escaped - On other python\nobjects, `str()` will be called\n\nAs a consequence, if you want to include plain HTML tags directly into\ne.g. a `Div()` they will get escaped by default (as a security measure\nto avoid code injections). This can be avoided by using `NotStr()`, a\nconvenient way to reuse python code that returns already HTML. If you\nuse pandas, you can use `pandas.DataFrame.to_html()` to get a nice\ntable. To include the output a FastHTML, wrap it in `NotStr()`, like\n`Div(NotStr(df.to_html()))`.\n\nAbove we saw how a dataclass behaves with the `__ft__` method defined.\nOn a plain dataclass, `str()` will be called (but not escaped).\n\n``` python\nfrom dataclasses import dataclass\n\n@dataclass\nclass Hero:\n title: str\n statement: str\n \n# rendering the dataclass with the default method\nMain(\n Hero(\"

Hello World

\", \"This is a hero statement\")\n)\n```\n\n``` html\n
Hero(title='

Hello World

', statement='This is a hero statement')
\n```\n\n``` python\n# This will display the HTML as text on your page\nDiv(\"Let's include some HTML here:
Some HTML
\")\n```\n\n``` html\n
Let's include some HTML here: <div>Some HTML</div>
\n```\n\n``` python\n# Keep the string untouched, will be rendered on the page\nDiv(NotStr(\"

Some HTML

\"))\n```\n\n``` html\n

Some HTML

\n```\n\n## Custom exception handlers\n\nFastHTML allows customization of exception handlers, but does so\ngracefully. What this means is by default it includes all the ``\ntags needed to display attractive content. Try it out!\n\n``` python\nfrom fasthtml.common import *\n\ndef not_found(req, exc): return Titled(\"404: I don't exist!\")\n\nexception_handlers = {404: not_found}\n\napp, rt = fast_app(exception_handlers=exception_handlers)\n\n@rt('/')\ndef get():\n return (Titled(\"Home page\", P(A(href=\"/oops\")(\"Click to generate 404 error\"))))\n\nserve()\n```\n\nWe can also use lambda to make things more terse:\n\n``` python\nfrom fasthtml.common import *\n\nexception_handlers={\n 404: lambda req, exc: Titled(\"404: I don't exist!\"),\n 418: lambda req, exc: Titled(\"418: I'm a teapot!\")\n}\n\napp, rt = fast_app(exception_handlers=exception_handlers)\n\n@rt('/')\ndef get():\n return (Titled(\"Home page\", P(A(href=\"/oops\")(\"Click to generate 404 error\"))))\n\nserve()\n```\n\n## Cookies\n\nWe can set cookies using the `cookie()` function. In our example, we’ll\ncreate a `timestamp` cookie.\n\n``` python\nfrom datetime import datetime\nfrom IPython.display import HTML\n```\n\n``` python\n@rt(\"/settimestamp\")\ndef get(req):\n now = datetime.now()\n return P(f'Set to {now}'), cookie('now', datetime.now())\n\nHTML(client.get('/settimestamp').text)\n```\n\n \n
 \n \n FastHTML page\n \n \n

Set to 2024-09-04 18:30:34.896373

\n \n \n\nNow let’s get it back using the same name for our parameter as the\ncookie name.\n\n``` python\n@rt('/gettimestamp')\ndef get(now:parsed_date): return f'Cookie was set at time {now.time()}'\n\nclient.get('/gettimestamp').text\n```\n\n 'Cookie was set at time 18:30:34.896405'\n\n## Sessions\n\nFor convenience and security, FastHTML has a mechanism for storing small\namounts of data in the user’s browser. We can do this by adding a\n`session` argument to routes. FastHTML sessions are Python dictionaries,\nand we can leverage to our benefit. The example below shows how to\nconcisely set and get sessions.\n\n``` python\n@rt('/adder/{num}')\ndef get(session, num: int):\n session.setdefault('sum', 0)\n session['sum'] = session.get('sum') + num\n return Response(f'The sum is {session[\"sum\"]}.')\n```\n\n## Toasts (also known as Messages)\n\nToasts, sometimes called “Messages” are small notifications usually in\ncolored boxes used to notify users that something has happened. Toasts\ncan be of four types:\n\n- info\n- success\n- warning\n- error\n\nExamples toasts might include:\n\n- “Payment accepted”\n- “Data submitted”\n- “Request approved”\n\nToasts require the use of the `setup_toasts()` function plus every view\nneeds these two features:\n\n- The session argument\n- Must return FT components\n\n``` python\nsetup_toasts(app)\n\n@rt('/toasting')\ndef get(session):\n # Normally one toast is enough, this allows us to see\n # different toast types in action.\n add_toast(session, f\"Toast is being cooked\", \"info\")\n add_toast(session, f\"Toast is ready\", \"success\")\n add_toast(session, f\"Toast is getting a bit crispy\", \"warning\")\n add_toast(session, f\"Toast is burning!\", \"error\")\n return Titled(\"I like toast\")\n```\n\nLine 1 \n`setup_toasts` is a helper function that adds toast dependencies.\nUsually this would be declared right after `fast_app()`\n\nLine 4 \nToasts require sessions\n\nLine 11 \nViews with Toasts must return FT components.\n\n## Authentication and authorization\n\nIn FastHTML the tasks of authentication and authorization are handled\nwith Beforeware. Beforeware are functions that run before the route\nhandler is called. They are useful for global tasks like ensuring users\nare authenticated or have permissions to access a view.\n\nFirst, we write a function that accepts a request and session arguments:\n\n``` python\n# Status code 303 is a redirect that can change POST to GET,\n# so it's appropriate for a login page.\nlogin_redir = RedirectResponse('/login', status_code=303)\n\ndef user_auth_before(req, sess):\n # The `auth` key in the request scope is automatically provided\n # to any handler which requests it, and can not be injected\n # by the user using query params, cookies, etc, so it should\n # be secure to use. \n auth = req.scope['auth'] = sess.get('auth', None)\n # If the session key is not there, it redirects to the login page.\n if not auth: return login_redir\n```\n\nNow we pass our `user_auth_before` function as the first argument into a\n[`Beforeware`](https://AnswerDotAI.github.io/fasthtml/api/core.html#beforeware)\nclass. We also pass a list of regular expressions to the `skip`\nargument, designed to allow users to still get to the home and login\npages.\n\n``` python\nbeforeware = Beforeware(\n user_auth_before,\n skip=[r'/favicon\\.ico', r'/static/.*', r'.*\\.css', r'.*\\.js', '/login', '/']\n)\n\napp, rt = fast_app(before=beforeware)\n```\n\n## Server-sent events (SSE)\n\nWith [server-sent\nevents](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events),\nit’s possible for a server to send new data to a web page at any time,\nby pushing messages to the web page. Unlike WebSockets, SSE can only go\nin one direction: server to client. SSE is also part of the HTTP\nspecification unlike WebSockets which uses its own specification.\n\nFastHTML introduces several tools for working with SSE which are covered\nin the example below. While concise, there’s a lot going on in this\nfunction so we’ve annotated it quite a bit.\n\n``` python\nimport random\nfrom asyncio import sleep\nfrom fasthtml.common import *\n\nhdrs=(Script(src=\"https://unpkg.com/htmx-ext-sse@2.2.1/sse.js\"),)\napp,rt = fast_app(hdrs=hdrs)\n\n@rt\ndef index():\n return Titled(\"SSE Random Number Generator\",\n P(\"Generate pairs of random numbers, as the list grows scroll downwards.\"),\n Div(hx_ext=\"sse\",\n sse_connect=\"/number-stream\",\n hx_swap=\"beforeend show:bottom\",\n sse_swap=\"message\"))\n\nshutdown_event = signal_shutdown()\n\nasync def number_generator():\n while not shutdown_event.is_set():\n data = Article(random.randint(1, 100))\n yield sse_message(data)\n await sleep(1)\n\n@rt(\"/number-stream\")\nasync def get(): return EventStream(number_generator())\n```\n\nLine 5 \nImport the HTMX SSE extension\n\nLine 12 \nTell HTMX to load the SSE extension\n\nLine 13 \nLook at the `/number-stream` endpoint for SSE content\n\nLine 14 \nWhen new items come in from the SSE endpoint, add them at the end of the\ncurrent content within the div. If they go beyond the screen, scroll\ndownwards\n\nLine 15 \nSpecify the name of the event. FastHTML’s default event name is\n“message”. Only change if you have more than one call to SSE endpoints\nwithin a view\n\nLine 17 \nSet up the asyncio event loop\n\nLine 19 \nDon’t forget to make this an `async` function!\n\nLine 20 \nIterate through the asyncio event loop\n\nLine 22 \nWe yield the data. Data ideally should be comprised of FT components as\nthat plugs nicely into HTMX in the browser\n\nLine 26 \nThe endpoint view needs to be an async function that returns a\n[`EventStream`](https://AnswerDotAI.github.io/fasthtml/api/core.html#eventstream)\n\n
\n\n> **New content as of September 1, 2024**\n>\n> - [Forms](../tutorials/quickstart_for_web_devs.html#forms)\n> - [Server-side Events\n> (SSE)](../tutorials/quickstart_for_web_devs.html#server-sent-events-sse)\n>\n> We’re going to be adding more to this document, so check back\n> frequently for updates.\n\n
\n\n## Unwritten quickstart sections\n\n- Websockets\n- Tables"},"filetype":{"kind":"string","value":"xml"}}},{"rowIdx":1,"cells":{"key":{"kind":"string","value":"llms.txt"},"id":{"kind":"string","value":"Docs: HTMX reference"},"text":{"kind":"string","value":"Things to remember when writing FastHTML apps:\n\n- Although parts of its API are inspired by FastAPI, it is *not* compatible with FastAPI syntax and is not targeted at creating API services\n- FastHTML includes support for Pico CSS and the fastlite sqlite library, although using both are optional; sqlalchemy can be used directly or via the fastsql library, and any CSS framework can be used. Support for the Surreal and css-scope-inline libraries are also included, but both are optional\n- FastHTML is compatible with JS-native web components and any vanilla JS library, but not with React, Vue, or Svelte\n- Use `serve()` for running uvicorn (`if __name__ == \"__main__\"` is not needed since it's automatic)\n- When a title is needed with a response, use `Titled`; note that that already wraps children in `Container`, and already includes both the meta title as well as the H1 element.+++\ntitle = \"Reference\"\n+++\n\n## Contents\n\n* [htmx Core Attributes](#attributes)\n* [htmx Additional Attributes](#attributes-additional)\n* [htmx CSS Classes](#classes)\n* [htmx Request Headers](#request_headers)\n* [htmx Response Headers](#response_headers)\n* [htmx Events](#events)\n* [htmx Extensions](https://extensions.htmx.org)\n* [JavaScript API](#api)\n* [Configuration Options](#config)\n\n## Core Attribute Reference {#attributes}\n\nThe most common attributes when using htmx.\n\n
\n\n| Attribute | Description |\n|--------------------------------------------------|--------------------------------------------------------------------------------------------------------------------|\n| [`hx-get`](@/attributes/hx-get.md) | issues a `GET` to the specified URL |\n| [`hx-post`](@/attributes/hx-post.md) | issues a `POST` to the specified URL |\n| [`hx-on*`](@/attributes/hx-on.md) | handle events with inline scripts on elements |\n| [`hx-push-url`](@/attributes/hx-push-url.md) | push a URL into the browser location bar to create history |\n| [`hx-select`](@/attributes/hx-select.md) | select content to swap in from a response |\n| [`hx-select-oob`](@/attributes/hx-select-oob.md) | select content to swap in from a response, somewhere other than the target (out of band) |\n| [`hx-swap`](@/attributes/hx-swap.md) | controls how content will swap in (`outerHTML`, `beforeend`, `afterend`, ...) |\n| [`hx-swap-oob`](@/attributes/hx-swap-oob.md) | mark element to swap in from a response (out of band) |\n| [`hx-target`](@/attributes/hx-target.md) | specifies the target element to be swapped |\n| [`hx-trigger`](@/attributes/hx-trigger.md) | specifies the event that triggers the request |\n| [`hx-vals`](@/attributes/hx-vals.md) | add values to submit with the request (JSON format) |\n\n
\n\n## Additional Attribute Reference {#attributes-additional}\n\nAll other attributes available in htmx.\n\n
\n\n| Attribute | Description |\n|------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------|\n| [`hx-boost`](@/attributes/hx-boost.md) | add [progressive enhancement](https://en.wikipedia.org/wiki/Progressive_enhancement) for links and forms |\n| [`hx-confirm`](@/attributes/hx-confirm.md) | shows a `confirm()` dialog before issuing a request |\n| [`hx-delete`](@/attributes/hx-delete.md) | issues a `DELETE` to the specified URL |\n| [`hx-disable`](@/attributes/hx-disable.md) | disables htmx processing for the given node and any children nodes |\n| [`hx-disabled-elt`](@/attributes/hx-disabled-elt.md) | adds the `disabled` attribute to the specified elements while a request is in flight |\n| [`hx-disinherit`](@/attributes/hx-disinherit.md) | control and disable automatic attribute inheritance for child nodes |\n| [`hx-encoding`](@/attributes/hx-encoding.md) | changes the request encoding type |\n| [`hx-ext`](@/attributes/hx-ext.md) | extensions to use for this element |\n| [`hx-headers`](@/attributes/hx-headers.md) | adds to the headers that will be submitted with the request |\n| [`hx-history`](@/attributes/hx-history.md) | prevent sensitive data being saved to the history cache |\n| [`hx-history-elt`](@/attributes/hx-history-elt.md) | the element to snapshot and restore during history navigation |\n| [`hx-include`](@/attributes/hx-include.md) | include additional data in requests |\n| [`hx-indicator`](@/attributes/hx-indicator.md) | the element to put the `htmx-request` class on during the request |\n| [`hx-inherit`](@/attributes/hx-inherit.md) | control and enable automatic attribute inheritance for child nodes if it has been disabled by default |\n| [`hx-params`](@/attributes/hx-params.md) | filters the parameters that will be submitted with a request |\n| [`hx-patch`](@/attributes/hx-patch.md) | issues a `PATCH` to the specified URL |\n| [`hx-preserve`](@/attributes/hx-preserve.md) | specifies elements to keep unchanged between requests |\n| [`hx-prompt`](@/attributes/hx-prompt.md) | shows a `prompt()` before submitting a request |\n| [`hx-put`](@/attributes/hx-put.md) | issues a `PUT` to the specified URL |\n| [`hx-replace-url`](@/attributes/hx-replace-url.md) | replace the URL in the browser location bar |\n| [`hx-request`](@/attributes/hx-request.md) | configures various aspects of the request |\n| [`hx-sync`](@/attributes/hx-sync.md) | control how requests made by different elements are synchronized |\n| [`hx-validate`](@/attributes/hx-validate.md) | force elements to validate themselves before a request |\n| [`hx-vars`](@/attributes/hx-vars.md) | adds values dynamically to the parameters to submit with the request (deprecated, please use [`hx-vals`](@/attributes/hx-vals.md)) |\n\n
\n\n## CSS Class Reference {#classes}\n\n
\n\n| Class | Description |\n|-----------|-------------|\n| `htmx-added` | Applied to a new piece of content before it is swapped, removed after it is settled.\n| `htmx-indicator` | A dynamically generated class that will toggle visible (opacity:1) when a `htmx-request` class is present\n| `htmx-request` | Applied to either the element or the element specified with [`hx-indicator`](@/attributes/hx-indicator.md) while a request is ongoing\n| `htmx-settling` | Applied to a target after content is swapped, removed after it is settled. The duration can be modified via [`hx-swap`](@/attributes/hx-swap.md).\n| `htmx-swapping` | Applied to a target before any content is swapped, removed after it is swapped. The duration can be modified via [`hx-swap`](@/attributes/hx-swap.md).\n\n
\n\n## HTTP Header Reference {#headers}\n\n### Request Headers Reference {#request_headers}\n\n
\n\n| Header | Description |\n|--------|-------------|\n| `HX-Boosted` | indicates that the request is via an element using [hx-boost](@/attributes/hx-boost.md)\n| `HX-Current-URL` | the current URL of the browser\n| `HX-History-Restore-Request` | \"true\" if the request is for history restoration after a miss in the local history cache\n| `HX-Prompt` | the user response to an [hx-prompt](@/attributes/hx-prompt.md)\n| `HX-Request` | always \"true\"\n| `HX-Target` | the `id` of the target element if it exists\n| `HX-Trigger-Name` | the `name` of the triggered element if it exists\n| `HX-Trigger` | the `id` of the triggered element if it exists\n\n
\n\n### Response Headers Reference {#response_headers}\n\n
\n\n| Header | Description |\n|------------------------------------------------------|-------------|\n| [`HX-Location`](@/headers/hx-location.md) | allows you to do a client-side redirect that does not do a full page reload\n| [`HX-Push-Url`](@/headers/hx-push-url.md) | pushes a new url into the history stack\n| [`HX-Redirect`](@/headers/hx-redirect.md) | can be used to do a client-side redirect to a new location\n| `HX-Refresh` | if set to \"true\" the client-side will do a full refresh of the page\n| [`HX-Replace-Url`](@/headers/hx-replace-url.md) | replaces the current URL in the location bar\n| `HX-Reswap` | allows you to specify how the response will be swapped. See [hx-swap](@/attributes/hx-swap.md) for possible values\n| `HX-Retarget` | a CSS selector that updates the target of the content update to a different element on the page\n| `HX-Reselect` | a CSS selector that allows you to choose which part of the response is used to be swapped in. Overrides an existing [`hx-select`](@/attributes/hx-select.md) on the triggering element\n| [`HX-Trigger`](@/headers/hx-trigger.md) | allows you to trigger client-side events\n| [`HX-Trigger-After-Settle`](@/headers/hx-trigger.md) | allows you to trigger client-side events after the settle step\n| [`HX-Trigger-After-Swap`](@/headers/hx-trigger.md) | allows you to trigger client-side events after the swap step\n\n
\n\n## Event Reference {#events}\n\n
\n\n| Event | Description |\n|-------|-------------|\n| [`htmx:abort`](@/events.md#htmx:abort) | send this event to an element to abort a request\n| [`htmx:afterOnLoad`](@/events.md#htmx:afterOnLoad) | triggered after an AJAX request has completed processing a successful response\n| [`htmx:afterProcessNode`](@/events.md#htmx:afterProcessNode) | triggered after htmx has initialized a node\n| [`htmx:afterRequest`](@/events.md#htmx:afterRequest) | triggered after an AJAX request has completed\n| [`htmx:afterSettle`](@/events.md#htmx:afterSettle) | triggered after the DOM has settled\n| [`htmx:afterSwap`](@/events.md#htmx:afterSwap) | triggered after new content has been swapped in\n| [`htmx:beforeCleanupElement`](@/events.md#htmx:beforeCleanupElement) | triggered before htmx [disables](@/attributes/hx-disable.md) an element or removes it from the DOM\n| [`htmx:beforeOnLoad`](@/events.md#htmx:beforeOnLoad) | triggered before any response processing occurs\n| [`htmx:beforeProcessNode`](@/events.md#htmx:beforeProcessNode) | triggered before htmx initializes a node\n| [`htmx:beforeRequest`](@/events.md#htmx:beforeRequest) | triggered before an AJAX request is made\n| [`htmx:beforeSwap`](@/events.md#htmx:beforeSwap) | triggered before a swap is done, allows you to configure the swap\n| [`htmx:beforeSend`](@/events.md#htmx:beforeSend) | triggered just before an ajax request is sent\n| [`htmx:configRequest`](@/events.md#htmx:configRequest) | triggered before the request, allows you to customize parameters, headers\n| [`htmx:confirm`](@/events.md#htmx:confirm) | triggered after a trigger occurs on an element, allows you to cancel (or delay) issuing the AJAX request\n| [`htmx:historyCacheError`](@/events.md#htmx:historyCacheError) | triggered on an error during cache writing\n| [`htmx:historyCacheMiss`](@/events.md#htmx:historyCacheMiss) | triggered on a cache miss in the history subsystem\n| [`htmx:historyCacheMissError`](@/events.md#htmx:historyCacheMissError) | triggered on a unsuccessful remote retrieval\n| [`htmx:historyCacheMissLoad`](@/events.md#htmx:historyCacheMissLoad) | triggered on a successful remote retrieval\n| [`htmx:historyRestore`](@/events.md#htmx:historyRestore) | triggered when htmx handles a history restoration action\n| [`htmx:beforeHistorySave`](@/events.md#htmx:beforeHistorySave) | triggered before content is saved to the history cache\n| [`htmx:load`](@/events.md#htmx:load) | triggered when new content is added to the DOM\n| [`htmx:noSSESourceError`](@/events.md#htmx:noSSESourceError) | triggered when an element refers to a SSE event in its trigger, but no parent SSE source has been defined\n| [`htmx:onLoadError`](@/events.md#htmx:onLoadError) | triggered when an exception occurs during the onLoad handling in htmx\n| [`htmx:oobAfterSwap`](@/events.md#htmx:oobAfterSwap) | triggered after an out of band element as been swapped in\n| [`htmx:oobBeforeSwap`](@/events.md#htmx:oobBeforeSwap) | triggered before an out of band element swap is done, allows you to configure the swap\n| [`htmx:oobErrorNoTarget`](@/events.md#htmx:oobErrorNoTarget) | triggered when an out of band element does not have a matching ID in the current DOM\n| [`htmx:prompt`](@/events.md#htmx:prompt) | triggered after a prompt is shown\n| [`htmx:pushedIntoHistory`](@/events.md#htmx:pushedIntoHistory) | triggered after an url is pushed into history\n| [`htmx:responseError`](@/events.md#htmx:responseError) | triggered when an HTTP response error (non-`200` or `300` response code) occurs\n| [`htmx:sendError`](@/events.md#htmx:sendError) | triggered when a network error prevents an HTTP request from happening\n| [`htmx:sseError`](@/events.md#htmx:sseError) | triggered when an error occurs with a SSE source\n| [`htmx:sseOpen`](/events#htmx:sseOpen) | triggered when a SSE source is opened\n| [`htmx:swapError`](@/events.md#htmx:swapError) | triggered when an error occurs during the swap phase\n| [`htmx:targetError`](@/events.md#htmx:targetError) | triggered when an invalid target is specified\n| [`htmx:timeout`](@/events.md#htmx:timeout) | triggered when a request timeout occurs\n| [`htmx:validation:validate`](@/events.md#htmx:validation:validate) | triggered before an element is validated\n| [`htmx:validation:failed`](@/events.md#htmx:validation:failed) | triggered when an element fails validation\n| [`htmx:validation:halted`](@/events.md#htmx:validation:halted) | triggered when a request is halted due to validation errors\n| [`htmx:xhr:abort`](@/events.md#htmx:xhr:abort) | triggered when an ajax request aborts\n| [`htmx:xhr:loadend`](@/events.md#htmx:xhr:loadend) | triggered when an ajax request ends\n| [`htmx:xhr:loadstart`](@/events.md#htmx:xhr:loadstart) | triggered when an ajax request starts\n| [`htmx:xhr:progress`](@/events.md#htmx:xhr:progress) | triggered periodically during an ajax request that supports progress events\n\n
\n\n## JavaScript API Reference {#api}\n\n
\n\n| Method | Description |\n|-------|-------------|\n| [`htmx.addClass()`](@/api.md#addClass) | Adds a class to the given element\n| [`htmx.ajax()`](@/api.md#ajax) | Issues an htmx-style ajax request\n| [`htmx.closest()`](@/api.md#closest) | Finds the closest parent to the given element matching the selector\n| [`htmx.config`](@/api.md#config) | A property that holds the current htmx config object\n| [`htmx.createEventSource`](@/api.md#createEventSource) | A property holding the function to create SSE EventSource objects for htmx\n| [`htmx.createWebSocket`](@/api.md#createWebSocket) | A property holding the function to create WebSocket objects for htmx\n| [`htmx.defineExtension()`](@/api.md#defineExtension) | Defines an htmx [extension](https://extensions.htmx.org)\n| [`htmx.find()`](@/api.md#find) | Finds a single element matching the selector\n| [`htmx.findAll()` `htmx.findAll(elt, selector)`](@/api.md#find) | Finds all elements matching a given selector\n| [`htmx.logAll()`](@/api.md#logAll) | Installs a logger that will log all htmx events\n| [`htmx.logger`](@/api.md#logger) | A property set to the current logger (default is `null`)\n| [`htmx.off()`](@/api.md#off) | Removes an event listener from the given element\n| [`htmx.on()`](@/api.md#on) | Creates an event listener on the given element, returning it\n| [`htmx.onLoad()`](@/api.md#onLoad) | Adds a callback handler for the `htmx:load` event\n| [`htmx.parseInterval()`](@/api.md#parseInterval) | Parses an interval declaration into a millisecond value\n| [`htmx.process()`](@/api.md#process) | Processes the given element and its children, hooking up any htmx behavior\n| [`htmx.remove()`](@/api.md#remove) | Removes the given element\n| [`htmx.removeClass()`](@/api.md#removeClass) | Removes a class from the given element\n| [`htmx.removeExtension()`](@/api.md#removeExtension) | Removes an htmx [extension](https://extensions.htmx.org)\n| [`htmx.swap()`](@/api.md#swap) | Performs swapping (and settling) of HTML content\n| [`htmx.takeClass()`](@/api.md#takeClass) | Takes a class from other elements for the given element\n| [`htmx.toggleClass()`](@/api.md#toggleClass) | Toggles a class from the given element\n| [`htmx.trigger()`](@/api.md#trigger) | Triggers an event on an element\n| [`htmx.values()`](@/api.md#values) | Returns the input values associated with the given element\n\n
\n\n\n## Configuration Reference {#config}\n\nHtmx has some configuration options that can be accessed either programmatically or declaratively. They are\nlisted below:\n\n
\n\n| Config Variable | Info |\n|---------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `htmx.config.historyEnabled` | defaults to `true`, really only useful for testing |\n| `htmx.config.historyCacheSize` | defaults to 10 |\n| `htmx.config.refreshOnHistoryMiss` | defaults to `false`, if set to `true` htmx will issue a full page refresh on history misses rather than use an AJAX request |\n| `htmx.config.defaultSwapStyle` | defaults to `innerHTML` |\n| `htmx.config.defaultSwapDelay` | defaults to 0 |\n| `htmx.config.defaultSettleDelay` | defaults to 20 |\n| `htmx.config.includeIndicatorStyles` | defaults to `true` (determines if the indicator styles are loaded) |\n| `htmx.config.indicatorClass` | defaults to `htmx-indicator` |\n| `htmx.config.requestClass` | defaults to `htmx-request` |\n| `htmx.config.addedClass` | defaults to `htmx-added` |\n| `htmx.config.settlingClass` | defaults to `htmx-settling` |\n| `htmx.config.swappingClass` | defaults to `htmx-swapping` |\n| `htmx.config.allowEval` | defaults to `true`, can be used to disable htmx's use of eval for certain features (e.g. trigger filters) |\n| `htmx.config.allowScriptTags` | defaults to `true`, determines if htmx will process script tags found in new content |\n| `htmx.config.inlineScriptNonce` | defaults to `''`, meaning that no nonce will be added to inline scripts |\n| `htmx.config.inlineStyleNonce` | defaults to `''`, meaning that no nonce will be added to inline styles |\n| `htmx.config.attributesToSettle` | defaults to `[\"class\", \"style\", \"width\", \"height\"]`, the attributes to settle during the settling phase |\n| `htmx.config.wsReconnectDelay` | defaults to `full-jitter` |\n| `htmx.config.wsBinaryType` | defaults to `blob`, the [the type of binary data](https://developer.mozilla.org/docs/Web/API/WebSocket/binaryType) being received over the WebSocket connection |\n| `htmx.config.disableSelector` | defaults to `[hx-disable], [data-hx-disable]`, htmx will not process elements with this attribute on it or a parent |\n| `htmx.config.withCredentials` | defaults to `false`, allow cross-site Access-Control requests using credentials such as cookies, authorization headers or TLS client certificates |\n| `htmx.config.timeout` | defaults to 0, the number of milliseconds a request can take before automatically being terminated |\n| `htmx.config.scrollBehavior` | defaults to 'instant', the behavior for a boosted link on page transitions. The allowed values are `auto`, `instant` and `smooth`. Instant will scroll instantly in a single jump, smooth will scroll smoothly, while auto will behave like a vanilla link. |\n| `htmx.config.defaultFocusScroll` | if the focused element should be scrolled into view, defaults to false and can be overridden using the [focus-scroll](@/attributes/hx-swap.md#focus-scroll) swap modifier. |\n| `htmx.config.getCacheBusterParam` | defaults to false, if set to true htmx will append the target element to the `GET` request in the format `org.htmx.cache-buster=targetElementId` |\n| `htmx.config.globalViewTransitions` | if set to `true`, htmx will use the [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API) API when swapping in new content. |\n| `htmx.config.methodsThatUseUrlParams` | defaults to `[\"get\", \"delete\"]`, htmx will format requests with these methods by encoding their parameters in the URL, not the request body |\n| `htmx.config.selfRequestsOnly` | defaults to `true`, whether to only allow AJAX requests to the same domain as the current document |\n| `htmx.config.ignoreTitle` | defaults to `false`, if set to `true` htmx will not update the title of the document when a `title` tag is found in new content |\n| `htmx.config.scrollIntoViewOnBoost` | defaults to `true`, whether or not the target of a boosted element is scrolled into the viewport. If `hx-target` is omitted on a boosted element, the target defaults to `body`, causing the page to scroll to the top. |\n| `htmx.config.triggerSpecsCache` | defaults to `null`, the cache to store evaluated trigger specifications into, improving parsing performance at the cost of more memory usage. You may define a simple object to use a never-clearing cache, or implement your own system using a [proxy object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy) |\n| `htmx.config.responseHandling` | the default [Response Handling](@/docs.md#response-handling) behavior for response status codes can be configured here to either swap or error |\n| `htmx.config.allowNestedOobSwaps` | defaults to `true`, whether to process OOB swaps on elements that are nested within the main response element. See [Nested OOB Swaps](@/attributes/hx-swap-oob.md#nested-oob-swaps). |\n\n
\n\nYou can set them directly in javascript, or you can use a `meta` tag:\n\n```html\n\n```
"},"filetype":{"kind":"string","value":"xml"}}},{"rowIdx":2,"cells":{"key":{"kind":"string","value":"llms.txt"},"id":{"kind":"string","value":"Docs: Surreal"},"text":{"kind":"string","value":"Things to remember when writing FastHTML apps:\n\n- Although parts of its API are inspired by FastAPI, it is *not* compatible with FastAPI syntax and is not targeted at creating API services\n- FastHTML includes support for Pico CSS and the fastlite sqlite library, although using both are optional; sqlalchemy can be used directly or via the fastsql library, and any CSS framework can be used. Support for the Surreal and css-scope-inline libraries are also included, but both are optional\n- FastHTML is compatible with JS-native web components and any vanilla JS library, but not with React, Vue, or Svelte\n- Use `serve()` for running uvicorn (`if __name__ == \"__main__\"` is not needed since it's automatic)\n- When a title is needed with a response, use `Titled`; note that that already wraps children in `Container`, and already includes both the meta title as well as the H1 element.# 🗿 Surreal\n### Tiny jQuery alternative for plain Javascript with inline [Locality of Behavior](https://htmx.org/essays/locality-of-behaviour/)!\n\n![cover](https://user-images.githubusercontent.com/24665/171092805-b41286b2-be4a-4aab-9ee6-d604699cc507.png)\n(Art by [shahabalizadeh](https://www.deviantart.com/shahabalizadeh))\n\n\n## Why does this exist?\n\nFor devs who love ergonomics! You may appreciate Surreal if:\n\n* You want to stay as close as possible to Vanilla JS.\n* Hate typing `document.querySelector` over.. and over..\n* Hate typing `addEventListener` over.. and over..\n* Really wish `document.querySelectorAll` had Array functions..\n* Really wish `this` would work in any inline `\n\n```\n\nSee the [Live Example](https://gnat.github.io/surreal/example.html)! Then [view source](https://github.com/gnat/surreal/blob/main/example.html).\n\n## 🎁 Install\n\nSurreal is only 320 lines. No build step. No dependencies.\n\n[📥 Download](https://raw.githubusercontent.com/gnat/surreal/main/surreal.js) into your project, and add `` in your ``\n\nOr, 🌐 via CDN: ``\n\n## ⚡ Usage\n\n### 🔍️ DOM Selection\n\n* Select **one** element: `me(...)`\n * Can be any of:\n * CSS selector: `\".button\"`, `\"#header\"`, `\"h1\"`, `\"body > .block\"`\n * Variables: `body`, `e`, `some_element`\n * Events: `event.currentTarget` will be used.\n * Surreal selectors: `me()`,`any()`\n * Choose the start location in the DOM with the 2nd arg. (Default: `document`)\n * 🔥 `any('button', me('#header')).classAdd('red')`\n * Add `.red` to any `
\n```\n```html\n
I fade out and remove myself.\n \n
\n```\n```html\n
Change color every second.\n \n
\n```\n```html\n\n```\n#### Array methods\n```js\nany('button')?.forEach(...)\nany('button')?.map(...)\n```\n\n## 👁️ Functions\nLooking for [DOM Selectors](#selectors)?\nLooking for stuff [we recommend doing in vanilla JS](#no-surreal)?\n### 🧭 Legend\n* 🔗 Chainable off `me()` and `any()`\n* 🌐 Global shortcut.\n* 🔥 Runnable example.\n* 🔌 Built-in Plugin\n### 👁️ At a glance\n\n* 🔗 `run`\n * It's `forEach` but less wordy and works on single elements, too!\n * 🔥 `me().run(e => { alert(e) })`\n * 🔥 `any('button').run(e => { alert(e) })`\n* 🔗 `remove`\n * 🔥 `me().remove()`\n * 🔥 `any('button').remove()`\n* 🔗 `classAdd` 🌗 `class_add` 🌗 `addClass` 🌗 `add_class`\n * 🔥 `me().classAdd('active')`\n * Leading `.` is **optional**\n * Same thing: `me().classAdd('active')` 🌗 `me().classAdd('.active')`\n* 🔗 `classRemove` 🌗 `class_remove` 🌗 `removeClass` 🌗 `remove_class`\n * 🔥 `me().classRemove('active')`\n* 🔗 `classToggle` 🌗 `class_toggle` 🌗 `toggleClass` 🌗 `toggle_class`\n * 🔥 `me().classToggle('active')`\n* 🔗 `styles`\n * 🔥 `me().styles('color: red')` Add style.\n * 🔥 `me().styles({ 'color':'red', 'background':'blue' })` Add multiple styles.\n * 🔥 `me().styles({ 'background':null })` Remove style.\n* 🔗 `attribute` 🌗 `attributes` 🌗 `attr`\n * Get: 🔥 `me().attribute('data-x')`\n * For single elements.\n * For many elements, wrap it in: `any(...).run(...)` or `any(...).forEach(...)`\n * Set: 🔥`me().attribute('data-x', true)`\n * Set multiple: 🔥 `me().attribute({ 'data-x':'yes', 'data-y':'no' })`\n * Remove: 🔥 `me().attribute('data-x', null)`\n * Remove multiple: 🔥 `me().attribute({ 'data-x': null, 'data-y':null })`\n* 🔗 `send` 🌗 `trigger`\n * 🔥 `me().send('change')`\n * 🔥 `me().send('change', {'data':'thing'})`\n * Wraps `dispatchEvent`\n* 🔗 `on`\n * 🔥 `me().on('click', ev => { me(ev).styles('background', 'red') })`\n * Wraps `addEventListener`\n* 🔗 `off`\n * 🔥 `me().off('click', fn)`\n * Wraps `removeEventListener`\n* 🔗 `offAll`\n * 🔥 `me().offAll()`\n* 🔗 `disable`\n * 🔥 `me().disable()`\n * Easy alternative to `off()`. Disables click, key, submit events.\n* 🔗 `enable`\n * 🔥 `me().enable()`\n * Opposite of `disable()`\n* 🌐 `sleep`\n * 🔥 `await sleep(1000, ev => { alert(ev) })`\n * `async` version of `setTimeout`\n * Wonderful for animation timelines.\n* 🌐 `tick`\n * 🔥 `await tick()`\n * `await` version of `rAF` / `requestAnimationFrame`.\n * Animation tick. Waits 1 frame.\n * Great if you need to wait for events to propagate.\n* 🌐 `rAF`\n * 🔥 `rAF(e => { return e })`\n * Animation tick. Fires when 1 frame has passed. Alias of [requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)\n * Great if you need to wait for events to propagate.\n* 🌐 `rIC`\n * 🔥 `rIC(e => { return e })`\n * Great time to compute. Fires function when JS is idle. Alias of [requestIdleCallback](https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback)\n* 🌐 `halt`\n * 🔥 `halt(event)`\n * Prevent default browser behaviors.\n * Wrapper for [preventDefault](https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n* 🌐 `createElement` 🌗 `create_element`\n * 🔥 `e_new = createElement(\"div\"); me().prepend(e_new)`\n * Alias of vanilla `document.createElement`\n* 🌐 `onloadAdd` 🌗 `onload_add` 🌗 `addOnload` 🌗 `add_onload`\n * 🔥 `onloadAdd(_ => { alert(\"loaded!\"); })`\n * 🔥 ``\n * Execute after the DOM is ready. Similar to jquery `ready()`\n * Add to `window.onload` while preventing overwrites of `window.onload` and predictable loading!\n * Alternatives:\n * Skip missing elements using `?.` example: `me(\"video\")?.requestFullscreen()`\n * Place ``\n * Inspired by the CSS \"next sibling\" combinator `+` but in reverse `-`\n* Or, use a relative start.\n * 🔥 `
`\n\n#### Ignore call chain when element is missing.\n* 🔥 `me(\"#i_dont_exist\")?.classAdd('active')`\n* No warnings: 🔥 `me(\"#i_dont_exist\", document, false)?.classAdd('active')`\n\n## 🔌 Your own plugin\n\nFeel free to edit Surreal directly- but if you prefer, you can use plugins to effortlessly merge with new versions.\n\n```javascript\nfunction pluginHello(e) {\n function hello(e, name=\"World\") {\n console.log(`Hello ${name} from ${e}`)\n return e // Make chainable.\n }\n // Add sugar\n e.hello = (name) => { return hello(e, name) }\n}\n\nsurreal.plugins.push(pluginHello)\n```\n\nNow use your function like: `me().hello(\"Internet\")`\n\n* See the included `pluginEffects` for a more comprehensive example.\n* Your functions are added globally by `globalsAdd()` If you do not want this, add it to the `restricted` list.\n* Refer to an existing function to see how to make yours work with 1 or many elements.\n\nMake an [issue](https://github.com/gnat/surreal/issues) or [pull request](https://github.com/gnat/surreal/pulls) if you think people would like to use it! If it's useful enough we'll want it in core.\n\n### ⭐ Awesome Surreal examples, plugins, and resources: [awesome-surreal](https://github.com/gnat/awesome-surreal) !\n\n## 📚️ Inspired by\n\n* [jQuery](https://jquery.com/) for the chainable syntax we all love.\n* [BlingBling.js](https://github.com/argyleink/blingblingjs) for modern minimalism.\n* [Bliss.js](https://blissfuljs.com/) for a focus on single elements and extensibility.\n* [Hyperscript](https://hyperscript.org) for Locality of Behavior and awesome ergonomics.\n* Shout out to [Umbrella](https://umbrellajs.com/), [Cash](https://github.com/fabiospampinato/cash), [Zepto](https://zeptojs.com/)- Not quite as ergonomic. Requires build step to extend.\n\n## 🌘 Future\n* Always more `example.html` goodies!\n* Automated browser testing perhaps with:\n * [Fava](https://github.com/fabiospampinato/fava). See: https://github.com/avajs/ava/issues/24#issuecomment-885949036\n * [Ava](https://github.com/avajs/ava/blob/main/docs/recipes/browser-testing.md)\n * [jsdom](https://github.com/jsdom/jsdom)\n * [jsdom notes](https://github.com/jsdom/jsdom#executing-scripts)"},"filetype":{"kind":"string","value":"xml"}}},{"rowIdx":3,"cells":{"key":{"kind":"string","value":"llms.txt"},"id":{"kind":"string","value":"Docs: CSS Scope Inline"},"text":{"kind":"string","value":"Things to remember when writing FastHTML apps:\n\n- Although parts of its API are inspired by FastAPI, it is *not* compatible with FastAPI syntax and is not targeted at creating API services\n- FastHTML includes support for Pico CSS and the fastlite sqlite library, although using both are optional; sqlalchemy can be used directly or via the fastsql library, and any CSS framework can be used. Support for the Surreal and css-scope-inline libraries are also included, but both are optional\n- FastHTML is compatible with JS-native web components and any vanilla JS library, but not with React, Vue, or Svelte\n- Use `serve()` for running uvicorn (`if __name__ == \"__main__\"` is not needed since it's automatic)\n- When a title is needed with a response, use `Titled`; note that that already wraps children in `Container`, and already includes both the meta title as well as the H1 element.# 🌘 CSS Scope Inline\n\n![cover](https://github.com/gnat/css-scope-inline/assets/24665/c4935c1b-34e3-4220-9d42-11f064999a57)\n(Art by [shahabalizadeh](https://www.artstation.com/artwork/zDgdd))\n\n## Why does this exist?\n\n* You want an easy inline vanilla CSS experience without Tailwind CSS.\n* Hate creating unique class names over.. and over.. to use once.\n* You want to co-locate your styles for ⚡️ [Locality of Behavior (LoB)](https://htmx.org/essays/locality-of-behaviour/)\n* You wish `this` would work in `\n \n
\n```\nSee the [Live Example](https://gnat.github.io/css-scope-inline/example.html)! Then [view source](https://github.com/gnat/css-scope-inline/blob/main/example.html).\n\n## 🌘 How does it work?\n\nThis uses `MutationObserver` to monitor the DOM, and the moment a `\n red\n
green
\n
green
\n
green
\n
yellow
\n
blue
\n
green
\n
green
\n
\n\n
\n red\n
green
\n
green
\n
green
\n
yellow
\n
blue
\n
green
\n
green
\n
\n```\n\n### CSS variables and child elements\nAt first glance, **Tailwind Example 2** looks very promising! Exciting ...but:\n* 🔴 **Every child style requires an explicit selector.**\n * Tailwinds' shorthand advantages sadly disappear.\n * Any more child styles added in Tailwind will become longer than vanilla CSS.\n * This limited example is the best case scenario for Tailwind.\n* 🔴 Not visible on github: **no highlighting for properties and units** begins to be painful.\n```html\n\n\n \n \n \n \n \n \n \n
\n \n
Home
\n
Team
\n
Profile
\n
Settings
\n
Log Out
\n
\n\n \n
\n
Home
\n
Team
\n
Profile
\n
Settings
\n
Log Out
\n
\n\n \n
\n
Home
\n
Team
\n
Profile
\n
Settings
\n
Log Out
\n
\n \n\n```\n## 🔎 Technical FAQ\n* Why do you use `querySelectorAll()` and not just process the `MutationObserver` results directly?\n * This was indeed the original design; it will work well up until you begin recieving subtrees (ex: DOM swaps with [htmx](https://htmx.org), ajax, jquery, etc.) which requires walking all subtree elements to ensure we do not miss a `