diff --git a/Cargo.toml b/Cargo.toml index a8a25de90..3fc503977 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ members = [ "examples/dyn_create_destroy_apps", "examples/file_upload", "examples/function_memory_game", + "examples/function_router", "examples/function_todomvc", "examples/futures", "examples/game_of_life", diff --git a/examples/function_router/Cargo.toml b/examples/function_router/Cargo.toml new file mode 100644 index 000000000..0593e73ca --- /dev/null +++ b/examples/function_router/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "function_router" +version = "0.1.0" +edition = "2021" +license = "MIT OR Apache-2.0" + +[dependencies] +lipsum = "0.8" +log = "0.4" +rand = { version = "0.8", features = ["small_rng"] } +yew = { path = "../../packages/yew" } +yew-router = { path = "../../packages/yew-router" } +serde = { version = "1.0", features = ["derive"] } +lazy_static = "1.4.0" +gloo-timers = "0.2" + +[target.'cfg(target_arch = "wasm32")'.dependencies] +getrandom = { version = "0.2", features = ["js"] } +instant = { version = "0.1", features = ["wasm-bindgen"] } +wasm-logger = "0.2" + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +instant = { version = "0.1" } diff --git a/examples/function_router/README.md b/examples/function_router/README.md new file mode 100644 index 000000000..2a78b7ba7 --- /dev/null +++ b/examples/function_router/README.md @@ -0,0 +1,49 @@ +# Function Router Example + +This is identical to the router example, but written in function +components. + +[![Demo](https://img.shields.io/website?label=demo&url=https%3A%2F%2Fexamples.yew.rs%2Ffunction_router)](https://examples.yew.rs/function_router) + +A blog all about yew. +The best way to figure out what this example is about is to just open it up. +It's mobile friendly too! + +## Running + +While not strictly necessary, this example should be built in release mode: + +```bash +trunk serve --release +``` + +Content generation can take up quite a bit of time in debug builds. + +## Concepts + +This example involves many different parts, here are just the Yew specific things: + +- Uses [`yew-router`] to render and switch between multiple pages. + +The example automatically adapts to the `--public-url` value passed to Trunk. +This allows it to be hosted on any path, not just at the root. +For example, our demo is hosted at [/router](https://examples.yew.rs/router). + +This is achieved by adding `` to the [index.html](index.html) file. +Trunk rewrites this tag to contain the value passed to `--public-url` which can then be retrieved at runtime. +Take a look at [`Route`](src/main.rs) for the implementation. + +## Improvements + +- Use a special image component which shows a progress bar until the image is loaded. +- Scroll back to the top after switching route +- Run content generation in a dedicated web worker +- Use longer Markov chains to achieve more coherent results +- Make images deterministic (the same seed should produce the same images) +- Show posts by the author on their page + (this is currently impossible because we need to find post seeds which in turn generate the author's seed) +- Show other posts at the end of a post ("continue reading") +- Home (`/`) should include links to the post list and the author introduction +- Detect sub-path from `--public-url` value passed to Trunk. See: thedodd/trunk#51 + +[`yew-router`]: https://docs.rs/yew-router/latest/yew_router/ diff --git a/examples/function_router/data/keywords.txt b/examples/function_router/data/keywords.txt new file mode 100644 index 000000000..874d1e2c3 --- /dev/null +++ b/examples/function_router/data/keywords.txt @@ -0,0 +1,34 @@ +allergenics +archaeology +austria +berries +birds +color +conservation +cosmology +culture +europe +evergreens +fleshy +france +guides +horticulture +ireland +landscaping +medicine +music +poison +religion +rome +rust +scotland +seeds +spain +taxonomy +toxics +tradition +trees +wasm +wood +woodworking +yew diff --git a/examples/function_router/data/syllables.txt b/examples/function_router/data/syllables.txt new file mode 100644 index 000000000..c6e97aabb --- /dev/null +++ b/examples/function_router/data/syllables.txt @@ -0,0 +1,20 @@ +ald +ber +fe +ger +jo +jus +kas +lix +lu +mon +mour +nas +ridge +ry +si +star +tey +tim +tin +yew diff --git a/examples/function_router/data/yew.txt b/examples/function_router/data/yew.txt new file mode 100644 index 000000000..8e3a2d9f4 --- /dev/null +++ b/examples/function_router/data/yew.txt @@ -0,0 +1,317 @@ +Taxonomy and naming + +The word yew is from Proto-Germanic, possibly originally a loanword from Gaulish. +In German it is known as Eibe. Baccata is Latin for bearing berries. +The word yew as it was originally used seems to refer to the color brown. +The yew was known to Theophrastus, who noted its preference for mountain coolness and shade, +its evergreen character and its slow growth. + +Most Romance languages, with the notable exception of French, +kept a version of the Latin word taxus from the same root as toxic. +In Slavic languages, the same root is preserved. + +In Iran, the tree is known as sorkhdār. + +The common yew was one of the many species first described by Linnaeus. +It is one of around 30 conifer species in seven genera in the family Taxaceae, which is placed in the order Pinales. + + +Description + +It is a small to medium-sized evergreen tree, growing 10 to 20 metres tall, with a trunk up to 2 metres in diameter. +The bark is thin, scaly brown, coming off in small flakes aligned with the stem. +The leaves are flat, dark green, 1 to 4 centimetres long and 2 to 3 millimetres broad, arranged spirally on the stem, +but with the leaf bases twisted to align the leaves in two flat rows either side of the stem, +except on erect leading shoots where the spiral arrangement is more obvious. +The leaves are poisonous. + +The seed cones are modified, each cone containing a single seed, which is 4 to 7 millimetres long, +and partly surrounded by a fleshy scale which develops into a soft, bright red berry-like structure called an aril. +The aril is 8 to 15 millimetres long and wide and open at the end. +The arils mature 6 to 9 months after pollination, and with the seed contained, +are eaten by thrushes, waxwings and other birds, which disperse the hard seeds undamaged in their droppings. +Maturation of the arils is spread over 2 to 3 months, increasing the chances of successful seed dispersal. +The seeds themselves are poisonous and bitter, but are opened and eaten by some bird species including hawfinches, +greenfinches and great tits. +The aril is not poisonous, it is gelatinous and very sweet tasting. The male cones are globose, +3–6 millimetres in diameter, and shed their pollen in early spring. +The yew is mostly dioecious, but occasional individuals can be variably monoecious, or change sex with time. + + +Longevity + +Taxus baccata can reach 400 to 600 years of age. +Some specimens live longer but the age of yews is often overestimated. +Ten yews in Britain are believed to predate the 10th century. +The potential age of yews is impossible to determine accurately and is subject to much dispute. +There is rarely any wood as old as the entire tree, while the boughs themselves often become hollow with age, +making ring counts impossible. +Evidence based on growth rates and archaeological work of surrounding structures suggests the oldest yews, +such as the Fortingall Yew in Perthshire, Scotland, may be in the range of 2,000 years, +placing them among the oldest plants in Europe. +One characteristic contributing to yew's longevity is that it is able to split under the weight of advanced growth +without succumbing to disease in the fracture, as do most other trees. Another is its ability to give rise to new +epicormic and basal shoots from cut surfaces and low on its trunk, even at an old age. + + +Significant trees + +The Fortingall Yew in Perthshire, Scotland, +has the largest recorded trunk girth in Britain and experts estimate it to be 2,000 to 3,000 years old, +although it may be a remnant of a post-Roman Christian site and around 1,500 years old. +The Llangernyw Yew in Clwyd, Wales, can be found at an early saint site and is about 1,500 years old. +Other well known yews include the Ankerwycke Yew, the Balderschwang Yew, the Caesarsboom, the Florence Court Yew, +and the Borrowdale Fraternal Four, of which poet William Wordsworth wrote. +The Kingley Vale National Nature Reserve in West Sussex has one of Europe's largest yew woodlands. + +The oldest specimen in Spain is located in Bermiego, Asturias. It is known as Teixu l'Iglesia in the Asturian language. +It stands 15m tall with a trunk diameter of 7m and a crown diameter of 15m. +It was declared a Natural Monument on April 27, +1995 by the Asturian Government and is protected by the Plan of Natural Resources. + +A unique forest formed by Taxus baccata and European box lies within the city of Sochi, in the Western Caucasus. + +The oldest Irish Yew, the Florence Court Yew, still stands in the grounds of Florence Court estate in County Fermanagh, +Northern Ireland. +The Irish Yew has become ubiquitous in cemeteries across the world and it is believed that all known examples are from +cuttings from this tree. + + +Toxicity + +The entire yew bush, except the aril, is poisonous. +It is toxic due to a group of chemicals called taxine alkaloids. +Their cardiotoxicity is well known and act via calcium and sodium channel antagonism, causing an increase in +cytoplasmic calcium currents of the myocardial cells. +The seeds contain the highest concentrations of these alkaloids. If any leaves or seeds of the plant are ingested, +urgent medical advice is recommended as well as observation for at least 6 hours after the point of ingestion. +The most cardiotoxic taxine is Taxine B followed by Taxine A. +Taxine B also happens to be the most common alkaloid in the Taxus species. + +Yew poisonings are relatively common in both domestic and wild animals who consume the plant accidentally, +resulting in countless fatalities in livestock. +The taxine alkaloids are absorbed quickly from the intestine and in high enough quantities can cause death due to +cardiac arrest or respiratory failure. +Taxines are also absorbed efficiently via the skin and Taxus species should thus be handled with care and preferably +with gloves. +Taxus baccata leaves contain approximately 5mg of taxines per 1g of leaves. + +The estimated lethal dose of taxine alkaloids is approximately 3.0mg/kg body weight for humans. +The lethal dose for an adult is reported to be 50g of yew needles. +Patients who ingest a lethal dose frequently die due to cardiogenic shock, in spite of resuscitation efforts. +There are currently no known antidotes for yew poisoning, +but drugs such as atropine have been used to treat the symptoms. +Taxine remains in the plant all year, with maximal concentrations appearing during the winter. +Dried yew plant material retains its toxicity for several months and even increases its toxicity as the water is removed. +Fallen leaves should therefore also be considered toxic. +Poisoning usually occurs when leaves of yew trees are eaten, +but in at least one case a victim inhaled sawdust from a yew tree. + +It is difficult to measure taxine alkaloids and this is a major reason as to why different studies show different results. + +Several studies have found taxine LD50 values under 20mg/kg in mice and rats. + +Male and monoecious yews in this genus release toxic pollen, which can cause the mild symptoms. +The pollen is also a trigger for asthma. +These pollen grains are only 15 microns in size, and can easily pass through most window screens. + + +Allergenic potential + +Yews in this genus are primarily separate-sexed, and males are extremely allergenic, +with an OPALS allergy scale rating of 10 out of 10. +Completely female yews have an OPALS rating of 1, and are considered allergy-fighting. +Male yews bloom and release abundant amounts of pollen in the spring; +completely female yews only trap pollen while producing none. + + +Uses and traditions + +In the ancient Celtic world, the yew tree had extraordinary importance; a passage by Caesar narrates that Cativolcus, +chief of the Eburones poisoned himself with yew rather than submit to Rome. +Similarly, Florus notes that when the Cantabrians were under siege by the legate Gaius Furnius in 22 BC, +most of them took their lives either by the sword, by fire, or by a poison extracted ex arboribus taxeis, that is, +from the yew tree. +In a similar way, Orosius notes that when the Astures were besieged at Mons Medullius, +they preferred to die by their own swords or by the yew tree poison rather than surrender. + +The word York is derived from the Brittonic name Eburākon, +a combination of eburos "yew-tree" and a suffix of appurtenance meaning either "place of the yew trees"; +or alternatively, "the settlement of Eburos". + +The name Eboracum became the Anglian Eoforwic in the 7th century. +When the Danish army conquered the city in 866, its name became Jórvík. + +The Old French and Norman name of the city following the Norman Conquest was recorded as Everwic in works such as +Wace's Roman de Rou. +Jórvík, meanwhile, gradually reduced to York in the centuries after the Conquest, +moving from the Middle English Yerk in the 14th century through Yourke in the 16th century to Yarke in the 17th century. +The form York was first recorded in the 13th century. Many company and place names, such as the Ebor race meeting, +refer to the Latinised Brittonic, Roman name. + +The 12th‑century chronicler Geoffrey of Monmouth, in his fictional account of the prehistoric kings of Britain, +Historia Regum Britanniae, suggests the name derives from that of a pre-Roman city founded by the legendary king Ebraucus. + +The Archbishop of York uses Ebor as his surname in his signature. + +The area of Ydre in the South Swedish highlands is interpreted to mean place of yews. +Two localities in particular, Idhult and Idebo, appear to be further associated with yews. + + +Religion + +The yew is traditionally and regularly found in churchyards in England, Wales, Scotland, Ireland and Northern France. +Some examples can be found in La Haye-de-Routot or La Lande-Patry. +It is said up to 40 people could stand inside one of the La-Haye-de-Routot yew trees, +and the Le Ménil-Ciboult yew is probably the largest at 13m diameter. +Yews may grow to become exceptionally large and may live to be over 2,000 years old. +Sometimes monks planted yews in the middle of their cloister, as at Muckross Abbey or abbaye de Jumièges. +Some ancient yew trees are located at St. Mary the Virgin Church, Overton-on-Dee in Wales. + +In Asturian tradition and culture, the yew tree was considered to be linked with the land, people, +ancestors and ancient religion. It was tradition on All Saints' Day to bring a branch of a yew tree to the tombs of +those who had died recently so they would be guided in their return to the Land of Shadows. +The yew tree has been found near chapels, +churches and cemeteries since ancient times as a symbol of the transcendence of death. +They are often found in the main squares of villages where people celebrated the open councils that served as a way of +general assembly to rule village affairs. + +It has been suggested that the sacred tree at the Temple at Uppsala was an ancient yew tree. +The Christian church commonly found it expedient to take over existing pre-Christian sacred sites for churches. +It has also been suggested that yews were planted at religious sites as their long life was suggestive of eternity, +or because, being toxic when ingested, they were seen as trees of death. +Another suggested explanation is that yews were planted to discourage farmers and drovers from letting animals wander +onto the burial grounds, the poisonous foliage being the disincentive. +A further possible reason is that fronds and branches of yew were often used as a substitute for palms on Palm Sunday. + +Some yew trees were actually native to the sites before the churches were built. +King Edward I of England ordered yew trees to be planted in churchyards to offer some protection to the buildings. +Yews are poisonous so by planting them in the churchyards cattle that were not allowed to graze on hallowed +ground were safe from eating yew. Yew branches touching the ground take root and sprout again; +this became a symbol of death, rebirth and therefore immortality. + +In interpretations of Norse cosmology, the tree Yggdrasil has traditionally been interpreted as a giant ash tree. +Some scholars now believe errors were made in past interpretations of the ancient writings, +and that the tree is most likely a European yew. + +In the Crann Ogham—the variation on the ancient Irish Ogham alphabet which consists of a list of trees—yew +is the last in the main list of 20 trees, primarily symbolizing death. +There are stories of people who have committed suicide by ingesting the foliage. +As the ancient Celts also believed in the transmigration of the soul, +there is in some cases a secondary meaning of the eternal soul that survives death to be reborn in a new form. + + +Medical + +Certain compounds found in the bark of yew trees were discovered by Wall and Wani in 1967 to have efficacy as +anti-cancer agents. +The precursors of the chemotherapy drug paclitaxel were later shown to be synthesized easily from extracts +of the leaves of European yew, which is a much more renewable source than the bark of the Pacific yew from which +they were initially isolated. +This ended a point of conflict in the early 1990s; many environmentalists, +including Al Gore, had opposed the destructive harvesting of Pacific yew for paclitaxel cancer treatments. +Docetaxel can then be obtained by semi-synthetic conversion from the precursors. + + +Woodworking and longbows + +Wood from the yew is classified as a closed-pore softwood, similar to cedar and pine. +Easy to work, yew is among the hardest of the softwoods; yet it possesses a remarkable elasticity, +making it ideal for products that require springiness, such as bows. +Due to all parts of the yew and its volatile oils being poisonous and cardiotoxic, +a mask should be worn if one comes in contact with sawdust from the wood. + +One of the world's oldest surviving wooden artifacts is a Clactonian yew spear head, found in 1911 at Clacton-on-Sea, +in Essex, UK. Known as the Clacton Spear, it is estimated to be over 400,000 years old. + +Yew is also associated with Wales and England because of the longbow, +an early weapon of war developed in northern Europe, +and as the English longbow the basis for a medieval tactical system. +The oldest surviving yew longbow was found at Rotten Bottom in Dumfries and Galloway, Scotland. +It has been given a calibrated radiocarbon date of 4040 BC to 3640 BC and is on display in the National Museum of +Scotland. Yew is the wood of choice for longbow making; +the heartwood is always on the inside of the bow with the sapwood on the outside. +This makes most efficient use of their properties as heartwood is best in compression whilst +sapwood is superior in tension. +However, much yew is knotty and twisted, and therefore unsuitable for bowmaking; +most trunks do not give good staves and even in a good trunk much wood has to be discarded. + +There was a tradition of planting yew trees in churchyards throughout Britain and Ireland, among other reasons, +as a resource for bows. +Ardchattan Priory whose yew trees, according to other accounts, +were inspected by Robert the Bruce and cut to make at least some of the longbows used at the Battle of Bannockburn. + +The trade of yew wood to England for longbows was so robust that it depleted the stocks of good-quality, +mature yew over a vast area. +The first documented import of yew bowstaves to England was in 1294. +In 1423 the Polish king commanded protection of yews in order to cut exports, +facing nearly complete destruction of local yew stock. In 1470 compulsory archery practice was renewed, and hazel, ash, +and laburnum were specifically allowed for practice bows. +Supplies still proved insufficient, until by the Statute of Westminster in 1472, +every ship coming to an English port had to bring four bowstaves for every tun. +Richard III of England increased this to ten for every tun. This stimulated a vast network of extraction and supply, +which formed part of royal monopolies in southern Germany and Austria. +In 1483, the price of bowstaves rose from two to eight pounds per hundred, +and in 1510 the Venetians would only sell a hundred for sixteen pounds. +In 1507 the Holy Roman Emperor asked the Duke of Bavaria to stop cutting yew, but the trade was profitable, +and in 1532 the royal monopoly was granted for the usual quantity if there are that many. +In 1562, the Bavarian government sent a long plea to the Holy Roman Emperor asking him to stop the cutting of yew, +and outlining the damage done to the forests by its selective extraction, +which broke the canopy and allowed wind to destroy neighbouring trees. In 1568, despite a request from Saxony, +no royal monopoly was granted because there was no yew to cut, +and the next year Bavaria and Austria similarly failed to produce enough yew to justify a royal monopoly. +Forestry records in this area in the 17th century do not mention yew, and it seems that no mature trees were to be had. +The English tried to obtain supplies from the Baltic, but at this period bows were being replaced by guns in any case. + + +Horticulture + +Today European yew is widely used in landscaping and ornamental horticulture. +Due to its dense, dark green, mature foliage, and its tolerance of even very severe pruning, +it is used especially for formal hedges and topiary. +Its relatively slow growth rate means that in such situations it needs to be clipped only once per year. + +Well over 200 cultivars of T. baccata have been named. The most popular of these are the Irish yew, +a fastigiate cultivar of the European yew selected from two trees found growing in Ireland, +and the several cultivars with yellow leaves, collectively known as golden yew. In some locations, +when hemmed in by buildings or other trees, +an Irish yew can reach 20 feet in height without exceeding 2 feet in diameter at its thickest point, +although with age many Irish yews assume a fat cigar shape rather than being truly columnar. + +European yew will tolerate growing in a wide range of soils and situations, including shallow chalk soils and shade, +although in deep shade its foliage may be less dense. +However it cannot tolerate waterlogging, +and in poorly-draining situations is liable to succumb to the root-rotting pathogen Phytophthora cinnamomi. + +In Europe, Taxus baccata grows naturally north to Molde in southern Norway, but it is used in gardens further north. +It is also popular as a bonsai in many parts of Europe and makes a handsome small- to large-sized bonsai. + + +Privies + +In England, yew has historically been sometimes associated with privies, +possibly because the smell of the plant keeps insects away. + + +Musical instruments + +The late Robert Lundberg, a noted luthier who performed extensive research on historical lute-making methodology, +states in his 2002 book Historical Lute Construction that yew was historically a prized wood for lute construction. +European legislation establishing use limits and requirements for yew limited supplies available to luthiers, +but it was apparently as prized among medieval, renaissance, +and baroque lute builders as Brazilian rosewood is among contemporary guitar-makers for its quality of sound and beauty. + + +Conservation + +Clippings from ancient specimens in the UK, including the Fortingall Yew, +were taken to the Royal Botanic Gardens in Edinburgh to form a mile-long hedge. +The purpose of this project is to maintain the DNA of Taxus baccata. +The species is threatened by felling, partly due to rising demand from pharmaceutical companies, and disease. + +Another conservation programme was run in Catalonia in the early 2010s, by the Forest Sciences Centre of Catalonia, +in order to protect genetically endemic yew populations, and preserve them from overgrazing and forest fires. +In the framework of this programme, the 4th International Yew Conference was organised in the Poblet Monastery in 2014, +which proceedings are available. + +There has also been a conservation programme in northern Portugal and Northern Spain. diff --git a/examples/function_router/index.html b/examples/function_router/index.html new file mode 100644 index 000000000..d7101222d --- /dev/null +++ b/examples/function_router/index.html @@ -0,0 +1,17 @@ + + + + + + + Yew • Function Router + + + + + + + diff --git a/examples/function_router/index.scss b/examples/function_router/index.scss new file mode 100644 index 000000000..fafc9be01 --- /dev/null +++ b/examples/function_router/index.scss @@ -0,0 +1,27 @@ +.hero { + &.has-background { + position: relative; + overflow: hidden; + } + + &-background { + position: absolute; + object-fit: cover; + object-position: bottom; + width: 100%; + height: 100%; + + &.is-transparent { + opacity: 0.3; + } + } +} + +.burger { + background-color: transparent; + border: none; +} + +.navbar-brand { + align-items: center; +} diff --git a/examples/function_router/src/app.rs b/examples/function_router/src/app.rs new file mode 100644 index 000000000..ce581a59b --- /dev/null +++ b/examples/function_router/src/app.rs @@ -0,0 +1,118 @@ +use yew::prelude::*; +use yew_router::prelude::*; + +use crate::components::nav::Nav; +use crate::pages::{ + author::Author, author_list::AuthorList, home::Home, page_not_found::PageNotFound, post::Post, + post_list::PostList, +}; + +#[derive(Routable, PartialEq, Clone, Debug)] +pub enum Route { + #[at("/posts/:id")] + Post { id: u32 }, + #[at("/posts")] + Posts, + #[at("/authors/:id")] + Author { id: u32 }, + #[at("/authors")] + Authors, + #[at("/")] + Home, + #[not_found] + #[at("/404")] + NotFound, +} + +#[function_component] +pub fn App() -> Html { + html! { + +