txt
stringlengths
202
72.4k
### ---------------------------------------------------- ### -- Air ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: index.md ### ---------------------------------------------------- Document Index =============== - [Air](docs/Air.md) - [Air::Base](docs/Air/Base.md) - [Air::Component](docs/Air/Component.md) - [Air::Form](docs/Air/Form.md) - [Air::Functional](docs/Air/Functional.md)
### ---------------------------------------------------- ### -- Air ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: dist.ini ### ---------------------------------------------------- name = Air [ReadmeFromPod] enabled = false filename = lib/Air.rakumod [UploadToZef] [Badges] provider = github-actions/test.yml
### ---------------------------------------------------- ### -- Air ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: bin/dunderm.raku ### ---------------------------------------------------- #!/usr/bin/env raku use lib "../lib"; my $p; { use Air::Functional :BASE; use Air::Base; #| write your own role to setup default values and custom attributes class MyPage is Page { submethod TWEAK { self.html.head.links.append: Link.new: attrs => {:rel<stylesheet>, :href<https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css>}; self.html.head.style = Style.new: q:to/END/; .jumbotron { background-color: #e6ffe6; text-align: center; } END } } #| then each Page instance can reuse the defaults $p = MyPage.new: description => 'raku does htmx', title => 'Raku HTMX', ; $p.html.body.main = Main.new: [ div :class<jumbotron>, [ h1 "Welcome to Dunder Mifflin!"; #use ; to stop <h1> slurping <p> p [ "Dunder Mifflin Inc. (stock symbol "; strong 'DMI'; ") "; q:to/END/; is a micro-cap regional paper and office supply distributor with an emphasis on servicing small-business clients. END ]; ]; p :hx-get<https://v2.jokeapi.dev/joke/Any?format=txt&safe-mode>, "Click Me"; ]; } { use Cro::HTTP::Router; use Cro::HTTP::Server; my $routes = route { get -> { content 'text/html', $p.HTML; } }; my Cro::Service $http = Cro::HTTP::Server.new( http => <1.1>, host => "0.0.0.0", port => 3000, application => $routes, ); $http.start; say "Listening at http://0.0.0.0:3000"; react { whenever signal(SIGINT) { say "Shutting down..."; $http.stop; done; } } }
### ---------------------------------------------------- ### -- Air ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: bin/minimal.raku ### ---------------------------------------------------- #!/usr/bin/env raku use lib "../lib"; my $p; { use Air::Functional :BASE; use Air::Base; $p = Page.new: title => "Raku HTMX", main => Main.new: p 'Hello World!'; $p.html.head.style = Style.new: 'p {color: blue;}'; } { use Cro::HTTP::Router; use Cro::HTTP::Server; my $routes = route { get -> { content 'text/html', $p.HTML; } }; my Cro::Service $http = Cro::HTTP::Server.new( http => <1.1>, host => "0.0.0.0", port => 3000, application => $routes, ); $http.start; say "Listening at http://0.0.0.0:3000"; react { whenever signal(SIGINT) { say "Shutting down..."; $http.stop; done; } } }
### ---------------------------------------------------- ### -- Air ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: bin/table.raku ### ---------------------------------------------------- #!/usr/bin/env raku use lib "../lib"; my $html; { use Air::Functional :BASE; use Air::Base; my %data = :thead[["Planet", "Hexameter (km)", "Distance to Sun (AU)", "Orbit (days)"],], :tbody[["Mercury", "4,880", "0.39", "88"], ["Venus" , "12,104", "0.72", "225"], ["Earth" , "12,742", "1.00", "365"], ["Mars" , "6,779", "1.52", "687"],], :tfoot[["Average", "9,126", "0.91", "341"],]; $html = div [ h3 'Table'; table |%data; ]; } { use Cro::HTTP::Router; use Cro::HTTP::Server; my $routes = route { get -> { content 'text/html', $html; } }; my Cro::Service $http = Cro::HTTP::Server.new( http => <1.1>, host => "0.0.0.0", port => 3000, application => $routes, ); $http.start; say "Listening at http://0.0.0.0:3000"; react { whenever signal(SIGINT) { say "Shutting down..."; $http.stop; done; } } }
### ---------------------------------------------------- ### -- Air ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: docs/Air.md ### ---------------------------------------------------- Air === Breathing life into the raku **hArc stack** (HTMX, Air, Red, Cro). **Air** aims to be the purest possible expression of [HTMX](https://htmx.org). **hArc** websites are written in functional code. This puts the emphasis firmly onto the content and layout of the site, rather than boilerplate markup that can often obscure the intention. **Air** is basically a set of libraries that produce HTML code and serve it using Cro. The result is a concise, legible and easy-to-maintain website codebase. SYNOPSIS ======== ```raku #!/usr/bin/env raku use Air::Functional :BASE; use Air::Base; my &index = &page.assuming( #:REFRESH(1), title => 'hÅrc', description => 'HTMX, Air, Red, Cro', footer => footer p ['Aloft on ', b safe '&Aring;ir'], ); my &planets = &table.assuming( :thead[["Planet", "Diameter (km)", "Distance to Sun (AU)", "Orbit (days)"],], :tbody[["Mercury", "4,880", "0.39", "88"], ["Venus" , "12,104", "0.72", "225"], ["Earth" , "12,742", "1.00", "365"], ["Mars" , "6,779", "1.52", "687"],], :tfoot[["Average", "9,126", "0.91", "341"],], ); sub SITE is export { site #:bold-color<blue>, index main div [ h3 'Planetary Table'; planets; ] } ``` GETTING STARTED =============== Install raku - eg. from [rakubrew](https://rakubrew.org), then: Install Air, Cro & Red - zef install --/test cro - zef install Red --exclude="pq:ver<5>" - zef install Air Run and view some examples - git clone https://github.com/librasteve/Air-Play.git && cd Air-Play - export WEBSITE_HOST="0.0.0.0" && export WEBSITE_PORT="3000" - raku -Ilib service.raku - browse to http://localhost:3000 Cro has many other options as documented at [Cro](https://cro.raku.org) for deployment to a production server. DESCRIPTION =========== Air is not a framework, but a set of libraries. Full control over the application loop is retained by the coder. Air does not provide an HTML templating language, instead each HTML tag is written as a subroutine call where the argument is a list of `@inners` and attributes are passed via the raku Pair syntax `:name<value>`. [Cro templates](https://cro.raku.org/docs/reference/cro-webapp-template-syntax) are great if you would rather take the template approach. Reusability is promoted by the structure of the libraries - individuals and teams can create and install your own libraries to encapsulate design themes, re-usable web components and best practice. Air is comprised of four core libraries: * Air::Functional - wraps HTML tags as functions * Air::Base - a set of handy prebuilt components * Air::Component - make your own components * Air::Form - declarative forms **[Air::Play](https://raku.land/zef:librasteve/Air::Play)** is a companion raku module with various **Air** website examples. The Air documentation is at [https://librasteve.github.io/Air](https://librasteve.github.io/Air) TIPS & TRICKS ============= * When debugging, use the raku `note` sub to out put debuggin info to stderr (ie in the Cro Log stream) * When passing a 2D Array to a tag function, make sure that there is a trailing comma `:tbody[["Mercury", "4,880", "0.39", "88"],]` * An error message like *insufficient arguments* is often caused by separating two tag functions with a comma `,` instead of a semicolon `;` * In development set CRO_DEV=1 in the [environment](https://cro.services/docs/reference/cro-webapp-template#Template_auto-reload) AUTHOR ====== Steve Roe <[email protected]> The `Air::Component` module provided is based on an early version of the raku `Cromponent` module, author Fernando Corrêa de Oliveira <[email protected]>, however unlike Cromponent this module does not use Cro Templates. COPYRIGHT AND LICENSE ===================== Copyright(c) 2025 Henley Cloud Consulting Ltd. This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
### ---------------------------------------------------- ### -- Air ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: docs/Air/Form.md ### ---------------------------------------------------- Air::Form ========= This raku module is one of the core libraries of the raku **Air** distribution. It provides a Form class that integrates Air with the Cro::WebApp::Form module to provide a simple,yet rich declarative abstraction for web forms. Air::Form uses Air::Functional for the Taggable role so that Forms can be employed within Air code. Air::Form is an alternative to Air::Component. SYNOPSIS ======== An Air::Form is declared as a regular raku Object Oriented (OO) class. Specifically form input fields are set up via public attributes of the class ... `has Str $.email` and so on. Check out the [primer](https://docs.raku.org/language/objects) on raku OO basics. #### Form Declaration ```raku use Air::Form; class Contact does Form { has Str $.first-names is validated(%va<names>); has Str $.last-name is validated(%va<name>) is required; has Str $.email is validated(%va<email>) is required is email; has Str $.city is validated(%va<text>); method form-routes { self.init; self.controller: -> Contact $form { if $form.is-valid { note "Got form data: $form.form-data()"; self.finish: 'Contact info received!' } else { self.retry: $form } } } } my $contact-form = Contact.empty; ``` Declaration Class and Attributes: * `use Air::Form` and then `does Form` in the class declaration * each public attribute such as `has Str $.email` declares a form input * attribute traits such as `is email` control the form behaviour * the trait `is required` is a regular class trait, and also marks the input * see below for details on `is validated(...)` and other traits * `novalidate` is set for the browser, since validation is done on the server Form Routes: * `method form-routes {}` is called by `site` to set up the form post route * the form uses HTMX `"hx-post="$form-url" hx-swap=\"outerHTML\"` * `self.init` initializes the form HTML with styles, validations and so on * `self.controller` takes a `&handler` * the handler is called by Cro, form field data is passed in the `$form` parameter Essential Methods: * `$form.is-valid` checks the form data against defined validations * `$form.form-data` returns the form data as a Hash * `self.finish` returns HTML to the client (for the HTMX swap) * `self.retry: $form` returns the partially validated form data with errors * `Contact.empty` prepares an empty form for the first use in a page (use instead of `Contact.new` to avoid validation errors) Several other Air::Form methods are described below. #### Form Consumption Forms can then be used in an Air application like this: ```raku my $contact-form = Contact.empty; #repeated from above use Air::Functional :BASE; use Air::Base; # define custom page properties my &index = &page.assuming( title => 'hÅrc', description => 'HTMX, Air, Red, Cro', nav => nav( logo => safe('<a href="/">h<b>&Aring;</b>rc</a>'), widgets => [lightdark], ), footer => footer p ['Aloft on ', b 'åir'], ); # use the $contact-form in an Air website sub SITE is export { site :register[$contact-form], index main content [ h2 'Contact Form'; $contact-form; ]; } ``` Note: * `:register[$contact-form]` tells the site to make the form route * `$contact-form` does the role `Taggable` so it can be used within Air::Functional code DESCRIPTION =========== `Air::Form`s do the `Cro::WebApp::Form` role. Therefore many of the features are set out in tne [Cro docs](https://cro.raku.org/docs/reference/cro-webapp-form). Form Controls ------------- Re-exported from `Cro::WebApp::Form`, per the [Cro docs](https://cro.raku.org/docs/reference/cro-webapp-form#Form_controls) Traits are used to describe the kinds of controls that will be used on a form. The full set of HTML5 control types are available. Remember to check browser support for them is sufficient if needing to cater to older browsers. They mostly follow the HTML 5 control names, however in a few cases alternative names are offered for convenience. Taking care to use is email and is telephone is especially helpful for mobile users. * is password - a password input * is number - a number input (set implicitly if a numeric type is used) * is color - a color input * is date - a date input * is datetime-local / is datetime - a datetime-local input * is email - an email input * is month - a month input * is multiline - a multiline text input (rendered as a text area); can have the number of rows and columns specified as named arguments, such as is multiline(:5rows, :60cols) * is tel / is telephone - a tel input for a phone number * is search - a search input * is time - a time input * is url - a url input * is week - a week input * will select { ... } - a select input, offering the options specified in the block, for example will select { 1..5 }. If the sigil of the attribute is @, then it will render a multi-select box. While self is not available in such a trait, it is passed as the topic of the block, so one can write a method get-options() { ... } and then do will select { .get-options }. Note that currently there is no assistance with handling situations where the options should depend on another form field. * is file - a file upload input; the attribute will be populated with an instance of Cro::HTTP::Body::MultiPartFormData::Part, which has properties filename, body-blob (binary upload) ond body-text (decodes the body-blob to a Str) * is hidden - a hidden input There is no trait for checkboxes; use the Bool type instead. ### Labels, help texts, and placeholders By default, the label for the control is formed by: Taking the attribute name Replacing each - with a space Calling tclc to title case it Use the `is label('Name')` trait in order to explicitly set a label. For text inputs, one can also set a placeholder using the is placeholder('Text') trait. This text is rendered in the textbox prior to the user filling it. Finally, one may use the `is help('...')` trait in order to provide help text. This is displayed beneath the form field. Validation ---------- ```raku our %va = ( text => ( /^ <[A..Za..z0..9\s.,_#-]>+ $/, 'In text, only ".,_-#" punctuation characters are allowed' ), name => ( /^ <[A..Za..z.'-]>+ $/, 'In a name, only ".-\'" punctuation characters are allowed' ), names => ( /^ <[A..Za..z\s.'-]>+ $/, 'In names, only ".-\'" punctuation characters are allowed' ), words => ( /^ <[A..Za..z\s]>+ $/, 'In words, only text characters are allowed' ), notes => ( /^ <[A..Za..z0..9\s.,:;_#!?()%$£-]>+ $/, 'In notes, only ".,:;_-#!?()%$£" punctuation characters are allowed' ), postcode => ( /^ <[A..Za..z0..9\s]>+ $/, 'In postcode, only alphanumeric characters are allowed' ), url => ( /^ <[a..z0..9:/.-]>+ $/, 'Only valid urls are allowed' ), tel => ( /^ <[0..9+()\s#-]>+ $/, 'Only valid tels are allowed' ), email => ( /^ <[a..zA..Z0..9._%+-]>+ '@' <[a..zA..Z0..9.-]>+ '.' <[a..zA..Z]> ** 2..6 $/, 'Only valid email addresses are allowed' ), password => ( ( /^ <[A..Za..z0..9!@#$%^&*()\-_=+{}\[\]|:;"'<>,.?/]> ** 8..* $/ & / <[A..Za..z]> / & /<[0..9]> /), 'Passwords must have minimum 8 characters with at least one letter and one number.' ), ); ``` ### role Form does Cro::WebApp::Form does Taggable {} This role has only private attrs to avoid creating form fields, get/set methods are provided instead. The `%!form-attrs` are the same as `Cro::WebApp::Form`. Air::Form currently supports these attrs: * `submit-button-text` - the text placed on the form submit button * `form-errors-text` - text that comes before form-level errors are rendered Here is an example of customizing the submit button text (ie place this method in your Contact form (or whatever you choose to call it). ```raku method do-form-attrs{ self.form-attrs: {:submit-button-text('Save Contact Info')} } ``` Air::Form code should avoid direct manipulation of the method and class styles detailed at [Cro docs](https://cro.raku.org/docs/reference/cro-webapp-form#Rendering) - instead override the `method styles {}`. Development Roadmap ------------------- The Air::Form module will be extended to perform full CRUD operations on a Red table by the selective grafting of Air::Component features over to Air::Form, for example: * `LOAD` method to load a form with values from a specific table row * `ADD` method to add a new table row with form values provided * `UPDATE` method to update table row with form value modifications * `DELETE` method to delete table row Other potential features include: * a table list view [with row/col filters] * an item list view [with edit/save loop] Technically it is envisaged that ::?CLASS.HOW does Cromponent::MetaCromponentRole; will be brought over from Cromponent with suitable controller methods. If you want to go model XXX does Form does Component, then there is a Taggable use conflict. ### has Str $!form-base optionally specify form url base (with get/set methods) ### method form-name ```raku method form-name() returns Mu ``` get url safe name of class doing Form role ### method form-url ```raku method form-url() returns Str ``` get url (ie base/name) ### has Associative %!form-attrs optional form attrs (with get/set methods) ### method HTML ```raku method HTML() returns Air::Functional::Markup(Any) ``` called when used as a Taggable, returns self.empty ### method HTML ```raku method HTML( Form $form ) returns Air::Functional::Markup(Any) ``` when passed a $form field set, returns populated form ### method retry ```raku method retry( Form $form ) returns Mu ``` return partially complete form ### method finish ```raku method finish( Str $msg ) returns Mu ``` return message (typically used when self.is-valis ### method submit ```raku method submit( &handler ) returns Mu ``` make a route to handle form submit ### method form-styles ```raku method form-styles() returns Mu ``` get form-styles (may be overridden) ### method SCRIPT ```raku method SCRIPT( $suffix = "*" ) returns Mu ``` get form-scripts, pass in a custom $suffix for required labels (may be overridden) AUTHOR ====== Steve Roe <[email protected]> COPYRIGHT AND LICENSE ===================== Copyright(c) 2025 Henley Cloud Consulting Ltd. This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
### ---------------------------------------------------- ### -- Air ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: docs/Air/Functional.md ### ---------------------------------------------------- Air::Functional =============== This raku module is one of the core libraries of the raku **Air** distribution. It exports HTML tags as raku subs that can be composed as functional code within a raku program. It replaces the HTML::Functional module by the same author. SYNOPSIS ======== Here's a regular HTML page: ```html <div class="jumbotron"> <h1>Welcome to Dunder Mifflin!</h1> <p> Dunder Mifflin Inc. (stock symbol <strong>DMI</strong>) is a micro-cap regional paper and office supply distributor with an emphasis on servicing small-business clients. </p> </div> ``` And here is the same page using Air::Functional: ```raku use Air::Functional; div :class<jumbotron>, [ h1 "Welcome to Dunder Mifflin!"; p [ "Dunder Mifflin Inc. (stock symbol "; strong 'DMI'; ") "; q:to/END/; is a micro-cap regional paper and office supply distributor with an emphasis on servicing small-business clients. END ]; ]; ``` DESCRIPTION =========== Key features shown are: * HTML tags are implemented as raku functions: `div, h1, p` and so on * parens `()` are optional in raku function calls * HTML tag attributes are passed as raku named arguments * HTML tag inners (e.g. the Str in `h1`) are passed as raku positional arguments * the raku Pair syntax is used for each attribute i.e. `:name<value>` * multiple `@inners` are passed as a literal Array `[]` – div contains h1 and p * the raku parser looks at functions from the inside out, so `strong` is evaluated before `p`, before `div` and so on * semicolon `;` is used as the Array literal separator to suppress nesting of tags Normally the items in a raku literal Array are comma `,` separated. Raku precedence considers that `div [h1 x, p y];` is equivalent to `div( h1(x, p(y) ) );` … so the p tag is embedded within the h1 tag unless parens are used to clarify. But replace the comma `,` with a semi colon `;` and predisposition to nest is reversed. So `div [h1 x; p y];` is equivalent to `div( h1(x), p(y) )`. Boy that Larry Wall was smart! The raku example also shows the power of the raku **Q-lang** at work: * double quotes `""` interpolate their contents * curlies denote an embedded code block `"{fn x}"` * tilde `~` is for Str concatenation * the heredoc form `q:to/END/;` can be used for verbatim text blocks This module generally returns `Str` values to be string concatenated and included in an HTML content/text response. It also defines a programmatic API for the use of HTML tags for raku functional coding and so is offered as a basis for sister modules that preserve the API, but have a different technical implementation such as a MemoizedDOM. Declare Constants ----------------- All of the HTML tags listed at [https://www.w3schools.com/tags/default.asp](https://www.w3schools.com/tags/default.asp) are covered ... ... of which empty (Singular) tags from [https://www.tutsinsider.com/html/html-empty-elements/](https://www.tutsinsider.com/html/html-empty-elements/) HTML Escape ----------- ### sub escape ```raku sub escape( Str:D(Any):D $s ) returns Str ``` Explicitly HTML::Escape inner text ### multi sub prefix:<^> ```raku multi sub prefix:<^>( Str:D(Any):D $s ) returns Str ``` also a shortcut ^ prefix Tag Rendering ------------- ### role Attr is Str {} - type for Attribute values, use Attr() for coercion ### subset Inner where Str | Tag | Taggable | Markup - type union for Inner elements role Tag [TagType Singular|Regular] {} - basis for Air functions ---------------------------------------------------------------- ### has Associative[Air::Functional::Attr(Any)] %.attrs can be provided with attrs ### has Positional[Air::Functional::Inner] @.inners can be provided with inners ### method new ```raku method new( *@inners, *%attrs ) returns Mu ``` ok to call .new with @inners as Positional ### method HTML ```raku method HTML() returns Mu ``` provides default .HTML method used by tag render ### Low Level API This level is where users want to mess around with the parts of a tag for customizations ### sub attrs ```raku sub attrs( %h ) returns Str ``` convert from raku Pair syntax to HTML tag attributes ### sub opener ```raku sub opener( $tag, *%h ) returns Str ``` open a custom tag ### sub inner ```raku sub inner( @inners ) returns Str ``` convert from an inner list to HTML tag inner string ### sub closer ```raku sub closer( $tag, :$nl ) returns Str ``` close a custom tag (unset :!nl to suppress the newline) ### High Level API This level is for general use from custom tags that behave like regular/singular tags ### sub do-regular-tag ```raku sub do-regular-tag( Str $tag, *@inners, *%h ) returns Air::Functional::Markup(Any) ``` do a regular tag (ie a tag with @inners) ### sub do-singular-tag ```raku sub do-singular-tag( Str $tag, *%h ) returns Air::Functional::Markup(Any) ``` do a singular tag (ie a tag without @inners) Tag Export Options ------------------ Exports all the tags programmatically package Air::Functional::EXPORT::DEFAULT ---------------------------------------- export all HTML tags viz. https://docs.raku.org/language/modules#Exporting_and_selective_importing package Air::Functional::EXPORT::CRO ------------------------------------ use :CRO as package to avoid collisions with Cro::Router names package Air::Functional::EXPORT::BASE ------------------------------------- use :BASE as package to avoid collisions with Cro::Router, Air::Base & Air::Component names NB the HTML description list tags <dl dd dt> are also excluded to avoid conflict with the raku `dd` command AUTHOR ====== Steve Roe <[email protected]> COPYRIGHT AND LICENSE ===================== Copyright(c) 2025 Henley Cloud Consulting Ltd. This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
### ---------------------------------------------------- ### -- Air ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: docs/Air/Base.md ### ---------------------------------------------------- Air::Base ========= This raku module is one of the core libraries of the raku **Air** distribution. It provides a Base library of functional Tags and Components that can be composed into web applications. Air::Base uses Air::Functional for standard HTML tags expressed as raku subs. Air::Base uses Air::Component for scaffolding for library Components. Architecture ------------ Here's a diagram of the various Air parts. (Air::Play is a separate raku module with several examples of Air websites.) +----------------+ | Air::Play | <-- Web App +----------------+ | +--------------------------+ | Air::Play::Site | <-- Site Lib +--------------------------+ / \ +----------------+ +-----------------+ | Air::Base | | Air::Form | <-- Base Lib +----------------+ +----------------+ | \ | +----------------+ +-----------------+ | Air::Component | | Air::Functional | <-- Services +----------------+ +-----------------+ The general idea is that there will a small number of Base libraries, typically provided by raku module authors that package code that implements a specific CSS package and/or site theme. Then, each user of Air - be they an individual or team - can create and selectively load their own Site library modules that extend and use the lower modules. All library Tags and Components can then be composed by the Web App. This facilitates an approach where Air users can curate and share back their own Tag and Component libraries. Therefore it is common to find a Base Lib and a Site Lib used together in the same Web App. In many cases Air::Base will consume a standard HTML tag (eg. `table`), customize and then re-export it with the same sub name. Therefore two export packages `:CRO` and `:BASE` are included to prevent namespace conflict. The current Air::Base package is unashamedly opionated about CSS and is based on [Pico CSS](https://picocss.org). Pico was selected for its semantic tags and very low level of HTML attribute noise. Pico SASS is used to control high level theme variables at the Site level. #### Notes * Higher layers also use Air::Functional and Air::Component services directly * Externally loadable packages such as Air::Theme are on the development backlog * Other CSS modules - Air::Base::TailWind? | Air::Base::Bootstrap? - are anticipated SYNOPSIS ======== The synopsis is split so that each part can be annotated. ### Content ```raku use Air::Functional :BASE; use Air::Base; my %data = :thead[["Planet", "Diameter (km)", "Distance to Sun (AU)", "Orbit (days)"],], :tbody[ ["Mercury", "4,880", "0.39", "88"], ["Venus" , "12,104", "0.72", "225"], ["Earth" , "12,742", "1.00", "365"], ["Mars" , "6,779", "1.52", "687"], ], :tfoot[["Average", "9,126", "0.91", "341"],]; my $Content1 = content [ h3 'Content 1'; table |%data, :class<striped>; ]; my $Content2 = content [ h3 'Content 2'; table |%data; ]; my $Google = external :href<https://google.com>; ``` Key features shown are: * application of the `:BASE` modifier on `use Air::Functional` to avoid namespace conflict * definition of table content as a Hash `%data` of Pairs `:name[[2D Array],]` * assignment of two functional `content` tags and their arguments to vars * assignment of a functional `external` tag with attrs to a var ### Page The template of an Air website (header, nav, logo, footer) is applied by making a custom `page` ... here `index` is set up as the template page. In this SPA example navlinks dynamically update the same page content via HTMX, so index is only used once, but in general multiple instances of the template page can be cookie cuttered. Any number of page template can be set up in this way and can reuse custom Components. ```raku my &index = &page.assuming( title => 'hÅrc', description => 'HTMX, Air, Red, Cro', nav => nav( logo => safe('<a href="/">h<b>&Aring;</b>rc</a>'), items => [:$Content1, :$Content2, :$Google], widgets => [lightdark], ), footer => footer p ['Aloft on ', b 'Åir'], ); ``` Key features shown are: * set the `index` functional tag as a modified Air::Base `page` tag * use of `.assuming` for functional code composition * use of => arrow Pair syntax to set a custom page theme with title, description, nav, footer * use of `nav` functional tag and passing it attrs of the `NavItems` defined * use of `:$Content1` Pair syntax to pass in both nav link text (ie the var name as key) and value * Nav routes are automagically generated and HTMX attrs are used to swap in the content inners * use of `safe` functional tag to suppress HTML escape * use of `lightdark` widget to toggle theme according to system and user preference ### Site ```raku sub SITE is export { site index main $Content1 } ``` Key features shown are: * use of `site` functional tag - that sets up the site Cro routes and Pico SASS theme * `site` takes the `index` page as positional argument * `index` takes a `main` functional tag as positional argument * `main` takes the initial content DESCRIPTION =========== Each feature of Air::Base is set out below: Basic Tags ---------- Air::Functional converts all HTML tags into raku functions. Air::Base overrides a subset of these HTML tags, providing them both as raku roles and functions. The Air::Base tags each embed some code to provide behaviours. This can be simple - `role Script {}` just marks JavaScript as exempt from HTML Escape. Or complex - `role Body {}` has `Header`, `Main` and `Footer` attributes with certain defaults and constructors. Combine these tags in the same way as the overall layout of an HTML webpage. Note that they hide complexity to expose only relevant information to the fore. Override them with your own roles and classes to implement your specific needs. ### role Safe does Tag[Regular] {...} ### method HTML ```raku method HTML() returns Mu ``` avoids HTML escape ### role Script does Tag[Regular] {...} ### method HTML ```raku method HTML() returns Mu ``` no html escape ### role Style does Tag[Regular] {...} ### method HTML ```raku method HTML() returns Mu ``` no html escape ### role Meta does Tag[Singular] {} ### role Title does Tag[Regular] {} ### role Link does Tag[Regular] {} ### role A does Tag[Regular] {...} Page Tags --------- A subset of Air::Functional basic HTML tags, provided as roles, that are slightly adjusted by Air::Base to provide a convenient and opinionated set of defaults for `html`, `head`, `body`, `header`, `nav`, `main` & `footer`. Several of the page tags offer shortcut attrs that are populated up the DOM immediately prior to first use. ### role Head does Tag[Regular] {...} Singleton pattern (ie. same Head for all pages) ### has Title $.title title ### has Meta $.description description ### has Positional[Meta] @.metas metas ### has Positional[Script] @.scripts scripts ### has Positional[Link] @.links links ### has Style $.style style ### method defaults ```raku method defaults() returns Mu ``` set up common defaults (called on instantiation) ### method HTML ```raku method HTML() returns Mu ``` .HTML method calls .HTML on all attrs ### role Header does Tag[Regular] {...} ### has Nav $.nav nav ### has Safe $.tagline tagline ### role Main does Tag[Regular] {...} ### role Footer does Tag[Regular] {...} head ==== 3 role Body does Tag[Regular] {...} ### has Header $.header header ### has Main $.main main ### has Footer $.footer footer ### has Positional[Script] @.scripts scripts ### role Html does Tag[Regular] {...} ### has Head $.head head ### has Body $.body body ### has Associative[Air::Functional::Attr(Any)] %.lang default :lang<en> ### has Associative[Air::Functional::Attr(Any)] %.mode default :data-theme<dark> Semantic Tags ------------- These are re-published with minor adjustments and align with Pico CSS semantic tags ### role Content does Tag[Regular] {...} ### role Section does Tag[Regular] {} ### role Article does Tag[Regular] {} ### role Article does Tag[Regular] {} ### role Time does Tag[Regular] {...} In HTML the time tag is typically of the form < time datetime="2025-03-13" > 13 March, 2025 < /time > . In Air you can just go time(:datetime < 2025-02-27 > ); and raku will auto format and fill out the inner human readable text. Optionally specify mode => [time | datetime], mode => date is default Widgets ------- Active tags that can be used anywhere to provide a nugget of UI behaviour, default should be a short word (or a single item) that can be used in Nav ### role LightDark does Tag[Regular] does Widget {...} ### method HTML ```raku method HTML() returns Mu ``` attribute 'show' may be set to 'icon'(default) or 'buttons' Tools ----- Tools are provided to the site tag to provide a nugget of side-wide behaviour, services method defaults are distributed to all pages on server start ### role Analytics does Tool {...} ### has Provider $.provider may be [Umami] - others TBD ### has Str $.key website ID from provider Site Tags --------- These are the central elements of Air::Base First we set up the NavItems = Internal | External | Content | Page ### role External does Tag[Regular] {...} ### role Internal does Tag[Regular] {...} class Nav --------- Nav does Component in order to support multiple nav instances with distinct NavItem and Widget attributes ### has Str $.hx-target HTMX attributes ### has Safe $.logo logo ### has Positional[NavItem] @.items NavItems ### has Positional[Widget] @.widgets Widgets ### method make-routes ```raku method make-routes() returns Mu ``` makes routes for Content NavItems (eg. SPA links that use HTMX), must be called from within a Cro route block ### method nav-items ```raku method nav-items() returns Mu ``` renders NavItems [subset NavItem of Pair where .value ~~ Internal | External | Content | Page;] ### method HTML ```raku method HTML() returns Mu ``` applies Style and Script for Hamburger reactive menu class Page ---------- Page does Component in order to support multiple page instances with distinct content and attributes. ### has Int $.REFRESH auto refresh browser every n secs in dev't page implements several shortcuts that are populated up the DOM, for example `page :title('My Page")` will go `self.html.head.title = Title.new: $.title with $.title;` ### has Str $.title shortcut self.html.head.title ### has Str $.description shortcut self.html.head.description ### has Nav $.nav shortcut self.html.body.header.nav -or- ### has Header $.header shortcut self.html.body.header [nav wins if both attrs set] ### has Main $.main shortcut self.html.body.main ### has Footer $.footer shortcut self.html.body.footer ### has Positional[Script] @.enqueue enqueue SCRIPT [creates Script tags from registrant .SCRIPT methods to be appended at the end of the body tag] ### has Bool $.styled-aside-on set to True with :styled-aside-on to apply self.html.head.style with right hand aside block ### has Html $.html build page DOM by calling Air tags ### method defaults ```raku method defaults() returns Mu ``` set all provided shortcuts on first use ### multi method new ```raku multi method new( Main $main, *%h ) returns Mu ``` .new positional with main only ### multi method new ```raku multi method new( Main $main, Footer $footer, *%h ) returns Mu ``` .new positional with main & footer only ### multi method new ```raku multi method new( Header $header, Main $main, Footer $footer, *%h ) returns Mu ``` .new positional with header, main & footer only ### method HTML ```raku method HTML() returns Mu ``` issue page DOM class Site ---------- Site is a holder for pages, performs setup of Cro routes and offers high level controls for style via Pico SASS. ### has Positional[Page] @.pages Page holder -or- ### has Page $.index index Page ( otherwise $!index = @!pages[0] ) ### has Positional @.register Register for route setup; default = [Nav.new] ### has Bool $.scss use :!scss to disable SASS compiler run ### has Str $.theme-color pick from: amber azure blue cyan fuchsia green indigo jade lime orange pink pumpkin purple red violet yellow (pico theme) ### has Str $.bold-color pick from:- aqua black blue fuchsia gray green lime maroon navy olive purple red silver teal white yellow (basic css) ### multi method new ```raku multi method new( Page $index, *%h ) returns Mu ``` .new positional with index only Pico Tags --------- The Air roadmap is to provide a full set of pre-styled tags as defined in the Pico [docs](https://picocss.com/docs). Did we say that Air::Base implements Pico CSS? ### role Table does Tag Attrs thead, tbody and tfoot can each be a 2D Array [[values],] that iterates to row and columns or a Tag|Component - if the latter then they are just rendered via their .HTML method. This allow for multi-row thead and tfoot. Table applies col and row header tags as required for Pico styles. Attrs provided as Pairs via tbody are extracted and applied. This is needed for :id<target> where HTMX is targetting the table body. ### has Mu $.tbody default = [] is provided ### has Mu $.thead optional ### has Mu $.tfoot optional ### has Mu $.class class for table ### method new ```raku method new( *@tbody, *%h ) returns Mu ``` .new positional takes tbody [[]] ### role Grid does Tag ### has Positional @.items list of items to populate grid, each item is wrapped in a span tag ### method new ```raku method new( *@items, *%h ) returns Mu ``` .new positional takes @items package EXPORT::DEFAULT ----------------------- put in all the @components as functions sub name( * @a, * %h) {Name.new(|@a,|%h)} AUTHOR ====== Steve Roe <[email protected]> COPYRIGHT AND LICENSE ===================== Copyright(c) 2025 Henley Cloud Consulting Ltd. This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
### ---------------------------------------------------- ### -- Air ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: docs/Air/Component.md ### ---------------------------------------------------- Air::Component ============== This raku module is one of the core libraries of the raku **Air** distribution. It is a scaffold to build dynamic, reusable web components. SYNOPSIS ======== The synopsis is split so that each part can be annotated. First, we import the Air core libraries. ```raku use Air::Functional :BASE; # import all HTML tags as raku subs use Air::Base; # import Base components (site, page, nav...) use Air::Component; ``` ### HTMX functions We prepare some custom HTMX actions for our Todo component. This declutters `class Todo` and keeps our `hx-attrs` tidy and local. ```raku role HxTodo { method hx-create(--> Hash()) { :hx-post("todo"), :hx-target<table>, :hx-swap<beforeend>, } method hx-delete(--> Hash()) { :hx-delete($.url-id), :hx-confirm<Are you sure?>, :hx-target<closest tr>, :hx-swap<delete>, } method hx-toggle(--> Hash()) { :hx-get("$.url-id/toggle"), :hx-target<closest tr>, :hx-swap<outerHTML>, } } ``` Key features are: * these are packaged in a raku role which is then consumed by `class Todo` * method names `hx-toggle` echo standard HTMX attributes such as `hx-get` * return values are coerced to a raku `Hash` containing HTMX attrs ### class Todo The core of our synopsis. It `does Component` to bring in the scaffolding. The general idea is that a raku class implements a web Component, multiple instances of the Component are represented by objects of the class and the methods of the class represent actions that can be performed on the Component in the browser. ```raku class Todo does Component { also does HxTodo; has Bool $.checked is rw = False; has Str $.text; method toggle is controller { $!checked = !$!checked; respond self; } multi method HTML { tr td( input :type<checkbox>, |$.hx-toggle, :$!checked ), td( $!checked ?? del $!text !! $!text), td( button :type<submit>, |$.hx-delete, :style<width:50px>, '-'), } } ``` Key features of `class Todo` are: * Todo objects have state `$.checked` and `$.text` with suitable defaults * `method toggle` takes the trait `is controller` - this makes a corresponding Cro route * `method toggle` adjusts the state and ends with the `respond` sub (which calls `.HTML`) * `class Todo` provides a `multi method HTML` which uses functional HTML tags `tr`, `td` and so on * we call our HxTodo methods eg `|$.hx-toggle` with the *call self* shorthand `$.` * the Hash is flattened into individual attrs with `|` * a smattering of style (or any HTML attr) can be added as needed The result is a concise, legible and easy-to-maintain component implementation. ### sub SITE Now, we can make a website as follows: ```raku my &index = &page.assuming( title => 'hÅrc', description => 'HTMX, Air, Red, Cro', footer => footer p ['Aloft on ', b 'Åir'], ); my @todos = do for <one two> -> $text { Todo.new: :$text }; sub SITE is export { site :register(@todos), index main [ h3 'Todos'; table @todos; form |Todo.hx-create, [ input :name<text>; button :type<submit>, '+'; ]; ] } ``` Key features of `sub SITE` are: * we make our own function `&index` that * (i) uses `.assuming` to preset some attributes (title, description, footer) and * (ii) then calls the `page` function provided by Air::Base * we set up our list of Todo components calling `Todo.new` * we use the Air::Base `site` function to make our website * the call chain `site(index(main(...))` then makes our website * `site` is passed `:register(@todos)` to make the component Cro routes Run Cro service.raku -------------------- Component automagically creates some cro routes for Todo when we start our website... > raku -Ilib service.raku theme-color=green bold-color=red adding GET todo/<#> adding POST todo adding DELETE todo/<#> adding PUT todo/<#> adding GET todo/<#>/toggle adding GET page/<#> Build time 0.67 sec Listening at http://0.0.0.0:3000 DESCRIPTION =========== The rationale for Air Components is rooted in the powerful raku code composition capabilities. It builds on the notion of Locality of Behaviour (aka [LOB](https://htmx.org/essays/locality-of-behaviour/)) and the intent is that a Component can represent and render every aspect of a piece of website behaviour. * Content * Layout * Theme * Data Model * Actions As Air evolves, it is expected that common code idioms will emerge to make each dimensions independent (ie HTML, CSS and JS relating to Air::Theme::Font would be local, and distinct from HTML, CSS and JS for Air::Theme::Nav). Air is an integral part of the hArc stack (HTMX, Air, Red, Cro). The Synopsis shows how a Component can externalize and consume HTMX attributes for method actions, perhaps even a set of Air::HTMX libraries can be anticipated. One implication of this is that each Component can use the [hx-swap-oob](https://htmx.org/attributes/hx-swap-oob/) attribute to deliver Content, Style and Script anywhere in the DOM (except the `html` tag). An instance of this could be a blog website where a common Red `model Post` could be harnessed to populate each blog post, a total page count calculation for paging and a post summary list in an `aside`. In the Synopsis, both raku class inheritance and role composition provide coding dimensions to greatly improve code clarity and evolution. While simple samples are shown, raku has comprehensive encapsulation and type capabilities in a friendly and approachable language. Raku is a multi-paradigm language for both Functional and Object Oriented (OO) coding styles. OO is a widely understood approach to code and state encapsulation - suitable for code evolution across many aspects - and is well suited for Component implementations. Functional is a surprisingly good paradigm for embedding HTML standard and custom tags into general raku source code. The example below illustrates the power of Functional tags inline when used in more intricate stanzas. While this kind of logic can in theory be delivered in a web app using web template files, as the author of the Cro Template language [comments](https://cro.raku.org/docs/reference/cro-webapp-template-syntax#Conditionals) *Those wishing for more are encouraged to consider writing their logic outside of the template.* ```raku method nav-items { do for @.items.map: *.kv -> ($name, $target) { given $target { when * ~~ External | Internal { $target.label = $name; li $target.HTML } when * ~~ Content { li a(:hx-get("$.name/$.serial/" ~ $name), safe $name) } when * ~~ Page { li a(:href("/{.name}/{.serial}"), safe $name) } } } } multi method HTML { self.style.HTML ~ ( nav [ { ul li :class<logo>, :href</>, $.logo } with $.logo; button( :class<hamburger>, :serial<hamburger>, safe '&#9776;' ); ul( :$!hx-target, :class<nav-links>, self.nav-items, do for @.wserialgets { li .HTML }, ); ul( :$!hx-target, :class<menu>, :serial<menu>, self.nav-items, ); ] ) ~ self.script.HTML } ``` From the implementation of the Air::Base::Nav component. TIPS & TRICKS ============= When writing components: * custom `multi method HTML` inners must be explicitly rendered with .HTML or wrapped in a tag eg. `div` since being passed as AN inner will call `render-tag` which will, in turn, call `.HTML` attributes and methods shared between Component and Component::Red roles ### has Str $!base optional attr to specify url base ### method url-name ```raku method url-name() returns Mu ``` get url safe name of class doing Component role ### method url ```raku method url() returns Str ``` get url (ie base/name) ### method url-path ```raku method url-path() returns Str ``` get url-id (ie base/name/id) ### method html-id ```raku method html-id() returns Str ``` get html-id (ie url-name-id), intended for HTML id attr ### method Str ```raku method Str() returns Mu ``` In general Cromponent::MetaCromponentRole calls .Str on a Cromponent when returning it this method substitutes .HTML for .Str Component is for non-Red classes ### has UInt $!id assigns and tracks instance ids ### method holder ```raku method holder() returns Hash ``` populates an instance holder [class method], may be overridden for external instance holder ### method all ```raku method all() returns Mu ``` get all instances in holder ### method make-methods ```raku method make-methods() returns Mu ``` adapt component to perform LOAD, UPDATE, DELETE, ADD action(s) called by role Site Component::Red is for Red models ### method make-methods ```raku method make-methods() returns Mu ``` adapt component to perform LOAD, UPDATE, DELETE, ADD action(s) called by role Site AUTHOR ====== Steve Roe <[email protected]> The `Air::Component` module integrates with the Cromponent module, author Fernando Corrêa de Oliveira <[email protected]>, however unlike Cromponent this module does not use Cro Templates. COPYRIGHT AND LICENSE ===================== Copyright(c) 2025 Henley Cloud Consulting Ltd. This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
### ---------------------------------------------------- ### -- Air ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: t/02-body.rakutest ### ---------------------------------------------------- use Test; use Air::Functional; plan 1; #had to fine tune the stock symbol& END newline to make test work (editor trims trailing spaces) my $main = main [ div :class<jumbotron>, [ h1 "Welcome to Dunder Mifflin!"; #use ; to stop <h1> slurping <p> p [ "Dunder Mifflin Inc. (stock symbol"; strong 'DMI'; ") "; q:to/END/; is a micro-cap regional paper and office supply distributor with an emphasis on servicing small-business clients. END ]; ]; p :hx-get<https://v2.jokeapi.dev/joke/Any?format=txt&safe-mode>, "Click Me"; p '<div class="content">Escaped & Raw HTML!</div>'; ]; my $expect = q:to/END/; <main> <div class="jumbotron"> <h1>Welcome to Dunder Mifflin!</h1> <p>Dunder Mifflin Inc. (stock symbol <strong>DMI</strong>) is a micro-cap regional paper and office supply distributor with an emphasis on servicing small-business clients. </p> </div> <p hx-get="https://v2.jokeapi.dev/joke/Any?format=txt&safe-mode">Click Me</p> <p>&lt;div class=&quot;content&quot;&gt;Escaped &amp; Raw HTML!&lt;/div&gt;</p> </main> END is $main, $expect.chomp, 'all-body'; done-testing;
### ---------------------------------------------------- ### -- Air ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: t/04-table.rakutest ### ---------------------------------------------------- use Test; # Normalize and compare ignoring order differences sub normalize(Str $html) { return $html.trans(' ' => '').comb.sort.join; } plan 1; use Air::Functional :BASE; use Air::Base; my %data = :thead[["Planet", "Hexameter (km)", "Distance to Sun (AU)", "Orbit (days)"],], :tbody[["Mercury", "4,880", "0.39", "88"], ["Venus" , "12,104", "0.72", "225"], ["Earth" , "12,742", "1.00", "365"], ["Mars" , "6,779", "1.52", "687"],], :tfoot[["Average", "9,126", "0.91", "341"],]; my $html = div [ h3 'Table'; table |%data; ]; my $expect = q:to/END/; <div> <h3>Table</h3> <table> <thead> <tr> <th scope="col">Planet</th> <th scope="col">Hexameter (km)</th> <th scope="col">Distance to Sun (AU)</th> <th scope="col">Orbit (days)</th> </tr></thead> <tbody> <tr> <th scope="row">Mercury</th> <td>4,880</td> <td>0.39</td> <td>88</td> </tr> <tr> <th scope="row">Venus</th> <td>12,104</td> <td>0.72</td> <td>225</td> </tr> <tr> <th scope="row">Earth</th> <td>12,742</td> <td>1.00</td> <td>365</td> </tr> <tr> <th scope="row">Mars</th> <td>6,779</td> <td>1.52</td> <td>687</td> </tr> </tbody> <tfoot> <tr> <th scope="row">Average</th> <td>9,126</td> <td>0.91</td> <td>341</td> </tr></tfoot> </table> </div> END is $html.&normalize, $expect.&normalize, 'all-table'; done-testing;
### ---------------------------------------------------- ### -- Air ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: t/01-basic.rakutest ### ---------------------------------------------------- use Test; use Air::Functional; is h1('text', :class<jumbotron>), "\n<h1 class=\"jumbotron\">text</h1>", 'h1'; is h1(:class<doobie>), "\n<h1 class=\"doobie\"></h1>", 'empty'; is div(:class<jumbotron>, 'xx'), "\n<div class=\"jumbotron\">xx</div>", 'regular'; is hr, "\n<hr />", 'singular'; #Str inners are auto escaped my $tainted = '<div class="content">Escaped & Raw HTML!</div>'; my $expect = "\n<p>\&lt;div class=\&quot;content\&quot;\&gt;Escaped \&amp; Raw HTML!\&lt;/div\&gt;</p>"; is p( $tainted ), $expect , 'escape'; done-testing;
### ---------------------------------------------------- ### -- Air ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: t/03-page.rakutest ### ---------------------------------------------------- use Test; # Normalize and compare ignoring order differences sub normalize(Str $html) { return $html.trans(' ' => '').comb.sort.join; } plan 1; use Air::Functional :BASE; use Air::Base; my $main = Main.new: p 'Hello World!'; my $page = Page.new: title => "Raku HTMX", :$main; # main => Main.new: p 'Hello World!'; #iamerejh $page.html.head.style = Style.new: 'p {color: blue;}'; my $expect = q:to/END/; <!doctype html> <html data-theme="dark" lang="en"> <head> <title>Raku HTMX</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <script crossorigin="anonymous" integrity="sha384-xcuj3WpfgjlKF+FXhSQFQ0ZNr39ln+hwjN3npfM9VBnUskLolQAcN80McRIVOPuO" src="https://unpkg.com/[email protected]"></script> <link rel="stylesheet" href="/css/styles.css" /> <link type="image/x-icon" href="/img/favicon.ico" rel="icon" /> <style>p {color: blue;}</style> </head> <body> <header class="container"></header> <main class="container"> <p>Hello World!</p></main> <footer class="container"></footer></body> </html> END is $page.HTML.&normalize, $expect.&normalize, 'all-page'; done-testing;
### ---------------------------------------------------- ### -- Air ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: lib/Air.rakumod ### ---------------------------------------------------- use v6.d; unit module Air; =begin pod =head1 Air Breathing life into the raku B<hArc stack> (HTMX, Air, Red, Cro). B<Air> aims to be the purest possible expression of L<HTMX|https://htmx.org>. B<hArc> websites are written in functional code. This puts the emphasis firmly onto the content and layout of the site, rather than boilerplate markup that can often obscure the intention. B<Air> is basically a set of libraries that produce HTML code and serve it using Cro. The result is a concise, legible and easy-to-maintain website codebase. =head1 SYNOPSIS =begin code :lang<raku> #!/usr/bin/env raku use Air::Functional :BASE; use Air::Base; my &index = &page.assuming( #:REFRESH(1), title => 'hÅrc', description => 'HTMX, Air, Red, Cro', footer => footer p ['Aloft on ', b safe '&Aring;ir'], ); my &planets = &table.assuming( :thead[["Planet", "Diameter (km)", "Distance to Sun (AU)", "Orbit (days)"],], :tbody[["Mercury", "4,880", "0.39", "88"], ["Venus" , "12,104", "0.72", "225"], ["Earth" , "12,742", "1.00", "365"], ["Mars" , "6,779", "1.52", "687"],], :tfoot[["Average", "9,126", "0.91", "341"],], ); sub SITE is export { site #:bold-color<blue>, index main div [ h3 'Planetary Table'; planets; ] } =end code =head1 GETTING STARTED Install raku - eg. from L<rakubrew|https://rakubrew.org>, then: =begin code Install Air, Cro & Red - zef install --/test cro - zef install Red --exclude="pq:ver<5>" - zef install Air Run and view some examples - git clone https://github.com/librasteve/Air-Play.git && cd Air-Play - export WEBSITE_HOST="0.0.0.0" && export WEBSITE_PORT="3000" - raku -Ilib service.raku - browse to http://localhost:3000 =end code Cro has many other options as documented at L<Cro|https://cro.raku.org> for deployment to a production server. =head1 DESCRIPTION Air is not a framework, but a set of libraries. Full control over the application loop is retained by the coder. Air does not provide an HTML templating language, instead each HTML tag is written as a subroutine call where the argument is a list of C<@inners> and attributes are passed via the raku Pair syntax C<:name<value>>. L<Cro templates|https://cro.raku.org/docs/reference/cro-webapp-template-syntax> are great if you would rather take the template approach. Reusability is promoted by the structure of the libraries - individuals and teams can create and install your own libraries to encapsulate design themes, re-usable web components and best practice. Air is comprised of four core libraries: =item Air::Functional - wraps HTML tags as functions =item Air::Base - a set of handy prebuilt components =item Air::Component - make your own components =item Air::Form - declarative forms B<L<Air::Play|https://raku.land/zef:librasteve/Air::Play>> is a companion raku module with various B<Air> website examples. The Air documentation is at L<https://librasteve.github.io/Air> =head1 TIPS & TRICKS =item When debugging, use the raku C<note> sub to out put debuggin info to stderr (ie in the Cro Log stream) =item When passing a 2D Array to a tag function, make sure that there is a trailing comma C<:tbody[["Mercury", "4,880", "0.39", "88"],]> =item An error message like I<insufficient arguments> is often caused by separating two tag functions with a comma C<,> instead of a semicolon C<;> =item In development set CRO_DEV=1 in the L<environment|https://cro.services/docs/reference/cro-webapp-template#Template_auto-reload> =head1 AUTHOR Steve Roe <[email protected]> The `Air::Component` module provided is based on an early version of the raku `Cromponent` module, author Fernando Corrêa de Oliveira <[email protected]>, however unlike Cromponent this module does not use Cro Templates. =head1 COPYRIGHT AND LICENSE Copyright(c) 2025 Henley Cloud Consulting Ltd. This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. =end pod
### ---------------------------------------------------- ### -- Air ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: lib/Air/Base.rakumod ### ---------------------------------------------------- ### -- Chunk 1 of 2 =begin pod =head1 Air::Base This raku module is one of the core libraries of the raku B<Air> distribution. It provides a Base library of functional Tags and Components that can be composed into web applications. Air::Base uses Air::Functional for standard HTML tags expressed as raku subs. Air::Base uses Air::Component for scaffolding for library Components. =head2 Architecture Here's a diagram of the various Air parts. (Air::Play is a separate raku module with several examples of Air websites.) =begin code +----------------+ | Air::Play | <-- Web App +----------------+ | +--------------------------+ | Air::Play::Site | <-- Site Lib +--------------------------+ / \ +----------------+ +-----------------+ | Air::Base | | Air::Form | <-- Base Lib +----------------+ +----------------+ | \ | +----------------+ +-----------------+ | Air::Component | | Air::Functional | <-- Services +----------------+ +-----------------+ =end code =para The general idea is that there will a small number of Base libraries, typically provided by raku module authors that package code that implements a specific CSS package and/or site theme. Then, each user of Air - be they an individual or team - can create and selectively load their own Site library modules that extend and use the lower modules. All library Tags and Components can then be composed by the Web App. =para This facilitates an approach where Air users can curate and share back their own Tag and Component libraries. Therefore it is common to find a Base Lib and a Site Lib used together in the same Web App. =para In many cases Air::Base will consume a standard HTML tag (eg. C<table>), customize and then re-export it with the same sub name. Therefore two export packages C<:CRO> and C<:BASE> are included to prevent namespace conflict. =para The current Air::Base package is unashamedly opionated about CSS and is based on L<Pico CSS|https://picocss.org>. Pico was selected for its semantic tags and very low level of HTML attribute noise. Pico SASS is used to control high level theme variables at the Site level. =head4 Notes =item Higher layers also use Air::Functional and Air::Component services directly =item Externally loadable packages such as Air::Theme are on the development backlog =item Other CSS modules - Air::Base::TailWind? | Air::Base::Bootstrap? - are anticipated =head1 SYNOPSIS The synopsis is split so that each part can be annotated. =head3 Content =begin code :lang<raku> use Air::Functional :BASE; use Air::Base; my %data = :thead[["Planet", "Diameter (km)", "Distance to Sun (AU)", "Orbit (days)"],], :tbody[ ["Mercury", "4,880", "0.39", "88"], ["Venus" , "12,104", "0.72", "225"], ["Earth" , "12,742", "1.00", "365"], ["Mars" , "6,779", "1.52", "687"], ], :tfoot[["Average", "9,126", "0.91", "341"],]; my $Content1 = content [ h3 'Content 1'; table |%data, :class<striped>; ]; my $Content2 = content [ h3 'Content 2'; table |%data; ]; my $Google = external :href<https://google.com>; =end code Key features shown are: =item application of the C<:BASE> modifier on C<use Air::Functional> to avoid namespace conflict =item definition of table content as a Hash C<%data> of Pairs C<:name[[2D Array],]> =item assignment of two functional C<content> tags and their arguments to vars =item assignment of a functional C<external> tag with attrs to a var =head3 Page =para The template of an Air website (header, nav, logo, footer) is applied by making a custom C<page> ... here C<index> is set up as the template page. In this SPA example navlinks dynamically update the same page content via HTMX, so index is only used once, but in general multiple instances of the template page can be cookie cuttered. Any number of page template can be set up in this way and can reuse custom Components. =begin code :lang<raku> my &index = &page.assuming( title => 'hÅrc', description => 'HTMX, Air, Red, Cro', nav => nav( logo => safe('<a href="/">h<b>&Aring;</b>rc</a>'), items => [:$Content1, :$Content2, :$Google], widgets => [lightdark], ), footer => footer p ['Aloft on ', b 'Åir'], ); =end code Key features shown are: =item set the C<index> functional tag as a modified Air::Base C<page> tag =item use of C<.assuming> for functional code composition =item use of => arrow Pair syntax to set a custom page theme with title, description, nav, footer =item use of C<nav> functional tag and passing it attrs of the C<NavItems> defined =item use of C<:$Content1> Pair syntax to pass in both nav link text (ie the var name as key) and value =item Nav routes are automagically generated and HTMX attrs are used to swap in the content inners =item use of C<safe> functional tag to suppress HTML escape =item use of C<lightdark> widget to toggle theme according to system and user preference =head3 Site =begin code :lang<raku> sub SITE is export { site index main $Content1 } =end code Key features shown are: =item use of C<site> functional tag - that sets up the site Cro routes and Pico SASS theme =item C<site> takes the C<index> page as positional argument =item C<index> takes a C<main> functional tag as positional argument =item C<main> takes the initial content =head1 DESCRIPTION Each feature of Air::Base is set out below: =end pod # TODO items #role Theme {...} use Air::Functional; use Air::Component; use Air::Form; my @functions = <Safe Site Page A External Internal Content Section Article Aside Time Nav LightDark Body Header Main Footer Table Grid Flexbox>; =head2 Basic Tags =para Air::Functional converts all HTML tags into raku functions. Air::Base overrides a subset of these HTML tags, providing them both as raku roles and functions. =para The Air::Base tags each embed some code to provide behaviours. This can be simple - C<role Script {}> just marks JavaScript as exempt from HTML Escape. Or complex - C<role Body {}> has C<Header>, C<Main> and C<Footer> attributes with certain defaults and constructors. =para Combine these tags in the same way as the overall layout of an HTML webpage. Note that they hide complexity to expose only relevant information to the fore. Override them with your own roles and classes to implement your specific needs. class Nav { ... } class Page { ... } =head3 role Safe does Tag[Regular] {...} role Safe does Tag[Regular] { #| avoids HTML escape multi method HTML { @.inners.join } } =head3 role Script does Tag[Regular] {...} role Script does Tag[Regular] { #| no html escape multi method HTML { opener($.name, |%.attrs) ~ ( @.inners.first // '' ) ~ closer($.name) ~ "\n" } } =head3 role Style does Tag[Regular] {...} role Style does Tag[Regular] { #| no html escape multi method HTML { opener($.name, |%.attrs) ~ @.inners.first ~ closer($.name) ~ "\n" } } =head3 role Meta does Tag[Singular] {} role Meta does Tag[Singular] {} =head3 role Title does Tag[Regular] {} role Title does Tag[Regular] {} =head3 role Link does Tag[Regular] {} role Link does Tag[Singular] {} =head3 role A does Tag[Regular] {...} role A does Tag[Regular] { multi method HTML { my %attrs = |%.attrs, :target<_blank>; do-regular-tag( $.name, @.inners, |%attrs ) } } =head2 Page Tags =para A subset of Air::Functional basic HTML tags, provided as roles, that are slightly adjusted by Air::Base to provide a convenient and opinionated set of defaults for C<html>, C<head>, C<body>, C<header>, C<nav>, C<main> & C<footer>. Several of the page tags offer shortcut attrs that are populated up the DOM immediately prior to first use. =head3 role Head does Tag[Regular] {...} role Head does Tag[Regular] { =para Singleton pattern (ie. same Head for all pages) my Head $instance; multi method new {note "Please use Head.instance rather than Head.new!\n"; self.instance} submethod instance { unless $instance { $instance = Head.bless; $instance.defaults; }; $instance; } #| title has Title $.title is rw; #| description has Meta $.description is rw; #| metas has Meta @.metas; #| scripts has Script @.scripts; #| links has Link @.links; #| style has Style $.style is rw; #| set up common defaults (called on instantiation) method defaults { self.metas.append: Meta.new: :charset<utf-8>; self.metas.append: Meta.new: :name<viewport>, :content('width=device-width, initial-scale=1'); self.links.append: Link.new: :rel<stylesheet>, :href</css/styles.css>; self.links.append: Link.new: :rel<icon>, :href</img/favicon.ico>, :type<image/x-icon>; self.scripts.append: Script.new: :src<https://unpkg.com/[email protected]>, :crossorigin<anonymous>, :integrity<sha384-xcuj3WpfgjlKF+FXhSQFQ0ZNr39ln+hwjN3npfM9VBnUskLolQAcN80McRIVOPuO>; } #| .HTML method calls .HTML on all attrs multi method HTML { opener($.name, |%.attrs) ~ "{ .HTML with $!title }" ~ "{ .HTML with $!description }" ~ "{(.HTML for @!metas ).join }" ~ "{(.HTML for @!scripts ).join }" ~ "{(.HTML for @!links ).join }" ~ "{ .HTML with $!style }" ~ closer($.name) ~ "\n" } } =head3 role Header does Tag[Regular] {...} role Header does Tag[Regular] { #| nav has Nav $.nav is rw; #| tagline has Safe $.tagline; multi method HTML { my %attrs = |%.attrs, :class<container>; my @inners = |@.inners, $.nav // Empty, $.tagline // Empty; do-regular-tag( $.name, @inners, |%attrs ) } } =head3 role Main does Tag[Regular] {...} role Main does Tag[Regular] { multi method HTML { my %attrs = |%.attrs, :class<container>; do-regular-tag( $.name, @.inners, |%attrs ) } } =head3 role Footer does Tag[Regular] {...} role Footer does Tag[Regular] { multi method HTML { my %attrs = |%.attrs, :class<container>; do-regular-tag( $.name, @.inners, |%attrs ) } } =head 3 role Body does Tag[Regular] {...} role Body does Tag[Regular] { #| header has Header $.header is rw .= new; #| main has Main $.main is rw .= new; #| footer has Footer $.footer is rw .= new; #| scripts has Script @.scripts; multi method HTML { opener($.name, |%.attrs) ~ $!header.HTML ~ $!main.HTML ~ $!footer.HTML ~ @!scripts.map(*.HTML).join ~ closer($.name) ~ "\n" } } =head3 role Html does Tag[Regular] {...} role Html does Tag[Regular] { my $loaded = 0; #| head has Head $.head .= instance; #| body has Body $.body is rw .= new; #| default :lang<en> has Attr() %.lang is rw = :lang<en>; #| default :data-theme<dark> has Attr() %.mode is rw = :data-theme<dark>; method defaults { self.attrs = |%!lang, |%!mode, |%.attrs; } multi method HTML { self.defaults unless $loaded++; opener($.name, |%.attrs) ~ $!head.HTML ~ $!body.HTML ~ closer($.name) ~ "\n" } } =head2 Semantic Tags =para These are re-published with minor adjustments and align with Pico CSS semantic tags =head3 role Content does Tag[Regular] {...} role Content does Tag[Regular] { multi method HTML { my %attrs = |%.attrs, :id<content>; do-regular-tag( $.name, @.inners, |%attrs ) } } =head3 role Section does Tag[Regular] {} role Section does Tag[Regular] {} =head3 role Article does Tag[Regular] {} role Article does Tag[Regular] {} =head3 role Article does Tag[Regular] {} # TODO load aside style via HTMX OOB role Aside does Tag[Regular] {} =head3 role Time does Tag[Regular] {...} =para In HTML the time tag is typically of the form E<lt> time datetime="2025-03-13" E<gt> 13 March, 2025 E<lt> /time E<gt> . In Air you can just go time(:datetime E<lt> 2025-02-27 E<gt> ); and raku will auto format and fill out the inner human readable text. role Time does Tag[Regular] { use DateTime::Format; multi method HTML { my $dt = DateTime.new(%.attrs<datetime>); =para Optionally specify mode => [time | datetime], mode => date is default sub inner { given %.attrs<mode> { when 'time' { strftime('%l:%M%P', $dt) } when 'datetime' { strftime('%l:%M%P on %B %d, %Y', $dt) } default { strftime('%B %d, %Y', $dt) } } } do-regular-tag( $.name, [inner], |%.attrs ) } } =head2 Widgets =para Active tags that can be used anywhere to provide a nugget of UI behaviour, default should be a short word (or a single item) that can be used in Nav role Widget {} =head3 role LightDark does Tag[Regular] does Widget {...} role LightDark does Tag does Widget { #| attribute 'show' may be set to 'icon'(default) or 'buttons' multi method HTML { my $show = self.attrs<show> // 'icon'; given $show { when 'buttons' { Safe.new: self.buttons } when 'icon' { Safe.new: self.icon } } } method buttons { Q| <div role="group"> <button class="contrast" id="themeToggle">Toggle</button> <button id="themeLight" >Light</button> <button class="secondary" id="themeDark" >Dark</button> <button class="outline" id="themeSystem">System</button> </div> <script> | ~ self.common ~ Q| // Attach to a button click document.getElementById("themeToggle").addEventListener("click", () => setTheme("toggle")); document.getElementById("themeDark").addEventListener("click", () => setTheme("dark")); document.getElementById("themeLight").addEventListener("click", () => setTheme("light")); document.getElementById("themeSystem").addEventListener("click", () => setTheme("system")); </script> |; } method icon { Q| <a style="font-variant-emoji: text" id ="sunIcon">&#9728;</a> <a style="font-variant-emoji: text" id ="moonIcon">&#9790;</a> <script> // Function to show/hide icons function updateIcons(theme) { if (theme === "dark") { sunIcon.style.display = "none"; // Hide sun moonIcon.style.display = "block"; // Show moon } else { sunIcon.style.display = "block"; // Show sun moonIcon.style.display = "none"; // Hide moon } } | ~ self.common ~ Q| const sunIcon = document.getElementById("sunIcon"); const moonIcon = document.getElementById("moonIcon"); // Attach to a icon click document.getElementById("sunIcon").addEventListener("click", () => setTheme("dark")); document.getElementById("moonIcon").addEventListener("click", () => setTheme("light")); </script> |; } method common { Q:to/END/ function setTheme(mode) { const htmlElement = document.documentElement; let newTheme = mode; if (mode === "toggle") { const currentTheme = htmlElement.getAttribute("data-theme") || "light"; newTheme = currentTheme === "dark" ? "light" : "dark"; } else if (mode === "system") { newTheme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"; } htmlElement.setAttribute("data-theme", newTheme); localStorage.setItem("theme", newTheme); // Save theme to localStorage updateIcons(newTheme); } // Load saved theme on page load document.addEventListener("DOMContentLoaded", () => { const savedTheme = localStorage.getItem("theme") || "dark"; //default to dark const systemPrefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches; const initialTheme = savedTheme || (systemPrefersDark ? "dark" : "light"); updateIcons(initialTheme); document.documentElement.setAttribute("data-theme", initialTheme); }); // Listen for system dark mode changes and update the theme dynamically window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => { setTheme("system"); // Follow system setting }); END } } =head2 Tools =para Tools are provided to the site tag to provide a nugget of side-wide behaviour, services method defaults are distributed to all pages on server start role Tool {} =head3 role Analytics does Tool {...} enum Provider is export <Umami>; role Analytics does Tool { #| may be [Umami] - others TBD has Provider $.provider; #| website ID from provider has Str $.key; multi method defaults($page) { given $!provider { when Umami { $page.html.head.scripts.append: Script.new: :defer, :src<https://cloud.umami.is/script.js>, :data-website-id($!key); } } } } =head2 Site Tags =para These are the central elements of Air::Base =para First we set up the NavItems = Internal | External | Content | Page =head3 role External does Tag[Regular] {...} role External does Tag { has Str $.label is rw = ''; has %.others = {:target<_blank>, :rel<noopener noreferrer>}; multi method HTML { my %attrs = |self.others, |%.attrs; do-regular-tag( 'a', [$.label], |%attrs ) } } =head3 role Internal does Tag[Regular] {...} role Internal does Tag { has Str $.label is rw = ''; multi method HTML { do-regular-tag( 'a', [$.label], |%.attrs ) } } subset NavItem of Pair where .value ~~ Internal | External | Content | Page; #| Nav does Component in order to support multiple nav instances #| with distinct NavItem and Widget attributes class Nav does Component { #| HTMX attributes has Str $.hx-target = '#content'; has Str $.hx-swap = 'outerHTML'; #| logo has Markup $.logo; #| NavItems has NavItem @.items; #| Widgets has Widget @.widgets; multi method new(*@items, *%h) { self.bless: :@items, |%h; } #| makes routes for Content NavItems (eg. SPA links that use HTMX), must be called from within a Cro route block method make-routes() { do for self.items.map: *.kv -> ($name, $target) { given $target { when * ~~ Content { my &new-method = method {$target.?HTML}; trait_mod:<is>(&new-method, :controller{:$name, :returns-html}); self.^add_method($name, &new-method); } } } } #| renders NavItems [subset NavItem of Pair where .value ~~ Internal | External | Content | Page;] method nav-items { do for @.items.map: *.kv -> ($name, $target) { given $target { when External | Internal { $target.label = $name; li $target.HTML } when Content { li a(:hx-get("$.url-path/$name"), Safe.new: $name) } when Page { li a(:href("/{.url-name}/{.id}"), Safe.new: $name) } } } } #| applies Style and Script for Hamburger reactive menu method HTML { self.style.HTML ~ ( nav [ { ul li :class<logo>, :href</>, $.logo } with $.logo; button( :class<hamburger>, :id<hamburger>, Safe.new: '&#9776;' ); #regular menu ul( :$!hx-target, :$!hx-swap, :class<nav-links>, self.nav-items, do for @.widgets { li .HTML }, ); #hamburger menu ul( :$!hx-target, :$!hx-swap, :class<menu>, :id<menu>, self.nav-items, ); ] ) ~ self.script.HTML } method style { Style.new: q:to/END/ /* Custom styles for the hamburger menu */ .menu { display: none; flex-direction: column; gap: 10px; position: absolute; top: 60px; right: 20px; background: rgba(128, 128, 128, .97); padding: 1rem; border-radius: 8px; box-shadow: 0 4px 6px rgba(128, 128, 128, .2); } .menu a { display: block; } .menu.show { display: flex; } .hamburger { color: var(--pico-primary); display: none; cursor: pointer; font-size: 2.5rem; background: none; border: none; padding: 0.5rem; } @media (max-width: 768px) { .hamburger { display: block; } .nav-links { display: none; } } END } method script { Script.new: Q:to/END/; const hamburger = document.getElementById('hamburger'); const menu = document.getElementById('menu'); hamburger.addEventListener('click', () => { menu.classList.toggle('show'); }); document.addEventListener('click', (e) => { if (!menu.contains(e.target) && !hamburger.contains(e.target)) { menu.classList.remove('show'); } }); // Hide the menu when resizing the viewport to a wider width window.addEventListener('resize', () => { if (window.innerWidth > 768) { menu.classList.remove('show'); } }); END } } #| Page does Component in order to support #| multiple page instances with distinct content and attributes. class Page does Component { has $!loaded = 0; #| auto refresh browser every n secs in dev't has Int $.REFRESH; =para page implements several shortcuts that are populated up the DOM, for example C<page :title('My Page")> will go C<self.html.head.title = Title.new: $.title with $.title;> #| shortcut self.html.head.title has Str $.title; #| shortcut self.html.head.description has Str $.description; #| shortcut self.html.body.header.nav -or- has Nav $.nav is rw; #| shortcut self.html.body.header [nav wins if both attrs set] has Header $.header; #| shortcut self.html.body.main has Main $.main is rw; #| shortcut self.html.body.footer has Footer $.footer; #| enqueue SCRIPT [creates Script tags from registrant .SCRIPT methods to be appended at the end of the body tag] has Script @.enqueue; has $.thing; #| set to True with :styled-aside-on to apply self.html.head.style with right hand aside block has Bool $.styled-aside-on = False; #| build page DOM by calling Air tags has Html $.html .= new; #| set all provided shortcuts on first use method defaults { unless $!loaded++ { self.html.head.scripts.append: $.scripted-refresh with $.REFRESH; self.html.body.scripts.append: @.enqueue; self.html.head.title = Title.new: $.title with $.title; self.html.head.description = Meta.new: :name<description>, :content($.description) with $.description; with $.nav { self.html.body.header.nav = $.nav } orwith $.header { self.html.body.header = $.header } self.html.body.main = $.main with $.main; self.html.body.footer = $.footer with $.footer; self.html.head.style = $.styled-aside if $.styled-aside-on; } } #| .new positional with main only multi method new(Main $main, *%h) { self.bless: :$main, |%h } #| .new positional with main & footer only multi method new(Main $main, Footer $footer, *%h) { self.bless: :$main, :$footer, |%h } #| .new positional with header, main & footer only multi method new(Header $header, Main $main, Footer $footer, *%h) { self.bless: :$header, :$main, :$footer, |%h } #| issue page DOM method HTML { self.defaults unless $!loaded; '<!doctype html>' ~ $!html.HTML } method styled-aside { Style.new: q:to/END/ /* Custom styles for aside layout */ main { display: grid; grid-template-columns: 3fr 1fr; gap: 20px; } aside { background-color: aliceblue; opacity: 0.9; padding: 20px; border-radius: 5px; } END } method scripted-refresh { Script.new: qq:to/END/ function checkServer() \{ console.log("Checking server..."); fetch(window.location.href, \{ method: "GET", cache: "no-store" \}) .then(response => \{ console.log("Server responded with status:", response.status); if (response.ok) \{ console.log("Server is up! Refreshing now..."); location.reload(); // Refresh immediately when the server is back \} \}) .catch(error => \{ console.log("Server is down, not refreshing."); \}); } setInterval(checkServer, {$!REFRESH*1000}); // Check every $!REFRESH seconds END } } #| Site is a holder for pages, performs setup #| of Cro routes and offers high level controls for style via Pico SASS. class Site { #| Page holder -or- has Page @.pages; #| index Page ( otherwise $!index = @!pages[0] ) has Page $.index; #| Register for route setup; default = [Nav.new] has @.register; #| use :!scss to disable SASS compiler run has Bool $.scss = True; #| pick from: amber azure blue cyan fuchsia green indigo jade lime orange #| pink pumpkin purple red violet yellow (pico theme) has Str $.theme-color = 'green'; #| pick from:- aqua black blue fuchsia gray green lime maroon navy #| olive purple red silver teal white yellow (basic css) has Str $.bold-color = 'red'; #| .new positional with index only multi method new(Page $index, *%h) { self.bless: :$index, |%h; } submethod TWEAK { with @!pages[0] { $!index = @!pages[0] } orwith $!index { @!pages[0] = $!index } else { note "No pages or index found!" } self.enqueue-all; } method enqueue-all { for @!register.unique( as => *.^name ) -> $registrant { for @!pages -> $page { $page.html.body.scripts.append: Script.new($registrant.?SCRIPT) } } } method routes { use Cro::HTTP::Router; self.scss with $!scss; route { #| always route Nav @!register.push: Nav.new; #| setup Cro routes for @!register.unique( as => *.^name ) { when Component::Common { .make-methods; .^add-cromponent-routes; } when Form { .form-routes } default { note "Only Component::Common and Form types may be added" } } #| setup static Cro routes get -> { content 'text/html', $.index.HTML } get -> 'css', *@path { static 'static/css', @path } get -> 'img', *@path { static 'static/img', @path } get -> 'js', *@path { static 'static/js', @path } get -> *@path { static 'static', @path } #| setup external navigation Cro routes for @!pages { my ($url-name, $id) = .url-name, .id; note "adding GET {$url-name}/<#>"; get -> Str $url-name, Int $id { content 'text/html', @!pages[$id-1].HTML } } } } method scss { my $css = self.css; note "theme-color=$!theme-color"; $css ~~ s:g/'%THEME_COLOR%'/$!theme-color/; note "bold-color=$!bold-color"; $css ~~ s:g/'%BOLD_COLOR%'/$!bold-color/; chdir "static/css"; spurt "styles.scss", $css; qx`sass styles.scss styles.css 2>/dev/null`; #sinks warnings to /dev/null chdir "../.."; } method css { Q:to/END/; @use "node_modules/@picocss/pico/scss" with ( $theme-color: "%THEME_COLOR%" ); //some root overrides for scale https://github.com/picocss/pico/discussions/482 :root { --pico-font-family-sans-serif: Inter, system-ui, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, Helvetica, Arial, "Helvetica Neue", sans-serif, var(--pico-font-family-emoji); --pico-font-size: 106.25%; /* Original: 100% */ --pico-line-height: 1.25; /* Original: 1.5 */ --pico-form-element-spacing-vertical: 0.5rem; /* Original: 1rem */ --pico-form-element-spacing-horizontal: 1.0rem; /* Original: 1.25rem */ --pico-border-radius: 0.375rem; /* Original: 0.25rem */ } h1, h2, h3, h4, h5, h6 { --pico-font-weight: 600; /* Original: 700 */ } article { border: 1px solid var(--pico-muted-border-color); /* Original doesn't have a border */ border-radius: calc(var(--pico-border-radius) * 2); /* Original: var(--pico-border-radius) */ } article>footer { border-radius: calc(var(--pico-border-radius) * 2); /* Original: var(--pico-border-radius) */ } b { color: %BOLD_COLOR%; } .logo, .logo:hover { /* Remove underline by default and on hover */ text-decoration: none; font-size:160%; font-weight:700; } body > footer > p { font-size:66%; font-style:italic; } END } } =head2 Pico Tags =para The Air roadmap is to provide a full set of pre-styled tags as defined in the Pico L<docs|https://picocss.com/docs>. Did we say that Air::Base implements Pico CSS? =head3 role Table does Tag role Table does Tag { =para Attrs thead, tbody and tfoot can each be a 2D Array [[values],] that iterates to row and columns or a Tag|Component - if the latter then they are just rendered via their .HTML method. This allow for multi-row thead and tfoot. =para Table applies col and row header tags as required for Pico styles. =para Attrs provided as Pairs via tbody are extracted and applied. This is needed for :id<target> where HTMX is targetting the table body. #| default = [] is provided has $.tbody = []; #| optional has $.thead; #| optional has $.tfoot; #| class for table has $.class; has %!tbody-attrs; #| .new positional takes tbody [[]] multi method new(*@tbody, *%h) { self.bless: :@tbody, |%h; } submethod TWEAK { %!tbody-attrs = $!tbody.grep: * ~~ Pair; $!tbody = $!tbody.grep: !(* ~~ Pair); } multi sub do-part($part, :$head) { '' } multi sub do-part(@part where .all ~~ Tag|Taggable) { tbody @
### ---------------------------------------------------- ### -- Air ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: lib/Air/Base.rakumod ### ---------------------------------------------------- ### -- Chunk 2 of 2 part.map(*.HTML) } multi sub do-part(@part where .all ~~ Array, :$head) { do for @part -> @row { tr do for @row.kv -> $col, $cell { given $col, $head { when *, *.so { th $cell, :scope<col> } when 0, * { th $cell, :scope<row> } default { td $cell } } } } } multi method HTML { table |%(:$!class if $!class), [ thead do-part($!thead, :head); tbody do-part($!tbody), :attrs(|%!tbody-attrs); tfoot do-part($!tfoot); ] } } =head3 role Grid does Tag role Grid does Component { #| list of items to populate grid, has @.items; #| col count (default 5) has $.cols = 5; #| row count (default 5) has $.rows = 5; #| row / col gap in em (default 0) has $.gap = 0; #| .new positional takes @items multi method new(*@items, *%h) { self.bless: :@items, |%h; } # optional grid style from https://cssgrid-generator.netlify.app/ method style { my $str = q:to/END/; <style> #%HTML-ID% { display: grid; grid-template-columns: repeat(%COLS%, 1fr); grid-template-rows: repeat(%ROWS%, 1fr); grid-column-gap: %GAP%em; grid-row-gap: %GAP%em; } </style> END $str ~~ s:g/'%HTML-ID%'/$.html-id/; $str ~~ s:g/'%COLS%'/$!cols/; $str ~~ s:g/'%ROWS%'/$!rows/; $str ~~ s:g/'%GAP%'/$!gap/; $str } multi method HTML { $.style ~ div :id($.html-id), @!items; } } =head3 role Grid does Tag role Flexbox does Component { #| list of items to populate grid, has @.items; #| flex-direction (default row) has $.direction = 'row'; #| gap bewteen items in em (default 1) has $.gap = 1; #| .new positional takes @items multi method new(*@items, *%h) { self.bless: :@items, |%h; } # optional grid style from https://cssgrid-generator.netlify.app/ method style { my $str = q:to/END/; <style> #%HTML-ID% { display: flex; flex-direction: %DIRECTION%; /* column row */ justify-content: center; /* centers horizontally */ gap: %GAP%em; } /* Responsive layout - makes a one column layout instead of a two-column layout */ @media (max-width: 768px) { #%HTML-ID% { flex-direction: column; } } </style> END $str ~~ s:g/'%HTML-ID%'/$.html-id/; $str ~~ s:g/'%DIRECTION%'/$!direction/; $str ~~ s:g/'%GAP%'/$!gap/; $str } multi method HTML { $.style ~ div :id($.html-id), @!items; } } ##### Functions Export ##### #| put in all the @components as functions sub name( * @a, * %h) {Name.new(|@a,|%h)} # viz. https://docs.raku.org/language/modules#Exporting_and_selective_importing my package EXPORT::DEFAULT { for @functions -> $name { OUR::{'&' ~ $name.lc} := sub (*@a, *%h) { ::($name).new( |@a, |%h ) } } } my package EXPORT::NONE { } =begin pod =head1 AUTHOR Steve Roe <[email protected]> =head1 COPYRIGHT AND LICENSE Copyright(c) 2025 Henley Cloud Consulting Ltd. This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. =end pod
### ---------------------------------------------------- ### -- Air ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: lib/Air/Form.rakumod ### ---------------------------------------------------- =begin pod =head1 Air::Form This raku module is one of the core libraries of the raku B<Air> distribution. It provides a Form class that integrates Air with the Cro::WebApp::Form module to provide a simple,yet rich declarative abstraction for web forms. Air::Form uses Air::Functional for the Taggable role so that Forms can be employed within Air code. Air::Form is an alternative to Air::Component. =head1 SYNOPSIS An Air::Form is declared as a regular raku Object Oriented (OO) class. Specifically form input fields are set up via public attributes of the class ... C<has Str $.email> and so on. Check out the L<primer|https://docs.raku.org/language/objects> on raku OO basics. =head4 Form Declaration =begin code :lang<raku> use Air::Form; class Contact does Form { has Str $.first-names is validated(%va<names>); has Str $.last-name is validated(%va<name>) is required; has Str $.email is validated(%va<email>) is required is email; has Str $.city is validated(%va<text>); method form-routes { self.init; self.controller: -> Contact $form { if $form.is-valid { note "Got form data: $form.form-data()"; self.finish: 'Contact info received!' } else { self.retry: $form } } } } my $contact-form = Contact.empty; =end code Declaration Class and Attributes: =item C<use Air::Form> and then C<does Form> in the class declaration =item each public attribute such as C<has Str $.email> declares a form input =item attribute traits such as C<is email> control the form behaviour =item the trait C<is required> is a regular class trait, and also marks the input =item see below for details on C<is validated(...)> and other traits =item C<novalidate> is set for the browser, since validation is done on the server Form Routes: =item C<method form-routes {}> is called by C<site> to set up the form post route =item the form uses HTMX C<"hx-post="$form-url" hx-swap=\"outerHTML\"> =item C<self.init> initializes the form HTML with styles, validations and so on =item C<self.controller> takes a C<&handler> =item the handler is called by Cro, form field data is passed in the C<$form> parameter Essential Methods: =item C<$form.is-valid> checks the form data against defined validations =item C<$form.form-data> returns the form data as a Hash =item C<self.finish> returns HTML to the client (for the HTMX swap) =item C<self.retry: $form> returns the partially validated form data with errors =item C<Contact.empty> prepares an empty form for the first use in a page (use instead of C<Contact.new> to avoid validation errors) Several other Air::Form methods are described below. =head4 Form Consumption Forms can then be used in an Air application like this: =begin code :lang<raku> my $contact-form = Contact.empty; #repeated from above use Air::Functional :BASE; use Air::Base; # define custom page properties my &index = &page.assuming( title => 'hÅrc', description => 'HTMX, Air, Red, Cro', nav => nav( logo => safe('<a href="/">h<b>&Aring;</b>rc</a>'), widgets => [lightdark], ), footer => footer p ['Aloft on ', b 'åir'], ); # use the $contact-form in an Air website sub SITE is export { site :register[$contact-form], index main content [ h2 'Contact Form'; $contact-form; ]; } =end code Note: =item C<:register[$contact-form]> tells the site to make the form route =item C<$contact-form> does the role C<Taggable> so it can be used within Air::Functional code =head1 DESCRIPTION C<Air::Form>s do the C<Cro::WebApp::Form> role. Therefore many of the features are set out in tne L<Cro docs|https://cro.raku.org/docs/reference/cro-webapp-form>. =head2 Form Controls =para Re-exported from C<Cro::WebApp::Form>, per the L<Cro docs|https://cro.raku.org/docs/reference/cro-webapp-form#Form_controls> Traits are used to describe the kinds of controls that will be used on a form. The full set of HTML5 control types are available. Remember to check browser support for them is sufficient if needing to cater to older browsers. They mostly follow the HTML 5 control names, however in a few cases alternative names are offered for convenience. Taking care to use is email and is telephone is especially helpful for mobile users. =item is password - a password input =item is number - a number input (set implicitly if a numeric type is used) =item is color - a color input =item is date - a date input =item is datetime-local / is datetime - a datetime-local input =item is email - an email input =item is month - a month input =item is multiline - a multiline text input (rendered as a text area); can have the number of rows and columns specified as named arguments, such as is multiline(:5rows, :60cols) =item is tel / is telephone - a tel input for a phone number =item is search - a search input =item is time - a time input =item is url - a url input =item is week - a week input =item will select { ... } - a select input, offering the options specified in the block, for example will select { 1..5 }. If the sigil of the attribute is @, then it will render a multi-select box. While self is not available in such a trait, it is passed as the topic of the block, so one can write a method get-options() { ... } and then do will select { .get-options }. Note that currently there is no assistance with handling situations where the options should depend on another form field. =item is file - a file upload input; the attribute will be populated with an instance of Cro::HTTP::Body::MultiPartFormData::Part, which has properties filename, body-blob (binary upload) ond body-text (decodes the body-blob to a Str) =item is hidden - a hidden input There is no trait for checkboxes; use the Bool type instead. =head3 Labels, help texts, and placeholders By default, the label for the control is formed by: Taking the attribute name Replacing each - with a space Calling tclc to title case it Use the C<is label('Name')> trait in order to explicitly set a label. For text inputs, one can also set a placeholder using the is placeholder('Text') trait. This text is rendered in the textbox prior to the user filling it. Finally, one may use the C<is help('...')> trait in order to provide help text. This is displayed beneath the form field. =head2 Validation =begin code :lang<raku> our %va = ( text => ( /^ <[A..Za..z0..9\s.,_#-]>+ $/, 'In text, only ".,_-#" punctuation characters are allowed' ), name => ( /^ <[A..Za..z.'-]>+ $/, 'In a name, only ".-\'" punctuation characters are allowed' ), names => ( /^ <[A..Za..z\s.'-]>+ $/, 'In names, only ".-\'" punctuation characters are allowed' ), words => ( /^ <[A..Za..z\s]>+ $/, 'In words, only text characters are allowed' ), notes => ( /^ <[A..Za..z0..9\s.,:;_#!?()%$£-]>+ $/, 'In notes, only ".,:;_-#!?()%$£" punctuation characters are allowed' ), postcode => ( /^ <[A..Za..z0..9\s]>+ $/, 'In postcode, only alphanumeric characters are allowed' ), url => ( /^ <[a..z0..9:/.-]>+ $/, 'Only valid urls are allowed' ), tel => ( /^ <[0..9+()\s#-]>+ $/, 'Only valid tels are allowed' ), email => ( /^ <[a..zA..Z0..9._%+-]>+ '@' <[a..zA..Z0..9.-]>+ '.' <[a..zA..Z]> ** 2..6 $/, 'Only valid email addresses are allowed' ), password => ( ( /^ <[A..Za..z0..9!@#$%^&*()\-_=+{}\[\]|:;"'<>,.?/]> ** 8..* $/ & / <[A..Za..z]> / & /<[0..9]> /), 'Passwords must have minimum 8 characters with at least one letter and one number.' ), ); =end code =head3 role Form does Cro::WebApp::Form does Taggable {} =para This role has only private attrs to avoid creating form fields, get/set methods are provided instead. =para The C<%!form-attrs> are the same as C<Cro::WebApp::Form>. =para Air::Form currently supports these attrs: =item C<submit-button-text> - the text placed on the form submit button =item C<form-errors-text> - text that comes before form-level errors are rendered =para Here is an example of customizing the submit button text (ie place this method in your Contact form (or whatever you choose to call it). =begin code :lang<raku> method do-form-attrs{ self.form-attrs: {:submit-button-text('Save Contact Info')} } =end code =para Air::Form code should avoid direct manipulation of the method and class styles detailed at L<Cro docs|https://cro.raku.org/docs/reference/cro-webapp-form#Rendering> - instead override the C<method styles {}>. =head2 Development Roadmap =para The Air::Form module will be extended to perform full CRUD operations on a Red table by the selective grafting of Air::Component features over to Air::Form, for example: =item C<LOAD> method to load a form with values from a specific table row =item C<ADD> method to add a new table row with form values provided =item C<UPDATE> method to update table row with form value modifications =item C<DELETE> method to delete table row =para Other potential features include: =item a table list view [with row/col filters] =item an item list view [with edit/save loop] =para Technically it is envisaged that ::?CLASS.HOW does Cromponent::MetaCromponentRole; will be brought over from Cromponent with suitable controller methods. If you want to go model XXX does Form does Component, then there is a Taggable use conflict. =end pod use Air::Functional :CRO; use Cro::WebApp::Form; use Cro::WebApp::Template; use Cro::WebApp::Template::Repository; use Cro::HTTP::Router; our %va = ( text => ( /^ <[A..Za..z0..9\s.,_#-]>+ $/, 'In text, only ".,_-#" punctuation characters are allowed' ), name => ( /^ <[A..Za..z.'-]>+ $/, 'In a name, only ".-\'" punctuation characters are allowed' ), names => ( /^ <[A..Za..z\s.'-]>+ $/, 'In names, only ".-\'" punctuation characters are allowed' ), words => ( /^ <[A..Za..z\s]>+ $/, 'In words, only text characters are allowed' ), notes => ( /^ <[A..Za..z0..9\s.,:;_#!?()%$£-]>+ $/, 'In notes, only ".,:;_-#!?()%$£" punctuation characters are allowed' ), postcode => ( /^ <[A..Za..z0..9\s]>+ $/, 'In postcode, only alphanumeric characters are allowed' ), url => ( /^ <[a..z0..9:/.-]>+ $/, 'Only valid urls are allowed' ), tel => ( /^ <[0..9+()\s#-]>+ $/, 'Only valid tels are allowed' ), email => ( /^ <[a..zA..Z0..9._%+-]>+ '@' <[a..zA..Z0..9.-]>+ '.' <[a..zA..Z]> ** 2..6 $/, 'Only valid email addresses are allowed' ), password => ( ( /^ <[A..Za..z0..9!@#$%^&*()\-_=+{}\[\]|:;"'<>,.?/]> ** 8..* $/ & / <[A..Za..z]> / & /<[0..9]> /), 'Passwords must have minimum 8 characters with at least one letter and one number.' ), ); role Form does Cro::WebApp::Form does Taggable { #| optionally specify form url base (with get/set methods) has Str $!form-base = ''; multi method form-base {$!form-base} multi method form-base($value) {$!form-base = $value} #| get url safe name of class doing Form role method form-name { ::?CLASS.^name.subst('::','-').lc } #| get url (ie base/name) method form-url(--> Str) { do with self.form-base { "$_/" } ~ self.form-name } #| optional form attrs (with get/set methods) has %!form-attrs; multi method form-attrs { %!form-attrs } multi method form-attrs(%h) { %!form-attrs{.key} = .value for %h } method init { self.do-form-styles; # self.do-form-scripts; self.do-form-defaults; self.?do-form-attrs; self.do-form-tmpl; } my $formtmp //= Q|%FORM-STYLES%<&form( .form, %FORM-ATTRS% )>|; method do-form-styles { $formtmp .= subst: /'%FORM-STYLES%'/, self.form-styles } method do-form-defaults { %!form-attrs = ( submit-button-text => 'Submit ' ~ ::?CLASS.^name, invalid-feedback-class => 'invalid-feedback-class', form-errors-class => 'form-errors-class', ) } method do-form-tmpl { $formtmp .= subst: /'%FORM-ATTRS%'/, self.form-attrs.map({":{.key}('{.value}')"}).join(',') } sub adjust($form-html, $form-url) { $form-html.subst( / 'method="post"' /, "hx-post=\"$form-url\" hx-swap=\"outerHTML\" novalidate" ) } #| called when used as a Taggable, returns self.empty multi method HTML(--> Markup()) { parse-template($formtmp) andthen .render( {form => self.empty} ).&adjust(self.form-url) } #| when passed a $form field set, returns populated form multi method HTML(Form $form --> Markup()) { parse-template($formtmp) andthen .render( {:$form} ).&adjust(self.form-url) } #| return partially complete form method retry(Form $form) is export { #! content 'text/plain', self.HTML($form) } #| return message (typically used when self.is-valis method finish(Str $msg) { content 'text/plain', $msg } #| make a route to handle form submit method submit(&handler) { post -> Str $ where self.form-url, { form-data &handler; } } #| get form-styles (may be overridden) method form-styles { q:to/END/ <style> input[required] { border: calc(var(--pico-border-width) * 2) var(--pico-border-color) solid; } .invalid-feedback-class { margin-top: -10px; margin-bottom: 10px; color: var(--pico-del-color); } .form-errors-class > * > li { color: var(--pico-del-color); } </style> END } #| get form-scripts, pass in a custom $suffix for required labels (may be overridden) method SCRIPT($suffix = '*') { my $javascript = q:to/END/; function appendRequiredSuffixToLabels() { const requiredInputs = document.querySelectorAll("input[required]"); requiredInputs.forEach(input => { const id = input.id; if (!id) return; // skip inputs without an ID const label = document.querySelector(`label[for="${id}"]`); if (label && !label.textContent.includes("(required)")) { label.textContent += "%SUFFIX%"; } }); } function scrollFormErrorsIntoView(evt) { //console.log('htmx:afterSwap fired', evt); const errorDiv = evt.target.querySelector('.form-errors-class'); if (errorDiv && errorDiv.innerText.trim() !== '') { errorDiv.focus(); errorDiv.scrollIntoView({ behavior: 'smooth', block: 'center' }); } } document.addEventListener('htmx:afterSwap', function(evt) { scrollFormErrorsIntoView(evt); appendRequiredSuffixToLabels(); }); document.addEventListener("DOMContentLoaded", function() { appendRequiredSuffixToLabels(); }); END $javascript ~~ s:g/'%SUFFIX%'/$suffix/; $javascript; } } # Re-export is traits multi trait_mod:<is>(Attribute:D $attr, :$label! --> Nil) is export { Cro::WebApp::Form::trait_mod:<is>($attr, :$label) } multi trait_mod:<is>(Attribute:D $attr, :$placeholder! --> Nil) is export { Cro::WebApp::Form::trait_mod:<is>($attr, :$placeholder) } multi trait_mod:<is>(Attribute:D $attr, :$help! --> Nil) is export { Cro::WebApp::Form::trait_mod:<is>($attr, :$help) } multi trait_mod:<is>(Attribute:D $attr, :$hidden! --> Nil) is export { Cro::WebApp::Form::trait_mod:<is>($attr, :$hidden) } multi trait_mod:<is>(Attribute:D $attr, :$file! --> Nil) is export { Cro::WebApp::Form::trait_mod:<is>($attr, :$file) } multi trait_mod:<is>(Attribute:D $attr, :$password! --> Nil) is export { Cro::WebApp::Form::trait_mod:<is>($attr, :$password) } multi trait_mod:<is>(Attribute:D $attr, :$number! --> Nil) is export { Cro::WebApp::Form::trait_mod:<is>($attr, :$number) } multi trait_mod:<is>(Attribute:D $attr, :$color! --> Nil) is export { Cro::WebApp::Form::trait_mod:<is>($attr, :$color) } multi trait_mod:<is>(Attribute:D $attr, :$date! --> Nil) is export { Cro::WebApp::Form::trait_mod:<is>($attr, :$date) } multi trait_mod:<is>(Attribute:D $attr, :datetime(:$datetime-local)! --> Nil) is export { Cro::WebApp::Form::trait_mod:<is>($attr, :$datetime-local) } multi trait_mod:<is>(Attribute:D $attr, :$email! --> Nil) is export { Cro::WebApp::Form::trait_mod:<is>($attr, :$email) } multi trait_mod:<is>(Attribute:D $attr, :$month! --> Nil) is export { Cro::WebApp::Form::trait_mod:<is>($attr, :$month) } multi trait_mod:<is>(Attribute:D $attr, :telephone(:$tel)! --> Nil) is export { Cro::WebApp::Form::trait_mod:<is>($attr, :$tel) } multi trait_mod:<is>(Attribute:D $attr, :$search! --> Nil) is export { Cro::WebApp::Form::trait_mod:<is>($attr, :$search) } multi trait_mod:<is>(Attribute:D $attr, :$time! --> Nil) is export { Cro::WebApp::Form::trait_mod:<is>($attr, :$time) } multi trait_mod:<is>(Attribute:D $attr, :$url! --> Nil) is export { Cro::WebApp::Form::trait_mod:<is>($attr, :$url) } multi trait_mod:<is>(Attribute:D $attr, :$week! --> Nil) is export { Cro::WebApp::Form::trait_mod:<is>($attr, :$week) } multi trait_mod:<is>(Attribute:D $attr, :$multiline! --> Nil) is export { Cro::WebApp::Form::trait_mod:<is>($attr, :$multiline) } multi trait_mod:<is>(Attribute:D $attr, Int :min-length(:$minlength)! --> Nil) is export { Cro::WebApp::Form::trait_mod:<is>($attr, :min-length(:$minlength)) } multi trait_mod:<is>(Attribute:D $attr, Int :max-length(:$maxlength)! --> Nil) is export { Cro::WebApp::Form::trait_mod:<is>($attr, :max-length(:$maxlength)) } multi trait_mod:<is>(Attribute:D $attr, Real :$min! --> Nil) is export { Cro::WebApp::Form::trait_mod:<is>($attr, :$min) } multi trait_mod:<is>(Attribute:D $attr, Real :$max! --> Nil) is export { Cro::WebApp::Form::trait_mod:<is>($attr, :$max) } multi trait_mod:<will>(Attribute:D $attr, &block, :$select! --> Nil) is export { Cro::WebApp::Form::trait_mod:<will>($attr, :$select) } multi trait_mod:<is>(Attribute:D $attr, :$validated! --> Nil) is export { Cro::WebApp::Form::trait_mod:<will>($attr, :$validated) } =begin pod =head1 AUTHOR Steve Roe <[email protected]> =head1 COPYRIGHT AND LICENSE Copyright(c) 2025 Henley Cloud Consulting Ltd. This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. =end pod
### ---------------------------------------------------- ### -- Air ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: lib/Air/Functional.rakumod ### ---------------------------------------------------- =begin pod =head1 Air::Functional This raku module is one of the core libraries of the raku B<Air> distribution. It exports HTML tags as raku subs that can be composed as functional code within a raku program. It replaces the HTML::Functional module by the same author. =head1 SYNOPSIS Here's a regular HTML page: =begin code :lang<html> <div class="jumbotron"> <h1>Welcome to Dunder Mifflin!</h1> <p> Dunder Mifflin Inc. (stock symbol <strong>DMI</strong>) is a micro-cap regional paper and office supply distributor with an emphasis on servicing small-business clients. </p> </div> =end code And here is the same page using Air::Functional: =begin code :lang<raku> use Air::Functional; div :class<jumbotron>, [ h1 "Welcome to Dunder Mifflin!"; p [ "Dunder Mifflin Inc. (stock symbol "; strong 'DMI'; ") "; q:to/END/; is a micro-cap regional paper and office supply distributor with an emphasis on servicing small-business clients. END ]; ]; =end code =head1 DESCRIPTION Key features shown are: =item HTML tags are implemented as raku functions: C<div, h1, p> and so on =item parens C<()> are optional in raku function calls =item HTML tag attributes are passed as raku named arguments =item HTML tag inners (e.g. the Str in C<h1>) are passed as raku positional arguments =item the raku Pair syntax is used for each attribute i.e. C<:name<value>> =item multiple C<@inners> are passed as a literal Array C<[]> – div contains h1 and p =item the raku parser looks at functions from the inside out, so C<strong> is evaluated before C<p>, before C<div> and so on =item semicolon C<;> is used as the Array literal separator to suppress nesting of tags Normally the items in a raku literal Array are comma C<,> separated. Raku precedence considers that C<div [h1 x, p y];> is equivalent to C<div( h1(x, p(y) ) );> … so the p tag is embedded within the h1 tag unless parens are used to clarify. But replace the comma C<,> with a semi colon C<;> and predisposition to nest is reversed. So C<div [h1 x; p y];> is equivalent to C<div( h1(x), p(y) )>. Boy that Larry Wall was smart! The raku example also shows the power of the raku B<Q-lang> at work: =item double quotes C<""> interpolate their contents =item curlies denote an embedded code block C<"{fn x}"> =item tilde C<~> is for Str concatenation =item the heredoc form C<q:to/END/;> can be used for verbatim text blocks This module generally returns C<Str> values to be string concatenated and included in an HTML content/text response. It also defines a programmatic API for the use of HTML tags for raku functional coding and so is offered as a basis for sister modules that preserve the API, but have a different technical implementation such as a MemoizedDOM. =end pod unit class Air::Functional; use HTML::Escape; =head2 Declare Constants =para All of the HTML tags listed at L<https://www.w3schools.com/tags/default.asp> are covered ... constant @all-tags = <a abbr address area article aside audio b base bdi bdo blockquote body br button canvas caption cite code col colgroup data datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe img input ins kbd label legend li link main map mark menu meta meter nav noscript object ol optgroup option output p param picture pre progress q rp rt ruby s samp script search section select small source span strong style sub summary sup svg table tbody td template textarea tfoot th thead time title tr track u ul var video wbr>; =para ... of which empty (Singular) tags from L<https://www.tutsinsider.com/html/html-empty-elements/> constant @singular-tags = <area base br col embed hr img input link meta param source track wbr>; =head2 HTML Escape #| Explicitly HTML::Escape inner text sub escape(Str:D() $s --> Str) is export { escape-html($s) } #| also a shortcut ^ prefix multi prefix:<^>(Str:D() $s --> Str) is export { escape-html($s) } =head2 Tag Rendering role Tag is export(:MANDATORY) {...} enum TagType is export(:MANDATORY) <Singular Regular>; =head3 role Attr is Str {} - type for Attribute values, use Attr() for coercion role Attr is Str is export(:MANDATORY) {} =head3 subset Inner where Str | Tag | Taggable | Markup - type union for Inner elements role Taggable is Str is export(:MANDATORY) {} role Markup is Str is export(:MANDATORY) {} subset Inner where Str | Tag | Taggable | Markup; =head2 role Tag [TagType Singular|Regular] {} - basis for Air functions role Tag[TagType $tag-type?] is export(:MANDATORY) { has Str $.name = ::?CLASS.^name.lc; #| can be provided with attrs has Attr() %.attrs is rw; #| can be provided with inners has Inner @.inners; #| ok to call .new with @inners as Positional multi method new(*@inners, *%attrs) { self.bless: :@inners, :%attrs } #| provides default .HTML method used by tag render multi method HTML { samewith $tag-type } multi method HTML(Singular) { do-singular-tag( $!name, |%.attrs ) } multi method HTML(Regular) { do-regular-tag( $!name, @.inners, |%.attrs ) } } =head3 Low Level API =para This level is where users want to mess around with the parts of a tag for customizations #| convert from raku Pair syntax to HTML tag attributes sub attrs(%h --> Str) is export { #| Discard attrs with False or undefined values my @discards = %h.keys.grep: { %h{$_} === False || %h{$_}.defined.not }; @discards.map: { %h{$_}:delete }; #| Special case Bool attrs eg <input type="checkbox" checked> my @attrs = %h.keys.grep: { %h{$_} eq 'True' }; @attrs.map: { %h{$_}:delete }; #| Attrs as key-value pairs @attrs.append: %h.map({.key ~ '="' ~ .value ~ '"'}); @attrs ?? ' ' ~ @attrs.join(' ') !! ''; } #| open a custom tag sub opener($tag, *%h -->Str) is export { "\n" ~ '<' ~ $tag ~ attrs(%h) ~ '>' } multi sub render-tag(Tag $inner) { $inner.HTML } multi sub render-tag(Taggable $inner) { $inner.HTML } multi sub render-tag(Markup $inner) { $inner } multi sub render-tag(Str() $inner) { escape-html($inner) } #| convert from an inner list to HTML tag inner string sub inner(@inners --> Str) is export { given @inners { when * == 0 { '' } when * == 1 { .first.&render-tag } when * >= 2 { .map(*.&render-tag).join } } } #| close a custom tag (unset :!nl to suppress the newline) sub closer($tag, :$nl --> Str) is export { ($nl ?? "\n" !! '') ~ '</' ~ $tag ~ '>' } =head3 High Level API =para This level is for general use from custom tags that behave like regular/singular tags #| do a regular tag (ie a tag with @inners) sub do-regular-tag(Str $tag, *@inners, *%h --> Markup() ) is export(:MANDATORY) { my $nl = @inners >= 2; opener($tag, |%h) ~ inner(@inners) ~ closer($tag, :$nl) } #| do a singular tag (ie a tag without @inners) sub do-singular-tag(Str $tag, *%h --> Markup() ) is export(:MANDATORY) { "\n" ~ '<' ~ $tag ~ attrs(%h) ~ ' />' } =head2 Tag Export Options =para Exports all the tags programmatically my @regular-tags = (@all-tags (-) @singular-tags).keys; #Set difference (-) #| export all HTML tags #| viz. https://docs.raku.org/language/modules#Exporting_and_selective_importing my package EXPORT::DEFAULT { for @regular-tags -> $tag { OUR::{'&' ~ $tag} := sub (*@inners, *%h) { do-regular-tag( "$tag", @inners, |%h ) } } for @singular-tags -> $tag { OUR::{'&' ~ $tag} := sub (*%h) { do-singular-tag( "$tag", |%h ) } } } my @exclude-cro = <header table template>; my @regular-cro = @regular-tags.grep: { $_ ∉ @exclude-cro }; my @singular-cro = @singular-tags.grep: { $_ ∉ @exclude-cro }; #| use :CRO as package to avoid collisions with Cro::Router names my package EXPORT::CRO { for @regular-cro -> $tag { OUR::{'&' ~ $tag} := sub (*@inners, *%h) { do-regular-tag( "$tag", @inners, |%h ) } } for @singular-cro -> $tag { OUR::{'&' ~ $tag} := sub (*%h) { do-singular-tag( "$tag", |%h ) } } } my @exclude-base = <section article aside time a body main header content footer nav table grid>; my @regular-base = @regular-tags.grep: { $_ ∉ @exclude-base }; my @singular-base = @singular-tags.grep: { $_ ∉ @exclude-base }; #| use :BASE as package to avoid collisions with Cro::Router, Air::Base & Air::Component names #| NB the HTML description list tags <dl dd dt> are also excluded to avoid conflict with the raku `dd` command my package EXPORT::BASE { for @regular-base -> $tag { OUR::{'&' ~ $tag} := sub (*@inners, *%h) { do-regular-tag( "$tag", @inners, |%h ) } } for @singular-base -> $tag { OUR::{'&' ~ $tag} := sub (*%h) { do-singular-tag( "$tag", |%h ) } } } =begin pod =head1 AUTHOR Steve Roe <[email protected]> =head1 COPYRIGHT AND LICENSE Copyright(c) 2025 Henley Cloud Consulting Ltd. This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. =end pod
### ---------------------------------------------------- ### -- Air ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: lib/Air/Component.rakumod ### ---------------------------------------------------- =begin pod =head1 Air::Component This raku module is one of the core libraries of the raku B<Air> distribution. It is a scaffold to build dynamic, reusable web components. =head1 SYNOPSIS The synopsis is split so that each part can be annotated. First, we import the Air core libraries. =begin code :lang<raku> use Air::Functional :BASE; # import all HTML tags as raku subs use Air::Base; # import Base components (site, page, nav...) use Air::Component; =end code =head3 HTMX functions We prepare some custom HTMX actions for our Todo component. This declutters C<class Todo> and keeps our C<hx-attrs> tidy and local. =begin code :lang<raku> role HxTodo { method hx-create(--> Hash()) { :hx-post("todo"), :hx-target<table>, :hx-swap<beforeend>, } method hx-delete(--> Hash()) { :hx-delete($.url-id), :hx-confirm<Are you sure?>, :hx-target<closest tr>, :hx-swap<delete>, } method hx-toggle(--> Hash()) { :hx-get("$.url-id/toggle"), :hx-target<closest tr>, :hx-swap<outerHTML>, } } =end code Key features are: =item these are packaged in a raku role which is then consumed by C<class Todo> =item method names C<hx-toggle> echo standard HTMX attributes such as C<hx-get> =item return values are coerced to a raku C<Hash> containing HTMX attrs =head3 class Todo The core of our synopsis. It C<does Component> to bring in the scaffolding. The general idea is that a raku class implements a web Component, multiple instances of the Component are represented by objects of the class and the methods of the class represent actions that can be performed on the Component in the browser. =begin code :lang<raku> class Todo does Component { also does HxTodo; has Bool $.checked is rw = False; has Str $.text; method toggle is controller { $!checked = !$!checked; respond self; } multi method HTML { tr td( input :type<checkbox>, |$.hx-toggle, :$!checked ), td( $!checked ?? del $!text !! $!text), td( button :type<submit>, |$.hx-delete, :style<width:50px>, '-'), } } =end code Key features of C<class Todo> are: =item Todo objects have state C<$.checked> and C<$.text> with suitable defaults =item C<method toggle> takes the trait C<is controller> - this makes a corresponding Cro route =item C<method toggle> adjusts the state and ends with the C<respond> sub (which calls C<.HTML>) =item C<class Todo> provides a C<multi method HTML> which uses functional HTML tags C<tr>, C<td> and so on =item we call our HxTodo methods eg C<|$.hx-toggle> with the I<call self> shorthand C<$.> =item the Hash is flattened into individual attrs with C<|> =item a smattering of style (or any HTML attr) can be added as needed The result is a concise, legible and easy-to-maintain component implementation. =head3 sub SITE Now, we can make a website as follows: =begin code :lang<raku> my &index = &page.assuming( title => 'hÅrc', description => 'HTMX, Air, Red, Cro', footer => footer p ['Aloft on ', b 'Åir'], ); my @todos = do for <one two> -> $text { Todo.new: :$text }; sub SITE is export { site :register(@todos), index main [ h3 'Todos'; table @todos; form |Todo.hx-create, [ input :name<text>; button :type<submit>, '+'; ]; ] } =end code Key features of C<sub SITE> are: =item1 we make our own function C<&index> that =item2 (i) uses C<.assuming> to preset some attributes (title, description, footer) and =item2 (ii) then calls the C<page> function provided by Air::Base =item1 we set up our list of Todo components calling C<Todo.new> =item1 we use the Air::Base C<site> function to make our website =item1 the call chain C<site(index(main(...))> then makes our website =item1 C<site> is passed C<:register(@todos)> to make the component Cro routes =head2 Run Cro service.raku Component automagically creates some cro routes for Todo when we start our website... =begin code > raku -Ilib service.raku theme-color=green bold-color=red adding GET todo/<#> adding POST todo adding DELETE todo/<#> adding PUT todo/<#> adding GET todo/<#>/toggle adding GET page/<#> Build time 0.67 sec Listening at http://0.0.0.0:3000 =end code =head1 DESCRIPTION The rationale for Air Components is rooted in the powerful raku code composition capabilities. It builds on the notion of Locality of Behaviour (aka L<LOB|https://htmx.org/essays/locality-of-behaviour/>) and the intent is that a Component can represent and render every aspect of a piece of website behaviour. =item Content =item Layout =item Theme =item Data Model =item Actions As Air evolves, it is expected that common code idioms will emerge to make each dimensions independent (ie HTML, CSS and JS relating to Air::Theme::Font would be local, and distinct from HTML, CSS and JS for Air::Theme::Nav). Air is an integral part of the hArc stack (HTMX, Air, Red, Cro). The Synopsis shows how a Component can externalize and consume HTMX attributes for method actions, perhaps even a set of Air::HTMX libraries can be anticipated. One implication of this is that each Component can use the L<hx-swap-oob|https://htmx.org/attributes/hx-swap-oob/> attribute to deliver Content, Style and Script anywhere in the DOM (except the C<html> tag). An instance of this could be a blog website where a common Red C<model Post> could be harnessed to populate each blog post, a total page count calculation for paging and a post summary list in an C<aside>. In the Synopsis, both raku class inheritance and role composition provide coding dimensions to greatly improve code clarity and evolution. While simple samples are shown, raku has comprehensive encapsulation and type capabilities in a friendly and approachable language. Raku is a multi-paradigm language for both Functional and Object Oriented (OO) coding styles. OO is a widely understood approach to code and state encapsulation - suitable for code evolution across many aspects - and is well suited for Component implementations. Functional is a surprisingly good paradigm for embedding HTML standard and custom tags into general raku source code. The example below illustrates the power of Functional tags inline when used in more intricate stanzas. While this kind of logic can in theory be delivered in a web app using web template files, as the author of the Cro Template language L<comments|https://cro.raku.org/docs/reference/cro-webapp-template-syntax#Conditionals> I<Those wishing for more are encouraged to consider writing their logic outside of the template.> =begin code :lang<raku> method nav-items { do for @.items.map: *.kv -> ($name, $target) { given $target { when * ~~ External | Internal { $target.label = $name; li $target.HTML } when * ~~ Content { li a(:hx-get("$.name/$.serial/" ~ $name), safe $name) } when * ~~ Page { li a(:href("/{.name}/{.serial}"), safe $name) } } } } multi method HTML { self.style.HTML ~ ( nav [ { ul li :class<logo>, :href</>, $.logo } with $.logo; button( :class<hamburger>, :serial<hamburger>, safe '&#9776;' ); ul( :$!hx-target, :class<nav-links>, self.nav-items, do for @.wserialgets { li .HTML }, ); ul( :$!hx-target, :class<menu>, :serial<menu>, self.nav-items, ); ] ) ~ self.script.HTML } =end code From the implementation of the Air::Base::Nav component. =head1 TIPS & TRICKS When writing components: =item custom C<multi method HTML> inners must be explicitly rendered with .HTML or wrapped in a tag eg. C<div> since being passed as AN inner will call C<render-tag> which will, in turn, call C<.HTML> =end pod use Air::Functional :CRO; use Cromponent; use Cromponent::MetaCromponentRole; sub to-kebab(Str() $_) { lc S:g/(\w)<?before <[A..Z]>>/$0-/ } multi trait_mod:<is>(Method $m, Bool :$controller!) is export { trait_mod:<is>($m, :controller{}) } multi trait_mod:<is>(Method $m, :%controller!) is export { my %accessible = %controller; %accessible<returns-cromponent> = True unless %controller<returns-html>; #make default trait_mod:<is>($m, :%accessible) } #| attributes and methods shared between Component and Component::Red roles role Component::Common does Taggable { #| optional attr to specify url base has Str $!base is built = ''; method base {$!base} #| get url safe name of class doing Component role method url-name { self.^shortname.&to-kebab, } #| get url (ie base/name) method url(--> Str) { do with self.base { "$_/" } ~ self.url-name} #| get url-id (ie base/name/id) method url-path(--> Str) { self.url ~ '/' ~ self.id } #| get html-id (ie url-name-id), intended for HTML id attr method html-id(--> Str) { self.url-name ~ '-' ~ self.id } #| In general Cromponent::MetaCromponentRole calls .Str on a Cromponent when returning it #| this method substitutes .HTML for .Str method Str { self.HTML } } #| Component is for non-Red classes role Component[ :C(:A(:$ADD)), :R(:L(:$LOAD)) = True, :U(:$UPDATE), :D(:$DELETE), ] does Component::Common { ::?CLASS.HOW does Cromponent::MetaCromponentRole; my UInt $next = 1; #| assigns and tracks instance ids has UInt $!id is built; method id { $!id } my %holder; #| populates an instance holder [class method], #| may be overridden for external instance holder method holder(--> Hash) { %holder } #| get all instances in holder method all { self.holder.keys.sort.map: { $.holder{$_} } } #| adapt component to perform LOAD, UPDATE, DELETE, ADD action(s) my $methods-made; #| called by role Site method make-methods { return if $methods-made++; #| Default ADD action (called on POST) - may be overridden if $ADD { self.^add_method( 'ADD', my method ADD(*%data) { ::?CLASS.new: |%data } ); } #| Default LOAD action (called on GET) - may be overridden if $LOAD { self.^add_method( 'LOAD', my method LOAD($id) { self.holder{$id} } ); } #| Default UPDATE action (called on PUT) - may be overridden if $UPDATE { self.^add_method( 'UPDATE', my method UPDATE(*%data) { self.data = |self.data, |%data } ); } #| Default DELETE action (called on DELETE) - may be overridden if $DELETE { self.^add_method( 'DELETE', my method DELETE { self.holder{self.id}:delete } ); } } submethod TWEAK { $!id //= $next++; %holder{$!id} = self; self.?make-routes; } } #| Component::Red is for Red models role Component::Red[ :C(:A(:$ADD)), :R(:L(:$LOAD)) = True, :U(:$UPDATE), :D(:$DELETE), ] does Component::Common { ::?CLASS.HOW does Cromponent::MetaCromponentRole; #| adapt component to perform LOAD, UPDATE, DELETE, ADD action(s) my $methods-made; #| called by role Site method make-methods { return if $methods-made++; #| Default ADD action (called on POST) - may be overridden if $ADD { self.^add_method( 'ADD', my method ADD(*%data) { ::?CLASS.^create: |%data } ); } #| Default LOAD action (called on GET) - may be overridden if $LOAD { self.^add_method( 'LOAD', my method LOAD(Str() $id) { ::?CLASS.^load: $id } ); } #| Default UPDATE action (called on PUT) - may be overridden if $UPDATE { self.^add_method( 'UPDATE', my method UPDATE(*%data) { $.data = |$.data, |%data; $.^save } #untested ); } #| Default DELETE action (called on DELETE) - may be overridden if $DELETE { self.^add_method( 'DELETE', my method DELETE { $.^delete } ); } } } =begin pod =head1 AUTHOR Steve Roe <[email protected]> The `Air::Component` module integrates with the Cromponent module, author Fernando Corrêa de Oliveira <[email protected]>, however unlike Cromponent this module does not use Cro Templates. =head1 COPYRIGHT AND LICENSE Copyright(c) 2025 Henley Cloud Consulting Ltd. This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. =end pod
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: service.raku ### ---------------------------------------------------- #!/usr/bin/env raku my $start = now; use lib "../lib"; use Cro::HTTP::Log::File; use Cro::HTTP::Router; use Cro::HTTP::Server; use Air::Play; my Cro::Service $http = Cro::HTTP::Server.new( http => <1.1>, host => "0.0.0.0", port => 3000, application => routes(), after => [ Cro::HTTP::Log::File.new(logs => $*OUT, errors => $*ERR) ], ); $http.start; my $elapsed = (now - $start).round(0.01); say "Build time $elapsed sec"; say "Listening at http://0.0.0.0:3000"; react { whenever signal(SIGINT) { say "Shutting down..."; $http.stop; done; } }
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: META6.json ### ---------------------------------------------------- { "name": "Air::Play", "description": "blah blah blah", "version": "0.0.11", "authors": [ "librasteve" ], "auth": "zef:librasteve", "depends": [ "Air" ], "build-depends": [], "provides": { "Air::Play": "lib/Air/Play.rakumod", "Air::Play::SearchTable": "lib/Air/Play/SearchTable.rakumod", "Air::Play::Site00-Nano": "lib/Air/Play/Site00-Nano.rakumod", "Air::Play::Site01-Minimal": "lib/Air/Play/Site01-Minimal.rakumod", "Air::Play::Site02-Sections": "lib/Air/Play/Site02-Sections.rakumod", "Air::Play::Site03-Pages": "lib/Air/Play/Site03-Pages.rakumod", "Air::Play::Site04-HarcStack": "lib/Air/Play/Site04-HarcStack.rakumod", "Air::Play::Site05-PagesFunc": "lib/Air/Play/Site05-PagesFunc.rakumod", "Air::Play::Site06-Semantic": "lib/Air/Play/Site06-Semantic.rakumod", "Air::Play::Site07-BaseExamples": "lib/Air/Play/Site07-BaseExamples.rakumod", "Air::Play::Site08-SearchTable": "lib/Air/Play/Site08-SearchTable.rakumod", "Air::Play::Site09-Todos": "lib/Air/Play/Site09-Todos.rakumod", "Air::Play::Site10-Counter": "lib/Air/Play/Site10-Counter.rakumod", "Air::Play::Site11-Form": "lib/Air/Play/Site11-Form.rakumod", "Air::Play::Site12-FormShort": "lib/Air/Play/Site12-FormShort.rakumod", "Air::Play::Site13-FormRed": "lib/Air/Play/Site13-FormRed.rakumod", "Air::Play::Site14-CounterRed": "lib/Air/Play/Site14-CounterRed.rakumod", "Air::Play::Site15-TodosRed": "lib/Air/Play/Site15-TodosRed.rakumod" }, "license": "Artistic-2.0", "source-url": "https://github.com/librasteve/Air-Play.git" }
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2006, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: README.md ### ---------------------------------------------------- [![License: Artistic-2.0](https://img.shields.io/badge/License-Artistic%202.0-0298c3.svg)](https://opensource.org/licenses/Artistic-2.0) Please raise an Issue if you would like to feedback or assist. # Air::Play Playing with the hArc stack (HTMX, Air, Red, Cro) - https://harcstack.org. Some website with Pico CSS styling. # Local ## GETTING STARTED Install raku - eg. from [rakubrew](https://rakubrew.org), then: ### Install Air, Cro & Red - `zef install --/test cro` - `zef install Red --exclude="pq:ver<5>"` - `zef install https://github.com/librasteve/Air.git" ### Install this repo - `git clone https://github.com/librasteve/Air-Play.git` - `cd Air-Play` && `zef install .` ### Run and view it - `export WEBSITE_HOST="0.0.0.0" && export WEBSITE_PORT="3000"` - `raku -Ilib service.raku` - Open a browser and go to `http://localhost:3000` Select the example site you want by commenting out the others in the `Play.rakumod` file. You will note that cro has many other options as documented at [Cro](https://cro.raku.org) if you want to deploy to a production server. --- # Server ## Development ### Pico CSS (IntelliJ) install sass (in the static/css dir) - follow this [guide](https://www.jetbrains.com/help/webstorm/transpiling-sass-less-and-scss-to-css.html) - install IJ sass & file watcher plugins - `cd static/css` - `brew install npm` - `npm install -g sass` - `npm install @picocss/pico` - in styles.css, `@use "node_modules/@picocss/pico/scss";` - `sass styles.scss styles.css` [target is then styles.scss/styles] - `--load-path=node_modules/@picocss/pico/scss/` from https://picocss.com - some tweaks to root styles (mainly to reduce scale) from [here](https://github.com/picocss/pico/discussions/482) ## Deployment - Install Air, Cro & Red (see above) - `git clone https://github.com/librasteve/Air-Play.git && cd Air-Play` - `zef install . --force-install --/test` - adjust .cro.yml for your needs (e.g. HTTPS) -or- - `export WEBSITE_HOST="0.0.0.0" && export WEBSITE_PORT="3000"` - `raku -Ilib service.raku` -or- - `nohup raku -Ilib service.raku >> server.log 2>&1` <=== detach from terminal [note PID] - `tail -f server.log` and finally `kill -9 PID` [ps -ef | grep raku] ## Build this site runs on a linux server preloaded with git, raku, zef (& docker-compose) which can be set up with raku [CLI::AWS::EC2-Simple](https://raku.land/zef:librasteve/CLI::AWS::EC2-Simple) - `sudo apt-get install build-essential` (for Digest::SHA1::Native) - viz. https://chatgpt.com/share/6748a185-c690-8009-96ff-80bf8018dd7d - `sudo apt-get install nginx` - `sudo systemctl start nginx` - `sudo systemctl enable nginx` - etc - `vi simple.raku` <= port to 8888 - `raku simple.raku` - using librasteve for certbot --- # COPYRIGHT AND LICENSE Copyright(c) 2025 Henley Cloud Consulting Ltd. This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: .cro.yml ### ---------------------------------------------------- --- "cro": 1 "endpoints": - "host-env": "HTTP_HOST" "id": "http" "name": "HTTP" "port-env": "HTTP_PORT" "protocol": "http" "entrypoint": "service.raku" "env": [] "id": "http" "links": [] "name": "http" "ignore": - .iml - .iml~ - .idea/ - static/css/ ...
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: dist.ini ### ---------------------------------------------------- name = Air::Play [ReadmeFromPod] enabled = false #filename = lib/Air/Play.rakumod [UploadToZef] [Badges] provider = github-actions/test.yml
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: t/01-basic.rakutest ### ---------------------------------------------------- use Test; use Air::Play; pass "replace me"; done-testing;
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: static/css/package-lock.json ### ---------------------------------------------------- { "name": "css", "lockfileVersion": 3, "requires": true, "packages": { "": { "dependencies": { "@picocss/pico": "^2.0.6" } }, "node_modules/@picocss/pico": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/@picocss/pico/-/pico-2.0.6.tgz", "integrity": "sha512-/d8qsykowelD6g8k8JYgmCagOIulCPHMEc2NC4u7OjmpQLmtSetLhEbt0j1n3fPNJVcrT84dRp0RfJBn3wJROA==", "license": "MIT", "engines": { "node": ">=18.19.0" } } } }
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: static/css/package.json ### ---------------------------------------------------- { "dependencies": { "@picocss/pico": "^2.0.6" } }
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: static/css/node_modules/.package-lock.json ### ---------------------------------------------------- { "name": "css", "lockfileVersion": 3, "requires": true, "packages": { "node_modules/@picocss/pico": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/@picocss/pico/-/pico-2.0.6.tgz", "integrity": "sha512-/d8qsykowelD6g8k8JYgmCagOIulCPHMEc2NC4u7OjmpQLmtSetLhEbt0j1n3fPNJVcrT84dRp0RfJBn3wJROA==", "license": "MIT", "engines": { "node": ">=18.19.0" } } } }
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: static/css/node_modules/@picocss/pico/LICENSE.md ### ---------------------------------------------------- MIT License Copyright (c) 2019-2024 Pico Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: static/css/node_modules/@picocss/pico/README.md ### ---------------------------------------------------- <p> <a href="https://picocss.com" target="_blank"> <picture> <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/picocss/pico/HEAD/.github/logo-dark.svg"> <source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/picocss/pico/HEAD/.github/logo-light.svg"> <img alt="Pico CSS" src="https://raw.githubusercontent.com/picocss/pico/HEAD/.github/logo-light.svg" width="auto" height="60"> </picture> </a> </p> [![Github release](https://img.shields.io/github/v/release/picocss/pico?color=0172ad&logo=github&logoColor=white)](https://github.com/picocss/pico/releases/latest) [![npm version](https://img.shields.io/npm/v/@picocss/pico?color=0172ad)](https://www.npmjs.com/package/@picocss/pico) [![License](https://img.shields.io/badge/license-MIT-%230172ad)](https://github.com/picocss/pico/blob/master/LICENSE.md) [![Twitter URL](https://img.shields.io/twitter/url/https/twitter.com/picocss.svg?style=social&label=Follow%20%40picocss)](https://twitter.com/picocss) ## Minimal CSS Framework for Semantic HTML A minimalist and lightweight starter kit that prioritizes semantic syntax, making every HTML element responsive and elegant by default. Write HTML, Add Pico CSS, and Voilà! ## What’s new in v2? Pico v2.0 features better accessibility, easier customization with SASS, a complete color palette, a new group component, and 20 precompiled color themes totaling over 100 combinations routable via CDN. [Read more](https://picocss.com/docs/v2) ## A Superpowered HTML Reset With just the right amount of everything, Pico is great starting point for a clean and lightweight design system. - Class-light and Semantic - Great Styles with Just CSS - Responsive Everything - Light or Dark Mode - Easy Customization - Optimized Performance ## Table of contents - [Quick start](#quick-start) - [Class-less version](#class-less-version) - [Limitations](#limitations) - [Documentation](#documentation) - [Browser Support](#browser-support) - [Contributing](#contributing) - [Copyright and license](#copyright-and-license) ## Quick start There are 4 ways to get started with pico.css: ### Install manually [Download Pico](https://github.com/picocss/pico/archive/refs/heads/main.zip) and link `/css/pico.min.css` in the `<head>` of your website. ```html <link rel="stylesheet" href="css/pico.min.css" /> ``` ### Usage from CDN Alternatively, you can use [jsDelivr CDN](https://www.jsdelivr.com/package/npm/@picocss/pico) to link pico.css. ```html <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css" /> ``` ### Install with NPM ```shell npm install @picocss/pico ``` Or ```shell yarn add @picocss/pico ``` Then, import Pico into your SCSS file with [@use](https://sass-lang.com/documentation/at-rules/use): ```SCSS @use "pico"; ``` ### Install with Composer ```shell composer require picocss/pico ``` ### Starter HTML template ```HTML <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="color-scheme" content="light dark" /> <link rel="stylesheet" href="css/pico.min.css"> <title>Hello world!</title> </head> <body> <main class="container"> <h1>Hello world!</h1> </main> </body> </html> ``` ## Class-less version Pico provides a `.classless` version. In this version, `<header>`, `<main>`, and `<footer>` inside `<body>` act as containers to define a centered or a fluid viewport. Use the default `.classless` version if you need centered viewports: ```html <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.classless.min.css" /> ``` Or use the `.fluid.classless` version if you need a fluid container: ```html <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.fluid.classless.min.css" /> ``` Then just write pure HTML, and it should look great: ```html <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="color-scheme" content="light dark" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.classless.min.css" /> <title>Hello, world!</title> </head> <body> <main> <h1>Hello, world!</h1> </main> </body> </html> ``` ## Limitations Pico CSS can be used without custom CSS for quick or small projects. However, it’s designed as a starting point, like a “reset CSS on steroids”. As Pico does not integrate any helpers or utilities `.classes`, this minimal CSS framework requires SCSS or CSS knowledge to build large projects. [Read more](https://picocss.com/docs/usage-scenarios) ## Documentation **Getting started** - [Quick start](https://picocss.com/docs) - [Version picker `New`](https://picocss.com/docs/version-picker) - [Color schemes](https://picocss.com/docs/color-schemes) - [Class-less version](https://picocss.com/docs/classless) - [Conditional styling `New`](https://picocss.com/docs/conditional) - [RTL](https://picocss.com/docs/rtl) **Customization** - [CSS Variables](https://picocss.com/docs/css-variables) - [Sass](https://picocss.com/docs/sass) - [Colors `New`](https://picocss.com/docs/colors) **Layout** - [Container](https://picocss.com/docs/container) - [Landmarks & section](https://picocss.com/docs/landmarks-section) - [Grid](https://picocss.com/docs/grid) - [Overflow auto `New`](https://picocss.com/docs/overflow-auto) **Content** - [Typography](https://picocss.com/docs/typography) - [Link](https://picocss.com/docs/link) - [Button](https://picocss.com/docs/button) - [Table](https://picocss.com/docs/table) **Forms** - [Overview](https://picocss.com/docs/forms) - [Input](https://picocss.com/docs/forms/input) - [Textarea](https://picocss.com/docs/forms/textarea) - [Select](https://picocss.com/docs/forms/select) - [Checkboxes](https://picocss.com/docs/forms/checkboxes) - [Radios](https://picocss.com/docs/forms/radios) - [Switch](https://picocss.com/docs/forms/switch) - [Range](https://picocss.com/docs/forms/range) **Components** - [Accordion](https://picocss.com/docs/accordion) - [Card](https://picocss.com/docs/card) - [Dropdown](https://picocss.com/docs/dropdown) - [Group `New`](https://picocss.com/docs/group) - [Loading](https://picocss.com/docs/loading) - [Modal](https://picocss.com/docs/modal) - [Nav](https://picocss.com/docs/nav) - [Progress](https://picocss.com/docs/progress) - [Tooltip](https://picocss.com/docs/tooltip) **About** - [What’s new in v2?](https://picocss.com/docs/v2) - [Mission](https://picocss.com/docs/mission) - [Usage scenarios](https://picocss.com/docs/usage-scenarios) - [Brand](https://picocss.com/docs/brand) - [Built With](https://picocss.com/docs/built-with) ## Browser Support Pico CSS is designed and tested for the latest stable Chrome, Firefox, Edge, and Safari releases. It does not support any version of IE, including IE 11. ## Contributing If you are interested in contributing to Pico CSS, please read our [contributing guidelines](https://github.com/picocss/pico/blob/master/.github/CONTRIBUTING.md). ## Copyright and license Licensed under the [MIT License](https://github.com/picocss/pico/blob/master/LICENSE.md).
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: static/css/node_modules/@picocss/pico/package.json ### ---------------------------------------------------- { "name": "@picocss/pico", "version": "2.0.6", "description": "Minimal CSS Framework for semantic HTML", "author": "Lucas Larroche", "main": "css/pico.min.css", "homepage": "https://picocss.com", "license": "MIT", "repository": { "type": "git", "url": "git+https://github.com/picocss/pico.git" }, "publishConfig": { "tag": "next" }, "keywords": [ "css", "css-framework", "dark-mode", "dark-theme", "lightweight", "minimal", "minimalist", "minimalistic", "native-html", "scss-framework", "semantic" ], "bugs": { "url": "https://github.com/picocss/pico/issues" }, "scripts": { "✨": "run-s build", "build": "run-s start lint \"build:*\" done --silent", "dev": "nodemon -q --watch scss/ --ext scss --exec 'run-s build'", "lint": "run-s \"lint:*\" --silent", "lint:prettier": "prettier --write --log-level silent 'scss/**/*.scss'", "lint:sort-scss": "postcss --config scss ./scss/**/*.scss --replace", "build:css": "sass --no-source-map --style expanded --no-error-css scss/:css/", "build:themes": "node scripts/build-themes", "build:autoprefix": "postcss --config css --replace css/*.css !css/*.min.css", "build:minify": "cleancss -O1 --with-rebase --batch --batch-suffix .min css/*.css !css/*.min.css", "prelint": "echo '[@picocss/pico] ✨ Lint'", "prebuild:css": "echo '[@picocss/pico] ✨ Compile'", "prebuild:themes": "echo '[@picocss/pico] ✨ Compile themes'", "prebuild:autoprefix": "echo '[@picocss/pico] ✨ Autoprefix'", "prebuild:minify": "echo '[@picocss/pico] ✨ Minify'", "start": "echo '\\033[96m[@picocss/pico] ✨ Start\\033[0m'", "done": "echo '\\033[32m[@picocss/pico] ✨ Done\\033[0m'" }, "devDependencies": { "autoprefixer": "^10.4.18", "caniuse-lite": "1.0.30001591", "clean-css-cli": "^5.6.3", "css-declaration-sorter": "^7.1.1", "nodemon": "^3.1.0", "npm-run-all": "^4.1.5", "postcss": "^8.4.35", "postcss-cli": "^11.0.0", "postcss-scss": "^4.0.9", "prettier": "^3.2.5", "sass": "^1.71.1" }, "engines": { "node": ">=18.19.0" }, "browserslist": [ "defaults" ] }
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: static/css/node_modules/@picocss/pico/composer.json ### ---------------------------------------------------- { "name": "picocss/pico", "description": "Minimal CSS Framework for semantic HTML.", "keywords": [ "css", "css-framework", "dark-mode", "dark-theme", "lightweight", "minimal", "minimalist", "minimalistic", "native-html", "scss-framework", "semantic" ], "homepage": "https://picocss.com", "authors": [ { "name": "Lucas Larroche", "email": "[email protected]", "homepage": "https://lucaslarroche.com", "role": "Developer" } ], "support": { "issues": "https://github.com/picocss/pico/issues/" }, "license": "MIT" }
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: lib/Air/Play.rakumod ### ---------------------------------------------------- unit class Air::Play; #use Air::Play::Site00-Nano; #use Air::Play::Site01-Minimal; use Air::Play::Site02-Sections; #use Air::Play::Site03-Pages; #use Air::Play::Site04-HarcStack; #use Air::Play::Site05-PagesFunc; #use Air::Play::Site06-Semantic; #use Air::Play::Site07-BaseExamples; #use Air::Play::Site08-SearchTable; #use Air::Play::Site09-Todos; #use Air::Play::Site10-Counter; #use Air::Play::Site11-Form; #use Air::Play::Site12-FormShort; #use Air::Play::Site13-FormRed; #use Air::Play::Site14-CounterRed; #use Air::Play::Site15-TodosRed; sub routes is export { SITE.routes }
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: lib/Air/Play/Site00-Nano.rakumod ### ---------------------------------------------------- use Air::Functional :BASE; use Air::Base; sub SITE is export { site page main p "Yo baby!" }
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: lib/Air/Play/Site03-Pages.rakumod ### ---------------------------------------------------- use Air::Functional :BASE; use Air::Base; use Air::Component; class MyPage is Page { has $.title = 'hÅrc'; has $.description = 'HTMX, Air, Red, Cro'; has $.footer = Footer.new: p safe Q| Hypered with <a href="https://htmx.org" target="_blank">htmx</a>. Aloft on <a href="https://github.com/librasteve/Air" target="_blank"><b>&Aring;ir</b></a>. Remembered by <a href="https://fco.github.io/Red/" target="_blank">red</a>. Constructed in <a href="https://cro.raku.org" target="_blank">cro</a>. &nbsp;&amp;&nbsp; Styled by <a href="https://picocss.com" target="_blank">picocss</a>. |; } my %data = :thead[["Planet", "Hexameter (km)", "Distance to Sun (AU)", "Orbit (days)"],], :tbody[["Mercury", "4,880", "0.39", "88"], ["Venus" , "12,104", "0.72", "225"], ["Earth" , "12,742", "1.00", "365"], ["Mars" , "6,779", "1.52", "687"],], :tfoot[["Average", "9,126", "0.91", "341"],]; my $page1 = MyPage.new: Main.new: div [ h3 'Page 1'; table |%data, :class<striped>; ]; my $page2 = MyPage.new: Main.new: div [ h3 'Page 2'; table |%data; ]; my $nav = Nav.new: logo => span safe( '<a href="/">h<b>&Aring;</b>rc</a>' ), items => [Page1 => $page1, Page2 => $page2]; $page1.nav = $page2.nav = $nav; sub SITE is export { Site.new: pages => [$page1, $page2] }
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: lib/Air/Play/Site06-Semantic.rakumod ### ---------------------------------------------------- use Air::Functional :BASE; use Air::Base; use Air::Component; sub SITE is export { site page :styled-aside-on, [ header [ h1 'Welcome to My Blog'; nav :widgets(lightdark), [ :Home(internal :href<#home>), :Blog(internal :href<#blog>), :About(internal :href<#about>), :Contact(internal :href<#contact>), ]; ]; main [ div [ section :id<blog>, [ h2 'Latest Blog Posts'; article [ h3 'Semantic HTML in Action'; p 'Published on ', time(:datetime<2025-03-11>); img :src<img/layout.gif>; p 'The semantic HTML tags used on this page.'; button 'Read More'; ]; article [ h3 'The Importance of Semantic HTML'; p 'Published on ', time(:datetime<2025-02-27>); p 'Semantic HTML is crucial for accessibility, SEO, and maintainable code. In this post, we explore its benefits and best practices.'; button 'Read More'; ]; article [ h3 'Getting Started with Pico CSS'; p 'Published at ', time(:datetime<2025-02-20T15:30:00>, :mode<time>); p 'Pico CSS is a minimal CSS framework that makes designing beautiful websites easy. Learn how to get started in this beginner-friendly guide.'; button 'Read More'; ]; ]; section :id<contact>, [ h2 'Contact Us'; form [ label :for<name>, 'Name:'; input :type<text>, :id<name>, :name<name>, :required; label :for<email>, 'Email:'; input :type<email>, :id<email>, :name<email>, :required; label :for<message>, 'Message:'; textarea :id<message>, :name<message>, :required; button :type<submit>, 'Send'; ]; ]; ]; aside :id<about>, [ h2 'About Me'; p "I'm a web developer passionate about creating accessible and user-friendly websites."; h3 'Recent Posts'; ul [ li a :href<#>, 'The Future of Web Designs'; li a :href<#>, '10 CSS Tricks You Should Know'; li a :href<#>, 'Why Accessibility Matters'; ]; h3 'Follow Me'; nav [ :Twitter(external :href<#>), :GitHub(external :href<#>), :LinkedIn(external :href<#>), ]; ]; ]; footer p safe '&copy; 2025 My Blog. All rights reserved.'; ] }
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: lib/Air/Play/Site08-SearchTable.rakumod ### ---------------------------------------------------- use Air::Functional :BASE; use Air::Base; use Air::Component; use Air::Play::SearchTable; my &index = &page.assuming( #:REFRESH(1), title => 'hÅrc', description => 'HTMX, Air, Red, Cro', footer => footer p ['Aloft on ', b 'Åir'], ); sub SITE is export { site :register[SearchTable.new], index main div [ searchtable :id(0) ] }
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: lib/Air/Play/Site13-FormRed.rakumod ### ---------------------------------------------------- use Air::Functional :BASE; use Air::Base; use Air::Form; use Red:api<2>; model Contact does Form { has Int $.id is serial is hidden; has Str $.first-name is column is validated(%va<name>); has Str $.last-name is column is validated(%va<name>) is required; has Str $.email is column is validated(%va<email>) is required is email; has Str $.city is column is validated(%va<text>); method form-routes { self.init; self.submit: -> Contact $form { if $form.is-valid { note "Got form data: $form.form-data()"; self.finish: 'Contact info received!' } else { self.retry: $form } } } method ^populate($model) { for json-data() -> %record { $model.^create(|%record); } } } red-defaults “SQLite”; Contact.^create-table; Contact.^populate; #note Contact.^all.map({ $_.first-name ~ ' ' ~ $_.last-name }).join(", "); my $contact-form = Contact.empty; class Index is Page { has Str $.title = 'hÅrc'; has Str $.description = 'HTMX, Air, Red, Cro'; has Nav $.nav = nav( logo => span( safe '<a href="/">h<b>&Aring;</b>rc</a>' ), widgets => [lightdark], ); has Footer $.footer = footer p ['Aloft on ', b 'åir']; } sub index(*@a, *%h) { Index.new( |@a, |%h ) }; sub SITE is export { site :register[$contact-form], index main content [ h2 'Contact Form'; $contact-form; ]; } ##### Contact Data ##### use JSON::Fast; sub json-data { from-json q:to/END/; [ {"first-name": "Venus", "last-name": "Grimes", "email": "[email protected]", "city": "Ankara"}, {"first-name": "Fletcher", "last-name": "Owen", "email": "[email protected]", "city": "Niort"}, {"first-name": "William", "last-name": "Hale", "email": "[email protected]", "city": "Te Awamutu"}, {"first-name": "TaShya", "last-name": "Cash", "email": "[email protected]", "city": "Titagarh"}, {"first-name": "Kevyn", "last-name": "Hoover", "email": "[email protected]", "city": "Cuenca"}, {"first-name": "Jakeem", "last-name": "Walker", "email": "[email protected]", "city": "St. Andrä"}, {"first-name": "Malcolm", "last-name": "Trujillo", "email": "[email protected]", "city": "Fort Resolution"}, {"first-name": "Wynne", "last-name": "Rice", "email": "[email protected]", "city": "Kinross"}, {"first-name": "Evangeline", "last-name": "Klein", "email": "[email protected]", "city": "San Giovanni in Galdo"}, {"first-name": "Jennifer", "last-name": "Russell", "email": "[email protected]", "city": "Laives/Leifers"}, {"first-name": "Rama", "last-name": "Freeman", "email": "[email protected]", "city": "Flin Flon"}, {"first-name": "Jena", "last-name": "Mathis", "email": "[email protected]", "city": "Fort Simpson"}, {"first-name": "Alexandra", "last-name": "Maynard", "email": "[email protected]", "city": "Nazilli"}, {"first-name": "Tallulah", "last-name": "Haley", "email": "[email protected]", "city": "Bay Roberts"}, {"first-name": "Timon", "last-name": "Small", "email": "[email protected]", "city": "Girona"}, {"first-name": "Randall", "last-name": "Pena", "email": "[email protected]", "city": "Edam"}, {"first-name": "Conan", "last-name": "Vaughan", "email": "[email protected]", "city": "Nadiad"}, {"first-name": "Dora", "last-name": "Allen", "email": "[email protected]", "city": "Renfrew"}, {"first-name": "Aiko", "last-name": "Little", "email": "[email protected]", "city": "Delitzsch"}, {"first-name": "Jessamine", "last-name": "Bauer", "email": "[email protected]", "city": "Offida"}, {"first-name": "Gillian", "last-name": "Livingston", "email": "[email protected]", "city": "Saskatoon"}, {"first-name": "Laith", "last-name": "Nicholson", "email": "[email protected]", "city": "Tallahassee"}, {"first-name": "Paloma", "last-name": "Alston", "email": "[email protected]", "city": "Cache Creek"}, {"first-name": "Freya", "last-name": "Dunn", "email": "[email protected]", "city": "Heist-aan-Zee"}, {"first-name": "Griffin", "last-name": "Rice", "email": "[email protected]", "city": "Montpelier"}, {"first-name": "Catherine", "last-name": "West", "email": "[email protected]", "city": "Tarnów"}, {"first-name": "Jena", "last-name": "Chambers", "email": "[email protected]", "city": "Konya"}, {"first-name": "Neil", "last-name": "Rodriguez", "email": "[email protected]", "city": "Kraków"}, {"first-name": "Freya", "last-name": "Charles", "email": "[email protected]", "city": "Arzano"}, {"first-name": "Anastasia", "last-name": "Strong", "email": "[email protected]", "city": "Polpenazze del Garda"}, {"first-name": "Bell", "last-name": "Simon", "email": "[email protected]", "city": "Caxias do Sul"}, {"first-name": "Minerva", "last-name": "Allison", "email": "[email protected]", "city": "Rio de Janeiro"}, {"first-name": "Yoko", "last-name": "Dawson", "email": "[email protected]", "city": "Saint-Remy-Geest"}, {"first-name": "Nadine", "last-name": "Justice", "email": "[email protected]", "city": "Calgary"}, {"first-name": "Hoyt", "last-name": "Rosa", "email": "[email protected]", "city": "Mold"}, {"first-name": "Shafira", "last-name": "Noel", "email": "[email protected]", "city": "Kitzbühel"}, {"first-name": "Jin", "last-name": "Nunez", "email": "[email protected]", "city": "Dreieich"}, {"first-name": "Barbara", "last-name": "Gay", "email": "[email protected]", "city": "Overland Park"}, {"first-name": "Riley", "last-name": "Hammond", "email": "[email protected]", "city": "Smoky Lake"}, {"first-name": "Molly", "last-name": "Fulton", "email": "[email protected]", "city": "Montese"}, {"first-name": "Dexter", "last-name": "Owen", "email": "[email protected]", "city": "Bousval"}, {"first-name": "Kuame", "last-name": "Merritt", "email": "[email protected]", "city": "Solingen"}, {"first-name": "Maggie", "last-name": "Delgado", "email": "[email protected]", "city": "Tredegar"}, {"first-name": "Hanae", "last-name": "Washington", "email": "[email protected]", "city": "Amersfoort"}, {"first-name": "Jonah", "last-name": "Cherry", "email": "[email protected]", "city": "Acciano"}, {"first-name": "Cheyenne", "last-name": "Munoz", "email": "[email protected]", "city": "Saint-Léonard"}, {"first-name": "India", "last-name": "Mack", "email": "[email protected]", "city": "Maryborough"}, {"first-name": "Lael", "last-name": "Mcneil", "email": "[email protected]", "city": "Livorno"}, {"first-name": "Jillian", "last-name": "Mckay", "email": "[email protected]", "city": "Salvador"}, {"first-name": "Shaine", "last-name": "Wright", "email": "[email protected]", "city": "Newton Abbot"}, {"first-name": "Keane", "last-name": "Richmond", "email": "[email protected]", "city": "Canterano"}, {"first-name": "Samuel", "last-name": "Davis", "email": "[email protected]", "city": "Peterhead"}, {"first-name": "Zelenia", "last-name": "Sheppard", "email": "[email protected]", "city": "Motta Visconti"}, {"first-name": "Giacomo", "last-name": "Cole", "email": "[email protected]", "city": "Donnas"}, {"first-name": "Mason", "last-name": "Hinton", "email": "[email protected]", "city": "St. Asaph"}, {"first-name": "Katelyn", "last-name": "Koch", "email": "[email protected]", "city": "Cleveland"}, {"first-name": "Olga", "last-name": "Spencer", "email": "[email protected]", "city": "Karapınar"}, {"first-name": "Erasmus", "last-name": "Strong", "email": "[email protected]", "city": "Passau"}, {"first-name": "Regan", "last-name": "Cline", "email": "[email protected]", "city": "Pergola"}, {"first-name": "Stone", "last-name": "Holt", "email": "[email protected]", "city": "Houston"}, {"first-name": "Deanna", "last-name": "Branch", "email": "[email protected]", "city": "Olcenengo"}, {"first-name": "Rana", "last-name": "Green", "email": "[email protected]", "city": "Onze-Lieve-Vrouw-Lombeek"}, {"first-name": "Caryn", "last-name": "Henson", "email": "[email protected]", "city": "Kington"}, {"first-name": "Clarke", "last-name": "Stein", "email": "[email protected]", "city": "Tenali"}, {"first-name": "Kelsie", "last-name": "Porter", "email": "[email protected]", "city": "İskenderun"}, {"first-name": "Cooper", "last-name": "Pugh", "email": "[email protected]", "city": "Delhi"}, {"first-name": "Paul", "last-name": "Spencer", "email": "[email protected]", "city": "Biez"}, {"first-name": "Cassady", "last-name": "Farrell", "email": "[email protected]", "city": "New Maryland"}, {"first-name": "Sydnee", "last-name": "Velazquez", "email": "[email protected]", "city": "Stroe"}, {"first-name": "Felix", "last-name": "Boyle", "email": "[email protected]", "city": "Edinburgh"}, {"first-name": "Ryder", "last-name": "House", "email": "[email protected]", "city": "Copertino"}, {"first-name": "Hadley", "last-name": "Holcomb", "email": "[email protected]", "city": "Avadi"}, {"first-name": "Marsden", "last-name": "Nunez", "email": "[email protected]", "city": "New Galloway"}, {"first-name": "Alana", "last-name": "Powell", "email": "[email protected]", "city": "Pitt Meadows"}, {"first-name": "Dennis", "last-name": "Wyatt", "email": "[email protected]", "city": "Wrexham"}, {"first-name": "Karleigh", "last-name": "Walton", "email": "[email protected]", "city": "Diksmuide"}, {"first-name": "Brielle", "last-name": "Donovan", "email": "[email protected]", "city": "Kolmont"}, {"first-name": "Donna", "last-name": "Dickerson", "email": "[email protected]", "city": "Vallepietra"}, {"first-name": "Eagan", "last-name": "Pate", "email": "[email protected]", "city": "Durness"}, {"first-name": "Carlos", "last-name": "Ramsey", "email": "[email protected]", "city": "Tiruvottiyur"}, {"first-name": "Regan", "last-name": "Murphy", "email": "[email protected]", "city": "Candidoni"}, {"first-name": "Claudia", "last-name": "Spence", "email": "[email protected]", "city": "Augusta"}, {"first-name": "Genevieve", "last-name": "Parker", "email": "[email protected]", "city": "Forbach"}, {"first-name": "Marshall", "last-name": "Allison", "email": "[email protected]", "city": "Landau"}, {"first-name": "Reuben", "last-name": "Davis", "email": "[email protected]", "city": "Schönebeck"}, {"first-name": "Ralph", "last-name": "Doyle", "email": "[email protected]", "city": "Linkebeek"}, {"first-name": "Constance", "last-name": "Gilliam", "email": "[email protected]", "city": "Enterprise"}, {"first-name": "Serina", "last-name": "Jacobson", "email": "[email protected]", "city": "Hérouville-Saint-Clair"}, {"first-name": "Charity", "last-name": "Byrd", "email": "[email protected]", "city": "Brussegem"}, {"first-name": "Hyatt", "last-name": "Bird", "email": "[email protected]", "city": "Gdynia"}, {"first-name": "Brent", "last-name": "Dunn", "email": "[email protected]", "city": "Hay-on-Wye"}, {"first-name": "Casey", "last-name": "Bonner", "email": "[email protected]", "city": "Kearny"}, {"first-name": "Hakeem", "last-name": "Gill", "email": "[email protected]", "city": "Portico e San Benedetto"}, {"first-name": "Stewart", "last-name": "Meadows", "email": "[email protected]", "city": "Dignano"}, {"first-name": "Nomlanga", "last-name": "Wooten", "email": "[email protected]", "city": "Troon"}, {"first-name": "Sebastian", "last-name": "Watts", "email": "[email protected]", "city": "Palermo"}, {"first-name": "Chelsea", "last-name": "Larsen", "email": "[email protected]", "city": "Poole"}, {"first-name": "Cameron", "last-name": "Humphrey", "email": "[email protected]", "city": "Manfredonia"}, {"first-name": "Juliet", "last-name": "Bush", "email": "[email protected]", "city": "Lavacherie"}, {"first-name": "Caryn", "last-name": "Hooper", "email": "[email protected]", "city": "Amelia"} ] END }
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: lib/Air/Play/Site15-TodosRed.rakumod ### ---------------------------------------------------- use Air::Functional :BASE; use Air::Base; use Air::Component; use Red:api<2>; red-defaults “SQLite”; role HxTodo { method hx-create(--> Hash()) { :hx-post("todo"), :hx-target<table>, :hx-swap<beforeend>, } method hx-delete(--> Hash()) { :hx-delete("todo/$.id"), :hx-confirm<Are you sure?>, :hx-target<closest tr>, :hx-swap<delete>, } method hx-toggle(--> Hash()) { :hx-get("todo/$.id/toggle"), :hx-target<closest tr>, :hx-swap<outerHTML>, } } model Todo does Component::Red[:C:R:U:D] { also does HxTodo; has UInt $.id is serial; has Bool $.checked is rw is column = False; has Str $.text is column is required; method toggle is controller { $!checked = !$!checked; $.^save; self } method HTML { tr td( input :type<checkbox>, |$.hx-toggle, :$!checked ), td( $!checked ?? del $!text !! $!text), td( button :type<submit>, |$.hx-delete, :style<width:50px>, '-'), } } Todo.^create-table; my &index = &page.assuming( title => 'hÅrc', description => 'HTMX, Air, Red, Cro', footer => footer p ['Aloft on ', b 'Åir'], ); for <one two> -> $text { Todo.^create: :$text }; sub SITE is export { site :register(Todo), index main [ h3 'Todos'; table Todo.^all; form |Todo.hx-create, [ input :name<text>; button :type<submit>, '+'; ]; ] }
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: lib/Air/Play/Site09-Todos.rakumod ### ---------------------------------------------------- use Air::Functional :BASE; use Air::Base; use Air::Component; role HxTodo { method hx-add(--> Hash()) { :hx-post("todo"), :hx-target<table>, :hx-swap<beforeend>, } method hx-delete(--> Hash()) { :hx-delete($.url-path), :hx-confirm<Are you sure?>, :hx-target<closest tr>, :hx-swap<delete>, } method hx-toggle(--> Hash()) { :hx-get("$.url-path/toggle"), :hx-target<closest tr>, :hx-swap<outerHTML>, } } class Todo does Component[:C:R:U:D] { also does HxTodo; has Bool $.checked is rw = False; has Str $.text; method toggle is controller { $!checked = !$!checked; self } multi method HTML { tr td( input :type<checkbox>, |$.hx-toggle, :$!checked ), td( $!checked ?? del $!text !! $!text), td( button :type<submit>, |$.hx-delete, :style<width:50px>, '-'), } } my &index = &page.assuming( title => 'hÅrc', description => 'HTMX, Air, Red, Cro', footer => footer p ['Aloft on ', b 'Åir'], ); for <one two> -> $text { Todo.new: :$text }; sub SITE is export { site :register(Todo), index main [ h3 'Todos'; table Todo.all; form |Todo.hx-add, [ input :name<text>; button :type<submit>, '+'; ]; ] }
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: lib/Air/Play/Site14-CounterRed.rakumod ### ---------------------------------------------------- use Air::Functional :BASE; use Air::Base; use Air::Component; use Red:api<2>; red-defaults “SQLite”; my &index = &page.assuming( title => 'hÅrc', description => 'HTMX, Air, Red, Cro', footer => footer p ['Aloft on ', b 'Åir'], ); model Counter does Component::Red { has UInt $.id is serial; has Int $.count is rw is column(:default{0}); method increment is controller { $!count++; $.^save; self } method hx-increment(--> Hash()) { :hx-get("counter/$.id/increment"), :hx-target("#counter-$.id"), :hx-swap<outerHTML>, :hx-trigger<submit>, } method HTML { input :id("counter-$.id"), :name("counter"), :value($!count) } } Counter.^create-table; my $counter = Counter.^create; sub SITE is export { site :register[$counter], #:theme-color<red>, index main form |$counter.hx-increment, [ h3 'Counter:'; ~$counter; button :type<submit>, '+'; ] }
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: lib/Air/Play/Site04-HarcStack.rakumod ### ---------------------------------------------------- use Air::Functional :BASE; use Air::Base; use Air::Component; my $htmx = external :href<https://htmx.org>; my $air = external :href<https://github.com/librasteve/Air>; my $red = external :href<https://github.com/FCO/Red>; my $cro = external :href<https://cro.raku.org>; my $raku = external :href<https://raku.org>; my $talk = external :href<https://discord.gg/VzYpdQ6>; my &index = &page.assuming( #:REFRESH(5), title => 'hÅrc', description => 'HTMX, Air, Red, Cro', nav => nav( logo => span( safe '<a href="/">h<b>&Aring;</b>rc</a>' ), items => [:$htmx,:$air,:$red,:$cro,:$raku,:$talk], widgets => [lightdark], ), footer => footer( p safe Q| Hypered with <a href="https://htmx.org" target="_blank">htmx</a>. Aloft on <a href="https://github.com/librasteve/Air" target="_blank"><b>&Aring;ir</b></a>. Remembered by <a href="https://fco.github.io/Red/" target="_blank">red</a>. Constructed in <a href="https://cro.raku.org" target="_blank">cro</a>. &nbsp;&amp;&nbsp; Styled by <a href="https://picocss.com" target="_blank">picocss</a>. |), ); my @tools = [Analytics.new: :provider(Umami), :key<35777f61-5123-4bb8-afb1-aced487af36e>,]; sub SITE is export { site :theme-color<azure>, :bold-color<maroon>, :@tools, index main [ div [ h2 'The hArc Stack'; # p 'Combining HTMX with raku Air, Red and Cro so that you can ', # em 'just build websites the right way™', '.'; figure [ img :src</img/Site10-Counter.png>, :alt<"hArc stack example code">, :style<width: 100%; max-width: 1024px; height: auto;>; figcaption 'hArc example code shown in IntelliJ IDE with raku plugin 2.0.'; ]; # p safe 'hArc stands for "HTMX, Air, Red, Cro" - the <a href="https://raku.land/zef:librasteve/Air">Air raku module </a> is the "glue" that makes the stack. There\'s also the <a href="https://raku.land/zef:librasteve/Air::Play">Air::Play module</a> for website examples and Getting Started instructions.'; hr; h2 'HTMX: Server Side'; p 'HTMX provides server side website code with the dynamic and attractive UX of a reactive JavaScript SPA. It extends HTML with attributes ike:'; ul [ li [ code 'hx-get="/data"'; ' → Fetches data via GET.' ]; li [ code 'hx-post="/submit"'; ' → Submits a form via POST.' ]; li [ code 'hx-target="#result"'; ' → Updates a specific part of the page.' ]; li [ code 'hx-swap="outerHTML"'; ' → Controls how content is replaced.' ]; ]; p 'It\'s a lightweight, declarative way to enhance interactivity while keeping your application state and server code simple.'; hr; h2 'Air: Code Clarity'; p 'Air aims to be the purest possible expression of HTMX, ensuring that hArc websites are built with a focus on content and layout rather than embedded markup. By embracing a functional coding style for composition, Air improves code clarity. It consists of a set of libraries that generate HTML and serve it via Cro, that results in concise, legible, and maintainable web applications.'; hr; h2 'Red: Data Model'; p 'Red is a powerful ORM (Object-Relational Mapper) for raku that provides an intuitive way to interact with databases. It supports various database backends and enables developers to model their data using raku’s expressive type system. Red simplifies database operations with a declarative syntax, making it easy to define schemas, query data, and perform complex transactions while maintaining the flexibility and safety of raku’s type system.'; hr; h2 'Cro: Web Services'; p 'Cro is raku’s ecosystem for building web services, offering a modular framework for creating HTTP applications, APIs, and real-time services. It provides a powerful and extensible pipeline-based architecture, making it easy to build scalable and maintainable applications. Cro’s built-in support for WebSockets, middleware, and async processing ensures that hArc applications can handle real-time interactions efficiently.'; hr; h2 'Raku: Language Toolkit'; p 'With support for functional, object-oriented, and reactive programming paradigms, raku is a language toolkit for developers to build concise and maintainable websites. A powerful concurrency model, grammars, and metaprogramming capabilities make it well-suited for more advanced web applications. This gradually-typed scripting language makes easy things easy and hard things possible.'; p '~librasteve'; ]; ]; }
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: lib/Air/Play/Site10-Counter.rakumod ### ---------------------------------------------------- use Air::Functional :BASE; use Air::Base; use Air::Component; my &index = &page.assuming( #:REFRESH(5), title => 'hÅrc', description => 'HTMX, Air, Red, Cro', footer => footer p ['Aloft on ', b 'Åir'], ); class Counter does Component { has Int $.count = 0; method increment is controller { $!count++; self } method hx-increment(--> Hash()) { :hx-get("counter/$.id/increment"), :hx-target("#counter-$.id"), :hx-swap<outerHTML>, :hx-trigger<submit>, } method HTML { input :id("counter-$.id"), :name("counter"), :value($!count) } } my $counter = Counter.new; sub SITE is export { site :register[$counter], #:theme-color<red>, index main form |$counter.hx-increment, [ h3 'Counter:'; ~$counter; button :type<submit>, '+'; ] }
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: lib/Air/Play/Site02-Sections.rakumod ### ---------------------------------------------------- use Air::Functional :BASE; use Air::Base; use Air::Component; # content my %data = :thead[["Planet", "Diameter (km)", "Distance to Sun (AU)", "Orbit (days)"],], :tbody[ ["Mercury", "4,880", "0.39", "88"], ["Venus" , "12,104", "0.72", "225"], ["Earth" , "12,742", "1.00", "365"], ["Mars" , "6,779", "1.52", "687"], ], :tfoot[["Average", "9,126", "0.91", "341"],]; my $Content1 = content [ h3 'Content 1'; table |%data, :class<striped>; ]; my $Content2 = content [ h3 'Content 2'; table |%data; ]; my $Google = external :href<https://google.com>; # theme my &index = &page.assuming( #:REFRESH(5), title => 'hÅrc', description => 'HTMX, Air, Red, Cro', nav => nav( logo => span( safe '<a href="/">h<b>&Aring;</b>rc</a>' ), items => [:$Content1, :$Content2, :$Google], widgets => [lightdark], ), footer => footer p ['Aloft on ', b 'åir'], ); # site sub SITE is export { site :bold-color<maroon>, index main $Content1 }
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: lib/Air/Play/Site11-Form.rakumod ### ---------------------------------------------------- use Air::Functional :BASE; use Air::Base; use Air::Form; class Contact does Form { has Str $.name is validated(%va<text>) is required; has Str $.street is validated(%va<text>); has Str $.city is validated(%va<text>); has Str $.state is validated(%va<text>); has Str $.zip is validated(%va<postcode>); has Str $.country is validated(%va<words>) is placeholder('USA'); has Bool $.is-company; has Str $.company is validated(%va<text>); has Str $.url is validated(%va<url>) is url ; has Str $.phone is validated(%va<tel>) is tel; has Str $.email is validated(%va<email>) is email is required; has Str $.password is validated(%va<password>) is password; has Int $.rating will select { 1..5 }; has Str $.comment is validated(%va<notes>) is multiline(:5rows, :60cols) is maxlength(400); has $.date is date is help("Leave blank for today's date"); has Str $.hidden is hidden; method do-form-attrs{ self.form-attrs: {:submit-button-text('Save Contact Info')} } method validate-form { if $!is-company && ! $!company { self.add-validation-error("Please fill in the Company field") } if $!company && ! $!is-company { self.add-validation-error("Please check the Is company box") } given $!date { when '' { $!date = Date.new: now } default { $!date = Date.new: $!date } } } method form-routes { self.init; self.submit: -> Contact $form { if $form.is-valid { note "Got form data: $form.form-data()"; self.finish: 'Contact info received!' } else { self.retry: $form } } } } my $contact = Contact.empty; class Index is Page { has Str $.title = 'hÅrc'; has Str $.description = 'HTMX, Air, Red, Cro'; has Footer $.footer = footer p ['Aloft on ', b 'åir']; } sub index(*@a, *%h) { Index.new( |@a, |%h ) }; sub SITE is export { site :register[$contact], #:theme-color<red>, index main [ h2 'Contact Form'; $contact; ] }
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: lib/Air/Play/Site05-PagesFunc.rakumod ### ---------------------------------------------------- use Air::Functional :BASE; use Air::Base; ### PAGE TEMPLATE ### class MyPage is Page { has Str $.title = 'hÅrc'; has Str $.description = 'HTMX, Air, Red, Cro'; has Footer $.footer = footer( p safe Q| Hypered with <a href="https://htmx.org" target="_blank">htmx</a>. Aloft on <a href="https://github.com/librasteve/Air" target="_blank"><b>&Aring;ir</b></a>. Remembered by <a href="https://fco.github.io/Red/" target="_blank">red</a>. Constructed in <a href="https://cro.raku.org" target="_blank">cro</a>. &nbsp;&amp;&nbsp; Styled by <a href="https://picocss.com" target="_blank">picocss</a>. |), } sub mypage(*@a, *%h) { MyPage.new( |@a, |%h ) }; ### SITE CONTENT ### sub planets(--> Hash) { { :thead[["Planet", "Hexameter (km)", "Distance to Sun (AU)", "Orbit (days)"],], :tbody[["Mercury", "4,880", "0.39", "88"], ["Venus" , "12,104", "0.72", "225"], ["Earth" , "12,742", "1.00", "365"], ["Mars" , "6,779", "1.52", "687"],], :tfoot[["Average", "9,126", "0.91", "341"],] } } my Page $Page1 = mypage main div [ h3 'Page 1'; table |planets, :class<striped>; ]; my Page $Page2 = mypage main div [ h3 'Page 2'; table |planets; ]; my Nav $nav = nav logo => span safe( '<a href="/">h<b>&Aring;</b>rc</a>' ), items => [:$Page1, :$Page2], widgets => [lightdark]; my Page @pages = [$Page1, $Page2]; { .nav = $nav } for @pages; sub SITE is export {site :@pages}
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: lib/Air/Play/Site01-Minimal.rakumod ### ---------------------------------------------------- use Air::Functional :BASE; use Air::Base; my &planets = &table.assuming( :class<striped>, :thead[["Planet", "Diameter (km)", "Distance to Sun (AU)", "Orbit (days)"],], :tbody[["Mercury", "4,880", "0.39", "88"], ["Venus" , "12,104", "0.72", "225"], ["Earth" , "12,742", "1.00", "365"], ["Mars" , "6,779", "1.52", "687"],], :tfoot[["Average", "9,126", "0.91", "341"],], ); my &index = &page.assuming( #:REFRESH(5), title => 'hÅrc', description => 'HTMX, Air, Red, Cro', footer => footer p ['Aloft on ', b 'Åir'], ); sub SITE is export { site :bold-color<blue>, index main div [ h3 'Planetary Table'; planets; ] }
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: lib/Air/Play/SearchTable.rakumod ### ---------------------------------------------------- use Air::Functional; use Air::Component; my @components = <SearchTable>; use Red:api<2>; model Person { has Int $.id is serial; has Str $.firstName is column; has Str $.lastName is column; has Str $.email is column; has Str $.city is column; method ^populate($model) { for json-data() -> %record { $model.^create(|%record); } } } red-defaults “SQLite”; Person.^create-table; Person.^populate; # Verify test records were created #note Person.^all.map({ $_.firstName ~ ' ' ~ $_.lastName }).join(", "); role HxSearchBox { method hx-search-box(--> Hash()) { :hx-put("{self.url}/{self.id}/search"), :hx-trigger<keyup changed delay:500ms, search>, :hx-target<#search-results>, :hx-swap<outerHTML>, :hx-indicator<.htmx-indicator>, } } class SearchBox does HxSearchBox { has $.url; has $.id; has $.title; multi method HTML { div [ h3 [ $!title, span :class<htmx-indicator>, [img :src</img/bars.svg>; ' Searching...'] ]; input :type<search>, :name<needle>, |$.hx-search-box, :placeholder<Begin typing to search...>; ] } } class Results does Component { has @.data is rw = []; multi method HTML { tbody :id<search-results>, do for @!data { tr td .firstName, td .lastName, td .email } } } class SearchTable does Component { has Str $.title = 'Search'; has $.thead = <First Last Email>; has SearchBox $.searchbox .= new: :url(self.url), :id(self.id), :$!title; has Results $.results .= new; method thead { tr do for |$!thead -> $cell { th :scope<col>, $cell } } method search(:$needle) is controller{:http-method('PUT')} { sub check($_) { .fc.contains($needle.fc) } $!results.data = Person.^all.grep: { $_.firstName.&check || $_.lastName.&check || $_.email.&check }; $!results; } multi method HTML { [ $!searchbox.HTML; table :class<striped>, [ thead $.thead; tbody :id<search-results>; ]; ] } } ##### HTML Functional Export ##### # put in all the tags programmatically # viz. https://docs.raku.org/language/modules#Exporting_and_selective_importing my package EXPORT::DEFAULT { for @components -> $name { OUR::{'&' ~ $name.lc} := sub (*@a, *%h) { ::($name).new( |@a, |%h ).HTML; } } } ##### Person Data ##### use JSON::Fast; sub json-data { from-json q:to/END/; [ {"firstName": "Venus", "lastName": "Grimes", "email": "[email protected]", "city": "Ankara"}, {"firstName": "Fletcher", "lastName": "Owen", "email": "[email protected]", "city": "Niort"}, {"firstName": "William", "lastName": "Hale", "email": "[email protected]", "city": "Te Awamutu"}, {"firstName": "TaShya", "lastName": "Cash", "email": "[email protected]", "city": "Titagarh"}, {"firstName": "Kevyn", "lastName": "Hoover", "email": "[email protected]", "city": "Cuenca"}, {"firstName": "Jakeem", "lastName": "Walker", "email": "[email protected]", "city": "St. Andrä"}, {"firstName": "Malcolm", "lastName": "Trujillo", "email": "[email protected]", "city": "Fort Resolution"}, {"firstName": "Wynne", "lastName": "Rice", "email": "[email protected]", "city": "Kinross"}, {"firstName": "Evangeline", "lastName": "Klein", "email": "[email protected]", "city": "San Giovanni in Galdo"}, {"firstName": "Jennifer", "lastName": "Russell", "email": "[email protected]", "city": "Laives/Leifers"}, {"firstName": "Rama", "lastName": "Freeman", "email": "[email protected]", "city": "Flin Flon"}, {"firstName": "Jena", "lastName": "Mathis", "email": "[email protected]", "city": "Fort Simpson"}, {"firstName": "Alexandra", "lastName": "Maynard", "email": "[email protected]", "city": "Nazilli"}, {"firstName": "Tallulah", "lastName": "Haley", "email": "[email protected]", "city": "Bay Roberts"}, {"firstName": "Timon", "lastName": "Small", "email": "[email protected]", "city": "Girona"}, {"firstName": "Randall", "lastName": "Pena", "email": "[email protected]", "city": "Edam"}, {"firstName": "Conan", "lastName": "Vaughan", "email": "[email protected]", "city": "Nadiad"}, {"firstName": "Dora", "lastName": "Allen", "email": "[email protected]", "city": "Renfrew"}, {"firstName": "Aiko", "lastName": "Little", "email": "[email protected]", "city": "Delitzsch"}, {"firstName": "Jessamine", "lastName": "Bauer", "email": "[email protected]", "city": "Offida"}, {"firstName": "Gillian", "lastName": "Livingston", "email": "[email protected]", "city": "Saskatoon"}, {"firstName": "Laith", "lastName": "Nicholson", "email": "[email protected]", "city": "Tallahassee"}, {"firstName": "Paloma", "lastName": "Alston", "email": "[email protected]", "city": "Cache Creek"}, {"firstName": "Freya", "lastName": "Dunn", "email": "[email protected]", "city": "Heist-aan-Zee"}, {"firstName": "Griffin", "lastName": "Rice", "email": "[email protected]", "city": "Montpelier"}, {"firstName": "Catherine", "lastName": "West", "email": "[email protected]", "city": "Tarnów"}, {"firstName": "Jena", "lastName": "Chambers", "email": "[email protected]", "city": "Konya"}, {"firstName": "Neil", "lastName": "Rodriguez", "email": "[email protected]", "city": "Kraków"}, {"firstName": "Freya", "lastName": "Charles", "email": "[email protected]", "city": "Arzano"}, {"firstName": "Anastasia", "lastName": "Strong", "email": "[email protected]", "city": "Polpenazze del Garda"}, {"firstName": "Bell", "lastName": "Simon", "email": "[email protected]", "city": "Caxias do Sul"}, {"firstName": "Minerva", "lastName": "Allison", "email": "[email protected]", "city": "Rio de Janeiro"}, {"firstName": "Yoko", "lastName": "Dawson", "email": "[email protected]", "city": "Saint-Remy-Geest"}, {"firstName": "Nadine", "lastName": "Justice", "email": "[email protected]", "city": "Calgary"}, {"firstName": "Hoyt", "lastName": "Rosa", "email": "[email protected]", "city": "Mold"}, {"firstName": "Shafira", "lastName": "Noel", "email": "[email protected]", "city": "Kitzbühel"}, {"firstName": "Jin", "lastName": "Nunez", "email": "[email protected]", "city": "Dreieich"}, {"firstName": "Barbara", "lastName": "Gay", "email": "[email protected]", "city": "Overland Park"}, {"firstName": "Riley", "lastName": "Hammond", "email": "[email protected]", "city": "Smoky Lake"}, {"firstName": "Molly", "lastName": "Fulton", "email": "[email protected]", "city": "Montese"}, {"firstName": "Dexter", "lastName": "Owen", "email": "[email protected]", "city": "Bousval"}, {"firstName": "Kuame", "lastName": "Merritt", "email": "[email protected]", "city": "Solingen"}, {"firstName": "Maggie", "lastName": "Delgado", "email": "[email protected]", "city": "Tredegar"}, {"firstName": "Hanae", "lastName": "Washington", "email": "[email protected]", "city": "Amersfoort"}, {"firstName": "Jonah", "lastName": "Cherry", "email": "[email protected]", "city": "Acciano"}, {"firstName": "Cheyenne", "lastName": "Munoz", "email": "[email protected]", "city": "Saint-Léonard"}, {"firstName": "India", "lastName": "Mack", "email": "[email protected]", "city": "Maryborough"}, {"firstName": "Lael", "lastName": "Mcneil", "email": "[email protected]", "city": "Livorno"}, {"firstName": "Jillian", "lastName": "Mckay", "email": "[email protected]", "city": "Salvador"}, {"firstName": "Shaine", "lastName": "Wright", "email": "[email protected]", "city": "Newton Abbot"}, {"firstName": "Keane", "lastName": "Richmond", "email": "[email protected]", "city": "Canterano"}, {"firstName": "Samuel", "lastName": "Davis", "email": "[email protected]", "city": "Peterhead"}, {"firstName": "Zelenia", "lastName": "Sheppard", "email": "[email protected]", "city": "Motta Visconti"}, {"firstName": "Giacomo", "lastName": "Cole", "email": "[email protected]", "city": "Donnas"}, {"firstName": "Mason", "lastName": "Hinton", "email": "[email protected]", "city": "St. Asaph"}, {"firstName": "Katelyn", "lastName": "Koch", "email": "[email protected]", "city": "Cleveland"}, {"firstName": "Olga", "lastName": "Spencer", "email": "[email protected]", "city": "Karapınar"}, {"firstName": "Erasmus", "lastName": "Strong", "email": "[email protected]", "city": "Passau"}, {"firstName": "Regan", "lastName": "Cline", "email": "[email protected]", "city": "Pergola"}, {"firstName": "Stone", "lastName": "Holt", "email": "[email protected]", "city": "Houston"}, {"firstName": "Deanna", "lastName": "Branch", "email": "[email protected]", "city": "Olcenengo"}, {"firstName": "Rana", "lastName": "Green", "email": "[email protected]", "city": "Onze-Lieve-Vrouw-Lombeek"}, {"firstName": "Caryn", "lastName": "Henson", "email": "[email protected]", "city": "Kington"}, {"firstName": "Clarke", "lastName": "Stein", "email": "[email protected]", "city": "Tenali"}, {"firstName": "Kelsie", "lastName": "Porter", "email": "[email protected]", "city": "İskenderun"}, {"firstName": "Cooper", "lastName": "Pugh", "email": "[email protected]", "city": "Delhi"}, {"firstName": "Paul", "lastName": "Spencer", "email": "[email protected]", "city": "Biez"}, {"firstName": "Cassady", "lastName": "Farrell", "email": "[email protected]", "city": "New Maryland"}, {"firstName": "Sydnee", "lastName": "Velazquez", "email": "[email protected]", "city": "Stroe"}, {"firstName": "Felix", "lastName": "Boyle", "email": "[email protected]", "city": "Edinburgh"}, {"firstName": "Ryder", "lastName": "House", "email": "[email protected]", "city": "Copertino"}, {"firstName": "Hadley", "lastName": "Holcomb", "email": "[email protected]", "city": "Avadi"}, {"firstName": "Marsden", "lastName": "Nunez", "email": "[email protected]", "city": "New Galloway"}, {"firstName": "Alana", "lastName": "Powell", "email": "[email protected]", "city": "Pitt Meadows"}, {"firstName": "Dennis", "lastName": "Wyatt", "email": "[email protected]", "city": "Wrexham"}, {"firstName": "Karleigh", "lastName": "Walton", "email": "[email protected]", "city": "Diksmuide"}, {"firstName": "Brielle", "lastName": "Donovan", "email": "[email protected]", "city": "Kolmont"}, {"firstName": "Donna", "lastName": "Dickerson", "email": "[email protected]", "city": "Vallepietra"}, {"firstName": "Eagan", "lastName": "Pate", "email": "[email protected]", "city": "Durness"}, {"firstName": "Carlos", "lastName": "Ramsey", "email": "[email protected]", "city": "Tiruvottiyur"}, {"firstName": "Regan", "lastName": "Murphy", "email": "[email protected]", "city": "Candidoni"}, {"firstName": "Claudia", "lastName": "Spence", "email": "[email protected]", "city": "Augusta"}, {"firstName": "Genevieve", "lastName": "Parker", "email": "[email protected]", "city": "Forbach"}, {"firstName": "Marshall", "lastName": "Allison", "email": "[email protected]", "city": "Landau"}, {"firstName": "Reuben", "lastName": "Davis", "email": "[email protected]", "city": "Schönebeck"}, {"firstName": "Ralph", "lastName": "Doyle", "email": "[email protected]", "city": "Linkebeek"}, {"firstName": "Constance", "lastName": "Gilliam", "email": "[email protected]", "city": "Enterprise"}, {"firstName": "Serina", "lastName": "Jacobson", "email": "[email protected]", "city": "Hérouville-Saint-Clair"}, {"firstName": "Charity", "lastName": "Byrd", "email": "[email protected]", "city": "Brussegem"}, {"firstName": "Hyatt", "lastName": "Bird", "email": "[email protected]", "city": "Gdynia"}, {"firstName": "Brent", "lastName": "Dunn", "email": "[email protected]", "city": "Hay-on-Wye"}, {"firstName": "Casey", "lastName": "Bonner", "email": "[email protected]", "city": "Kearny"}, {"firstName": "Hakeem", "lastName": "Gill", "email": "[email protected]", "city": "Portico e San Benedetto"}, {"firstName": "Stewart", "lastName": "Meadows", "email": "[email protected]", "city": "Dignano"}, {"firstName": "Nomlanga", "lastName": "Wooten", "email": "[email protected]", "city": "Troon"}, {"firstName": "Sebastian", "lastName": "Watts", "email": "[email protected]", "city": "Palermo"}, {"firstName": "Chelsea", "lastName": "Larsen", "email": "[email protected]", "city": "Poole"}, {"firstName": "Cameron", "lastName": "Humphrey", "email": "[email protected]", "city": "Manfredonia"}, {"firstName": "Juliet", "lastName": "Bush", "email": "[email protected]", "city": "Lavacherie"}, {"firstName": "Caryn", "lastName": "Hooper", "email": "[email protected]", "city": "Amelia"} ] END }
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: lib/Air/Play/Site12-FormShort.rakumod ### ---------------------------------------------------- # form use Air::Form; class Contact does Form { has Str $.first-names is validated(%va<names>); has Str $.last-name is validated(%va<name>) is required; has Str $.email is validated(%va<email>) is required is email; has Str $.city is validated(%va<text>); method form-routes { self.init; self.submit: -> Contact $form { if $form.is-valid { note "Got form data: $form.form-data()"; self.finish: 'Contact info received!' } else { self.retry: $form } } } } my $contact-form = Contact.empty; # site use Air::Functional :BASE; use Air::Base; class Index is Page { has Str $.title = 'hÅrc'; has Str $.description = 'HTMX, Air, Red, Cro'; has Nav $.nav = nav( logo => span( safe '<a href="/">h<b>&Aring;</b>rc</a>' ), widgets => [lightdark], ); has Footer $.footer = footer p ['Aloft on ', b 'åir']; } sub index(*@a, *%h) { Index.new( |@a, |%h ) }; sub SITE is export { site :register[$contact-form], index main content [ h2 'Contact Form'; $contact-form; ]; }
### ---------------------------------------------------- ### -- Air::Play ### -- Licenses: Artistic-2.0 ### -- Authors: librasteve ### -- File: lib/Air/Play/Site07-BaseExamples.rakumod ### ---------------------------------------------------- use Air::Functional :BASE; use Air::Base; use Air::Component; my &index = &page.assuming( #:REFRESH(1), title => 'hÅrc', description => 'HTMX, Air, Red, Cro', footer => footer p ['Aloft on ', b 'Åir'], ); sub SITE is export { site #:theme-color<blue>, index #:REFRESH(5), main div [ h3 'Table'; table [[1,2],[3,4]], :thead[<Left Right>,]; h3 'Grid'; grid [span $_ for 1..17]; h3 'Button'; div :role<group>, [ button 'Button'; button 'Secondary', :class<secondary>; button 'Contrast', :class<contrast>; button 'Outline', :class<secondary outline>; button 'Disabled', :class<outline> :disabled; ]; hr; ] }
### ---------------------------------------------------- ### -- Algorithm::AhoCorasick ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: META6.json ### ---------------------------------------------------- { "author" : "cpan:TITSUKI", "authors" : [ "Itsuki Toyota" ], "build-depends" : [ ], "depends" : [ ], "description" : "A Raku Aho-Corasick dictionary matching algorithm implementation", "license" : "Artistic-2.0", "name" : "Algorithm::AhoCorasick", "perl" : "6.c", "provides" : { "Algorithm::AhoCorasick" : "lib/Algorithm/AhoCorasick.pm6", "Algorithm::AhoCorasick::Node" : "lib/Algorithm/AhoCorasick/Node.pm6" }, "resources" : [ ], "source-url" : "git://github.com/titsuki/raku-Algorithm-AhoCorasick.git", "tags" : [ ], "test-depends" : [ ], "version" : "0.0.13" }
### ---------------------------------------------------- ### -- Algorithm::AhoCorasick ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2015, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- Algorithm::AhoCorasick ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: README.md ### ---------------------------------------------------- [![Build Status](https://travis-ci.org/titsuki/raku-Algorithm-AhoCorasick.svg?branch=master)](https://travis-ci.org/titsuki/raku-Algorithm-AhoCorasick) NAME ==== Algorithm::AhoCorasick - A Raku Aho-Corasick dictionary matching algorithm implementation SYNOPSIS ======== use Algorithm::AhoCorasick; my Algorithm::AhoCorasick $aho-corasick .= new(keywords => ['corasick','sick','algorithm','happy']); my $matched = $aho-corasick.match('aho-corasick was invented in 1975'); # set("corasick","sick") my $located = $aho-corasick.locate('aho-corasick was invented in 1975'); # {"corasick" => [4], "sick" => [8]} DESCRIPTION =========== Algorithm::AhoCorasick is a implmentation of the Aho-Corasick algorithm (1975). It constructs the finite state machine from a list of keywords offline. By the finite state machine, it can find the keywords within an input text online. CONSTRUCTOR ----------- ### new my Algorithm::AhoCorasick $aho-corasick .= new(keywords => @keyword-list); Constructs a new finite state machine from a list of keywords. METHODS ------- ### match my $matched = $aho-corasick.match($text); Returns elements of a finite set of strings within an input text. ### locate my $located = $aho-corasick.locate($text); Returns elements of a finite set of strings within an input text where each string contains the locations in which it appeared. AUTHOR ====== titsuki <[email protected]> COPYRIGHT AND LICENSE ===================== Copyright 2016 titsuki This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. The algorithm is from Alfred V. Aho and Margaret J. Corasick, Efficient string matching: an aid to bibliographic search, CACM, 18(6):333-340, June 1975.
### ---------------------------------------------------- ### -- Algorithm::AhoCorasick ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: .travis.yml ### ---------------------------------------------------- language: perl6 perl6: - latest install: - rakudobrew build-zef - zef --debug --depsonly --/test install . script: - PERL6LIB=$PWD/lib prove -e perl6 -vr t/ sudo: false
### ---------------------------------------------------- ### -- Algorithm::AhoCorasick ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: dist.ini ### ---------------------------------------------------- name = Algorithm-AhoCorasick [ReadmeFromPod] ; disable = true filename = lib/Algorithm/AhoCorasick.pm6 [PruneFiles] ; match = ^ 'xt/'
### ---------------------------------------------------- ### -- Algorithm::AhoCorasick ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: t/01-basic.t ### ---------------------------------------------------- use v6; use Test; use-ok 'Algorithm::AhoCorasick'; use Algorithm::AhoCorasick; # locate { my Algorithm::AhoCorasick $aho-corasick .= new(keywords => ['corasick']); my $actual = $aho-corasick.locate('corasick'); my $expected = {'corasick' => [0]}; is $actual, $expected, "Given a text that contains a keyword, .locate should match the keyword and return it with its location"; } { my Algorithm::AhoCorasick $aho-corasick .= new(keywords => ['corasick']); my $actual = $aho-corasick.locate('corasic'); my $expected = Hash; is $actual, $expected, "Given a text that doesn't contain any keywords, .locate should return a Hash type object"; } { my Algorithm::AhoCorasick $aho-corasick .= new(keywords => ['corasick','sick','co','si']); my $actual = $aho-corasick.locate('corasick'); my $expected = {'corasick' => [0],'co' => [0],'si' => [4],'sick' => [4]}; is $actual, $expected, "Given a text that contains some keywords, .locate should match all of the keywords and return these with each locations"; } { my Algorithm::AhoCorasick $aho-corasick .= new(keywords => ['It\'s a piece of cake']); my $actual = $aho-corasick.locate('Tom said "It\'s a piece of cake."'); my $expected = {'It\'s a piece of cake' => [10]}; is $actual, $expected, "Given a text that contains a keyword composed of some whitespaces and alphabetic characters, .locate should match the keyword and return it with its location"; } # Easy Japanese test { my Algorithm::AhoCorasick $aho-corasick .= new(keywords => ['駄菓子','菓子','洋菓子']); my $actual = $aho-corasick.locate('駄菓子と洋菓子どちらが良いか悩ましい。'); my $expected = {'駄菓子' => [0],'洋菓子' => [4],'菓子' => [1,5]}; is $actual, $expected, "Given a text that contains Japanese keyword, .locate should match all Japanese keywords and return these with each locations"; } # match { my Algorithm::AhoCorasick $aho-corasick .= new(keywords => ['corasick']); my $actual = $aho-corasick.match('corasick'); my $expected = set('corasick'); ok $actual ~~ $expected, "Given a text that contains a keyword, .match should match the keyword and return it"; } { my Algorithm::AhoCorasick $aho-corasick .= new(keywords => ['corasick']); my $actual = $aho-corasick.match('corasic'); my $expected = Set; ok $actual ~~ $expected, "Given a text that doesn't contain any keywords, .match should match none of words and return a Set type object"; } { my Algorithm::AhoCorasick $aho-corasick .= new(keywords => ['corasick','sick','co','si']); my $actual = $aho-corasick.match('corasick'); my $expected = set('corasick','co','sick','si'); ok $actual ~~ $expected, "Given a text that contains some keywords, .match should match all of the keywords and return these"; } { my Algorithm::AhoCorasick $aho-corasick .= new(keywords => ['It\'s a piece of cake']); my $actual = $aho-corasick.match('Tom said "It\'s a piece of cake."'); my $expected = set('It\'s a piece of cake'); ok $actual ~~ $expected, "It should match a keyword including whitespaces"; } # Easy Japanese test { my Algorithm::AhoCorasick $aho-corasick .= new(keywords => ['駄菓子','菓子','洋菓子']); my $actual = $aho-corasick.match('駄菓子と洋菓子どちらが良いか悩ましい。'); my $expected = set('駄菓子','洋菓子','菓子'); ok $actual ~~ $expected, "It should match all Japanese keywords"; } done-testing;
### ---------------------------------------------------- ### -- Algorithm::BinaryIndexedTree ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: META6.json ### ---------------------------------------------------- { "auth": "zef:titsuki", "authors": [ "Itsuki Toyota" ], "build-depends": [ ], "depends": [ ], "description": "data structure for cumulative frequency tables", "license": "Artistic-2.0", "name": "Algorithm::BinaryIndexedTree", "perl": "6.c", "provides": { "Algorithm::BinaryIndexedTree": "lib/Algorithm/BinaryIndexedTree.pm6" }, "resources": [ ], "source-url": "https://github.com/titsuki/raku-Algorithm-BinaryIndexedTree.git", "tags": [ ], "test-depends": [ ], "version": "0.0.8" }
### ---------------------------------------------------- ### -- Algorithm::BinaryIndexedTree ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2015, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- Algorithm::BinaryIndexedTree ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: README.md ### ---------------------------------------------------- [![Actions Status](https://github.com/titsuki/raku-Algorithm-BinaryIndexedTree/workflows/test/badge.svg)](https://github.com/titsuki/raku-Algorithm-BinaryIndexedTree/actions) NAME ==== Algorithm::BinaryIndexedTree - data structure for cumulative frequency tables SYNOPSIS ======== use Algorithm::BinaryIndexedTree; my $BIT = Algorithm::BinaryIndexedTree.new(); $BIT.add(5,10); $BIT.get(0).say; # 0 $BIT.get(5).say; # 10 $BIT.sum(4).say; # 0 $BIT.sum(5).say; # 10 $BIT.add(0,10); $BIT.sum(5).say; # 20 DESCRIPTION =========== Algorithm::BinaryIndexedTree is the data structure for maintainig the cumulative frequencies. CONSTRUCTOR ----------- ### new my $BIT = Algorithm::BinaryIndexedTree.new(%options); #### OPTIONS * `size => $size` Sets table size. Default is 1000. METHODS ------- ### add $BIT.add($index, $value); Adds given value to the index `$index`. ### sum my $sum = $BIT.sum($index); Returns sum of the values of items from index 0 to index `$index` inclusive. ### get my $value = $BIT.get($index); Returns the value at index `$index`. AUTHOR ====== titsuki <[email protected]> COPYRIGHT AND LICENSE ===================== Copyright 2016 titsuki This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. The algorithm is from Fenwick, Peter M. "A new data structure for cumulative frequency tables." Software: Practice and Experience 24.3 (1994): 327-336.
### ---------------------------------------------------- ### -- Algorithm::BinaryIndexedTree ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: .travis.yml ### ---------------------------------------------------- language: perl6 perl6: - latest install: - rakudobrew build-zef - zef --debug --depsonly --/test install . script: - PERL6LIB=$PWD/lib prove -e perl6 -vr t/ sudo: false
### ---------------------------------------------------- ### -- Algorithm::BinaryIndexedTree ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: dist.ini ### ---------------------------------------------------- name = raku-Algorithm-BinaryIndexedTree [ReadmeFromPod] ; disable = true filename = lib/Algorithm/BinaryIndexedTree.pm6 [UploadToZef] [PruneFiles] ; match = ^ 'xt/' [Badges] provider = github-actions/test
### ---------------------------------------------------- ### -- Algorithm::BinaryIndexedTree ### -- Licenses: Artistic-2.0 ### -- Authors: Itsuki Toyota ### -- File: t/01-basic.t ### ---------------------------------------------------- use v6; use Test; use Algorithm::BinaryIndexedTree; subtest { my $BIT = Algorithm::BinaryIndexedTree.new(); $BIT.add(5,10); is $BIT.get(4), 0, "when it gets tree[4] then it should return 0"; is $BIT.get(5), 10, "when it gets tree[5] then it should return 10"; is $BIT.sum(4), 0, "when it sums tree[0..4] then it should return 0"; is $BIT.sum(5), 10, "when it sums tree[0..5] then it should return 10"; is $BIT.sum(6), 10, "when it sums tree[0..6] then it should return 10"; }, "Given: It adds value 10 to tree[5]"; subtest { my $BIT = Algorithm::BinaryIndexedTree.new(); $BIT.add(0,10); dies-ok { $BIT.get(-1); }, "when it gets tree[-1] then it should die"; is $BIT.get(0), 10, "when it gets tree[0] then it should return 10 "; is $BIT.get(1), 0, "when it gets tree[1] then it should return 0"; dies-ok { $BIT.sum(-1); }, "when it sums tree[-1] then it should die"; is $BIT.sum(0), 10, "when it sums tree[0..0] then it should return 10"; is $BIT.sum(1), 10, "when it sums tree[0..1] then it should return 10"; }, "Given: It adds value 10 to tree[0]"; subtest { my $BIT = Algorithm::BinaryIndexedTree.new(); $BIT.add(5,10); $BIT.add(5,10); is $BIT.get(4), 0, "when it gets tree[4] then it should return 0"; is $BIT.get(5), 20, "when it gets tree[5] then it should return 20"; is $BIT.sum(4), 0, "when it sums tree[0..4] then it should return 0"; is $BIT.sum(5), 20, "when it sums tree[0..5] then it should return 20"; is $BIT.sum(6), 20, "when it sums tree[0..6] then it should return 20"; }, "Given: It adds value 10 to tree[5] twice"; subtest { my $BIT = Algorithm::BinaryIndexedTree.new(); $BIT.add(0,10); $BIT.add(0,10); dies-ok { $BIT.get(-1); }, "when it gets tree[-1] then it should die"; is $BIT.get(0), 20, "when it gets tree[0] then it should return 20"; is $BIT.get(1), 0, "when it gets tree[1] then it should return 0"; dies-ok { $BIT.sum(-1); }, "when it sums tree[-1] then it should die"; is $BIT.sum(0), 20, "when it sums tree[0..0] then it should return 20"; is $BIT.sum(1), 20, "when it sums tree[0..1] then it should return 20"; }, "Given: It adds value 10 to tree[0] twice"; subtest { my $BIT = Algorithm::BinaryIndexedTree.new(size => 1000); $BIT.add(999,10); $BIT.add(1000,10); dies-ok { $BIT.add(1001,10); }, "when it adds value 10 to tree[1001] then it should die"; is $BIT.sum(1000),20, "when it sums tree[0..1000] then it should return 20"; dies-ok { $BIT.sum(1001); }, "when it sums tree[0..1001] then it should die"; }, "Given: BIT size is 1000"; done-testing;
### ---------------------------------------------------- ### -- Algorithm::BloomFilter ### -- Licenses: Artistic-2.0 ### -- Authors: yowcow ### -- File: META6.json ### ---------------------------------------------------- { "authors" : [ "yowcow" ], "build-depends" : [ ], "depends" : [ "Digest::MurmurHash3" ], "description" : "A bloom filter implementation in Perl 6", "name" : "Algorithm::BloomFilter", "license" : "Artistic-2.0", "perl" : "6.c", "provides" : { "Algorithm::BloomFilter" : "lib/Algorithm/BloomFilter.pm6" }, "resources" : [ ], "source-url" : "[email protected]:yowcow/p6-Algorithm-BloomFilter.git", "test-depends" : [ "Test", "Test::META" ], "version" : "0.1.0" }
### ---------------------------------------------------- ### -- Algorithm::BloomFilter ### -- Licenses: Artistic-2.0 ### -- Authors: yowcow ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2016, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- Algorithm::BloomFilter ### -- Licenses: Artistic-2.0 ### -- Authors: yowcow ### -- File: README.md ### ---------------------------------------------------- [![Build Status](https://travis-ci.org/yowcow/p6-Algorithm-BloomFilter.svg?branch=master)](https://travis-ci.org/yowcow/p6-Algorithm-BloomFilter) NAME ==== Algorithm::BloomFilter - A bloom filter implementation in Perl 6 SYNOPSIS ======== use Algorithm::BloomFilter; my $filter = Algorithm::BloomFilter.new( capacity => 100, error-rate => 0.01, ); $filter.add("foo-bar"); $filter.check("foo-bar"); # True $filter.check("bar-foo"); # False with possible false-positive DESCRIPTION =========== Algorithm::BloomFilter is a pure Perl 6 implementation of [Bloom Filter](https://en.wikipedia.org/wiki/Bloom_filter), mostly based on [Bloom::Filter](https://metacpan.org/pod/Bloom::Filter) from Perl 5. Digest::MurmurHash3 is used for hashing from version 0.1.0. METHODS ======= ### new(Rat:D :$error-rate, Int:D :$capacity) Creates a Bloom::Filter instance. ### add(Cool:D $key) Adds a given key to filter instance. ### check(Cool:D $key) returns Bool Checks if a given key is in filter instance. INTERNAL METHODS ================ ### calculate-shortest-filter-length(Int:D :$num-keys, Rat:D $error-rate) returns Hash[Int] Calculates and returns filter's length and a number of hash functions. ### create-salts(Int:D :$count) returns Seq[Int] Creates and returns `$count` unique and random uint32 salts. ### get-cells(Cool:D $key, Int:D :$filter-length, Int:D :$blankvec, Int:D :@salts) returns List Calculates and returns positions to check in a bit vector. SEE ALSO ======== [Bloom Filter](https://en.wikipedia.org/wiki/Bloom_filter) [Bloom::Filter](https://metacpan.org/pod/Bloom::Filter) AUTHOR ====== yowcow <[email protected]> COPYRIGHT AND LICENSE ===================== Copyright 2016 yowcow This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
### ---------------------------------------------------- ### -- Algorithm::BloomFilter ### -- Licenses: Artistic-2.0 ### -- Authors: yowcow ### -- File: .travis.yml ### ---------------------------------------------------- language: perl6 perl6: - latest install: - rakudobrew build-panda - panda --notests installdeps . script: - perl6 -MPanda::Builder -e 'Panda::Builder.build(~$*CWD)' #- PERL6LIB=$PWD/lib prove -e perl6 -vr t/ - prove sudo: false
### ---------------------------------------------------- ### -- Algorithm::BloomFilter ### -- Licenses: Artistic-2.0 ### -- Authors: yowcow ### -- File: t/00-meta.t ### ---------------------------------------------------- use v6; use Test; use Test::META; plan 1; meta-ok; done-testing;
### ---------------------------------------------------- ### -- Algorithm::BloomFilter ### -- Licenses: Artistic-2.0 ### -- Authors: yowcow ### -- File: t/02-functions.t ### ---------------------------------------------------- use v6; use Algorithm::BloomFilter; use Test; subtest { my Int %filter := Algorithm::BloomFilter.calculate-shortest-filter-length( num-keys => 1092, error-rate => 0.00001 ); is %filter<length>, 26172; is %filter<num-hash-funcs>, 17; }, 'Test calculate-shortest-filter-length'; subtest { subtest { my Int @salts = Algorithm::BloomFilter.create-salts(count => 1); is @salts.elems, 1; }, 'When 1'; subtest { my Int @salts = Algorithm::BloomFilter.create-salts(count => 5); is @salts.elems, 5; }, 'When 5'; }, 'Test create-salts'; subtest { my Int @salts = Algorithm::BloomFilter.create-salts(count => 2); my Int @cells = Algorithm::BloomFilter.get-cells( 'hogehoge', filter-length => 10, blankvec => 0, salts => @salts, ); is @cells.elems, 2; }, 'Test get-cells'; done-testing;
### ---------------------------------------------------- ### -- Algorithm::BloomFilter ### -- Licenses: Artistic-2.0 ### -- Authors: yowcow ### -- File: t/03-instance.t ### ---------------------------------------------------- use v6; use Algorithm::BloomFilter; use Test; subtest { subtest { dies-ok { Algorithm::BloomFilter.new }, 'Dies without error-rate and capacity'; dies-ok { Algorithm::BloomFilter.new(error-rate => 0.001) }, 'Dies without error-rate'; dies-ok { Algorithm::BloomFilter.new(capacity => 10000) }, 'Dies without capacity'; }, 'Fails with invalid parameters'; subtest { my Algorithm::BloomFilter $bloom .= new( error-rate => 0.1, capacity => 10, ); isa-ok $bloom, 'Algorithm::BloomFilter'; is $bloom.error-rate, 0.1; is $bloom.capacity, 10; is $bloom.key-count, 0; is $bloom.filter-length, 49; is $bloom.num-hash-funcs, 3; is $bloom.salts.elems, 3; }, 'Succeeds with valid parameters'; }, 'Test new'; subtest { dies-ok { Algorithm::BloomFilter.add('hogehoge') }; dies-ok { Algorithm::BloomFilter.check('hogehoge') }; }, 'Test `add` and `check` are instance method'; subtest { my Algorithm::BloomFilter $bloom .= new( error-rate => 0.01, capacity => 100, ); lives-ok { $bloom.add('hogehoge') }, 'adding "hogehoge" succeeds'; ok $bloom.check('hogehoge'), 'checking "hogehoge" succeeds'; ok !$bloom.check('fugafuga'), 'checking "fugafuga" fails'; }, 'Test add/check'; subtest { my Algorithm::BloomFilter $bloom .= new( error-rate => 0.1, capacity => 2, ); $bloom.add('hogehoge'); $bloom.add('fugafuga'); dies-ok { $bloom.add('foobar') }; }, 'Test add exceeds capacity'; done-testing;
### ---------------------------------------------------- ### -- Algorithm::BloomFilter ### -- Licenses: Artistic-2.0 ### -- Authors: yowcow ### -- File: t/01-basic.t ### ---------------------------------------------------- use v6; use Test; use-ok 'Algorithm::BloomFilter'; done-testing;
### ---------------------------------------------------- ### -- Algorithm::BloomFilter ### -- Licenses: Artistic-2.0 ### -- Authors: yowcow ### -- File: eg/benchmark.p6 ### ---------------------------------------------------- use v6; use Algorithm::BloomFilter; my $filter = Algorithm::BloomFilter.new( error-rate => 0.01, capacity => 10_000, ); say "Adding items to filter"; $filter.add($_) for 1 .. 100; say "Checking items in filter"; say $filter.check($_) for 1 .. 100;
### ---------------------------------------------------- ### -- Algorithm::DawkinsWeasel ### -- Licenses: Artistic-2.0, GPL-2.0+ ### -- Authors: Jaldhar H. Vyas ### -- File: META6.json ### ---------------------------------------------------- { "authors" : [ "Jaldhar H. Vyas" ], "build-depends" : [ ], "depends" : [ ], "description" : "An Illustration of Cumulative Selection", "license" : [ "Artistic-2.0", "GPL-2.0+" ], "name" : "Algorithm::DawkinsWeasel", "perl" : "6.c", "provides" : { "Algorithm::DawkinsWeasel" : "lib/Algorithm/DawkinsWeasel.pm6" }, "resources" : [ ], "source-url" : "https://github.com/jaldhar/Algorithm-DawkinsWeasel.git", "tags" : [ ], "test-depends" : [ ], "version" : "0.1.1" }
### ---------------------------------------------------- ### -- Algorithm::DawkinsWeasel ### -- Licenses: Artistic-2.0, GPL-2.0+ ### -- Authors: Jaldhar H. Vyas ### -- File: LICENSE ### ---------------------------------------------------- Copyright (c) 2017 Consolidated Braincells Inc. All rights reserved. This distribution is free software; you can redistribute it and/or modify it under the terms of either: a) the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version, or b) the Artistic License version 2.0. --------------------------------------------------------------------------- The General Public License (GPL) Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave, Cambridge, MA 02139, USA. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS --------------------------------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2006, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- Algorithm::DawkinsWeasel ### -- Licenses: Artistic-2.0, GPL-2.0+ ### -- Authors: Jaldhar H. Vyas ### -- File: README.md ### ---------------------------------------------------- NAME ==== Algorithm::DawkinsWeasel - An Illustration of Cumulative Selection SYNOPSIS ======== ``` use Algorithm::DawkinsWeasel; my $weasel = Algorithm::DawkinsWeasel.new( target-phrase => 'METHINKS IT IS LIKE A WEASEL', mutation-threshold => 0.05, copies => 100, ); for $weasel.evolution { say .count.fmt('%04d '), .current-phrase, ' [', .hi-score, ']'; } ``` DESCRIPTION =========== Algorithm::DawkinsWeasel is a simple model illustrating the idea of cumulative selection in evolution. The original form of it looked like this: 1. Start with a random string of 28 characters. 2. Make 100 copies of this string, with a 5% chance per character of that character being replaced with a random character. 3. Compare each new string with "METHINKS IT IS LIKE A WEASEL", and give each a score (the number of letters in the string that are correct and in the correct position). 4. If any of the new strings has a perfect score (== 28), halt. 5. Otherwise, take the highest scoring string, and go to step 2 This module parametrizes the target string, mutation threshold, and number of copies per round. INSTALLATION ============ With a normal rakudo installation, you should have available one or both of the installer tools: - `zef` - `panda` `zef` is becoming the preferred tool because of more features (including an uninstall function) and more active development, but either tool should work fine for a first installation of a desired module. We'll use `zef` for the rest of the examples. ```Perl6 zef install Algorithm::DawkinsWeasel ``` If the attempt shows that the module isn't found or available, ensure your installer is current: ```Perl6 zef update ``` If you want to use the latest version in the git repository (or it's not available in the Perl 6 ecosystem), clone it and then install it from its local directory. Here we assume the module is on Github in location "https://github.com/jaldhar/Algorithm-DawkinsWeasel", but use the Github clone instructions for the desired module. (Note the repository name is usually not the exact name of the module as used in Perl 6.) ```Perl6 git clone https://github.com/jaldhar/Algorithm-DawkinsWeasel.git cd /path/to/cloned/repository/directory zef install . ``` AUTHOR ====== Jaldhar H. Vyas <[email protected]> COPYRIGHT AND LICENSE ===================== Copyright (C) 2017, Consolidated Braincells Inc. All rights reserved. This distribution is free software; you can redistribute it and/or modify it under the terms of either: a) the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version, or b) the Artistic License version 2.0. The full text of the license can be found in the LICENSE file included with this distribution.
### ---------------------------------------------------- ### -- Algorithm::DawkinsWeasel ### -- Licenses: Artistic-2.0, GPL-2.0+ ### -- Authors: Jaldhar H. Vyas ### -- File: .travis.yml ### ---------------------------------------------------- os: - linux - osx language: perl6 perl6: - latest install: - rakudobrew build zef - zef install --depsonly --/test . script: - PERL6LIB=$PWD/lib prove -e perl6 -vr t/ sudo: false
### ---------------------------------------------------- ### -- Algorithm::DawkinsWeasel ### -- Licenses: Artistic-2.0, GPL-2.0+ ### -- Authors: Jaldhar H. Vyas ### -- File: t/01-basic.t ### ---------------------------------------------------- use v6.c; use Test; use Algorithm::DawkinsWeasel; my $weasel = Algorithm::DawkinsWeasel.new; ok $weasel.isa('Algorithm::DawkinsWeasel'), 'is a Algorithm::DawkinsWeasel'; is $weasel.target-phrase, 'METHINKS IT IS LIKE A WEASEL', 'target-phrase'; is $weasel.mutation-threshold, 0.05, 'mutation-threshold'; is $weasel.copies, 100, 'copies'; for $weasel.evolution { diag join '', (.count.fmt('%04d '), .current-phrase, ' [', .hi-score, ']'); } is $weasel.current-phrase, 'METHINKS IT IS LIKE A WEASEL', 'target reached'; done-testing;
### ---------------------------------------------------- ### -- Algorithm::Diff ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: META6.json ### ---------------------------------------------------- { "auth": "zef:raku-community-modules", "build-depends": [ ], "depends": [ ], "description": "Compute `intelligent' differences between two files / lists", "license": "Artistic-2.0", "name": "Algorithm::Diff", "perl": "6.*", "provides": { "Algorithm::Diff": "lib/Algorithm/Diff.rakumod" }, "resources": [ ], "source-url": "https://github.com/raku-community-modules/Algorithm-Diff.git", "tags": [ "CPAN5", "DIFF", "ALGORITHM" ], "test-depends": [ ], "version": "0.0.4" }
### ---------------------------------------------------- ### -- Algorithm::Diff ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2006, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- Algorithm::Diff ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: README.md ### ---------------------------------------------------- ### -- Chunk 1 of 2 [![Actions Status](https://github.com/raku-community-modules/Algorithm-Diff/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/Algorithm-Diff/actions) [![Actions Status](https://github.com/raku-community-modules/Algorithm-Diff/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/Algorithm-Diff/actions) [![Actions Status](https://github.com/raku-community-modules/Algorithm-Diff/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/Algorithm-Diff/actions) NAME ==== Algorithm::Diff - Compute `intelligent' differences between two files / lists SYNOPSIS ======== ```raku use Algorithm::Diff; # This example produces traditional 'diff' output: my $diff = Algorithm::Diff.new( @seq1, @seq2 ); $diff.Base( 1 ); # Return line numbers, not indices while $diff.Next { next if $diff.Same; my $sep = ''; if !$diff.Items(2) { printf "%d,%dd%d\n", $diff.Min(1), $diff.Max(1), $diff.Max(2); } elsif !$diff.Items(1) { printf "%da%d,%d\n", $diff.Min(1), $diff.Max(1), $diff.Max(2); } else { $sep = "---\n"; printf "%d,%dc%d,%d\n", $diff.Min(1), $diff.Max(1), $diff.Min(2), $diff.Max(2); } print "< $_" for $diff.Items(1); print $sep; print "> $_" for $diff.Items(2); } # Alternate interfaces: use Algorithm::Diff; @lcs = LCS( @seq1, @seq2 ); $count = LCS_length( @seq1, @seq2 ); ( $seq1idxlist, $seq2idxlist ) = LCSidx( @seq1, @seq2 ); # Complicated interfaces: @diffs = diff( @seq1, @seq2 ); @sdiffs = sdiff( @seq1, @seq2 ); @cdiffs = compact_diff( @seq1, @seq2 ); traverse_sequences( @seq1, @seq2, MATCH => &callback1, DISCARD_A => &callback2, DISCARD_B => &callback3, &key_generator, ); traverse_balanced( @seq1, @seq2, MATCH => &callback1, DISCARD_A => &callback2, DISCARD_B => &callback3, CHANGE => &callback4, &key_generator, ); ``` INTRODUCTION ============ (by Mark-Jason Dominus) I once read an article written by the authors of `diff`; they said that they worked very hard on the algorithm until they found the right one. I think what they ended up using (and I hope someone will correct me, because I am not very confident about this) was the `longest common subsequence' method. In the LCS problem, you have two sequences of items: a b c d f g h j q z a b c d e f g i j k r x y z and you want to find the longest sequence of items that is present in both original sequences in the same order. That is, you want to find a new sequence *S* which can be obtained from the first sequence by deleting some items, and from the secend sequence by deleting other items. You also want *S* to be as long as possible. In this case *S* is a b c d f g j z From there it's only a small step to get diff-like output: e h i k q r x y + - + + - + + + This module solves the LCS problem. It also includes a canned function to generate `diff`-like output. It might seem from the example above that the LCS of two sequences is always pretty obvious, but that's not always the case, especially when the two sequences have many repeated elements. For example, consider a x b y c z p d q a b c a x b y c z A naive approach might start by matching up the `a` and `b` that appear at the beginning of each sequence, like this: a x b y c z p d q a b c a b y c z This finds the common subsequence `a b c z`. But actually, the LCS is `a x b y c z`: a x b y c z p d q a b c a x b y c z or a x b y c z p d q a b c a x b y c z USAGE ===== (See several example scripts include with this module.) This module now provides an object-oriented interface that uses less memory and is easier to use than most of the previous procedural interfaces. It also still provides several exportable functions. We'll deal with these in ascending order of difficulty: `LCS`, `LCS_length`, `LCSidx`, OO interface, `prepare`, `diff`, `sdiff`, `traverse_sequences`, and `traverse_balanced`. LCS --- Given two lists of items, LCS returns an array containing their longest common subsequence. ```raku @lcs = LCS( @seq1, @seq2 ); ``` `LCS` may be passed an optional third parameter; this is a CODE reference to a key generation function. See [/KEY GENERATION FUNCTIONS](/KEY GENERATION FUNCTIONS). ```raku @lcs = LCS( @seq1, @seq2, $keyGen ); ``` LCS_length ---------- This is just like `LCS` except it only returns the length of the longest common subsequence. This provides a performance gain of about 9% compared to `LCS`. LCSidx ------ Like `LCS` except it returns references to two lists. The first list contains the indices into @seq1 where the LCS items are located. The second list contains the indices into @seq2 where the LCS items are located. Therefore, the following three lists will contain the same values: ```raku my( $idx1, $idx2 ) = LCSidx( @seq1, @seq2 ); my @list1 = @seq1[ $idx1 ]; my @list2 = @seq2[ $idx2 ]; my @list3 = LCS( @seq1, @seq2 ); ``` new --- ```raku $diff = Algorithm::Diffs.new( @seq1, @seq2 ); $diff = Algorithm::Diffs.new( @seq1, @seq2, &keyGen ); ``` `new` computes the smallest set of additions and deletions necessary to turn the first sequence into the second and compactly records them in the object. You use the object to iterate over *hunks*, where each hunk represents a contiguous section of items which should be added, deleted, replaced, or left unchanged. The following summary of all of the methods looks a lot like Perl code but some of the symbols have different meanings: <table class="pod-table"> <tbody> <tr> <td>[ ]</td> <td>Encloses optional arguments</td> </tr> <tr> <td>:</td> <td>Is followed by the default value for an optional argument</td> </tr> <tr> <td>|</td> <td>Separates alternate return results</td> </tr> </tbody> </table> Method summary: ```raku $obj = Algorithm::Diff.new( @seq1, @seq2, [ &keyGen ] ); $pos = $obj.Next( [ $count : 1 ] ); $revPos = $obj.Prev( [ $count : 1 ] ); $obj = $obj.Reset( [ $pos : 0 ] ); $copy = $obj.Copy( [ $pos, [ $newBase ] ] ); $oldBase = $obj.Base( [ $newBase ] ); ``` Note that all of the following methods `die` if used on an object that is "reset" (not currently pointing at any hunk). ```raku $bits = $obj.Diff; @items = $obj.Same; @items = $obj.Items( $seqNum ); @idxs = $obj.Range( $seqNum, [ $base ] ); $minIdx = $obj.Min( $seqNum, [ $base ] ); $maxIdx = $obj.Max( $seqNum, [ $base ] ); @values = $obj.Get( @names ); ``` Passing in an undefined value for an optional argument is always treated the same as if no argument were passed in. Next ---- ```raku $pos = $diff.Next; # Move forward 1 hunk $pos = $diff.Next( 2 ); # Move forward 2 hunks $pos = $diff.Next(-5); # Move backward 5 hunks ``` `Next` moves the object to point at the next hunk. The object starts out "reset", which means it isn't pointing at any hunk. If the object is reset, then `Next()` moves to the first hunk. `Next` returns a true value iff the move didn't go past the last hunk. So `Next(0)` will return true iff the object is not reset. Actually, `Next` returns the object's new position, which is a number between 1 and the number of hunks (inclusive), or returns a false value. Prev ---- `Prev($N)` is almost identical to `Next(-$N)`; it moves to the $Nth previous hunk. On a 'reset' object, `Prev()` [and `Next(-1)`] move to the last hunk. The position returned by `Prev` is relative to the *end* of the hunks; -1 for the last hunk, -2 for the second-to-last, etc. `Reset` ------- ```raku $diff.Reset; # Reset the object's position $diff.Reset($pos); # Move to the specified hunk $diff.Reset(1); # Move to the first hunk $diff.Reset(-1); # Move to the last hunk ``` `Reset` returns the object, so, for example, you could use `$diff.Reset().Next(-1) ` to get the number of hunks. Copy ---- ```raku $copy = $diff.Copy( $newPos, $newBase ); ``` `Copy` returns a copy of the object. The copy and the orignal object share most of their data, so making copies takes very little memory. The copy maintains its own position (separate from the original), which is the main purpose of copies. It also maintains its own base. By default, the copy's position starts out the same as the original object's position. But `Copy` takes an optional first argument to set the new position, so the following three snippets are equivalent: ```raku $copy = $diff.Copy($pos); $copy = $diff.Copy; $copy.Reset($pos); $copy = $diff.Copy.Reset($pos); ``` `Copy` takes an optional second argument to set the base for the copy. If you wish to change the base of the copy but leave the position the same as in the original, here are two equivalent ways: ```raku $copy = $diff.Copy; $copy.Base( 0 ); $copy = $diff.Copy(Nil,0); ``` Here are two equivalent way to get a "reset" copy: ```raku $copy = $diff.Copy(0); $copy = $diff.Copy.Reset; ``` Diff ---- ```raku $bits = $obj.Diff; ``` `Diff` returns a true value iff the current hunk contains items that are different between the two sequences. It actually returns one of the follow 4 values: ### 3 `3==(1|2)`. This hunk contains items from @seq1 and the items from @seq2 that should replace them. Both sequence 1 and 2 contain changed items so both the 1 and 2 bits are set. ### 2 This hunk only contains items from @seq2 that should be inserted (not items from @seq1). Only sequence 2 contains changed items so only the 2 bit is set. ### 1 This hunk only contains items from @seq1 that should be deleted (not items from @seq2). Only sequence 1 contains changed items so only the 1 bit is set. ### 0 This means that the items in this hunk are the same in both sequences. Neither sequence 1 nor 2 contain changed items so neither the 1 nor the 2 bits are set. Same ---- `Same` returns a true value iff the current hunk contains items that are the same in both sequences. It actually returns the list of items if they are the same or an emty list if they aren't. In a scalar context, it returns the size of the list. Items ----- ```raku $count = $diff.Items(2); @items = $diff.Items($seqNum); ``` `Items` returns the (number of) items from the specified sequence that are part of the current hunk. If the current hunk contains only insertions, then `$diff.Items(1) ` will return an empty list (0 in a scalar conext). If the current hunk contains only deletions, then `$diff.Items(2) ` will return an empty list (0 in a scalar conext). If the hunk contains replacements, then both `$diff.Items(1) ` and `$diff.Items(2) ` will return different, non-empty lists. Otherwise, the hunk contains identical items and all of the following will return the same lists: ```raku @items = $diff.Items(1); @items = $diff.Items(2); @items = $diff.Same; ``` Range ----- ```raku $count = $diff.Range( $seqNum ); @indices = $diff.Range( $seqNum ); @indices = $diff.Range( $seqNum, $base ); ``` `Range` is like `Items` except that it returns a list of *indices* to the items rather than the items themselves. By default, the index of the first item (in each sequence) is 0 but this can be changed by calling the `Base` method. So, by default, the following two snippets return the same lists: ```raku @list = $diff.Items(2); @list = @seq2[ $diff.Range(2) ]; ``` You can also specify the base to use as the second argument. So the following two snippets *always* return the same lists: ```raku @list = $diff.Items(1); @list = @seq1[ $diff.Range(1,0) ]; ``` Base ---- ```raku $curBase = $diff.Base(); $oldBase = $diff.Base($newBase); ``` `Base` sets and/or returns the current base (usually 0 or 1) that is used when you request range information. The base defaults to 0 so that range information is returned as array indices. You can set the base to 1 if you want to report traditional line numbers instead. Min --- ```raku $min1 = $diff.Min(1); $min = $diff.Min( $seqNum, $base ); ``` `Min` returns the first value that `Range` would return (given the same arguments) or returns `undef` if `Range` would return an empty list. Max --- `Max` returns the last value that `Range` would return or `Nil`. prepare ------- Given a reference to a list of items, `prepare` returns a reference to a hash which can be used when comparing this sequence to other sequences with `LCS` or `LCS_length`. ```raku $prep = prepare( @seq1 ); for ^10_000 { @lcs = LCS( $prep, @seq2[$_] ); # do something useful with @lcs } ``` `prepare` may be passed an optional third parameter; this is a CODE reference to a key generation function. See [/KEY GENERATION FUNCTIONS](/KEY GENERATION FUNCTIONS). ```raku $prep = prepare( @seq1, &keyGen ); for ^10_000 { @lcs = LCS( @seq2[$_], $prep, &keyGen ); # do something useful with @lcs } ``` Using `prepare` provides a performance gain of about 50% when calling LCS many times compared with not preparing. diff ---- ```raku @diffs = diff( @seq1, @seq2 ); ``` `diff` computes the smallest set of additions and deletions necessary to turn the first sequence into the second, and returns a description of these changes. The description is a list of *hunks*; each hunk represents a contiguous section of items which should be added, deleted, or replaced. (Hunks containing unchanged items are not included.) The return value of `diff` is a list of hunks, or, in scalar context, a reference to such a list. If there are no differences, the list will be empty. Here is an example. Calling `diff` for the following two sequences: a b c e h j l m n p b c d e f j k l m r s t would produce the following list: ```raku ( [ [ '-', 0, 'a' ] ], [ [ '+', 2, 'd' ] ], [ [ '-', 4, 'h' ], [ '+', 4, 'f' ] ], [ [ '+', 6, 'k' ] ], [ [ '-', 8, 'n' ], [ '-', 9, 'p' ], [ '+', 9, 'r' ], [ '+', 10, 's' ], [ '+', 11, 't' ] ], ) ``` There are five hunks here. The first hunk says that the `a` at position 0 of the first sequence should be deleted (`-`). The second hunk says that the `d` at position 2 of the second sequence should be inserted (`+`). The third hunk says that the `h` at position 4 of the first sequence should be removed and replaced with the `f` from position 4 of the second sequence. And so on. `diff` may be passed an optional third parameter; this is a CODE reference to a key generation function. See [/KEY GENERATION FUNCTIONS](/KEY GENERATION FUNCTIONS). Additional parameters, if any, will be passed to the key generation routine. sdiff ----- ```raku @sdiffs = sdiff( @seq1, @seq2 ); ``` `sdiff` computes all necessary components to show two sequences and their minimized differences side by side, just like the Unix-utility *sdiff* does: same same before | after old < - - > new It returns a list of array refs, each pointing to an array of display instructions. If there are no differences, the list will have one entry per item, each indicating that the item was unchanged. Display instructions consist of three elements: A modifier indicator (`+`: Element added, `-`: Element removed, `u`: Element unmodified, `c`: Element changed) and the value of the old and new elements, to be displayed side-by-side. An `sdiff` of the following two sequences: a b c e h j l m n p b c d e f j k l m r s t results in ```raku ( [ '-', 'a', '' ], [ 'u', 'b', 'b' ], [ 'u', 'c', 'c' ], [ '+', '', 'd' ], [ 'u', 'e', 'e' ], [ 'c', 'h', 'f' ], [ 'u', 'j', 'j' ], [ '+', '', 'k' ], [ 'u', 'l', 'l' ], [ 'u', 'm', 'm' ], [ 'c', 'n', 'r' ], [ 'c', 'p', 's' ], [ '+', '', 't' ], ) ``` `sdiff` may be passed an optional third parameter; this is a CODE reference to a key generation function. See [/KEY GENERATION FUNCTIONS](/KEY GENERATION FUNCTIONS). Additional parameters, if any, will be passed to the key generation routine. compact_diff ------------ `compact_diff` is much like `sdiff` except it returns a much more compact description consisting of just one flat list of indices. An example helps explain the format: ```raku my @a = <a b c e h j l m n p >; my @b = < b c d e f j k l m r s t>; @cdiff = compact_diff( @a, @b ); # Returns: # @a @b @a @b # start start values values ( 0, 0, # = 0, 0, # a ! 1, 0, # b c = b c 3, 2, # ! d 3, 3, # e = e 4, 4, # f ! h 5, 5, # j = j 6, 6, # ! k 6, 7, # l m = l m 8, 9, # n p ! r s t 10, 12, # ); ``` The 0th, 2nd, 4th, etc. entries are all indices into @seq1 (@a in the above example) indicating where a hunk begins. The 1st, 3rd, 5th, etc. entries are all indices into @seq2 (@b in the above example) indicating where the same hunk begins. So each pair of indices (except the last pair) describes where a hunk begins (in each sequence). Since each hunk must end at the item just before the item that starts the next hunk, the next pair of indices can be used to determine where the hunk ends. So, the first 4 entries (0..3) describe the first hunk. Entries 0 and 1 describe where the first hunk begins (and so are always both 0). Entries 2 and 3 describe where the next hunk begins, so subtracting 1 from each tells us where the first hunk ends. That is, the first hunk contains items `$diff[0]` through `$diff[2] - 1` of the first sequence and contains items `$diff[1]` through `$diff[3] - 1` of the second sequence. In other words, the first hunk consists of the following two lists of items: ```raku # 1st pair 2nd pair # of indices of indices @list1 = @a[ $cdiff[0] .. $cdiff[2]-1 ]; @list2 = @b[ $cdiff[1] .. $cdiff[3]-1 ]; # Hunk start Hunk end ``` Note that the hunks will always alternate between those that are part of the LCS (those that contain unchanged items) and those that contain changes. This means that all we need to be told is whether the first hunk is a 'same' or 'diff' hunk and we can determine which of the other hunks contain 'same' items or 'diff' items. By convention, we always make the first hunk contain unchanged items. So the 1st, 3rd, 5th, etc. hunks (all odd-numbered hunks if you start counting from 1) all contain unchanged items. And the 2nd, 4th, 6th, etc. hunks (all even-numbered hunks if you start counting from 1) all contain changed items. Since @a and @b don't begin with the same value, the first hunk in our example is empty (otherwise we'd violate the above convention). Note that the first 4 index values in our example are all zero. Plug these values into our previous code block and we get: ```raku @hunk1a = @a[ 0 .. 0-1 ]; @hunk1b = @b[ 0 .. 0-1 ]; ``` And `0..-1` returns the empty list. Move down one pair of indices (2..5) and we get the offset ranges for the second hunk, which contains changed items. Since `@diff[2..5]` contains (0,0,1,0) in our example, the second hunk consists of these two lists of items: ```raku @hunk2a = @a[ $cdiff[2] .. $cdiff[4]-1 ]; @hunk2b = @b[ $cdiff[3] .. $cdiff[5]-1 ]; # or @hunk2a = @a[ 0 .. 1-1 ]; @hunk2b = @b[ 0 .. 0-1 ]; # or @hunk2a = @a[ 0 .. 0 ]; @hunk2b = @b[ 0 .. -1 ]; # or @hunk2a = ( 'a' ); @hunk2b = ( ); ``` That is, we would delete item 0 ('a') from @a. Since `@diff[4..7]` contains (1,0,3,2) in our example, the third hunk consists of these two lists of items: ```raku @hunk3a = @a[ $cdiff[4] .. $cdiff[6]-1 ]; @hunk3a = @b[ $cdiff[5] .. $cdiff[7]-1 ]; # or @hunk3a = @a[ 1 .. 3-1 ]; @hunk3a = @b[ 0 .. 2-1 ]; # or @hunk3a = @a[ 1 .. 2 ]; @hunk3a = @b[ 0 .. 1 ]; # or @hunk3a = qw( b c ); @hunk3a = qw( b c ); ``` Note that this third hunk contains unchanged items as our convention demands. You can continue this process until you reach the last two indices, which will always be the number of items in each sequence. This is required so that subtracting one from each will give you the indices to the last items in each sequence. traverse_sequences ------------------ `traverse_sequences` used to be the most general facility provided by this module (the new OO interface is more powerful and much easier to use). Imagine that there are two arrows. Arrow A points to an element of sequence A, and arrow B points to an element of the sequence B. Initially, the arrows point to the first elements of the respective sequences. `traverse_sequences` will advance the arrows through the sequences one element at a time, calling an appropriate user-specified callback function before each advance. It willadvance the arrows in such a way that if there are equal elements `$A[$i]` and `$B[$j]` which are equal and which are part of the LCS, there will be some moment during the execution of `traverse_sequences` when arrow A is pointing to `$A[$i]` and arrow B is pointing to `$B[$j]`. When this happens, `traverse_sequences` will call the `MATCH` callback function and then it will advance both arrows. Otherwise, one of the arrows is pointing to an element of its sequence that is not part of the LCS. `traverse_sequences` will advance that arrow and will call the `DISCARD_A` or the `DISCARD_B` callback, depending on which arrow it advanced. If both arrows point to elements that are not part of the LCS, then `traverse_sequences` will advance one of them and call the appropriate callback, but it is not specified which it will call. The arguments to `traverse_sequences` are the two sequences to traverse, and a hash which specifies the callback functions, like this: ```raku traverse_sequences( @seq1, @seq2, MATCH => &callback_1, DISCARD_A => &callback_2, DISCARD_B => &callback_3, ); ``` Callbacks for MATCH, DISCARD_A, and DISCARD_B are invoked with at least the indices of the two arrows as their arguments. They are not expected to return any values. If a callback is omitted from the table, it is not called. Callbacks for A_FINISHED and B_FINISHED are invoked with at least the corresponding index in A or B. If arrow A reaches the end of its sequence, before arrow B does, `traverse_sequences` will call the `A_FINISHED` callback when it advances arrow B, if there is such a function; if not it will call `DISCARD_B` instead. Similarly if arrow B finishes first. `traverse_sequences` returns when both arrows are at the ends of their respective sequences. It returns true on success and false on failure. At present there is no way to fail. `traverse_sequences` may be passed an optional fourth parameter; this is a CODE reference to a key generation function. See [/KEY GENERATION FUNCTIONS](/KEY GENERATION FUNCTIONS). `traverse_sequences` does not have a useful return value; you are expected to plug in the appropriate behavior with the callback functions. traverse_balanced ----------------- `traverse_balanced` is an alternative to `traverse_sequences`. It uses a different algorithm to iterate through the entries in the computed LCS. Instead of sticking to one side and showing element changes as insertions and deletions only, it will jump back and forth between the two sequences and report *changes* occurring as deletions on one side followed immediatly by an insertion on the other side. In addition to the `DISCARD_A`, `DISCARD_B`, and `MATCH` callbacks supported by `traverse_sequences`, `traverse_balanced` supports a `CHANGE` callback indicating that one element got `replaced` by another: ```raku traverse_balanced( @seq1, @seq2, MATCH => $callback_1, DISCARD_A => $callback_2, DISCARD_B => $callback_3, CHANGE => $callback_4, ); ``` If no `CHANGE` callback is specified, `traverse_balanced` will map `CHANGE` events to `DISCARD_A` and `DISCARD_B` actions, therefore resulting in a similar behaviour as `traverse_sequences` with different order of events. `traverse_balanced` might be a bit slower than `traverse_sequences`, noticable only while processing huge amounts of data. The `sdiff` function of this module is implemented as call to `traverse_balanced`. `traverse_balanced` does not have a useful return value; you are expected to plug in the appropriate behavior with the callback functions. KEY GENERATION FUNCTIONS ======================== Most of the functions accept an optional extra parameter. This is a CODE reference to a key generating (hashing) function that should return a string that uniquely identifies a given element. It should be the case that if two elements are to be considered equal, their keys should be the same (and the other way around). If no key generation function is provided, the key will be the element as a string. By default, comparisons will use "eq" and elements will be turned into keys using the default stringizing operator '""'. Where this is important is when you're comparing something other than strings. If it is the case that you have multiple different objects that should be considered to be equal, you should supply a key generation function. Otherwise, you have to make sure that your arrays contain unique references. For instance, consider this example: ```raku class Person { has $.name; has $.ssn; our sub hash($person) { $person.ssn } } my $person1 = Person.new( name => 'Joe', ssn => '123-45-6789' ); my $person2 = Person.new( name => 'Mary', ssn => '123-47-0000' ); my $person3 = Person.new( name => 'Pete', ssn => '999-45-2222' ); my $person4 = Person.new( name => 'Peggy', ssn => '123-45-9999' ); my $person5 = Person.new( name => 'Frank', ssn => '000-45-9999' ); ``` If you did this: ```raku my $array1 = [ $person1, $person2, $person4 ]; my $array2 = [ $person1, $person3, $person4, $person5 ]; Algorithm::Diff::diff( $array1, $array2 ); ``` everything would work out OK (each of the objects would be converted into a string like "Person<2832536624368>" for comparison). But if you did this: ```raku my $array1 = [ $person1, $person2, $person4 ]; my $array2 = [ $person1, $person3, $person4.clone, $person5 ]; Algorithm::Diff::diff( $array1, $array2 ); ``` $person4 and $person4.clone (which have the same name and SSN) would be seen as different objects. If you wanted them to be considered equivalent, you would have to pass in a key generation function: ```raku my $array1 = [ $person1, $person2, $person4 ]; my $array2 = [ $person1, $person3, $person4.clone, $person5 ]; Algorithm::Diff::diff( $array1, $array2, \&Person::hash ); ``` This would use the 'ssn' field in each Person as a comparison key, and so would consider $person4 and $person4.clone as equal. AUTHOR ====== Based on Perl 5 version released by Tye McQueen (http://perlmonks.org/?node=tye). Initial procedural interface port by takadonet. Further procedural porting and object interface port by Steve Schulze. LICENSE ======= Parts Copyright (c) 2000-2004 Ned Konz. All rights reserved. Parts by Tye McQueen. Copyright 2024 Raku Community This program is free software; you can redistribute it and/or modify it under the same terms as Perl. CREDITS ======= Versions through 0.59 (and much of this documentation) were written by: Mark-Jason Dominus, [email protected] This version borrows some documentation and routine names from Mark-Jason's, but Diff.pm's code was completely replaced. This code was adapted from the Smalltalk code of Mario Wolczko <[email protected]>, which is available at ftp://st.cs.uiuc.edu/pub/Smalltalk/MANCHESTER/manchester/4.0/diff.st `sdiff` and `traverse_balanced` were written by Mike Schilli <[email protected]>. The algorithm is that described in *A Fast Algorithm for Computing Longest Common Subsequences*, CACM, vol.20, no.5, pp.350-353, May 1977, with a few minor improvements to improve the speed. Much work was done by Ned Konz ([email protected]). The OO interface and some other changes are by Tye McQueen. Raku port by Philip Mabon (takadonet) and Steve Schulze (thundergnat) Further maintenance by the Raku Community. ORIGINAL README =============== This is a module for computing the difference between two files, two strings, or any other two lists of things. It uses an intelligent algorithm similar to (or identical to) the one used by the Unix "diff" program. It is guaranteed to find the *smallest possible* set of differences. This package contains a few parts. Algorithm::Diff is the module that contains several interfaces for which computing the differences betwen two lists. The several "diff" programs also included in this package use Algorithm::Diff to find the differences and then they format the output. Algorithm::Diff also includes some other useful functions such as "LCS", which computes the longest common subsequence of two lists. A::D is suitable for many uses. You can use it for finding the smallest set of differences between two strings, or for computing the most efficient way to update the screen if you were replacing "curses". Algorithm::DiffOld is a previous version of the module which is included primarilly for those wanting to use a
### ---------------------------------------------------- ### -- Algorithm::Diff ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: README.md ### ---------------------------------------------------- ### -- Chunk 2 of 2 custom comparison function rather than a key generating function (and who don't mind the significant performance penalty of perhaps 20-fold). diff.pl implements a "diff" in Perl that is as simple as (was previously) possible so that you can see how it works. The output format is not compatible with regular "diff". It needs to be reimplemented using the OO interface to greatly simplify the code. diffnew.pl implements a "diff" in Perl with full bells and whistles. By Mark-Jason, with code from cdiff.pl included. cdiff.pl implements "diff" that generates real context diffs in either traditional format or GNU unified format. Original contextless "context" diff supplied by Christian Murphy. Modifications to make it into a real full-featured diff with -c and -u options supplied by Amir D. Karger. Yes, you can use this program to generate patches. OTHER RESOURCES "Longest Common Subsequences", at http://www.ics.uci.edu/~eppstein/161/960229.html This code was adapted from the Smalltalk code of Mario Wolczko <[email protected]>, which is available at ftp://st.cs.uiuc.edu/pub/Smalltalk/MANCHESTER/manchester/4.0/diff.st THANKS SECTION Thanks to Ned Konz's for rewriting the module to greatly improve performance, for maintaining it over the years, and for readilly handing it over to me so I could plod along with my improvements. (From Ned Konz's earlier versions): Thanks to Mark-Jason Dominus for doing the original Perl version and maintaining it over the last couple of years. Mark-Jason has been a huge contributor to the Perl community and CPAN; it's because of people like him that Perl has become a success. Thanks to Mario Wolczko <[email protected]> for writing and making publicly available his Smalltalk version of diff, which this Perl version is heavily based on. Thanks to Mike Schilli <[email protected]> for writing sdiff and traverse_balanced and making them available for the Algorithm::Diff distribution. (From Mark-Jason Dominus' earlier versions): Huge thanks to Amir Karger for adding full context diff support to "cdiff.pl", and then for waiting patiently for five months while I let it sit in a closet and didn't release it. Thank you thank you thank you, Amir! Thanks to Christian Murphy for adding the first context diff format support to "cdiff.pl".
### ---------------------------------------------------- ### -- Algorithm::Diff ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: dist.ini ### ---------------------------------------------------- name = Algorithm-Diff [ReadmeFromPod] ; enabled = false filename = doc/Algorithm-Diff.rakudoc [UploadToZef] [PruneFiles] ; match = ^ 'xt/' [Badges] provider = github-actions/linux.yml provider = github-actions/macos.yml provider = github-actions/windows.yml
### ---------------------------------------------------- ### -- Algorithm::Diff ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: bin/diff.raku ### ---------------------------------------------------- use v6; # `Diff' program in Perl # Current author # Copyright 2010 Philip Mabon ([email protected]) # Original author # Copyright 1998 M-J. Dominus. ([email protected]) # # This program is free software; you can redistribute it and/or modify it # under the same terms as Perl itself. # use Algorithm::Diff; sub MAIN (IO(Str) $file1, IO(Str) $file2) { die "File does not exists: '$file1'" unless $file1.e; die "File does not exists: '$file2'" unless $file2.e; my @f1 = $file1.lines; my @f2 = $file2.lines; if diff(@f1, @f2) -> @diffs { for @diffs -> @chunk { my ($sign, $lineno, $text) = @chunk; with $text { printf "%4d$sign %s\n", $lineno+1, $_; say "--------"; } } exit 1; } }
### ---------------------------------------------------- ### -- Algorithm::Diff ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: t/oo.rakutest ### ---------------------------------------------------- use Test; use Algorithm::Diff; plan 801; # Before 'make install' is performed this script should be runnable with # 'make test'. After 'make install' it should work as 'raku oo.t' my $undef; my ( $a, $b, $hunks ); for ( [ "a b c e h j l m n p", " b c d e f j k l m r s t", 9 ], [ "", "", 0 ], [ "a b c", "", 1 ], [ "", "a b c d", 1 ], [ "a b", "x y z", 1 ], [ " c e h j l m n p r", "a b c d f g j k l m s t", 7 ], [ "a b c d", "a b c d", 1 ], [ "a d", "a b c d", 3 ], [ "a b c d", "a d", 3 ], [ "a b c d", " b c ", 3 ], [ " b c ", "a b c d", 3 ], ) -> @pair { ( $a, $b, $hunks ) = @pair; my @a = $a.comb(/ \S+ /); my @b = $b.comb(/ \S+ /); my $d = Algorithm::Diff.new( @a, @b ); ok $d.defined, "It's defined..."; isa-ok $d, Algorithm::Diff, "... and it's an Algorithm::Diff"; # ('-' x 79).say; # say "Sequence A: ",$a; # say "Sequence B: ",$b; # $d.raku.say; # ('-' x 79).say; is( $d.Base, 0, 'call Base with nothing' ); is( $d.Base($undef), 0, 'call Base with undef' ); is( $d.Base(1), 0, 'call Base with 1' ); is( $d.Base($undef), 1, 'call Base with undef' ); is( $d.Base(0), 1, 'call Base with 0' ); dies-ok( { $d.Diff }, "dies properly on invalid Diff"); dies-ok( { $d.Same }, "dies properly on invalid Same" ); dies-ok( { $d.Items }, "dies properly on invalid Items" ); dies-ok( { $d.Range(2) }, "dies properly on invalid Range" ); dies-ok( { $d.Min(1) }, "dies properly on invalid Min" ); dies-ok( { $d.Max(2) }, "dies properly on invalid Max" ); is( $d.Next(0), 0, 'call Next with 0' ); dies-ok( { $d.Same }, 'dies properly on invalid Same' ); is( $d.Next, 1, 'call Next with 0' ) if 0 < $hunks; is( $d.Next($undef), 2, 'call Next with undef' ) if 1 < $hunks; is( $d.Next(1), 3, 'call Next with 1' ) if 2 < $hunks; is( $d.Next(-1), 2, 'call Next with -1' ) if 1 < $hunks; is( $d.Next(-2), 0, 'call Next with -2' ); dies-ok( { $d.Same }, "dies properly on invalid Same" ); is( $d.Prev(0), 0, 'Prev with 0' ); dies-ok( { $d.Same }, 'dies properly on invalid Same' ); is( $d.Prev, -1, 'call Prev with nothing' ) if 0 < $hunks; is( $d.Prev($undef), -2, 'call Prev with undef' ) if 1 < $hunks; is( $d.Prev(1), -3, 'call Prev with 1' ) if 2 < $hunks; is( $d.Prev(-1), -2, 'call Prev with -1' ) if 1 < $hunks; is( $d.Prev(-2), 0, 'call Prev with -2' ); is( $d.Next, 1, 'call Next with default' ) if 0 < $hunks; is( $d.Prev, 0, 'call Prev with default' ); is( $d.Next, 1, 'call Next with default' ) if 0 < $hunks; is( $d.Prev(2), 0, 'call Prev with step 2' ); is( $d.Prev, -1, 'call Prev with default' ) if 0 < $hunks; is( $d.Next, 0, 'call Next with default' ); is( $d.Prev, -1, 'call Prev with default' ) if 0 < $hunks; is( $d.Next(5), 0, 'call Next with step 5'); is( $d.Next, 1, 'call Next with default' ) if 0 < $hunks; is( $d.Reset, $d, 'Reset default returns object' ); is( $d.Prev(0), 0, 'Prev on Reset object already at 0' ); is( $d.Reset(3).Next(0), 3, 'chained Reset->Next returns correct term' ) if 2 < $hunks; is( $d.Reset(-2).Prev, -3, 'chained Reset->Prev returns correct term' ) if 2 < $hunks; is( $d.Reset(0).Next(-1), $hunks, 'chained Reset(0)->Next(-1) returns number of hunks' ); my $c = $d.Copy; isa-ok $c, Algorithm::Diff, 'Copy makes a new object of the correct type.'; is( $c.Base, $d.Base, 'with the correct Base' ); is( $c.Next(0), $d.Next(0), 'both iterate correctly' ); is( $d.Copy(-4).Next(0), $d.Copy().Reset(-4).Next(0), 'equivalent chained operations return equivalent results' ); $c = $d.Copy( $undef, 1 ); is( $c.Base(), 1, 'Copy with parameters yields expected result' ); is( $c.Next(0), $d.Next(0), 'Copy with parameters iterates correctly' ); $d.Reset(); my ( @A, @B ); # The two tests in the following group marked with the comments are different # from the Perl tests. .Same and .Items return elements and .Range returns # indicies. The Perlests were comparing array refs in scalar context so they # would pass as long as they both were the same size. Now they check to see if # they have the same contents. while ( $d.Next ) { my $i = 1; if ( $d.Same ) { is( $d.Diff, 0, "if loop sequence #{$i++}" ); is( $d.Same, @b[$d.Range(2)], "if loop sequence #{$i++}" ); # different from Perl !! is( $d.Items(2), @a[$d.Range(1)], "if loop sequence #{$i++}" ); # different from Perl!! is( ~$d.Same, ~$d.Items(1), "if loop sequence #{$i++}" ); is( ~$d.Items(1), ~$d.Items(2), "if loop sequence #{$i++}" ); is( ~$d.Items(2), ~@a[$d.Range(1)], "if loop sequence #{$i++}" ); is( ~@a[$d.Range(1,0)], @b[$d.Range(2)], "if loop sequence #{$i++}" ); append @A, $d.Same; append @B, @b[$d.Range(2)]; } else { is( $d.Same, '', "else loop sequence #{$i++}" ); is( $d.Diff && 1, 1 * $d.Range(1).Bool, "else loop sequence #{$i++}" ); is( $d.Diff && 2, 2 * $d.Range(2).Bool, "else loop sequence #{$i++}" ); is( ~$d.Items(1), ~@a[$d.Range(1)], "else loop sequence #{$i++}" ); is( ~$d.Items(2), ~@b[$d.Range(2,0)], "else loop sequence #{$i++}" ); append @A, @a[$d.Range(1)]; append @B, $d.Items(2); } } is( ~@A, ~@a, 'A & a arrays are equivalent' ); is( ~@B, ~@b, 'B & b arrays are equivalent' ); next unless $hunks; is($d.Next, 1, 'next ok if hunks left' ); dies-ok( { $d.Items }, 'need to call Items with a parameter' ); dies-ok( { $d.Items(0) }, 'need to call Items with a valid parameter' ); dies-ok( { $d.Range }, 'need to call Range with a parameter' ); dies-ok( { $d.Range(3) }, 'need to call Range with a valid parameter' ); dies-ok( { $d.Min }, 'need to call Min with a parameter' ); dies-ok( { $d.Min(-1) }, 'need to call Min with a valid parameter' ); dies-ok( { $d.Max }, 'need to call Max with a parameter' ); dies-ok( { $d.Max(9) }, 'need to call Max with a valid parameter' ); $d.Reset(-1); $c = $d.Copy( $undef, 1 ); is( ~@a[$d.Range(1)], ~[(0,@a).flat.[$c.Range(1)]], 'Range offsets are sane' ); is( ~@b[$c.Range(2,0)], ~[(0,@b).flat.[$d.Range(2,1)]], 'Range offsets are sane' ); } ############################################################################## # .Get not implemented so can't test Get method # # ok( "@a[$d->Get('min1')..$d->Get('0Max1')]", # "@{[(0,@a)[$d->Get('1MIN1')..$c->Get('MAX1')]]}" ); # ok( "@{[$c->Min(1),$c->Max(2,0)]}", # "@{[$c->Get('Min1','0Max2')]}" ); # ok( ! eval { scalar $c->Get('Min1','0Max2'); 1 } ); # ok( "@{[0+$d->Same(),$d->Diff(),$d->Base()]}", # "@{[$d->Get(qq<same Diff BASE>)]}" ); # ok( "@{[0+$d->Range(1),0+$d->Range(2)]}", # "@{[$d->Get(qq<Range1 rAnGe2>)]}" ); # ok( ! eval { $c->Get('range'); 1 } ); # ok( ! eval { $c->Get('min'); 1 } ); # ok( ! eval { $c->Get('max'); 1 } ); } # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- Algorithm::Diff ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: t/base.rakutest ### ---------------------------------------------------- use Test; use Algorithm::Diff; plan 61; my @d = (2,4,6,8,10); my ($h, $i); $i = Algorithm::Diff::_replaceNextLargerWith( @d, 3, $h ); is( ~@d, '2 3 6 8 10', "_replaceNextLargerWith() works ok for inserts"); is( $i, 1, "_replaceNextLargerWith() returns correct index for inserts"); $i = Algorithm::Diff::_replaceNextLargerWith( @d, 0, $h ); is( ~@d, '0 3 6 8 10', "_replaceNextLargerWith() works ok for inserts at beginning"); is( $i, 0, "_replaceNextLargerWith() returns correct index for inserts at beginning"); $i = Algorithm::Diff::_replaceNextLargerWith( @d, 11, $h ); is( ~@d, '0 3 6 8 10 11', "_replaceNextLargerWith() works ok for inserts at end"); is( $i, 5, "_replaceNextLargerWith() returns correct index for inserts at end"); $i = Algorithm::Diff::_replaceNextLargerWith( @d, 6, $h ); is( ~@d, '0 3 6 8 10 11', "_replaceNextLargerWith() doesn't change array for already seen elements"); ok( !$i.defined, "_replaceNextLargerWith() returns undef index for already seen elements"); my @a = <a b c e h j l m n p>; my @b = <b c d e f j k l m r s t>; my @correctResult = <b c e j l m>; my $correctResult = @correctResult.join(' '); my $skippedA = 'a h n p'; my $skippedB = 'd f k r s t'; # Result of LCS must be as long as @a my @result = Algorithm::Diff::_longestCommonSubsequence( @a, @b ); is( @result.grep( *.defined ).elems(), @correctResult.elems(), "_longestCommonSubsequence returns expected number of elements" ); # result has b[] line#s keyed by a[] line# #say "result = " ~ @result; my @aresult = map { @result[$_].defined ?? @a[$_] !! slip() } , 0..^@result; my @bresult = map { @result[$_].defined ?? @b[@result[$_]] !! slip() } , 0..^@result; is( ~@aresult, $correctResult, "_longestCommonSubsequence @a results match expected results" ); is( ~@bresult, $correctResult, "_longestCommonSubsequence @b results match expected results" ); my ( @matchedA, @matchedB, @discardsA, @discardsB, $finishedA, $finishedB ); sub match { my ( $a, $b ) = @_; @matchedA.push( @a[$a] ); @matchedB.push( @b[$b] ); } sub discard_b { my ( $a, $b ) = @_; @discardsB.push(@b[$b]); } sub discard_a { my ( $a, $b ) = @_; @discardsA.push(@a[$a]); } sub finished_a { my ( $a, $b ) = @_; $finishedA = $a; } sub finished_b { my ( $a, $b ) = @_; $finishedB = $b; } traverse_sequences(@a, @b, MATCH => &match, DISCARD_A => &discard_a, DISCARD_B => &discard_b ); is( ~@matchedA, $correctResult, "traverse_sequences() returns expected matches for @a"); is( ~@matchedB, $correctResult, "traverse_sequences() returns expected matches for @b"); is( ~@discardsA, $skippedA, "traverse_sequences() returns expected skips for @a"); is( ~@discardsB, $skippedB, "traverse_sequences() returns expected skips for @b"); @matchedA = @matchedB = @discardsA = @discardsB = (); $finishedA = $finishedB = Mu; traverse_sequences(@a,@b, MATCH => &match, DISCARD_A => &discard_a, DISCARD_B => &discard_b, A_FINISHED => &finished_a, B_FINISHED => &finished_b, ); is( ~@matchedA, $correctResult, "traverse_sequences() w/finished callback gives expected matches for @a"); is( ~@matchedB, $correctResult, "traverse_sequences() w/finished callback gives expected matches for @b"); is( ~@discardsA, $skippedA, "traverse_sequences() w/finished callback gives expected skips for @a"); is( ~@discardsB, $skippedB, "traverse_sequences() w/finished callback gives expected skips for @b"); is( $finishedA, 9, "traverse_sequences() index of finishedA is as expected" ); ok( !$finishedB.defined, "traverse_sequences() index of finishedB is as expected" ); ######################################################## # Compare the diff output with the one from the Algorithm::Diff manpage. my $diff = diff( @a, @b ); # From the Algorithm::Diff manpage: my $correctDiffResult = [ [ [ '-', 0, 'a' ] ], [ [ '+', 2, 'd' ] ], [ [ '-', 4, 'h' ], [ '+', 4, 'f' ] ], [ [ '+', 6, 'k' ] ], [ [ '-', 8, 'n' ], [ '+', 9, 'r' ], [ '-', 9, 'p' ], [ '+', 10, 's' ], [ '+', 11, 't' ], ] ]; is( $diff, $correctDiffResult, 'diff() returns expected output'); my @lcs = LCS( @a, @b ); is( ~@lcs, $correctResult, "LCS() returns expected result" ); is(LCS_length( @a, @b ), +@lcs, 'LCS_length() returns expected result' ); my $keygen = sub { @_[0].uc }; my @au = @a>>.uc; my %hash = prepare(@b); @lcs = LCS( @a, %hash ); is( ~@lcs, $correctResult, "LCS() with prepare returns expected result" ); @lcs = LCS( %hash, @a ); is( ~@lcs, $correctResult, "LCS() with prepare returns expected result" ); @lcs = LCS( @au, @b, $keygen ); is( ~@lcs, $correctResult.uc, "LCS() with keygen returns expected result" ); @lcs = LCS( @au, prepare(@b>>.uc), $keygen ); is( ~@lcs, $correctResult.uc, "LCS() with prepare and keygen returns expected result" ); ######################################################################## # Exercise LCS (which in turn calls _longestCommonSubsequence, # _replaceNextLargerWith & _withPositionsOfInInterval ) with # various corner cases. # my $count = 1; for ( [ "a b c e h j l m n p", " b c d e f j k l m r s t", "b c e j l m" ], [ "", "", "" ], [ "a b c", "", "" ], [ "", "a b c d", "" ], [ "a b", "x y z", "" ], [ " c e h j l m n p r", "a b c d f g j k l m s t", "c j l m" ], [ "a b c d", "a b c d", "a b c d" ], [ "a d", "a b c d", "a d" ], [ "a b c d", "a d", "a d" ], [ "a b c d", " b c ", "b c" ], [ " b c ", "a b c d", "b c" ], ) -> @group { my ( $a, $b, $check ) = @group; @a = $a.comb(/ \S+ /); @b = $b.comb(/ \S+ /); is( ~LCS(@a,@b), $check, "Excercise LCS with various corner cases: #$count"); $count++; } ######################################################################## # Compare the compact_diff output with the one # from the Algorithm::Diff manpage. @a = <a b c e h j l m n p >; @b = < b c d e f j k l m r s t>; my @cdiff = compact_diff( @a, @b ); is(@cdiff, # @a @b @a @b # start start values values [ 0, 0, # = 0, 0, # a ! 1, 0, # b c = b c 3, 2, # ! d 3, 3, # e = e 4, 4, # f ! h 5, 5, # j = j 6, 6, # ! k 6, 7, # l m = l m 8, 9, # n p ! r s t 10, 12 # ], "compact_diff() returns expected result" ); ################################################## # <Mike Schilli> [email protected] 03/23/2002: # Tests for sdiff-interface ################################################# @a = <abc def yyy xxx ghi jkl>; @b = <abc dxf xxx ghi jkl>; $correctDiffResult = [ ['u', 'abc', 'abc'], ['c', 'def', 'dxf'], ['-', 'yyy', ''], ['u', 'xxx', 'xxx'], ['u', 'ghi', 'ghi'], ['u', 'jkl', 'jkl'] ]; @result = sdiff(@a, @b); is(@result, $correctDiffResult, 'sdiff() returns expected output for multi-character strings'); ################################################# @a = <a b c e h j l m n p>; @b = <b c d e f j k l m r s t>; $correctDiffResult = [ ['-', 'a', '' ], ['u', 'b', 'b'], ['u', 'c', 'c'], ['+', '', 'd'], ['u', 'e', 'e'], ['c', 'h', 'f'], ['u', 'j', 'j'], ['+', '', 'k'], ['u', 'l', 'l'], ['u', 'm', 'm'], ['c', 'n', 'r'], ['c', 'p', 's'], ['+', '', 't'], ]; @result = sdiff(@a, @b); is(@result,$correctDiffResult, 'sdiff() output correct'); ################################################# @a = <a b c d e>; @b = <a e>; $correctDiffResult = [ ['u', 'a', 'a' ], ['-', 'b', ''], ['-', 'c', ''], ['-', 'd', ''], ['u', 'e', 'e'], ]; @result = sdiff(@a, @b); is(@result, $correctDiffResult, 'sdiff() output ok, various corner cases'); ################################################# @a = <a e>; @b = <a b c d e>; $correctDiffResult = [ ['u', 'a', 'a' ], ['+', '', 'b'], ['+', '', 'c'], ['+', '', 'd'], ['u', 'e', 'e'], ]; @result = sdiff(@a, @b); is(@result, $correctDiffResult, 'sdiff() output ok, various corner cases'); ################################################# @a = <v x a e>; @b = <w y a b c d e>; $correctDiffResult = [ ['c', 'v', 'w' ], ['c', 'x', 'y' ], ['u', 'a', 'a' ], ['+', '', 'b'], ['+', '', 'c'], ['+', '', 'd'], ['u', 'e', 'e'], ]; @result = sdiff(@a, @b); is(@result, $correctDiffResult, 'sdiff() output ok, various corner cases'); ################################################# @a = <x a e>; @b = <a b c d e>; $correctDiffResult = [ ['-', 'x', '' ], ['u', 'a', 'a' ], ['+', '', 'b'], ['+', '', 'c'], ['+', '', 'd'], ['u', 'e', 'e'], ]; @result = sdiff(@a, @b); is(@result, $correctDiffResult, 'sdiff() output ok, various corner cases'); ################################################# @a = <a e>; @b = <x a b c d e>; $correctDiffResult = [ ['+', '', 'x' ], ['u', 'a', 'a' ], ['+', '', 'b'], ['+', '', 'c'], ['+', '', 'd'], ['u', 'e', 'e'], ]; @result = sdiff(@a, @b); is(@result, $correctDiffResult, 'sdiff() output ok, various corner cases'); ################################################# @a = <a e v>; @b = <x a b c d e w x>; $correctDiffResult = [ ['+', '', 'x' ], ['u', 'a', 'a' ], ['+', '', 'b'], ['+', '', 'c'], ['+', '', 'd'], ['u', 'e', 'e'], ['c', 'v', 'w'], ['+', '', 'x'], ]; @result = sdiff(@a, @b); is(@result, $correctDiffResult, 'sdiff() output ok, various corner cases'); ################################################# @a=(); @b = <a b c>; $correctDiffResult = [ ['+', '', 'a' ], ['+', '', 'b' ], ['+', '', 'c' ], ]; @result = sdiff(@a, @b); is(@result, $correctDiffResult, 'sdiff() output ok, various corner cases'); ################################################# @a = <a b c>; @b = (); $correctDiffResult = [ ['-', 'a', '' ], ['-', 'b', '' ], ['-', 'c', '' ], ]; @result = sdiff(@a, @b); is(@result, $correctDiffResult, 'sdiff() output ok, various corner cases'); ################################################# @a = <a b c>; @b = <1>; $correctDiffResult = [ ['c', 'a', '1' ], ['-', 'b', '' ], ['-', 'c', '' ], ]; @result = sdiff(@a, @b); is(@result, $correctDiffResult, 'sdiff() output ok, various corner cases'); ################################################# @a = <a b c>; @b = <c>; $correctDiffResult = [ ['-', 'a', '' ], ['-', 'b', '' ], ['u', 'c', 'c' ], ]; @result = sdiff(@a, @b); is(@result, $correctDiffResult, 'sdiff() output ok, various corner cases'); ################################################# @a = <a b c>; @b = <a x c>; my $r = ""; traverse_balanced( @a, @b, MATCH => sub { $r ~= "M " ~@_;}, DISCARD_A => sub { $r ~= "DA " ~@_;}, DISCARD_B => sub { $r ~= "DB " ~@_;}, CHANGE => sub { $r ~= "C " ~@_;}, ); is($r, "M 0 0C 1 1M 2 2", "traverse_balanced() output ok" ); ################################################# #No CHANGE callback => use discard_a/b instead @a = <a b c>; @b = <a x c>; $r = ""; traverse_balanced( @a, @b, MATCH => sub { $r ~= "M " ~@_;}, DISCARD_A => sub { $r ~= "DA " ~@_;}, DISCARD_B => sub { $r ~= "DB " ~@_;}, ); is($r, "M 0 0DA 1 1DB 2 1M 2 2", "traverse_balanced() with no CHANGE callback output ok"); ################################################# @a = <a x y c>; @b = <a v w c>; $r = ""; traverse_balanced( @a, @b, MATCH => sub { $r ~= "M " ~@_;}, DISCARD_A => sub { $r ~= "DA " ~@_;}, DISCARD_B => sub { $r ~= "DB " ~@_;}, CHANGE => sub { $r ~= "C " ~@_;}, ); is($r, "M 0 0C 1 1C 2 2M 3 3", "traverse_balanced() output ok, various corner cases"); ################################################# @a = <a x y c>; @b = <a v c>; $r = ""; traverse_balanced( @a, @b, MATCH => sub { $r ~= "M " ~@_;}, DISCARD_A => sub { $r ~= "DA " ~@_;}, DISCARD_B => sub { $r ~= "DB " ~@_;}, CHANGE => sub { $r ~= "C " ~@_;}, ); is($r, "M 0 0C 1 1DA 2 2M 3 2", "traverse_balanced() output ok, various corner cases"); ################################################# @a = <x y c>; @b = <v w c>; $r = ""; traverse_balanced( @a, @b, MATCH => sub { $r ~= "M " ~@_;}, DISCARD_A => sub { $r ~= "DA " ~@_;}, DISCARD_B => sub { $r ~= "DB " ~@_;}, CHANGE => sub { $r ~= "C " ~@_;}, ); is($r, "C 0 0C 1 1M 2 2", "traverse_balanced() output ok, various corner cases"); ################################################# @a = <a x y z>; @b = <b v w>; $r = ""; traverse_balanced( @a, @b, MATCH => sub { $r ~= "M " ~@_;}, DISCARD_A => sub { $r ~= "DA " ~@_;}, DISCARD_B => sub { $r ~= "DB " ~@_;}, CHANGE => sub { $r ~= "C " ~@_;}, ); is($r, "C 0 0C 1 1C 2 2DA 3 3", "traverse_balanced() output ok, various corner cases"); ################################################# @a = <a z>; @b = <a>; $r = ""; traverse_balanced( @a, @b, MATCH => sub { $r ~= "M " ~@_;}, DISCARD_A => sub { $r ~= "DA " ~@_;}, DISCARD_B => sub { $r ~= "DB " ~@_;}, CHANGE => sub { $r ~= "C " ~@_;}, ); is($r, "M 0 0DA 1 1", "traverse_balanced() output ok, various corner cases"); ################################################# @a = <z a>; @b = <a>; $r = ""; traverse_balanced( @a, @b, MATCH => sub { $r ~= "M " ~@_;}, DISCARD_A => sub { $r ~= "DA " ~@_;}, DISCARD_B => sub { $r ~= "DB " ~@_;}, CHANGE => sub { $r ~= "C " ~@_;}, ); is($r, "DA 0 0M 1 0", "traverse_balanced() output ok, various corner cases"); ################################################# @a = <a b c>; @b = <x y z>; $r = ""; traverse_balanced( @a, @b, MATCH => sub { $r ~= "M " ~@_;}, DISCARD_A => sub { $r ~= "DA " ~@_;}, DISCARD_B => sub { $r ~= "DB " ~@_;}, CHANGE => sub { $r ~= "C " ~@_;}, ); is($r, "C 0 0C 1 1C 2 2", "traverse_balanced() output ok, various corner cases"); # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- Algorithm::Diff ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: t/issue12.rakutest ### ---------------------------------------------------- use Test; use Algorithm::Diff; plan 2; # This test catches triggers the following error: # Type check failed for return value; expected Int but got Mu (Mu) # in sub _replaceNextLargerWith at /home/alex/src/Algorithm--Diff/lib/Algorithm/Diff.pm (Algorithm::Diff) line 56 # ... my $a = "The Way that can be told of is not the eternal Way"; my $b = "The Tao that can be told of is not the eternal Tao"; my @alist = $a.split(/<|w>/); my @blist = $b.split(/<|w>/); my $diff = Algorithm::Diff.new(@alist, @blist); my @from; my @to; while $diff.Next { if $diff.Same { @from.append($diff.Items(1)); @to.append($diff.Items(2)); } else { @from.push('<del>' ~ $diff.Items(1) ~ '</del>') if $diff.Items(1); @to.push('<ins>' ~ $diff.Items(2) ~ '</ins>') if $diff.Items(2); } } is @from.join(''), "The <del>Way</del> that can be told of is not the eternal <del>Way</del>", "deletions"; is @to.join(''), "The <ins>Tao</ins> that can be told of is not the eternal <ins>Tao</ins>", "insertions"; # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- Algorithm::Diff ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: lib/Algorithm/Diff.rakumod ### ---------------------------------------------------- class Algorithm::Diff { # # McIlroy-Hunt diff algorithm # # Adapted from the Smalltalk code of Mario I. Wolczko, <[email protected]> # # by Ned Konz, [email protected] # # Updates by Tye McQueen, http://perlmonks.org/?node=tye # # Raku port by Philip Mabon aka: takadonet. # Additional porting by Stephen Schulze, aka: thundergnat. # default key generator to use in the most common case: # comparison of two strings my &default_keyGen = { @_[0] } # Create a hash that maps each element of @aCollection to the set of # positions it occupies in @aCollection, restricted to the elements # within the range of indexes specified by $start and $end. # The fourth parameter is a subroutine reference that will be called to # generate a string to use as a key. # # my %hash = _withPositionsOfInInterval( @array, $start, $end, &keyGen ); sub _withPositionsOfInInterval( @aCollection, $start, $end, &keyGen ) { my %d; for $start .. $end -> $index { %d{keyGen(@aCollection[$index])}.unshift($index); } %d } # Find the place at which aValue would normally be inserted into the # array. If that place is already occupied by aValue, do nothing, and # return undef. If the place does not exist (i.e., it is off the end of # the array), add it to the end, otherwise replace the element at that # point with aValue. It is assumed that the array's values are numeric. # This is where the bulk (75%) of the time is spent in this module, so # try to make it fast! our sub _replaceNextLargerWith( @array, $aValue, $high is copy ) { $high ||= +@array-1; # off the end? if $high == -1 || $aValue > @array[*-1] { @array.push($aValue); return $high + 1; } # binary search for insertion point... my $low = 0; my $index; my $found; while $low <= $high { $index = (( $high + $low ) / 2).Int; $found = @array[$index]; if $aValue == $found { return Int; } elsif $aValue > $found { $low = $index + 1; } else { $high = $index - 1; } } # now insertion point is in $low. @array[$low] = $aValue; # overwrite next larger $low } # This method computes the longest common subsequence in @a and @b. # Result is array whose contents is such that # @a[ $i ] == @b[ @result[ $i ] ] # foreach $i in ( 0 .. ^@result ) if @result[ $i ] is defined. # An additional argument may be passed; this is a hash or key generating # function that should return a string that uniquely identifies the given # element. It should be the case that if the key is the same, the elements # will compare the same. If this parameter is undef or missing, the key # will be the element as a string. # By default, comparisons will use "eq" and elements will be turned into keys # using the default stringizing operator '""'. # If passed two arrays, trim any leading or trailing common elements, then # process (&prepare) the second array to a hash and redispatch our proto sub _longestCommonSubsequence(@a,$,$counting?,&fcn?,%args?,*%) {*} our multi sub _longestCommonSubsequence( @a, @b, $counting = 0, &keyGen = &default_keyGen ) { my sub compare( $a, $b ) { keyGen( $a ) eq keyGen( $b ) } my ( $aStart, $aFinish ) = ( 0, +@a-1 ); my ( $bStart, $bFinish ) = ( 0, +@b-1 ); my @matchVector; my ( $prunedCount, %bMatches ) = ( 0, %({}) ); # First we prune off any common elements at the beginning while $aStart <= $aFinish and $bStart <= $bFinish and compare( @a[$aStart], @b[$bStart]) { @matchVector[ $aStart++ ] = $bStart++; $prunedCount++; } # now the end while $aStart <= $aFinish and $bStart <= $bFinish and compare( @a[$aFinish], @b[$bFinish] ) { @matchVector[ $aFinish-- ] = $bFinish--; $prunedCount++; } # Now compute the equivalence classes of positions of elements %bMatches = _withPositionsOfInInterval( @b, $bStart, $bFinish, &keyGen); # and redispatch _longestCommonSubsequence( @a, %bMatches, $counting, &keyGen, PRUNED => $prunedCount, ASTART => $aStart, AFINISH => $aFinish, MATCHVEC => @matchVector ) } our multi sub _longestCommonSubsequence( @a, %bMatches, $counting = 0, &keyGen = &default_keyGen, :PRUNED( $prunedCount ), :ASTART( $aStart ) = 0, :AFINISH( $aFinish ) = +@a-1, :MATCHVEC( @matchVector ) = [] ) { my ( @thresh, @links, $ai ); for $aStart .. $aFinish -> $i { $ai = keyGen( @a[$i] ); if %bMatches{$ai}:exists { my $k; for @(%bMatches{$ai}) -> $j { # optimization: most of the time this will be true if ( $k and @thresh[$k] > $j and @thresh[ $k - 1 ] < $j ) { @thresh[$k] = $j; } else { $k = _replaceNextLargerWith( @thresh, $j, $k ); } # oddly, it's faster to always test this (CPU cache?). # ( still true for Raku? need to test. ) if $k.defined { @links[$k] = $k ?? [ @links[ $k - 1 ] , $i, $j ] !! [ Mu, $i, $j ]; } } } } if @thresh { return $prunedCount + @thresh if $counting; loop ( my $link = @links[+@thresh-1] ; $link ; $link = $link[0] ) { @matchVector[ $link[1] ] = $link[2]; } } elsif $counting { return $prunedCount; } @matchVector } sub traverse_sequences( @a, @b, &keyGen = &default_keyGen, :MATCH( &match ), :DISCARD_A( &discard_a ), :DISCARD_B( &discard_b ), :A_FINISHED( &finished_a ) is copy, :B_FINISHED( &finished_b ) is copy ) is export(:traverse_sequences :DEFAULT) { my @matchVector = _longestCommonSubsequence( @a, @b, 0, &keyGen ); # Process all the lines in @matchVector my ( $lastA, $lastB, $bi ) = ( +@a-1, +@b-1, 0 ); my $ai; loop ( $ai = 0 ; $ai < +@matchVector ; $ai++ ) { my $bLine = @matchVector[$ai]; if $bLine.defined { # matched discard_b( $ai, $bi++ ) while $bi < $bLine; match( $ai, $bi++ ); } else { discard_a( $ai, $bi); } } # The last entry (if any) processed was a match. # $ai and $bi point just past the last matching lines in their sequences. while $ai <= $lastA or $bi <= $lastB { # last A? if $ai == $lastA + 1 and $bi <= $lastB { if &finished_a.defined { finished_a( $lastA ); &finished_a = sub {}; } else { discard_b( $ai, $bi++ ) while $bi <= $lastB; } } # last B? if ( $bi == $lastB + 1 and $ai <= $lastA ) { if &finished_b.defined { finished_b( $lastB ); &finished_b = sub {}; } else { discard_a( $ai++, $bi ) while $ai <= $lastA; } } discard_a( $ai++, $bi ) if $ai <= $lastA; discard_b( $ai, $bi++ ) if $bi <= $lastB; } 1 } sub traverse_balanced( @a, @b, &keyGen = &default_keyGen, :MATCH( &match ), :DISCARD_A( &discard_a ), :DISCARD_B( &discard_b ), :CHANGE( &change ) ) is export { my @matchVector = _longestCommonSubsequence( @a, @b, 0, &keyGen ); # Process all the lines in match vector my ( $lastA, $lastB ) = ( +@a-1, +@b-1); my ( $bi, $ai, $ma ) = ( 0, 0, -1 ); my $mb; loop { # Find next match indices $ma and $mb repeat { $ma++; } while $ma < +@matchVector && !(@matchVector[$ma].defined); last if $ma >= +@matchVector; # end of matchVector? $mb = @matchVector[$ma]; # Proceed with discard a/b or change events until # next match while $ai < $ma || $bi < $mb { if $ai < $ma && $bi < $mb { # Change if &change.defined { change( $ai++, $bi++); } else { discard_a( $ai++, $bi); discard_b( $ai, $bi++); } } elsif $ai < $ma { discard_a( $ai++, $bi); } else { # $bi < $mb discard_b( $ai, $bi++); } } # Match match( $ai++, $bi++ ); } while $ai <= $lastA || $bi <= $lastB { if $ai <= $lastA && $bi <= $lastB { # Change if &change.defined { change( $ai++, $bi++); } else { discard_a( $ai++, $bi); discard_b( $ai, $bi++); } } elsif $ai <= $lastA { discard_a( $ai++, $bi); } else { # $bi <= $lastB discard_b( $ai, $bi++); } } 1 } sub prepare ( @a, &keyGen = &default_keyGen ) is export { _withPositionsOfInInterval( @a, 0, +@a-1, &keyGen ) } proto sub LCS(|) is export {*} multi sub LCS( %b, @a, &keyGen = &default_keyGen ) { # rearrange args and re-dispatch LCS( @a, %b, &keyGen ) } multi sub LCS( @a, @b, &keyGen = &default_keyGen ) { my @matchVector = _longestCommonSubsequence( @a, @b, 0, &keyGen); @a[(^@matchVector).grep: { @matchVector[$^a].defined }] } multi sub LCS( @a, %b, &keyGen = &default_keyGen ) { my @matchVector = _longestCommonSubsequence( @a, %b, 0, &keyGen); @a[(^@matchVector).grep: { @matchVector[$^a].defined }]; } sub LCS_length( @a, @b, &keyGen = &default_keyGen ) is export { _longestCommonSubsequence( @a, @b, 1, &keyGen ) } sub LCSidx( @a, @b, &keyGen = &default_keyGen ) is export { my @match = _longestCommonSubsequence( @a, @b, 0, &keyGen ); my $amatch_indices = (^@match).grep({ @match[$^a].defined }).list; my $bmatch_indices = @match[@$amatch_indices]; ($amatch_indices, $bmatch_indices); } sub compact_diff( @a, @b, &keyGen = &default_keyGen ) is export { my ( $am, $bm ) = LCSidx( @a, @b, &keyGen ); my @am = $am.list; my @bm = $bm.list; my @cdiff; my ( $ai, $bi ) = ( 0, 0 ); @cdiff.append: $ai, $bi; loop { while @am && $ai == @am.[0] && $bi == @bm.[0] { @am.shift; @bm.shift; ++$ai, ++$bi; } @cdiff.append: $ai, $bi; last if !@am; $ai = @am.[0]; $bi = @bm.[0]; @cdiff.append: $ai, $bi; } @cdiff.append( +@a, +@b ) if $ai < @a || $bi < @b; @cdiff } sub diff( @a, @b ) is export { my ( @retval, @hunk ); traverse_sequences( @a, @b, MATCH => sub ($x,$y) { @retval.append( @hunk ); @hunk = () }, DISCARD_A => sub ($x,$y) { @hunk.push( [ '-', $x, @a[ $x ] ] ) }, DISCARD_B => sub ($x,$y) { @hunk.push( [ '+', $y, @b[ $y ] ] ) } ); @retval, @hunk } sub sdiff( @a, @b ) is export { my @retval; traverse_balanced( @a, @b, MATCH => sub ($x,$y) { @retval.push( [ 'u', @a[ $x ], @b[ $y ] ] ) }, DISCARD_A => sub ($x,$y) { @retval.push( [ '-', @a[ $x ], '' ] ) }, DISCARD_B => sub ($x,$y) { @retval.push( [ '+', '' , @b[ $y ] ] ) }, CHANGE => sub ($x,$y) { @retval.push( [ 'c', @a[ $x ], @b[ $y ] ] ) } ); @retval } ############################################################################# # Object Interface # has @._Idx is rw; # Array of hunk indices has @._Seq is rw; # First , Second sequence has $._End is rw; # Diff between forward and reverse pos has $._Same is rw; # 1 if pos 1 contains unchanged items has $._Base is rw; # Added to range's min and max has $._Pos is rw; # Which hunk is currently selected has $._Off is rw; # Offset into _Idx for current position has $._Min = -2; # Added to _Off to get min instead of max+1 method new ( @seq1, @seq2, &keyGen = &default_keyGen ) { my @cdif = compact_diff( @seq1, @seq2, &keyGen ); my $same = 1; if 0 == @cdif[2] && 0 == @cdif[3] { $same = 0; @cdif.splice( 0, 2 ); } Algorithm::Diff.bless( :_Idx( @cdif ), :_Seq( '', [@seq1], [@seq2] ), :_End( ((1 + @cdif ) / 2).Int ), :_Same( $same ), :_Base( 0 ), :_Pos( 0 ), :_Off( 0 ), ) } # sanity check to make sure Pos index is a defined & non-zero. method _ChkPos { die( "Method illegal on a \"Reset\" Diff object" ) unless $._Pos; } # increment Pos index pointer; default: +1, or passed parameter. method Next ($steps? is copy ) { $steps = 1 if !$steps.defined; if $steps { my $pos = $._Pos; my $new = $pos + $steps; $new = 0 if ($pos and $new) < 0; self.Reset( $new ); } $._Pos } # inverse of Next. method Prev ( $steps? is copy ) { $steps = 1 unless $steps.defined; my $pos = self.Next( -$steps ); $pos -= $._End if $pos; $pos } # set the Pos pointer to passed index or 0 if none passed. method Reset ( $pos? is copy ) { $pos = 0 unless $pos.defined; $pos += $._End if $pos < 0; $pos = 0 if $pos < 0 || $._End <= $pos; $._Pos = $pos // 0; $._Off = 2 * $pos - 1; self } # make sure a valid hunk is at the sequence/offset. method _ChkSeq ( $seq ) { 1 == $seq || 2 == $seq ?? $seq + $._Off !! die( "Invalid sequence number ($seq); must be 1 or 2" ); } # Change indexing base to the passed parameter (0 or 1 typically). method Base ( $base? ) { my $oldBase = $._Base; $._Base = 0 + $base if $base.defined; $oldBase } # Generate a new Diff object bassed on an existing one. method Copy ( $pos?, $base? ) { my $you = self.clone; $you.Reset( $pos ) if $pos.defined; $you.Base( $base ); $you } # returns the index of the first item in a given hunk. method Min ( $seq, $base? is copy ) { self._ChkPos; my $off = self._ChkSeq( $seq ); $base = $._Base if !$base.defined; $base + @._Idx[ $off + $._Min ] } # returns the index of the last item in a given hunk. method Max ( $seq, $base? is copy ) { self._ChkPos; my $off = self._ChkSeq( $seq ); $base = $._Base if !$base.defined; $base + @._Idx[ $off ] - 1 } # returns the indicies of the items in a given hunk. method Range ( $seq, $base? is copy ) { self._ChkPos; my $off = self._ChkSeq( $seq ); $base = $._Base if !$base.defined; ( $base + @._Idx[ $off + $._Min ] ) .. ( $base + @._Idx[ $off ] - 1 ) } # returns the items in a given hunk. method Items ( $seq ) { self._ChkPos; my $off = self._ChkSeq( $seq ); @._Seq[$seq][@._Idx[ $off + $._Min ] .. @._Idx[ $off ] - 1 ] } # returns a bit mask representing the operations to change the current # hunk from seq2 to seq1. # 0 - no change # 1 - delete items from sequence 1 # 2 - insert items from sequence 2 # 3 - replace items from sequence 1 with those from sequence 2 method Diff { self._ChkPos; return 0 if $._Same == ( 1 +& $._Pos ); my $ret = 0; my $off = $._Off; for 1, 2 -> $seq { $ret +|= $seq if @._Idx[ $off + $seq + $._Min ] < @._Idx[ $off + $seq ]; } $ret } # returns the items in the current hunk if they are equivalent # or an empty list if not. method Same { self._ChkPos; $._Same != ( 1 +& $._Pos ) ?? () !! self.Items(1) } } # end Algorithm::Diff # ############################################################################ # Unported Perl object methods. Everything below except Die is to support Get # with its extensive symbol table mangling. It's not worth the aggravation. # sub Die # { # require Carp; # Carp::confess( @_ ); # } # sub getObjPkg # { # my( $us )= @_; # return ref $us if ref $us; # return $us . "::_obj"; # } # my %getName; # BEGIN { # %getName= ( # same => \&Same, # diff => \&Diff, # base => \&Base, # min => \&Min, # max => \&Max, # range=> \&Range, # items=> \&Items, # same thing # ); # } # sub Get # { # my $me= shift @_; # $me->_ChkPos(); # my @value; # for my $arg ( @_ ) { # for my $word ( split ' ', $arg ) { # my $meth; # if( $word !~ /^(-?\d+)?([a-zA-Z]+)([12])?$/ # || not $meth= $getName{ lc $2 } # ) { # Die( $Root, ", Get: Invalid request ($word)" ); # } # my( $base, $name, $seq )= ( $1, $2, $3 ); # push @value, scalar( # 4 == length($name) # ? $meth->( $me ) # : $meth->( $me, $seq, $base ) # ); # } # } # if( wantarray ) { # return @value; # } elsif( 1 == @value ) { # return $value[0]; # } # Die( 0+@value, " values requested from ", # $Root, "'s Get in scalar context" ); # } # my $Obj= getObjPkg($Root); # no strict 'refs'; # for my $meth ( qw( new getObjPkg ) ) { # *{$Root."::".$meth} = \&{$meth}; # *{$Obj ."::".$meth} = \&{$meth}; # } # for my $meth ( qw( # Next Prev Reset Copy Base Diff # Same Items Range Min Max Get # _ChkPos _ChkSeq # ) ) { # *{$Obj."::".$meth} = \&{$meth}; # } ############################################################# # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- Algorithm::Elo ### -- Licenses: MIT ### -- Authors: Rob Hoelz, Raku Community ### -- File: META6.json ### ---------------------------------------------------- { "auth": "zef:raku-community-modules", "authors": [ "Rob Hoelz", "Raku Community" ], "build-depends": [ ], "depends": [ ], "description": "Implementation of the Elo chess rating system", "license": "MIT", "name": "Algorithm::Elo", "perl": "6.*", "provides": { "Algorithm::Elo": "lib/Algorithm/Elo.rakumod" }, "resources": [ ], "source-url": "https://github.com/raku-community-modules/Algorithm-Elo.git", "tags": [ "ELO", "CHESS", "RATING" ], "test-depends": [ ], "version": "0.1.1" }
### ---------------------------------------------------- ### -- Algorithm::Elo ### -- Licenses: MIT ### -- Authors: Rob Hoelz, Raku Community ### -- File: LICENSE ### ---------------------------------------------------- Copyright (c) 2015 Rob Hoelz <rob at hoelz.ro> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
### ---------------------------------------------------- ### -- Algorithm::Elo ### -- Licenses: MIT ### -- Authors: Rob Hoelz, Raku Community ### -- File: README.md ### ---------------------------------------------------- [![Actions Status](https://github.com/raku-community-modules/Algorithm-Elo/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/Algorithm-Elo/actions) [![Actions Status](https://github.com/raku-community-modules/Algorithm-Elo/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/Algorithm-Elo/actions) [![Actions Status](https://github.com/raku-community-modules/Algorithm-Elo/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/Algorithm-Elo/actions) NAME ==== Algorithm::Elo SYNOPSIS ======== ```raku use Algorithm::Elo; my ( $player-a-score, $player-b-score ) = 1_600, 1_600; ( $player-a-score, $player-b-score ) = calculate-elo($player-a-score, $player-b-score, :left); ``` DESCRIPTION =========== This module implements the Elo rating system, commonly used to rate chess players. SUBROUTINES =========== calculate-elo(Int $left, Int $right, :left, :right, :draw) ---------------------------------------------------------- Given two current ratings and the result of a match (`:left` if the left player wins, `:right` if the right player wins, `:draw` for a draw), return two new ratings for the left and right players. SEE-ALSO ======== [Elo Rating System](https://en.wikipedia.org/wiki/Elo_rating_system) AUTHORS ======= * Rob Hoelz * Raku Community COPYRIGHT AND LICENSE ===================== Copyright (c) 2015 - 2017 Rob Hoelz Copyright (c) 2024 Raku Community This library is free software; you can redistribute it and/or modify it under the MIT license.
### ---------------------------------------------------- ### -- Algorithm::Elo ### -- Licenses: MIT ### -- Authors: Rob Hoelz, Raku Community ### -- File: dist.ini ### ---------------------------------------------------- name = Algorithm::Elo [ReadmeFromPod] filename = lib/Algorithm/Elo.rakumod [UploadToZef] [Badges] provider = github-actions/linux.yml provider = github-actions/macos.yml provider = github-actions/windows.yml
### ---------------------------------------------------- ### -- Algorithm::Elo ### -- Licenses: MIT ### -- Authors: Rob Hoelz, Raku Community ### -- File: t/01-basic.rakutest ### ---------------------------------------------------- use Test; use Algorithm::Elo; plan 12; ( my $player-a, my $player-b ) = calculate-elo(1_600, 1_600, :left); is $player-a, 1_616; is $player-b, 1_584; ( $player-a, $player-b ) = calculate-elo(1_600, 1_600, :right); is $player-a, 1_584; is $player-b, 1_616; ( $player-a, $player-b ) = calculate-elo(1_600, 1_600, :draw); is $player-a, 1_600; is $player-b, 1_600; ( $player-a, $player-b ) = calculate-elo(2_000, 1_000, :left); is $player-a, 2_000; is $player-b, 1_000; ( $player-a, $player-b ) = calculate-elo(2_000, 1_000, :right); is $player-a, 1_968; is $player-b, 1_032; ( $player-a, $player-b ) = calculate-elo(2_000, 1_000, :draw); is $player-a, 1984; is $player-b, 1016; # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- Algorithm::Elo ### -- Licenses: MIT ### -- Authors: Rob Hoelz, Raku Community ### -- File: lib/Algorithm/Elo.rakumod ### ---------------------------------------------------- my constant $k = 32; my sub do-it(Int:D $delta) { 1 / (1 + (10 ** ($delta / 400))); } my sub calculate-elo( Int:D $left, Int:D $right, Bool :left($left-wins), Bool :right($right-wins), Bool :$draw ) is export { unless $left-wins ^ $right-wins ^ $draw { die ':left, :right, and :draw are mutually exclusive'; } unless $left-wins | $right-wins | $draw { die 'exactly least one of :left, :right, or :draw must be specified'; } my $expected-left = do-it($right - $left); my $expected-right = do-it($left - $right); my $left-multiplier = $left-wins ?? 1 !! ($right-wins ?? 0 !! 0.5); my $right-multiplier = 1 - $left-multiplier; ( round($left + $k * ($left-multiplier - $expected-left)), round($right + $k * ($right-multiplier - $expected-right)), ) } =begin pod =head1 NAME Algorithm::Elo =head1 SYNOPSIS =begin code :lang<raku> use Algorithm::Elo; my ( $player-a-score, $player-b-score ) = 1_600, 1_600; ( $player-a-score, $player-b-score ) = calculate-elo($player-a-score, $player-b-score, :left); =end code =head1 DESCRIPTION This module implements the Elo rating system, commonly used to rate chess players. =head1 SUBROUTINES =head2 calculate-elo(Int $left, Int $right, :left, :right, :draw) Given two current ratings and the result of a match (C<:left> if the left player wins, C<:right> if the right player wins, C<:draw> for a draw), return two new ratings for the left and right players. =head1 SEE-ALSO L<Elo Rating System|https://en.wikipedia.org/wiki/Elo_rating_system> =head1 AUTHORS =item Rob Hoelz =item Raku Community =head1 COPYRIGHT AND LICENSE Copyright (c) 2015 - 2017 Rob Hoelz Copyright (c) 2024 Raku Community This library is free software; you can redistribute it and/or modify it under the MIT license. =end pod # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- Algorithm::Evolutionary::Simple ### -- Licenses: Artistic-2.0 ### -- Authors: JJ Merelo ### -- File: META6.json ### ---------------------------------------------------- { "name": "Algorithm::Evolutionary::Simple", "description": "A simple evolutionary algorithm", "version": "0.0.8", "perl": "6.*", "authors": [ "JJ Merelo" ], "auth": "zef:jjmerelo", "depends": [], "test-depends": [ "Test", "Test::META" ], "provides": { "Algorithm::Evolutionary::Fitness::P-Peaks": "lib/Algorithm/Evolutionary/Fitness/P-Peaks.pm6", "Algorithm::Evolutionary::Simple": "lib/Algorithm/Evolutionary/Simple.pm6" }, "resources": [ "examples/max-ones.p6", "examples/concurrent-selecto-recombinative-EA.p6", "examples/concurrent-evolutionary-algorithm.p6", "examples/population-mixer.p6" ], "license": "Artistic-2.0", "tags": [ "evolutionary algorithms", "genetic algorithms", "optimization", "computational intelligence", "evolutionary computation" ], "source-url": "https://github.com/JJ/p6-algorithm-evolutionary-simple.git" }
### ---------------------------------------------------- ### -- Algorithm::Evolutionary::Simple ### -- Licenses: Artistic-2.0 ### -- Authors: JJ Merelo ### -- File: LICENSE ### ---------------------------------------------------- GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: <program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>. The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.
### ---------------------------------------------------- ### -- Algorithm::Evolutionary::Simple ### -- Licenses: Artistic-2.0 ### -- Authors: JJ Merelo ### -- File: README.md ### ---------------------------------------------------- [![Test-install and cache deps](https://github.com/JJ/p6-algorithm-evolutionary-simple/actions/workflows/test.yaml/badge.svg)](https://github.com/JJ/p6-algorithm-evolutionary-simple/actions/workflows/test.yaml) NAME ==== Algorithm::Evolutionary::Simple - A simple evolutionary algorithm SYNOPSIS ======== use Algorithm::Evolutionary::Simple; # From resources/examples/max-ones.p6 my UInt :$length = 64; my UInt :$population-size = 256; my @initial-population = initialize( size => $population-size, genome-length => $length ); my %fitness-of; my $population = evaluate( population => @initial-population, fitness-of => %fitness-of, evaluator => &max-ones ); my $result = 0; while $population.sort(*.value).reverse.[0].value < $length { $population = generation( population => $population, fitness-of => %fitness-of, evaluator => &max-ones, population-size => $population-size) ; $result += $population-size; info(to-json( { best => best-fitness($population) } )); } say $result DESCRIPTION =========== `Algorithm::Evolutionary::Simple` is a module for writing simple and quasi -canonical evolutionary algorithms in Raku. It uses binary representation, integer fitness (which is needed for the kind of data structure we are using) and a single fitness function. It is intended mainly for demo purposes, although it's been actually used in research. In the future, more versions will be available. It uses a fitness cache for storing and not reevaluating already seen chromosomes, so be mindful of memory bloat. EXAMPLES ======== Go to [`resources/examples`](resources/examples) for examples. For instance , run `max-ones.p6` or `p-peaks.p6` there. You'll need to run zef install --deps-only . To install needed modules in that directory. METHODS ======= initialize( UInt :$size, UInt :$genome-length --> Array ) is export ------------------------------------------------------------------- Creates the initial population of binary chromosomes with the indicated length; returns an array. random-chromosome( UInt $length --> List ) ------------------------------------------ Generates a random chromosome of indicated length. Returns a `Seq` of `Bool`s max-ones( @chromosome --> Int ) ------------------------------- Returns the number of trues (or ones) in the chromosome. leading-ones( @chromosome --> Int ) ----------------------------------- Returns the number of ones from the beginning of the chromosome. royal-road( @chromosome ) ------------------------- That's a bumpy road, returns 1 for each block of 4 which has the same true or false value. multi evaluate( :@population, :%fitness-of, :$evaluator, :$auto-t = False --> Mix ) is export --------------------------------------------------------------------------------------------- Evaluates the chromosomes, storing values in the fitness cache. If `auto-t` is set to 'True', uses autothreading for faster operation (if needed). In absence of that parameter, defaults to sequential. sub evaluate-nocache( :@population, :$evaluator --> Mix ) --------------------------------------------------------- Evaluates the population, returning a Mix, but does not use a cache. Intended mainly for concurrent operation. get-pool-roulette-wheel( Mix $population, UInt $need = $population.elems ) is export ------------------------------------------------------------------------------------ Returns `$need` elements with probability proportional to its *weight*, which is fitness in this case. mutation( @chromosome is copy --> Array ) ----------------------------------------- Returns the chromosome with a random bit flipped. crossover ( @chromosome1 is copy, @chromosome2 is copy ) returns List --------------------------------------------------------------------- Returns two chromosomes, with parts of it crossed over. Generally you will want to do crossover first, then mutation. produce-offspring( @pool, $size = @pool.elems --> Seq ) is export ----------------------------------------------------------------- Produces offspring from an array that contains the reproductive pool; it returns a `Seq`. produce-offspring-no-mutation( @pool, $size = @pool.elems --> Seq ) is export ----------------------------------------------------------------------------- Produces offspring from an array that contains the reproductive pool without using mutation; it returns a `Seq`. best-fitness( $population ) --------------------------- Returns the fitness of the first element. Mainly useful to check if the algorithm is finished. multi sub generation( :@population, :%fitness-of, :$evaluator, :$population-size = $population.elems, Bool :$auto-t --> Mix ) ----------------------------------------------------------------------------------------------------------------------------- Single generation of an evolutionary algorithm. The initial `Mix` has to be evaluated before entering here using the `evaluate` function. Will use auto-threading if `$auto-t` is `True`. multi sub generation( :@population, :%fitness-of, :$evaluator, :$population-size = $population.elems, Bool :$no-mutation --> Mix ) ---------------------------------------------------------------------------------------------------------------------------------- Single generation of an evolutionary algorithm. The initial `Mix` has to be evaluated before entering here using the `evaluate` function. Will not use mutation if that variable is set to `True` sub generations-without-change( $generations, $population ) ----------------------------------------------------------- Returns `False` if the number of generations in `$generations` has not been reached without changing; it returns `True` otherwise. mix( $population1, $population2, $size --> Mix ) is export ----------------------------------------------------------- Mixes the two populations, returning a single one of the indicated size and with type Mix. sub pack-individual( @individual --> Int ) ------------------------------------------ Packs the individual in a single `Int`. The invidual must be binary, and the maximum length is 64. sub unpack-individual( Int $packed, UInt $bits --> Array(Seq)) -------------------------------------------------------------- Unpacks the individual that has been packed previously using `pack-individual` sub pack-population( @population --> Buf) ------------------------------------------ Packs a population, producing a buffer which can be sent to a channel or stored in a compact form. sub unpack-population( Buf $buffer, UInt $bits --> Array ) ---------------------------------------------------------- Unpacks the population that has been packed using `pack-population` multi sub frequencies( $population) ----------------------------------- `$population` can be an array or a Mix, in which case the keys are extracted. This returns the per-bit (or gene) frequency of one (or True) for the population. multi sub frequencies-best( $population, $proportion = 2) --------------------------------------------------------- `$population` is a Mix, in which case the keys are extracted. This returns the per-bit (or gene) frequency of one (or True) for the population of the best part of the population; the size of the population will be divided by the $proportion variable. sub generate-by-frequencies( $population-size, @frequencies ) ------------------------------------------------------------- Generates a population of that size with every gene according to the indicated frequency. sub crossover-frequencies( @frequencies, @frequencies-prime --> Array ) ----------------------------------------------------------------------- Generates a new array with random elements of the two arrays that are used as arguments. SEE ALSO ======== There is a very interesting implementation of an evolutionary algorithm in [Algorithm::Genetic](https://github.com/samgwise/p6-algorithm-genetic). Check it out. This is also kind of a port of [Algorithm::Evolutionary::Simple to Perl6](https ://metacpan.org/release/Algorithm-Evolutionary-Simple), which has a few more goodies, but it's not simply a port, since most of the code is completely different. AUTHOR ====== JJ Merelo <[email protected]> COPYRIGHT AND LICENSE ===================== Copyright 2018, 2019, 2022 JJ Merelo This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
### ---------------------------------------------------- ### -- Algorithm::Evolutionary::Simple ### -- Licenses: Artistic-2.0 ### -- Authors: JJ Merelo ### -- File: _config.yml ### ---------------------------------------------------- theme: jekyll-theme-slate
### ---------------------------------------------------- ### -- Algorithm::Evolutionary::Simple ### -- Licenses: Artistic-2.0 ### -- Authors: JJ Merelo ### -- File: dist.ini ### ---------------------------------------------------- name = Algorithm-Evolutionary-Simple [ReadmeFromPod] ; disable = true filename = lib/Algorithm/Evolutionary/Simple.pm6 [PruneFiles] ; match = ^ 'xt/'
### ---------------------------------------------------- ### -- Algorithm::Evolutionary::Simple ### -- Licenses: Artistic-2.0 ### -- Authors: JJ Merelo ### -- File: resources/examples/supply.p6 ### ---------------------------------------------------- #!/usr/bin/env perl6 use v6; use Algorithm::Evolutionary::Simple; my $length = 32; my $supplier = Supplier.new; my $supply = $supplier.Supply; my $pairs = $supply.batch( elems => 2 ); $supply.tap( -> $v { say "First : ", $v }); $supply.tap( -> $χ { say max-ones( $χ ) } ); $pairs.tap( -> @pair { say crossover( @pair[0], @pair[1] )} ); for 1 .. 10 { $supplier.emit( random-chromosome($length) ); }