### Getting Started with Clay: Setup and First Document Source: https://github.com/scicloj/clay/blob/main/docs/index.html This sequence of commands guides you through setting up Clay, starting a Clojure REPL with the necessary dependency, loading the Clay API, and generating your first simple HTML document from a Clojure form. ```Shell clj -Sdeps "{:deps {org.scicloj/clay {:mvn/version \"2-beta23\"}}}" ``` ```Clojure (require '[scicloj.clay.v2.api :as clay]) ``` ```Clojure (clay/make! {:single-form '(+ 1 2 3)}) ``` -------------------------------- ### Clojure Namespace Setup for Clay Source: https://github.com/scicloj/clay/blob/main/examples/example-project/docs/example1.html This snippet demonstrates how to define a Clojure namespace and require the `scicloj.kindly.v4.kind` library. This setup is essential for integrating Clay's rendering capabilities and other functionalities within a Clojure notebook environment. ```Clojure (ns example1 (:require [scicloj.kindly.v4.kind :as kind])) ``` -------------------------------- ### Clay API Usage Examples for Notebook Generation Source: https://github.com/scicloj/clay/blob/main/examples/example-project/docs/example1.html This commented Clojure code block provides examples of direct API calls to the Clay library. It demonstrates how to require the `scicloj.clay.v2.api` namespace and use `clay/make!` to either process an entire source file or render a single Clojure value, offering an alternative to editor-based execution. ```Clojure (comment ;; Instead of using your editor setup and keybindings, ;; you can also use the Clay API directly: (require '[scicloj.clay.v2.api :as clay]) ;; Show the whole namespace (clay/make! {:source-path "notebooks/example1.clj"}) ;; Show a given value (clay/make! {:single-value (kind/hiccup [:div {:style {:background-color "#eeddcc"}} [:p "hello"]]}) ,) ``` -------------------------------- ### Main Frontend Utility Script Initialization Source: https://github.com/scicloj/clay/blob/main/examples/example-project/docs/example1.html This script initializes various client-side functionalities upon the DOMContentLoaded event. It includes functions for toggling the body's color mode (dark/light), adding anchor links to headings, enabling 'copy to clipboard' functionality for code blocks, and creating interactive hover tooltips for footnotes and bibliography references. ```javascript window.document.addEventListener("DOMContentLoaded", function (event) { const toggleBodyColorMode = (bsSheetEl) => { const mode = bsSheetEl.getAttribute("data-mode"); const bodyEl = window.document.querySelector("body"); if (mode === "dark") { bodyEl.classList.add("quarto-dark"); bodyEl.classList.remove("quarto-light"); } else { bodyEl.classList.add("quarto-light"); bodyEl.classList.remove("quarto-dark"); } } const toggleBodyColorPrimary = () => { const bsSheetEl = window.document.querySelector("link#quarto-bootstrap"); if (bsSheetEl) { toggleBodyColorMode(bsSheetEl); } } toggleBodyColorPrimary(); const icon = "\uE94B"; const anchorJS = new window.AnchorJS(); anchorJS.options = { placement: 'right', icon: icon }; anchorJS.add('.anchored'); const clipboard = new window.ClipboardJS('.code-copy-button', { target: function(trigger) { return trigger.previousElementSibling; } }); clipboard.on('success', function(e) { // button target const button = e.trigger; // don't keep focus button.blur(); // flash "checked" button.classList.add('code-copy-button-checked'); var currentTitle = button.getAttribute("title"); button.setAttribute("title", "Copied!"); let tooltip; if (window.bootstrap) { button.setAttribute("data-bs-toggle", "tooltip"); button.setAttribute("data-bs-placement", "left"); button.setAttribute("data-bs-title", "Copied!"); tooltip = new bootstrap.Tooltip(button, { trigger: "manual", customClass: "code-copy-button-tooltip", offset: [0, -8]}); tooltip.show(); } setTimeout(function() { if (tooltip) { tooltip.hide(); button.removeAttribute("data-bs-title"); button.removeAttribute("data-bs-toggle"); button.removeAttribute("data-bs-placement"); } button.setAttribute("title", currentTitle); button.classList.remove('code-copy-button-checked'); }, 1000); // clear code selection e.clearSelection(); }); function tippyHover(el, contentFn) { const config = { allowHTML: true, content: contentFn, maxWidth: 500, delay: 100, arrow: false, appendTo: function(el) { return el.parentElement; }, interactive: true, interactiveBorder: 10, theme: 'quarto', placement: 'bottom-start' }; window.tippy(el, config); } const noterefs = window.document.querySelectorAll('a[role="doc-noteref"]'); for (var i=0; i { const parentEl = el.parentElement; if (parentEl) { const cites = parentEl.dataset.cites; if (cites) { return { el, cites: cites.split(' ') }; } else { return findCites(el.parentElement) } } else { return undefined; } }; var bibliorefs = window.document.querySelectorAll('a[role="doc-biblioref"]'); for (var i=0; i> (+ x 4) (for [x [1 2 3]]))) (kind/hiccup [:div [:script (str "var xml1 = parse('" code "')")] [:div {:id "blocklyDiv1", :style {:height "100px"}}] [:script "var workspace1 = Blockly.inject('blocklyDiv1', {'toolbox': twotiles.toolbox, 'sounds': false})"] [:script "const xmlDom1 = Blockly.utils.xml.textToDom(xml1)"] [:script "Blockly.Xml.clearWorkspaceAndLoadFromXml(xmlDom1,workspace1)"]]) ``` ```JavaScript var xml1 = parse('(->> (+ x 4) (for [x [1 2 3]]))') var workspace1 = Blockly.inject('blocklyDiv1', {'toolbox': twotiles.toolbox, 'sounds': false}) const xmlDom1 = Blockly.utils.xml.textToDom(xml1) Blockly.Xml.clearWorkspaceAndLoadFromXml(xmlDom1,workspace1) ``` -------------------------------- ### Rendering Hiccup HTML in Clay Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Shows how Clay renders Hiccup, a Clojure representation of HTML, into actual HTML content using `kind/hiccup`. The example creates an unordered list with styled paragraphs. ```Clojure (kind/hiccup [:ul [:li [:p "hi"]] [:li [:big [:big [:p {:style ; https://www.htmlcsscolor.com/hex/7F5F3F {:color "#7F5F3F"}} "hello"]]]]]) ``` -------------------------------- ### Use Same Source and Target Paths Source: https://github.com/scicloj/clay/blob/main/docs/index.html Illustrates configuring `clay/make!` to use the same directory for both source and target paths. This example sets up a Quarto HTML format for a specific source file. ```Clojure (comment (clay/make! {:format [:quarto :html] :base-source-path "notebooks" :source-path "demo.clj" :base-target-path "notebooks"})) ``` -------------------------------- ### Clojure: Render Hiccup HTML and LaTeX Math Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Examples of using `kind/hiccup` to generate HTML elements and `kind/md` for rendering LaTeX mathematical expressions. ```Clojure ``` -------------------------------- ### Run Clay using Configured Alias Source: https://github.com/scicloj/clay/blob/main/docs/index.html Demonstrates how to invoke Clay using the `deps.edn` alias configured previously. This provides a more concise and convenient way to start Clay from the command line. ```clojure-cli clojure -M:clay ``` -------------------------------- ### Launch Clay from Command Line Source: https://github.com/scicloj/clay/blob/main/docs/index.html Shows the basic command to launch Clay from the command line. By default, this starts Clay in live-reload mode, automatically watching the `notebooks` directory for changes and updating the output. ```clojure-cli clojure -M -m scicloj.clay.v2.main ``` -------------------------------- ### Load Java BufferedImage from URL Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Imports necessary Java classes and defines a `defonce` to load an image from a URL into a `BufferedImage` object, which Clay can then display. ```Clojure (import javax.imageio.ImageIO java.net.URL) ``` ```Clojure (defonce clay-image (-> "https://upload.wikimedia.org/wikipedia/commons/2/2c/Clay-ss-2005.jpg" (URL.) (ImageIO/read))) ``` -------------------------------- ### Display Athletes Data as Table Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Renders the 'athletes' dataset as an interactive table using 'Inputs.table'. ```JavaScript Inputs.table(athletes) ``` -------------------------------- ### Load Athletes Dataset in Observable Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html This example shows how to load a CSV file containing athletes data into an Observable notebook using FileAttachment and csv({typed: true}). It includes both the raw Observable JavaScript and its Quarto (kind/observable) wrapper. ```Clojure (kind/observable "athletes = FileAttachment('notebooks/datasets/athletes.csv').csv({typed: true})") ``` ```JavaScript athletes = FileAttachment('notebooks/datasets/athletes.csv').csv({typed: true}) ``` -------------------------------- ### Render Cytoscape Graphs in Clay Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Defines a Cytoscape graph structure in Clojure, including nodes, edges, and styling. The `kind/cytoscape` function then renders this data into an interactive graph. Examples include basic rendering and applying CSS styles. ```Clojure (def cytoscape-example {:elements {:nodes [{:data {:id "a" :parent "b"} :position {:x 215 :y 85}} {:data {:id "b"}} {:data {:id "c" :parent "b"} :position {:x 300 :y 85}} {:data {:id "d"} :position {:x 215 :y 175}} {:data {:id "e"}} {:data {:id "f" :parent "e"} :position {:x 300 :y 175}}] :edges [{:data {:id "ad" :source "a" :target "d"}} {:data {:id "eb" :source "e" :target "b"}}]} :style [{:selector "node" :css {:content "data(id)" :text-valign "center" :text-halign "center"}} {:selector "parent" :css {:text-valign "top" :text-halign "center"}} {:selector "edge" :css {:curve-style "bezier" :target-arrow-shape "triangle"}}] :layout {:name "preset" :padding 5}}) (kind/cytoscape cytoscape-example) ``` ```JavaScript { value = {"elements":{"nodes":[{"data":{"id":"a","parent":"b"},"position":{"x":215,"y":85}},{"data":{"id":"b"}},{"data":{"id":"c","parent":"b"},"position":{"x":300,"y":85}},{"data":{"id":"d"},"position":{"x":215,"y":175}},{"data":{"id":"e"}},{"data":{"id":"f","parent":"e"},"position":{"x":300,"y":175}}],"edges":[{"data":{"id":"ad","source":"a","target":"d"}},{"data":{"id":"eb","source":"e","target":"b"}}]},"style":[{"selector":"node","css":{"content":"data(id)","text-valign":"center","text-halign":"center"}},{"selector":"parent","css":{"text-valign":"top","text-halign":"center"}},{"selector":"edge","css":{"curve-style":"bezier","target-arrow-shape":"triangle"}}],"layout":{"name":"preset","padding":5}}; value['container'] = document.currentScript.parentElement; cytoscape(value); }; ``` ```Clojure (-> cytoscape-example (kind/cytoscape {:style {:width "100px" :height "100px"}})) ``` ```JavaScript { value = {"elements":{"nodes":[{"data":{"id":"a","parent":"b"},"position":{"x":215,"y":85}},{"data":{"id":"b"}},{"data":{"id":"c","parent":"b"},"position":{"x":300,"y":85}},{"data":{"id":"d"},"position":{"x":215,"y":175}},{"data":{"id":"e"}},{"data":{"id":"f","parent":"e"},"position":{"x":300,"y":175}}],"edges":[{"data":{"id":"ad","source":"a","target":"d"}},{"data":{"id":"eb","source":"e","target":"b"}}]},"style":[{"selector":"node","css":{"content":"data(id)","text-valign":"center","text-halign":"center"}},{"selector":"parent","css":{"text-valign":"top","text-halign":"center"}},{"selector":"edge","css":{"curve-style":"bezier","target-arrow-shape":"triangle"}}],"layout":{"name":"preset","padding":5}}; value['container'] = document.currentScript.parentElement; cytoscape(value); }; ``` -------------------------------- ### Embed Vega-Lite Point Plot with Inline Data (JavaScript) Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Shows the JavaScript code generated by Clay to embed a Vega-Lite visualization. This example includes the full data values and encoding specifications directly within the `vegaEmbed` call. ```JavaScript vegaEmbed(document.currentScript.parentElement, {"data":{"values":[{"w":6,"z":5,"x":0,"y":-0.1580095078907623},{"w":8,"z":1,"x":1,"y":-0.2551104430969119},{"w":1,"z":1,"x":2,"y":0.061750208482353464},{"w":6,"z":2,"x":3,"y":-0.03040498944419623},{"w":2,"z":5,"x":4,"y":-0.0658557952888732},{"w":8,"z":3,"x":5,"y":-0.26014976291175007},{"w":0,"z":5,"x":6,"y":-0.054972311955674646},{"w":2,"z":3,"x":7,"y":0.2885396659940157},{"w":6,"z":4,"x":8,"y":0.47468593575204787}]},"mark":"point","encoding":{"size":{"field":"w","type":"quantitative"},"x":{"field":"x","type":"quantitative"},"y":{"field":"y","type":"quantitative"},"fill":{"field":"z","type":"nominal"}}}); ``` -------------------------------- ### Plotly Viewer Configuration JSON Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html JSON configuration for the Plotly viewer, specifying dimensions and padding for both viewer and browser contexts. ```JSON {"viewer":{"width":"100%","height":400,"padding":"0","fille":true},"browser":{"width":"100%","height":400,"padding":"0","fille":true}} ``` -------------------------------- ### Render Markdown content with kind/md Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Shows how to render Markdown text using `kind/md`, supporting single strings, vectors of strings, and lists of strings for multi-paragraph or complex Markdown structures. ```Clojure (kind/md "This is [markdown](https://www.markdownguide.org/).") ``` ```Clojure (kind/md ["\n* This is [markdown](https://www.markdownguide.org/).\n * *Isn't it??*" "\n* Here is **some more** markdown."]) ``` ```Clojure (kind/md (list "\n* This is [markdown](https://www.markdownguide.org/).\n * *Isn't it??*" "\n* Here is **some more** markdown.")) ``` -------------------------------- ### Display image from URL with kind/image Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Uses `kind/image` with a map containing a `:src` key to display an image directly from a given URL, providing a simple way to embed external images. ```Clojure (kind/image {:src "https://upload.wikimedia.org/wikipedia/commons/2/2c/Clay-ss-2005.jpg"}) ``` -------------------------------- ### Initialize AnchorJS for Headings Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Sets up AnchorJS to add permalinks (anchors) to headings with the class '.anchored'. This allows users to easily link to specific sections of the document, executed once the DOM is loaded. ```JavaScript const icon = "\uE94B"; const anchorJS = new window.AnchorJS(); anchorJS.options = { placement: 'right', icon: icon }; anchorJS.add('.anchored'); ``` -------------------------------- ### Render Table with DataTables Integration Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Illustrates how to convert a collection of maps into a dataset and then render it as an interactive table using `kind/table`, explicitly enabling DataTables for enhanced functionality. ```Clojure (-> people-as-maps tc/dataset (kind/table {:use-datatables true})) ``` -------------------------------- ### Display a table directly from a sequence of sequences Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Demonstrates `kind/table`'s ability to directly accept a sequence of sequences (like `people-as-vectors`) as input. This creates a table where each inner sequence represents a row. ```Clojure (kind/table (take 5 people-as-vectors)) ``` -------------------------------- ### Import and Display D3 Zoomable Sunburst Chart Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Imports a pre-built zoomable sunburst chart from '@d3/zoomable-sunburst' and assigns the loaded 'population' data to it. The 'chart' variable is then displayed. ```JavaScript import { chart } with { population as data } from '@d3/zoomable-sunburst' chart ``` -------------------------------- ### Create Vega-Lite Plot from Inline CSV Data (Clojure) Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Demonstrates how to define a Vega-Lite point plot in Clojure where the dataset is provided directly as an inline CSV string within the `kind/vega-lite` function call. ```Clojure (-> {:data {:values "x,y 1,1 2,4 3,9 -1,1 -2,4 -3,9" :format {:type :csv}}, :mark "point" :encoding {:x {:field "x", :type "quantitative"} :y {:field "y", :type "quantitative"}}}} kind/vega-lite) ``` -------------------------------- ### Generate Vega-Lite Point Plot in Clojure Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Provides Clojure functions to create random data and define a Vega-Lite point plot specification. This snippet showcases programmatic visualization definition using `kind/vega-lite`. ```Clojure (defn vega-lite-point-plot [data] (-> {:data {:values data}, :mark "point" :encoding {:size {:field "w" :type "quantitative"} :x {:field "x", :type "quantitative"}, :y {:field "y", :type "quantitative"}, :fill {:field "z", :type "nominal"}}}} kind/vega-lite)) (defn random-data [n] (->> (repeatedly n #(- (rand) 0.5)) (reductions +) (map-indexed (fn [x y] {:w (rand-int 9) :z (rand-int 9) :x x :y y})))) (defn random-vega-lite-plot [n] (-> n random-data vega-lite-point-plot)) (random-vega-lite-plot 9) ``` -------------------------------- ### Display a table from row maps with selected columns Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Illustrates how to display a subset of columns when rendering a table from a sequence of maps using `kind/table`. By specifying `:column-names`, only the desired columns are shown. ```Clojure (kind/table {:column-names [:preferred-language] :row-maps (take 5 people-as-maps)}) ``` -------------------------------- ### PDB HELIX Record: Alpha Helix Definition Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html The HELIX record identifies the location and type of helical secondary structures within the protein, specifying start and end residues, helix class, and length. ```PDB Format HELIX 1 H1 SER A 50 GLU A 54 1 5 HELIX 2 H2 GLY A 77 PHE A 83 1 7 HELIX 3 H3 ARG A 208 VAL A 214 1 7 ``` -------------------------------- ### Code Block Copy-to-Clipboard Functionality Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Implements copy-to-clipboard for code blocks using ClipboardJS. It handles success feedback (flashing 'Copied!' message), clears text selection, and correctly extracts text from code blocks by removing annotation elements. This setup runs on 'DOMContentLoaded'. ```JavaScript const isCodeAnnotation = (el) => { for (const clz of el.classList) { if (clz.startsWith('code-annotation-')) { return true; } } return false; } const onCopySuccess = function(e) { const button = e.trigger; button.blur(); button.classList.add('code-copy-button-checked'); var currentTitle = button.getAttribute("title"); button.setAttribute("title", "Copied!"); let tooltip; if (window.bootstrap) { button.setAttribute("data-bs-toggle", "tooltip"); button.setAttribute("data-bs-placement", "left"); button.setAttribute("data-bs-title", "Copied!"); tooltip = new bootstrap.Tooltip(button, { trigger: "manual", customClass: "code-copy-button-tooltip", offset: [0, -8]}); tooltip.show(); } setTimeout(function() { if (tooltip) { tooltip.hide(); button.removeAttribute("data-bs-title"); button.removeAttribute("data-bs-toggle"); button.removeAttribute("data-bs-placement"); } button.setAttribute("title", currentTitle); button.classList.remove('code-copy-button-checked'); }, 1000); e.clearSelection(); } const getTextToCopy = function(trigger) { const codeEl = trigger.previousElementSibling.cloneNode(true); for (const childEl of codeEl.children) { if (isCodeAnnotation(childEl)) { childEl.remove(); } } return codeEl.innerText; } const clipboard = new window.ClipboardJS('.code-copy-button:not([data-in-quarto-modal])', { text: getTextToCopy }); clipboard.on('success', onCopySuccess); if (window.document.getElementById('quarto-embedded-source-code-modal')) { const clipboardModal = new window.ClipboardJS('.code-copy-button[data-in-quarto-modal]', { text: getTextToCopy, container: window.document.getElementById('quarto-embedded-source-code-modal') }); clipboardModal.on('success', onCopySuccess); } ``` -------------------------------- ### Clojure Hiccup HTML Generation with Kindly Source: https://github.com/scicloj/clay/blob/main/examples/example-project/docs/example1.html This Clojure snippet utilizes the `kind/hiccup` function to generate HTML content. It constructs a div element with a specified background color and embeds a paragraph containing 'hello', showcasing how to produce rich, styled output in Clay notebooks. ```Clojure (kind/hiccup [:div {:style {:background-color "#eeddcc"}} [:p "hello"]]) ``` -------------------------------- ### OJS Runtime Initialization and File Protocol Alert Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Initializes the OJS runtime paths and displays an alert if the page is accessed via the 'file://' protocol, as the runtime requires a web server. This block executes immediately upon script loading. ```JavaScript if (window.location.protocol === "file:") { alert("The OJS runtime does not work with file:// URLs. Please use a web server to view this document."); } window._ojs.paths.runtimeToDoc = "../.."; window._ojs.paths.runtimeToRoot = "../.."; window._ojs.paths.docToRoot = ""; window._ojs.selfContained = false; window._ojs.runtime.interpretFromScriptTags(); ``` -------------------------------- ### Create Quarto Book with Favicon Source: https://github.com/scicloj/clay/blob/main/docs/index.html Demonstrates how to create a Quarto book using `clay/make!` with a specified favicon. It configures the output format to Quarto HTML, sets source and target paths, and defines the book title and favicon. ```Clojure (comment (clay/make! {:format [:quarto :html] :base-source-path "notebooks" :source-path ["index.clj" "chapter.clj" "another_chapter.md"] :base-target-path "book" :book {:title "Book Example" :favicon "notebooks/favicon.ico"} ;; Empty the target directory first: :clean-up-target-dir true})) ``` -------------------------------- ### Basic Python Arithmetic Example Source: https://github.com/scicloj/clay/blob/main/notebooks/test.ipynb A simple Python example demonstrating basic arithmetic operations. This snippet shows the addition of two integers, illustrating fundamental language syntax. ```Python 1+2 ``` -------------------------------- ### Rendering a Simple Reagent Function Component in Clay Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Demonstrates rendering a basic Reagent function component using `kind/reagent`. The component takes a list of numbers, increments them, and displays the result within a styled paragraph. ```Clojure (kind/reagent ['(fn [numbers] [:p {:style {:background "#d4ebe9"}} (pr-str (map inc numbers))]) (vec (range 40))]) ``` ```ClojureScript (Rendered Output) (reagent.dom/render [(fn [numbers] [:p {:style {:background "#d4ebe9"}} (pr-str (map inc numbers))]) [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39]] (js/document.getElementById "id1")) ``` -------------------------------- ### Display Clojure code with kind/code Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Demonstrates how to display Clojure code snippets using `kind/code`, supporting single code strings, vectors of code strings, and lists of code strings for presenting multiple lines or blocks of code. ```Clojure (kind/code "(update {:x 9} :x inc)") ``` ```Clojure (kind/code ["(update {:x 9} :x inc)" "(update {:x 9} :x dec)"]) ``` ```Clojure (kind/code (list "(update {:x 9} :x inc)" "(update {:x 9} :x dec)")) ``` -------------------------------- ### Clojure Hiccup Specification Example Source: https://github.com/scicloj/clay/blob/main/docs/index.html Demonstrates creating a simple HTML structure using Hiccup syntax within a Clojure notebook. This example shows a `div` with inline styling and an unordered list with three list items. ```Clojure (kind/hiccup [:div {:style {:background "#efe9e6" :border-style :solid}} [:ul [:li "one"] [:li "two"] [:li "three"]]]) ``` -------------------------------- ### Load Population JSON Data in Observable Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html This example shows how to load a JSON file containing population data into an Observable notebook using FileAttachment and json(). It includes both the raw Observable JavaScript and its Quarto (kind/observable) wrapper. ```Clojure (kind/observable "population = FileAttachment('notebooks/datasets/population.json').json()") ``` ```JavaScript population = FileAttachment('notebooks/datasets/population.json').json() ``` -------------------------------- ### Render Athletes Data as Interactive Table in Observable Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html This example uses Inputs.table() to render the athletes dataset as an interactive, sortable table within an Observable notebook. It includes both the raw Observable JavaScript and its Quarto (kind/observable) wrapper. ```Clojure (kind/observable "Inputs.table(athletes)") ``` ```JavaScript Inputs.table(athletes) ``` -------------------------------- ### Clojure Namespace Definition for Clay Project Source: https://github.com/scicloj/clay/blob/main/examples/example-project/docs/example1-revealjs.html This Clojure code defines a namespace `example1` and requires the `scicloj.clay.v2.api` and `scicloj.kindly.v4.kind` libraries. This setup is essential for using Clay's functionalities and Kindly's rendering capabilities within a Clojure project. ```Clojure (ns example1 (:require [scicloj.clay.v2.api :as clay] [scicloj.kindly.v4.kind :as kind])) ``` -------------------------------- ### Create a Tablecloth dataset from a sequence of maps Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Demonstrates creating a Tablecloth dataset from a sequence of maps. Each map represents a row, and keys become column names. Missing keys in some maps result in `nil` values for those cells. ```Clojure (-> [{:x 1 :y 2 :z 3} {:y 4 :z 5}] tc/dataset) ``` -------------------------------- ### Programmatic 3Dmol Viewer Control in Reagent Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html This advanced snippet demonstrates programmatic control over a 3Dmol.js viewer within a Reagent component. It first fetches PDB data, then uses a `ref` callback to directly interact with the 3Dmol.js API. It creates a viewer, applies custom styles (like outline), adds models and a sphere, and controls zooming and rendering, showcasing direct manipulation of the viewer's state and appearance. It also requires the `:three-d-mol` dependency. ```Clojure (defonce pdb-2POR (slurp "https://files.rcsb.org/download/2POR.pdb")) (kind/reagent ['(fn [{:keys [pdb-data]}] [:div {:style {:width "100%" :height "500px" :position "relative"} :ref (fn [el] (let [config (clj->js {:backgroundColor "0xffffff"}) viewer (.createViewer js/$3Dmol el)] (.setViewStyle viewer (clj->js {:style "outline"})) (.addModelsAsFrames viewer pdb-data "pdb") (.addSphere viewer (clj->js {:center {:x 0 :y 0 :z 0} :radius 5 :color "green" :alpha 0.2})) (.zoomTo viewer) (.render viewer) (.zoom viewer 0.8 2000)))}]) {:pdb-data pdb-2POR}] ;; Note we need to mention the dependency: {:html/deps [:three-d-mol]}) ``` -------------------------------- ### Rendering Dynamic Echarts with Reagent in Clay Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Shows how to integrate Echarts with Reagent components in Clay. This example creates a dynamic bar chart that updates its data periodically using `js/setInterval` and a Reagent atom to manage the chart specification. ```Clojure (kind/reagent ['(fn [{:keys [spec0 transition time-for-transition]}] (let [*spec (reagent.core/atom spec0)] (fn [] ^{:key @*spec} [:div [:div {:style {:height "400px"} :ref (fn [el] (when el (let [chart (.init js/echarts el)] (.setOption chart (clj->js @*spec)))))}] (js/setInterval #(swap! *spec transition) time-for-for-transition) ;; Include this to force component update: [:p {:style {:display :none}} (hash @*spec)]]))) {:spec0 {:title {:text "Echarts Example"} :tooltip {} :legend {:data ["sales"]} :xAxis {:data ["Shirts", "Cardigans", "Chiffons", "Pants", "Heels", "Socks"]} :yAxis {} :series [{:name "sales" :type "bar" :data [5 20 36 10 10 20]}]} :transition '(fn [spec] (update-in spec [:series 0 :data] (partial map #(+ % (rand-int 10) -5)))) :time-for-transition 1000}] {:html/deps [:echarts]}) ``` ```ClojureScript (Rendered Output) (reagent.dom/render [(fn [{:keys [spec0 transition time-for-transition]}] (let [*spec (reagent.core/atom spec0)] (fn [] [:div [:div {:style {:height "400px"}, :ref (fn [el] (when el (let [chart (.init js/echarts el)] (.setOption chart (clj->js (clojure.core/deref *spec)))))}] (js/setInterval (fn* [] (swap! *spec transition)) time-for-transition) [:p {:style {:display :none}} (hash (clojure.core/deref *spec))]]))) {:spec0 {:title {:text "Echarts Example"}, :tooltip {}, :legend {:data ["sales"]}, :xAxis {:data ["Shirts" "Cardigans" "Chiffons" "Pants" "Heels" "Socks"]}, :yAxis {}, :series [{:name "sales", :type "bar", :data [5 20 36 10 10 20]}]}, :transition (fn [spec] (update-in spec [:series 0 :data] (partial map (fn* [p1__62347#] (+ p1__62347# (rand-int 10) -5))))), :time-for-transition 1000}] (js/document.getElementById "id3")) ``` -------------------------------- ### Create a Tablecloth dataset from a map of vectors Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Illustrates the creation of a `tech.ml.dataset` using Tablecloth's `tc/dataset` function. The dataset is constructed from a map where keys represent column names and values are vectors of data. ```Clojure (-> {:x (range 6) :y [:A :B :C :A :B :C]} tc/dataset) ``` -------------------------------- ### Create ECharts Visualizations in Clay Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Illustrates how to define ECharts options in Clojure for a bar chart, including title, tooltip, legend, axes, and series data. The `kind/echarts` function processes this definition to generate the chart. Examples show basic rendering and applying container styles. ```Clojure (def echarts-example {:title {:text "Echarts Example"} :tooltip {} :legend {:data ["sales"]} :xAxis {:data ["Shirts", "Cardigans", "Chiffons", "Pants", "Heels", "Socks"]} :yAxis {} :series [{:name "sales" :type "bar" :data [5 20 36 10 10 20]}]}) (kind/echarts echarts-example) ``` ```JavaScript { var myChart = echarts.init(document.currentScript.parentElement); myChart.setOption({"title":{"text":"Echarts Example"},"tooltip":{},"legend":{"data":["sales"]},"xAxis":{"data":["Shirts","Cardigans","Chiffons","Pants","Heels","Socks"]},"yAxis":{},"series":[{"name":"sales","type":"bar","data":[5,20,36,10,10,20]}]}); }; ``` ```Clojure (-> echarts-example (kind/echarts {:style {:width "500px" :height "200px"}})) ``` ```JavaScript { var myChart = echarts.init(document.currentScript.parentElement); myChart.setOption({"title":{"text":"Echarts Example"},"tooltip":{},"legend":{"data":["sales"]},"xAxis":{"data":["Shirts","Cardigans","Chiffons","Pants","Heels","Socks"]},"yAxis":{},"series":[{"name":"sales","type":"bar","data":[5,20,36,10,10,20]}]}); }; ``` -------------------------------- ### Display a Tablecloth dataset as an interactive table Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Shows how to render an existing Tablecloth dataset (`people-as-dataset`) as an interactive table using Clay's `kind/table` function. This provides a visual representation of the dataset's contents. ```Clojure (-> people-as-dataset kind/table) ``` -------------------------------- ### Display a table from a map of sequences using kind/table Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Illustrates `kind/table`'s support for a map where keys are column names and values are sequences representing column data. This format is convenient for columnar data input. ```Clojure (kind/table {:x (range 6) :y [:A :B :C :A :B :C]}) ``` -------------------------------- ### Load Population JSON Data Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Loads population data from a JSON file using 'FileAttachment'. ```JavaScript population = FileAttachment('notebooks/datasets/population.json').json() ``` -------------------------------- ### Render HTML content with kind/html Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Demonstrates various ways to embed and render raw HTML and SVG content using the `kind/html` function, including single strings, multi-line strings, vectors of strings, and lists of strings. ```Clojure (kind/html "
") ``` ```Clojure (kind/html "\n\n\n ") ``` ```Clojure (kind/html ["" "" ""]) ``` ```Clojure (kind/html (list "" "" "")) ``` -------------------------------- ### Embed Clojure/EDN Output using Portal JavaScript API Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Demonstrates how to use the `portal_api.embed().renderOutputItem` function to display Clojure (EDN) data, including Hiccup and Vega-Lite visualizations, directly in a web environment. This allows for dynamic rendering of Clojure data structures. ```JavaScript portal_api.embed().renderOutputItem( {'mime': 'x-application/edn', 'text': (() => "[^{:kindly/kind :kind/hiccup, :kindly/options nil, :portal.viewer/default :portal.viewer/hiccup} [:big [:big \"a plot\"]] ^#:portal.viewer{:default :portal.viewer/hiccup} [:portal.viewer/vega-lite ^#:kindly{:kind :kind/vega-lite, :options nil} {:data {:values ({:w 1, :z 2, :x 0, :y -0.10935787509621697} {:w 2, :z 2, :x 1, :y 0.018434476814047085} {:w 1, :z 6, :x 2, :y 0.15983638696696334} {:w 5, :z 8, :x 3, :y -0.027527588594307262} {:w 2, :z 5, :x 4, :y -0.30341415217320244} {:w 2, :z 1, :x 5, :y -0.13849755100904582} {:w 4, :z 6, :x 6, :y -0.525205179816681} {:w 2, :z 1, :x 7, :y -0.8676626719497325} {:w 8, :z 8, :x 8, :y -1.1358042718418164})}, :mark \"point\", :encoding {:size {:field \"w\", :type \"quantitative\"}, :x {:field \"x\", :type \"quantitative\"}, :y {:field \"y\", :type \"quantitative\"}, :fill {:field \"z\", :type \"nominal\"}}}]])} , document.currentScript.parentElement); ``` -------------------------------- ### Display Population Data Variable Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Simply outputs the 'population' variable, which typically renders its content in Observable notebooks. ```JavaScript population ``` -------------------------------- ### Display Athletes Data Variable Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Simply outputs the 'athletes' variable, which typically renders its content in Observable notebooks. ```JavaScript athletes ``` -------------------------------- ### JavaScript DataTables Initialization (Full Options) Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Shows the generated JavaScript code for initializing a DataTables instance directly in the browser, configuring options such as disabling paging, setting scroll height, and specifying pagination type. ```JavaScript new DataTable(document.currentScript.parentElement, {"paging":false,"scrollY":400,"sPaginationType":"full\_numbers","order":[]}); ``` -------------------------------- ### Log message to JavaScript console Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Demonstrates logging a string to the browser's JavaScript console from ClojureScript using `js/console.log`. ```Clojure (.log js/console "hello") ``` -------------------------------- ### Load Athletes CSV Data Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Loads athlete data from a CSV file using 'FileAttachment' and parses it with type inference enabled. ```JavaScript athletes = FileAttachment('notebooks/datasets/athletes.csv').csv({typed: true}) ``` -------------------------------- ### Pretty print a data structure using Clay's kind/pprint Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Demonstrates the use of `:kind/pprint` to pretty-print a complex Clojure data structure. This function ensures that the output is formatted for readability, including special handling for embedded Hiccup and dataset elements. ```Clojure (kind/pprint nested-structure-1) ``` -------------------------------- ### PDB SITE Record: Binding Site Definition Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html The SITE record identifies residues and heteroatoms that form a specific functional site -------------------------------- ### Hiding Values with Kindly in Clay Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Illustrates the use of `kind/hidden` to prevent values from being displayed in Clay. Values wrapped with `kind/hidden` are not rendered. ```Clojure (kind/hidden 9) ``` -------------------------------- ### Rendering an Interactive Reagent Component with Atom in Clay Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Illustrates rendering a Reagent component that uses a `reagent.core/atom` to manage state. The component displays a click counter with an interactive button that updates the atom's value. ```Clojure (kind/reagent ['(fn [] (let [*click-count (reagent.core/atom 0)] (fn [] [:div "The atom " [:code "*click-count"] " has value: " @*click-count ". " [:input {:type "button" :value "Click me!" :on-click #(swap! *click-count inc)}]])))]) ``` ```ClojureScript (Rendered Output) (reagent.dom/render [(fn [] (let [*click-count (reagent.core/atom 0)] (fn [] [:div "The atom " [:code "*click-count"] " has value: " (clojure.core/deref *click-count) ". " [:input {:type "button", :value "Click me!", :on-click (fn* [] (swap! *click-count inc))}]]) )] (js/document.getElementById "id2")) ``` -------------------------------- ### Display a table directly from a sequence of maps Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Shows `kind/table` accepting a sequence of maps directly. It automatically infers column names from the map keys and displays the data as a table, simplifying table generation. ```Clojure (kind/table (take 5 people-as-maps)) ``` -------------------------------- ### Define a Tablecloth dataset from `people-as-maps` Source: https://github.com/scicloj/clay/blob/main/docs/clay_book.examples.html Defines a new variable `people-as-dataset` by converting the `people-as-maps` data into a Tablecloth dataset. This dataset can then be used for further analysis or display. ```Clojure (def people-as-dataset (tc/dataset people-as-maps)) ```