✨ Serve the PageTop guides with pagetop-mdbook
Rebuild the website on the current PageTop API, with Bootsier as its
theme and edition 2024. Add the first Spanish guide (doc/v0.6/es) as an
mdBook book, built in build.rs and served with pagetop-mdbook, and the
/doc/latest/{lang} redirect.
Add `tools/doccheck.sh` to check the links of the guides and to compile,
run and test their examples against PageTop.
Move the configuration to config/common.toml and translate the README
to English.
This commit is contained in:
parent
e41e71cc78
commit
1a41a456d4
80 changed files with 14112 additions and 1218 deletions
655
doc/theme/book.js
vendored
Normal file
655
doc/theme/book.js
vendored
Normal file
|
|
@ -0,0 +1,655 @@
|
|||
"use strict";
|
||||
|
||||
// Fix back button cache problem
|
||||
window.onunload = function () { };
|
||||
|
||||
// Global variable, shared between modules
|
||||
function playground_text(playground, hidden = true) {
|
||||
let code_block = playground.querySelector("code");
|
||||
|
||||
if (window.ace && code_block.classList.contains("editable")) {
|
||||
let editor = window.ace.edit(code_block);
|
||||
return editor.getValue();
|
||||
} else if (hidden) {
|
||||
return code_block.textContent;
|
||||
} else {
|
||||
return code_block.innerText;
|
||||
}
|
||||
}
|
||||
|
||||
(function codeSnippets() {
|
||||
function fetch_with_timeout(url, options, timeout = 6000) {
|
||||
return Promise.race([
|
||||
fetch(url, options),
|
||||
new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), timeout))
|
||||
]);
|
||||
}
|
||||
|
||||
var playgrounds = Array.from(document.querySelectorAll(".playground"));
|
||||
if (playgrounds.length > 0) {
|
||||
fetch_with_timeout("https://play.rust-lang.org/meta/crates", {
|
||||
headers: {
|
||||
'Content-Type': "application/json",
|
||||
},
|
||||
method: 'POST',
|
||||
mode: 'cors',
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(response => {
|
||||
// get list of crates available in the rust playground
|
||||
let playground_crates = response.crates.map(item => item["id"]);
|
||||
playgrounds.forEach(block => handle_crate_list_update(block, playground_crates));
|
||||
});
|
||||
}
|
||||
|
||||
function handle_crate_list_update(playground_block, playground_crates) {
|
||||
// update the play buttons after receiving the response
|
||||
update_play_button(playground_block, playground_crates);
|
||||
|
||||
// and install on change listener to dynamically update ACE editors
|
||||
if (window.ace) {
|
||||
let code_block = playground_block.querySelector("code");
|
||||
if (code_block.classList.contains("editable")) {
|
||||
let editor = window.ace.edit(code_block);
|
||||
editor.addEventListener("change", function (e) {
|
||||
update_play_button(playground_block, playground_crates);
|
||||
});
|
||||
// add Ctrl-Enter command to execute rust code
|
||||
editor.commands.addCommand({
|
||||
name: "run",
|
||||
bindKey: {
|
||||
win: "Ctrl-Enter",
|
||||
mac: "Ctrl-Enter"
|
||||
},
|
||||
exec: _editor => run_rust_code(playground_block)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// updates the visibility of play button based on `no_run` class and
|
||||
// used crates vs ones available on https://play.rust-lang.org
|
||||
function update_play_button(pre_block, playground_crates) {
|
||||
var play_button = pre_block.querySelector(".play-button");
|
||||
|
||||
// skip if code is `no_run`
|
||||
if (pre_block.querySelector('code').classList.contains("no_run")) {
|
||||
play_button.classList.add("hidden");
|
||||
return;
|
||||
}
|
||||
|
||||
// get list of `extern crate`'s from snippet
|
||||
var txt = playground_text(pre_block);
|
||||
var re = /extern\s+crate\s+([a-zA-Z_0-9]+)\s*;/g;
|
||||
var snippet_crates = [];
|
||||
var item;
|
||||
while (item = re.exec(txt)) {
|
||||
snippet_crates.push(item[1]);
|
||||
}
|
||||
|
||||
// check if all used crates are available on play.rust-lang.org
|
||||
var all_available = snippet_crates.every(function (elem) {
|
||||
return playground_crates.indexOf(elem) > -1;
|
||||
});
|
||||
|
||||
if (all_available) {
|
||||
play_button.classList.remove("hidden");
|
||||
} else {
|
||||
play_button.classList.add("hidden");
|
||||
}
|
||||
}
|
||||
|
||||
function run_rust_code(code_block) {
|
||||
var result_block = code_block.querySelector(".result");
|
||||
if (!result_block) {
|
||||
result_block = document.createElement('code');
|
||||
result_block.className = 'result hljs language-bash';
|
||||
|
||||
code_block.append(result_block);
|
||||
}
|
||||
|
||||
let text = playground_text(code_block);
|
||||
let classes = code_block.querySelector('code').classList;
|
||||
let edition = "2015";
|
||||
if(classes.contains("edition2018")) {
|
||||
edition = "2018";
|
||||
} else if(classes.contains("edition2021")) {
|
||||
edition = "2021";
|
||||
}
|
||||
var params = {
|
||||
version: "stable",
|
||||
optimize: "0",
|
||||
code: text,
|
||||
edition: edition
|
||||
};
|
||||
|
||||
if (text.indexOf("#![feature") !== -1) {
|
||||
params.version = "nightly";
|
||||
}
|
||||
|
||||
result_block.innerText = "Running...";
|
||||
|
||||
fetch_with_timeout("https://play.rust-lang.org/evaluate.json", {
|
||||
headers: {
|
||||
'Content-Type': "application/json",
|
||||
},
|
||||
method: 'POST',
|
||||
mode: 'cors',
|
||||
body: JSON.stringify(params)
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(response => {
|
||||
if (response.result.trim() === '') {
|
||||
result_block.innerText = "No output";
|
||||
result_block.classList.add("result-no-output");
|
||||
} else {
|
||||
result_block.innerText = response.result;
|
||||
result_block.classList.remove("result-no-output");
|
||||
}
|
||||
})
|
||||
.catch(error => result_block.innerText = "Playground Communication: " + error.message);
|
||||
}
|
||||
|
||||
// Syntax highlighting Configuration
|
||||
hljs.configure({
|
||||
tabReplace: ' ', // 4 spaces
|
||||
languages: [], // Languages used for auto-detection
|
||||
});
|
||||
|
||||
let code_nodes = Array
|
||||
.from(document.querySelectorAll('code'))
|
||||
// Don't highlight `inline code` blocks in headers.
|
||||
.filter(function (node) {return !node.parentElement.classList.contains("header"); });
|
||||
|
||||
if (window.ace) {
|
||||
// language-rust class needs to be removed for editable
|
||||
// blocks or highlightjs will capture events
|
||||
code_nodes
|
||||
.filter(function (node) {return node.classList.contains("editable"); })
|
||||
.forEach(function (block) { block.classList.remove('language-rust'); });
|
||||
|
||||
code_nodes
|
||||
.filter(function (node) {return !node.classList.contains("editable"); })
|
||||
.forEach(function (block) { hljs.highlightBlock(block); });
|
||||
} else {
|
||||
code_nodes.forEach(function (block) { hljs.highlightBlock(block); });
|
||||
}
|
||||
|
||||
// Adding the hljs class gives code blocks the color css
|
||||
// even if highlighting doesn't apply
|
||||
code_nodes.forEach(function (block) { block.classList.add('hljs'); });
|
||||
|
||||
Array.from(document.querySelectorAll("code.hljs")).forEach(function (block) {
|
||||
|
||||
var lines = Array.from(block.querySelectorAll('.boring'));
|
||||
// If no lines were hidden, return
|
||||
if (!lines.length) { return; }
|
||||
block.classList.add("hide-boring");
|
||||
|
||||
var buttons = document.createElement('div');
|
||||
buttons.className = 'buttons';
|
||||
buttons.innerHTML = "<button class=\"fa fa-eye\" title=\"Show hidden lines\" aria-label=\"Show hidden lines\"></button>";
|
||||
|
||||
// add expand button
|
||||
var pre_block = block.parentNode;
|
||||
pre_block.insertBefore(buttons, pre_block.firstChild);
|
||||
|
||||
pre_block.querySelector('.buttons').addEventListener('click', function (e) {
|
||||
if (e.target.classList.contains('fa-eye')) {
|
||||
e.target.classList.remove('fa-eye');
|
||||
e.target.classList.add('fa-eye-slash');
|
||||
e.target.title = 'Hide lines';
|
||||
e.target.setAttribute('aria-label', e.target.title);
|
||||
|
||||
block.classList.remove('hide-boring');
|
||||
} else if (e.target.classList.contains('fa-eye-slash')) {
|
||||
e.target.classList.remove('fa-eye-slash');
|
||||
e.target.classList.add('fa-eye');
|
||||
e.target.title = 'Show hidden lines';
|
||||
e.target.setAttribute('aria-label', e.target.title);
|
||||
|
||||
block.classList.add('hide-boring');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if (window.playground_copyable) {
|
||||
Array.from(document.querySelectorAll('pre code')).forEach(function (block) {
|
||||
var pre_block = block.parentNode;
|
||||
if (!pre_block.classList.contains('playground')) {
|
||||
var buttons = pre_block.querySelector(".buttons");
|
||||
if (!buttons) {
|
||||
buttons = document.createElement('div');
|
||||
buttons.className = 'buttons';
|
||||
pre_block.insertBefore(buttons, pre_block.firstChild);
|
||||
}
|
||||
|
||||
var clipButton = document.createElement('button');
|
||||
clipButton.className = 'fa fa-copy clip-button';
|
||||
clipButton.title = 'Copy to clipboard';
|
||||
clipButton.setAttribute('aria-label', clipButton.title);
|
||||
clipButton.innerHTML = '<i class=\"tooltiptext\"></i>';
|
||||
|
||||
buttons.insertBefore(clipButton, buttons.firstChild);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Process playground code blocks
|
||||
Array.from(document.querySelectorAll(".playground")).forEach(function (pre_block) {
|
||||
// Add play button
|
||||
var buttons = pre_block.querySelector(".buttons");
|
||||
if (!buttons) {
|
||||
buttons = document.createElement('div');
|
||||
buttons.className = 'buttons';
|
||||
pre_block.insertBefore(buttons, pre_block.firstChild);
|
||||
}
|
||||
|
||||
var runCodeButton = document.createElement('button');
|
||||
runCodeButton.className = 'fa fa-play play-button';
|
||||
runCodeButton.hidden = true;
|
||||
runCodeButton.title = 'Run this code';
|
||||
runCodeButton.setAttribute('aria-label', runCodeButton.title);
|
||||
|
||||
buttons.insertBefore(runCodeButton, buttons.firstChild);
|
||||
runCodeButton.addEventListener('click', function (e) {
|
||||
run_rust_code(pre_block);
|
||||
});
|
||||
|
||||
if (window.playground_copyable) {
|
||||
var copyCodeClipboardButton = document.createElement('button');
|
||||
copyCodeClipboardButton.className = 'fa fa-copy clip-button';
|
||||
copyCodeClipboardButton.innerHTML = '<i class="tooltiptext"></i>';
|
||||
copyCodeClipboardButton.title = 'Copy to clipboard';
|
||||
copyCodeClipboardButton.setAttribute('aria-label', copyCodeClipboardButton.title);
|
||||
|
||||
buttons.insertBefore(copyCodeClipboardButton, buttons.firstChild);
|
||||
}
|
||||
|
||||
let code_block = pre_block.querySelector("code");
|
||||
if (window.ace && code_block.classList.contains("editable")) {
|
||||
var undoChangesButton = document.createElement('button');
|
||||
undoChangesButton.className = 'fa fa-history reset-button';
|
||||
undoChangesButton.title = 'Undo changes';
|
||||
undoChangesButton.setAttribute('aria-label', undoChangesButton.title);
|
||||
|
||||
buttons.insertBefore(undoChangesButton, buttons.firstChild);
|
||||
|
||||
undoChangesButton.addEventListener('click', function () {
|
||||
let editor = window.ace.edit(code_block);
|
||||
editor.setValue(editor.originalCode);
|
||||
editor.clearSelection();
|
||||
});
|
||||
}
|
||||
});
|
||||
})();
|
||||
|
||||
(function themes() {
|
||||
var html = document.querySelector('html');
|
||||
var themeToggleButton = document.getElementById('theme-toggle');
|
||||
var themePopup = document.getElementById('theme-list');
|
||||
var themeColorMetaTag = document.querySelector('meta[name="theme-color"]');
|
||||
var stylesheets = {
|
||||
ayuHighlight: document.querySelector("[href$='ayu-highlight.css']"),
|
||||
tomorrowNight: document.querySelector("[href$='tomorrow-night.css']"),
|
||||
highlight: document.querySelector("[href$='highlight.css']"),
|
||||
};
|
||||
|
||||
function showThemes() {
|
||||
themePopup.style.display = 'block';
|
||||
themeToggleButton.setAttribute('aria-expanded', true);
|
||||
themePopup.querySelector("button#" + get_theme()).focus();
|
||||
}
|
||||
|
||||
function updateThemeSelected() {
|
||||
themePopup.querySelectorAll('.theme-selected').forEach(function (el) {
|
||||
el.classList.remove('theme-selected');
|
||||
});
|
||||
themePopup.querySelector("button#" + get_theme()).classList.add('theme-selected');
|
||||
}
|
||||
|
||||
function hideThemes() {
|
||||
themePopup.style.display = 'none';
|
||||
themeToggleButton.setAttribute('aria-expanded', false);
|
||||
themeToggleButton.focus();
|
||||
}
|
||||
|
||||
function get_theme() {
|
||||
var theme;
|
||||
try { theme = localStorage.getItem('mdbook-theme'); } catch (e) { }
|
||||
if (theme === null || theme === undefined) {
|
||||
return default_theme;
|
||||
} else {
|
||||
return theme;
|
||||
}
|
||||
}
|
||||
|
||||
function set_theme(theme, store = true) {
|
||||
let ace_theme;
|
||||
|
||||
if (theme == 'coal' || theme == 'navy') {
|
||||
stylesheets.ayuHighlight.disabled = true;
|
||||
stylesheets.tomorrowNight.disabled = false;
|
||||
stylesheets.highlight.disabled = true;
|
||||
|
||||
ace_theme = "ace/theme/tomorrow_night";
|
||||
} else if (theme == 'ayu') {
|
||||
stylesheets.ayuHighlight.disabled = false;
|
||||
stylesheets.tomorrowNight.disabled = true;
|
||||
stylesheets.highlight.disabled = true;
|
||||
ace_theme = "ace/theme/tomorrow_night";
|
||||
} else {
|
||||
stylesheets.ayuHighlight.disabled = true;
|
||||
stylesheets.tomorrowNight.disabled = true;
|
||||
stylesheets.highlight.disabled = false;
|
||||
ace_theme = "ace/theme/dawn";
|
||||
}
|
||||
|
||||
setTimeout(function () {
|
||||
themeColorMetaTag.content = getComputedStyle(document.documentElement).backgroundColor;
|
||||
}, 1);
|
||||
|
||||
if (window.ace && window.editors) {
|
||||
window.editors.forEach(function (editor) {
|
||||
editor.setTheme(ace_theme);
|
||||
});
|
||||
}
|
||||
|
||||
var previousTheme = get_theme();
|
||||
|
||||
if (store) {
|
||||
try { localStorage.setItem('mdbook-theme', theme); } catch (e) { }
|
||||
}
|
||||
|
||||
html.classList.remove(previousTheme);
|
||||
html.classList.add(theme);
|
||||
updateThemeSelected();
|
||||
}
|
||||
|
||||
// Set theme
|
||||
var theme = get_theme();
|
||||
|
||||
set_theme(theme, false);
|
||||
|
||||
themeToggleButton.addEventListener('click', function () {
|
||||
if (themePopup.style.display === 'block') {
|
||||
hideThemes();
|
||||
} else {
|
||||
showThemes();
|
||||
}
|
||||
});
|
||||
|
||||
themePopup.addEventListener('click', function (e) {
|
||||
var theme;
|
||||
if (e.target.className === "theme") {
|
||||
theme = e.target.id;
|
||||
} else if (e.target.parentElement.className === "theme") {
|
||||
theme = e.target.parentElement.id;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
set_theme(theme);
|
||||
});
|
||||
|
||||
themePopup.addEventListener('focusout', function(e) {
|
||||
// e.relatedTarget is null in Safari and Firefox on macOS (see workaround below)
|
||||
if (!!e.relatedTarget && !themeToggleButton.contains(e.relatedTarget) && !themePopup.contains(e.relatedTarget)) {
|
||||
hideThemes();
|
||||
}
|
||||
});
|
||||
|
||||
// Should not be needed, but it works around an issue on macOS & iOS: https://github.com/rust-lang/mdBook/issues/628
|
||||
document.addEventListener('click', function(e) {
|
||||
if (themePopup.style.display === 'block' && !themeToggleButton.contains(e.target) && !themePopup.contains(e.target)) {
|
||||
hideThemes();
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('keydown', function (e) {
|
||||
if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) { return; }
|
||||
if (!themePopup.contains(e.target)) { return; }
|
||||
|
||||
switch (e.key) {
|
||||
case 'Escape':
|
||||
e.preventDefault();
|
||||
hideThemes();
|
||||
break;
|
||||
case 'ArrowUp':
|
||||
e.preventDefault();
|
||||
var li = document.activeElement.parentElement;
|
||||
if (li && li.previousElementSibling) {
|
||||
li.previousElementSibling.querySelector('button').focus();
|
||||
}
|
||||
break;
|
||||
case 'ArrowDown':
|
||||
e.preventDefault();
|
||||
var li = document.activeElement.parentElement;
|
||||
if (li && li.nextElementSibling) {
|
||||
li.nextElementSibling.querySelector('button').focus();
|
||||
}
|
||||
break;
|
||||
case 'Home':
|
||||
e.preventDefault();
|
||||
themePopup.querySelector('li:first-child button').focus();
|
||||
break;
|
||||
case 'End':
|
||||
e.preventDefault();
|
||||
themePopup.querySelector('li:last-child button').focus();
|
||||
break;
|
||||
}
|
||||
});
|
||||
})();
|
||||
|
||||
(function sidebar() {
|
||||
var body = document.querySelector("body");
|
||||
var sidebar = document.getElementById("sidebar");
|
||||
var sidebarLinks = document.querySelectorAll('#sidebar a');
|
||||
var sidebarToggleButton = document.getElementById("sidebar-toggle");
|
||||
var sidebarResizeHandle = document.getElementById("sidebar-resize-handle");
|
||||
var firstContact = null;
|
||||
|
||||
function showSidebar() {
|
||||
body.classList.remove('sidebar-hidden')
|
||||
body.classList.add('sidebar-visible');
|
||||
Array.from(sidebarLinks).forEach(function (link) {
|
||||
link.setAttribute('tabIndex', 0);
|
||||
});
|
||||
sidebarToggleButton.setAttribute('aria-expanded', true);
|
||||
sidebar.setAttribute('aria-hidden', false);
|
||||
try { localStorage.setItem('mdbook-sidebar', 'visible'); } catch (e) { }
|
||||
}
|
||||
|
||||
|
||||
var sidebarAnchorToggles = document.querySelectorAll('#sidebar a.toggle');
|
||||
|
||||
function toggleSection(ev) {
|
||||
ev.currentTarget.parentElement.classList.toggle('expanded');
|
||||
}
|
||||
|
||||
Array.from(sidebarAnchorToggles).forEach(function (el) {
|
||||
el.addEventListener('click', toggleSection);
|
||||
});
|
||||
|
||||
function hideSidebar() {
|
||||
body.classList.remove('sidebar-visible')
|
||||
body.classList.add('sidebar-hidden');
|
||||
Array.from(sidebarLinks).forEach(function (link) {
|
||||
link.setAttribute('tabIndex', -1);
|
||||
});
|
||||
sidebarToggleButton.setAttribute('aria-expanded', false);
|
||||
sidebar.setAttribute('aria-hidden', true);
|
||||
try { localStorage.setItem('mdbook-sidebar', 'hidden'); } catch (e) { }
|
||||
}
|
||||
|
||||
// Toggle sidebar
|
||||
sidebarToggleButton.addEventListener('click', function sidebarToggle() {
|
||||
if (body.classList.contains("sidebar-hidden")) {
|
||||
var current_width = parseInt(
|
||||
document.documentElement.style.getPropertyValue('--sidebar-width'), 10);
|
||||
if (current_width < 150) {
|
||||
document.documentElement.style.setProperty('--sidebar-width', '150px');
|
||||
}
|
||||
showSidebar();
|
||||
} else if (body.classList.contains("sidebar-visible")) {
|
||||
hideSidebar();
|
||||
} else {
|
||||
if (getComputedStyle(sidebar)['transform'] === 'none') {
|
||||
hideSidebar();
|
||||
} else {
|
||||
showSidebar();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
sidebarResizeHandle.addEventListener('mousedown', initResize, false);
|
||||
|
||||
function initResize(e) {
|
||||
window.addEventListener('mousemove', resize, false);
|
||||
window.addEventListener('mouseup', stopResize, false);
|
||||
body.classList.add('sidebar-resizing');
|
||||
}
|
||||
function resize(e) {
|
||||
var viewportOffset = sidebar.getBoundingClientRect();
|
||||
var pos = (e.clientX - sidebar.offsetLeft - viewportOffset.left);
|
||||
if (pos < 20) {
|
||||
hideSidebar();
|
||||
} else {
|
||||
if (body.classList.contains("sidebar-hidden")) {
|
||||
showSidebar();
|
||||
}
|
||||
pos = Math.min(pos, window.innerWidth - 100);
|
||||
document.documentElement.style.setProperty('--sidebar-width', pos + 'px');
|
||||
}
|
||||
}
|
||||
//on mouseup remove windows functions mousemove & mouseup
|
||||
function stopResize(e) {
|
||||
body.classList.remove('sidebar-resizing');
|
||||
window.removeEventListener('mousemove', resize, false);
|
||||
window.removeEventListener('mouseup', stopResize, false);
|
||||
}
|
||||
|
||||
document.addEventListener('touchstart', function (e) {
|
||||
firstContact = {
|
||||
x: e.touches[0].clientX,
|
||||
time: Date.now()
|
||||
};
|
||||
}, { passive: true });
|
||||
|
||||
document.addEventListener('touchmove', function (e) {
|
||||
if (!firstContact)
|
||||
return;
|
||||
|
||||
var curX = e.touches[0].clientX;
|
||||
var xDiff = curX - firstContact.x,
|
||||
tDiff = Date.now() - firstContact.time;
|
||||
|
||||
if (tDiff < 250 && Math.abs(xDiff) >= 150) {
|
||||
if (xDiff >= 0 && firstContact.x < Math.min(document.body.clientWidth * 0.25, 300))
|
||||
showSidebar();
|
||||
else if (xDiff < 0 && curX < 300)
|
||||
hideSidebar();
|
||||
|
||||
firstContact = null;
|
||||
}
|
||||
}, { passive: true });
|
||||
})();
|
||||
|
||||
(function chapterNavigation() {
|
||||
document.addEventListener('keydown', function (e) {
|
||||
if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) { return; }
|
||||
if (window.search && window.search.hasFocus()) { return; }
|
||||
var html = document.querySelector('html');
|
||||
|
||||
function next() {
|
||||
var nextButton = document.querySelector('.nav-chapters.next');
|
||||
if (nextButton) {
|
||||
window.location.href = nextButton.href;
|
||||
}
|
||||
}
|
||||
function prev() {
|
||||
var previousButton = document.querySelector('.nav-chapters.previous');
|
||||
if (previousButton) {
|
||||
window.location.href = previousButton.href;
|
||||
}
|
||||
}
|
||||
switch (e.key) {
|
||||
case 'ArrowRight':
|
||||
e.preventDefault();
|
||||
if (html.dir == 'rtl') {
|
||||
prev();
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
break;
|
||||
case 'ArrowLeft':
|
||||
e.preventDefault();
|
||||
if (html.dir == 'rtl') {
|
||||
next();
|
||||
} else {
|
||||
prev();
|
||||
}
|
||||
break;
|
||||
}
|
||||
});
|
||||
})();
|
||||
|
||||
(function clipboard() {
|
||||
var clipButtons = document.querySelectorAll('.clip-button');
|
||||
|
||||
function hideTooltip(elem) {
|
||||
elem.firstChild.innerText = "";
|
||||
elem.className = 'fa fa-copy clip-button';
|
||||
}
|
||||
|
||||
function showTooltip(elem, msg) {
|
||||
elem.firstChild.innerText = msg;
|
||||
elem.className = 'fa fa-copy tooltipped';
|
||||
}
|
||||
|
||||
var clipboardSnippets = new ClipboardJS('.clip-button', {
|
||||
text: function (trigger) {
|
||||
hideTooltip(trigger);
|
||||
let playground = trigger.closest("pre");
|
||||
return playground_text(playground, false);
|
||||
}
|
||||
});
|
||||
|
||||
Array.from(clipButtons).forEach(function (clipButton) {
|
||||
clipButton.addEventListener('mouseout', function (e) {
|
||||
hideTooltip(e.currentTarget);
|
||||
});
|
||||
});
|
||||
|
||||
clipboardSnippets.on('success', function (e) {
|
||||
e.clearSelection();
|
||||
showTooltip(e.trigger, "Copied!");
|
||||
});
|
||||
|
||||
clipboardSnippets.on('error', function (e) {
|
||||
showTooltip(e.trigger, "Clipboard error!");
|
||||
});
|
||||
})();
|
||||
|
||||
(function scrollToTop () {
|
||||
var menuTitle = document.querySelector('.menu-title');
|
||||
|
||||
menuTitle.addEventListener('click', function () {
|
||||
document.scrollingElement.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
});
|
||||
})();
|
||||
|
||||
(function controllMenu() {
|
||||
var menu = document.getElementById('menu-bar');
|
||||
|
||||
(function controllBorder() {
|
||||
function updateBorder() {
|
||||
if (menu.offsetTop === 0) {
|
||||
menu.classList.remove('bordered');
|
||||
} else {
|
||||
menu.classList.add('bordered');
|
||||
}
|
||||
}
|
||||
updateBorder();
|
||||
document.addEventListener('scroll', updateBorder, { passive: true });
|
||||
})();
|
||||
})();
|
||||
82
doc/theme/highlight.css
vendored
Normal file
82
doc/theme/highlight.css
vendored
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
/*
|
||||
* An increased contrast highlighting scheme loosely based on the
|
||||
* "Base16 Atelier Dune Light" theme by Bram de Haan
|
||||
* (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/dune)
|
||||
* Original Base16 color scheme by Chris Kempson
|
||||
* (https://github.com/chriskempson/base16)
|
||||
*/
|
||||
|
||||
/* Comment */
|
||||
.hljs-comment,
|
||||
.hljs-quote {
|
||||
color: #575757;
|
||||
}
|
||||
|
||||
/* Red */
|
||||
.hljs-variable,
|
||||
.hljs-template-variable,
|
||||
.hljs-attribute,
|
||||
.hljs-tag,
|
||||
.hljs-name,
|
||||
.hljs-regexp,
|
||||
.hljs-link,
|
||||
.hljs-name,
|
||||
.hljs-selector-id,
|
||||
.hljs-selector-class {
|
||||
color: #d70025;
|
||||
}
|
||||
|
||||
/* Orange */
|
||||
.hljs-number,
|
||||
.hljs-meta,
|
||||
.hljs-built_in,
|
||||
.hljs-builtin-name,
|
||||
.hljs-literal,
|
||||
.hljs-type,
|
||||
.hljs-params {
|
||||
color: #b21e00;
|
||||
}
|
||||
|
||||
/* Green */
|
||||
.hljs-string,
|
||||
.hljs-symbol,
|
||||
.hljs-bullet {
|
||||
color: #008200;
|
||||
}
|
||||
|
||||
/* Blue */
|
||||
.hljs-title,
|
||||
.hljs-section {
|
||||
color: #0030f2;
|
||||
}
|
||||
|
||||
/* Purple */
|
||||
.hljs-keyword,
|
||||
.hljs-selector-tag {
|
||||
color: #9d00ec;
|
||||
}
|
||||
|
||||
.hljs {
|
||||
display: block;
|
||||
overflow-x: auto;
|
||||
background: #f6f7f6;
|
||||
color: #000;
|
||||
}
|
||||
|
||||
.hljs-emphasis {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.hljs-strong {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.hljs-addition {
|
||||
color: #22863a;
|
||||
background-color: #f0fff4;
|
||||
}
|
||||
|
||||
.hljs-deletion {
|
||||
color: #b31d28;
|
||||
background-color: #ffeef0;
|
||||
}
|
||||
53
doc/theme/highlight.js
vendored
Normal file
53
doc/theme/highlight.js
vendored
Normal file
File diff suppressed because one or more lines are too long
292
doc/theme/index.hbs
vendored
Normal file
292
doc/theme/index.hbs
vendored
Normal file
|
|
@ -0,0 +1,292 @@
|
|||
<!-- Lang: {{ language }} -->
|
||||
<!-- Title: {{ title }} -->
|
||||
<!-- Print: {{#if print_enable}}enabled{{else}}disabled{{/if}} -->
|
||||
<!-- MathJax: {{#if mathjax_support}}supported{{else}}unsupported{{/if}} -->
|
||||
|
||||
<!-- mdBook -->
|
||||
|
||||
<!-- Provide site root to javascript -->
|
||||
<script>
|
||||
var path_to_root = "{{ path_to_root }}";
|
||||
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "{{ preferred_dark_theme }}" : "{{ default_theme }}";
|
||||
</script>
|
||||
|
||||
<!-- Work around some values being stored in localStorage wrapped in quotes -->
|
||||
<script>
|
||||
try {
|
||||
var theme = localStorage.getItem('mdbook-theme');
|
||||
var sidebar = localStorage.getItem('mdbook-sidebar');
|
||||
|
||||
if (theme.startsWith('"') && theme.endsWith('"')) {
|
||||
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
|
||||
}
|
||||
|
||||
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
|
||||
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
|
||||
}
|
||||
} catch (e) { }
|
||||
</script>
|
||||
|
||||
<!-- Set the theme before any content is loaded, prevents flash -->
|
||||
<script>
|
||||
var theme;
|
||||
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
|
||||
if (theme === null || theme === undefined) { theme = default_theme; }
|
||||
var html = document.querySelector('html');
|
||||
html.classList.remove('{{ default_theme }}')
|
||||
html.classList.add(theme);
|
||||
var body = document.querySelector('body');
|
||||
body.classList.remove('no-js')
|
||||
body.classList.add('js');
|
||||
</script>
|
||||
|
||||
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
|
||||
|
||||
<!-- Hide / unhide sidebar before it is displayed -->
|
||||
<script>
|
||||
var body = document.querySelector('body');
|
||||
var sidebar = null;
|
||||
var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
|
||||
if (document.body.clientWidth >= 1080) {
|
||||
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
|
||||
sidebar = sidebar || 'visible';
|
||||
} else {
|
||||
sidebar = 'hidden';
|
||||
}
|
||||
sidebar_toggle.checked = sidebar === 'visible';
|
||||
body.classList.remove('sidebar-visible');
|
||||
body.classList.add("sidebar-" + sidebar);
|
||||
</script>
|
||||
|
||||
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
|
||||
<div class="sidebar-scrollbox">
|
||||
{{#toc}}{{/toc}}
|
||||
</div>
|
||||
<div id="sidebar-resize-handle" class="sidebar-resize-handle">
|
||||
<div class="sidebar-resize-indicator"></div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<!-- Track and set sidebar scroll position -->
|
||||
<script>
|
||||
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
|
||||
sidebarScrollbox.addEventListener('click', function(e) {
|
||||
if (e.target.tagName === 'A') {
|
||||
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
|
||||
}
|
||||
}, { passive: true });
|
||||
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
|
||||
sessionStorage.removeItem('sidebar-scroll');
|
||||
if (sidebarScrollTop) {
|
||||
// preserve sidebar scroll position when navigating via links within sidebar
|
||||
sidebarScrollbox.scrollTop = sidebarScrollTop;
|
||||
} else {
|
||||
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
|
||||
var activeSection = document.querySelector('#sidebar .active');
|
||||
if (activeSection) {
|
||||
activeSection.scrollIntoView({ block: 'center' });
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div id="page-wrapper" class="page-wrapper">
|
||||
|
||||
<div class="page">
|
||||
{{> header}}
|
||||
<div id="menu-bar-hover-placeholder"></div>
|
||||
<div id="menu-bar" class="menu-bar sticky">
|
||||
<div class="left-buttons">
|
||||
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
|
||||
<i class="fa fa-bars"></i>
|
||||
</label>
|
||||
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
|
||||
<i class="fa fa-paint-brush"></i>
|
||||
</button>
|
||||
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
|
||||
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
|
||||
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
|
||||
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
|
||||
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
|
||||
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
|
||||
</ul>
|
||||
{{#if search_enabled}}
|
||||
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
|
||||
<i class="fa fa-search"></i>
|
||||
</button>
|
||||
{{/if}}
|
||||
</div>
|
||||
|
||||
<h1 class="menu-title">{{ book_title }}</h1>
|
||||
|
||||
<div class="right-buttons">
|
||||
{{#if print_enable}}
|
||||
<a href="{{ path_to_root }}print.html" title="Print this book" aria-label="Print this book">
|
||||
<i id="print-button" class="fa fa-print"></i>
|
||||
</a>
|
||||
{{/if}}
|
||||
{{#if git_repository_url}}
|
||||
<a href="{{git_repository_url}}" title="Git repository" aria-label="Git repository">
|
||||
<i id="git-repository-button" class="fa {{git_repository_icon}}"></i>
|
||||
</a>
|
||||
{{/if}}
|
||||
{{#if git_repository_edit_url}}
|
||||
<a href="{{git_repository_edit_url}}" title="Suggest an edit" aria-label="Suggest an edit">
|
||||
<i id="git-edit-button" class="fa fa-edit"></i>
|
||||
</a>
|
||||
{{/if}}
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{{#if search_enabled}}
|
||||
<div id="search-wrapper" class="hidden">
|
||||
<form id="searchbar-outer" class="searchbar-outer">
|
||||
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
|
||||
</form>
|
||||
<div id="searchresults-outer" class="searchresults-outer hidden">
|
||||
<div id="searchresults-header" class="searchresults-header"></div>
|
||||
<ul id="searchresults">
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
{{/if}}
|
||||
|
||||
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
|
||||
<script>
|
||||
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
|
||||
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
|
||||
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
|
||||
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
|
||||
});
|
||||
</script>
|
||||
|
||||
<div id="content" class="content">
|
||||
<main>
|
||||
{{{ content }}}
|
||||
</main>
|
||||
|
||||
<nav class="nav-wrapper" aria-label="Page navigation">
|
||||
<!-- Mobile navigation buttons -->
|
||||
{{#previous}}
|
||||
<a rel="prev" href="{{ path_to_root }}{{link}}" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
|
||||
<i class="fa fa-angle-left"></i>
|
||||
</a>
|
||||
{{/previous}}
|
||||
|
||||
{{#next}}
|
||||
<a rel="next prefetch" href="{{ path_to_root }}{{link}}" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
|
||||
<i class="fa fa-angle-right"></i>
|
||||
</a>
|
||||
{{/next}}
|
||||
|
||||
<div style="clear: both"></div>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav class="nav-wide-wrapper" aria-label="Page navigation">
|
||||
{{#previous}}
|
||||
<a rel="prev" href="{{ path_to_root }}{{link}}" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
|
||||
<i class="fa fa-angle-left"></i>
|
||||
</a>
|
||||
{{/previous}}
|
||||
|
||||
{{#next}}
|
||||
<a rel="next prefetch" href="{{ path_to_root }}{{link}}" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
|
||||
<i class="fa fa-angle-right"></i>
|
||||
</a>
|
||||
{{/next}}
|
||||
</nav>
|
||||
|
||||
</div>
|
||||
|
||||
{{#if live_reload_endpoint}}
|
||||
<!-- Livereload script (if served using the cli tool) -->
|
||||
<script>
|
||||
const wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const wsAddress = wsProtocol + "//" + location.host + "/" + "{{{live_reload_endpoint}}}";
|
||||
const socket = new WebSocket(wsAddress);
|
||||
socket.onmessage = function (event) {
|
||||
if (event.data === "reload") {
|
||||
socket.close();
|
||||
location.reload();
|
||||
}
|
||||
};
|
||||
|
||||
window.onbeforeunload = function() {
|
||||
socket.close();
|
||||
}
|
||||
</script>
|
||||
{{/if}}
|
||||
|
||||
{{#if google_analytics}}
|
||||
<!-- Google Analytics Tag -->
|
||||
<script>
|
||||
var localAddrs = ["localhost", "127.0.0.1", ""];
|
||||
|
||||
// make sure we don't activate google analytics if the developer is
|
||||
// inspecting the book locally...
|
||||
if (localAddrs.indexOf(document.location.hostname) === -1) {
|
||||
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
|
||||
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
|
||||
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
|
||||
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
|
||||
|
||||
ga('create', '{{google_analytics}}', 'auto');
|
||||
ga('send', 'pageview');
|
||||
}
|
||||
</script>
|
||||
{{/if}}
|
||||
|
||||
{{#if playground_line_numbers}}
|
||||
<script>
|
||||
window.playground_line_numbers = true;
|
||||
</script>
|
||||
{{/if}}
|
||||
|
||||
{{#if playground_copyable}}
|
||||
<script>
|
||||
window.playground_copyable = true;
|
||||
</script>
|
||||
{{/if}}
|
||||
|
||||
{{#if playground_js}}
|
||||
<script src="{{ path_to_root }}ace.js"></script>
|
||||
<script src="{{ path_to_root }}editor.js"></script>
|
||||
<script src="{{ path_to_root }}mode-rust.js"></script>
|
||||
<script src="{{ path_to_root }}theme-dawn.js"></script>
|
||||
<script src="{{ path_to_root }}theme-tomorrow_night.js"></script>
|
||||
{{/if}}
|
||||
|
||||
{{#if search_js}}
|
||||
<script src="{{ path_to_root }}elasticlunr.min.js"></script>
|
||||
<script src="{{ path_to_root }}mark.min.js"></script>
|
||||
<script src="{{ path_to_root }}searcher.js"></script>
|
||||
{{/if}}
|
||||
|
||||
<script src="{{ path_to_root }}clipboard.min.js"></script>
|
||||
<script src="{{ path_to_root }}highlight.js"></script>
|
||||
<script src="{{ path_to_root }}book.js"></script>
|
||||
|
||||
<!-- Custom JS scripts -->
|
||||
{{#each additional_js}}
|
||||
<script src="{{ ../path_to_root }}{{this}}"></script>
|
||||
{{/each}}
|
||||
|
||||
{{#if is_print}}
|
||||
{{#if mathjax_support}}
|
||||
<script>
|
||||
window.addEventListener('load', function() {
|
||||
MathJax.Hub.Register.StartupHook('End', function() {
|
||||
window.setTimeout(window.print, 100);
|
||||
});
|
||||
});
|
||||
</script>
|
||||
{{else}}
|
||||
<script>
|
||||
window.addEventListener('load', function() {
|
||||
window.setTimeout(window.print, 100);
|
||||
});
|
||||
</script>
|
||||
{{/if}}
|
||||
{{/if}}
|
||||
14
doc/v0.6/es/book.toml
Normal file
14
doc/v0.6/es/book.toml
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
[book]
|
||||
authors = ["Manuel Cillero"]
|
||||
language = "es"
|
||||
src = "src"
|
||||
title = "Guía de PageTop"
|
||||
|
||||
[output.html]
|
||||
theme = "../../theme"
|
||||
# The guides number the steps of each page themselves; the sidebar groups pages by kind.
|
||||
no-section-label = true
|
||||
|
||||
# The examples need PageTop: they cannot run in the Rust playground.
|
||||
[output.html.playground]
|
||||
runnable = false
|
||||
3
doc/v0.6/es/src/404.md
Normal file
3
doc/v0.6/es/src/404.md
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
# Documento no encontrado (404)
|
||||
|
||||
Esta URL no es válida, lo sentimos. ¡Intenta buscar en su lugar!
|
||||
73
doc/v0.6/es/src/SUMMARY.md
Normal file
73
doc/v0.6/es/src/SUMMARY.md
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
# Summary
|
||||
|
||||
[PageTop](intro.md)
|
||||
|
||||
# Tutoriales
|
||||
|
||||
- [Tu primera aplicación](tutorials/first-app.md)
|
||||
- [Recorrido por PageTop](tutorials/tour.md)
|
||||
- [Tareas del huerto con HTMX](tutorials/htmx-tasks.md)
|
||||
- [Guarda las tareas en una base de datos](tutorials/database.md)
|
||||
|
||||
# Guías prácticas
|
||||
|
||||
- [Páginas y componentes]()
|
||||
- [Añadir rutas](how-to/routes.md)
|
||||
- [Construir páginas](how-to/pages.md)
|
||||
- [Mostrar páginas de error](how-to/error-pages.md)
|
||||
- [Escribir HTML con `html!`](how-to/html.md)
|
||||
- [Usar componentes](how-to/components.md)
|
||||
- [Crear un componente](how-to/custom-components.md)
|
||||
- [Maquetar con Flex y Grid](how-to/layout.md)
|
||||
- [Añadir navegación](how-to/navigation.md)
|
||||
- [Crear y procesar formularios](how-to/forms.md)
|
||||
- [Mostrar tablas ordenables y paginadas](how-to/tables.md)
|
||||
- [Interactividad con HTMX]()
|
||||
- [Añadir HTMX a una aplicación](how-to/htmx-setup.md)
|
||||
- [Cargar contenido bajo demanda](how-to/htmx-load.md)
|
||||
- [Buscar mientras se escribe](how-to/htmx-search.md)
|
||||
- [Validar un campo al vuelo](how-to/htmx-validation.md)
|
||||
- [Editar en línea](how-to/htmx-edit.md)
|
||||
- [Borrar con confirmación](how-to/htmx-delete.md)
|
||||
- [Ordenar y paginar sin recargar](how-to/htmx-tables.md)
|
||||
- [Cargar más al hacer *scroll*](how-to/htmx-infinite.md)
|
||||
- [Actualizar periódicamente](how-to/htmx-polling.md)
|
||||
- [Dirigir al navegador desde el servidor](how-to/htmx-responses.md)
|
||||
- [Datos y usuarios]()
|
||||
- [Conectar una base de datos](how-to/database.md)
|
||||
- [Añadir usuarios y permisos](how-to/users.md)
|
||||
- [Añadir páginas al panel de administración](how-to/admin.md)
|
||||
- [La aplicación]()
|
||||
- [Configurar la aplicación](how-to/configuration.md)
|
||||
- [Compartir un servicio entre rutas](how-to/services.md)
|
||||
- [Añadir *middleware*](how-to/middleware.md)
|
||||
- [Traducir la aplicación](how-to/localization.md)
|
||||
- [Servir recursos estáticos](how-to/assets.md)
|
||||
- [Probar rutas y componentes](how-to/testing.md)
|
||||
- [Registrar trazas](how-to/logging.md)
|
||||
- [Desplegar en producción](how-to/deployment.md)
|
||||
- [Extender PageTop]()
|
||||
- [Crear una extensión](how-to/extensions.md)
|
||||
- [Intervenir con acciones](how-to/actions.md)
|
||||
- [Crear un tema](how-to/themes.md)
|
||||
|
||||
# Referencia
|
||||
|
||||
- [Opciones de configuración](reference/configuration.md)
|
||||
- [Catálogo de componentes](reference/components.md)
|
||||
- [HTMX: atributos, cabeceras y respuestas](reference/htmx.md)
|
||||
- [Extensiones oficiales](reference/extensions.md)
|
||||
- [Referencia rápida](reference/cheatsheet.md)
|
||||
|
||||
# Explicación
|
||||
|
||||
- [Por qué PageTop](explanation/why.md)
|
||||
- [PageTop frente a otros *frameworks*](explanation/comparison.md)
|
||||
- [Arquitectura: del arranque a la respuesta](explanation/architecture.md)
|
||||
- [Componentes, temas y renderizado](explanation/rendering.md)
|
||||
- [HTML por la red: por qué HTMX](explanation/htmx.md)
|
||||
- [Si vienes de Axum](explanation/coming-from-axum.md)
|
||||
|
||||
---
|
||||
|
||||
[Preguntas frecuentes](faq.md)
|
||||
131
doc/v0.6/es/src/explanation/architecture.md
Normal file
131
doc/v0.6/es/src/explanation/architecture.md
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
# Arquitectura: del arranque a la respuesta
|
||||
|
||||
Una aplicación PageTop vive dos momentos distintos: el **arranque**, que ocurre una vez y prepara
|
||||
todo, y la **petición**, que ocurre miles de veces y debe ser rápida. Entender qué pasa en cada uno
|
||||
explica casi todas las decisiones de diseño de PageTop.
|
||||
|
||||
## Un árbol de extensiones
|
||||
|
||||
Una aplicación es un **árbol de extensiones**. En la raíz está la tuya; de ella cuelgan las que
|
||||
declara como dependencias, y de esas, las suyas:
|
||||
|
||||
```text
|
||||
MyApp <- root extension
|
||||
├── Bootsier <- theme
|
||||
├── User <- accounts and permissions
|
||||
│ ├── Admin
|
||||
│ ├── SeaORM <- database
|
||||
│ └── Htmx
|
||||
└── Blog <- your feature
|
||||
└── SeaORM <- the same one: each extension is registered once
|
||||
```
|
||||
|
||||
Este árbol es independiente de las dependencias de `Cargo.toml`: Cargo decide qué se **compila**;
|
||||
`dependencies()` decide qué se **activa** y en qué orden. Una extensión compilada pero que nadie
|
||||
declara no registra rutas ni ajustes.
|
||||
|
||||
Separar la extensión raíz en `src/lib.rs` y dejar `src/main.rs` con lo mínimo permite usar la
|
||||
aplicación como biblioteca, por ejemplo desde las pruebas:
|
||||
|
||||
```text
|
||||
my-app/
|
||||
├── Cargo.toml
|
||||
├── config/
|
||||
│ ├── common.toml <- common settings
|
||||
│ └── local.toml <- local settings (not versioned)
|
||||
└── src/
|
||||
├── lib.rs <- root extension
|
||||
├── main.rs <- startup
|
||||
└── locale/ <- translations
|
||||
├── en-US/
|
||||
└── es-ES/
|
||||
```
|
||||
|
||||
## El arranque
|
||||
|
||||
`Application::prepare()` sigue siempre los mismos pasos:
|
||||
|
||||
```text
|
||||
Application::prepare(&MyApp)
|
||||
1. banner and traces [log] settles how much is traced and where
|
||||
2. language and time zone the defaults of [app]
|
||||
3. register extensions walks the tree: dependencies first, each one once
|
||||
4. load settings every settings() section, validated
|
||||
5. default theme the one in [app] theme, or Basic with a warning
|
||||
6. register actions every actions(), sorted by weight
|
||||
7. initialize extensions every initialize(), dependencies first
|
||||
|
|
||||
v
|
||||
.run()
|
||||
8. build the server routes + middleware + static files
|
||||
9. serve requests until Ctrl+C or SIGTERM
|
||||
```
|
||||
|
||||
Dos consecuencias importantes:
|
||||
|
||||
- **Lo que falla, falla al arrancar.** Una clave mal escrita, un valor no válido, una base de datos
|
||||
que no responde o una migración rota detienen la aplicación antes de servir una sola petición,
|
||||
con un mensaje que explica la causa. Nunca hay una aplicación a medias en producción.
|
||||
- **Lo costoso se hace una vez.** Las traducciones, los ajustes, las acciones y los recursos
|
||||
estáticos se cargan o se registran al arrancar; en cada petición sólo se consultan.
|
||||
|
||||
## La petición
|
||||
|
||||
Cuando llega una petición, recorre las capas que construyó `run()`:
|
||||
|
||||
```text
|
||||
request
|
||||
|
|
||||
v
|
||||
+------------------------------------------------------------+
|
||||
| static files (/static, /htmx...) -> served directly, |
|
||||
| without middleware |
|
||||
+------------------------------------------------------------+
|
||||
| middleware of the extensions (session, current user...) |
|
||||
| +------------------------------------------------------+ |
|
||||
| | router -> your handler | |
|
||||
| | Page::new(request) builds the Context: | |
|
||||
| | language, theme, user, zone | |
|
||||
| | .with_child(...) adds components, not HTML | |
|
||||
| | .render() the theme lays out the page | |
|
||||
| +------------------------------------------------------+ |
|
||||
+------------------------------------------------------------+
|
||||
|
|
||||
v
|
||||
response (complete HTML, or a fragment for HTMX)
|
||||
```
|
||||
|
||||
- Los **archivos estáticos** se registran después del *middleware*, así que no pasan por él:
|
||||
servir una hoja de estilos no resuelve sesiones ni consulta la base de datos.
|
||||
- El **middleware** de cada extensión (`configure_middleware()`) envuelve las rutas de **todas**
|
||||
las extensiones. Así, `pagetop-user` resuelve la sesión una vez y cualquier ruta sabe quién pide.
|
||||
- El ***handler*** es un *handler* de Axum normal. `Page::new(request)` crea el **contexto** de la
|
||||
petición, que viajará por todos los componentes: el idioma negociado, el tema, el usuario, la
|
||||
zona horaria, los recursos y los mensajes.
|
||||
|
||||
Qué pasa dentro de `render()` se explica en [Componentes, temas y renderizado](rendering.md).
|
||||
|
||||
## Sin estado mutable compartido
|
||||
|
||||
Los ajustes son de sólo lectura, las acciones se registran una vez y los componentes globales
|
||||
(`InRegion`) se **clonan** para cada página. Cada petición trabaja con su propio contexto y sus
|
||||
propias copias: lo que un componente cambia al renderizarse no afecta a otras peticiones. El estado
|
||||
que debe compartirse entre peticiones (datos, sesiones) vive en la base de datos o, si es tuyo, en
|
||||
tus propias estructuras.
|
||||
|
||||
## El preludio
|
||||
|
||||
Casi todo lo que necesitas está en un solo `use`:
|
||||
|
||||
```rust
|
||||
use pagetop::prelude::*;
|
||||
```
|
||||
|
||||
Trae los tipos principales (`Extension`, `Page`, `Component`, `Lc`...), los componentes base, las
|
||||
macros (`html!`, `include_locales!`...) y accesos directos a módulos como `web`, `trace`, `util` o
|
||||
`global`. Las extensiones tienen el suyo: `pagetop_htmx::prelude::*`, `pagetop_user::prelude::*`...
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Componentes, temas y renderizado](rendering.md).
|
||||
- [Si vienes de Axum](coming-from-axum.md): qué es igual y qué cambia.
|
||||
59
doc/v0.6/es/src/explanation/coming-from-axum.md
Normal file
59
doc/v0.6/es/src/explanation/coming-from-axum.md
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
# Si vienes de Axum
|
||||
|
||||
PageTop está construido **sobre** [Axum](https://docs.rs/axum) y [Tokio](https://tokio.rs), no al
|
||||
lado. Lo que sabes de Axum sigue valiendo: las rutas, los extractores, las respuestas y el
|
||||
*middleware* son los suyos, reexportados en `web`. PageTop añade lo que una aplicación web completa
|
||||
necesita encima, y una forma de organizarlo.
|
||||
|
||||
## Lo que se traduce directamente
|
||||
|
||||
| En Axum | En PageTop | Qué cambia |
|
||||
|---|---|---|
|
||||
| `Router::new().route(...)` | `configure_router()` de cada extensión | Cada extensión añade sus rutas al mismo `Router` |
|
||||
| `axum::routing::get`, `post`... | `web::get`, `web::post`... | Nada: son los mismos |
|
||||
| `Path`, `Query`, `Form`, `Json` | `web::Path`, `web::Query`, `web::Form`, `Json` | Nada |
|
||||
| `Request` | `HttpRequest` | Una vista clonable de la petición, que no consume el cuerpo y se puede pedir junto a cualquier extractor |
|
||||
| `impl IntoResponse` | `IntoResponse`, `Response` | Nada; `Markup` y `ErrorPage` también la implementan |
|
||||
| `Redirect::to(...)` | `Redirect::see_other(...)`, `found()`, `temporary()`... | Un constructor por código de estado |
|
||||
| `middleware::from_fn` | `web::middleware::from_fn` en `configure_middleware()` | Se aplica a las rutas de todas las extensiones |
|
||||
| `ServeDir` | `serve_static_files!` en `configure_static_files()` | Los archivos pueden ir dentro del binario |
|
||||
| `#[tokio::main]` | `#[pagetop::main]` | Prepara el *runtime* que usa PageTop |
|
||||
| `#[tokio::test]` | `#[pagetop::test]` | Igual, para las pruebas |
|
||||
| `State<T>` | Ajustes con `#[settings]`, estáticos propios | Ver abajo |
|
||||
|
||||
## Lo que PageTop añade
|
||||
|
||||
- **Páginas completas** con `Page`: el `<head>`, los recursos sin duplicados, el idioma, la
|
||||
dirección del texto y la estructura del tema.
|
||||
- **Componentes** con su HTML, sus estilos y su comportamiento, que se adaptan al tema activo.
|
||||
- **Temas intercambiables** desde la configuración.
|
||||
- **Configuración en cascada** con validación al arrancar.
|
||||
- **Traducciones** con Fluent, integradas en el binario.
|
||||
- **Extensiones** con dependencias y un orden de arranque garantizado, que se suman con una línea.
|
||||
- **Páginas de error** (403, 404, 500...) con el aspecto del sitio.
|
||||
|
||||
## El estado de la aplicación
|
||||
|
||||
En Axum, el estado compartido suele viajar con `State<T>`. En PageTop, cada extensión gestiona el
|
||||
suyo:
|
||||
|
||||
- La **configuración** se declara con `#[settings]` y se lee desde cualquier sitio con su estático
|
||||
(`SETTINGS.page_size`), sin pasarla de *handler* en *handler*.
|
||||
- Los **recursos** que se crean al arrancar (una conexión, un cliente HTTP, una caché) se
|
||||
inicializan en `initialize()` y se guardan en un estático (`OnceLock`, `LazyLock`). Así lo hace
|
||||
`pagetop-seaorm` con su `dbconn()`. Paso a paso en [Compartir un servicio entre
|
||||
rutas](../how-to/services.md).
|
||||
- Lo que depende de **cada petición** (el idioma, el usuario, el tema) está en el `Context` que crea
|
||||
`Page::new(request)` y que reciben todos los componentes.
|
||||
|
||||
## Mezclar código de Axum
|
||||
|
||||
`configure_router()` recibe y devuelve un `Router` de Axum, así que puedes añadirle cualquier cosa
|
||||
que Axum admita: rutas con capas propias, servicios de Tower, rutas anidadas o un `Router`
|
||||
existente con `merge()`. Una ruta que devuelve JSON convive sin problemas con las que devuelven
|
||||
páginas.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Arquitectura: del arranque a la respuesta](architecture.md).
|
||||
- [Tu primera aplicación](../tutorials/first-app.md).
|
||||
108
doc/v0.6/es/src/explanation/comparison.md
Normal file
108
doc/v0.6/es/src/explanation/comparison.md
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
# PageTop frente a otros *frameworks*
|
||||
|
||||
Rust tiene muy buenos *frameworks* web, y es justo preguntarse por qué elegir uno u otro. Esta
|
||||
página compara PageTop con los más conocidos, con sus puntos fuertes y también con lo que a PageTop
|
||||
todavía le falta.
|
||||
|
||||
A grandes rasgos hay dos familias. Los **modulares** (Axum, Actix Web) te dan las piezas básicas
|
||||
para atender peticiones y te dejan elegir el resto: base de datos, plantillas, usuarios. Los
|
||||
**completos** (Rocket en parte, Loco, Cot) traen de serie muchas de esas piezas y unas convenciones
|
||||
para encajarlas. PageTop está en la segunda familia, con un matiz: lo que trae lo organiza en
|
||||
**extensiones**, **componentes** y **temas**, y casi todo es opcional.
|
||||
|
||||
## Tabla comparativa
|
||||
|
||||
| | PageTop | Axum | Actix Web | Rocket | Loco | Cot |
|
||||
|:--|:--|:--|:--|:--|:--|:--|
|
||||
| **Enfoque** | Completo, por extensiones | Modular | Modular | Completo en parte | Completo (como Rails) | Completo (como Django) |
|
||||
| **Base** | Axum | Hyper y Tokio | Actix | Hyper y Tokio | Axum | Axum |
|
||||
| **HTML** | `html!` con componentes y temas | A tu elección | A tu elección | Tera o Handlebars | Tera | Askama |
|
||||
| **Interactividad** | HTMX (extensión) | A tu elección | A tu elección | A tu elección | A tu elección | A tu elección |
|
||||
| **Base de datos** | SeaORM (extensión) | A tu elección | A tu elección | Varias, con su integración | SeaORM | ORM propio |
|
||||
| **Migraciones** | Escritas en Rust, aplicadas al arrancar | Herramientas externas | Herramientas externas | Herramientas externas | Generadas con su CLI | Generadas a partir de los modelos |
|
||||
| **Usuarios y permisos** | Extensión (roles y permisos) | No | No | No | Autenticación con JWT | Autenticación |
|
||||
| **Panel de administración** | Extensible, con formularios de ajustes | No | No | No | No | Generado a partir de los modelos |
|
||||
| **Traducciones** | Fluent, de serie | No | No | No | Fluent, en su plantilla de proyecto | No |
|
||||
| **Tareas en segundo plano y correo** | Todavía no | No | No | No | Sí | Correo y caché |
|
||||
|
||||
## PageTop frente a Axum
|
||||
|
||||
PageTop **está construido sobre Axum**, así que comparten rutas, extractores y respuestas. Lo que
|
||||
sabes de Axum lo puedes usar en PageTop (lo cuenta [Si vienes de Axum](coming-from-axum.md)).
|
||||
|
||||
- **Elige Axum si** quieres controlar cada pieza, construyes una API o un microservicio sin
|
||||
interfaz, o prefieres montar tu propia pila.
|
||||
- **Elige PageTop si** vas a generar páginas: te ahorra el trabajo de juntar plantillas,
|
||||
traducciones, recursos estáticos, configuración y extensiones, y sigues teniendo Axum debajo
|
||||
cuando lo necesites.
|
||||
|
||||
## PageTop frente a Actix Web
|
||||
|
||||
Actix Web es maduro y uno de los más rápidos que existen.
|
||||
|
||||
- **Elige Actix Web si** el rendimiento bruto por petición es lo que más pesa, o ya tienes código
|
||||
sobre su ecosistema.
|
||||
- **Elige PageTop si** te importa más avanzar rápido en una aplicación con interfaz. Rust y Axum ya
|
||||
dan un rendimiento de sobra para la inmensa mayoría de aplicaciones de gestión.
|
||||
|
||||
## PageTop frente a Rocket
|
||||
|
||||
Rocket es conocido por lo agradable que resulta escribir rutas con sus macros y por sus guardas de
|
||||
petición.
|
||||
|
||||
- **Elige Rocket si** te gusta su estilo de API y no te importa elegir tú la capa de datos, los
|
||||
usuarios y la interfaz.
|
||||
- **Elige PageTop si** quieres que esas piezas vengan resueltas: usuarios y permisos, panel de
|
||||
administración, temas y traducciones.
|
||||
|
||||
## PageTop frente a Loco
|
||||
|
||||
Loco se presenta como «el Rails de Rust»: convenciones fuertes, una CLI que genera código y muchas
|
||||
piezas incluidas, también sobre Axum y SeaORM.
|
||||
|
||||
- **Elige Loco si** te gusta la filosofía de Rails, quieres generadores de código, o necesitas ya
|
||||
**tareas en segundo plano**, **tareas programadas** o **envío de correo**, que PageTop todavía no
|
||||
tiene.
|
||||
- **Elige PageTop si** tu aplicación es sobre todo interfaz: los componentes tipados, los temas que
|
||||
pueden cambiar cualquier componente y HTMX integrado no tienen equivalente en Loco, que deja la
|
||||
interfaz en manos de las plantillas.
|
||||
|
||||
## PageTop frente a Cot
|
||||
|
||||
Cot toma la filosofía de Django: un ORM propio que genera las migraciones a partir de los modelos y
|
||||
un panel de administración que se construye solo.
|
||||
|
||||
- **Elige Cot si** te gusta Django y quieres un panel de administración con altas, bajas y
|
||||
modificaciones de tus modelos sin escribir nada.
|
||||
- **Elige PageTop si** prefieres SeaORM, quieres construir la interfaz con componentes y temas en
|
||||
lugar de plantillas, o necesitas traducciones. El panel de PageTop no genera páginas a partir de
|
||||
los modelos, pero cada extensión le añade las suyas, con sus permisos (ve [Añadir páginas al panel
|
||||
de administración](../how-to/admin.md)).
|
||||
|
||||
## PageTop frente a summer-rs
|
||||
|
||||
[summer-rs](https://summer-rs.github.io) (antes spring-rs) se inspira en Spring Boot: un núcleo
|
||||
pequeño de *plugins* que integran piezas del ecosistema (Axum, SQLx, SeaORM, Redis, correo con
|
||||
lettre, tareas programadas, OpenTelemetry, gRPC...), configurados en TOML y con inyección de
|
||||
dependencias en tiempo de compilación.
|
||||
|
||||
- **Elige summer-rs si** construyes servicios o APIs y quieres tener ya integrados la caché, las
|
||||
colas, el correo, las tareas programadas o la observabilidad.
|
||||
- **Elige PageTop si** lo que construyes son páginas: summer-rs no trae plantillas, componentes,
|
||||
temas ni traducciones. La idea de los *plugins* es muy parecida a la de las extensiones; donde
|
||||
summer-rs inyecta componentes, PageTop guarda los servicios en estáticos (ve [Compartir un
|
||||
servicio entre rutas](../how-to/services.md)).
|
||||
|
||||
## ¿Y Leptos o Dioxus?
|
||||
|
||||
Leptos y Dioxus son *frameworks* **de pila completa** que compilan la interfaz a WebAssembly y la
|
||||
ejecutan en el navegador, con renderizado en el servidor como punto de partida. Es el modelo
|
||||
contrario al de PageTop: aquí la interfaz vive en el servidor y HTMX sólo intercambia fragmentos
|
||||
de HTML. Si tu aplicación necesita mucha lógica en el navegador o funcionar sin conexión, mira hacia
|
||||
ellos (lo explica también [Por qué PageTop](why.md#cuándo-no-es-la-mejor-opción)).
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Por qué PageTop](why.md): las ideas detrás del diseño.
|
||||
- [Si vienes de Axum](coming-from-axum.md): lo que ya sabes y lo que cambia.
|
||||
- [HTML por la red: por qué HTMX](htmx.md).
|
||||
68
doc/v0.6/es/src/explanation/htmx.md
Normal file
68
doc/v0.6/es/src/explanation/htmx.md
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
# HTML por la red: por qué HTMX
|
||||
|
||||
PageTop genera HTML en el servidor. Para la interactividad podría haber elegido un *framework* de
|
||||
JavaScript que pidiera JSON y pintara la interfaz en el navegador. Elige [HTMX](https://htmx.org)
|
||||
porque encaja con todo lo demás: el servidor sigue generando el HTML, y el navegador sólo decide
|
||||
cuándo pedirlo y dónde ponerlo.
|
||||
|
||||
## Dos formas de hacer una interfaz interactiva
|
||||
|
||||
| | Aplicación de una sola página (SPA) | HTMX |
|
||||
|---|---|---|
|
||||
| El servidor envía | JSON | HTML |
|
||||
| La interfaz se genera en | El navegador, con JavaScript | El servidor, con los mismos componentes que la página |
|
||||
| Estado de la interfaz | Duplicado: en el servidor y en el cliente | En el servidor |
|
||||
| Lo que hay que mantener | Dos aplicaciones y la API que las une | Una aplicación |
|
||||
| Validación | En los dos lados | En el servidor |
|
||||
| Sin JavaScript | No funciona | Funciona, con recargas completas, si se diseña así |
|
||||
|
||||
Con HTMX, una ruta que responde a una interacción es una ruta como las demás: recibe la petición,
|
||||
consulta lo que haga falta y devuelve HTML. No hay que diseñar una API, ni serializar, ni mantener
|
||||
en sincronía dos modelos de datos.
|
||||
|
||||
## Por qué encaja con PageTop
|
||||
|
||||
- **Los mismos componentes.** El fragmento que devuelve una ruta para HTMX se genera con los mismos
|
||||
componentes, el mismo tema y las mismas traducciones que la página entera. No hay una segunda
|
||||
versión de la interfaz en JavaScript.
|
||||
- **Los atributos son sólo atributos.** Los componentes de PageTop no conocen HTMX. Aceptan
|
||||
atributos con `with_prop()`, y `hx-get` es uno más. Por eso HTMX es una extensión opcional, y
|
||||
un componente sirve igual con HTMX o sin él.
|
||||
- **Lo que se prueba es HTML.** Una ruta para HTMX se prueba como cualquier otra: se envía la
|
||||
petición y se comprueba el HTML y las cabeceras de la respuesta. El comportamiento en el navegador
|
||||
lo declaran los atributos, sin lógica propia que probar.
|
||||
- **Un solo lenguaje.** La lógica de la interfaz está en Rust, comprobada por el compilador.
|
||||
|
||||
## Mejora progresiva
|
||||
|
||||
Una página bien hecha con HTMX funciona **antes** de que HTMX llegue: los enlaces llevan su `href` y
|
||||
los formularios su `action`. HTMX intercepta esa navegación y la convierte en una petición parcial,
|
||||
y la ruta responde según quién llame:
|
||||
|
||||
```text
|
||||
+--> HX-Request: true --> only the fragment
|
||||
GET /plants?q=to ------+
|
||||
+--> (no header) --> the whole page
|
||||
```
|
||||
|
||||
Así, la misma URL sirve para buscar sin recargar, para compartir el resultado y para recargar la
|
||||
página. Las guías de [búsqueda](../how-to/htmx-search.md) y de [tablas](../how-to/htmx-tables.md) lo
|
||||
aplican.
|
||||
|
||||
## Cuándo no es la herramienta adecuada
|
||||
|
||||
HTMX resuelve muy bien las interfaces de gestión, los formularios, los listados, los paneles y la
|
||||
mayoría de webs con contenido. No es la mejor opción para:
|
||||
|
||||
- interfaces que deben funcionar **sin conexión**;
|
||||
- interacciones de **alta frecuencia** en el propio navegador, como un editor gráfico, un juego o
|
||||
arrastrar elementos con respuesta inmediata a cada píxel;
|
||||
- aplicaciones donde casi todo ocurre en el cliente y el servidor apenas interviene.
|
||||
|
||||
Para esos casos puntuales, nada impide añadir JavaScript propio a una página o a un componente:
|
||||
PageTop lo gestiona como cualquier otro recurso.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Tareas del huerto con HTMX](../tutorials/htmx-tasks.md): el enfoque en la práctica.
|
||||
- [HTMX: atributos, cabeceras y respuestas](../reference/htmx.md).
|
||||
101
doc/v0.6/es/src/explanation/rendering.md
Normal file
101
doc/v0.6/es/src/explanation/rendering.md
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
# Componentes, temas y renderizado
|
||||
|
||||
En PageTop, una página no se escribe: se **compone**. El *handler* añade componentes; el tema decide
|
||||
dónde va cada uno y cómo se ve; las extensiones pueden intervenir en el camino. Esta página explica
|
||||
quién decide qué, y en qué orden.
|
||||
|
||||
## Componentes, no HTML
|
||||
|
||||
`with_child()` no añade HTML a la página, sino **un componente**: un valor Rust con sus datos.
|
||||
El HTML se genera más tarde, al llamar a `render()`, cuando ya se sabe:
|
||||
|
||||
- el **idioma** de quien visita, para resolver cada `Lc`;
|
||||
- el **tema** activo, que puede ajustar o reescribir el componente;
|
||||
- el **usuario**, para mostrar u ocultar lo que corresponda;
|
||||
- los **recursos** que necesita cada componente, para ponerlos en el `<head>`.
|
||||
|
||||
Por eso un componente no debe guardar HTML ya generado: guarda los datos (un `Lc`, una ruta, otros
|
||||
componentes) y los convierte en HTML al renderizarse.
|
||||
|
||||
## Regiones y plantillas
|
||||
|
||||
Un tema reparte la página en **regiones** (cabecera, contenido, barra lateral, pie...) según una
|
||||
**plantilla**. Los componentes llegan a una región por tres caminos:
|
||||
|
||||
| Camino | Alcance |
|
||||
|---|---|
|
||||
| `page.with_child(c)` / `with_child_in(®ion, c)` | Sólo esta página |
|
||||
| `InRegion::Global(®ion).add(c)` | Todas las páginas, con cualquier tema |
|
||||
| `InRegion::ForTheme(&theme, ®ion).add(c)` | Todas las páginas, sólo con ese tema |
|
||||
|
||||
Las regiones de `CoreRegions` (`Header`, `Content`, `Aside`, `Footer`) existen en cualquier tema,
|
||||
así que una extensión que las use funciona con todos. Un tema puede definir más.
|
||||
|
||||
## El renderizado de una página
|
||||
|
||||
`Page::render()` sigue este orden:
|
||||
|
||||
```text
|
||||
Page::render()
|
||||
1. theme: before_render_page_body(page) the theme adds its own assets
|
||||
2. extensions: BeforeRenderBody e.g. HTMX adds its script
|
||||
3. <body>: the theme renders the regions every component, see below
|
||||
4. theme: after_render_page_body(page)
|
||||
5. extensions: AfterRenderBody
|
||||
6. <head>: title, metadata and every asset collected so far
|
||||
```
|
||||
|
||||
El `<head>` se genera **al final**: así recoge los estilos y *scripts* que los componentes
|
||||
añadieron al contexto mientras se renderizaban. Un componente que sólo aparece en algunas páginas
|
||||
sólo carga sus recursos en esas páginas, y una vez aunque aparezca muchas veces.
|
||||
|
||||
## El renderizado de un componente
|
||||
|
||||
Cada componente, en cada región, pasa por estos pasos:
|
||||
|
||||
```text
|
||||
component.render(cx)
|
||||
1. is_renderable(cx)? no -> nothing is rendered
|
||||
2. setup(cx) the component adjusts its own state
|
||||
3. BeforeRender<C> extensions adjust it (add classes, change texts...)
|
||||
4. for the active theme, then its parent, and so on:
|
||||
setup_component() the theme adjusts it
|
||||
render_component() the theme may render it its own way -> done
|
||||
5. prepare(cx) if no theme rendered it, the component does
|
||||
6. AfterRender<C> extensions react
|
||||
7. TransformMarkup<C> extensions retouch the final HTML
|
||||
```
|
||||
|
||||
Tres ideas salen de aquí:
|
||||
|
||||
- **El componente propone, el tema dispone.** El componente define sus datos y un HTML por defecto;
|
||||
el tema puede retocar los datos (`setup_component()`) o reemplazar el HTML entero
|
||||
(`render_component()`). Por eso los componentes exponen sus datos con *getters*: el tema los lee
|
||||
sin depender de sus detalles internos.
|
||||
- **Los temas se heredan.** Si el tema activo no reescribe un componente, se pregunta a su padre, y
|
||||
así hasta llegar al HTML del propio componente. Un tema hijo sólo cambia lo que necesita.
|
||||
- **Las extensiones no se pisan.** Varias acciones del mismo tipo se ejecutan en orden de peso, y
|
||||
cada `TransformMarkup` recibe el HTML que dejó la anterior.
|
||||
|
||||
Si `prepare()` devuelve un error, la página no se cae: se registra una traza con el componente y la
|
||||
ruta, y se pinta un contenido de reserva en su lugar.
|
||||
|
||||
## `setup()` prepara, `prepare()` pinta
|
||||
|
||||
`setup()` es síncrono y recibe el componente mutable: es el sitio para calcular clases o ajustar
|
||||
datos. `prepare()` es asíncrono y recibe el componente sin poder modificarlo: es el sitio para
|
||||
consultar una base de datos o un servicio y generar el HTML. Separarlos permite que las acciones y
|
||||
el tema actúen **entre** los dos, sobre un componente ya ajustado.
|
||||
|
||||
## Fragmentos para HTMX
|
||||
|
||||
Un componente también se renderiza fuera de una página, con `component.render(&mut cx)`, para
|
||||
devolverlo como fragmento a [HTMX](htmx.md). Pasa por los mismos pasos, con el mismo tema y las
|
||||
mismas acciones, así que el fragmento es idéntico a como se vería dentro de la página. Lo único que
|
||||
no tiene es `<head>`: los recursos que el componente añada al contexto no llegan al navegador, y la
|
||||
página que recibe el fragmento debe cargarlos ya.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Crear un componente](../how-to/custom-components.md).
|
||||
- [Crear un tema](../how-to/themes.md) e [Intervenir con acciones](../how-to/actions.md).
|
||||
62
doc/v0.6/es/src/explanation/why.md
Normal file
62
doc/v0.6/es/src/explanation/why.md
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
# Por qué PageTop
|
||||
|
||||
Durante años, la web se construyó así: el servidor genera HTML, el navegador lo muestra y un poco
|
||||
de JavaScript lo hace más ágil. Funcionaba, se entendía y cualquiera podía inspeccionarlo. Luego
|
||||
llegaron las aplicaciones de una sola página, los *frameworks* isomórficos y los *builds* de
|
||||
*frontend* con cientos de dependencias.
|
||||
|
||||
PageTop apuesta por volver a lo esencial, pero con herramientas de hoy:
|
||||
|
||||
| La web clásica | Lo que añade PageTop |
|
||||
|---|---|
|
||||
| HTML generado en el servidor | Generado con código Rust comprobado por el compilador |
|
||||
| Plantillas sueltas | Componentes tipados, configurables y reutilizables |
|
||||
| *Plugins* con efectos inesperados | Extensiones con dependencias declaradas y orden de arranque garantizado |
|
||||
| Temas que se pelean con el contenido | Temas que deciden cómo se pinta cada componente |
|
||||
| Despliegue de muchos archivos | Un binario con los recursos dentro |
|
||||
|
||||
## Cuatro ideas, nada más
|
||||
|
||||
Todo PageTop gira alrededor de cuatro conceptos. Los verás una y otra vez en esta guía:
|
||||
|
||||
- **Extensiones.** Unidades de funcionalidad. Tu aplicación es una extensión, y las que añadas
|
||||
(base de datos, usuarios, un tema...) también lo son.
|
||||
- **Componentes.** Piezas de interfaz que encapsulan HTML, CSS y JavaScript. Se combinan como
|
||||
bloques para formar páginas.
|
||||
- **Temas.** Extensiones especiales que dan el aspecto: maquetan la página por regiones y pueden
|
||||
ajustar o reescribir cualquier componente.
|
||||
- **Acciones.** Puntos de enganche: permiten que una extensión modifique lo que hace otra sin
|
||||
tocar su código.
|
||||
|
||||
## Lo que hay debajo
|
||||
|
||||
PageTop no reinventa la rueda; reúne piezas consolidadas del ecosistema Rust:
|
||||
|
||||
- [Axum](https://docs.rs/axum) y [Tokio](https://tokio.rs) para el servidor web asíncrono.
|
||||
- [Maud](https://maud.lambda.xyz) para escribir HTML dentro de Rust.
|
||||
- [Fluent](https://projectfluent.org) para las traducciones.
|
||||
- [config-rs](https://docs.rs/config) para la configuración en archivos TOML.
|
||||
- [tracing](https://docs.rs/tracing) para las trazas.
|
||||
|
||||
Y se apoya en extensiones opcionales para todo lo demás: [Bootstrap](https://getbootstrap.com) como
|
||||
tema, [HTMX](https://htmx.org) para la interactividad o [SeaORM](https://www.sea-ql.org/SeaORM)
|
||||
para las bases de datos.
|
||||
|
||||
## Cuándo no es la mejor opción
|
||||
|
||||
PageTop está pensado para aplicaciones web generadas en el servidor: gestión, portales, intranets,
|
||||
sitios con contenido. Probablemente **no** sea lo que buscas si:
|
||||
|
||||
- necesitas una aplicación que funcione **sin conexión**, o casi toda su lógica vive en el
|
||||
navegador;
|
||||
- sólo quieres una **API** JSON, sin páginas: Axum a secas es más directo;
|
||||
- necesitas **estabilidad** de API a largo plazo hoy mismo: PageTop todavía cambia entre versiones
|
||||
hasta la 1.0.
|
||||
|
||||
Para todo lo demás, sigue leyendo: [HTML por la red: por qué HTMX](htmx.md) explica cómo cubre
|
||||
PageTop la interactividad sin un *frontend* aparte.
|
||||
|
||||
## Licencia
|
||||
|
||||
PageTop es software libre con doble licencia **MIT o Apache 2.0**, a tu elección. Puedes usarlo en
|
||||
proyectos abiertos o cerrados.
|
||||
132
doc/v0.6/es/src/faq.md
Normal file
132
doc/v0.6/es/src/faq.md
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
# Preguntas frecuentes
|
||||
|
||||
## Desarrollo
|
||||
|
||||
**¿En qué se diferencia PageTop de Loco, Cot o Axum?**
|
||||
|
||||
En que organiza la aplicación en extensiones, componentes y temas, y genera la interfaz en el
|
||||
servidor con HTMX para la interactividad. La comparación completa, con lo que a PageTop todavía le
|
||||
falta, está en [PageTop frente a otros *frameworks*](explanation/comparison.md).
|
||||
|
||||
**¿Cómo reinicio la aplicación sola cada vez que cambio el código?**
|
||||
|
||||
Con una herramienta que vigile los archivos, como [watchexec](https://github.com/watchexec/watchexec):
|
||||
|
||||
```sh
|
||||
watchexec -r -e rs,toml,ftl -- cargo run
|
||||
```
|
||||
|
||||
Reinicia el servidor al cambiar el código, la configuración o las traducciones.
|
||||
[bacon](https://dystroy.org/bacon/) es otra buena opción.
|
||||
|
||||
**¿Puedo cambiar el CSS sin recompilar?**
|
||||
|
||||
Sí. Si publicas tus archivos con `serve_static_files!(router, ["./static", app] => "/static")`,
|
||||
mientras el directorio `static/` exista se sirven desde el disco: editas, recargas el navegador y
|
||||
ves el cambio. En producción, sin ese directorio, se sirven desde el binario. Ver [Servir recursos
|
||||
estáticos](how-to/assets.md).
|
||||
|
||||
**¿Cómo cambio el puerto?**
|
||||
|
||||
En `config/local.toml`, sin recompilar:
|
||||
|
||||
```toml
|
||||
[server]
|
||||
bind_port = 3000
|
||||
```
|
||||
|
||||
**Mi aplicación no arranca después de tocar la configuración.**
|
||||
|
||||
Es a propósito: una clave desconocida o un valor no válido detienen el arranque. El mensaje dice la
|
||||
sección y la clave. Compara con las [opciones de configuración](reference/configuration.md).
|
||||
|
||||
**¿Por qué los enlaces de mi página añaden `?lang=es`?**
|
||||
|
||||
Porque el visitante eligió idioma con `?lang=es` y ése no es el idioma por defecto. Los enlaces
|
||||
internos lo conservan para que no lo pierda al navegar. Si construyes las URL con `cx.route()` o
|
||||
pasas rutas a los componentes, PageTop se encarga solo. Ver [Añadir
|
||||
navegación](how-to/navigation.md#enlaces-que-conservan-el-idioma).
|
||||
|
||||
## Interfaz
|
||||
|
||||
**¿Puedo usar mi propio CSS, o Tailwind?**
|
||||
|
||||
Sí. Puedes añadir hojas de estilo a cualquier página o componente, o crear un tema que las cargue
|
||||
en todas. Los componentes usan clases propias y el tema decide cómo se ven; un tema hijo puede
|
||||
traducir esas clases a las de tu *framework* CSS. Ver [Crear un tema](how-to/themes.md).
|
||||
|
||||
**¿Cómo añado JavaScript propio?**
|
||||
|
||||
Como un recurso más: `JavaScript::defer("/static/js/app.js")` en una página o un componente, o
|
||||
`JavaScript::on_load()` para código que se ejecuta cuando el DOM está listo. Ver [Construir
|
||||
páginas](how-to/pages.md#4-añade-estilos-y-scripts).
|
||||
|
||||
**Mi fragmento de HTMX no aparece en la página.**
|
||||
|
||||
Las causas habituales, en este orden:
|
||||
|
||||
1. La ruta responde con un código **4xx o 5xx**: HTMX no coloca esas respuestas. Usa 200 para los
|
||||
errores que el usuario deba ver.
|
||||
2. El **destino** no existe: revisa el selector de `hx-target`. Si el fragmento sustituyó al propio
|
||||
destino (`outerHTML`) sin incluir su `id`, la siguiente petición ya no lo encuentra.
|
||||
3. Un atributo **heredado** de un elemento padre (`hx-swap`, `hx-target`) cambia el comportamiento.
|
||||
|
||||
En la pestaña *Red* de las herramientas del navegador ves la petición, su código y el HTML
|
||||
recibido.
|
||||
|
||||
**¿Puedo tener una API JSON en la misma aplicación?**
|
||||
|
||||
Sí. Una ruta puede devolver `Json<T>` con cualquier tipo serializable, junto a las que devuelven
|
||||
páginas. Ver [Añadir rutas](how-to/routes.md#4-elige-la-respuesta).
|
||||
|
||||
## Datos
|
||||
|
||||
**¿Qué bases de datos admite?**
|
||||
|
||||
PostgreSQL, MySQL (y MariaDB) y SQLite, a través de `pagetop-seaorm`. El código es el mismo para
|
||||
las tres; cambian la *feature* y la configuración. Ver [Conectar una base de
|
||||
datos](how-to/database.md).
|
||||
|
||||
**¿Puedo escribir SQL a mano?**
|
||||
|
||||
Sí. `fetch_all()` y `fetch_one()` ejecutan consultas construidas con `db::query`, y `execute()`
|
||||
sentencias que modifican datos. Ver [Escribe SQL a mano](how-to/database.md#8-escribe-sql-a-mano).
|
||||
|
||||
**¿Cómo muestro una página 404 o 500 con el aspecto del sitio?**
|
||||
|
||||
Devuelve `Err(ErrorPage::NotFound(Some(request)))` (o la variante que toque) desde el *handler*. Ver
|
||||
[Mostrar páginas de error](how-to/error-pages.md).
|
||||
|
||||
**¿Cómo comprimo las respuestas o limito el tamaño de lo que se envía?**
|
||||
|
||||
Con las capas de `tower-http` en `configure_middleware()`. Ver [Añadir
|
||||
*middleware*](how-to/middleware.md).
|
||||
|
||||
**¿Puedo programar tareas periódicas o enviar correos?**
|
||||
|
||||
Todavía no: PageTop no tiene aún tareas en segundo plano ni envío de correo (ve la [comparación
|
||||
con otros *frameworks*](explanation/comparison.md)).
|
||||
|
||||
**¿Tengo que usar una base de datos?**
|
||||
|
||||
No. Sólo la necesitan las extensiones que la usan, como `pagetop-user`. Una aplicación sin datos
|
||||
persistentes, o que los guarda en otro sitio, funciona igual.
|
||||
|
||||
## Producción
|
||||
|
||||
**¿Necesito Cargo o Rust en el servidor?**
|
||||
|
||||
No. El binario de `cargo build --release` lleva dentro los estilos, los *scripts*, las imágenes y
|
||||
las traducciones. En el servidor sólo necesita, a su lado, el directorio `config/`. Ver [Desplegar
|
||||
en producción](how-to/deployment.md).
|
||||
|
||||
**¿Está listo para producción?**
|
||||
|
||||
PageTop está en desarrollo activo y su API puede cambiar entre versiones hasta la 1.0. Se apoya en
|
||||
piezas maduras del ecosistema (Axum, Tokio, SeaORM, Fluent), pero conviene evaluarlo con tus
|
||||
propios requisitos antes de llevarlo a un sistema crítico.
|
||||
|
||||
**¿Cómo se detiene sin perder peticiones?**
|
||||
|
||||
Con `Ctrl+C` o con `SIGTERM` (lo que envían `systemd` y Docker), PageTop deja de aceptar
|
||||
conexiones, termina las peticiones en curso y vuelca las trazas pendientes.
|
||||
118
doc/v0.6/es/src/how-to/actions.md
Normal file
118
doc/v0.6/es/src/how-to/actions.md
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
# Intervenir con acciones
|
||||
|
||||
**Objetivo:** cambiar lo que hace otra extensión (cómo se ve un componente, qué HTML genera, qué
|
||||
lleva cada página) sin tocar su código.
|
||||
|
||||
Una **acción** permite a una extensión intervenir en lo que hace otra sin tocar su código: ajustar
|
||||
un componente antes de pintarlo, retocar su HTML o añadir algo a todas las páginas.
|
||||
|
||||
Se declaran en `actions()` con la macro `actions!`. PageTop las registra una sola vez al arrancar.
|
||||
|
||||
## 1. Ajusta un componente antes de renderizarlo
|
||||
|
||||
`BeforeRender<C>` recibe el componente (mutable) y el contexto, justo antes de que se pinte. Por
|
||||
ejemplo, añadir una clase a **todos** los botones de la aplicación:
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
|
||||
pub struct RoundButtons;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for RoundButtons {
|
||||
fn actions(&self) -> Vec<ActionBox> {
|
||||
actions![action::component::BeforeRender::<Button>::new(round)]
|
||||
}
|
||||
}
|
||||
|
||||
fn round(button: &mut Button, _cx: &mut Context) {
|
||||
button.alter_prop(PropsOp::add_classes("rounded-pill"));
|
||||
}
|
||||
```
|
||||
|
||||
Para actuar sólo sobre un componente concreto, fíltralo por su identificador:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn highlight(button: &mut Button, _cx: &mut Context) {}
|
||||
# fn f() -> Vec<ActionBox> {
|
||||
actions![
|
||||
action::component::BeforeRender::<Button>::new(highlight).filter_by_referer_id("buy"),
|
||||
]
|
||||
# }
|
||||
```
|
||||
|
||||
## 2. Retoca el HTML final
|
||||
|
||||
`TransformMarkup<C>` recibe el HTML ya generado y devuelve el nuevo. Si hay varias, se encadenan:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
pub struct Marker;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Marker {
|
||||
fn actions(&self) -> Vec<ActionBox> {
|
||||
actions![action::component::TransformMarkup::<Block>::new(mark_block)]
|
||||
}
|
||||
}
|
||||
|
||||
fn mark_block(_block: &Block, _cx: &Context, markup: Markup) -> Markup {
|
||||
html! {
|
||||
div class="marked-block" { (markup) }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`AfterRender<C>` se ejecuta tras renderizar, por si sólo necesitas reaccionar (registrar algo,
|
||||
por ejemplo).
|
||||
|
||||
## 3. Interviene en todas las páginas
|
||||
|
||||
`BeforeRenderBody` y `AfterRenderBody` reciben la página entera. Así añade la extensión HTMX su
|
||||
*script* a todas las páginas:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
pub struct Analytics;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Analytics {
|
||||
fn actions(&self) -> Vec<ActionBox> {
|
||||
actions![action::page::BeforeRenderBody::new(add_script)]
|
||||
}
|
||||
}
|
||||
|
||||
fn add_script(page: &mut Page) {
|
||||
page.alter_assets(JavaScript::defer("/static/js/analytics.js"));
|
||||
}
|
||||
```
|
||||
|
||||
## 4. Decide el orden
|
||||
|
||||
Las acciones de un mismo tipo se ejecutan por **peso** (de menor a mayor; admite negativos) y,
|
||||
a igualdad de peso, por orden de registro:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn first(b: &mut Button, cx: &mut Context) {}
|
||||
# fn f() -> Vec<ActionBox> {
|
||||
actions![action::component::BeforeRender::<Button>::new(first).with_weight(-10)]
|
||||
# }
|
||||
```
|
||||
|
||||
## Resumen
|
||||
|
||||
| Acción | Recibe | Momento |
|
||||
|---|---|---|
|
||||
| `component::BeforeRender<C>` | `&mut C`, `&mut Context` | Antes de renderizar `C` |
|
||||
| `component::AfterRender<C>` | `&mut C`, `&mut Context` | Después de renderizar `C` |
|
||||
| `component::TransformMarkup<C>` | `&C`, `&Context`, `Markup` | Para sustituir el HTML de `C` |
|
||||
| `page::BeforeRenderBody` | `&mut Page` | Antes de renderizar el `<body>` |
|
||||
| `page::AfterRenderBody` | `&mut Page` | Después de renderizar el `<body>` |
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Crear un tema](themes.md): un tema puede hacer lo mismo para todos los componentes.
|
||||
- [Componentes, temas y renderizado](../explanation/rendering.md): en qué momento exacto actúa cada
|
||||
acción.
|
||||
400
doc/v0.6/es/src/how-to/admin.md
Normal file
400
doc/v0.6/es/src/how-to/admin.md
Normal file
|
|
@ -0,0 +1,400 @@
|
|||
# Añadir páginas al panel de administración
|
||||
|
||||
**Objetivo:** dar a tu extensión su sitio en el panel `/admin`: una página de ajustes que el panel
|
||||
construye y guarda por ti, y una página propia con tu contenido, cada una protegida por su permiso.
|
||||
|
||||
El panel lo aporta `pagetop-admin`. No tienes que montarlo: llega con
|
||||
[`pagetop-user`](users.md), que lo necesita para administrar usuarios y roles. Tu extensión sólo
|
||||
**declara** sus páginas, y el panel las coloca en su sección, las enlaza desde el inicio del panel
|
||||
(*dashboard*) y las muestra sólo a quien tenga permiso.
|
||||
|
||||
## 1. Añade la dependencia
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
pagetop-admin = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
||||
pagetop-user = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
||||
pagetop-seaorm = { git = "https://git.cillero.es/manuelcillero/pagetop", features = ["sqlite"] }
|
||||
```
|
||||
|
||||
Tu extensión sigue dependiendo sólo de `pagetop_user::User`, como en [Añadir usuarios y
|
||||
permisos](users.md); el *crate* `pagetop-admin` hace falta para usar sus tipos.
|
||||
|
||||
Ese es el `Cargo.toml` de la **aplicación**, la única que elige el motor de base de datos (aquí
|
||||
SQLite) para todas sus extensiones. Si escribes una extensión aparte, declara `pagetop-admin` y
|
||||
`pagetop-user` igual, pero sin `pagetop-seaorm` (ve [Elige el motor](database.md#1-elige-el-motor)).
|
||||
|
||||
## 2. Define el permiso de cada página
|
||||
|
||||
Cada página del panel exige un permiso. Decláralo como cualquier otro:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum GardenPermission {
|
||||
Configure,
|
||||
SeeHarvest,
|
||||
}
|
||||
|
||||
impl Permission for GardenPermission {
|
||||
fn key(&self) -> CowStr {
|
||||
match self {
|
||||
Self::Configure => "garden.configure".into(),
|
||||
Self::SeeHarvest => "garden.see_harvest".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn label(&self) -> Lc {
|
||||
match self {
|
||||
Self::Configure => Lc::n("Configure the garden"),
|
||||
Self::SeeHarvest => Lc::n("See the harvest report"),
|
||||
}
|
||||
}
|
||||
|
||||
fn group(&self) -> &'static str {
|
||||
"garden"
|
||||
}
|
||||
|
||||
fn group_label(&self) -> Lc {
|
||||
Lc::n("Community garden")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Regístralo con `DeclarePermissions` para que aparezca en la pantalla de roles (lo verás en el
|
||||
ejemplo completo).
|
||||
|
||||
## 3. Deja que el panel construya tus ajustes
|
||||
|
||||
Para una página de ajustes no necesitas ni *handler* ni ruta. Describe los campos con un
|
||||
`SettingsSchema` y declara la página con `AdminPageKind::ConfigForm`. El panel registra la ruta,
|
||||
pinta el formulario con los valores actuales, comprueba que llegan los obligatorios y guarda lo
|
||||
que se envía:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# use pagetop_admin::prelude::*;
|
||||
# #[derive(Clone, Copy, Debug)]
|
||||
# enum GardenPermission { Configure }
|
||||
# impl Permission for GardenPermission {
|
||||
# fn key(&self) -> CowStr { "garden.configure".into() }
|
||||
# }
|
||||
fn garden_settings() -> SettingsSchema {
|
||||
SettingsSchema::new("garden")
|
||||
.with_field(
|
||||
SettingField::text("notice", "Notice for the gardeners")
|
||||
.with_help("Shown on the home page. Leave it empty to hide it."),
|
||||
)
|
||||
.with_field(SettingField::number("plots", "Number of plots").with_required(true))
|
||||
.with_field(SettingField::boolean("open", "Open to new gardeners"))
|
||||
}
|
||||
|
||||
fn declare_pages(bag: &mut PageBag) {
|
||||
bag.add(AdminPage {
|
||||
path: "/admin/config/garden".to_owned(),
|
||||
section: "config".to_owned(),
|
||||
title: Lc::n("Garden"),
|
||||
description: Some(Lc::n("Notice, plots and new gardeners.")),
|
||||
weight: 0,
|
||||
permission: &GardenPermission::Configure,
|
||||
kind: AdminPageKind::ConfigForm(garden_settings()),
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Los campos pueden ser `text`, `number`, `boolean` o `select` (con sus opciones), y admiten
|
||||
`with_required()`, `with_help()` y `with_default()`.
|
||||
|
||||
Las páginas se agrupan en las secciones del panel: `people` (personas), `structure` (estructura),
|
||||
`config` (configuración), `reports` (informes) y `help` (ayuda). El campo `path` es la ruta de la
|
||||
página, que suele colgar de la de su sección (`/admin/config/...`).
|
||||
|
||||
## 4. Lee los ajustes guardados
|
||||
|
||||
Cada campo se guarda con la clave `<ámbito>.<campo>`: aquí, `garden.notice`, `garden.plots` y
|
||||
`garden.open`. Léelos con `pagetop_admin::settings::get_or()`, con el valor que quieras mientras
|
||||
nadie los haya guardado:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
let notice: String = pagetop_admin::settings::get_or("garden.notice", String::new()).await;
|
||||
let open = pagetop_admin::settings::get_or("garden.open", String::new()).await == "true";
|
||||
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("Community garden"))
|
||||
.with_child(Html::with(move |_| {
|
||||
html! {
|
||||
@if !notice.is_empty() {
|
||||
p class="garden-notice" { (notice) }
|
||||
}
|
||||
p { @if open { "We are open to new gardeners." } @else { "No free plots now." } }
|
||||
}
|
||||
}))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
```
|
||||
|
||||
El formulario guarda todos los valores **como texto**, también los números y las casillas
|
||||
(`"true"` o `"false"`): conviértelos al leerlos.
|
||||
|
||||
## 5. Añade una página con tu propio contenido
|
||||
|
||||
Cuando la página no es un formulario de ajustes, declárala con `AdminPageKind::View` y registra tú
|
||||
la ruta. El *handler* crea la página con `Page::admin()` y envuelve el contenido en un
|
||||
`AdminFrame`, que añade la ruta de migas, el título y las pestañas y botones del panel:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# use pagetop_admin::prelude::*;
|
||||
# #[derive(Clone, Copy, Debug)]
|
||||
# enum GardenPermission { SeeHarvest }
|
||||
# impl Permission for GardenPermission {
|
||||
# fn key(&self) -> CowStr { "garden.see_harvest".into() }
|
||||
# }
|
||||
fn declare_report(bag: &mut PageBag) {
|
||||
bag.add(AdminPage {
|
||||
path: "/admin/reports/harvest".to_owned(),
|
||||
section: "reports".to_owned(),
|
||||
title: Lc::n("Harvest"),
|
||||
description: Some(Lc::n("Kilos harvested by crop.")),
|
||||
weight: 0,
|
||||
permission: &GardenPermission::SeeHarvest,
|
||||
kind: AdminPageKind::View,
|
||||
});
|
||||
}
|
||||
|
||||
async fn harvest(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
require_permission(&request, &GardenPermission::SeeHarvest)?;
|
||||
|
||||
let rows = [("Tomatoes", 42), ("Lettuces", 18), ("Courgettes", 27)];
|
||||
Page::admin(request)
|
||||
.with_title(Lc::n("Harvest"))
|
||||
.with_child(
|
||||
AdminFrame::new().with_title(Lc::n("Harvest")).with_child(Html::with(move |_| {
|
||||
html! {
|
||||
ul {
|
||||
@for (crop, kilos) in rows {
|
||||
li { (crop) ": " (kilos) " kg" }
|
||||
}
|
||||
}
|
||||
}
|
||||
})),
|
||||
)
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
```
|
||||
|
||||
Declarar la página no protege la ruta: el `require_permission()` del principio sigue haciendo
|
||||
falta, porque cualquiera puede escribir la URL.
|
||||
|
||||
## 6. Crea una sección propia (opcional)
|
||||
|
||||
Si ninguna sección encaja, declara la tuya con `DeclareAdminSections`. Aparece en el panel en
|
||||
cuanto tenga alguna página que el usuario pueda abrir:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# use pagetop_admin::prelude::*;
|
||||
fn declare_sections(bag: &mut SectionBag) {
|
||||
bag.add(AdminSection {
|
||||
key: "garden".to_owned(),
|
||||
path: "/admin/garden".to_owned(),
|
||||
title: Lc::n("Garden"),
|
||||
weight: 25,
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Regístrala junto a las páginas: `actions![DeclareAdminSections::new(declare_sections), ...]`. El
|
||||
peso decide su posición entre las demás (las de serie usan 10, 20, 30...). Con
|
||||
`DeclareAdminTasks` y `DeclareAdminActions` puedes añadir también pestañas y botones a una página.
|
||||
|
||||
## El ejemplo completo
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
use pagetop_admin::prelude::*;
|
||||
use pagetop_user::PermissionRegistry;
|
||||
use pagetop_user::prelude::*;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum GardenPermission {
|
||||
Configure,
|
||||
SeeHarvest,
|
||||
}
|
||||
|
||||
impl Permission for GardenPermission {
|
||||
fn key(&self) -> CowStr {
|
||||
match self {
|
||||
Self::Configure => "garden.configure".into(),
|
||||
Self::SeeHarvest => "garden.see_harvest".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn label(&self) -> Lc {
|
||||
match self {
|
||||
Self::Configure => Lc::n("Configure the garden"),
|
||||
Self::SeeHarvest => Lc::n("See the harvest report"),
|
||||
}
|
||||
}
|
||||
|
||||
fn group(&self) -> &'static str {
|
||||
"garden"
|
||||
}
|
||||
|
||||
fn group_label(&self) -> Lc {
|
||||
Lc::n("Community garden")
|
||||
}
|
||||
}
|
||||
|
||||
fn declare_permissions(registry: &mut PermissionRegistry) {
|
||||
registry.register(&GardenPermission::Configure);
|
||||
registry.register(&GardenPermission::SeeHarvest);
|
||||
}
|
||||
|
||||
fn garden_settings() -> SettingsSchema {
|
||||
SettingsSchema::new("garden")
|
||||
.with_field(
|
||||
SettingField::text("notice", "Notice for the gardeners")
|
||||
.with_help("Shown on the home page. Leave it empty to hide it."),
|
||||
)
|
||||
.with_field(SettingField::number("plots", "Number of plots").with_required(true))
|
||||
.with_field(SettingField::boolean("open", "Open to new gardeners"))
|
||||
}
|
||||
|
||||
fn declare_pages(bag: &mut PageBag) {
|
||||
bag.add(AdminPage {
|
||||
path: "/admin/config/garden".to_owned(),
|
||||
section: "config".to_owned(),
|
||||
title: Lc::n("Garden"),
|
||||
description: Some(Lc::n("Notice, plots and new gardeners.")),
|
||||
weight: 0,
|
||||
permission: &GardenPermission::Configure,
|
||||
kind: AdminPageKind::ConfigForm(garden_settings()),
|
||||
});
|
||||
bag.add(AdminPage {
|
||||
path: "/admin/reports/harvest".to_owned(),
|
||||
section: "reports".to_owned(),
|
||||
title: Lc::n("Harvest"),
|
||||
description: Some(Lc::n("Kilos harvested by crop.")),
|
||||
weight: 0,
|
||||
permission: &GardenPermission::SeeHarvest,
|
||||
kind: AdminPageKind::View,
|
||||
});
|
||||
}
|
||||
|
||||
struct Garden;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Garden {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_user::User]
|
||||
}
|
||||
|
||||
fn actions(&self) -> Vec<ActionBox> {
|
||||
actions![
|
||||
DeclarePermissions::new(declare_permissions),
|
||||
DeclareAdminPages::new(declare_pages),
|
||||
]
|
||||
}
|
||||
|
||||
async fn initialize(&self) -> Result<(), BoxError> {
|
||||
InRegion::Global(&CoreRegions::Header).add(TopBar::new());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router
|
||||
.route("/", web::get(home))
|
||||
.route("/admin/reports/harvest", web::get(harvest))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(AutoDefault, Clone, Debug)]
|
||||
struct TopBar;
|
||||
|
||||
#[async_trait]
|
||||
impl Component for TopBar {
|
||||
fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
|
||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
let brand = Brand::new()
|
||||
.with_title(Lc::n("Community garden"))
|
||||
.with_route(Route::from("/"));
|
||||
Ok(Navbar::brand_left(brand)
|
||||
.with_item(navbar::Item::nav(account_menu(cx)))
|
||||
.render(cx)
|
||||
.await)
|
||||
}
|
||||
}
|
||||
|
||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
let notice: String = pagetop_admin::settings::get_or("garden.notice", String::new()).await;
|
||||
let open = pagetop_admin::settings::get_or("garden.open", String::new()).await == "true";
|
||||
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("Community garden"))
|
||||
.with_child(Html::with(move |_| {
|
||||
html! {
|
||||
@if !notice.is_empty() {
|
||||
p class="garden-notice" { (notice) }
|
||||
}
|
||||
p { @if open { "We are open to new gardeners." } @else { "No free plots now." } }
|
||||
}
|
||||
}))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
async fn harvest(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
require_permission(&request, &GardenPermission::SeeHarvest)?;
|
||||
|
||||
let rows = [("Tomatoes", 42), ("Lettuces", 18), ("Courgettes", 27)];
|
||||
Page::admin(request)
|
||||
.with_title(Lc::n("Harvest"))
|
||||
.with_child(
|
||||
AdminFrame::new().with_title(Lc::n("Harvest")).with_child(Html::with(move |_| {
|
||||
html! {
|
||||
ul {
|
||||
@for (crop, kilos) in rows {
|
||||
li { (crop) ": " (kilos) " kg" }
|
||||
}
|
||||
}
|
||||
}
|
||||
})),
|
||||
)
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
#[pagetop::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
Application::prepare(&Garden).await.run().await
|
||||
}
|
||||
```
|
||||
|
||||
Usa la misma configuración de base de datos y del administrador que en [Añadir usuarios y
|
||||
permisos](users.md#2-configura-la-base-de-datos-y-el-primer-administrador).
|
||||
|
||||
## Comprueba
|
||||
|
||||
1. Sin iniciar sesión, <http://localhost:8080/admin/reports/harvest> responde con la página de
|
||||
acceso denegado (403).
|
||||
2. Inicia sesión como `admin` y entra en **Administración** desde el menú de cuenta. El inicio del
|
||||
panel muestra «Garden» en Configuración y «Harvest» en Informes.
|
||||
3. Abre «Garden», escribe un aviso, marca «Open to new gardeners» y guarda. La portada muestra el
|
||||
aviso y «We are open to new gardeners.».
|
||||
4. En la pantalla de roles aparece el grupo «Community garden» con sus dos permisos. Concede «See
|
||||
the harvest report» a otro rol: sus usuarios verán el informe, pero no los ajustes.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Añadir usuarios y permisos](users.md): roles, permisos y el menú de cuenta.
|
||||
- [Extensiones oficiales](../reference/extensions.md#administración): lo que aporta
|
||||
`pagetop-admin`.
|
||||
- [Intervenir con acciones](actions.md): `DeclareAdminPages` y compañía son acciones.
|
||||
105
doc/v0.6/es/src/how-to/assets.md
Normal file
105
doc/v0.6/es/src/how-to/assets.md
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
# Servir recursos estáticos
|
||||
|
||||
**Objetivo:** incluir en el binario las hojas de estilo, *scripts*, fuentes e imágenes de tu
|
||||
aplicación, publicarlos en una ruta y usarlos en las páginas.
|
||||
|
||||
Hojas de estilo, *scripts*, fuentes e imágenes se **incluyen en el binario** al compilar. En
|
||||
producción no hay que copiar ningún directorio: el ejecutable lo lleva todo.
|
||||
|
||||
## 1. Sigue la convención `assets/` -> `static/`
|
||||
|
||||
```text
|
||||
my-app/
|
||||
├── assets/ <- versioned sources (SCSS, JS, images...)
|
||||
├── static/ <- generated when compiling; add it to .gitignore
|
||||
└── build.rs <- turns assets/ into static/ and prepares the bundles
|
||||
```
|
||||
|
||||
Añade `pagetop-build` como dependencia de compilación:
|
||||
|
||||
```toml
|
||||
[build-dependencies]
|
||||
pagetop-build = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
||||
```
|
||||
|
||||
## 2. Prepara el `build.rs`
|
||||
|
||||
```rust,no_run
|
||||
use pagetop_build::*;
|
||||
|
||||
fn main() -> std::io::Result<()> {
|
||||
// Regenerates static/ only if something changes in assets/.
|
||||
println!("cargo:rerun-if-changed=assets");
|
||||
let _ = std::fs::remove_dir_all("static");
|
||||
|
||||
// Transforms the sources.
|
||||
compile_scss("assets/scss/app.scss", "static/css/app.min.css")?;
|
||||
minify_js("assets/js/app.js", "static/js/app.min.js")?;
|
||||
copy_dir("assets/img", "static/img")?;
|
||||
|
||||
// Bundles static/ to include it in the binary with the name "app".
|
||||
StaticFilesBundle::from_dir("./static", None)
|
||||
.with_name("app")
|
||||
.build()
|
||||
}
|
||||
```
|
||||
|
||||
Funciones disponibles: `compile_scss()`, `minify_js()`, `copy_dir()`, `copy_file()` y
|
||||
`copy_file_replacing()`, que copia sustituyendo textos (útil para corregir referencias al renombrar
|
||||
archivos). Puedes crear varios paquetes, cada uno con su nombre.
|
||||
|
||||
## 3. Sirve los archivos
|
||||
|
||||
En la extensión, publica el paquete con `serve_static_files!` dentro de
|
||||
`configure_static_files()`:
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
|
||||
pub struct MyApp;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for MyApp {
|
||||
fn configure_static_files(&self, router: Router) -> Router {
|
||||
serve_static_files!(router, ["./static", app] => "/static");
|
||||
router
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Con la forma `["./static", app]`, si el directorio existe en disco (durante el desarrollo) los
|
||||
archivos se sirven desde ahí y puedes editarlos sin recompilar; si no existe (en producción), se
|
||||
sirven desde el binario. Con `[app]` se sirven siempre desde el binario.
|
||||
|
||||
Las rutas de `configure_static_files()` no pasan por el *middleware* de las extensiones: servir un
|
||||
archivo no resuelve sesiones ni hace trabajo innecesario. Los archivos se sirven con `ETag`, así
|
||||
que el navegador sólo los descarga de nuevo si cambian.
|
||||
|
||||
## 4. Úsalos en las páginas
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_assets(StyleSheet::from("/static/css/app.min.css").with_version("1.0"))
|
||||
.with_assets(JavaScript::defer("/static/js/app.min.js").with_version("1.0"))
|
||||
.with_child(Html::with(|_| html! { img src="/static/img/logo.svg" alt="Logo"; }))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
```
|
||||
|
||||
Si tu extensión es un componente o un tema, añade sus recursos en el `setup()` del componente o
|
||||
en el tema: así se cargan sólo cuando hacen falta.
|
||||
|
||||
## Comprueba
|
||||
|
||||
Pide uno de los archivos directamente (`curl -I http://localhost:8080/static/css/app.min.css`):
|
||||
responde `200` con su `ETag`. Compila en modo *release*, borra `static/` y arranca el binario:
|
||||
sigue sirviéndolo, desde dentro del ejecutable.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Crear un componente](custom-components.md#5-sus-propios-estilos): componentes que traen sus
|
||||
propios estilos.
|
||||
- [Desplegar en producción](deployment.md).
|
||||
193
doc/v0.6/es/src/how-to/components.md
Normal file
193
doc/v0.6/es/src/how-to/components.md
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
# Usar componentes
|
||||
|
||||
**Objetivo:** construir la interfaz con los componentes que trae PageTop: crearlos, configurarlos,
|
||||
anidarlos y ajustar sus clases y atributos sin tocar su código.
|
||||
|
||||
Un **componente** es una pieza de interfaz con su propio HTML (y, si los necesita, sus estilos y
|
||||
*scripts*). Se crea con un constructor, se configura con métodos `with_*()` encadenados y se añade
|
||||
a una página o a otro componente.
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_child(
|
||||
Block::new()
|
||||
.with_title(Lc::n("What's new"))
|
||||
.with_child(Html::with(|_| html! { p { "Version 2 is here." } }))
|
||||
.with_child(Button::anchor(Lc::n("Download"), "/downloads")),
|
||||
)
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
```
|
||||
|
||||
Los componentes **no se pintan al crearlos**, sino al renderizar la página. Por eso pueden
|
||||
adaptarse al idioma de cada visitante, al tema activo o al usuario conectado.
|
||||
|
||||
## El catálogo básico
|
||||
|
||||
PageTop trae un conjunto de componentes que funcionan con cualquier tema. La lista completa, con
|
||||
sus constructores, está en el [catálogo de componentes](../reference/components.md).
|
||||
|
||||
| Componente | Para qué sirve |
|
||||
|---|---|
|
||||
| `Html` | Marcado puntual con `html!` |
|
||||
| `Container` | Agrupa componentes en un `<div>`, `<section>`, `<header>`... |
|
||||
| `Block` | Bloque con título y contenido |
|
||||
| `Intro` | Portada de bienvenida con título, eslogan y botón |
|
||||
| `Button` | Botones y enlaces con aspecto de botón |
|
||||
| `Badge` | Etiquetas pequeñas de estado |
|
||||
| `Image` | Imágenes, también *responsive* |
|
||||
| `Brand` | Logotipo y nombre del sitio |
|
||||
| `Breadcrumb` | Migas de pan |
|
||||
| `Messages` | Avisos al usuario |
|
||||
| `Dialog` | Ventanas de diálogo |
|
||||
| `Flex`, `Grid` | [Maquetación](layout.md) |
|
||||
| `Nav`, `Navbar`, `Dropdown` | [Navegación](navigation.md) |
|
||||
| `Form` y sus campos | [Formularios](forms.md) |
|
||||
| `Table`, `Pager` | [Tablas y paginación](tables.md) |
|
||||
| `PoweredBy` | Pie con el crédito «Funciona con PageTop» |
|
||||
|
||||
## Contenedores
|
||||
|
||||
`Container` agrupa varios componentes. Elige la etiqueta con el constructor:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Container {
|
||||
Container::section()
|
||||
.with_id("team")
|
||||
.with_child(Html::with(|_| html! { h2 { "The team" } }))
|
||||
.with_child(Block::new().with_title(Lc::n("Ana")))
|
||||
.with_child(Block::new().with_title(Lc::n("Luke")))
|
||||
# }
|
||||
```
|
||||
|
||||
`Container::new()` genera un `<div>`; también están `header()`, `main()`, `section()`,
|
||||
`article()` y `footer()`.
|
||||
|
||||
## Botones
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Vec<Button> { vec![
|
||||
// A link that looks like a button.
|
||||
Button::anchor(Lc::n("See the catalog"), "/catalog"),
|
||||
// A form submit button, with style and intent.
|
||||
Button::submit(Lc::n("Save"))
|
||||
.with_style(button::Style::Solid(Intent::Success))
|
||||
.with_size(button::Size::Large),
|
||||
// An outline button, disabled.
|
||||
Button::plain(Lc::n("Delete"))
|
||||
.with_style(button::Style::Outline(Intent::Severe))
|
||||
.with_disabled(true),
|
||||
# ] }
|
||||
```
|
||||
|
||||
## Intenciones
|
||||
|
||||
Muchos componentes reciben una `Intent`: el **significado** del color, no el color. El tema decide
|
||||
cómo se ve cada una.
|
||||
|
||||
| `Intent` | Significado |
|
||||
|---|---|
|
||||
| `Primary` | Acción principal |
|
||||
| `Neutral` | Sin énfasis |
|
||||
| `Info` | Información |
|
||||
| `Success` | Éxito o confirmación |
|
||||
| `Warning` | Advertencia |
|
||||
| `Severe` | Error o acción peligrosa |
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Vec<Badge> { vec![
|
||||
Badge::success(Lc::n("Active")),
|
||||
Badge::warning(Lc::n("Pending")),
|
||||
Badge::neutral(Lc::n("Archived")),
|
||||
# ] }
|
||||
```
|
||||
|
||||
## Imágenes
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Image {
|
||||
Image::with(image::Source::responsive("/static/img/cover.jpg"))
|
||||
.with_alternative(Lc::n("View of the harbour at dawn"))
|
||||
# }
|
||||
```
|
||||
|
||||
El origen (`image::Source`) decide cómo se muestra: `plain()` a su tamaño, `responsive()` ajustada
|
||||
al ancho disponible y `thumbnail()` como miniatura.
|
||||
|
||||
## Identificadores, clases y estilos
|
||||
|
||||
Todos los componentes aceptan `with_id()` y `with_prop()`. Con `PropsOp` añades clases, atributos
|
||||
o estilos sin tocar el componente:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Block {
|
||||
Block::new()
|
||||
.with_id("featured")
|
||||
.with_prop(PropsOp::add_classes("block-highlight shadow"))
|
||||
.with_prop(PropsOp::set("data-section", "home"))
|
||||
.with_prop(PropsOp::add_style("border-radius", "8px"))
|
||||
# }
|
||||
```
|
||||
|
||||
Para márgenes y rellenos hay tipos propios, `Margin` y `Padding`, con unidades tipadas:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Block {
|
||||
Block::new()
|
||||
.with_prop(Margin::new().with_bottom(UnitValue::RelRem(2.0)))
|
||||
.with_prop(Padding::new().with_all(UnitValue::Px(16)))
|
||||
# }
|
||||
```
|
||||
|
||||
## Mensajes al usuario
|
||||
|
||||
`Page` acumula avisos en su contexto y el componente `Messages` los muestra:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
async fn saved(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
let mut page = Page::new(request).with_child(Messages::new());
|
||||
page.context()
|
||||
.push_message(MessageLevel::Info, Lc::n("Your changes have been saved."));
|
||||
page.render().await
|
||||
}
|
||||
```
|
||||
|
||||
## Una portada en un minuto
|
||||
|
||||
`Intro` monta una página de presentación con un solo componente:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
async fn landing(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_child(
|
||||
Intro::custom()
|
||||
.with_title(Lc::n("Urban Garden"))
|
||||
.with_slogan(Lc::n("Grow your city"))
|
||||
.with_button(Some((Lc::n("Start here"), Route::from("/guide"))))
|
||||
.with_child(
|
||||
Block::new()
|
||||
.with_title(Lc::n("What is it?"))
|
||||
.with_child(Html::with(|_| html! { p { "A network of community gardens." } })),
|
||||
),
|
||||
)
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
```
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Crear un componente](custom-components.md), cuando ninguno encaja.
|
||||
- [Maquetar con Flex y Grid](layout.md).
|
||||
- [Catálogo de componentes](../reference/components.md).
|
||||
160
doc/v0.6/es/src/how-to/configuration.md
Normal file
160
doc/v0.6/es/src/how-to/configuration.md
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
# Configurar la aplicación
|
||||
|
||||
**Objetivo:** ajustar la aplicación con archivos TOML, distintos por entorno y sin recompilar, y
|
||||
dar a tu extensión sus propios ajustes, validados al arrancar.
|
||||
|
||||
La configuración vive en archivos [TOML](https://toml.io) dentro del directorio `config/`, junto
|
||||
al `Cargo.toml`. Cambiar un puerto o un idioma no requiere recompilar.
|
||||
|
||||
## 1. Entiende la cascada de archivos
|
||||
|
||||
PageTop lee estos archivos, todos opcionales, en este orden. Cada uno sobrescribe a los anteriores
|
||||
**sólo** en las claves que define:
|
||||
|
||||
| Archivo | Para qué |
|
||||
|---|---|
|
||||
| `config/common.toml` | Ajustes comunes a todos los entornos |
|
||||
| `config/{mode}.toml` | Ajustes del modo de ejecución |
|
||||
| `config/local.{mode}.toml` | Ajustes locales de ese modo (no se versiona) |
|
||||
| `config/local.toml` | Ajustes locales para cualquier modo (no se versiona) |
|
||||
|
||||
El modo lo da la variable de entorno `PAGETOP_RUN_MODE` (`default` si no se define):
|
||||
|
||||
```sh
|
||||
PAGETOP_RUN_MODE=production ./my-app # reads common.toml, production.toml, ...
|
||||
```
|
||||
|
||||
Las variables de entorno **no** sobrescriben ajustes sueltos. Las únicas que se leen son
|
||||
`PAGETOP_RUN_MODE` y `CONFIG_DIR`, que cambia el directorio `config/`. Las contraseñas y demás
|
||||
secretos van en un `local.toml` que no se sube al repositorio.
|
||||
|
||||
## 2. Ajusta PageTop
|
||||
|
||||
Un `config/common.toml` típico:
|
||||
|
||||
```toml
|
||||
[app]
|
||||
name = "Urban Garden"
|
||||
theme = "Bootsier"
|
||||
language = "es-ES"
|
||||
timezone = "Europe/Madrid"
|
||||
|
||||
[server]
|
||||
bind_address = "0.0.0.0"
|
||||
bind_port = 8080
|
||||
|
||||
[log]
|
||||
tracing = "Info"
|
||||
rolling = "Daily"
|
||||
```
|
||||
|
||||
| Sección | Claves principales |
|
||||
|---|---|
|
||||
| `[app]` | `name`, `theme` (por defecto `"Basic"`), `language`, `lang_negotiation`, `timezone`, `startup_banner` |
|
||||
| `[server]` | `bind_address` (por defecto `"localhost"`), `bind_port` (por defecto `8080`) |
|
||||
| `[log]` | `enabled`, `tracing`, `rolling`, `path`, `prefix`, `format` |
|
||||
| `[dev]` | `pagetop_static_dir`, para servir los recursos de PageTop desde disco |
|
||||
|
||||
Todas las opciones, con su tipo y su valor por defecto, están en [Opciones de
|
||||
configuración](../reference/configuration.md).
|
||||
|
||||
## 3. Léelos desde el código
|
||||
|
||||
Los ajustes de PageTop se leen en `global::SETTINGS`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() {
|
||||
let name = &global::SETTINGS.app.name;
|
||||
let port = global::SETTINGS.server.bind_port;
|
||||
# }
|
||||
```
|
||||
|
||||
## 4. Errores que no pasan desapercibidos
|
||||
|
||||
Una **clave desconocida** (típicamente, una errata) o un **valor no válido** impiden arrancar la
|
||||
aplicación, con un mensaje que lo localiza: el archivo y la línea si el TOML está mal escrito, o la
|
||||
sección y la clave si el valor no es válido. Una sección que no corresponde a
|
||||
ninguna extensión se ignora, con un aviso al arrancar.
|
||||
|
||||
## 5. Ajustes de tu extensión
|
||||
|
||||
Cada extensión declara sus ajustes en una estructura con `#[settings]`, ligada a una **sección
|
||||
propia** del archivo. Los valores por defecto van en los campos:
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
|
||||
/// Settings of the `[blog]` section.
|
||||
pub static SETTINGS: LazySettings<BlogSettings> = LazySettings::new();
|
||||
|
||||
/// The **`[blog]`** section of the configuration.
|
||||
#[settings(section = "blog")]
|
||||
pub struct BlogSettings {
|
||||
/// Title of the blog.
|
||||
#[default = "My blog"]
|
||||
pub title: String,
|
||||
/// Posts per page.
|
||||
#[default = 10]
|
||||
pub page_size: u32,
|
||||
/// Optional footer text (no default value: `None`).
|
||||
pub footer: Option<String>,
|
||||
/// Comments, in the `[blog.comments]` subsection.
|
||||
pub comments: CommentsSettings,
|
||||
}
|
||||
|
||||
/// The **`[blog.comments]`** subsection.
|
||||
#[settings]
|
||||
pub struct CommentsSettings {
|
||||
/// Whether comments are allowed.
|
||||
#[default = true]
|
||||
pub enabled: bool,
|
||||
}
|
||||
```
|
||||
|
||||
La extensión los devuelve en `settings()` para que se carguen (y se validen) al arrancar:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# pub static SETTINGS: LazySettings<BlogSettings> = LazySettings::new();
|
||||
# #[settings(section = "blog")]
|
||||
# pub struct BlogSettings {
|
||||
# #[default = 10]
|
||||
# pub page_size: u32,
|
||||
# }
|
||||
pub struct Blog;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Blog {
|
||||
fn settings(&self) -> Option<&'static dyn LoadSettings> {
|
||||
Some(&SETTINGS)
|
||||
}
|
||||
}
|
||||
|
||||
fn posts_per_page() -> u32 {
|
||||
SETTINGS.page_size
|
||||
}
|
||||
```
|
||||
|
||||
Y en `config/common.toml`:
|
||||
|
||||
```toml
|
||||
[blog]
|
||||
title = "Garden diary"
|
||||
|
||||
[blog.comments]
|
||||
enabled = false
|
||||
```
|
||||
|
||||
Los ajustes son de **sólo lectura** mientras la aplicación está en marcha.
|
||||
|
||||
## Comprueba
|
||||
|
||||
Escribe mal una clave en `config/common.toml` (`bind_prot = 9000`) y arranca: la aplicación se
|
||||
detiene y señala la clave. Corrígela y arranca con `PAGETOP_RUN_MODE=production`: se leen además
|
||||
`production.toml` y `local.production.toml`, si existen.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Opciones de configuración](../reference/configuration.md): la referencia completa.
|
||||
- [Desplegar en producción](deployment.md): la configuración en el servidor.
|
||||
240
doc/v0.6/es/src/how-to/custom-components.md
Normal file
240
doc/v0.6/es/src/how-to/custom-components.md
Normal file
|
|
@ -0,0 +1,240 @@
|
|||
# Crear un componente
|
||||
|
||||
**Objetivo:** convertir un fragmento de interfaz que se repite en un componente propio: con sus
|
||||
datos, sus métodos `with_*()`, su HTML, sus hijos y sus estilos.
|
||||
|
||||
Antes de crear uno, mira el [catálogo de componentes](../reference/components.md): quizá ya existe.
|
||||
|
||||
## 1. El mínimo
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
|
||||
#[derive(AutoDefault, Clone, Debug)]
|
||||
pub struct Notice;
|
||||
|
||||
#[async_trait]
|
||||
impl Component for Notice {
|
||||
fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
|
||||
async fn prepare(&self, _cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
Ok(html! { p class="notice" { "Scheduled maintenance on Sunday." } })
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Tres requisitos:
|
||||
|
||||
- **`new()`** crea la instancia; lo habitual es devolver `Self::default()`.
|
||||
- **`prepare()`** devuelve el HTML. Es `async`, así que puede consultar una base de datos o un
|
||||
servicio externo.
|
||||
- **`Clone`** es obligatorio, aunque el compilador no lo exija directamente: sin él, el
|
||||
componente no podría clonarse para cada página.
|
||||
|
||||
Ya puedes usarlo como cualquier otro: `.with_child(Notice::new())`.
|
||||
|
||||
## 2. Datos y métodos `with_*()`
|
||||
|
||||
Lo normal es que un componente tenga datos. La receta de PageTop:
|
||||
|
||||
- Campos **privados**, con `Getters` para leerlos.
|
||||
- `AutoDefault` para los valores por defecto.
|
||||
- Métodos `with_*()` para configurarlo, en un bloque `impl` marcado con `#[builder_impl]`.
|
||||
- Los textos como `Lc`, para que se traduzcan al renderizar.
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
|
||||
#[derive(AutoDefault, Clone, Debug, Getters)]
|
||||
pub struct Card {
|
||||
/// Returns the title of the card.
|
||||
title: Lc,
|
||||
/// Returns the text of the card.
|
||||
text: Lc,
|
||||
/// Returns the link target, if any.
|
||||
link: Option<Route>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Component for Card {
|
||||
fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
Ok(html! {
|
||||
div class="card" {
|
||||
h3 class="card-title" { (self.title().using(cx)) }
|
||||
p class="card-text" { (self.text().using(cx)) }
|
||||
@if let Some(link) = self.link() {
|
||||
a href=(link.resolve(cx)) { "Read more" }
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[builder_impl]
|
||||
impl Card {
|
||||
/// Sets the title.
|
||||
pub fn with_title(mut self, title: Lc) -> Self {
|
||||
self.title = title;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the text.
|
||||
pub fn with_text(mut self, text: Lc) -> Self {
|
||||
self.text = text;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the link target.
|
||||
pub fn with_link(mut self, link: impl Into<Option<Route>>) -> Self {
|
||||
self.link = link.into();
|
||||
self
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Y se usa así:
|
||||
|
||||
```rust,ignore
|
||||
Card::new()
|
||||
.with_title(Lc::n("Rust"))
|
||||
.with_text(Lc::n("Fast, reliable and productive."))
|
||||
.with_link(Route::from("/rust"))
|
||||
```
|
||||
|
||||
`#[builder_impl]` genera, junto a cada `with_*()`, un método `alter_*()` que modifica la instancia
|
||||
por referencia (`&mut self`). Lo agradecerás cuando un tema o una acción quieran cambiar el
|
||||
componente. Para un método suelto, fuera de un bloque así, existe `#[builder_fn]`.
|
||||
|
||||
## 3. Prepara y pinta
|
||||
|
||||
Cuando una página se renderiza, cada componente pasa por estos pasos, siempre en este orden:
|
||||
|
||||
1. **`is_renderable(cx)`**: ¿se pinta? Si devuelve `false`, el componente desaparece.
|
||||
2. **`setup(&mut self, cx)`**: ajusta su estado antes de pintarse. Es síncrono.
|
||||
3. Las extensiones pueden intervenir con la acción `BeforeRender`.
|
||||
4. El **tema** puede ajustarlo o pintarlo a su manera; si no lo hace, se llama a
|
||||
**`prepare(&self, cx)`**.
|
||||
5. Las extensiones pueden reaccionar (`AfterRender`) o retocar el HTML final
|
||||
(`TransformMarkup`).
|
||||
|
||||
Un ejemplo con los tres métodos propios:
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
|
||||
#[derive(AutoDefault, Clone, Debug, Getters)]
|
||||
pub struct Counter {
|
||||
/// Returns the number of notices.
|
||||
#[getters(copy)]
|
||||
notices: u32,
|
||||
/// Returns the computed CSS classes.
|
||||
classes: String,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Component for Counter {
|
||||
fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
// Nothing is rendered without notices.
|
||||
fn is_renderable(&self, _cx: &Context) -> bool {
|
||||
self.notices() > 0
|
||||
}
|
||||
|
||||
// Computes the classes from the state, before rendering.
|
||||
fn setup(&mut self, _cx: &mut Context) {
|
||||
self.classes = if self.notices > 9 { "counter counter-full" } else { "counter" }.into();
|
||||
}
|
||||
|
||||
async fn prepare(&self, _cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
Ok(html! { span class=(self.classes()) { (self.notices()) } })
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
La regla de oro: **`setup()` prepara, `prepare()` pinta**. Las consultas a la base de datos y
|
||||
cualquier operación de entrada/salida van en `prepare()`, que es el único paso asíncrono.
|
||||
|
||||
## 4. Componentes que contienen componentes
|
||||
|
||||
Para aceptar hijos, guarda un `Children` y renderízalo dentro de `prepare()`:
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
|
||||
#[derive(AutoDefault, Clone, Debug, Getters)]
|
||||
pub struct Panel {
|
||||
/// Returns the child components.
|
||||
children: Children,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Component for Panel {
|
||||
fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
Ok(html! {
|
||||
div class="panel" { (self.children().render(cx).await) }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[builder_impl]
|
||||
impl Panel {
|
||||
/// Adds a child component.
|
||||
pub fn with_child(mut self, op: impl Into<ChildOp>) -> Self {
|
||||
self.children.alter_child(op.into());
|
||||
self
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> **Consejo:** nunca guardes `Markup` ya generado en un campo. Guarda el dato en bruto (`Lc`,
|
||||
> otro componente...) y conviértelo en HTML en `prepare()`. Así el componente se adapta al idioma
|
||||
> y al tema de cada petición.
|
||||
|
||||
## 5. Sus propios estilos
|
||||
|
||||
Un componente puede traer su hoja de estilos o su *script*. Los añade al contexto al renderizarse,
|
||||
así que sólo se cargan en las páginas que lo usan, y una sola vez aunque aparezca muchas veces:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# #[derive(AutoDefault, Clone, Debug)]
|
||||
# pub struct Card;
|
||||
#[async_trait]
|
||||
impl Component for Card {
|
||||
fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
cx.alter_assets(StyleSheet::from("/static/css/card.css").with_version("1.0"));
|
||||
Ok(html! { div class="card" { "..." } })
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Cómo publicar ese archivo se explica en [Servir recursos estáticos](assets.md). Usa clases propias
|
||||
con el prefijo del componente (`card-title`, `card-text`...) para no chocar con las del tema.
|
||||
|
||||
## Comprueba
|
||||
|
||||
Usa el componente en una página y renderízala: si te falta `Clone` o un método obligatorio, no
|
||||
compila. Para comprobar su HTML sin servidor, mira [Probar rutas y
|
||||
componentes](testing.md#3-prueba-un-componente-suelto).
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Componentes, temas y renderizado](../explanation/rendering.md): el ciclo completo, con las
|
||||
acciones y el tema.
|
||||
- [Intervenir con acciones](actions.md): cómo otra extensión puede retocar tu componente.
|
||||
813
doc/v0.6/es/src/how-to/database.md
Normal file
813
doc/v0.6/es/src/how-to/database.md
Normal file
|
|
@ -0,0 +1,813 @@
|
|||
# Conectar una base de datos
|
||||
|
||||
**Objetivo:** conectar la aplicación a PostgreSQL, MySQL o SQLite con `pagetop-seaorm`, mantener el
|
||||
esquema con migraciones, consultar los datos con entidades tipadas, relacionar tablas y escribir
|
||||
SQL cuando haga falta.
|
||||
|
||||
El tutorial [Guarda las tareas en una base de datos](../tutorials/database.md) recorre un caso
|
||||
completo paso a paso. Esta guía reúne lo que necesitarás después.
|
||||
|
||||
## 1. Elige el motor
|
||||
|
||||
En una **aplicación**, activa el motor con una *feature* de `pagetop-seaorm`. Declararlas como
|
||||
*features* propias te permite cambiar de motor al compilar:
|
||||
|
||||
```toml
|
||||
[features]
|
||||
default = ["postgres"]
|
||||
postgres = ["pagetop-seaorm/postgres"]
|
||||
mysql = ["pagetop-seaorm/mysql"]
|
||||
sqlite = ["pagetop-seaorm/sqlite"]
|
||||
|
||||
[dependencies]
|
||||
pagetop-seaorm = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
||||
```
|
||||
|
||||
En una **extensión**, declara la dependencia sin *features*: el motor lo elige la aplicación que la
|
||||
use, y Cargo lo activa para todo el árbol de dependencias.
|
||||
|
||||
## 2. Configura la conexión
|
||||
|
||||
La sección `[database]` describe la conexión. Lo que cambia entre motores:
|
||||
|
||||
```toml
|
||||
# PostgreSQL (port 5432 by default)
|
||||
[database]
|
||||
db_type = "postgres"
|
||||
db_name = "garden"
|
||||
db_user = "garden"
|
||||
db_host = "localhost"
|
||||
```
|
||||
|
||||
```toml
|
||||
# MySQL or MariaDB (port 3306 by default)
|
||||
[database]
|
||||
db_type = "mysql"
|
||||
db_name = "garden"
|
||||
db_user = "garden"
|
||||
db_host = "localhost"
|
||||
```
|
||||
|
||||
```toml
|
||||
# SQLite: db_name is the file; mode=rwc creates it if it does not exist
|
||||
[database]
|
||||
db_type = "sqlite"
|
||||
db_name = "garden.db?mode=rwc"
|
||||
```
|
||||
|
||||
La contraseña, `db_pass`, va en `config/local.toml`, que no se sube al repositorio. `db_port` fija
|
||||
otro puerto y `max_pool_size` el número máximo de conexiones simultáneas (5 por defecto).
|
||||
|
||||
Declara la extensión como dependencia de la tuya. Al arrancar, abre el *pool* de conexiones antes
|
||||
de inicializar tu extensión; si no puede conectar, la aplicación no arranca y explica por qué.
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
pub struct Garden;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Garden {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_seaorm::SeaORM]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 3. Escribe las migraciones
|
||||
|
||||
Cada migración es un módulo dentro de `migration/`, con un nombre que empieza por la fecha para que
|
||||
el orden sea el cronológico:
|
||||
|
||||
```text
|
||||
src/
|
||||
├── lib.rs
|
||||
└── migration/
|
||||
├── m20261015_000001_create_plots.rs
|
||||
└── m20261101_000002_add_plot_notes.rs
|
||||
```
|
||||
|
||||
Una crea la tabla y un índice:
|
||||
|
||||
```rust,no_run
|
||||
// src/migration/m20261015_000001_create_plots.rs
|
||||
use pagetop_seaorm::migration::*;
|
||||
|
||||
pub struct Migration;
|
||||
|
||||
#[pagetop::async_trait]
|
||||
impl MigrationTrait for Migration {
|
||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
table_auto(Plots::Table)
|
||||
.col(pk_auto(Plots::Id))
|
||||
.col(string_uniq(Plots::Name))
|
||||
.col(string(Plots::Holder))
|
||||
.col(integer(Plots::Area))
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
manager
|
||||
.create_index(
|
||||
Index::create()
|
||||
.name("idx_plots_holder")
|
||||
.table(Plots::Table)
|
||||
.col(Plots::Holder)
|
||||
.to_owned(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(Plots::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
enum Plots {
|
||||
Table,
|
||||
Id,
|
||||
Name,
|
||||
Holder,
|
||||
Area,
|
||||
}
|
||||
```
|
||||
|
||||
Y otra, más adelante, añade una columna opcional:
|
||||
|
||||
```rust,no_run
|
||||
// src/migration/m20261101_000002_add_plot_notes.rs
|
||||
use pagetop_seaorm::migration::*;
|
||||
|
||||
pub struct Migration;
|
||||
|
||||
#[pagetop::async_trait]
|
||||
impl MigrationTrait for Migration {
|
||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.alter_table(
|
||||
Table::alter()
|
||||
.table(Plots::Table)
|
||||
.add_column(text_null(Plots::Notes))
|
||||
.to_owned(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
enum Plots {
|
||||
Table,
|
||||
Notes,
|
||||
}
|
||||
```
|
||||
|
||||
Las funciones de columna siguen un patrón: `string()`, `integer()`, `boolean()`, `date()`... son
|
||||
obligatorias; con `_null` admiten nulos y con `_uniq` son únicas. `table_auto()` añade las columnas
|
||||
`created_at` y `updated_at`.
|
||||
|
||||
## 4. Aplícalas al arrancar
|
||||
|
||||
En `src/lib.rs`, declara el módulo y aplica las migraciones en `initialize()`, en orden:
|
||||
|
||||
```rust,ignore
|
||||
use pagetop::prelude::*;
|
||||
use pagetop_seaorm::install_migrations;
|
||||
|
||||
mod migration {
|
||||
pub mod m20261015_000001_create_plots;
|
||||
pub mod m20261101_000002_add_plot_notes;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Garden {
|
||||
// ...
|
||||
|
||||
async fn initialize(&self) -> Result<(), BoxError> {
|
||||
install_migrations!(
|
||||
m20261015_000001_create_plots,
|
||||
m20261101_000002_add_plot_notes,
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Cada migración aplicada queda anotada en la tabla `seaql_migrations`, así que en los arranques
|
||||
siguientes sólo se aplican las nuevas. Si una falla, la aplicación no arranca.
|
||||
|
||||
## 5. Define las entidades
|
||||
|
||||
Una entidad describe una fila. El *struct* se llama `Model` y sus campos son públicos; a partir de
|
||||
él, `DeriveEntityModel` genera `Entity`, `Column` y `ActiveModel`:
|
||||
|
||||
```rust,no_run
|
||||
// src/entity/plot.rs
|
||||
use pagetop_seaorm::db::*;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
||||
#[sea_orm(table_name = "plots")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key)]
|
||||
pub id: i32,
|
||||
pub name: String,
|
||||
pub holder: String,
|
||||
pub area: i32,
|
||||
pub notes: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
||||
pub enum Relation {}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
```
|
||||
|
||||
Una columna que admite nulos es un `Option` en la entidad.
|
||||
|
||||
## 6. Consulta los datos
|
||||
|
||||
Todas las consultas reciben el *pool* con `dbconn()`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop_seaorm::db::*;
|
||||
# mod plot {
|
||||
# use pagetop_seaorm::db::*;
|
||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
||||
# #[sea_orm(table_name = "plots")]
|
||||
# pub struct Model {
|
||||
# #[sea_orm(primary_key)]
|
||||
# pub id: i32,
|
||||
# pub name: String,
|
||||
# pub holder: String,
|
||||
# pub area: i32,
|
||||
# pub notes: Option<String>,
|
||||
# }
|
||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
||||
# pub enum Relation {}
|
||||
# impl ActiveModelBehavior for ActiveModel {}
|
||||
# }
|
||||
async fn examples() -> Result<(), DbErr> {
|
||||
// All of them, ordered.
|
||||
let plots = plot::Entity::find()
|
||||
.order_by_asc(plot::Column::Name)
|
||||
.all(dbconn())
|
||||
.await?;
|
||||
|
||||
// Filtered, and by primary key.
|
||||
let large = plot::Entity::find()
|
||||
.filter(plot::Column::Area.gte(20))
|
||||
.all(dbconn())
|
||||
.await?;
|
||||
let first = plot::Entity::find_by_id(1).one(dbconn()).await?;
|
||||
|
||||
// Insert.
|
||||
let added = plot::ActiveModel {
|
||||
name: Set("C3".into()),
|
||||
holder: Set("Marta".into()),
|
||||
area: Set(15),
|
||||
..Default::default()
|
||||
}
|
||||
.insert(dbconn())
|
||||
.await?;
|
||||
|
||||
// Update only some columns.
|
||||
let mut changed = added.into_active_model();
|
||||
changed.holder = Set("Luke".into());
|
||||
changed.update(dbconn()).await?;
|
||||
|
||||
// Delete.
|
||||
plot::Entity::delete_by_id(3).exec(dbconn()).await?;
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
Para un listado paginado, `paginate()` devuelve la página pedida con el total de elementos y de
|
||||
páginas, justo lo que necesita un [`Pager`](tables.md#3-pagina-el-listado):
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop_seaorm::db::*;
|
||||
# mod plot {
|
||||
# use pagetop_seaorm::db::*;
|
||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
||||
# #[sea_orm(table_name = "plots")]
|
||||
# pub struct Model {
|
||||
# #[sea_orm(primary_key)]
|
||||
# pub id: i32,
|
||||
# pub name: String,
|
||||
# }
|
||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
||||
# pub enum Relation {}
|
||||
# impl ActiveModelBehavior for ActiveModel {}
|
||||
# }
|
||||
# async fn f(page_number: u64) -> Result<(), DbErr> {
|
||||
let page = paginate(plot::Entity::find().order_by_asc(plot::Column::Name), page_number, 20).await?;
|
||||
// page.items, page.total, page.page, page.per_page, page.total_pages
|
||||
# Ok(())
|
||||
# }
|
||||
```
|
||||
|
||||
Y para varias operaciones que deben aplicarse todas o ninguna, una transacción. Si cualquiera de
|
||||
ellas falla, se deshacen todas: el intercambio de titulares nunca se queda a medias:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop_seaorm::db::*;
|
||||
# mod plot {
|
||||
# use pagetop_seaorm::db::*;
|
||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
||||
# #[sea_orm(table_name = "plots")]
|
||||
# pub struct Model {
|
||||
# #[sea_orm(primary_key)]
|
||||
# pub id: i32,
|
||||
# pub holder: String,
|
||||
# }
|
||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
||||
# pub enum Relation {}
|
||||
# impl ActiveModelBehavior for ActiveModel {}
|
||||
# }
|
||||
# async fn f() -> Result<(), DbErr> {
|
||||
// Swaps the holders of two plots.
|
||||
dbconn()
|
||||
.transaction::<_, (), DbErr>(|txn| {
|
||||
Box::pin(async move {
|
||||
plot::ActiveModel {
|
||||
id: Unchanged(1),
|
||||
holder: Set("Luke".into()),
|
||||
..Default::default()
|
||||
}
|
||||
.update(txn)
|
||||
.await?;
|
||||
plot::ActiveModel {
|
||||
id: Unchanged(2),
|
||||
holder: Set("Ana".into()),
|
||||
..Default::default()
|
||||
}
|
||||
.update(txn)
|
||||
.await?;
|
||||
Ok(())
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(flatten_txn_err)
|
||||
# }
|
||||
```
|
||||
|
||||
`flatten_txn_err` convierte el error de la transacción en un `DbErr` normal, para seguir usando
|
||||
`?`.
|
||||
|
||||
## 7. Relaciona tablas
|
||||
|
||||
Cada parcela da varias cosechas. La tabla `harvests` guarda el `id` de su parcela en `plot_id`, con
|
||||
una clave ajena que impide apuntar a una parcela que no existe y borra sus cosechas si se borra la
|
||||
parcela:
|
||||
|
||||
```rust,no_run
|
||||
// src/migration/m20261120_000003_create_harvests.rs
|
||||
use pagetop_seaorm::migration::*;
|
||||
|
||||
pub struct Migration;
|
||||
|
||||
#[pagetop::async_trait]
|
||||
impl MigrationTrait for Migration {
|
||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
table_auto(Harvests::Table)
|
||||
.col(pk_auto(Harvests::Id))
|
||||
.col(integer(Harvests::PlotId))
|
||||
.col(string(Harvests::Crop))
|
||||
.col(integer(Harvests::Kilos))
|
||||
.foreign_key(
|
||||
ForeignKey::create()
|
||||
.name("fk_harvests_plot")
|
||||
.from(Harvests::Table, Harvests::PlotId)
|
||||
.to(Plots::Table, Plots::Id)
|
||||
.on_delete(ForeignKeyAction::Cascade),
|
||||
)
|
||||
.to_owned(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
enum Harvests {
|
||||
Table,
|
||||
Id,
|
||||
PlotId,
|
||||
Crop,
|
||||
Kilos,
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
enum Plots {
|
||||
Table,
|
||||
Id,
|
||||
}
|
||||
```
|
||||
|
||||
La relación se declara en las dos entidades. La cosecha **pertenece a** una parcela (`belongs_to`),
|
||||
indicando qué columna apunta a cuál:
|
||||
|
||||
```rust,no_run
|
||||
# mod harvest {
|
||||
// src/entity/harvest.rs
|
||||
use pagetop_seaorm::db::*;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
||||
#[sea_orm(table_name = "harvests")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key)]
|
||||
pub id: i32,
|
||||
pub plot_id: i32,
|
||||
pub crop: String,
|
||||
pub kilos: i32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
||||
pub enum Relation {
|
||||
#[sea_orm(
|
||||
belongs_to = "super::plot::Entity",
|
||||
from = "Column::PlotId",
|
||||
to = "super::plot::Column::Id"
|
||||
)]
|
||||
Plot,
|
||||
}
|
||||
|
||||
impl Related<super::plot::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Plot.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
# }
|
||||
# mod plot {
|
||||
# use pagetop_seaorm::db::*;
|
||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
||||
# #[sea_orm(table_name = "plots")]
|
||||
# pub struct Model {
|
||||
# #[sea_orm(primary_key)]
|
||||
# pub id: i32,
|
||||
# }
|
||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
||||
# pub enum Relation {}
|
||||
# impl ActiveModelBehavior for ActiveModel {}
|
||||
# }
|
||||
```
|
||||
|
||||
Y la parcela **tiene muchas** cosechas (`has_many`). Su `Relation`, vacía hasta ahora, queda así:
|
||||
|
||||
```rust,ignore
|
||||
// src/entity/plot.rs
|
||||
#[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
||||
pub enum Relation {
|
||||
#[sea_orm(has_many = "super::harvest::Entity")]
|
||||
Harvests,
|
||||
}
|
||||
|
||||
impl Related<super::harvest::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Harvests.def()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Con las dos declaradas, puedes ir de una a otra sin escribir el `JOIN`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop_seaorm::db::*;
|
||||
# mod plot {
|
||||
# use pagetop_seaorm::db::*;
|
||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
||||
# #[sea_orm(table_name = "plots")]
|
||||
# pub struct Model {
|
||||
# #[sea_orm(primary_key)]
|
||||
# pub id: i32,
|
||||
# pub name: String,
|
||||
# }
|
||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
||||
# pub enum Relation {
|
||||
# #[sea_orm(has_many = "super::harvest::Entity")]
|
||||
# Harvests,
|
||||
# }
|
||||
# impl Related<super::harvest::Entity> for Entity {
|
||||
# fn to() -> RelationDef {
|
||||
# Relation::Harvests.def()
|
||||
# }
|
||||
# }
|
||||
# impl ActiveModelBehavior for ActiveModel {}
|
||||
# }
|
||||
# mod harvest {
|
||||
# use pagetop_seaorm::db::*;
|
||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
||||
# #[sea_orm(table_name = "harvests")]
|
||||
# pub struct Model {
|
||||
# #[sea_orm(primary_key)]
|
||||
# pub id: i32,
|
||||
# pub plot_id: i32,
|
||||
# pub crop: String,
|
||||
# pub kilos: i32,
|
||||
# }
|
||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
||||
# pub enum Relation {
|
||||
# #[sea_orm(
|
||||
# belongs_to = "super::plot::Entity",
|
||||
# from = "Column::PlotId",
|
||||
# to = "super::plot::Column::Id"
|
||||
# )]
|
||||
# Plot,
|
||||
# }
|
||||
# impl Related<super::plot::Entity> for Entity {
|
||||
# fn to() -> RelationDef {
|
||||
# Relation::Plot.def()
|
||||
# }
|
||||
# }
|
||||
# impl ActiveModelBehavior for ActiveModel {}
|
||||
# }
|
||||
# async fn f() -> Result<(), DbErr> {
|
||||
// Each harvest together with its plot, in a single query.
|
||||
let rows: Vec<(harvest::Model, Option<plot::Model>)> = harvest::Entity::find()
|
||||
.find_also_related(plot::Entity)
|
||||
.all(dbconn())
|
||||
.await?;
|
||||
|
||||
// The harvests of one plot.
|
||||
if let Some(plot) = plot::Entity::find_by_id(1).one(dbconn()).await? {
|
||||
let harvests = plot.find_related(harvest::Entity).all(dbconn()).await?;
|
||||
}
|
||||
# Ok(())
|
||||
# }
|
||||
# fn main() {}
|
||||
```
|
||||
|
||||
La parcela de `find_also_related()` es un `Option` porque, en general, la columna podría estar
|
||||
vacía; con una clave ajena obligatoria como esta, siempre llega.
|
||||
|
||||
## 8. Escribe SQL a mano
|
||||
|
||||
Para lo que no encaja en una entidad, como un total por grupos, construye la consulta con
|
||||
`db::query` y léela con `fetch_all()`. Cada fila llega sin tipo, y cada columna se extrae con
|
||||
`try_get()`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop_seaorm::db::*;
|
||||
use pagetop_seaorm::db::query::*;
|
||||
|
||||
# async fn f() -> Result<(), DbErr> {
|
||||
// Kilos by crop, the largest first.
|
||||
let stmt = Query::select()
|
||||
.column(Alias::new("crop"))
|
||||
.expr_as(Expr::col(Alias::new("kilos")).sum(), Alias::new("total"))
|
||||
.from(Alias::new("harvests"))
|
||||
.group_by_col(Alias::new("crop"))
|
||||
.order_by(Alias::new("total"), Order::Desc)
|
||||
.to_owned();
|
||||
|
||||
for row in fetch_all(&stmt).await? {
|
||||
let crop: String = row.try_get("", "crop")?;
|
||||
let total: i64 = row.try_get("", "total")?;
|
||||
println!("{crop}: {total} kg");
|
||||
}
|
||||
# Ok(())
|
||||
# }
|
||||
```
|
||||
|
||||
`fetch_one()` devuelve sólo la primera fila. Para modificar datos sin entidad, `execute()` recibe
|
||||
la sentencia como texto y devuelve cuántas filas ha cambiado:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop_seaorm::db::*;
|
||||
# async fn f() -> Result<(), DbErr> {
|
||||
let result = execute("DELETE FROM harvests WHERE kilos = 0").await?;
|
||||
println!("{} empty harvests removed", result.rows_affected());
|
||||
# Ok(())
|
||||
# }
|
||||
```
|
||||
|
||||
`execute()` envía el texto tal cual: **nunca** pegues en él datos que vengan del usuario, porque
|
||||
abrirías la puerta a la inyección de SQL. Con esos datos, usa las entidades o el constructor de
|
||||
consultas, que los escapan por ti.
|
||||
|
||||
## Comprueba
|
||||
|
||||
Una prueba con SQLite en memoria aplica las migraciones y verifica las consultas, sin tocar tu base
|
||||
de datos (ve [Usa otra configuración para las pruebas](testing.md#5-usa-otra-configuración-para-las-pruebas)):
|
||||
|
||||
```rust
|
||||
# use pagetop::prelude::*;
|
||||
# use pagetop_seaorm::db::*;
|
||||
# use pagetop_seaorm::install_migrations;
|
||||
# mod migration {
|
||||
# pub mod m20261015_000001_create_plots {
|
||||
# use pagetop_seaorm::migration::*;
|
||||
# pub struct Migration;
|
||||
# #[pagetop::async_trait]
|
||||
# impl MigrationTrait for Migration {
|
||||
# async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
# manager
|
||||
# .create_table(
|
||||
# table_auto(Plots::Table)
|
||||
# .col(pk_auto(Plots::Id))
|
||||
# .col(string_uniq(Plots::Name))
|
||||
# .col(string(Plots::Holder))
|
||||
# .col(integer(Plots::Area))
|
||||
# .to_owned(),
|
||||
# )
|
||||
# .await
|
||||
# }
|
||||
# }
|
||||
# #[derive(DeriveIden)]
|
||||
# enum Plots { Table, Id, Name, Holder, Area }
|
||||
# }
|
||||
# pub mod m20261101_000002_add_plot_notes {
|
||||
# use pagetop_seaorm::migration::*;
|
||||
# pub struct Migration;
|
||||
# #[pagetop::async_trait]
|
||||
# impl MigrationTrait for Migration {
|
||||
# async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
# manager
|
||||
# .alter_table(
|
||||
# Table::alter()
|
||||
# .table(Plots::Table)
|
||||
# .add_column(text_null(Plots::Notes))
|
||||
# .to_owned(),
|
||||
# )
|
||||
# .await
|
||||
# }
|
||||
# }
|
||||
# #[derive(DeriveIden)]
|
||||
# enum Plots { Table, Notes }
|
||||
# }
|
||||
# pub mod m20261120_000003_create_harvests {
|
||||
# use pagetop_seaorm::migration::*;
|
||||
# pub struct Migration;
|
||||
# #[pagetop::async_trait]
|
||||
# impl MigrationTrait for Migration {
|
||||
# async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
# manager
|
||||
# .create_table(
|
||||
# table_auto(Harvests::Table)
|
||||
# .col(pk_auto(Harvests::Id))
|
||||
# .col(integer(Harvests::PlotId))
|
||||
# .col(string(Harvests::Crop))
|
||||
# .col(integer(Harvests::Kilos))
|
||||
# .foreign_key(
|
||||
# ForeignKey::create()
|
||||
# .name("fk_harvests_plot")
|
||||
# .from(Harvests::Table, Harvests::PlotId)
|
||||
# .to(Plots::Table, Plots::Id)
|
||||
# .on_delete(ForeignKeyAction::Cascade),
|
||||
# )
|
||||
# .to_owned(),
|
||||
# )
|
||||
# .await
|
||||
# }
|
||||
# }
|
||||
# #[derive(DeriveIden)]
|
||||
# enum Harvests { Table, Id, PlotId, Crop, Kilos }
|
||||
# #[derive(DeriveIden)]
|
||||
# enum Plots { Table, Id }
|
||||
# }
|
||||
# }
|
||||
# mod plot {
|
||||
# use pagetop_seaorm::db::*;
|
||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
||||
# #[sea_orm(table_name = "plots")]
|
||||
# pub struct Model {
|
||||
# #[sea_orm(primary_key)]
|
||||
# pub id: i32,
|
||||
# pub name: String,
|
||||
# pub holder: String,
|
||||
# pub area: i32,
|
||||
# pub notes: Option<String>,
|
||||
# }
|
||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
||||
# pub enum Relation {
|
||||
# #[sea_orm(has_many = "super::harvest::Entity")]
|
||||
# Harvests,
|
||||
# }
|
||||
# impl Related<super::harvest::Entity> for Entity {
|
||||
# fn to() -> RelationDef {
|
||||
# Relation::Harvests.def()
|
||||
# }
|
||||
# }
|
||||
# impl ActiveModelBehavior for ActiveModel {}
|
||||
# }
|
||||
# mod harvest {
|
||||
# use pagetop_seaorm::db::*;
|
||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
||||
# #[sea_orm(table_name = "harvests")]
|
||||
# pub struct Model {
|
||||
# #[sea_orm(primary_key)]
|
||||
# pub id: i32,
|
||||
# pub plot_id: i32,
|
||||
# pub crop: String,
|
||||
# pub kilos: i32,
|
||||
# }
|
||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
||||
# pub enum Relation {
|
||||
# #[sea_orm(
|
||||
# belongs_to = "super::plot::Entity",
|
||||
# from = "Column::PlotId",
|
||||
# to = "super::plot::Column::Id"
|
||||
# )]
|
||||
# Plot,
|
||||
# }
|
||||
# impl Related<super::plot::Entity> for Entity {
|
||||
# fn to() -> RelationDef {
|
||||
# Relation::Plot.def()
|
||||
# }
|
||||
# }
|
||||
# impl ActiveModelBehavior for ActiveModel {}
|
||||
# }
|
||||
# pub struct Garden;
|
||||
# #[async_trait]
|
||||
# impl Extension for Garden {
|
||||
# fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
# vec![&pagetop_seaorm::SeaORM]
|
||||
# }
|
||||
# async fn initialize(&self) -> Result<(), BoxError> {
|
||||
# install_migrations!(
|
||||
# m20261015_000001_create_plots,
|
||||
# m20261101_000002_add_plot_notes,
|
||||
# m20261120_000003_create_harvests,
|
||||
# )?;
|
||||
# Ok(())
|
||||
# }
|
||||
# }
|
||||
# fn new_plot(name: &str, holder: &str, area: i32) -> plot::ActiveModel {
|
||||
# plot::ActiveModel {
|
||||
# name: Set(name.into()),
|
||||
# holder: Set(holder.into()),
|
||||
# area: Set(area),
|
||||
# ..Default::default()
|
||||
# }
|
||||
# }
|
||||
# fn new_harvest(plot_id: i32, crop: &str, kilos: i32) -> harvest::ActiveModel {
|
||||
# harvest::ActiveModel {
|
||||
# plot_id: Set(plot_id),
|
||||
# crop: Set(crop.into()),
|
||||
# kilos: Set(kilos),
|
||||
# ..Default::default()
|
||||
# }
|
||||
# }
|
||||
#[pagetop::test]
|
||||
async fn plots_and_harvests_are_stored_and_queried() {
|
||||
Application::prepare(&Garden).await;
|
||||
|
||||
for (name, holder, area) in [("A1", "Ana", 25), ("A2", "Luke", 12), ("B1", "Marta", 30)] {
|
||||
new_plot(name, holder, area).insert(dbconn()).await.unwrap();
|
||||
}
|
||||
|
||||
let large = plot::Entity::find()
|
||||
.filter(plot::Column::Area.gte(20))
|
||||
.count(dbconn())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(large, 2);
|
||||
|
||||
let page = paginate(plot::Entity::find().order_by_asc(plot::Column::Name), 2, 2)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!((page.total, page.total_pages), (3, 2));
|
||||
assert_eq!(page.items[0].name, "B1");
|
||||
assert_eq!(page.items[0].notes, None);
|
||||
|
||||
// Plot 1 (A1) gives two harvests and plot 3 (B1) one.
|
||||
for (plot_id, crop, kilos) in [(1, "Tomatoes", 12), (1, "Lettuces", 5), (3, "Tomatoes", 9)] {
|
||||
new_harvest(plot_id, crop, kilos).insert(dbconn()).await.unwrap();
|
||||
}
|
||||
|
||||
let a1 = plot::Entity::find_by_id(1).one(dbconn()).await.unwrap().unwrap();
|
||||
let harvests = a1.find_related(harvest::Entity).all(dbconn()).await.unwrap();
|
||||
assert_eq!(harvests.len(), 2);
|
||||
|
||||
let rows = harvest::Entity::find()
|
||||
.find_also_related(plot::Entity)
|
||||
.all(dbconn())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(rows.iter().all(|(_, plot)| plot.is_some()));
|
||||
|
||||
use pagetop_seaorm::db::query::*;
|
||||
let stmt = Query::select()
|
||||
.column(Alias::new("crop"))
|
||||
.expr_as(Expr::col(Alias::new("kilos")).sum(), Alias::new("total"))
|
||||
.from(Alias::new("harvests"))
|
||||
.group_by_col(Alias::new("crop"))
|
||||
.order_by(Alias::new("total"), Order::Desc)
|
||||
.to_owned();
|
||||
let first = &fetch_all(&stmt).await.unwrap()[0];
|
||||
let crop: String = first.try_get("", "crop").unwrap();
|
||||
let total: i64 = first.try_get("", "total").unwrap();
|
||||
assert_eq!((crop.as_str(), total), ("Tomatoes", 21));
|
||||
}
|
||||
```
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Añadir usuarios y permisos](users.md): `pagetop-user` guarda usuarios y sesiones en esta misma
|
||||
base de datos.
|
||||
- [Ordenar y paginar sin recargar](htmx-tables.md): un listado paginado con HTMX.
|
||||
133
doc/v0.6/es/src/how-to/deployment.md
Normal file
133
doc/v0.6/es/src/how-to/deployment.md
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
# Desplegar en producción
|
||||
|
||||
**Objetivo:** compilar la aplicación en modo optimizado y ponerla en marcha en un servidor, como
|
||||
servicio del sistema o en un contenedor, detrás de un proxy inverso con HTTPS.
|
||||
|
||||
## 1. Compila para producción
|
||||
|
||||
```sh
|
||||
cargo build --release
|
||||
```
|
||||
|
||||
Para un binario más pequeño y rápido, añade a tu `Cargo.toml`:
|
||||
|
||||
```toml
|
||||
[profile.release]
|
||||
opt-level = 3
|
||||
lto = "fat"
|
||||
codegen-units = 1
|
||||
strip = true
|
||||
```
|
||||
|
||||
El ejecutable de `target/release/` incluye estilos, *scripts*, imágenes y traducciones. Sólo
|
||||
necesita, a su lado, el directorio `config/`.
|
||||
|
||||
## 2. Ponla en marcha
|
||||
|
||||
```text
|
||||
/opt/my-app/
|
||||
├── my-app <- the binary
|
||||
└── config/
|
||||
├── common.toml
|
||||
├── production.toml
|
||||
└── local.production.toml <- secrets of this server
|
||||
```
|
||||
|
||||
```sh
|
||||
cd /opt/my-app
|
||||
PAGETOP_RUN_MODE=production ./my-app
|
||||
```
|
||||
|
||||
O, desde cualquier directorio, indicando dónde está la configuración:
|
||||
|
||||
```sh
|
||||
CONFIG_DIR=/opt/my-app/config PAGETOP_RUN_MODE=production /opt/my-app/my-app
|
||||
```
|
||||
|
||||
Recuerda que, por defecto, el servidor sólo escucha en `localhost`. Para aceptar conexiones de
|
||||
fuera, o de un proxy en otro equipo, fija `bind_address = "0.0.0.0"` en `[server]`.
|
||||
|
||||
## 3. Como servicio del sistema
|
||||
|
||||
PageTop se detiene de forma ordenada con `SIGTERM`, la señal que envían `systemd` o Docker: deja de
|
||||
aceptar conexiones, termina las peticiones en curso y vuelca las trazas pendientes. Una unidad de
|
||||
`systemd` sencilla:
|
||||
|
||||
```ini
|
||||
[Unit]
|
||||
Description=My PageTop application
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
WorkingDirectory=/opt/my-app
|
||||
Environment=PAGETOP_RUN_MODE=production
|
||||
ExecStart=/opt/my-app/my-app
|
||||
Restart=on-failure
|
||||
User=my-app
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
|
||||
## 4. En un contenedor
|
||||
|
||||
El binario no necesita nada a su lado salvo `config/`, así que la imagen final puede ser mínima. Un
|
||||
`Dockerfile` en dos fases, que compila en una imagen de Rust y copia sólo el resultado:
|
||||
|
||||
```dockerfile
|
||||
FROM rust:1.88 AS build
|
||||
WORKDIR /src
|
||||
COPY . .
|
||||
RUN cargo build --release
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
WORKDIR /app
|
||||
COPY --from=build /src/target/release/my-app /app/my-app
|
||||
COPY config /app/config
|
||||
ENV PAGETOP_RUN_MODE=production
|
||||
EXPOSE 8080
|
||||
CMD ["/app/my-app"]
|
||||
```
|
||||
|
||||
Dentro del contenedor, el servidor debe escuchar en todas las interfaces: pon
|
||||
`bind_address = "0.0.0.0"` en `config/production.toml`. Docker detiene los contenedores con
|
||||
`SIGTERM`, que PageTop atiende cerrando de forma ordenada.
|
||||
|
||||
## 5. Detrás de un proxy inverso
|
||||
|
||||
Para HTTPS, certificados y compresión, pon delante un proxy inverso como nginx o Caddy. Un ejemplo
|
||||
con nginx:
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen 443 ssl;
|
||||
server_name my-app.example.com;
|
||||
|
||||
# ssl_certificate ... ssl_certificate_key ...
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:8080;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Con el proxy delante, deja `bind_address = "localhost"` (el valor por defecto): así sólo el proxy
|
||||
llega a la aplicación.
|
||||
|
||||
## Comprueba
|
||||
|
||||
```sh
|
||||
curl -I https://my-app.example.com/
|
||||
```
|
||||
|
||||
Responde `200` a través del proxy. En el servidor, `systemctl status my-app` (o `docker logs`)
|
||||
muestra las trazas de arranque, y `systemctl stop my-app` detiene la aplicación sin cortar las
|
||||
peticiones en curso.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Registrar trazas](logging.md): trazas en archivos con rotación.
|
||||
- [Opciones de configuración](../reference/configuration.md).
|
||||
286
doc/v0.6/es/src/how-to/error-pages.md
Normal file
286
doc/v0.6/es/src/how-to/error-pages.md
Normal file
|
|
@ -0,0 +1,286 @@
|
|||
# Mostrar páginas de error
|
||||
|
||||
**Objetivo:** responder con una página de error cuando algo no sale bien (un recurso que no existe,
|
||||
un acceso no permitido, un fallo al leer los datos) sin que el visitante pierda la navegación del
|
||||
sitio, responder con JSON cuando quien llama es una API, y saber qué ocurre cuando el fallo es
|
||||
grave.
|
||||
|
||||
Las cosas fallan: alguien escribe mal una dirección, un archivo desaparece o la base de datos no
|
||||
responde. PageTop distingue dos niveles. Los **errores controlados** los decide tu código y se
|
||||
muestran como una página más del sitio, con su cabecera, su menú y su pie. Los **fallos graves**
|
||||
(un `panic!`) los atrapa PageTop y responde con una página mínima. Esta guía recorre los dos.
|
||||
|
||||
## 1. Devuelve el error desde el *handler*
|
||||
|
||||
Un *handler* que construye una página devuelve `Result<Markup, ErrorPage>`. Para responder con un
|
||||
error, devuelve la variante que corresponda:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
const PLOTS: [(&str, &str); 2] = [("a1", "Ana"), ("b2", "Luke")];
|
||||
|
||||
async fn plot(
|
||||
request: HttpRequest,
|
||||
web::Path(code): web::Path<String>,
|
||||
) -> Result<Markup, ErrorPage> {
|
||||
let Some((_, holder)) = PLOTS.iter().find(|(c, _)| *c == code) else {
|
||||
return Err(ErrorPage::NotFound(Some(request)));
|
||||
};
|
||||
let holder = holder.to_string();
|
||||
Page::new(request)
|
||||
.with_title(Lc::n(code))
|
||||
.with_child(Html::with(move |_| html! { p { "Holder: " (holder) } }))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
```
|
||||
|
||||
`/plots/a1` muestra la parcela y `/plots/z9` responde con un 404 que conserva el aspecto del sitio.
|
||||
Elige la variante por lo que ha pasado:
|
||||
|
||||
| Variante | Código | Cuándo |
|
||||
|---|---|---|
|
||||
| `ErrorPage::BadRequest` | 400 | Los datos de la petición no tienen sentido |
|
||||
| `ErrorPage::AccessDenied` | 403 | El usuario no tiene permiso para verlo |
|
||||
| `ErrorPage::NotFound` | 404 | Lo que se pide no existe |
|
||||
| `ErrorPage::InternalError` | 500 | Algo ha fallado en el servidor |
|
||||
| `ErrorPage::ServiceUnavailable` | 503 | El servicio no puede atender ahora (mantenimiento, carga) |
|
||||
| `ErrorPage::GatewayTimeout` | 504 | Un servicio externo no ha respondido a tiempo |
|
||||
|
||||
Pásale siempre la petición (`Some(request)`): con ella la página de error sale en el idioma del
|
||||
visitante y sabe quién es, por ejemplo para mostrar su menú de cuenta. Con `None` también se
|
||||
muestra, pero sin esos datos.
|
||||
|
||||
Las rutas que no existen no necesitan nada: PageTop responde por sí solo con la misma página 404.
|
||||
|
||||
## 2. Convierte tus errores en un `ErrorPage`
|
||||
|
||||
Lo normal es que el error venga de otra parte: un archivo que no se puede leer, una consulta que
|
||||
falla. Conviértelo con `map_err()` y sigue usando `?`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
async fn report(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
let text = std::fs::read_to_string("data/report.txt").map_err(|err| {
|
||||
trace::error!(%err, "Cannot read the report");
|
||||
ErrorPage::InternalError(Some(request.clone()))
|
||||
})?;
|
||||
|
||||
Page::new(request)
|
||||
.with_child(Html::with(move |_| html! { pre { (text) } }))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
```
|
||||
|
||||
Clonar la petición es barato, así que no te preocupes por el `request.clone()`.
|
||||
|
||||
## 3. Guarda los detalles en el registro, no en la página
|
||||
|
||||
La página de error **nunca** muestra el motivo del fallo: dice qué ha pasado en términos que
|
||||
entiende el visitante («se ha producido un error interno») y nada más. Es deliberado: un mensaje
|
||||
de la base de datos o una ruta de un archivo darían pistas a quien no debe tenerlas.
|
||||
|
||||
Los detalles van al registro, como en el ejemplo anterior con `trace::error!`. Allí los encontrarás
|
||||
cuando tengas que averiguar qué ocurrió (ve [Registrar trazas](logging.md)).
|
||||
|
||||
## 4. Cambia su contenido desde el tema
|
||||
|
||||
Los textos de las páginas de error vienen traducidos de serie. Si quieres otro contenido, por
|
||||
ejemplo una página 404 con un enlace a la portada, el tema activo puede sustituirlo con
|
||||
`error_403()`, `error_404()` y `error_fatal()` (este último para 400, 500, 503 y 504). Lo explica
|
||||
[Crear un tema](themes.md#6-cambia-las-páginas-de-error).
|
||||
|
||||
## 5. Ten en cuenta HTMX
|
||||
|
||||
Si la petición la hace HTMX, recuerda que HTMX **no sustituye** el contenido cuando la respuesta es
|
||||
un 4xx o un 5xx: el usuario no vería nada. Para avisar de un error en un fragmento, responde con un
|
||||
200 y el mensaje, o cambia el destino con `HtmxResponse` (ve [Dirigir al navegador desde el
|
||||
servidor](htmx-responses.md)).
|
||||
|
||||
## 6. Los fallos graves
|
||||
|
||||
Un `panic!` en un *handler*, un componente o el tema no tumba el servidor. PageTop lo atrapa,
|
||||
anota el motivo en el registro y responde con un 500 y una página mínima, sin tema ni componentes:
|
||||
después de un fallo así no es seguro volver a usar el mismo ciclo de renderizado que acaba de
|
||||
fallar.
|
||||
|
||||
```rust,no_run
|
||||
async fn boom() -> &'static str {
|
||||
panic!("This should never happen");
|
||||
}
|
||||
```
|
||||
|
||||
Es la red de seguridad, no una forma de gestionar errores: reserva `panic!` para lo que de verdad
|
||||
no puede ocurrir y devuelve un `ErrorPage` en todo lo demás.
|
||||
|
||||
## 7. Errores de una API JSON
|
||||
|
||||
Una ruta que devuelve JSON no debe responder a un error con una página HTML: quien la llama es un
|
||||
programa, y espera JSON. Define un tipo de error con [`thiserror`](https://docs.rs/thiserror),
|
||||
decide en `IntoResponse` el código de cada variante y devuelve el mensaje en un cuerpo JSON:
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum ApiError {
|
||||
#[error("Plot {0} not found")]
|
||||
PlotNotFound(String),
|
||||
#[error("The harvest must weigh more than zero kilos")]
|
||||
InvalidKilos,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct ErrorBody {
|
||||
status: u16,
|
||||
error: String,
|
||||
}
|
||||
|
||||
impl web::IntoResponse for ApiError {
|
||||
fn into_response(self) -> Response {
|
||||
let status = match self {
|
||||
Self::PlotNotFound(_) => web::http::StatusCode::NOT_FOUND,
|
||||
Self::InvalidKilos => web::http::StatusCode::UNPROCESSABLE_ENTITY,
|
||||
};
|
||||
let body = ErrorBody { status: status.as_u16(), error: self.to_string() };
|
||||
(status, Json(body)).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Plot {
|
||||
code: String,
|
||||
holder: &'static str,
|
||||
}
|
||||
|
||||
async fn api_plot(web::Path(code): web::Path<String>) -> Result<Json<Plot>, ApiError> {
|
||||
match code.as_str() {
|
||||
"a1" => Ok(Json(Plot { code, holder: "Ana" })),
|
||||
_ => Err(ApiError::PlotNotFound(code)),
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`/api/plots/z9` responde con un 404 y `{"status":404,"error":"Plot z9 not found"}`. Como el tipo
|
||||
implementa `IntoResponse`, el *handler* sigue usando `?` con normalidad.
|
||||
|
||||
Aquí los mensajes son para quien usa la API, así que se envían tal cual. Un error interno (una
|
||||
consulta que falla) es otra cosa: regístralo con `trace::error!` y responde con un 500 y un mensaje
|
||||
genérico, igual que haría una página de error.
|
||||
|
||||
## El ejemplo completo
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
|
||||
const PLOTS: [(&str, &str); 2] = [("a1", "Ana"), ("b2", "Luke")];
|
||||
|
||||
struct Garden;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Garden {
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router
|
||||
.route("/plots/{code}", web::get(plot))
|
||||
.route("/report", web::get(report))
|
||||
.route("/boom", web::get(boom))
|
||||
}
|
||||
}
|
||||
|
||||
async fn plot(
|
||||
request: HttpRequest,
|
||||
web::Path(code): web::Path<String>,
|
||||
) -> Result<Markup, ErrorPage> {
|
||||
let Some((_, holder)) = PLOTS.iter().find(|(c, _)| *c == code) else {
|
||||
return Err(ErrorPage::NotFound(Some(request)));
|
||||
};
|
||||
let holder = holder.to_string();
|
||||
Page::new(request)
|
||||
.with_title(Lc::n(code))
|
||||
.with_child(Html::with(move |_| html! { p { "Holder: " (holder) } }))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
async fn report(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
let text = std::fs::read_to_string("data/report.txt").map_err(|err| {
|
||||
trace::error!(%err, "Cannot read the report");
|
||||
ErrorPage::InternalError(Some(request.clone()))
|
||||
})?;
|
||||
|
||||
Page::new(request)
|
||||
.with_child(Html::with(move |_| html! { pre { (text) } }))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
async fn boom() -> &'static str {
|
||||
panic!("This should never happen");
|
||||
}
|
||||
|
||||
#[pagetop::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
Application::prepare(&Garden).await.run().await
|
||||
}
|
||||
```
|
||||
|
||||
## Comprueba
|
||||
|
||||
Arranca la aplicación con `cargo run` y prueba cada caso:
|
||||
|
||||
```sh
|
||||
curl -i http://localhost:8080/plots/a1 # 200 OK, the plot page
|
||||
curl -i http://localhost:8080/plots/z9 # 404 Not Found, with the site's error page
|
||||
curl -i http://localhost:8080/report # 500 until data/report.txt exists (reason in the log)
|
||||
curl -i http://localhost:8080/boom # 500 with the minimal page; the panic is in the log
|
||||
```
|
||||
|
||||
En el navegador, la 404 y la 500 tienen la cabecera y el pie del sitio; la de `/boom`, no.
|
||||
|
||||
También puedes comprobarlo en una prueba (ve [Probar rutas y componentes](testing.md)):
|
||||
|
||||
```rust
|
||||
# use pagetop::prelude::*;
|
||||
# const PLOTS: [(&str, &str); 2] = [("a1", "Ana"), ("b2", "Luke")];
|
||||
# struct Garden;
|
||||
# #[async_trait]
|
||||
# impl Extension for Garden {
|
||||
# fn configure_router(&self, router: Router) -> Router {
|
||||
# router.route("/plots/{code}", web::get(plot))
|
||||
# }
|
||||
# }
|
||||
# async fn plot(
|
||||
# request: HttpRequest,
|
||||
# web::Path(code): web::Path<String>,
|
||||
# ) -> Result<Markup, ErrorPage> {
|
||||
# let Some((_, holder)) = PLOTS.iter().find(|(c, _)| *c == code) else {
|
||||
# return Err(ErrorPage::NotFound(Some(request)));
|
||||
# };
|
||||
# let holder = holder.to_string();
|
||||
# Page::new(request)
|
||||
# .with_title(Lc::n(code))
|
||||
# .with_child(Html::with(move |_| html! { p { "Holder: " (holder) } }))
|
||||
# .render()
|
||||
# .await
|
||||
# }
|
||||
#[pagetop::test]
|
||||
async fn an_unknown_plot_shows_the_not_found_page() {
|
||||
let app = web::test::init_router(Application::prepare(&Garden).await.test());
|
||||
|
||||
let request = web::test::TestRequest::get().uri("/plots/z9").to_request();
|
||||
let response = web::test::send_request(&app, request).await;
|
||||
|
||||
assert_eq!(response.status(), web::http::StatusCode::NOT_FOUND);
|
||||
let body = web::test::read_body_text(response).await;
|
||||
assert!(body.contains("The requested page could not be found."));
|
||||
}
|
||||
```
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Crear un tema](themes.md#6-cambia-las-páginas-de-error): otro contenido para las páginas de
|
||||
error.
|
||||
- [Registrar trazas](logging.md): dónde acaban los detalles de cada fallo.
|
||||
- [Añadir usuarios y permisos](users.md): `AccessDenied` en acción.
|
||||
157
doc/v0.6/es/src/how-to/extensions.md
Normal file
157
doc/v0.6/es/src/how-to/extensions.md
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
# Crear una extensión
|
||||
|
||||
**Objetivo:** empaquetar una funcionalidad (rutas, componentes, ajustes, traducciones) en una
|
||||
extensión que cualquier aplicación pueda añadir con una línea.
|
||||
|
||||
Una extensión es una estructura que implementa `Extension`. Todos sus métodos son opcionales:
|
||||
sobrescribe sólo los que necesites.
|
||||
|
||||
| Método | Para qué |
|
||||
|---|---|
|
||||
| `name()`, `description()` | Nombre y descripción legibles (con `Lc`, traducibles) |
|
||||
| `dependencies()` | Extensiones que deben arrancar antes |
|
||||
| `settings()` | [Ajustes](configuration.md#5-ajustes-de-tu-extensión) que se cargan al arrancar |
|
||||
| `actions()` | [Acciones](actions.md) que registra |
|
||||
| `initialize()` | Código que se ejecuta al arrancar |
|
||||
| `configure_router()` | [Rutas](routes.md) |
|
||||
| `configure_middleware()` | Capas que envuelven las rutas de **todas** las extensiones |
|
||||
| `configure_static_files()` | [Recursos estáticos](assets.md) |
|
||||
| `theme()` | Si la extensión es un [tema](themes.md) |
|
||||
|
||||
## 1. Una extensión completa
|
||||
|
||||
Un pequeño blog: declara sus dependencias, añade un enlace al pie de todas las páginas y registra
|
||||
sus rutas.
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
|
||||
pub struct Blog;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Blog {
|
||||
fn name(&self) -> Lc {
|
||||
Lc::n("Blog")
|
||||
}
|
||||
|
||||
fn description(&self) -> Lc {
|
||||
Lc::n("Posts and news")
|
||||
}
|
||||
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_bootsier::Bootsier]
|
||||
}
|
||||
|
||||
async fn initialize(&self) -> Result<(), BoxError> {
|
||||
InRegion::Global(&CoreRegions::Footer)
|
||||
.add(Html::with(|cx| html! { a href=(cx.route("/blog")) { "Blog" } }));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router
|
||||
.route("/blog", web::get(index))
|
||||
.route("/blog/{slug}", web::get(post))
|
||||
}
|
||||
}
|
||||
|
||||
async fn index(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request).with_title(Lc::n("Blog")).render().await
|
||||
}
|
||||
|
||||
async fn post(
|
||||
request: HttpRequest,
|
||||
web::Path(slug): web::Path<String>,
|
||||
) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_child(Html::with(move |_| html! { h1 { (slug) } }))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
```
|
||||
|
||||
Para usarla, la aplicación sólo tiene que declararla como dependencia:
|
||||
|
||||
```rust,ignore
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&blog::Blog]
|
||||
}
|
||||
```
|
||||
|
||||
## 2. Declara sus dependencias
|
||||
|
||||
`dependencies()` construye el árbol de la aplicación. PageTop garantiza que cada dependencia está
|
||||
registrada e inicializada **antes** que la extensión que la declara. Es independiente de las
|
||||
dependencias de `Cargo.toml`, que sólo resuelven la compilación.
|
||||
|
||||
## 3. Inicialízala al arrancar
|
||||
|
||||
`initialize()` es `async`: puede conectar con una base de datos, aplicar migraciones o cargar
|
||||
datos. Si devuelve un error, la aplicación **no arranca**: PageTop muestra el error con sus
|
||||
causas y termina. Gracias a `BoxError`, puedes propagar cualquier error con `?`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
pub struct Catalog;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Catalog {
|
||||
async fn initialize(&self) -> Result<(), BoxError> {
|
||||
let data = std::fs::read_to_string("catalog.json")?;
|
||||
trace::info!("Catalog loaded: {} bytes", data.len());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 4. Pon componentes en todas las páginas
|
||||
|
||||
`InRegion` registra un componente una sola vez para que aparezca en todas las páginas:
|
||||
|
||||
| Variante | Dónde aparece |
|
||||
|---|---|
|
||||
| `InRegion::Content` | Región de contenido, en todas las páginas |
|
||||
| `InRegion::Global(®ion)` | La región indicada, con cualquier tema |
|
||||
| `InRegion::ForTheme(&theme, ®ion)` | La región indicada, sólo con ese tema |
|
||||
|
||||
Cada página recibe una **copia nueva** del componente. Si debe mostrarse sólo a veces (por
|
||||
ejemplo, a usuarios autenticados), haz que lo decida su `is_renderable()`.
|
||||
|
||||
## 5. Añade *middleware*
|
||||
|
||||
Las capas añadidas en `configure_middleware()` se aplican a las rutas de todas las extensiones,
|
||||
sin importar el orden. Así funciona, por ejemplo, la resolución de la sesión de usuario:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
async fn custom_header(request: web::Request, next: web::middleware::Next) -> Response {
|
||||
let mut response = next.run(request).await;
|
||||
response.headers_mut().insert("x-powered-by", web::http::HeaderValue::from_static("PageTop"));
|
||||
response
|
||||
}
|
||||
|
||||
pub struct Headers;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Headers {
|
||||
fn configure_middleware(&self, router: Router) -> Router {
|
||||
router.layer(web::middleware::from_fn(custom_header))
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Para una capa que sólo afecte a tus rutas, crea un `Router` propio en `configure_router()`, aplica
|
||||
la capa sobre él y únelo con `router.merge(...)`. Compresión, límites, tiempo máximo, CORS y el
|
||||
orden de las capas, en [Añadir *middleware*](middleware.md).
|
||||
|
||||
## Comprueba
|
||||
|
||||
Declara la extensión en `dependencies()` de tu aplicación y arranca: sus rutas responden y, si su
|
||||
`initialize()` falla, la aplicación no arranca y lo explica en el terminal.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Intervenir con acciones](actions.md): cómo una extensión modifica lo que hace otra.
|
||||
- [Configurar la aplicación](configuration.md#5-ajustes-de-tu-extensión): ajustes propios de la
|
||||
extensión.
|
||||
- [Arquitectura: del arranque a la respuesta](../explanation/architecture.md).
|
||||
186
doc/v0.6/es/src/how-to/forms.md
Normal file
186
doc/v0.6/es/src/how-to/forms.md
Normal file
|
|
@ -0,0 +1,186 @@
|
|||
# Crear y procesar formularios
|
||||
|
||||
**Objetivo:** construir un formulario accesible, recibir sus datos en el servidor, validarlos y
|
||||
responder sin que una recarga lo reenvíe.
|
||||
|
||||
## 1. Construye el formulario
|
||||
|
||||
Un formulario se construye con `Form` y sus campos, que generan el HTML accesible (etiquetas,
|
||||
textos de ayuda, atributos ARIA) por ti.
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
fn contact_form() -> Form {
|
||||
Form::new()
|
||||
.with_id("contact")
|
||||
.with_action("/contact")
|
||||
.with_method(form::Method::Post)
|
||||
.with_child(
|
||||
form::input::Field::text()
|
||||
.with_name("name")
|
||||
.with_label(Lc::n("Name"))
|
||||
.with_required(true),
|
||||
)
|
||||
.with_child(
|
||||
form::input::Field::email()
|
||||
.with_name("email")
|
||||
.with_label(Lc::n("Email"))
|
||||
.with_help_text(Lc::n("We will only use it to reply to you.")),
|
||||
)
|
||||
.with_child(
|
||||
form::Textarea::new()
|
||||
.with_name("message")
|
||||
.with_label(Lc::n("Message"))
|
||||
.with_rows(5),
|
||||
)
|
||||
.with_child(Button::submit(Lc::n("Send")))
|
||||
}
|
||||
```
|
||||
|
||||
## 2. Elige los campos
|
||||
|
||||
| Campo | Constructor |
|
||||
|---|---|
|
||||
| Texto, correo, URL, teléfono, búsqueda | `form::input::Field::text()`, `email()`, `url()`, `telephone()`, `search()` |
|
||||
| Contraseña | `form::input::Field::password()` |
|
||||
| Número | `form::Number::new()` con `with_min()`, `with_max()`, `with_step()` |
|
||||
| Rango | `form::Range::new()` |
|
||||
| Área de texto | `form::Textarea::new()` |
|
||||
| Casilla o interruptor | `form::Checkbox::check()`, `form::Checkbox::switch()` |
|
||||
| Grupo de casillas | `form::check::Field` con `form::check::Item` |
|
||||
| Opciones excluyentes | `form::radio::Field` con `form::radio::Item` |
|
||||
| Lista desplegable | `form::select::Field` con `form::select::Item` |
|
||||
| Fecha, hora, fecha y hora | `form::date::Field::date()`, `time()`, `datetime()` |
|
||||
| Campo oculto | `form::Hidden::field(name, value)` |
|
||||
| Idioma, tema, zona horaria | `form::SelectLanguage`, `form::SelectTheme`, `form::SelectTimezone` |
|
||||
|
||||
Agrupa campos relacionados con `form::Fieldset`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> form::Fieldset {
|
||||
form::Fieldset::new()
|
||||
.with_legend(Lc::n("Preferences"))
|
||||
.with_child(
|
||||
form::radio::Field::new()
|
||||
.with_name("frequency")
|
||||
.with_label(Lc::n("How often do you want news?"))
|
||||
.with_item(form::radio::Item::new("weekly", Lc::n("Every week")).with_checked(true))
|
||||
.with_item(form::radio::Item::new("monthly", Lc::n("Every month"))),
|
||||
)
|
||||
.with_child(
|
||||
form::select::Field::new()
|
||||
.with_name("country")
|
||||
.with_label(Lc::n("Country"))
|
||||
.with_item(form::select::Item::new("es", Lc::n("Spain")))
|
||||
.with_item(form::select::Item::new("mx", Lc::n("Mexico")))
|
||||
.with_item(form::select::Item::new("ar", Lc::n("Argentina"))),
|
||||
)
|
||||
.with_child(form::Checkbox::switch().with_name("alerts").with_label(Lc::n("Alert me")))
|
||||
# }
|
||||
```
|
||||
|
||||
## 3. Recibe y valida los datos
|
||||
|
||||
Atiende `GET` y `POST` en la misma ruta. El *handler* del envío recibe los campos con
|
||||
`web::Form`, siempre como **último** parámetro (consume el cuerpo de la petición):
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
use serde::Deserialize;
|
||||
|
||||
# fn contact_form() -> Form { Form::new() }
|
||||
pub struct Contact;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Contact {
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router.route("/contact", web::get(show).post(send))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ContactData {
|
||||
name: String,
|
||||
email: String,
|
||||
message: String,
|
||||
}
|
||||
|
||||
async fn show(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("Contact"))
|
||||
.with_child(Messages::new())
|
||||
.with_child(contact_form())
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
async fn send(
|
||||
request: HttpRequest,
|
||||
web::Form(data): web::Form<ContactData>,
|
||||
) -> Result<Response, ErrorPage> {
|
||||
if data.message.trim().is_empty() {
|
||||
// Shows the form again with a message.
|
||||
let mut page = Page::new(request)
|
||||
.with_child(Messages::new())
|
||||
.with_child(contact_form());
|
||||
page.context()
|
||||
.push_message(MessageLevel::Error, Lc::n("Please write a message."));
|
||||
return page.render().await.map(IntoResponse::into_response);
|
||||
}
|
||||
// ... save or send `data` ...
|
||||
Ok(Redirect::see_other("/contact/thanks"))
|
||||
}
|
||||
```
|
||||
|
||||
Tras guardar, redirige con `see_other()` (patrón *Post/Redirect/Get*): así, si el usuario recarga
|
||||
la página, no reenvía el formulario.
|
||||
|
||||
## 4. Campos con varios valores
|
||||
|
||||
`web::Form` no admite claves repetidas (`interest=rust&interest=web`), que es lo que envían un grupo
|
||||
de casillas o una lista de selección múltiple. Para ellas, lee el cuerpo en bruto con
|
||||
`web::RawForm` y deserialízalo con [`serde_qs`](https://docs.rs/serde_qs):
|
||||
|
||||
```rust,ignore
|
||||
#[derive(Deserialize)]
|
||||
struct Interests {
|
||||
#[serde(default)]
|
||||
interest: Vec<String>,
|
||||
}
|
||||
|
||||
async fn save(request: HttpRequest, web::RawForm(body): web::RawForm) -> Response {
|
||||
let data: Interests = serde_qs::from_bytes(&body).unwrap_or(Interests { interest: vec![] });
|
||||
// ...
|
||||
# todo!()
|
||||
}
|
||||
```
|
||||
|
||||
## 5. Fechas en el idioma del usuario
|
||||
|
||||
`form::date::Field` muestra y lee las fechas con el formato del idioma activo (`dd/mm/aaaa` en
|
||||
español). Para interpretar el texto recibido, usa los métodos del contexto:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
fn read_date(cx: &Context, text: &str) {
|
||||
match cx.parse_date(text) {
|
||||
Ok(Some(date)) => { /* a valid date: a `NaiveDate` */ }
|
||||
Ok(None) => { /* empty field */ }
|
||||
Err(_) => { /* invalid format */ }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Comprueba
|
||||
|
||||
1. Envía el formulario vacío: el navegador lo impide, porque `name` es obligatorio.
|
||||
2. Envía un mensaje en blanco (sólo espacios): el servidor lo rechaza y el formulario vuelve con el
|
||||
aviso.
|
||||
3. Envía uno correcto y recarga la página de destino: el navegador no ofrece reenviar el
|
||||
formulario.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Validar un campo al vuelo](htmx-validation.md): los mismos errores, sin recargar la página.
|
||||
- [Añadir usuarios y permisos](users.md): formularios que sólo ven algunos usuarios.
|
||||
233
doc/v0.6/es/src/how-to/html.md
Normal file
233
doc/v0.6/es/src/how-to/html.md
Normal file
|
|
@ -0,0 +1,233 @@
|
|||
# Escribir HTML con `html!`
|
||||
|
||||
**Objetivo:** escribir marcado con la macro `html!`: elementos, valores de Rust, atributos
|
||||
condicionales, bucles y fragmentos reutilizables, todo comprobado al compilar.
|
||||
|
||||
PageTop escribe HTML con la macro `html!`, basada en [Maud](https://maud.lambda.xyz). Es Rust: si
|
||||
cierras mal una etiqueta o te equivocas con una variable, **no compila**.
|
||||
|
||||
```rust
|
||||
# use pagetop::prelude::*;
|
||||
let markup = html! {
|
||||
article class="post" {
|
||||
h2 { "Title" }
|
||||
p { "A paragraph with " strong { "bold" } " text." }
|
||||
img src="/photo.jpg" alt="A photo";
|
||||
}
|
||||
};
|
||||
assert_eq!(
|
||||
markup.into_string(),
|
||||
r#"<article class="post"><h2>Title</h2><p>A paragraph with <strong>bold</strong> text.</p><img src="/photo.jpg" alt="A photo"></article>"#
|
||||
);
|
||||
```
|
||||
|
||||
Las reglas básicas:
|
||||
|
||||
- Un elemento con contenido lleva llaves: `p { ... }`.
|
||||
- Un elemento vacío termina en punto y coma: `br;`, `img src="...";`.
|
||||
- El texto va entre comillas y los atributos se escriben como en HTML.
|
||||
- Los comentarios son los de Rust (`// ...`) y no llegan al HTML.
|
||||
|
||||
No hace falta escribir el `<!DOCTYPE>`, el `<head>` ni el `<body>`: los pone `Page` (ve
|
||||
[Construir páginas](pages.md)). Con `html!` escribes sólo el contenido.
|
||||
|
||||
## Insertar valores de Rust
|
||||
|
||||
Cualquier expresión entre paréntesis se inserta en el HTML, **escapada**:
|
||||
|
||||
```rust
|
||||
# use pagetop::prelude::*;
|
||||
let name = "<Ana>";
|
||||
let total = 3;
|
||||
let markup = html! { p { "Hello, " (name) ". You have " (total) " notices." } };
|
||||
assert_eq!(markup.into_string(), "<p>Hello, <Ana>. You have 3 notices.</p>");
|
||||
```
|
||||
|
||||
El escape es lo que te protege de la inyección de código (XSS): si un usuario escribe
|
||||
`<script>` en un formulario, la página muestra el texto, no lo ejecuta.
|
||||
|
||||
Si necesitas insertar HTML que ya es seguro, envuélvelo en `PreEscaped`:
|
||||
|
||||
```rust
|
||||
# use pagetop::prelude::*;
|
||||
let fragment = "<em>already escaped</em>";
|
||||
let markup = html! { p { (PreEscaped(fragment)) } };
|
||||
assert_eq!(markup.into_string(), "<p><em>already escaped</em></p>");
|
||||
```
|
||||
|
||||
Lo que pongas en `PreEscaped` llega al navegador tal cual. Úsalo sólo con contenido de confianza,
|
||||
nunca con texto que venga de un usuario.
|
||||
|
||||
## Atributos dinámicos
|
||||
|
||||
```rust
|
||||
# use pagetop::prelude::*;
|
||||
let url = "/profile";
|
||||
let title: Option<&str> = None;
|
||||
let active = true;
|
||||
let markup = html! {
|
||||
a href=(url) title=[title] { "Profile" }
|
||||
input type="checkbox" checked[active];
|
||||
li class="item" .active[active] { "Home" }
|
||||
};
|
||||
assert_eq!(
|
||||
markup.into_string(),
|
||||
r#"<a href="/profile">Profile</a><input type="checkbox" checked><li class="item active">Home</li>"#
|
||||
);
|
||||
```
|
||||
|
||||
- `attr=(expr)` fija el valor.
|
||||
- `attr=[option]` sólo escribe el atributo si la opción es `Some`.
|
||||
- `attr[condition]` escribe un atributo booleano si la condición es cierta.
|
||||
- `.class[condition]` añade una clase si la condición es cierta. Se combina con `class="..."`:
|
||||
`html!` junta las fijas y las condicionadas en un único atributo `class`.
|
||||
- Los atributos con guiones se escriben tal cual: `hx-get="/time"`, `aria-label="Close"`,
|
||||
`data-id=(id)`.
|
||||
|
||||
## Control de flujo
|
||||
|
||||
```rust
|
||||
# use pagetop::prelude::*;
|
||||
let tasks = ["Read", "Code", "Rest"];
|
||||
let user: Option<&str> = Some("Ana");
|
||||
let markup = html! {
|
||||
@if let Some(name) = user {
|
||||
p { "Signed in as " (name) }
|
||||
} @else {
|
||||
p { "Not signed in" }
|
||||
}
|
||||
ul {
|
||||
@for (i, task) in tasks.iter().enumerate() {
|
||||
@let number = i + 1;
|
||||
li { (number) ". " (task) }
|
||||
}
|
||||
}
|
||||
};
|
||||
assert!(markup.into_string().starts_with("<p>Signed in as Ana</p><ul><li>1. Read</li>"));
|
||||
```
|
||||
|
||||
`@match` elige el marcado según un valor, con los mismos patrones que un `match` de Rust:
|
||||
|
||||
```rust
|
||||
# use pagetop::prelude::*;
|
||||
enum Plot {
|
||||
Free,
|
||||
Taken(&'static str),
|
||||
}
|
||||
|
||||
let plots = [Plot::Taken("Ana"), Plot::Free];
|
||||
let markup = html! {
|
||||
@for plot in &plots {
|
||||
@match plot {
|
||||
Plot::Free => span class="free" { "Free" },
|
||||
Plot::Taken(holder) => span { "Taken by " (holder) },
|
||||
}
|
||||
}
|
||||
};
|
||||
assert_eq!(markup.into_string(), r#"<span>Taken by Ana</span><span class="free">Free</span>"#);
|
||||
```
|
||||
|
||||
También existe `@while`.
|
||||
|
||||
## Reutilizar fragmentos
|
||||
|
||||
Un fragmento que se repite se convierte en una función que devuelve `Markup`, y se inserta como
|
||||
cualquier otro valor:
|
||||
|
||||
```rust
|
||||
# use pagetop::prelude::*;
|
||||
fn plot_card(name: &str, holder: &str) -> Markup {
|
||||
html! {
|
||||
article class="plot-card" {
|
||||
h3 { (name) }
|
||||
p { "Holder: " (holder) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let markup = html! {
|
||||
(plot_card("A1", "Ana"))
|
||||
(plot_card("B2", "Luke"))
|
||||
};
|
||||
assert_eq!(
|
||||
markup.into_string(),
|
||||
concat!(
|
||||
r#"<article class="plot-card"><h3>A1</h3><p>Holder: Ana</p></article>"#,
|
||||
r#"<article class="plot-card"><h3>B2</h3><p>Holder: Luke</p></article>"#,
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
Es lo que en un motor de plantillas haría un *include*, pero con parámetros tipados: si te olvidas
|
||||
de uno, no compila. Y no necesitas una plantilla base de la que heredar: la estructura común de
|
||||
todas las páginas (cabecera, menú, pie) la ponen el tema y sus regiones.
|
||||
|
||||
## Insertar tus propios tipos
|
||||
|
||||
Cualquier tipo que implemente `Display` se inserta directamente, escapado:
|
||||
|
||||
```rust
|
||||
# use pagetop::prelude::*;
|
||||
use std::fmt;
|
||||
|
||||
struct Holder {
|
||||
name: String,
|
||||
}
|
||||
|
||||
impl fmt::Display for Holder {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{} (gardener)", self.name)
|
||||
}
|
||||
}
|
||||
|
||||
let holder = Holder { name: "Ana".to_string() };
|
||||
let markup = html! { p { (holder) } };
|
||||
assert_eq!(markup.into_string(), "<p>Ana (gardener)</p>");
|
||||
```
|
||||
|
||||
Para que un tipo genere su propio marcado, implementa `Render`:
|
||||
|
||||
```rust
|
||||
# use pagetop::prelude::*;
|
||||
struct Area(u32);
|
||||
|
||||
impl Render for Area {
|
||||
fn render(&self) -> Markup {
|
||||
html! { span class="area" { (self.0) " m²" } }
|
||||
}
|
||||
}
|
||||
|
||||
let markup = html! { p { "Size: " (Area(25)) } };
|
||||
assert_eq!(markup.into_string(), r#"<p>Size: <span class="area">25 m²</span></p>"#);
|
||||
```
|
||||
|
||||
Una función o un tipo con `Render` bastan para piezas pequeñas sin estado. Cuando la pieza necesita
|
||||
el idioma, la petición o que un tema pueda cambiarla, conviértela en un
|
||||
[componente](custom-components.md).
|
||||
|
||||
## `Html`: el componente comodín
|
||||
|
||||
En una página no se inserta `Markup` directamente, sino **componentes**. El más sencillo es
|
||||
`Html`, que envuelve un cierre con `html!`. El cierre recibe el contexto de renderizado (`cx`), con
|
||||
el idioma, el tema o la petición actuales:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_child(Html::with(|cx| {
|
||||
let greeting = Lc::n("Welcome");
|
||||
html! { h1 { (greeting.using(cx)) } }
|
||||
}))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
```
|
||||
|
||||
Úsalo para marcado puntual. Cuando un fragmento se repite o tiene entidad propia, conviértelo en
|
||||
un [componente](custom-components.md).
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Usar componentes](components.md): antes de escribir HTML, mira si ya existe un componente.
|
||||
- [Crear un componente](custom-components.md).
|
||||
235
doc/v0.6/es/src/how-to/htmx-delete.md
Normal file
235
doc/v0.6/es/src/how-to/htmx-delete.md
Normal file
|
|
@ -0,0 +1,235 @@
|
|||
# Borrar con confirmación
|
||||
|
||||
**Objetivo:** un botón en cada fila de una tabla que pide confirmación, borra en el servidor y
|
||||
retira la fila con un fundido, actualizando a la vez un contador que está fuera de la tabla.
|
||||
|
||||
Partimos de una aplicación con [HTMX añadido](htmx-setup.md) y de una tabla como las de [Mostrar
|
||||
tablas ordenables y paginadas](tables.md).
|
||||
|
||||
## 1. Un botón de borrar en cada fila
|
||||
|
||||
Las piezas de `Table` (filas, celdas, cabeceras) aceptan atributos con `with_prop()`, igual que los
|
||||
componentes. El botón de cada fila lleva cuatro:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
|
||||
struct Plot {
|
||||
id: u32,
|
||||
name: &'static str,
|
||||
holder: &'static str,
|
||||
}
|
||||
|
||||
fn plot_row(plot: &Plot) -> table::Row {
|
||||
let delete = Button::plain(Lc::n("Delete"))
|
||||
.with_style(button::Style::Outline(Intent::Severe))
|
||||
.with_prop(PropsOp::set(hx::DELETE, util::join!("/plots/", plot.id.to_string())))
|
||||
.with_prop(PropsOp::set(hx::CONFIRM, "Delete this plot?"))
|
||||
.with_prop(PropsOp::set(hx::TARGET, "closest tr"))
|
||||
.with_prop(PropsOp::set(hx::SWAP, "outerHTML swap:300ms"));
|
||||
table::Row::new()
|
||||
.with_cell(plot.name)
|
||||
.with_cell(plot.holder)
|
||||
.with_cell(delete)
|
||||
}
|
||||
```
|
||||
|
||||
- `hx-confirm` muestra el diálogo de confirmación del navegador. Si el usuario cancela, no se envía
|
||||
nada.
|
||||
- `hx-target="closest tr"` apunta a la fila que contiene el botón, sin necesidad de darle un `id`.
|
||||
- `swap:300ms` espera 300 ms antes de sustituir la fila. Es el tiempo del fundido del paso 3.
|
||||
|
||||
## 2. La ruta devuelve un fragmento vacío
|
||||
|
||||
Al sustituir la fila (`outerHTML`) por una respuesta vacía, la fila desaparece. Y el contador de
|
||||
parcelas, que está fuera de la tabla, viaja en la misma respuesta **fuera de banda**:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
# struct Plot { id: u32 }
|
||||
# fn plots() -> std::sync::MutexGuard<'static, Vec<Plot>> { todo!() }
|
||||
|
||||
fn count_update(count: usize) -> Markup {
|
||||
html! { span id="plot-count" hx-swap-oob="true" { (count) } }
|
||||
}
|
||||
|
||||
async fn delete(web::Path(id): web::Path<u32>) -> HtmxResponse {
|
||||
let mut plots = plots();
|
||||
plots.retain(|plot| plot.id != id);
|
||||
HtmxResponse::empty().oob(count_update(plots.len()))
|
||||
}
|
||||
```
|
||||
|
||||
## 3. El fundido
|
||||
|
||||
Durante esos 300 ms, HTMX pone la clase `htmx-swapping` en la fila. Con una regla CSS en la hoja de
|
||||
estilos de tu aplicación, la fila se desvanece antes de irse:
|
||||
|
||||
```css
|
||||
tr.htmx-swapping {
|
||||
opacity: 0;
|
||||
transition: opacity 300ms ease-out;
|
||||
}
|
||||
```
|
||||
|
||||
## 4. Cuando no queda nada
|
||||
|
||||
Al borrar la última fila, lo correcto es mostrar la tabla vacía con su mensaje («No plots left»),
|
||||
no una tabla sin filas. La ruta puede **cambiar el destino** de su respuesta: en lugar de la fila,
|
||||
sustituye el contenedor de la tabla entera.
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# use pagetop_htmx::prelude::*;
|
||||
# struct Plot { id: u32 }
|
||||
# fn plots() -> std::sync::MutexGuard<'static, Vec<Plot>> { todo!() }
|
||||
# fn count_update(_: usize) -> Markup { html! {} }
|
||||
# fn plots_table(_: &[Plot]) -> Container { Container::new() }
|
||||
async fn delete(request: HttpRequest, web::Path(id): web::Path<u32>) -> HtmxResponse {
|
||||
let (empty_table, count) = {
|
||||
let mut plots = plots();
|
||||
plots.retain(|plot| plot.id != id);
|
||||
(plots.is_empty().then(|| plots_table(&plots)), count_update(plots.len()))
|
||||
};
|
||||
if let Some(mut table) = empty_table {
|
||||
let table = table.render(&mut Context::new(request)).await;
|
||||
return HtmxResponse::new(table)
|
||||
.retarget("#plots")
|
||||
.reswap(hx::swap::OUTER_HTML)
|
||||
.oob(count);
|
||||
}
|
||||
HtmxResponse::empty().oob(count)
|
||||
}
|
||||
```
|
||||
|
||||
`plots_table()` construye la tabla dentro de un `Container` con `id="plots"`, que es el nuevo
|
||||
destino (lo tienes en el ejemplo completo). El bloque `{ ... }` suelta el `Mutex` **antes** del
|
||||
`.await`: un candado de la biblioteca estándar no puede quedar abierto mientras la tarea espera.
|
||||
|
||||
`retarget()` y `reswap()` envían las cabeceras `HX-Retarget` y `HX-Reswap`, que mandan sobre lo que
|
||||
dijeran los atributos del botón.
|
||||
|
||||
## El ejemplo completo
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
|
||||
use std::sync::{LazyLock, Mutex, MutexGuard};
|
||||
|
||||
struct Plot {
|
||||
id: u32,
|
||||
name: &'static str,
|
||||
holder: &'static str,
|
||||
}
|
||||
|
||||
static PLOTS: LazyLock<Mutex<Vec<Plot>>> = LazyLock::new(|| {
|
||||
Mutex::new(vec![
|
||||
Plot { id: 1, name: "A1", holder: "Ana" },
|
||||
Plot { id: 2, name: "A2", holder: "Luke" },
|
||||
Plot { id: 3, name: "B1", holder: "Marta" },
|
||||
])
|
||||
});
|
||||
|
||||
fn plots() -> MutexGuard<'static, Vec<Plot>> {
|
||||
PLOTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
|
||||
struct Allotments;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Allotments {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_htmx::Htmx]
|
||||
}
|
||||
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router
|
||||
.route("/", web::get(home))
|
||||
.route("/plots/{id}", web::delete(delete))
|
||||
}
|
||||
}
|
||||
|
||||
fn plot_row(plot: &Plot) -> table::Row {
|
||||
let delete = Button::plain(Lc::n("Delete"))
|
||||
.with_style(button::Style::Outline(Intent::Severe))
|
||||
.with_prop(PropsOp::set(hx::DELETE, util::join!("/plots/", plot.id.to_string())))
|
||||
.with_prop(PropsOp::set(hx::CONFIRM, "Delete this plot?"))
|
||||
.with_prop(PropsOp::set(hx::TARGET, "closest tr"))
|
||||
.with_prop(PropsOp::set(hx::SWAP, "outerHTML swap:300ms"));
|
||||
table::Row::new()
|
||||
.with_cell(plot.name)
|
||||
.with_cell(plot.holder)
|
||||
.with_cell(delete)
|
||||
}
|
||||
|
||||
fn plots_table(plots: &[Plot]) -> Container {
|
||||
let mut table = Table::new()
|
||||
.with_column(table::Column::new(Lc::n("Plot")))
|
||||
.with_column(table::Column::new(Lc::n("Holder")))
|
||||
.with_column(table::Column::new(Lc::none()))
|
||||
.with_empty(Lc::n("No plots left."));
|
||||
for plot in plots {
|
||||
table = table.with_row(plot_row(plot));
|
||||
}
|
||||
Container::new().with_id("plots").with_child(table)
|
||||
}
|
||||
|
||||
fn count_update(count: usize) -> Markup {
|
||||
html! { span id="plot-count" hx-swap-oob="true" { (count) } }
|
||||
}
|
||||
|
||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
let (table, count) = {
|
||||
let plots = plots();
|
||||
(plots_table(&plots), plots.len())
|
||||
};
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("Allotments"))
|
||||
.with_child(Html::with(move |_| html! {
|
||||
style { "tr.htmx-swapping { opacity: 0; transition: opacity 300ms ease-out; }" }
|
||||
h1 { "Allotments (" span id="plot-count" { (count) } ")" }
|
||||
}))
|
||||
.with_child(table)
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
async fn delete(request: HttpRequest, web::Path(id): web::Path<u32>) -> HtmxResponse {
|
||||
let (empty_table, count) = {
|
||||
let mut plots = plots();
|
||||
plots.retain(|plot| plot.id != id);
|
||||
(plots.is_empty().then(|| plots_table(&plots)), count_update(plots.len()))
|
||||
};
|
||||
if let Some(mut table) = empty_table {
|
||||
let table = table.render(&mut Context::new(request)).await;
|
||||
return HtmxResponse::new(table)
|
||||
.retarget("#plots")
|
||||
.reswap(hx::swap::OUTER_HTML)
|
||||
.oob(count);
|
||||
}
|
||||
HtmxResponse::empty().oob(count)
|
||||
}
|
||||
|
||||
#[pagetop::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
Application::prepare(&Allotments).await.run().await
|
||||
}
|
||||
```
|
||||
|
||||
El ejemplo pone la regla CSS en un `<style>` para que quepa en un archivo; en una aplicación, va en
|
||||
su [hoja de estilos](assets.md).
|
||||
|
||||
## Comprueba
|
||||
|
||||
1. Pulsa *Delete* en una fila y acepta: la fila se desvanece y el contador del título baja.
|
||||
2. Pulsa *Delete* y cancela: no pasa nada, y en la pestaña *Red* no hay petición.
|
||||
3. Borra todas: al irse la última, aparece «No plots left.» y el contador marca 0.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Ordenar y paginar sin recargar](htmx-tables.md).
|
||||
- [Dirigir al navegador desde el servidor](htmx-responses.md): todas las cabeceras que puede enviar
|
||||
una respuesta.
|
||||
273
doc/v0.6/es/src/how-to/htmx-edit.md
Normal file
273
doc/v0.6/es/src/how-to/htmx-edit.md
Normal file
|
|
@ -0,0 +1,273 @@
|
|||
# Editar en línea
|
||||
|
||||
**Objetivo:** que un bloque de datos se convierta en un formulario al pulsar *Edit*, y vuelva a ser
|
||||
un bloque al guardar o cancelar, sin salir de la página.
|
||||
|
||||
Partimos de una aplicación con [HTMX añadido](htmx-setup.md). El tutorial [Tareas del huerto con
|
||||
HTMX](../tutorials/htmx-tasks.md) hace lo mismo con elementos de una lista; aquí se hace con
|
||||
componentes: un `Block` con un `Form` dentro.
|
||||
|
||||
## 1. Dos versiones del mismo bloque
|
||||
|
||||
La idea es tener dos funciones que construyen **el mismo bloque** (mismo `id`) en sus dos estados.
|
||||
Los dos llevan `hx-target="this"` y `hx-swap="outerHTML"`, que heredan sus botones: cualquier
|
||||
petición que salga de dentro sustituye el bloque entero.
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Contact {
|
||||
name: String,
|
||||
phone: String,
|
||||
}
|
||||
|
||||
fn contact_block() -> Block {
|
||||
Block::new()
|
||||
.with_id("contact")
|
||||
.with_title(Lc::n("Garden coordinator"))
|
||||
.with_prop(PropsOp::set(hx::TARGET, "this"))
|
||||
.with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML))
|
||||
}
|
||||
|
||||
fn view_block(contact: &Contact) -> Block {
|
||||
let contact = contact.clone();
|
||||
contact_block()
|
||||
.with_child(Html::with(move |_| html! {
|
||||
p { (contact.name) }
|
||||
p { (contact.phone) }
|
||||
}))
|
||||
.with_child(Button::plain(Lc::n("Edit")).with_prop(PropsOp::set(hx::GET, "/contact/edit")))
|
||||
}
|
||||
|
||||
fn edit_block(contact: &Contact) -> Block {
|
||||
contact_block().with_child(Messages::new()).with_child(
|
||||
Form::new()
|
||||
.with_prop(PropsOp::set(hx::PUT, "/contact"))
|
||||
.with_child(
|
||||
form::input::Field::text()
|
||||
.with_name("name")
|
||||
.with_value(&contact.name)
|
||||
.with_label(Lc::n("Name"))
|
||||
.with_required(true),
|
||||
)
|
||||
.with_child(
|
||||
form::input::Field::telephone()
|
||||
.with_name("phone")
|
||||
.with_value(&contact.phone)
|
||||
.with_label(Lc::n("Phone")),
|
||||
)
|
||||
.with_child(Button::submit(Lc::n("Save")))
|
||||
.with_child(Button::plain(Lc::n("Cancel")).with_prop(PropsOp::set(hx::GET, "/contact"))),
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
El formulario no necesita `hx-target` propio: lo hereda del bloque. *Cancel* es un botón normal
|
||||
(`type="button"`), así que no envía el formulario; sólo pide la vista.
|
||||
|
||||
## 2. Tres rutas pequeñas
|
||||
|
||||
| Ruta | Devuelve |
|
||||
|---|---|
|
||||
| `GET /contact/edit` | El bloque con el formulario |
|
||||
| `GET /contact` | El bloque en modo vista (para *Cancel*) |
|
||||
| `PUT /contact` | El bloque en modo vista con los datos nuevos, o el formulario con un error |
|
||||
|
||||
Las tres renderizan un `Block` fuera de una página, con un `Context` creado a partir de la
|
||||
petición. Una función común lo hace, y de paso añade el error si lo hay:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# use pagetop_htmx::prelude::*;
|
||||
async fn fragment(request: HttpRequest, mut block: Block, error: Option<Lc>) -> HtmxResponse {
|
||||
let mut cx = Context::new(request);
|
||||
if let Some(error) = error {
|
||||
cx.push_message(MessageLevel::Error, error);
|
||||
}
|
||||
HtmxResponse::new(block.render(&mut cx).await)
|
||||
}
|
||||
```
|
||||
|
||||
Guardar valida antes de cambiar nada. Si algo falla, el usuario recibe su formulario **con lo que
|
||||
escribió** y el motivo:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# use pagetop_htmx::prelude::*;
|
||||
# use serde::Deserialize;
|
||||
# use std::sync::Mutex;
|
||||
# #[derive(Clone)]
|
||||
# struct Contact { name: String, phone: String }
|
||||
# static CONTACT: Mutex<Option<Contact>> = Mutex::new(None);
|
||||
# fn stored() -> std::sync::MutexGuard<'static, Option<Contact>> { CONTACT.lock().unwrap() }
|
||||
# fn view_block(_: &Contact) -> Block { Block::new() }
|
||||
# fn edit_block(_: &Contact) -> Block { Block::new() }
|
||||
# async fn fragment(_: HttpRequest, _: Block, _: Option<Lc>) -> HtmxResponse { todo!() }
|
||||
#[derive(Deserialize)]
|
||||
struct ContactForm {
|
||||
name: String,
|
||||
phone: String,
|
||||
}
|
||||
|
||||
async fn save(request: HttpRequest, web::Form(form): web::Form<ContactForm>) -> HtmxResponse {
|
||||
let contact = Contact {
|
||||
name: form.name.trim().to_string(),
|
||||
phone: form.phone.trim().to_string(),
|
||||
};
|
||||
if contact.name.is_empty() {
|
||||
let error = Lc::n("The coordinator needs a name.");
|
||||
return fragment(request, edit_block(&contact), Some(error)).await;
|
||||
}
|
||||
*stored() = Some(contact.clone());
|
||||
fragment(request, view_block(&contact), None).await
|
||||
}
|
||||
```
|
||||
|
||||
## El ejemplo completo
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
use serde::Deserialize;
|
||||
|
||||
use std::sync::{Mutex, MutexGuard};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Contact {
|
||||
name: String,
|
||||
phone: String,
|
||||
}
|
||||
|
||||
static CONTACT: Mutex<Option<Contact>> = Mutex::new(None);
|
||||
|
||||
fn stored() -> MutexGuard<'static, Option<Contact>> {
|
||||
CONTACT.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
|
||||
fn current_contact() -> Contact {
|
||||
stored().clone().unwrap_or_else(|| Contact {
|
||||
name: "Ana Pérez".into(),
|
||||
phone: "+34 600 000 000".into(),
|
||||
})
|
||||
}
|
||||
|
||||
struct Coordinator;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Coordinator {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_htmx::Htmx]
|
||||
}
|
||||
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router
|
||||
.route("/", web::get(home))
|
||||
.route("/contact", web::get(show).put(save))
|
||||
.route("/contact/edit", web::get(edit))
|
||||
}
|
||||
}
|
||||
|
||||
fn contact_block() -> Block {
|
||||
Block::new()
|
||||
.with_id("contact")
|
||||
.with_title(Lc::n("Garden coordinator"))
|
||||
.with_prop(PropsOp::set(hx::TARGET, "this"))
|
||||
.with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML))
|
||||
}
|
||||
|
||||
fn view_block(contact: &Contact) -> Block {
|
||||
let contact = contact.clone();
|
||||
contact_block()
|
||||
.with_child(Html::with(move |_| html! {
|
||||
p { (contact.name) }
|
||||
p { (contact.phone) }
|
||||
}))
|
||||
.with_child(Button::plain(Lc::n("Edit")).with_prop(PropsOp::set(hx::GET, "/contact/edit")))
|
||||
}
|
||||
|
||||
fn edit_block(contact: &Contact) -> Block {
|
||||
contact_block().with_child(Messages::new()).with_child(
|
||||
Form::new()
|
||||
.with_prop(PropsOp::set(hx::PUT, "/contact"))
|
||||
.with_child(
|
||||
form::input::Field::text()
|
||||
.with_name("name")
|
||||
.with_value(&contact.name)
|
||||
.with_label(Lc::n("Name"))
|
||||
.with_required(true),
|
||||
)
|
||||
.with_child(
|
||||
form::input::Field::telephone()
|
||||
.with_name("phone")
|
||||
.with_value(&contact.phone)
|
||||
.with_label(Lc::n("Phone")),
|
||||
)
|
||||
.with_child(Button::submit(Lc::n("Save")))
|
||||
.with_child(Button::plain(Lc::n("Cancel")).with_prop(PropsOp::set(hx::GET, "/contact"))),
|
||||
)
|
||||
}
|
||||
|
||||
async fn fragment(request: HttpRequest, mut block: Block, error: Option<Lc>) -> HtmxResponse {
|
||||
let mut cx = Context::new(request);
|
||||
if let Some(error) = error {
|
||||
cx.push_message(MessageLevel::Error, error);
|
||||
}
|
||||
HtmxResponse::new(block.render(&mut cx).await)
|
||||
}
|
||||
|
||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("Our garden"))
|
||||
.with_child(view_block(¤t_contact()))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
async fn show(request: HttpRequest) -> HtmxResponse {
|
||||
fragment(request, view_block(¤t_contact()), None).await
|
||||
}
|
||||
|
||||
async fn edit(request: HttpRequest) -> HtmxResponse {
|
||||
fragment(request, edit_block(¤t_contact()), None).await
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ContactForm {
|
||||
name: String,
|
||||
phone: String,
|
||||
}
|
||||
|
||||
async fn save(request: HttpRequest, web::Form(form): web::Form<ContactForm>) -> HtmxResponse {
|
||||
let contact = Contact {
|
||||
name: form.name.trim().to_string(),
|
||||
phone: form.phone.trim().to_string(),
|
||||
};
|
||||
if contact.name.is_empty() {
|
||||
let error = Lc::n("The coordinator needs a name.");
|
||||
return fragment(request, edit_block(&contact), Some(error)).await;
|
||||
}
|
||||
*stored() = Some(contact.clone());
|
||||
fragment(request, view_block(&contact), None).await
|
||||
}
|
||||
|
||||
#[pagetop::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
Application::prepare(&Coordinator).await.run().await
|
||||
}
|
||||
```
|
||||
|
||||
## Comprueba
|
||||
|
||||
1. Pulsa *Edit*: el bloque se convierte en un formulario con los datos actuales.
|
||||
2. Pulsa *Cancel*: vuelve la vista, sin cambios.
|
||||
3. Borra el nombre (con espacios, para que el navegador no lo impida) y guarda: el formulario
|
||||
vuelve con el aviso y con el teléfono que habías escrito.
|
||||
4. Escribe otro nombre y guarda: la vista muestra el nuevo. Recarga la página: el cambio se
|
||||
mantiene.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Borrar con confirmación](htmx-delete.md).
|
||||
- [Validar un campo al vuelo](htmx-validation.md), para avisar antes de guardar.
|
||||
157
doc/v0.6/es/src/how-to/htmx-infinite.md
Normal file
157
doc/v0.6/es/src/how-to/htmx-infinite.md
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
# Cargar más al hacer *scroll*
|
||||
|
||||
**Objetivo:** una lista larga que carga los siguientes elementos al pulsar «Load more» o, mejor
|
||||
aún, sola, cuando el usuario llega al final.
|
||||
|
||||
Partimos de una aplicación con [HTMX añadido](htmx-setup.md).
|
||||
|
||||
## 1. Un lote de elementos y un testigo
|
||||
|
||||
La ruta devuelve un **lote** de elementos y, si quedan más, un último elemento especial: el
|
||||
**testigo**, que sabe pedir el lote siguiente y ocupa su lugar.
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
const PER_PAGE: usize = 10;
|
||||
const TOTAL: usize = 35;
|
||||
|
||||
fn entries(page: usize) -> Markup {
|
||||
let start = (page - 1) * PER_PAGE;
|
||||
let end = (start + PER_PAGE).min(TOTAL);
|
||||
let next = util::join!("/diary/entries?page=", (page + 1).to_string());
|
||||
html! {
|
||||
@for day in start + 1..=end {
|
||||
li { "Day " (day) ": the garden is growing." }
|
||||
}
|
||||
@if end < TOTAL {
|
||||
li {
|
||||
button hx-get=(next) hx-target="closest li" hx-swap="outerHTML" { "Load more" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Al pulsar el botón, la respuesta (diez elementos y un testigo nuevo) **sustituye al testigo**: la
|
||||
lista crece por abajo y el botón baja con ella. Cuando no quedan elementos, el último lote no trae
|
||||
testigo y la carga termina sola.
|
||||
|
||||
## 2. Sin botón: al llegar al final
|
||||
|
||||
Para cargar sin que el usuario pulse nada, el testigo se dispara con `revealed`, que ocurre cuando
|
||||
el elemento entra en la pantalla:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f(next: String) -> Markup {
|
||||
html! {
|
||||
li hx-get=(next) hx-trigger="revealed" hx-swap="outerHTML" { "Loading more..." }
|
||||
}
|
||||
# }
|
||||
```
|
||||
|
||||
Es el mismo patrón con otro disparador. Si la lista está dentro de un contenedor con su propio
|
||||
*scroll* (`overflow: auto`), usa `hx-trigger="intersect once"`, que funciona con cualquier
|
||||
contenedor.
|
||||
|
||||
## 3. La página y la ruta del lote
|
||||
|
||||
La página pinta el primer lote dentro de la lista; la ruta del lote devuelve sólo los `<li>`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn entries(_: usize) -> Markup { html! {} }
|
||||
use serde::Deserialize;
|
||||
|
||||
async fn diary(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("Garden diary"))
|
||||
.with_child(Html::with(|_| html! { ul id="diary" { (entries(1)) } }))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Batch {
|
||||
page: usize,
|
||||
}
|
||||
|
||||
async fn more_entries(web::Query(batch): web::Query<Batch>) -> Markup {
|
||||
entries(batch.page.max(1))
|
||||
}
|
||||
```
|
||||
|
||||
## El ejemplo completo
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
use serde::Deserialize;
|
||||
|
||||
const PER_PAGE: usize = 10;
|
||||
const TOTAL: usize = 35;
|
||||
|
||||
struct Diary;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Diary {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_htmx::Htmx]
|
||||
}
|
||||
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router
|
||||
.route("/", web::get(diary))
|
||||
.route("/diary/entries", web::get(more_entries))
|
||||
}
|
||||
}
|
||||
|
||||
fn entries(page: usize) -> Markup {
|
||||
let start = (page - 1) * PER_PAGE;
|
||||
let end = (start + PER_PAGE).min(TOTAL);
|
||||
let next = util::join!("/diary/entries?page=", (page + 1).to_string());
|
||||
html! {
|
||||
@for day in start + 1..=end {
|
||||
li { "Day " (day) ": the garden is growing." }
|
||||
}
|
||||
@if end < TOTAL {
|
||||
li hx-get=(next) hx-trigger="revealed" hx-swap="outerHTML" { "Loading more..." }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn diary(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("Garden diary"))
|
||||
.with_child(Html::with(|_| html! { ul id="diary" { (entries(1)) } }))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Batch {
|
||||
page: usize,
|
||||
}
|
||||
|
||||
async fn more_entries(web::Query(batch): web::Query<Batch>) -> Markup {
|
||||
entries(batch.page.max(1))
|
||||
}
|
||||
|
||||
#[pagetop::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
Application::prepare(&Diary).await.run().await
|
||||
}
|
||||
```
|
||||
|
||||
## Comprueba
|
||||
|
||||
1. Abre la página y baja: cada vez que el testigo «Loading more...» asoma por abajo, llegan diez
|
||||
días más. Si la ventana es alta y el testigo ya se ve al cargar, el segundo lote llega sin
|
||||
esperar: está a la vista.
|
||||
2. Sigue bajando hasta el día 35: el testigo ya no aparece.
|
||||
3. En la pestaña *Red* hay tres peticiones a `/diary/entries`, una por lote.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Ordenar y paginar sin recargar](htmx-tables.md): cuando el usuario necesita saltar a una página
|
||||
concreta, un paginador es mejor opción.
|
||||
- [Actualizar periódicamente](htmx-polling.md).
|
||||
168
doc/v0.6/es/src/how-to/htmx-load.md
Normal file
168
doc/v0.6/es/src/how-to/htmx-load.md
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
# Cargar contenido bajo demanda
|
||||
|
||||
**Objetivo:** que una parte de la página se cargue después que el resto: cuando el usuario la pida,
|
||||
en cuanto la página esté lista o cuando se haga visible. La página aparece antes, y lo costoso
|
||||
llega por su cuenta.
|
||||
|
||||
Partimos de una aplicación con [HTMX añadido](htmx-setup.md).
|
||||
|
||||
## 1. Al pulsar
|
||||
|
||||
El caso básico: un botón trae el contenido y lo pone en su sitio.
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Html {
|
||||
Html::with(|_| html! {
|
||||
button hx-get="/forecast" hx-target="#forecast" { "Show the forecast" }
|
||||
div id="forecast" {}
|
||||
})
|
||||
# }
|
||||
```
|
||||
|
||||
Para que el botón desaparezca y su lugar lo ocupe el contenido, apunta al propio botón y sustitúyelo
|
||||
entero:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Html {
|
||||
Html::with(|_| html! {
|
||||
button hx-get="/forecast" hx-swap="outerHTML" { "Show the forecast" }
|
||||
})
|
||||
# }
|
||||
```
|
||||
|
||||
## 2. En cuanto se carga la página
|
||||
|
||||
Con `hx-trigger="load"`, el elemento pide su contenido nada más aparecer. Mientras llega, muestra
|
||||
lo que tenga dentro:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Html {
|
||||
Html::with(|_| html! {
|
||||
div hx-get="/forecast" hx-trigger="load" hx-swap="outerHTML" {
|
||||
p { "Loading the forecast..." }
|
||||
}
|
||||
})
|
||||
# }
|
||||
```
|
||||
|
||||
Úsalo para lo que tarda (un servicio externo, una consulta pesada): la página se sirve al momento y
|
||||
ese bloque se completa después.
|
||||
|
||||
## 3. Cuando se hace visible
|
||||
|
||||
Con `hx-trigger="revealed"`, la petición espera a que el elemento entre en la pantalla. Ideal para
|
||||
lo que queda al final de una página larga, como los comentarios:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Html {
|
||||
Html::with(|_| html! {
|
||||
section hx-get="/comments" hx-trigger="revealed" hx-swap="outerHTML" {
|
||||
p { "Comments will load when you get here." }
|
||||
}
|
||||
})
|
||||
# }
|
||||
```
|
||||
|
||||
Si el usuario nunca baja hasta ahí, la petición no se hace.
|
||||
|
||||
## 4. Muestra que está cargando
|
||||
|
||||
Mientras dura una petición, HTMX añade la clase `htmx-request` al elemento que la hizo. Los
|
||||
elementos con la clase `htmx-indicator` están ocultos y se muestran sólo durante la petición del
|
||||
elemento que los contiene, o de quien los señale con `hx-indicator`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Html {
|
||||
Html::with(|_| html! {
|
||||
button hx-get="/forecast" hx-target="#forecast" hx-indicator="#spinner" {
|
||||
"Show the forecast"
|
||||
}
|
||||
span id="spinner" class="htmx-indicator" { " Loading..." }
|
||||
div id="forecast" {}
|
||||
})
|
||||
# }
|
||||
```
|
||||
|
||||
HTMX trae los estilos de `htmx-indicator`, así que funciona sin escribir CSS.
|
||||
|
||||
## El ejemplo completo
|
||||
|
||||
Una página con las tres formas, sobre las mismas dos rutas:
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
|
||||
struct Garden;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Garden {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_htmx::Htmx]
|
||||
}
|
||||
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router
|
||||
.route("/", web::get(home))
|
||||
.route("/forecast", web::get(forecast))
|
||||
.route("/comments", web::get(comments))
|
||||
}
|
||||
}
|
||||
|
||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("The garden today"))
|
||||
.with_child(Html::with(|_| html! {
|
||||
h1 { "The garden today" }
|
||||
|
||||
h2 { "Forecast" }
|
||||
button hx-get="/forecast" hx-swap="outerHTML" { "Show the forecast" }
|
||||
|
||||
h2 { "Forecast, on load" }
|
||||
div hx-get="/forecast" hx-trigger="load" hx-swap="outerHTML" {
|
||||
p { "Loading the forecast..." }
|
||||
}
|
||||
|
||||
h2 { "Comments" }
|
||||
div style="height: 150vh" { p { "Scroll down..." } }
|
||||
section hx-get="/comments" hx-trigger="revealed" hx-swap="outerHTML" {
|
||||
p { "Comments will load when you get here." }
|
||||
}
|
||||
}))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
async fn forecast() -> Markup {
|
||||
html! { p class="forecast" { "Sunny, 24 °C. Water in the evening." } }
|
||||
}
|
||||
|
||||
async fn comments() -> Markup {
|
||||
html! {
|
||||
ul class="comments" {
|
||||
li { "Ana: the lettuces are ready." }
|
||||
li { "Luke: who has the hose key?" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[pagetop::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
Application::prepare(&Garden).await.run().await
|
||||
}
|
||||
```
|
||||
|
||||
## Comprueba
|
||||
|
||||
1. Al abrir la página, el segundo bloque ya muestra la previsión: se pidió nada más cargarse.
|
||||
2. El botón del primero se sustituye por la previsión al pulsarlo.
|
||||
3. En la pestaña *Red*, `/comments` no aparece hasta que bajas al final de la página.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Cargar más al hacer *scroll*](htmx-infinite.md): `revealed` aplicado a listas largas.
|
||||
- [Actualizar periódicamente](htmx-polling.md): pedir el mismo fragmento cada pocos segundos.
|
||||
177
doc/v0.6/es/src/how-to/htmx-polling.md
Normal file
177
doc/v0.6/es/src/how-to/htmx-polling.md
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
# Actualizar periódicamente
|
||||
|
||||
**Objetivo:** que una parte de la página se refresque sola cada pocos segundos (el progreso de una
|
||||
tarea larga, un contador, el estado de un servicio) y que deje de hacerlo cuando ya no haga falta.
|
||||
|
||||
Partimos de una aplicación con [HTMX añadido](htmx-setup.md).
|
||||
|
||||
## 1. Sondear cada pocos segundos
|
||||
|
||||
Con `hx-trigger="every 2s"`, el elemento repite su petición cada dos segundos mientras siga en la
|
||||
página:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Html {
|
||||
Html::with(|_| html! {
|
||||
div hx-get="/sensors" hx-trigger="every 2s" {
|
||||
p { "Reading the sensors..." }
|
||||
}
|
||||
})
|
||||
# }
|
||||
```
|
||||
|
||||
La ruta devuelve el contenido actualizado y HTMX lo pone dentro del `div`. Es la forma más
|
||||
sencilla de mantener un dato al día, sin conexiones permanentes ni JavaScript.
|
||||
|
||||
## 2. Parar cuando termina
|
||||
|
||||
Para el progreso de una tarea, el sondeo debe acabar cuando la tarea acaba. El truco es que **cada
|
||||
respuesta decide si sigue el sondeo**: el fragmento sustituye al elemento entero (`outerHTML`) y
|
||||
sólo lleva `hx-trigger` mientras la tarea no ha terminado.
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
fn progress(percent: u64) -> Markup {
|
||||
if percent < 100 {
|
||||
html! {
|
||||
div id="watering" hx-get="/watering" hx-trigger="every 1s" hx-swap="outerHTML" {
|
||||
progress value=(percent) max="100" {}
|
||||
" " (percent) "%"
|
||||
}
|
||||
}
|
||||
} else {
|
||||
html! {
|
||||
div id="watering" {
|
||||
p { "Watering finished." }
|
||||
button hx-post="/watering" hx-target="#watering" hx-swap="outerHTML" {
|
||||
"Water again"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Cuando llega la versión final, sin `hx-trigger`, ya no queda nada que sondee.
|
||||
|
||||
Si prefieres no sustituir el elemento, hay otra forma de parar: responder con el código de estado
|
||||
**286**. HTMX lo interpreta como «deja de sondear».
|
||||
|
||||
## 3. Arrancar la tarea
|
||||
|
||||
Un botón inicia la tarea con un `POST`; la respuesta es el primer fragmento de progreso, que ya
|
||||
sondea por su cuenta:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# use std::sync::Mutex;
|
||||
# use std::time::Instant;
|
||||
# static STARTED: Mutex<Option<Instant>> = Mutex::new(None);
|
||||
# fn progress(_: u64) -> Markup { html! {} }
|
||||
# fn started() -> std::sync::MutexGuard<'static, Option<Instant>> { STARTED.lock().unwrap() }
|
||||
async fn start() -> Markup {
|
||||
*started() = Some(Instant::now());
|
||||
progress(0)
|
||||
}
|
||||
```
|
||||
|
||||
En una aplicación real, `start` lanzaría el trabajo en segundo plano y guardaría su estado; la ruta
|
||||
del sondeo sólo lo consulta. Aquí, para no depender de nada, el progreso se calcula a partir del
|
||||
tiempo transcurrido.
|
||||
|
||||
## El ejemplo completo
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
|
||||
use std::sync::{Mutex, MutexGuard};
|
||||
use std::time::Instant;
|
||||
|
||||
// Seconds that the simulated watering lasts.
|
||||
const DURATION: u64 = 5;
|
||||
|
||||
static STARTED: Mutex<Option<Instant>> = Mutex::new(None);
|
||||
|
||||
fn started() -> MutexGuard<'static, Option<Instant>> {
|
||||
STARTED.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
|
||||
struct Watering;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Watering {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_htmx::Htmx]
|
||||
}
|
||||
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router
|
||||
.route("/", web::get(home))
|
||||
.route("/watering", web::get(status).post(start))
|
||||
}
|
||||
}
|
||||
|
||||
fn progress(percent: u64) -> Markup {
|
||||
if percent < 100 {
|
||||
html! {
|
||||
div id="watering" hx-get="/watering" hx-trigger="every 1s" hx-swap="outerHTML" {
|
||||
progress value=(percent) max="100" {}
|
||||
" " (percent) "%"
|
||||
}
|
||||
}
|
||||
} else {
|
||||
html! {
|
||||
div id="watering" {
|
||||
p { "Watering finished." }
|
||||
button hx-post="/watering" hx-target="#watering" hx-swap="outerHTML" {
|
||||
"Water again"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("Watering"))
|
||||
.with_child(Html::with(|_| html! {
|
||||
h1 { "Watering" }
|
||||
div id="watering" {
|
||||
button hx-post="/watering" hx-target="#watering" hx-swap="outerHTML" {
|
||||
"Start watering"
|
||||
}
|
||||
}
|
||||
}))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
async fn start() -> Markup {
|
||||
*started() = Some(Instant::now());
|
||||
progress(0)
|
||||
}
|
||||
|
||||
async fn status() -> Markup {
|
||||
let elapsed = started().map_or(DURATION, |since| since.elapsed().as_secs());
|
||||
progress((elapsed * 100 / DURATION).min(100))
|
||||
}
|
||||
|
||||
#[pagetop::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
Application::prepare(&Watering).await.run().await
|
||||
}
|
||||
```
|
||||
|
||||
## Comprueba
|
||||
|
||||
1. Pulsa *Start watering*: aparece una barra que avanza cada segundo.
|
||||
2. A los cinco segundos, la barra da paso a «Watering finished.». En la pestaña *Red*, las
|
||||
peticiones a `/watering` se detienen.
|
||||
3. *Water again* vuelve a empezar.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Dirigir al navegador desde el servidor](htmx-responses.md): avisar a otras partes de la página
|
||||
cuando algo termina.
|
||||
- [Cargar contenido bajo demanda](htmx-load.md).
|
||||
221
doc/v0.6/es/src/how-to/htmx-responses.md
Normal file
221
doc/v0.6/es/src/how-to/htmx-responses.md
Normal file
|
|
@ -0,0 +1,221 @@
|
|||
# Dirigir al navegador desde el servidor
|
||||
|
||||
**Objetivo:** que sea el servidor, y no los atributos de la página, quien decida qué pasa tras una
|
||||
petición: poner la respuesta en otro sitio, avisar a otras partes de la página, cambiar la URL o
|
||||
redirigir.
|
||||
|
||||
Partimos de una aplicación con [HTMX añadido](htmx-setup.md). Todo se hace con `HtmxResponse`, que
|
||||
añade a la respuesta las cabeceras `HX-*` que HTMX entiende.
|
||||
|
||||
## 1. Cambiar el destino según el resultado
|
||||
|
||||
Un formulario de suscripción coloca su respuesta en `#signup`. Si el correo no es válido, el error
|
||||
debe ir a otro sitio, junto al campo. La ruta lo decide:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Signup {
|
||||
email: String,
|
||||
}
|
||||
|
||||
fn looks_like_an_email(email: &str) -> bool {
|
||||
email
|
||||
.split_once('@')
|
||||
.is_some_and(|(name, domain)| !name.is_empty() && domain.contains('.'))
|
||||
}
|
||||
|
||||
async fn subscribe(web::Form(signup): web::Form<Signup>) -> HtmxResponse {
|
||||
if !looks_like_an_email(&signup.email) {
|
||||
return HtmxResponse::new(html! { "That does not look like an email." })
|
||||
.retarget("#signup-error")
|
||||
.reswap(hx::swap::INNER_HTML);
|
||||
}
|
||||
// ... store the subscription ...
|
||||
HtmxResponse::new(html! { p { "Subscribed! See you at the next harvest." } })
|
||||
}
|
||||
```
|
||||
|
||||
`retarget()` y `reswap()` mandan sobre `hx-target` y `hx-swap`. El formulario sigue en su sitio y
|
||||
el usuario puede corregir el correo.
|
||||
|
||||
## 2. Avisar a otras partes de la página
|
||||
|
||||
Tras una suscripción, el contador de suscriptores de la cabecera debería actualizarse. En lugar de
|
||||
que la ruta sepa qué hay en la cabecera, **dispara un evento**:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# use pagetop_htmx::prelude::*;
|
||||
# fn f() -> HtmxResponse {
|
||||
HtmxResponse::new(html! { p { "Subscribed! See you at the next harvest." } })
|
||||
.trigger("subscribed")
|
||||
# }
|
||||
```
|
||||
|
||||
Y quien quiera enterarse, lo escucha. El evento sube hasta `body`, así que basta con
|
||||
`from:body`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Html {
|
||||
Html::with(|_| html! {
|
||||
span hx-get="/subscribers" hx-trigger="subscribed from:body" { "0" }
|
||||
})
|
||||
# }
|
||||
```
|
||||
|
||||
Las dos partes no se conocen: el formulario anuncia y el contador escucha. Puedes añadir más
|
||||
oyentes sin tocar la ruta. Para enviar varios eventos o datos con ellos, `trigger()` admite una
|
||||
lista separada por comas o un objeto JSON.
|
||||
|
||||
## 3. Redirigir
|
||||
|
||||
Tras una acción con HTMX, una redirección normal (`303`) la seguiría HTMX por su cuenta y pondría
|
||||
la página nueva **dentro** del destino. Para cambiar de página de verdad, usa `redirect()`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
|
||||
async fn close_season() -> HtmxResponse {
|
||||
// ... close the season ...
|
||||
HtmxResponse::empty().redirect("/season/closed")
|
||||
}
|
||||
```
|
||||
|
||||
`location()` es la alternativa suave: navega con HTMX, sin recargar los estilos y *scripts* de la
|
||||
página.
|
||||
|
||||
## Las cabeceras disponibles
|
||||
|
||||
| Método | Cabecera | Efecto |
|
||||
|---|---|---|
|
||||
| `retarget(selector)` | `HX-Retarget` | Pone la respuesta en otro elemento |
|
||||
| `reswap(estrategia)` | `HX-Reswap` | Cambia cómo se coloca (`innerHTML`, `outerHTML`...) |
|
||||
| `reselect(selector)` | `HX-Reselect` | Usa sólo una parte de la respuesta |
|
||||
| `trigger(eventos)` | `HX-Trigger` | Dispara eventos al recibir la respuesta |
|
||||
| `trigger_after_swap(eventos)` | `HX-Trigger-After-Swap` | ...después de colocarla |
|
||||
| `trigger_after_settle(eventos)` | `HX-Trigger-After-Settle` | ...cuando se ha asentado |
|
||||
| `push_url(url)` | `HX-Push-Url` | Añade una entrada al historial |
|
||||
| `replace_url(url)` | `HX-Replace-Url` | Cambia la URL sin añadir entrada |
|
||||
| `redirect(url)` | `HX-Redirect` | Navegación completa a otra página |
|
||||
| `location(url)` | `HX-Location` | Navegación con HTMX, sin recargar la página |
|
||||
| `refresh()` | `HX-Refresh` | Recarga la página entera |
|
||||
| `oob(markup)` | - | Añade un fragmento [fuera de banda](htmx-delete.md#2-la-ruta-devuelve-un-fragmento-vacío) |
|
||||
|
||||
## El ejemplo completo
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
use serde::Deserialize;
|
||||
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
static SUBSCRIBERS: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
struct Newsletter;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Newsletter {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_htmx::Htmx]
|
||||
}
|
||||
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router
|
||||
.route("/", web::get(home))
|
||||
.route("/subscribe", web::post(subscribe))
|
||||
.route("/subscribers", web::get(subscribers))
|
||||
.route("/season/close", web::post(close_season))
|
||||
.route("/season/closed", web::get(season_closed))
|
||||
}
|
||||
}
|
||||
|
||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("Newsletter"))
|
||||
.with_child(Html::with(|_| html! {
|
||||
p {
|
||||
"Subscribers: "
|
||||
span hx-get="/subscribers" hx-trigger="subscribed from:body" {
|
||||
(SUBSCRIBERS.load(Ordering::Relaxed))
|
||||
}
|
||||
}
|
||||
div id="signup" {
|
||||
form hx-post="/subscribe" hx-target="#signup" {
|
||||
input type="email" name="email" placeholder="you@example.com";
|
||||
button type="submit" { "Subscribe" }
|
||||
p id="signup-error" {}
|
||||
}
|
||||
}
|
||||
button hx-post="/season/close" hx-confirm="Close the season?" { "Close the season" }
|
||||
}))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Signup {
|
||||
email: String,
|
||||
}
|
||||
|
||||
fn looks_like_an_email(email: &str) -> bool {
|
||||
email
|
||||
.split_once('@')
|
||||
.is_some_and(|(name, domain)| !name.is_empty() && domain.contains('.'))
|
||||
}
|
||||
|
||||
async fn subscribe(web::Form(signup): web::Form<Signup>) -> HtmxResponse {
|
||||
if !looks_like_an_email(&signup.email) {
|
||||
return HtmxResponse::new(html! { "That does not look like an email." })
|
||||
.retarget("#signup-error")
|
||||
.reswap(hx::swap::INNER_HTML);
|
||||
}
|
||||
SUBSCRIBERS.fetch_add(1, Ordering::Relaxed);
|
||||
HtmxResponse::new(html! { p { "Subscribed! See you at the next harvest." } })
|
||||
.trigger("subscribed")
|
||||
}
|
||||
|
||||
async fn subscribers() -> Markup {
|
||||
html! { (SUBSCRIBERS.load(Ordering::Relaxed)) }
|
||||
}
|
||||
|
||||
async fn close_season() -> HtmxResponse {
|
||||
HtmxResponse::empty().redirect("/season/closed")
|
||||
}
|
||||
|
||||
async fn season_closed(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("Season closed"))
|
||||
.with_child(Html::with(|_| html! { h1 { "The season is closed. See you in spring!" } }))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
#[pagetop::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
Application::prepare(&Newsletter).await.run().await
|
||||
}
|
||||
```
|
||||
|
||||
El formulario de este ejemplo está escrito en `html!` para que se vea entero; con `Form` y sus
|
||||
campos, los atributos se ponen igual, con `with_prop()`.
|
||||
|
||||
## Comprueba
|
||||
|
||||
1. Escribe `ana@garden` y suscríbete: el navegador lo da por bueno, pero el servidor exige un
|
||||
dominio con punto. El aviso aparece bajo el campo y el formulario sigue ahí.
|
||||
2. Escribe un correo válido: el formulario se sustituye por la confirmación y el contador de
|
||||
suscriptores sube, sin que la ruta lo haya tocado.
|
||||
3. Pulsa *Close the season* y acepta: el navegador cambia de página.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [HTMX: atributos, cabeceras y respuestas](../reference/htmx.md), la referencia completa.
|
||||
- [Probar rutas y componentes](testing.md): las cabeceras `HX-*` también se pueden comprobar en
|
||||
las pruebas.
|
||||
219
doc/v0.6/es/src/how-to/htmx-search.md
Normal file
219
doc/v0.6/es/src/how-to/htmx-search.md
Normal file
|
|
@ -0,0 +1,219 @@
|
|||
# Buscar mientras se escribe
|
||||
|
||||
**Objetivo:** un buscador que filtra los resultados a medida que el usuario escribe, que deja en la
|
||||
barra de direcciones una URL que se puede compartir y que funciona también sin JavaScript.
|
||||
|
||||
Partimos de una aplicación con [HTMX añadido](htmx-setup.md).
|
||||
|
||||
## 1. Un buscador de toda la vida
|
||||
|
||||
Empieza por lo que funcionaría sin HTMX: un formulario `GET` que envía `q` a `/plants`, y una ruta
|
||||
que muestra los resultados.
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
const PLANTS: &[&str] = &[
|
||||
"Basil", "Bean", "Beetroot", "Cabbage", "Carrot", "Chard", "Courgette", "Cucumber", "Garlic",
|
||||
"Leek", "Lettuce", "Onion", "Parsley", "Pepper", "Potato", "Pumpkin", "Radish", "Spinach",
|
||||
"Strawberry", "Tomato",
|
||||
];
|
||||
|
||||
fn results(q: &str) -> Markup {
|
||||
let q = q.trim().to_lowercase();
|
||||
let found: Vec<&str> = PLANTS
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|plant| plant.to_lowercase().contains(&q))
|
||||
.collect();
|
||||
html! {
|
||||
div id="results" {
|
||||
@if found.is_empty() {
|
||||
p { "No plants found." }
|
||||
} @else {
|
||||
ul {
|
||||
@for plant in &found {
|
||||
li { (plant) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
El contenedor `#results` forma parte del fragmento. Así, al sustituirlo entero (`outerHTML`), el
|
||||
destino sigue existiendo para la búsqueda siguiente.
|
||||
|
||||
## 2. Que busque al escribir
|
||||
|
||||
Al formulario se le añaden cinco atributos:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
|
||||
fn search_form(q: &str) -> Form {
|
||||
Form::new()
|
||||
.with_action("/plants")
|
||||
.with_method(form::Method::Get)
|
||||
.with_prop(PropsOp::set(hx::GET, "/plants"))
|
||||
.with_prop(PropsOp::set(hx::TRIGGER, "input delay:300ms, submit"))
|
||||
.with_prop(PropsOp::set(hx::TARGET, "#results"))
|
||||
.with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML))
|
||||
.with_prop(PropsOp::set(hx::REPLACE_URL, "true"))
|
||||
.with_child(
|
||||
form::input::Field::search()
|
||||
.with_name("q")
|
||||
.with_value(q)
|
||||
.with_label(Lc::n("Search plants")),
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
- `hx-trigger="input delay:300ms, submit"`: busca cuando cambia el texto, pero espera a que el
|
||||
usuario lleve 300 ms sin teclear. Así, escribir «tomato» hace una petición, no seis. `submit`
|
||||
mantiene la tecla Intro.
|
||||
- El evento `input` sube desde el campo hasta el formulario, y una petición `GET` de un formulario
|
||||
incluye todos sus campos: no hay que decir qué enviar.
|
||||
- `hx-replace-url="true"`: la barra de direcciones pasa a `/plants?q=tom`, sin llenar el historial
|
||||
con una entrada por búsqueda.
|
||||
|
||||
## 3. Una ruta, dos respuestas
|
||||
|
||||
La URL que queda en la barra se puede recargar o compartir. Esa petición llega **sin** HTMX y
|
||||
espera una página entera; las de HTMX, sólo los resultados:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# use pagetop_htmx::prelude::*;
|
||||
# fn results(_: &str) -> Markup { html! {} }
|
||||
# fn search_form(_: &str) -> Form { Form::new() }
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Search {
|
||||
#[serde(default)]
|
||||
q: String,
|
||||
}
|
||||
|
||||
async fn plants(request: HttpRequest, web::Query(search): web::Query<Search>) -> Response {
|
||||
if request.is_htmx() {
|
||||
return HtmxResponse::new(results(&search.q)).into_response();
|
||||
}
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("Plants"))
|
||||
.with_child(search_form(&search.q))
|
||||
.with_child(Html::with(move |_| results(&search.q)))
|
||||
.render()
|
||||
.await
|
||||
.into_response()
|
||||
}
|
||||
```
|
||||
|
||||
Sin JavaScript, el formulario se envía como siempre y la misma ruta devuelve la página completa: el
|
||||
buscador funciona igual, sólo que pulsando Intro.
|
||||
|
||||
## El ejemplo completo
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
use serde::Deserialize;
|
||||
|
||||
const PLANTS: &[&str] = &[
|
||||
"Basil", "Bean", "Beetroot", "Cabbage", "Carrot", "Chard", "Courgette", "Cucumber", "Garlic",
|
||||
"Leek", "Lettuce", "Onion", "Parsley", "Pepper", "Potato", "Pumpkin", "Radish", "Spinach",
|
||||
"Strawberry", "Tomato",
|
||||
];
|
||||
|
||||
struct PlantFinder;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for PlantFinder {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_htmx::Htmx]
|
||||
}
|
||||
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router
|
||||
.route("/", web::get(|| async { Redirect::see_other("/plants") }))
|
||||
.route("/plants", web::get(plants))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Search {
|
||||
#[serde(default)]
|
||||
q: String,
|
||||
}
|
||||
|
||||
async fn plants(request: HttpRequest, web::Query(search): web::Query<Search>) -> Response {
|
||||
if request.is_htmx() {
|
||||
return HtmxResponse::new(results(&search.q)).into_response();
|
||||
}
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("Plants"))
|
||||
.with_child(search_form(&search.q))
|
||||
.with_child(Html::with(move |_| results(&search.q)))
|
||||
.render()
|
||||
.await
|
||||
.into_response()
|
||||
}
|
||||
|
||||
fn search_form(q: &str) -> Form {
|
||||
Form::new()
|
||||
.with_action("/plants")
|
||||
.with_method(form::Method::Get)
|
||||
.with_prop(PropsOp::set(hx::GET, "/plants"))
|
||||
.with_prop(PropsOp::set(hx::TRIGGER, "input delay:300ms, submit"))
|
||||
.with_prop(PropsOp::set(hx::TARGET, "#results"))
|
||||
.with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML))
|
||||
.with_prop(PropsOp::set(hx::REPLACE_URL, "true"))
|
||||
.with_child(
|
||||
form::input::Field::search()
|
||||
.with_name("q")
|
||||
.with_value(q)
|
||||
.with_label(Lc::n("Search plants")),
|
||||
)
|
||||
}
|
||||
|
||||
fn results(q: &str) -> Markup {
|
||||
let q = q.trim().to_lowercase();
|
||||
let found: Vec<&str> = PLANTS
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|plant| plant.to_lowercase().contains(&q))
|
||||
.collect();
|
||||
html! {
|
||||
div id="results" {
|
||||
@if found.is_empty() {
|
||||
p { "No plants found." }
|
||||
} @else {
|
||||
ul {
|
||||
@for plant in &found {
|
||||
li { (plant) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[pagetop::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
Application::prepare(&PlantFinder).await.run().await
|
||||
}
|
||||
```
|
||||
|
||||
## Comprueba
|
||||
|
||||
1. Abre <http://localhost:8080/plants> y escribe `to`: la lista se reduce a *Potato* y *Tomato*
|
||||
sin pulsar nada, y la barra de direcciones muestra `/plants?q=to`.
|
||||
2. Recarga la página: sale la misma búsqueda, ya resuelta por el servidor.
|
||||
3. En la pestaña *Red*, escribir una palabra seguida produce una sola petición.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Ordenar y paginar sin recargar](htmx-tables.md): el mismo patrón sobre una tabla con su
|
||||
paginador.
|
||||
- [Validar un campo al vuelo](htmx-validation.md).
|
||||
216
doc/v0.6/es/src/how-to/htmx-setup.md
Normal file
216
doc/v0.6/es/src/how-to/htmx-setup.md
Normal file
|
|
@ -0,0 +1,216 @@
|
|||
# Añadir HTMX a una aplicación
|
||||
|
||||
**Objetivo:** que tus páginas carguen [HTMX](https://htmx.org), que sus elementos pidan fragmentos
|
||||
de HTML al servidor y que tus rutas sepan responderlos.
|
||||
|
||||
Si es tu primer contacto con HTMX, el tutorial [Tareas del huerto con
|
||||
HTMX](../tutorials/htmx-tasks.md) lo presenta paso a paso. Esta guía reúne lo esencial para
|
||||
cualquier aplicación.
|
||||
|
||||
## 1. Declara la extensión
|
||||
|
||||
Añade `pagetop-htmx` a `Cargo.toml`:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
pagetop-htmx = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
||||
```
|
||||
|
||||
Y declárala como dependencia de tu extensión:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
pub struct MyApp;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for MyApp {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_htmx::Htmx]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
No hace falta nada más: la extensión añade el *script* de HTMX 2 a **todas** las páginas, con
|
||||
`defer`, y lo sirve desde el propio binario. No hay que descargar nada ni configurar una CDN.
|
||||
|
||||
## 2. Escribe atributos `hx-*` en `html!`
|
||||
|
||||
Los atributos de HTMX se escriben en `html!` como cualquier otro:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Html {
|
||||
Html::with(|_| html! {
|
||||
button hx-get="/time" hx-target="#time" { "What time is it?" }
|
||||
span id="time" {}
|
||||
})
|
||||
# }
|
||||
```
|
||||
|
||||
Al pulsar el botón, HTMX hace `GET /time` y pone la respuesta dentro de `#time`. Los atributos
|
||||
principales:
|
||||
|
||||
| Atributo | Qué indica | Por defecto |
|
||||
|---|---|---|
|
||||
| `hx-get`, `hx-post`, `hx-put`, `hx-patch`, `hx-delete` | Método y URL de la petición | - |
|
||||
| `hx-trigger` | Qué evento la lanza | `click`; `change` en campos; `submit` en formularios |
|
||||
| `hx-target` | Dónde va la respuesta (selector CSS, `this`, `closest tr`...) | El propio elemento |
|
||||
| `hx-swap` | Cómo se coloca | `innerHTML`: sustituye el contenido |
|
||||
|
||||
La lista completa está en la [referencia de HTMX](../reference/htmx.md).
|
||||
|
||||
## 3. Ponlos en componentes con `with_prop()`
|
||||
|
||||
Los componentes no conocen HTMX, pero todos aceptan atributos con `with_prop()`. El módulo `hx` de
|
||||
`pagetop-htmx` tiene una constante para cada atributo y para sus valores habituales:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
|
||||
# fn f() -> Button {
|
||||
Button::plain(Lc::n("What time is it?"))
|
||||
.with_prop(PropsOp::set(hx::GET, "/time"))
|
||||
.with_prop(PropsOp::set(hx::TARGET, "#time"))
|
||||
.with_prop(PropsOp::set(hx::SWAP, hx::swap::INNER_HTML))
|
||||
# }
|
||||
```
|
||||
|
||||
Con las constantes, una errata como `hx::GTE` no compila; escrita como texto, `"hx-gte"` fallaría
|
||||
en silencio en el navegador.
|
||||
|
||||
## 4. Responde con un fragmento
|
||||
|
||||
Una ruta para HTMX devuelve **sólo el trozo de HTML** que va en el destino, no una página. Lo más
|
||||
sencillo es devolver `Markup`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
async fn time() -> Markup {
|
||||
html! { (Utc::now().format("%H:%M:%S")) " UTC" }
|
||||
}
|
||||
```
|
||||
|
||||
Si además necesitas cabeceras de HTMX (cambiar el destino, disparar eventos, redirigir...),
|
||||
devuelve un `HtmxResponse`. Lo verás en [Dirigir al navegador desde el
|
||||
servidor](htmx-responses.md):
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
|
||||
async fn time() -> HtmxResponse {
|
||||
HtmxResponse::new(html! { (Utc::now().format("%H:%M:%S")) " UTC" })
|
||||
.trigger("timeShown")
|
||||
}
|
||||
```
|
||||
|
||||
## 5. Renderiza componentes en un fragmento
|
||||
|
||||
Fuera de una `Page`, un componente se renderiza con un `Context` creado a partir de la petición. El
|
||||
contexto aporta el idioma, el tema y las rutas, así que el fragmento sale igual que dentro de la
|
||||
página:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
|
||||
async fn notice(request: HttpRequest) -> HtmxResponse {
|
||||
let mut cx = Context::new(request);
|
||||
let mut badge = Badge::success(Lc::n("Saved"));
|
||||
HtmxResponse::new(badge.render(&mut cx).await)
|
||||
}
|
||||
```
|
||||
|
||||
> **Los recursos de un componente no viajan en un fragmento.** Si un componente añade su hoja de
|
||||
> estilos o su *script* al contexto, en una página acaban en el `<head>`; en un fragmento suelto no
|
||||
> hay `<head>` donde ponerlos. Asegúrate de que la página que recibe el fragmento ya los carga, por
|
||||
> ejemplo usando ese mismo componente en ella o añadiéndolos con `with_assets()`.
|
||||
|
||||
## 6. Una ruta, dos respuestas
|
||||
|
||||
Cuando la misma URL puede pedirse con HTMX (para un fragmento) o directamente (al recargar, desde
|
||||
un enlace compartido o sin JavaScript), comprueba quién llama con `is_htmx()`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
|
||||
async fn plants(request: HttpRequest) -> Response {
|
||||
let list = html! { ul { li { "Tomato" } li { "Pepper" } } };
|
||||
if request.is_htmx() {
|
||||
HtmxResponse::new(list).into_response()
|
||||
} else {
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("Plants"))
|
||||
.with_child(Html::with(move |_| list.clone()))
|
||||
.render()
|
||||
.await
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`is_htmx()` lee la cabecera `HX-Request` que HTMX añade a sus peticiones. El trait
|
||||
`HtmxRequestExt` también ofrece `hx_target()`, `hx_trigger_id()`, `is_boosted()`... para leer las
|
||||
demás.
|
||||
|
||||
## El ejemplo completo
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
|
||||
struct Clock;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Clock {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_htmx::Htmx]
|
||||
}
|
||||
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router
|
||||
.route("/", web::get(home))
|
||||
.route("/time", web::get(time))
|
||||
}
|
||||
}
|
||||
|
||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("Clock"))
|
||||
.with_child(
|
||||
Button::plain(Lc::n("What time is it?"))
|
||||
.with_prop(PropsOp::set(hx::GET, "/time"))
|
||||
.with_prop(PropsOp::set(hx::TARGET, "#time")),
|
||||
)
|
||||
.with_child(Html::with(|_| html! { p id="time" { "Not asked yet." } }))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
async fn time(request: HttpRequest) -> HtmxResponse {
|
||||
let mut cx = Context::new(request);
|
||||
let mut badge = Badge::info(Lc::n(Utc::now().format("%H:%M:%S UTC").to_string()));
|
||||
HtmxResponse::new(badge.render(&mut cx).await)
|
||||
}
|
||||
|
||||
#[pagetop::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
Application::prepare(&Clock).await.run().await
|
||||
}
|
||||
```
|
||||
|
||||
## Comprueba
|
||||
|
||||
1. Arranca la aplicación y abre <http://localhost:8080>.
|
||||
2. Pulsa el botón: la hora aparece en una etiqueta, sin recargar.
|
||||
3. En las herramientas de desarrollo del navegador (pestaña *Red*), la petición a `/time` lleva la
|
||||
cabecera `HX-Request: true` y la respuesta es una sola etiqueta `<span>`.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Cargar contenido bajo demanda](htmx-load.md): al pulsar, al cargar la página o al hacerse
|
||||
visible.
|
||||
- [Probar rutas y componentes](testing.md): cómo probar una ruta de HTMX sin navegador.
|
||||
- [HTML por la red: por qué HTMX](../explanation/htmx.md).
|
||||
252
doc/v0.6/es/src/how-to/htmx-tables.md
Normal file
252
doc/v0.6/es/src/how-to/htmx-tables.md
Normal file
|
|
@ -0,0 +1,252 @@
|
|||
# Ordenar y paginar sin recargar
|
||||
|
||||
**Objetivo:** una tabla que se ordena al pulsar sus cabeceras y se pagina con su `Pager`, sustituyendo
|
||||
sólo la tabla, con URLs reales en la barra de direcciones y sin perder nada si JavaScript no está
|
||||
disponible.
|
||||
|
||||
Partimos de una aplicación con [HTMX añadido](htmx-setup.md) y de lo visto en [Mostrar tablas
|
||||
ordenables y paginadas](tables.md): `Table`, `SortLink` y `Pager` ya generan enlaces normales que
|
||||
funcionan sin HTMX. Aquí sólo se les añade el comportamiento.
|
||||
|
||||
## 1. Un contenedor como destino
|
||||
|
||||
La tabla y su paginador van juntos en un `Container` con `id`. Ése es el destino de todas las
|
||||
peticiones: al ordenar o cambiar de página, se sustituyen los dos.
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn table() -> Table { Table::new() }
|
||||
# fn pager() -> Pager { Pager::new() }
|
||||
# fn f() -> Container {
|
||||
Container::new()
|
||||
.with_id("harvests")
|
||||
.with_child(table())
|
||||
.with_child(pager())
|
||||
# }
|
||||
```
|
||||
|
||||
## 2. Cabeceras que ordenan con HTMX
|
||||
|
||||
`hx_table::sort_link()` crea el enlace de una cabecera con los atributos de HTMX ya puestos: hace
|
||||
`GET` a la misma URL del enlace, sustituye el destino, vuelve arriba y actualiza la barra de
|
||||
direcciones. Sólo hay que darle la URL, el destino y la dirección actual de esa columna:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
|
||||
fn sortable(cx: &Context, field: &str, label: Lc, sort: &str, dir: SortDir) -> table::Column {
|
||||
// `Some` only if the table is sorted by this column right now.
|
||||
let active = (field == sort).then_some(dir);
|
||||
let href = cx
|
||||
.route("/harvests")
|
||||
.with_param("sort", field)
|
||||
.with_param("dir", SortDir::next_for(active));
|
||||
table::Column::new(label).with_sort(hx_table::sort_link(href, "#harvests", active))
|
||||
}
|
||||
```
|
||||
|
||||
`SortDir::next_for()` calcula la dirección del siguiente clic: ascendente si la columna no ordena
|
||||
ahora, la contraria si ya lo hace. `cx.route()` conserva el parámetro `?lang=` cuando lo hay.
|
||||
|
||||
## 3. Un paginador que navega con HTMX
|
||||
|
||||
`Pager` no necesita atributos en cada enlace: con `hx-boost` en su `<nav>`, HTMX convierte en
|
||||
peticiones AJAX todos los enlaces que contiene, reutilizando su `href`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
|
||||
# fn f(sort: &str, dir: SortDir, page: u64, total: u64) -> Pager {
|
||||
Pager::new()
|
||||
.with_base_path("/harvests")
|
||||
.with_extra_query("sort", sort)
|
||||
.with_extra_query("dir", dir.as_str())
|
||||
.with_current_page(page)
|
||||
.with_items_per_page(5)
|
||||
.with_total_items(total)
|
||||
.with_prop(PropsOp::set(hx::BOOST, "true"))
|
||||
.with_prop(PropsOp::set(hx::TARGET, "#harvests"))
|
||||
.with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML_SCROLL_TOP))
|
||||
.with_prop(PropsOp::set(hx::PUSH_URL, "true"))
|
||||
# }
|
||||
```
|
||||
|
||||
`with_extra_query()` mantiene el orden al cambiar de página.
|
||||
|
||||
## 4. La ruta: página entera o sólo la tabla
|
||||
|
||||
Una sola ruta atiende todo. Lee el estado de la URL, construye el contenedor y lo devuelve solo (con
|
||||
HTMX) o dentro de una página (sin HTMX, al recargar o desde un enlace compartido). En los dos casos
|
||||
usa un `Context`: el de la página, o uno creado a partir de la petición.
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# use pagetop_htmx::prelude::*;
|
||||
# fn harvests(_: &Context, _: &str, _: SortDir, _: u64) -> Container { Container::new() }
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ListQuery {
|
||||
sort: Option<String>,
|
||||
dir: Option<String>,
|
||||
page: Option<u64>,
|
||||
}
|
||||
|
||||
async fn list(request: HttpRequest, web::Query(query): web::Query<ListQuery>) -> Response {
|
||||
let sort = query.sort.as_deref().unwrap_or("crop");
|
||||
let dir = SortDir::from_query(query.dir.as_deref());
|
||||
let page = query.page.unwrap_or(1).max(1);
|
||||
|
||||
if request.is_htmx() {
|
||||
let mut cx = Context::new(request);
|
||||
let mut table = harvests(&cx, sort, dir, page);
|
||||
return HtmxResponse::new(table.render(&mut cx).await).into_response();
|
||||
}
|
||||
let mut full = Page::new(request).with_title(Lc::n("Harvests"));
|
||||
let table = harvests(full.context(), sort, dir, page);
|
||||
full.with_child(table).render().await.into_response()
|
||||
}
|
||||
```
|
||||
|
||||
## El ejemplo completo
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
use serde::Deserialize;
|
||||
|
||||
const PER_PAGE: u64 = 5;
|
||||
|
||||
struct Harvest {
|
||||
crop: &'static str,
|
||||
plot: &'static str,
|
||||
kilos: u32,
|
||||
}
|
||||
|
||||
const HARVESTS: &[Harvest] = &[
|
||||
Harvest { crop: "Tomato", plot: "A1", kilos: 42 },
|
||||
Harvest { crop: "Lettuce", plot: "A2", kilos: 12 },
|
||||
Harvest { crop: "Pepper", plot: "B1", kilos: 18 },
|
||||
Harvest { crop: "Courgette", plot: "B2", kilos: 35 },
|
||||
Harvest { crop: "Onion", plot: "A1", kilos: 20 },
|
||||
Harvest { crop: "Potato", plot: "C1", kilos: 60 },
|
||||
Harvest { crop: "Bean", plot: "C2", kilos: 9 },
|
||||
Harvest { crop: "Pumpkin", plot: "B1", kilos: 51 },
|
||||
Harvest { crop: "Chard", plot: "A2", kilos: 14 },
|
||||
Harvest { crop: "Carrot", plot: "C1", kilos: 16 },
|
||||
Harvest { crop: "Garlic", plot: "C2", kilos: 7 },
|
||||
Harvest { crop: "Strawberry", plot: "B2", kilos: 11 },
|
||||
];
|
||||
|
||||
struct HarvestLog;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for HarvestLog {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_htmx::Htmx]
|
||||
}
|
||||
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router
|
||||
.route("/", web::get(|| async { Redirect::see_other("/harvests") }))
|
||||
.route("/harvests", web::get(list))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ListQuery {
|
||||
sort: Option<String>,
|
||||
dir: Option<String>,
|
||||
page: Option<u64>,
|
||||
}
|
||||
|
||||
async fn list(request: HttpRequest, web::Query(query): web::Query<ListQuery>) -> Response {
|
||||
let sort = query.sort.as_deref().unwrap_or("crop");
|
||||
let dir = SortDir::from_query(query.dir.as_deref());
|
||||
let page = query.page.unwrap_or(1).max(1);
|
||||
|
||||
if request.is_htmx() {
|
||||
let mut cx = Context::new(request);
|
||||
let mut table = harvests(&cx, sort, dir, page);
|
||||
return HtmxResponse::new(table.render(&mut cx).await).into_response();
|
||||
}
|
||||
let mut full = Page::new(request).with_title(Lc::n("Harvests"));
|
||||
let table = harvests(full.context(), sort, dir, page);
|
||||
full.with_child(table).render().await.into_response()
|
||||
}
|
||||
|
||||
fn harvests(cx: &Context, sort: &str, dir: SortDir, page: u64) -> Container {
|
||||
let mut rows: Vec<&Harvest> = HARVESTS.iter().collect();
|
||||
match sort {
|
||||
"kilos" => rows.sort_by_key(|harvest| harvest.kilos),
|
||||
_ => rows.sort_by_key(|harvest| harvest.crop),
|
||||
}
|
||||
if dir == SortDir::Desc {
|
||||
rows.reverse();
|
||||
}
|
||||
|
||||
let mut table = Table::new()
|
||||
.with_column(sortable(cx, "crop", Lc::n("Crop"), sort, dir))
|
||||
.with_column(table::Column::new(Lc::n("Plot")))
|
||||
.with_column(sortable(cx, "kilos", Lc::n("Kilos"), sort, dir));
|
||||
let skip = ((page - 1) * PER_PAGE) as usize;
|
||||
for harvest in rows.iter().skip(skip).take(PER_PAGE as usize) {
|
||||
table = table.with_row(
|
||||
table::Row::new()
|
||||
.with_cell(harvest.crop)
|
||||
.with_cell(harvest.plot)
|
||||
.with_cell(harvest.kilos.to_string()),
|
||||
);
|
||||
}
|
||||
|
||||
let pager = Pager::new()
|
||||
.with_base_path("/harvests")
|
||||
.with_extra_query("sort", sort)
|
||||
.with_extra_query("dir", dir.as_str())
|
||||
.with_current_page(page)
|
||||
.with_items_per_page(PER_PAGE)
|
||||
.with_total_items(rows.len() as u64)
|
||||
.with_prop(PropsOp::set(hx::BOOST, "true"))
|
||||
.with_prop(PropsOp::set(hx::TARGET, "#harvests"))
|
||||
.with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML_SCROLL_TOP))
|
||||
.with_prop(PropsOp::set(hx::PUSH_URL, "true"));
|
||||
|
||||
Container::new()
|
||||
.with_id("harvests")
|
||||
.with_child(table)
|
||||
.with_child(pager)
|
||||
}
|
||||
|
||||
fn sortable(cx: &Context, field: &str, label: Lc, sort: &str, dir: SortDir) -> table::Column {
|
||||
// `Some` only if the table is sorted by this column right now.
|
||||
let active = (field == sort).then_some(dir);
|
||||
let href = cx
|
||||
.route("/harvests")
|
||||
.with_param("sort", field)
|
||||
.with_param("dir", SortDir::next_for(active));
|
||||
table::Column::new(label).with_sort(hx_table::sort_link(href, "#harvests", active))
|
||||
}
|
||||
|
||||
#[pagetop::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
Application::prepare(&HarvestLog).await.run().await
|
||||
}
|
||||
```
|
||||
|
||||
## Comprueba
|
||||
|
||||
1. Abre <http://localhost:8080/harvests>: cinco cosechas ordenadas por cultivo y un paginador de
|
||||
tres páginas.
|
||||
2. Pulsa la cabecera *Kilos*: la tabla se ordena de menos a más; púlsala otra vez, de más a menos.
|
||||
La barra de direcciones refleja cada estado (`?sort=kilos&dir=desc`).
|
||||
3. Ve a la página 2: se conserva el orden. Usa el botón *Atrás* del navegador y recarga: la URL
|
||||
muestra exactamente lo que había.
|
||||
4. Desactiva JavaScript y repite: todo funciona igual, con recargas de página completas.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Buscar mientras se escribe](htmx-search.md): añade un buscador que filtre la misma tabla.
|
||||
- [Cargar más al hacer *scroll*](htmx-infinite.md): la alternativa al paginador para listas que se
|
||||
leen de arriba abajo.
|
||||
315
doc/v0.6/es/src/how-to/htmx-validation.md
Normal file
315
doc/v0.6/es/src/how-to/htmx-validation.md
Normal file
|
|
@ -0,0 +1,315 @@
|
|||
# Validar un campo al vuelo
|
||||
|
||||
**Objetivo:** avisar de un error mientras el usuario rellena el formulario (un nombre de usuario ya
|
||||
ocupado, por ejemplo) y, al enviarlo, mostrar los errores **dentro** del formulario sin recargar la
|
||||
página ni perder lo escrito.
|
||||
|
||||
Partimos de una aplicación con [HTMX añadido](htmx-setup.md) y de lo visto en [Crear y procesar
|
||||
formularios](forms.md).
|
||||
|
||||
## 1. El formulario y su validación
|
||||
|
||||
Un formulario para unirse al huerto, con su validación en el servidor. Una función construye el
|
||||
formulario con los valores recibidos, para poder repetirlo sin perder lo escrito:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
use serde::Deserialize;
|
||||
|
||||
const TAKEN: &[&str] = &["admin", "ana", "luke"];
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(default)]
|
||||
struct JoinData {
|
||||
username: String,
|
||||
email: String,
|
||||
}
|
||||
|
||||
fn validate(data: &JoinData) -> Option<Lc> {
|
||||
let username = data.username.trim();
|
||||
if username.chars().count() < 3 {
|
||||
Some(Lc::n("The username needs at least 3 characters."))
|
||||
} else if TAKEN.contains(&username) {
|
||||
Some(Lc::n("That username is already taken."))
|
||||
} else if !data.email.contains('@') {
|
||||
Some(Lc::n("Write a valid email."))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`#[serde(default)]` permite deserializar el formulario aunque falte algún campo, lo que vendrá bien
|
||||
en el paso 2.
|
||||
|
||||
## 2. Comprobar un campo mientras se escribe
|
||||
|
||||
Los atributos `hx-*` de un campo se ponen con su `with_prop()`. El campo hace un `POST` a
|
||||
`/join/check` cuando el usuario deja de escribir medio segundo, y la respuesta va a `#username-check`,
|
||||
justo debajo:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
# #[derive(Default)]
|
||||
# struct JoinData { username: String, email: String }
|
||||
|
||||
fn username_field(data: &JoinData) -> form::input::Field {
|
||||
form::input::Field::text()
|
||||
.with_name("username")
|
||||
.with_value(&data.username)
|
||||
.with_label(Lc::n("Username"))
|
||||
.with_required(true)
|
||||
.with_prop(PropsOp::set(hx::POST, "/join/check"))
|
||||
.with_prop(PropsOp::set(hx::TRIGGER, "input delay:500ms"))
|
||||
.with_prop(PropsOp::set(hx::TARGET, "#username-check"))
|
||||
.with_prop(PropsOp::set(hx::SWAP, hx::swap::INNER_HTML))
|
||||
}
|
||||
```
|
||||
|
||||
`hx-swap` parece innecesario, porque `innerHTML` es el valor por defecto. Pero los atributos de
|
||||
HTMX **se heredan**: en el paso 3 el formulario tendrá `hx-swap="outerHTML"`, y el campo lo
|
||||
heredaría, así que la etiqueta sustituiría al propio `#username-check` y la siguiente comprobación
|
||||
ya no tendría dónde ir.
|
||||
|
||||
Una petición que no es `GET` incluye **todos** los campos del formulario que la contiene, así que la
|
||||
ruta recibe el mismo `JoinData`. Sólo mira el nombre:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# use pagetop_htmx::prelude::*;
|
||||
# const TAKEN: &[&str] = &[];
|
||||
# #[derive(Default, serde::Deserialize)]
|
||||
# #[serde(default)]
|
||||
# struct JoinData { username: String }
|
||||
async fn check_username(request: HttpRequest, web::Form(data): web::Form<JoinData>) -> HtmxResponse {
|
||||
let username = data.username.trim();
|
||||
if username.is_empty() {
|
||||
return HtmxResponse::empty();
|
||||
}
|
||||
let mut badge = if TAKEN.contains(&username) {
|
||||
Badge::severe(Lc::n("Already taken"))
|
||||
} else {
|
||||
Badge::success(Lc::n("Available"))
|
||||
};
|
||||
HtmxResponse::new(badge.render(&mut Context::new(request)).await)
|
||||
}
|
||||
```
|
||||
|
||||
> **Responde con 200, también a los errores.** Por defecto, HTMX **no coloca** las respuestas con
|
||||
> código 4xx o 5xx. Un error de validación es una respuesta normal que el usuario debe ver.
|
||||
|
||||
## 3. Errores dentro del formulario al enviarlo
|
||||
|
||||
Para que el formulario completo se envíe con HTMX y se sustituya por la respuesta, el formulario y
|
||||
sus mensajes van en un contenedor con `id`, y ése es el destino:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# use pagetop_htmx::prelude::*;
|
||||
# #[derive(Default)]
|
||||
# struct JoinData { username: String, email: String }
|
||||
# fn username_field(_: &JoinData) -> form::input::Field { form::input::Field::text() }
|
||||
fn join_box(data: &JoinData) -> Container {
|
||||
Container::new().with_id("join").with_child(Messages::new()).with_child(
|
||||
Form::new()
|
||||
.with_action("/join")
|
||||
.with_prop(PropsOp::set(hx::POST, "/join"))
|
||||
.with_prop(PropsOp::set(hx::TARGET, "#join"))
|
||||
.with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML))
|
||||
.with_child(username_field(data))
|
||||
.with_child(Html::with(|_| html! { div id="username-check" {} }))
|
||||
.with_child(
|
||||
form::input::Field::email()
|
||||
.with_name("email")
|
||||
.with_value(&data.email)
|
||||
.with_label(Lc::n("Email")),
|
||||
)
|
||||
.with_child(Button::submit(Lc::n("Join"))),
|
||||
)
|
||||
}
|
||||
|
||||
fn welcome_box(username: &str) -> Container {
|
||||
let username = username.trim().to_string();
|
||||
Container::new()
|
||||
.with_id("join")
|
||||
.with_child(Html::with(move |_| html! { p { "Welcome to the garden, " (username) "!" } }))
|
||||
}
|
||||
```
|
||||
|
||||
La ruta del envío valida y responde con uno u otro contenedor. Con HTMX, sólo el contenedor; sin
|
||||
JavaScript, una página entera con él. El error viaja como un mensaje del contexto, que muestra
|
||||
`Messages`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# use pagetop_htmx::prelude::*;
|
||||
# #[derive(Default, serde::Deserialize)]
|
||||
# struct JoinData { username: String }
|
||||
# fn validate(_: &JoinData) -> Option<Lc> { None }
|
||||
# fn join_box(_: &JoinData) -> Container { Container::new() }
|
||||
# fn welcome_box(_: &str) -> Container { Container::new() }
|
||||
async fn join(request: HttpRequest, web::Form(data): web::Form<JoinData>) -> Response {
|
||||
let error = validate(&data);
|
||||
let mut content = match error {
|
||||
Some(_) => join_box(&data),
|
||||
None => welcome_box(&data.username),
|
||||
};
|
||||
if request.is_htmx() {
|
||||
let mut cx = Context::new(request);
|
||||
if let Some(error) = error {
|
||||
cx.push_message(MessageLevel::Error, error);
|
||||
}
|
||||
return HtmxResponse::new(content.render(&mut cx).await).into_response();
|
||||
}
|
||||
let mut page = Page::new(request).with_child(content);
|
||||
if let Some(error) = error {
|
||||
page.context().push_message(MessageLevel::Error, error);
|
||||
}
|
||||
page.render().await.into_response()
|
||||
}
|
||||
```
|
||||
|
||||
## El ejemplo completo
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
use serde::Deserialize;
|
||||
|
||||
const TAKEN: &[&str] = &["admin", "ana", "luke"];
|
||||
|
||||
struct JoinTheGarden;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for JoinTheGarden {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_htmx::Htmx]
|
||||
}
|
||||
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router
|
||||
.route("/", web::get(home))
|
||||
.route("/join", web::post(join))
|
||||
.route("/join/check", web::post(check_username))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(default)]
|
||||
struct JoinData {
|
||||
username: String,
|
||||
email: String,
|
||||
}
|
||||
|
||||
fn validate(data: &JoinData) -> Option<Lc> {
|
||||
let username = data.username.trim();
|
||||
if username.chars().count() < 3 {
|
||||
Some(Lc::n("The username needs at least 3 characters."))
|
||||
} else if TAKEN.contains(&username) {
|
||||
Some(Lc::n("That username is already taken."))
|
||||
} else if !data.email.contains('@') {
|
||||
Some(Lc::n("Write a valid email."))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn username_field(data: &JoinData) -> form::input::Field {
|
||||
form::input::Field::text()
|
||||
.with_name("username")
|
||||
.with_value(&data.username)
|
||||
.with_label(Lc::n("Username"))
|
||||
.with_required(true)
|
||||
.with_prop(PropsOp::set(hx::POST, "/join/check"))
|
||||
.with_prop(PropsOp::set(hx::TRIGGER, "input delay:500ms"))
|
||||
.with_prop(PropsOp::set(hx::TARGET, "#username-check"))
|
||||
.with_prop(PropsOp::set(hx::SWAP, hx::swap::INNER_HTML))
|
||||
}
|
||||
|
||||
fn join_box(data: &JoinData) -> Container {
|
||||
Container::new().with_id("join").with_child(Messages::new()).with_child(
|
||||
Form::new()
|
||||
.with_action("/join")
|
||||
.with_prop(PropsOp::set(hx::POST, "/join"))
|
||||
.with_prop(PropsOp::set(hx::TARGET, "#join"))
|
||||
.with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML))
|
||||
.with_child(username_field(data))
|
||||
.with_child(Html::with(|_| html! { div id="username-check" {} }))
|
||||
.with_child(
|
||||
form::input::Field::email()
|
||||
.with_name("email")
|
||||
.with_value(&data.email)
|
||||
.with_label(Lc::n("Email")),
|
||||
)
|
||||
.with_child(Button::submit(Lc::n("Join"))),
|
||||
)
|
||||
}
|
||||
|
||||
fn welcome_box(username: &str) -> Container {
|
||||
let username = username.trim().to_string();
|
||||
Container::new()
|
||||
.with_id("join")
|
||||
.with_child(Html::with(move |_| html! { p { "Welcome to the garden, " (username) "!" } }))
|
||||
}
|
||||
|
||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("Join the garden"))
|
||||
.with_child(join_box(&JoinData::default()))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
async fn check_username(request: HttpRequest, web::Form(data): web::Form<JoinData>) -> HtmxResponse {
|
||||
let username = data.username.trim();
|
||||
if username.is_empty() {
|
||||
return HtmxResponse::empty();
|
||||
}
|
||||
let mut badge = if TAKEN.contains(&username) {
|
||||
Badge::severe(Lc::n("Already taken"))
|
||||
} else {
|
||||
Badge::success(Lc::n("Available"))
|
||||
};
|
||||
HtmxResponse::new(badge.render(&mut Context::new(request)).await)
|
||||
}
|
||||
|
||||
async fn join(request: HttpRequest, web::Form(data): web::Form<JoinData>) -> Response {
|
||||
let error = validate(&data);
|
||||
let mut content = match error {
|
||||
Some(_) => join_box(&data),
|
||||
None => welcome_box(&data.username),
|
||||
};
|
||||
if request.is_htmx() {
|
||||
let mut cx = Context::new(request);
|
||||
if let Some(error) = error {
|
||||
cx.push_message(MessageLevel::Error, error);
|
||||
}
|
||||
return HtmxResponse::new(content.render(&mut cx).await).into_response();
|
||||
}
|
||||
let mut page = Page::new(request).with_child(content);
|
||||
if let Some(error) = error {
|
||||
page.context().push_message(MessageLevel::Error, error);
|
||||
}
|
||||
page.render().await.into_response()
|
||||
}
|
||||
|
||||
#[pagetop::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
Application::prepare(&JoinTheGarden).await.run().await
|
||||
}
|
||||
```
|
||||
|
||||
## Comprueba
|
||||
|
||||
1. Escribe `ana` en el nombre de usuario y espera: aparece «Already taken». Cambia a `marta`:
|
||||
«Available».
|
||||
2. Envía el formulario con `ana`: el error aparece encima del formulario y lo escrito sigue ahí.
|
||||
3. Corrige el nombre, escribe un correo y envía: el formulario se sustituye por la bienvenida.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Editar en línea](htmx-edit.md): el mismo intercambio de formulario y vista, sobre un dato
|
||||
existente.
|
||||
- [Dirigir al navegador desde el servidor](htmx-responses.md): cambiar el destino de la respuesta
|
||||
según el resultado.
|
||||
136
doc/v0.6/es/src/how-to/layout.md
Normal file
136
doc/v0.6/es/src/how-to/layout.md
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
# Maquetar con Flex y Grid
|
||||
|
||||
**Objetivo:** colocar componentes en filas, columnas o rejillas, y adaptarlos al tamaño de la
|
||||
pantalla, sin escribir CSS.
|
||||
|
||||
Para colocar componentes en filas, columnas o rejillas no hace falta escribir CSS: `Flex` y `Grid`
|
||||
generan las reglas por ti, y funcionan con cualquier tema.
|
||||
|
||||
## Flex: filas y columnas
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn item(t: &'static str) -> Html { Html::with(move |_| html! { div { (t) } }) }
|
||||
# fn f() -> Flex {
|
||||
Flex::new()
|
||||
.with_justify(flex::ContentJustify::SpaceBetween)
|
||||
.with_align(align::Items::Center)
|
||||
.with_gap(align::Gap::Both(UnitValue::RelRem(1.0)))
|
||||
.with_child(item("One"))
|
||||
.with_child(item("Two"))
|
||||
.with_child(item("Three"))
|
||||
# }
|
||||
```
|
||||
|
||||
| Método | Controla |
|
||||
|---|---|
|
||||
| `with_direction()` | `Row`, `RowReverse`, `Column` o `ColumnReverse` |
|
||||
| `with_justify()` | Reparto en el eje principal: `Start`, `Center`, `End`, `SpaceBetween`... |
|
||||
| `with_align()` | Alineación en el eje transversal: `Start`, `Center`, `End`, `Stretch`, `Baseline` |
|
||||
| `with_wrap()` | Si los elementos saltan de línea |
|
||||
| `with_gap()` | Separación entre elementos |
|
||||
|
||||
Cada hijo puede ajustarse por separado con `FlexItem`, que se pasa a su `with_prop()`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Flex {
|
||||
Flex::new()
|
||||
.with_child(Block::new().with_title(Lc::n("Menu")))
|
||||
.with_child(
|
||||
Block::new()
|
||||
.with_title(Lc::n("Content"))
|
||||
.with_prop(FlexItem::new().with_grow(flex::ItemGrow::Is1)),
|
||||
)
|
||||
.with_child(
|
||||
Block::new()
|
||||
.with_title(Lc::n("Help"))
|
||||
.with_prop(FlexItem::push_end()),
|
||||
)
|
||||
# }
|
||||
```
|
||||
|
||||
`FlexItem::push_end()` empuja el elemento al final de la fila. Es la forma habitual de alinear a
|
||||
la derecha el último grupo de un menú.
|
||||
|
||||
## Grid: rejillas
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn item(t: &'static str) -> Html { Html::with(move |_| html! { div { (t) } }) }
|
||||
# fn f() -> Grid {
|
||||
Grid::new()
|
||||
.with_columns(grid::Tracks::repeat(3, grid::AxisTrack::Fraction(1.0)))
|
||||
.with_gap(align::Gap::Both(UnitValue::RelRem(1.0)))
|
||||
.with_child(item("A"))
|
||||
.with_child(item("B"))
|
||||
.with_child(item("C"))
|
||||
.with_child(item("D"))
|
||||
# }
|
||||
```
|
||||
|
||||
Tres columnas iguales (`1fr` cada una). Las pistas se combinan a voluntad:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Grid {
|
||||
// A fixed 240 px column and another one that takes the rest.
|
||||
Grid::new().with_columns(
|
||||
grid::Tracks::new()
|
||||
.with_track(grid::AxisTrack::Fixed(UnitValue::Px(240)))
|
||||
.with_track(grid::AxisTrack::Fraction(1.0)),
|
||||
)
|
||||
# }
|
||||
```
|
||||
|
||||
Un hijo puede ocupar varias celdas con `GridItem`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Block {
|
||||
Block::new()
|
||||
.with_title(Lc::n("Featured"))
|
||||
.with_prop(GridItem::new().with_column(grid::ItemPlacement::Span(2)))
|
||||
# }
|
||||
```
|
||||
|
||||
## Diseño *responsive*
|
||||
|
||||
Casi todos los métodos tienen una variante `_at()` que se aplica **a partir de** un punto de
|
||||
corte (el diseño es *mobile-first*: lo que no lleva `_at()` vale para todos los tamaños):
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Flex {
|
||||
// A column on mobile; a row from medium screens on.
|
||||
Flex::new()
|
||||
.with_direction(flex::Direction::Column)
|
||||
.with_direction_at(Breakpoint::Md, flex::Direction::Row)
|
||||
# }
|
||||
```
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Grid {
|
||||
// One column on mobile, two on tablets and four on desktop.
|
||||
Grid::new()
|
||||
.with_columns(grid::Tracks::repeat(1, grid::AxisTrack::Fraction(1.0)))
|
||||
.with_columns_at(Breakpoint::Md, grid::Tracks::repeat(2, grid::AxisTrack::Fraction(1.0)))
|
||||
.with_columns_at(Breakpoint::Xl, grid::Tracks::repeat(4, grid::AxisTrack::Fraction(1.0)))
|
||||
# }
|
||||
```
|
||||
|
||||
Los puntos de corte son `Xs`, `Sm`, `Md`, `Lg`, `Xl`, `Xxl` y `Xxxl`. Sus anchos los decide el
|
||||
tema; por defecto son 576, 768, 992, 1200, 1400 y 1920 píxeles a partir de `Sm` (`Xs` no tiene
|
||||
mínimo).
|
||||
|
||||
## Comprueba
|
||||
|
||||
Estrecha la ventana del navegador: los elementos cambian de disposición al cruzar cada punto de
|
||||
corte. En las herramientas de desarrollo verás que cada `_at()` se ha convertido en una regla
|
||||
`@media`.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Añadir navegación](navigation.md).
|
||||
- [Crear un tema](themes.md): cómo un tema fija los anchos de los puntos de corte.
|
||||
150
doc/v0.6/es/src/how-to/localization.md
Normal file
150
doc/v0.6/es/src/how-to/localization.md
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
# Traducir la aplicación
|
||||
|
||||
**Objetivo:** mostrar cada texto en el idioma del visitante, con plurales correctos, y formatear
|
||||
fechas y horas según su idioma y su zona horaria.
|
||||
|
||||
PageTop traduce con [Fluent](https://projectfluent.org), el sistema de Mozilla: cada idioma tiene
|
||||
sus archivos `.ftl` con pares `key = text`, y las traducciones se integran en el binario al
|
||||
compilar.
|
||||
|
||||
## 1. Crea los archivos de traducción
|
||||
|
||||
Por defecto viven en `src/locale/`, en un directorio por idioma:
|
||||
|
||||
```text
|
||||
src/locale/
|
||||
├── en-US/
|
||||
│ └── app.ftl
|
||||
└── es-ES/
|
||||
└── app.ftl
|
||||
```
|
||||
|
||||
```text
|
||||
# src/locale/es-ES/app.ftl
|
||||
greeting = ¡Hola!
|
||||
welcome = Te damos la bienvenida, { $name }.
|
||||
notices = { $total ->
|
||||
[one] Tienes un aviso
|
||||
*[other] Tienes { $total } avisos
|
||||
}
|
||||
```
|
||||
|
||||
```text
|
||||
# src/locale/en-US/app.ftl
|
||||
greeting = Hello!
|
||||
welcome = Welcome, { $name }.
|
||||
notices = { $total ->
|
||||
[one] You have one notice
|
||||
*[other] You have { $total } notices
|
||||
}
|
||||
```
|
||||
|
||||
Fluent resuelve los plurales y las variantes de cada idioma en el propio archivo, sin lógica en el
|
||||
código.
|
||||
|
||||
## 2. Úsalos en el código
|
||||
|
||||
Declara el conjunto de traducciones una vez con `include_locales!`:
|
||||
|
||||
```rust
|
||||
# use pagetop::prelude::*;
|
||||
include_locales!(LOCALES_APP);
|
||||
```
|
||||
|
||||
Y crea textos con `Lc`:
|
||||
|
||||
| Constructor | Qué representa |
|
||||
|---|---|
|
||||
| `Lc::t("key", &LOCALES_APP)` | Traducción de tus archivos |
|
||||
| `Lc::l("key")` | Traducción de los archivos de PageTop |
|
||||
| `Lc::n("text")` | Texto literal, sin traducir |
|
||||
| `Lc::none()` | Ningún texto |
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
include_locales!(LOCALES_APP);
|
||||
|
||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_title(Lc::t("greeting", &LOCALES_APP))
|
||||
.with_child(Html::with(|cx| {
|
||||
let welcome = Lc::t("welcome", &LOCALES_APP).with_arg("name", "Ana");
|
||||
let notices = Lc::t("notices", &LOCALES_APP).with_number("total", 3);
|
||||
html! {
|
||||
h1 { (welcome.using(cx)) }
|
||||
p { (notices.using(cx)) }
|
||||
}
|
||||
}))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
```
|
||||
|
||||
- `with_arg()` rellena una variable; `with_number()` la rellena con un número, para que Fluent
|
||||
elija el plural correcto.
|
||||
- `using(cx)` devuelve el texto listo para insertarlo como **contenido** en `html!`.
|
||||
- `lookup(cx)` devuelve `Option<String>`. Úsalo para los **atributos** (`title`, `alt`,
|
||||
`placeholder`...), donde el texto se escapa como cualquier otro valor:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# include_locales!(LOCALES_APP);
|
||||
# fn f() -> Html {
|
||||
Html::with(|cx| {
|
||||
let title = Lc::t("greeting", &LOCALES_APP).lookup(cx);
|
||||
html! { button title=[title] { "?" } }
|
||||
})
|
||||
# }
|
||||
```
|
||||
|
||||
Los componentes reciben `Lc`, no cadenas: así cada visitante ve el texto en su idioma.
|
||||
|
||||
## 3. Decide qué idioma ve cada visitante
|
||||
|
||||
Por defecto, PageTop decide el idioma de cada petición en este orden:
|
||||
|
||||
1. El parámetro `?lang=` de la URL.
|
||||
2. El idioma preferido del usuario, si ha iniciado sesión y lo tiene.
|
||||
3. El idioma de la configuración (`[app] language`).
|
||||
4. La cabecera `Accept-Language` del navegador.
|
||||
5. El idioma de respaldo, `en-US`.
|
||||
|
||||
La clave `lang_negotiation` de `[app]` cambia la estrategia: `"NoQuery"` ignora `?lang=` y
|
||||
`"ConfigOnly"` usa sólo el idioma configurado. Los enlaces internos conservan `?lang=` solos (ver
|
||||
[Navegación](navigation.md#enlaces-que-conservan-el-idioma)).
|
||||
|
||||
PageTop trae sus propios textos en español (`es-ES`) e inglés (`en-US` y `en-GB`).
|
||||
|
||||
## 4. Formatea fechas y horas
|
||||
|
||||
El contexto formatea fechas con las convenciones del idioma y la zona horaria del visitante:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Html {
|
||||
Html::with(|cx| {
|
||||
let date = NaiveDate::from_ymd_opt(2026, 10, 12).unwrap();
|
||||
let now = Utc::now();
|
||||
html! {
|
||||
p { "Published on " (cx.format_date(date, DateFormat::Long)) }
|
||||
p { "Updated: " (cx.format_datetime(now, DateFormat::Short, TimeFormat::Short)) }
|
||||
}
|
||||
})
|
||||
# }
|
||||
```
|
||||
|
||||
Los formatos son `Short`, `Medium`, `Long`, `Iso` y `Custom("...")`. La zona horaria se configura
|
||||
con `[app] timezone`.
|
||||
|
||||
## Comprueba
|
||||
|
||||
Abre una página con `?lang=es` y con `?lang=en`: los textos cambian, y los plurales cambian con el
|
||||
número. Si a un idioma le falta una clave, se usa la del idioma de respaldo, `en-US`; si no existe
|
||||
en ninguno, el texto sale vacío. Una [prueba](testing.md) que busque los textos en cada idioma lo
|
||||
detecta antes que los usuarios.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Añadir navegación](navigation.md#enlaces-que-conservan-el-idioma): enlaces que conservan el
|
||||
idioma elegido.
|
||||
- [Probar rutas y componentes](testing.md): comprobar las traducciones en una prueba.
|
||||
101
doc/v0.6/es/src/how-to/logging.md
Normal file
101
doc/v0.6/es/src/how-to/logging.md
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
# Registrar trazas
|
||||
|
||||
**Objetivo:** dejar constancia de lo que pasa en la aplicación, con el nivel de detalle adecuado
|
||||
en cada entorno, por el terminal o en archivos con rotación.
|
||||
|
||||
PageTop usa [tracing](https://docs.rs/tracing), y lo expone en el módulo `trace` del preludio.
|
||||
|
||||
## 1. Escribe trazas
|
||||
|
||||
Hay una macro por nivel, de más a menos grave: `error!`, `warn!`, `info!`, `debug!` y `trace!`.
|
||||
Admiten el formato de `format!`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f(order: u32, error: &str) {
|
||||
trace::info!("Order {order} received");
|
||||
trace::warn!("Low stock for order {order}");
|
||||
trace::error!("Could not charge order {order}: {error}");
|
||||
# }
|
||||
```
|
||||
|
||||
Y también **campos** con nombre, que en formato JSON salen como claves propias y se pueden filtrar
|
||||
y buscar:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f(order: u32, total: f64) {
|
||||
trace::info!(order, total, "Order received");
|
||||
# }
|
||||
```
|
||||
|
||||
## 2. Agrupa las trazas de una operación
|
||||
|
||||
Un *span* (intervalo) agrupa todo lo que ocurre durante una operación. Las trazas emitidas dentro
|
||||
llevan sus campos, aunque vengan de otras funciones:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn charge() {}
|
||||
# fn send_receipt() {}
|
||||
# fn f(order: u32) {
|
||||
let span = trace::info_span!("checkout", order);
|
||||
let _entered = span.enter();
|
||||
trace::info!("Charging"); // checkout{order=42}: Charging
|
||||
charge();
|
||||
send_receipt();
|
||||
# }
|
||||
```
|
||||
|
||||
No mantengas un `span.enter()` abierto a través de un `.await`: en código asíncrono, la tarea
|
||||
puede continuar en otro hilo.
|
||||
|
||||
## 3. Elige qué se registra
|
||||
|
||||
La sección `[log]` decide el nivel, la salida y el formato:
|
||||
|
||||
```toml
|
||||
[log]
|
||||
tracing = "Info,sqlx=Warn" # General level and levels per module.
|
||||
rolling = "Daily" # Stdout, Daily, Hourly, Minutely or Endless.
|
||||
path = "log" # Directory of the trace files.
|
||||
format = "Json" # Full, Compact, Pretty or Json.
|
||||
```
|
||||
|
||||
- **`tracing`** fija el nivel general y, separados por comas, niveles por módulo. `"Info,sqlx=Warn"`
|
||||
registra todo desde `info`, salvo las sentencias SQL, que sólo aparecen si fallan.
|
||||
- **`rolling`**: con `"Stdout"` (por defecto) las trazas salen por el terminal; con `"Daily"`,
|
||||
`"Hourly"` o `"Minutely"` se escriben en archivos que rotan con esa frecuencia, y con
|
||||
`"Endless"` en un único archivo.
|
||||
- **`format`**: `"Full"` para leer en el terminal, `"Json"` para que lo procese otra herramienta.
|
||||
|
||||
Un filtro mal escrito no detiene la aplicación: se usa `"Info"` y se avisa al arrancar.
|
||||
|
||||
## 4. Un nivel por entorno
|
||||
|
||||
Con la [cascada de configuración](configuration.md), cada entorno tiene su nivel sin tocar el
|
||||
código:
|
||||
|
||||
```toml
|
||||
# config/common.toml
|
||||
[log]
|
||||
tracing = "Info,sqlx=Warn"
|
||||
```
|
||||
|
||||
```toml
|
||||
# config/local.toml (your machine only, not versioned)
|
||||
[log]
|
||||
tracing = "Debug,pagetop=Info"
|
||||
format = "Pretty"
|
||||
```
|
||||
|
||||
## Comprueba
|
||||
|
||||
Arranca con `rolling = "Daily"`: aparece el directorio `log/` con un archivo `tracing.log.<fecha>`.
|
||||
Las trazas se escriben en segundo plano, sin frenar las peticiones, y PageTop vuelca las pendientes
|
||||
al detenerse con `Ctrl+C` o `SIGTERM`.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Desplegar en producción](deployment.md).
|
||||
- [Opciones de configuración](../reference/configuration.md#log): todas las claves de `[log]`.
|
||||
267
doc/v0.6/es/src/how-to/middleware.md
Normal file
267
doc/v0.6/es/src/how-to/middleware.md
Normal file
|
|
@ -0,0 +1,267 @@
|
|||
# Añadir *middleware*
|
||||
|
||||
**Objetivo:** aplicar a todas las peticiones lo que no es asunto de ningún *handler* concreto:
|
||||
medir lo que tarda cada una, comprimir las respuestas, limitar el tamaño de lo que se envía, cortar
|
||||
las que se eternizan o abrir una API a otros dominios con CORS.
|
||||
|
||||
Un *middleware* es una **capa** que envuelve las rutas: recibe la petición antes que el *handler*
|
||||
y la respuesta después. PageTop usa las capas de Axum y de [Tower](https://docs.rs/tower), así que
|
||||
tienes a mano todo su ecosistema. Cada extensión añade las suyas en `configure_middleware()`, y se
|
||||
aplican a las rutas de **todas** las extensiones.
|
||||
|
||||
## 1. Escribe una capa propia
|
||||
|
||||
`web::middleware::from_fn()` convierte una función `async` en una capa. La función recibe la
|
||||
petición y `next`, que ejecuta el resto de la cadena y devuelve la respuesta:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
use std::time::Instant;
|
||||
|
||||
async fn timing(request: web::Request, next: web::middleware::Next) -> Response {
|
||||
let path = request.uri().path().to_owned();
|
||||
let start = Instant::now();
|
||||
|
||||
let response = next.run(request).await;
|
||||
|
||||
trace::info!(
|
||||
%path,
|
||||
status = response.status().as_u16(),
|
||||
elapsed_ms = start.elapsed().as_millis() as u64,
|
||||
"Request served"
|
||||
);
|
||||
response
|
||||
}
|
||||
|
||||
pub struct Garden;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Garden {
|
||||
fn configure_middleware(&self, router: Router) -> Router {
|
||||
router.layer(web::middleware::from_fn(timing))
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Lo que va antes de `next.run()` ocurre a la ida (aquí, anotar la hora); lo que va después, a la
|
||||
vuelta, con la respuesta ya hecha. Una capa también puede responder ella misma sin llamar a `next`,
|
||||
por ejemplo para cerrar el sitio por mantenimiento.
|
||||
|
||||
## 2. Reutiliza las capas de `tower-http`
|
||||
|
||||
Para lo habitual no hace falta escribir nada: [`tower-http`](https://docs.rs/tower-http) trae las
|
||||
capas hechas. Añádelo con las *features* de las que vayas a usar (es la misma versión que usa
|
||||
PageTop):
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
tower-http = { version = "0.7", features = ["compression-gzip", "cors", "limit", "timeout"] }
|
||||
```
|
||||
|
||||
Y apílalas en `configure_middleware()`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
use std::time::Duration;
|
||||
|
||||
use tower_http::compression::CompressionLayer;
|
||||
use tower_http::limit::RequestBodyLimitLayer;
|
||||
use tower_http::timeout::TimeoutLayer;
|
||||
|
||||
# pub struct Garden;
|
||||
# #[async_trait]
|
||||
# impl Extension for Garden {
|
||||
fn configure_middleware(&self, router: Router) -> Router {
|
||||
router
|
||||
// Requests with a body over 1 MiB get a 413 Payload Too Large.
|
||||
.layer(RequestBodyLimitLayer::new(1024 * 1024))
|
||||
// Requests that take more than 30 seconds get a 408 Request Timeout.
|
||||
.layer(TimeoutLayer::with_status_code(
|
||||
web::http::StatusCode::REQUEST_TIMEOUT,
|
||||
Duration::from_secs(30),
|
||||
))
|
||||
// Responses go compressed with gzip to the browsers that accept it.
|
||||
.layer(CompressionLayer::new())
|
||||
}
|
||||
# }
|
||||
```
|
||||
|
||||
| Capa | Para qué |
|
||||
|---|---|
|
||||
| `CompressionLayer` | Comprime las respuestas si el navegador lo admite (*feature* `compression-gzip`, o `compression-full` para todos los formatos) |
|
||||
| `RequestBodyLimitLayer` | Rechaza los cuerpos demasiado grandes (*feature* `limit`) |
|
||||
| `TimeoutLayer` | Corta las peticiones que tardan demasiado (*feature* `timeout`) |
|
||||
| `CorsLayer` | Permite llamadas desde otros dominios (*feature* `cors`) |
|
||||
| `SetResponseHeaderLayer` | Añade una cabecera a todas las respuestas (*feature* `set-header`) |
|
||||
|
||||
## 3. Ten en cuenta el orden
|
||||
|
||||
Cada `.layer()` envuelve todo lo anterior, así que **la última capa añadida es la más externa**: la
|
||||
primera que ve la petición y la última que toca la respuesta. En el ejemplo, la compresión envuelve
|
||||
a las demás y comprime también el 408 del tiempo máximo, y el límite de tamaño, el más interno,
|
||||
actúa justo antes del *handler*.
|
||||
|
||||
Lo mismo vale entre extensiones: las capas de cada una envuelven las de las extensiones que se
|
||||
inicializaron antes.
|
||||
|
||||
## 4. Aplica una capa sólo a tus rutas
|
||||
|
||||
`configure_middleware()` afecta a todo. Para que una capa sólo envuelva unas rutas, crea con ellas
|
||||
un `Router` propio en `configure_router()`, ponle la capa y únelo al resto con `merge()`. Es lo
|
||||
natural para CORS, que sólo debe abrirse en la API:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# use serde::Serialize;
|
||||
use tower_http::cors::CorsLayer;
|
||||
|
||||
# #[derive(Serialize)]
|
||||
# struct Plot { code: &'static str }
|
||||
# async fn home() -> &'static str { "" }
|
||||
# async fn plots() -> Json<Vec<Plot>> { Json(vec![]) }
|
||||
# pub struct Garden;
|
||||
# #[async_trait]
|
||||
# impl Extension for Garden {
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
let cors = CorsLayer::new()
|
||||
.allow_origin(web::http::HeaderValue::from_static("https://garden.example.org"))
|
||||
.allow_methods([web::http::Method::GET]);
|
||||
|
||||
let api = Router::new()
|
||||
.route("/api/plots", web::get(plots))
|
||||
.layer(cors);
|
||||
|
||||
router.route("/", web::get(home)).merge(api)
|
||||
}
|
||||
# }
|
||||
```
|
||||
|
||||
## 5. Lo que no pasa por el *middleware*
|
||||
|
||||
Los **archivos estáticos** que publicas con `configure_static_files()` se sirven por fuera de las
|
||||
capas: no se comprimen ni se miden. Es deliberado, para que servir un estilo o una imagen sea lo más
|
||||
barato posible. Si quieres comprimirlos, hazlo en el *proxy* que tengas delante (ve [Desplegar en
|
||||
producción](deployment.md)).
|
||||
|
||||
Las **páginas de error** se pintan después, por fuera de todas las capas. Las capas sí ven la
|
||||
respuesta de error (la miden, le añaden cabeceras, que se conservan), pero la página que llega al
|
||||
navegador no sale comprimida. Tampoco la página mínima de un `panic!`, que PageTop atrapa en la
|
||||
capa más externa de todas.
|
||||
|
||||
## El ejemplo completo
|
||||
|
||||
```rust,no_run
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use pagetop::prelude::*;
|
||||
use serde::Serialize;
|
||||
use tower_http::compression::CompressionLayer;
|
||||
use tower_http::cors::CorsLayer;
|
||||
use tower_http::limit::RequestBodyLimitLayer;
|
||||
use tower_http::timeout::TimeoutLayer;
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Plot {
|
||||
code: &'static str,
|
||||
holder: &'static str,
|
||||
}
|
||||
|
||||
struct Garden;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Garden {
|
||||
fn configure_middleware(&self, router: Router) -> Router {
|
||||
router
|
||||
.layer(web::middleware::from_fn(timing))
|
||||
.layer(RequestBodyLimitLayer::new(1024 * 1024))
|
||||
.layer(TimeoutLayer::with_status_code(
|
||||
web::http::StatusCode::REQUEST_TIMEOUT,
|
||||
Duration::from_secs(30),
|
||||
))
|
||||
.layer(CompressionLayer::new())
|
||||
}
|
||||
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
let cors = CorsLayer::new()
|
||||
.allow_origin(web::http::HeaderValue::from_static("https://garden.example.org"))
|
||||
.allow_methods([web::http::Method::GET]);
|
||||
|
||||
let api = Router::new()
|
||||
.route("/api/plots", web::get(plots))
|
||||
.layer(cors);
|
||||
|
||||
router
|
||||
.route("/", web::get(home))
|
||||
.route("/notes", web::post(notes))
|
||||
.merge(api)
|
||||
}
|
||||
}
|
||||
|
||||
async fn timing(request: web::Request, next: web::middleware::Next) -> Response {
|
||||
let path = request.uri().path().to_owned();
|
||||
let start = Instant::now();
|
||||
|
||||
let response = next.run(request).await;
|
||||
|
||||
trace::info!(
|
||||
%path,
|
||||
status = response.status().as_u16(),
|
||||
elapsed_ms = start.elapsed().as_millis() as u64,
|
||||
"Request served"
|
||||
);
|
||||
response
|
||||
}
|
||||
|
||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("Community garden"))
|
||||
.with_child(Html::with(|_| html! {
|
||||
@for i in 1..=50 {
|
||||
p { "Plot " (i) ": tomatoes, lettuces and courgettes." }
|
||||
}
|
||||
}))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
async fn notes(body: String) -> String {
|
||||
format!("Received {} bytes", body.len())
|
||||
}
|
||||
|
||||
async fn plots() -> Json<Vec<Plot>> {
|
||||
Json(vec![
|
||||
Plot { code: "a1", holder: "Ana" },
|
||||
Plot { code: "b2", holder: "Luke" },
|
||||
])
|
||||
}
|
||||
|
||||
#[pagetop::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
Application::prepare(&Garden).await.run().await
|
||||
}
|
||||
```
|
||||
|
||||
## Comprueba
|
||||
|
||||
```sh
|
||||
# Compressed: the answer includes content-encoding: gzip.
|
||||
curl -s -o /dev/null -D - -H 'Accept-Encoding: gzip' http://localhost:8080/ | grep -i encoding
|
||||
|
||||
# Too big: 413 Payload Too Large.
|
||||
head -c 2000000 /dev/zero | curl -s -o /dev/null -w '%{http_code}\n' --data-binary @- \
|
||||
http://localhost:8080/notes
|
||||
|
||||
# CORS: only the API answers to the allowed origin.
|
||||
curl -s -o /dev/null -D - -H 'Origin: https://garden.example.org' \
|
||||
http://localhost:8080/api/plots | grep -i access-control
|
||||
```
|
||||
|
||||
Y en el terminal, una línea `Request served` por petición, con su ruta, su código y lo que ha
|
||||
tardado.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Crear una extensión](extensions.md): el resto de lo que puede aportar una extensión.
|
||||
- [Registrar trazas](logging.md): dónde acaban las líneas de `timing`.
|
||||
- [Arquitectura: del arranque a la respuesta](../explanation/architecture.md): dónde encajan las
|
||||
capas en el recorrido de una petición.
|
||||
148
doc/v0.6/es/src/how-to/navigation.md
Normal file
148
doc/v0.6/es/src/how-to/navigation.md
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
# Añadir navegación
|
||||
|
||||
**Objetivo:** dar a la aplicación un menú en todas las páginas, con desplegables, una barra que se
|
||||
pliega en móvil, migas de pan y enlaces que conservan el idioma del visitante.
|
||||
|
||||
## Menús con `Nav`
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Nav {
|
||||
Nav::new()
|
||||
.with_item(nav::Item::link(Lc::n("Home"), "/"))
|
||||
.with_item(nav::Item::link(Lc::n("Blog"), "/blog"))
|
||||
.with_item(nav::Item::link_blank(Lc::n("Code"), "https://git.cillero.es/manuelcillero/pagetop"))
|
||||
.with_item(nav::Item::link_disabled(Lc::n("Shop"), "/shop"))
|
||||
# }
|
||||
```
|
||||
|
||||
El enlace que coincide con la ruta actual se marca solo como activo (con `aria-current="page"`).
|
||||
`nav::Item::with_active()` permite forzarlo.
|
||||
|
||||
## Desplegables
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Nav {
|
||||
Nav::new().with_item(nav::Item::dropdown(
|
||||
Dropdown::new()
|
||||
.with_title(Lc::n("Products"))
|
||||
.with_item(dropdown::Item::header(Lc::n("Software")))
|
||||
.with_item(dropdown::Item::link(Lc::n("Desktop"), "/products/desktop"))
|
||||
.with_item(dropdown::Item::link(Lc::n("Mobile"), "/products/mobile"))
|
||||
.with_item(dropdown::Item::divider())
|
||||
.with_item(dropdown::Item::link(Lc::n("See all"), "/products")),
|
||||
))
|
||||
# }
|
||||
```
|
||||
|
||||
## Barra de navegación
|
||||
|
||||
`Navbar` combina marca, menús y otros elementos. Con `brand_left()`, en pantallas estrechas los
|
||||
menús se pliegan tras un botón de despliegue:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Navbar {
|
||||
let brand = Brand::new()
|
||||
.with_title(Lc::n("Urban Garden"))
|
||||
.with_route(Route::from("/"));
|
||||
|
||||
let menu = Nav::new()
|
||||
.with_item(nav::Item::link(Lc::n("Gardens"), "/gardens"))
|
||||
.with_item(nav::Item::link(Lc::n("Events"), "/events"));
|
||||
|
||||
let account = Nav::new()
|
||||
.with_prop(FlexItem::push_end())
|
||||
.with_item(nav::Item::link(Lc::n("Sign in"), "/login"));
|
||||
|
||||
Navbar::brand_left(brand)
|
||||
.with_item(navbar::Item::nav(menu))
|
||||
.with_item(navbar::Item::nav(account))
|
||||
# }
|
||||
```
|
||||
|
||||
Otras formas de empezar:
|
||||
|
||||
| Constructor | Marca | Botón de despliegue |
|
||||
|---|---|---|
|
||||
| `Navbar::simple()` | No | No |
|
||||
| `Navbar::simple_toggle()` | No | Sí |
|
||||
| `Navbar::simple_brand_left(brand)` | A la izquierda | No |
|
||||
| `Navbar::brand_left(brand)` | A la izquierda | Sí |
|
||||
| `Navbar::brand_right(brand)` | A la derecha | Sí |
|
||||
|
||||
## Un menú en todas las páginas
|
||||
|
||||
Registra el menú una sola vez al arrancar, en la región de cabecera, con `InRegion`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
pub struct MyApp;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for MyApp {
|
||||
async fn initialize(&self) -> Result<(), BoxError> {
|
||||
let menu = Navbar::simple().with_item(navbar::Item::nav(
|
||||
Nav::new()
|
||||
.with_item(nav::Item::link(Lc::n("Home"), "/"))
|
||||
.with_item(nav::Item::link(Lc::n("Contact"), "/contact")),
|
||||
));
|
||||
InRegion::Global(&CoreRegions::Header).add(menu);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Migas de pan
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Breadcrumb {
|
||||
Breadcrumb::new()
|
||||
.with_crumb(breadcrumb::Crumb::new(Lc::n("Home"), "/"))
|
||||
.with_crumb(breadcrumb::Crumb::new(Lc::n("Blog"), "/blog"))
|
||||
.with_crumb(breadcrumb::Crumb::current(Lc::n("My first post")))
|
||||
# }
|
||||
```
|
||||
|
||||
## Enlaces que conservan el idioma
|
||||
|
||||
Si el visitante eligió idioma con `?lang=en`, los enlaces internos deben conservarlo. PageTop lo
|
||||
hace por ti siempre que no construyas las URL a mano:
|
||||
|
||||
- Los componentes aceptan rutas como `Route`: un literal como `"/blog"` ya se convierte solo,
|
||||
y la URL definitiva se calcula al renderizar, con el idioma de cada petición.
|
||||
- Las URL externas (`https://...`, `mailto:`...) se detectan y se dejan tal cual.
|
||||
- Dentro de un componente o de `Html::with()`, usa `cx.route()`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Html {
|
||||
Html::with(|cx| {
|
||||
let post = cx.route("/blog/my-first-post");
|
||||
html! { a href=(post) { "Read the post" } }
|
||||
})
|
||||
# }
|
||||
```
|
||||
|
||||
- Cuando la ruta depende del contexto, `Route::with()` recibe un cierre que se evalúa en cada
|
||||
petición:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> nav::Item {
|
||||
nav::Item::link(
|
||||
Lc::n("My profile"),
|
||||
Route::with(|cx| match cx.current_user().id() {
|
||||
Some(id) => cx.route(util::join!("/users/", id.to_string())),
|
||||
None => cx.route("/login"),
|
||||
}),
|
||||
)
|
||||
# }
|
||||
```
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Crear una extensión](extensions.md): más sobre `InRegion` e `initialize()`.
|
||||
- [Traducir la aplicación](localization.md): de dónde sale el `?lang=` que conservan los enlaces.
|
||||
147
doc/v0.6/es/src/how-to/pages.md
Normal file
147
doc/v0.6/es/src/how-to/pages.md
Normal file
|
|
@ -0,0 +1,147 @@
|
|||
# Construir páginas
|
||||
|
||||
**Objetivo:** montar una página completa: título y metadatos, contenido en las regiones del tema,
|
||||
estilos y *scripts* propios, y datos compartidos con sus componentes.
|
||||
|
||||
## 1. Crea la página
|
||||
|
||||
`Page` es un documento HTML completo. Se crea a partir de la petición, se configura con métodos
|
||||
encadenados y termina con `render()`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
async fn about(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("About us"))
|
||||
.with_description(Lc::n("Who we are and what we do"))
|
||||
.with_child(Html::with(|_| html! { p { "We are a small team." } }))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
```
|
||||
|
||||
El tema activo se encarga del resto: el `<head>`, la estructura del `<body>`, sus estilos y
|
||||
*scripts*.
|
||||
|
||||
## 2. Reparte el contenido en regiones
|
||||
|
||||
Un tema reparte la página en **regiones**. PageTop define cuatro que cualquier tema respeta:
|
||||
|
||||
| Región | Uso habitual |
|
||||
|---|---|
|
||||
| `CoreRegions::Header` | Cabecera: logotipo, menú principal |
|
||||
| `CoreRegions::Content` | Contenido principal |
|
||||
| `CoreRegions::Aside` | Barra lateral |
|
||||
| `CoreRegions::Footer` | Pie de página |
|
||||
|
||||
`with_child()` añade al contenido principal; `with_child_in()` elige la región:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
async fn news(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_child(Html::with(|_| html! { h1 { "News" } }))
|
||||
.with_child_in(
|
||||
&CoreRegions::Aside,
|
||||
Block::new()
|
||||
.with_title(Lc::n("Archive"))
|
||||
.with_child(Html::with(|_| html! { p { "October, September..." } })),
|
||||
)
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
```
|
||||
|
||||
Los componentes añadidos así sólo existen en esa página. Para que algo aparezca en **todas** (un
|
||||
menú, un pie...), regístralo una vez con `InRegion`, como se explica en [Crear una
|
||||
extensión](extensions.md#4-pon-componentes-en-todas-las-páginas).
|
||||
|
||||
## 3. Añade metadatos
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# async fn h(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_metadata("author", "PageTop Team")
|
||||
.with_property("og:title", "PageTop")
|
||||
.with_assets(Favicon::new().with_icon("/static/favicon.ico"))
|
||||
.render()
|
||||
.await
|
||||
# }
|
||||
```
|
||||
|
||||
`with_metadata()` genera `<meta name="..." content="...">` y `with_property()` genera
|
||||
`<meta property="...">`, la forma que usa Open Graph.
|
||||
|
||||
## 4. Añade estilos y *scripts*
|
||||
|
||||
Una página puede pedir sus propios recursos. PageTop los ordena, evita duplicados y los añade al
|
||||
`<head>`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# async fn h(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_assets(StyleSheet::from("/static/css/catalog.css"))
|
||||
.with_assets(JavaScript::defer("/static/js/catalog.js").with_version("1.2"))
|
||||
.with_assets(JavaScript::on_load("greeting", |_| "console.log('Ready!');".to_string()))
|
||||
.render()
|
||||
.await
|
||||
# }
|
||||
```
|
||||
|
||||
- `StyleSheet::from()` enlaza una hoja de estilos; `.for_media(TargetMedia::Print)` la limita
|
||||
a la impresión.
|
||||
- `JavaScript::defer()` carga el *script* sin bloquear la página; `JavaScript::from()` lo carga de
|
||||
forma normal y `asynchronous()` con `async`.
|
||||
- `JavaScript::inline()` y `on_load()` incrustan código; el segundo lo ejecuta cuando el DOM está
|
||||
listo.
|
||||
- `with_version()` añade `?v=...` a la URL para que el navegador descargue la nueva versión.
|
||||
- `with_weight()` ordena los recursos: los de menor peso van antes.
|
||||
|
||||
Cómo publicar esos archivos se explica en [Recursos estáticos](assets.md).
|
||||
|
||||
## 5. Páginas de administración
|
||||
|
||||
`Page::admin()` crea la página con la plantilla de administración en lugar de la estándar. El tema
|
||||
puede maquetar ambas de forma distinta:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
async fn dashboard(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::admin(request)
|
||||
.with_title(Lc::n("Dashboard"))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
```
|
||||
|
||||
## 6. Comparte datos con los componentes
|
||||
|
||||
Una página puede guardar valores en su contexto para que cualquier componente los lea durante el
|
||||
renderizado:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
async fn shop(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_param("currency", "EUR")
|
||||
.with_child(Html::with(|cx| {
|
||||
let currency = cx.param_or("currency", "USD");
|
||||
html! { p { "Prices in " (currency) } }
|
||||
}))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
```
|
||||
|
||||
## Comprueba
|
||||
|
||||
Abre la página y mira su código fuente (`Ctrl+U`): el `<title>`, las etiquetas `<meta>` y los
|
||||
`<link>` y `<script>` están en el `<head>`, sin duplicados, en el orden de sus pesos.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Escribir HTML con `html!`](html.md).
|
||||
- [Usar componentes](components.md).
|
||||
- [Componentes, temas y renderizado](../explanation/rendering.md): qué hace `render()` por dentro.
|
||||
195
doc/v0.6/es/src/how-to/routes.md
Normal file
195
doc/v0.6/es/src/how-to/routes.md
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
# Añadir rutas
|
||||
|
||||
**Objetivo:** registrar las rutas de tu extensión, leer los datos de cada petición y responder con
|
||||
una página, un error, una redirección o JSON.
|
||||
|
||||
## 1. Registra las rutas
|
||||
|
||||
Cada extensión registra sus rutas en `configure_router()`. Recibe las rutas acumuladas por las
|
||||
extensiones anteriores, añade las suyas y las devuelve.
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# async fn list() -> &'static str { "" }
|
||||
# async fn view() -> &'static str { "" }
|
||||
# async fn create() -> &'static str { "" }
|
||||
pub struct Blog;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Blog {
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router
|
||||
.route("/posts", web::get(list))
|
||||
.route("/posts/{id}", web::get(view))
|
||||
.route("/posts/new", web::get(create).post(create))
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Los métodos disponibles son `web::get`, `web::post`, `web::put`, `web::patch` y `web::delete`, y se
|
||||
encadenan para atender varios en la misma ruta.
|
||||
|
||||
## 2. Agrupa rutas bajo un prefijo
|
||||
|
||||
Para agrupar rutas bajo un prefijo común, crea un `Router` aparte y anídalo:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# async fn dashboard() -> &'static str { "" }
|
||||
# async fn users() -> &'static str { "" }
|
||||
# pub struct Admin;
|
||||
# #[async_trait]
|
||||
# impl Extension for Admin {
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
let admin = Router::new()
|
||||
.route("/dashboard", web::get(dashboard))
|
||||
.route("/users", web::get(users));
|
||||
router.nest("/admin", admin)
|
||||
}
|
||||
# }
|
||||
```
|
||||
|
||||
## 3. Lee los datos de la petición
|
||||
|
||||
Un *handler* es una función `async` que recibe lo que necesite de la petición y devuelve algo que
|
||||
se pueda convertir en respuesta. PageTop reexporta los extractores de [Axum](https://docs.rs/axum)
|
||||
en `web`:
|
||||
|
||||
| Extractor | Qué obtiene |
|
||||
|---|---|
|
||||
| `HttpRequest` | La petición completa; la necesita `Page::new()` |
|
||||
| `web::Path<T>` | Segmentos de la ruta, como `{id}` |
|
||||
| `web::Query<T>` | Parámetros de la URL (`?page=2`) |
|
||||
| `web::Form<T>` | Campos de un formulario enviado |
|
||||
| `web::RawForm` | El cuerpo del formulario sin interpretar |
|
||||
| `Json<T>` | Cuerpo JSON |
|
||||
|
||||
Para `Query`, `Form` y `Json` define una estructura con `serde::Deserialize` (añade `serde` con la
|
||||
*feature* `derive` a tu `Cargo.toml`):
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Search {
|
||||
q: String,
|
||||
page: Option<u32>,
|
||||
}
|
||||
|
||||
async fn search(
|
||||
request: HttpRequest,
|
||||
web::Query(search): web::Query<Search>,
|
||||
) -> Result<Markup, ErrorPage> {
|
||||
let page = search.page.unwrap_or(1);
|
||||
Page::new(request)
|
||||
.with_child(Html::with(move |_| {
|
||||
html! { p { "Searching for “" (search.q) "”, page " (page) } }
|
||||
}))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
```
|
||||
|
||||
Una ruta puede tener varios segmentos variables. Recógelos en una tupla, en el mismo orden en que
|
||||
aparecen:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
// Registered as .route("/plots/{zone}/{number}", web::get(plot))
|
||||
async fn plot(web::Path((zone, number)): web::Path<(String, u32)>) -> String {
|
||||
format!("Plot {number} in zone {zone}")
|
||||
}
|
||||
```
|
||||
|
||||
`/plots/north/7` responde «Plot 7 in zone north». Si un segmento no se puede convertir al tipo
|
||||
pedido (`/plots/north/seven`), el *handler* no llega a ejecutarse: Axum responde por su cuenta con
|
||||
un 400 y un texto explicando el motivo.
|
||||
|
||||
Para recoger **todo** lo que sigue a un prefijo, por muchos segmentos que tenga, usa un comodín con
|
||||
asterisco:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
// Registered as .route("/files/{*path}", web::get(file))
|
||||
async fn file(web::Path(path): web::Path<String>) -> String {
|
||||
format!("You asked for {path}")
|
||||
}
|
||||
```
|
||||
|
||||
`/files/seeds/2026/list.txt` da `path = "seeds/2026/list.txt"`. El comodín tiene que ir al final de
|
||||
la ruta y no coincide con `/files/` a secas.
|
||||
|
||||
## 4. Elige la respuesta
|
||||
|
||||
**Páginas HTML.** Lo habitual: `Result<Markup, ErrorPage>`, que es lo que devuelve
|
||||
`Page::render()`.
|
||||
|
||||
**Errores.** `ErrorPage` se renderiza con el tema activo, para que el usuario no pierda la
|
||||
navegación del sitio (todos los casos en [Mostrar páginas de error](error-pages.md)):
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
async fn view(
|
||||
request: HttpRequest,
|
||||
web::Path(id): web::Path<u32>,
|
||||
) -> Result<Markup, ErrorPage> {
|
||||
if id == 0 {
|
||||
return Err(ErrorPage::NotFound(Some(request)));
|
||||
}
|
||||
Page::new(request).render().await
|
||||
}
|
||||
```
|
||||
|
||||
Las variantes son `BadRequest` (400), `AccessDenied` (403), `NotFound` (404), `InternalError`
|
||||
(500), `ServiceUnavailable` (503) y `GatewayTimeout` (504). Las rutas que no existen responden
|
||||
solas con la página 404.
|
||||
|
||||
**Redirecciones.** `Redirect` crea la respuesta con el código adecuado:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
async fn save() -> Response {
|
||||
// ... save the data ...
|
||||
Redirect::see_other("/posts")
|
||||
}
|
||||
```
|
||||
|
||||
Hay también `Redirect::found()`, `temporary()`, `permanent()` y `moved()`.
|
||||
|
||||
**JSON.** Para una API, devuelve `Json<T>` con cualquier tipo que implemente `serde::Serialize`:
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Status {
|
||||
version: &'static str,
|
||||
active: bool,
|
||||
}
|
||||
|
||||
async fn status() -> Json<Status> {
|
||||
Json(Status { version: "1.0", active: true })
|
||||
}
|
||||
```
|
||||
|
||||
**Texto plano.** Cualquier tipo que Axum sepa convertir en respuesta también sirve, como
|
||||
`&'static str` o `String`.
|
||||
|
||||
Para una página o un fragmento de HTML para HTMX, mira también [Una ruta, dos
|
||||
respuestas](htmx-setup.md#6-una-ruta-dos-respuestas).
|
||||
|
||||
## Comprueba
|
||||
|
||||
```sh
|
||||
curl -i http://localhost:8080/posts/0 # HTTP/1.1 404 Not Found, with the error page
|
||||
curl -i http://localhost:8080/nope # Also 404: unknown routes get the same error page
|
||||
```
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Construir páginas](pages.md): lo que va dentro de `Page::new(request)`.
|
||||
- [Crear y procesar formularios](forms.md): `web::Form` en acción.
|
||||
- [Mostrar páginas de error](error-pages.md): cuándo usar cada `ErrorPage`.
|
||||
- [Probar rutas y componentes](testing.md).
|
||||
373
doc/v0.6/es/src/how-to/services.md
Normal file
373
doc/v0.6/es/src/how-to/services.md
Normal file
|
|
@ -0,0 +1,373 @@
|
|||
# Compartir un servicio entre rutas
|
||||
|
||||
**Objetivo:** crear una sola vez, a partir de los ajustes, un objeto que usan muchas rutas y
|
||||
componentes (un contador, un catálogo cargado al arrancar, el cliente de un servicio externo), y
|
||||
llegar a él desde cualquier sitio sin pasarlo de mano en mano.
|
||||
|
||||
En otros *frameworks* este objeto se registra en un contenedor y se pide en cada *handler* (en
|
||||
Axum, con `State<T>`). En PageTop no hace falta: una extensión lo guarda en un **estático** y
|
||||
ofrece una función para obtenerlo, igual que hace `pagetop-seaorm` con `dbconn()`. Así lo usan
|
||||
igual un *handler*, un componente o un tema, que no reciben el estado de Axum.
|
||||
|
||||
## 1. Define el servicio
|
||||
|
||||
Un contador de visitas por ruta. Guarda su estado tras un `Mutex`, porque lo usarán a la vez
|
||||
peticiones de varios hilos, y toma de los ajustes cuántas rutas distintas recuerda como mucho:
|
||||
|
||||
```rust,no_run
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Mutex;
|
||||
|
||||
pub struct Visits {
|
||||
max_paths: usize,
|
||||
counts: Mutex<HashMap<String, u64>>,
|
||||
}
|
||||
|
||||
impl Visits {
|
||||
fn new(max_paths: usize) -> Self {
|
||||
Visits { max_paths, counts: Mutex::new(HashMap::new()) }
|
||||
}
|
||||
|
||||
/// Counts a visit to `path` and returns its total.
|
||||
pub fn record(&self, path: &str) -> u64 {
|
||||
let mut counts = self.counts.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
if !counts.contains_key(path) && counts.len() >= self.max_paths {
|
||||
return 0;
|
||||
}
|
||||
let total = counts.entry(path.to_string()).or_insert(0);
|
||||
*total += 1;
|
||||
*total
|
||||
}
|
||||
|
||||
/// Returns the `n` most visited paths.
|
||||
pub fn top(&self, n: usize) -> Vec<(String, u64)> {
|
||||
let counts = self.counts.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
let mut top: Vec<_> = counts.iter().map(|(p, c)| (p.clone(), *c)).collect();
|
||||
top.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
|
||||
top.truncate(n);
|
||||
top
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`unwrap_or_else(|poisoned| poisoned.into_inner())` sigue adelante aunque otra petición haya
|
||||
fallado con el `Mutex` tomado: un contador a medias no justifica dejar de responder.
|
||||
|
||||
## 2. Créalo con los ajustes
|
||||
|
||||
Los ajustes de la extensión, como en [Ajustes de tu
|
||||
extensión](configuration.md#5-ajustes-de-tu-extensión):
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
static SETTINGS: LazySettings<StatsSettings> = LazySettings::new();
|
||||
|
||||
#[settings(section = "stats")]
|
||||
pub struct StatsSettings {
|
||||
/// Maximum number of different paths that are counted.
|
||||
#[default = 100]
|
||||
pub max_paths: usize,
|
||||
}
|
||||
```
|
||||
|
||||
Si crearlo es inmediato y no puede fallar, basta con un `LazyLock`: se construye la primera vez que
|
||||
alguien lo pide, ya con los ajustes cargados:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# use std::sync::LazyLock;
|
||||
# static SETTINGS: LazySettings<StatsSettings> = LazySettings::new();
|
||||
# #[settings(section = "stats")]
|
||||
# pub struct StatsSettings {
|
||||
# #[default = 100]
|
||||
# pub max_paths: usize,
|
||||
# }
|
||||
# pub struct Visits;
|
||||
# impl Visits {
|
||||
# fn new(_max_paths: usize) -> Self { Visits }
|
||||
# }
|
||||
static VISITS: LazyLock<Visits> = LazyLock::new(|| Visits::new(SETTINGS.max_paths));
|
||||
|
||||
/// The visit counter of the application.
|
||||
pub fn visits() -> &'static Visits {
|
||||
&VISITS
|
||||
}
|
||||
```
|
||||
|
||||
No lo uses antes de que arranque la aplicación: hasta entonces los ajustes no están cargados.
|
||||
|
||||
## 3. Úsalo en *handlers* y componentes
|
||||
|
||||
Cualquier código lo pide con `visits()`. Un *handler* cuenta la visita:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# pub struct Visits;
|
||||
# impl Visits { pub fn record(&self, _: &str) -> u64 { 0 } }
|
||||
# static VISITS: Visits = Visits;
|
||||
# fn visits() -> &'static Visits { &VISITS }
|
||||
async fn page(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
let total = visits().record(request.path());
|
||||
Page::new(request)
|
||||
.with_child(Html::with(move |_| html! { p { "Visits to this page: " (total) } }))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
```
|
||||
|
||||
Y un componente puesto en el pie de todas las páginas muestra las más visitadas, sin que nadie le
|
||||
pase el contador:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# pub struct Visits;
|
||||
# impl Visits { pub fn top(&self, _: usize) -> Vec<(String, u64)> { vec![] } }
|
||||
# static VISITS: Visits = Visits;
|
||||
# fn visits() -> &'static Visits { &VISITS }
|
||||
# fn f() {
|
||||
InRegion::Global(&CoreRegions::Footer).add(Html::with(|_| {
|
||||
let top = visits().top(3);
|
||||
html! {
|
||||
p { "Most visited: "
|
||||
@for (path, total) in top {
|
||||
a href=(path) { (path) } " (" (total) ") "
|
||||
}
|
||||
}
|
||||
}
|
||||
}));
|
||||
# }
|
||||
```
|
||||
|
||||
## 4. Si crearlo puede fallar, hazlo al arrancar
|
||||
|
||||
Cuando crear el servicio es asíncrono o puede fallar (conectar con un servidor, leer un archivo),
|
||||
hazlo en `initialize()` y guárdalo en un `OnceLock`. Si devuelve un error, la aplicación **no
|
||||
arranca** y explica por qué, en lugar de fallar más tarde en mitad de una petición:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# use std::sync::OnceLock;
|
||||
# pub struct Station;
|
||||
# impl Station {
|
||||
# async fn connect(_url: &str) -> Result<Self, std::io::Error> { Ok(Station) }
|
||||
# }
|
||||
# static SETTINGS: LazySettings<WeatherSettings> = LazySettings::new();
|
||||
# #[settings(section = "weather")]
|
||||
# pub struct WeatherSettings {
|
||||
# #[default = "http://localhost:9000"]
|
||||
# pub url: String,
|
||||
# }
|
||||
static STATION: OnceLock<Station> = OnceLock::new();
|
||||
|
||||
/// The weather station, connected when the application starts.
|
||||
pub fn station() -> &'static Station {
|
||||
STATION.get().expect("Weather station not connected: is the extension a dependency?")
|
||||
}
|
||||
|
||||
pub struct Weather;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Weather {
|
||||
fn settings(&self) -> Option<&'static dyn LoadSettings> {
|
||||
Some(&SETTINGS)
|
||||
}
|
||||
|
||||
async fn initialize(&self) -> Result<(), BoxError> {
|
||||
if STATION.get().is_none() {
|
||||
let station = Station::connect(&SETTINGS.url).await?;
|
||||
let _ = STATION.set(station);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`initialize()` se ejecuta cada vez que se prepara la aplicación, y en las pruebas eso ocurre varias
|
||||
veces en el mismo proceso: por eso comprueba primero si el servicio ya existe.
|
||||
|
||||
## El ejemplo completo
|
||||
|
||||
```rust,no_run
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
|
||||
use pagetop::prelude::*;
|
||||
|
||||
static SETTINGS: LazySettings<StatsSettings> = LazySettings::new();
|
||||
|
||||
#[settings(section = "stats")]
|
||||
pub struct StatsSettings {
|
||||
/// Maximum number of different paths that are counted.
|
||||
#[default = 100]
|
||||
pub max_paths: usize,
|
||||
}
|
||||
|
||||
pub struct Visits {
|
||||
max_paths: usize,
|
||||
counts: Mutex<HashMap<String, u64>>,
|
||||
}
|
||||
|
||||
impl Visits {
|
||||
fn new(max_paths: usize) -> Self {
|
||||
Visits { max_paths, counts: Mutex::new(HashMap::new()) }
|
||||
}
|
||||
|
||||
/// Counts a visit to `path` and returns its total.
|
||||
pub fn record(&self, path: &str) -> u64 {
|
||||
let mut counts = self.counts.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
if !counts.contains_key(path) && counts.len() >= self.max_paths {
|
||||
return 0;
|
||||
}
|
||||
let total = counts.entry(path.to_string()).or_insert(0);
|
||||
*total += 1;
|
||||
*total
|
||||
}
|
||||
|
||||
/// Returns the `n` most visited paths.
|
||||
pub fn top(&self, n: usize) -> Vec<(String, u64)> {
|
||||
let counts = self.counts.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
let mut top: Vec<_> = counts.iter().map(|(p, c)| (p.clone(), *c)).collect();
|
||||
top.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
|
||||
top.truncate(n);
|
||||
top
|
||||
}
|
||||
}
|
||||
|
||||
static VISITS: LazyLock<Visits> = LazyLock::new(|| Visits::new(SETTINGS.max_paths));
|
||||
|
||||
/// The visit counter of the application.
|
||||
pub fn visits() -> &'static Visits {
|
||||
&VISITS
|
||||
}
|
||||
|
||||
struct Garden;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Garden {
|
||||
fn settings(&self) -> Option<&'static dyn LoadSettings> {
|
||||
Some(&SETTINGS)
|
||||
}
|
||||
|
||||
async fn initialize(&self) -> Result<(), BoxError> {
|
||||
InRegion::Global(&CoreRegions::Footer).add(Html::with(|_| {
|
||||
let top = visits().top(3);
|
||||
html! {
|
||||
p { "Most visited: "
|
||||
@for (path, total) in top {
|
||||
a href=(path) { (path) } " (" (total) ") "
|
||||
}
|
||||
}
|
||||
}
|
||||
}));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router
|
||||
.route("/", web::get(page))
|
||||
.route("/plots", web::get(page))
|
||||
.route("/harvest", web::get(page))
|
||||
}
|
||||
}
|
||||
|
||||
async fn page(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
let total = visits().record(request.path());
|
||||
Page::new(request)
|
||||
.with_child(Html::with(move |_| html! { p { "Visits to this page: " (total) } }))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
#[pagetop::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
Application::prepare(&Garden).await.run().await
|
||||
}
|
||||
```
|
||||
|
||||
## Comprueba
|
||||
|
||||
Arranca con `cargo run` y visita varias veces `/`, `/plots` y `/harvest`: cada página dice cuántas
|
||||
veces la has visto, y el pie de todas ordena las tres por visitas. Con `max_paths = 2` en la
|
||||
sección `[stats]` de `config/local.toml`, la tercera ruta distinta deja de contarse.
|
||||
|
||||
En una prueba, todas comparten el mismo contador, porque es un estático del proceso: escribe una
|
||||
sola prueba por flujo (ve [Probar rutas y componentes](testing.md)).
|
||||
|
||||
```rust
|
||||
# use std::collections::HashMap;
|
||||
# use std::sync::{LazyLock, Mutex};
|
||||
# use pagetop::prelude::*;
|
||||
# static SETTINGS: LazySettings<StatsSettings> = LazySettings::new();
|
||||
# #[settings(section = "stats")]
|
||||
# pub struct StatsSettings {
|
||||
# #[default = 100]
|
||||
# pub max_paths: usize,
|
||||
# }
|
||||
# pub struct Visits {
|
||||
# max_paths: usize,
|
||||
# counts: Mutex<HashMap<String, u64>>,
|
||||
# }
|
||||
# impl Visits {
|
||||
# fn new(max_paths: usize) -> Self {
|
||||
# Visits { max_paths, counts: Mutex::new(HashMap::new()) }
|
||||
# }
|
||||
# pub fn record(&self, path: &str) -> u64 {
|
||||
# let mut counts = self.counts.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
# if !counts.contains_key(path) && counts.len() >= self.max_paths {
|
||||
# return 0;
|
||||
# }
|
||||
# let total = counts.entry(path.to_string()).or_insert(0);
|
||||
# *total += 1;
|
||||
# *total
|
||||
# }
|
||||
# pub fn top(&self, n: usize) -> Vec<(String, u64)> {
|
||||
# let counts = self.counts.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
# let mut top: Vec<_> = counts.iter().map(|(p, c)| (p.clone(), *c)).collect();
|
||||
# top.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
|
||||
# top.truncate(n);
|
||||
# top
|
||||
# }
|
||||
# }
|
||||
# static VISITS: LazyLock<Visits> = LazyLock::new(|| Visits::new(SETTINGS.max_paths));
|
||||
# pub fn visits() -> &'static Visits {
|
||||
# &VISITS
|
||||
# }
|
||||
# struct Garden;
|
||||
# #[async_trait]
|
||||
# impl Extension for Garden {
|
||||
# fn settings(&self) -> Option<&'static dyn LoadSettings> {
|
||||
# Some(&SETTINGS)
|
||||
# }
|
||||
# fn configure_router(&self, router: Router) -> Router {
|
||||
# router.route("/plots", web::get(page)).route("/harvest", web::get(page))
|
||||
# }
|
||||
# }
|
||||
# async fn page(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
# let total = visits().record(request.path());
|
||||
# Page::new(request)
|
||||
# .with_child(Html::with(move |_| html! { p { "Visits to this page: " (total) } }))
|
||||
# .render()
|
||||
# .await
|
||||
# }
|
||||
#[pagetop::test]
|
||||
async fn visits_are_counted_by_path() {
|
||||
let app = web::test::init_router(Application::prepare(&Garden).await.test());
|
||||
|
||||
for uri in ["/plots", "/plots", "/harvest"] {
|
||||
let request = web::test::TestRequest::get().uri(uri).to_request();
|
||||
web::test::send_request(&app, request).await;
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
visits().top(2),
|
||||
[("/plots".to_string(), 2), ("/harvest".to_string(), 1)]
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Configurar la aplicación](configuration.md#5-ajustes-de-tu-extensión): los ajustes del servicio.
|
||||
- [Crear una extensión](extensions.md): el servicio es parte de una extensión.
|
||||
- [Si vienes de Axum](../explanation/coming-from-axum.md#el-estado-de-la-aplicación): por qué no se
|
||||
usa `State<T>`.
|
||||
99
doc/v0.6/es/src/how-to/tables.md
Normal file
99
doc/v0.6/es/src/how-to/tables.md
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
# Mostrar tablas ordenables y paginadas
|
||||
|
||||
**Objetivo:** mostrar datos en una tabla con cabeceras que ordenan y un paginador, usando enlaces
|
||||
normales que funcionan en cualquier navegador.
|
||||
|
||||
## 1. Construye la tabla
|
||||
|
||||
`Table` se construye columna a columna y fila a fila. Cada celda acepta texto, un `Lc` o
|
||||
cualquier componente:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
struct Book {
|
||||
title: &'static str,
|
||||
author: &'static str,
|
||||
available: bool,
|
||||
}
|
||||
|
||||
fn books_table(books: &[Book]) -> Table {
|
||||
let mut table = Table::new()
|
||||
.with_column(table::Column::new(Lc::n("Title")))
|
||||
.with_column(table::Column::new(Lc::n("Author")))
|
||||
.with_column(table::Column::new(Lc::n("Status")))
|
||||
.with_empty(Lc::n("There are no books in the catalog."));
|
||||
|
||||
for book in books {
|
||||
let status = if book.available {
|
||||
Badge::success(Lc::n("Available"))
|
||||
} else {
|
||||
Badge::warning(Lc::n("On loan"))
|
||||
};
|
||||
table = table.with_row(
|
||||
table::Row::new()
|
||||
.with_cell(book.title)
|
||||
.with_cell(book.author)
|
||||
.with_cell(table::Cell::new(status)),
|
||||
);
|
||||
}
|
||||
table
|
||||
}
|
||||
```
|
||||
|
||||
Si no hay filas, se muestra el texto de `with_empty()` (o uno genérico, si no lo indicas).
|
||||
|
||||
## 2. Ordena por columnas
|
||||
|
||||
Una columna se hace ordenable con un `SortLink`: la URL a la que lleva y, si la tabla ya está
|
||||
ordenada por ella, en qué dirección. `Table` marca la cabecera con `aria-sort` y con clases que el
|
||||
tema usa para dibujar la flecha:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f(sort: &str, dir: SortDir) -> table::Column {
|
||||
table::Column::new(Lc::n("Title")).with_sort(
|
||||
table::SortLink::new("/books?sort=title")
|
||||
.with_dir((sort == "title").then_some(dir)),
|
||||
)
|
||||
# }
|
||||
```
|
||||
|
||||
Tu *handler* lee los parámetros (con `web::Query`) y consulta los datos en ese orden.
|
||||
|
||||
## 3. Pagina el listado
|
||||
|
||||
`Pager` genera los enlaces de un listado paginado. Sólo se muestra si hay más de una página:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f(page: u64, total: u64) -> Pager {
|
||||
Pager::new()
|
||||
.with_base_path("/books")
|
||||
.with_extra_query("sort", "title")
|
||||
.with_current_page(page)
|
||||
.with_items_per_page(20)
|
||||
.with_total_items(total)
|
||||
# }
|
||||
```
|
||||
|
||||
Cada enlace lleva el parámetro `page` con el número de página, más los que añadas con
|
||||
`with_extra_query()` (para conservar el orden o la búsqueda). Coloca el paginador junto a la tabla:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn table() -> Table { Table::new() }
|
||||
# fn pager() -> Pager { Pager::new() }
|
||||
# fn f() -> Container {
|
||||
Container::new()
|
||||
.with_child(table())
|
||||
.with_child(pager())
|
||||
# }
|
||||
```
|
||||
|
||||
La guía [Ordenar y paginar sin recargar](htmx-tables.md) tiene un ejemplo completo con su *handler*,
|
||||
que lee `sort`, `dir` y `page` de la URL.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Ordenar y paginar sin recargar](htmx-tables.md): la misma tabla, sustituida con HTMX.
|
||||
- [Borrar con confirmación](htmx-delete.md): botones de acción en cada fila.
|
||||
228
doc/v0.6/es/src/how-to/testing.md
Normal file
228
doc/v0.6/es/src/how-to/testing.md
Normal file
|
|
@ -0,0 +1,228 @@
|
|||
# Probar rutas y componentes
|
||||
|
||||
**Objetivo:** comprobar con `cargo test` lo que devuelve cada ruta y cada componente, sin arrancar
|
||||
el servidor ni abrir un navegador.
|
||||
|
||||
Las pruebas detectan lo que se rompe antes de que lo vean tus usuarios, te dejan reorganizar el
|
||||
código con la tranquilidad de que todo sigue funcionando y, de paso, muestran cómo se usa cada ruta.
|
||||
En PageTop son baratas: la aplicación entera se prepara en memoria y responde en milisegundos.
|
||||
|
||||
## 1. Prepara la aplicación sin servidor
|
||||
|
||||
`Application::prepare()` hace lo mismo que al arrancar (registra las extensiones, carga los ajustes,
|
||||
las inicializa...), y `test()` devuelve sus rutas sin abrir ningún puerto. Con
|
||||
`web::test::send_request()` se le envían peticiones:
|
||||
|
||||
```rust
|
||||
use pagetop::prelude::*;
|
||||
|
||||
struct MyApp;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for MyApp {
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router.route("/hello/{name}", web::get(hello))
|
||||
}
|
||||
}
|
||||
|
||||
async fn hello(
|
||||
request: HttpRequest,
|
||||
web::Path(name): web::Path<String>,
|
||||
) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_child(Html::with(move |_| html! { h1 { "Hello, " (name) "!" } }))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn greets_by_name() {
|
||||
let app = web::test::init_router(Application::prepare(&MyApp).await.test());
|
||||
|
||||
let request = web::test::TestRequest::get().uri("/hello/Ana").to_request();
|
||||
let response = web::test::send_request(&app, request).await;
|
||||
|
||||
assert_eq!(response.status(), web::http::StatusCode::OK);
|
||||
let body = web::test::read_body_text(response).await;
|
||||
assert!(body.contains("<h1>Hello, Ana!</h1>"));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn unknown_routes_answer_with_404() {
|
||||
let app = web::test::init_router(Application::prepare(&MyApp).await.test());
|
||||
|
||||
let request = web::test::TestRequest::get().uri("/nope").to_request();
|
||||
let response = web::test::send_request(&app, request).await;
|
||||
|
||||
assert_eq!(response.status(), web::http::StatusCode::NOT_FOUND);
|
||||
}
|
||||
```
|
||||
|
||||
`#[pagetop::test]` ejecuta cada prueba en el mismo *runtime* asíncrono multihilo que usa la
|
||||
aplicación real. Las pruebas que sólo usan la API pública van en `tests/`; si la aplicación vive
|
||||
en `src/lib.rs`, cada archivo de `tests/` la importa como una biblioteca más.
|
||||
|
||||
## 2. Envía formularios y otros métodos
|
||||
|
||||
`TestRequest` tiene un constructor por método (`get()`, `post()`, `put()`, `patch()` y
|
||||
`delete()`), y `form()` envía los campos de un formulario, ya codificados, como lo hace el
|
||||
navegador:
|
||||
|
||||
```rust
|
||||
# use pagetop::prelude::*;
|
||||
use serde::Deserialize;
|
||||
|
||||
struct Contact;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Contact {
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router.route("/contact", web::post(send))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Message {
|
||||
text: String,
|
||||
}
|
||||
|
||||
async fn send(web::Form(message): web::Form<Message>) -> Response {
|
||||
if message.text.trim().is_empty() {
|
||||
return web::http::StatusCode::UNPROCESSABLE_ENTITY.into_response();
|
||||
}
|
||||
Redirect::see_other("/contact/thanks")
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn a_message_redirects_to_the_thanks_page() {
|
||||
let app = web::test::init_router(Application::prepare(&Contact).await.test());
|
||||
|
||||
let request = web::test::TestRequest::post()
|
||||
.uri("/contact")
|
||||
.form("text=Hello")
|
||||
.to_request();
|
||||
let response = web::test::send_request(&app, request).await;
|
||||
|
||||
assert_eq!(response.status(), web::http::StatusCode::SEE_OTHER);
|
||||
assert_eq!(response.headers()["location"], "/contact/thanks");
|
||||
}
|
||||
```
|
||||
|
||||
## 3. Prueba un componente suelto
|
||||
|
||||
Un componente se renderiza con un `Context`, sin aplicación ni rutas. `Context::default()` usa el
|
||||
idioma por defecto; para probar otro idioma o una ruta concreta, créalo a partir de una petición de
|
||||
prueba:
|
||||
|
||||
```rust
|
||||
# use pagetop::prelude::*;
|
||||
#[pagetop::test]
|
||||
async fn a_badge_shows_its_label() {
|
||||
let mut cx = Context::default();
|
||||
let mut badge = Badge::success(Lc::n("Active"));
|
||||
|
||||
let html = badge.render(&mut cx).await.into_string();
|
||||
|
||||
assert!(html.contains("Active"));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn internal_links_keep_the_language() {
|
||||
let request = web::test::TestRequest::get().uri("/?lang=es").to_http_request();
|
||||
let cx = Context::new(request);
|
||||
|
||||
assert_eq!(cx.route("/blog").to_string(), "/blog?lang=es");
|
||||
}
|
||||
```
|
||||
|
||||
## 4. Prueba las rutas de HTMX
|
||||
|
||||
Una ruta para HTMX es una ruta normal que devuelve un fragmento. Envía la cabecera `HX-Request`,
|
||||
como hace HTMX, y comprueba el fragmento y las cabeceras `HX-*` de la respuesta:
|
||||
|
||||
```rust
|
||||
# use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
|
||||
struct Clock;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Clock {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_htmx::Htmx]
|
||||
}
|
||||
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router.route("/time", web::get(time))
|
||||
}
|
||||
}
|
||||
|
||||
async fn time(request: HttpRequest) -> Response {
|
||||
if !request.is_htmx() {
|
||||
return Redirect::see_other("/");
|
||||
}
|
||||
HtmxResponse::new(html! { span { "12:00" } })
|
||||
.trigger("timeShown")
|
||||
.into_response()
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn time_answers_htmx_with_a_fragment_and_an_event() {
|
||||
let app = web::test::init_router(Application::prepare(&Clock).await.test());
|
||||
|
||||
let request = web::test::TestRequest::get()
|
||||
.uri("/time")
|
||||
.header("hx-request", "true")
|
||||
.to_request();
|
||||
let response = web::test::send_request(&app, request).await;
|
||||
|
||||
assert_eq!(response.headers()["hx-trigger"], "timeShown");
|
||||
assert_eq!(web::test::read_body_text(response).await, "<span>12:00</span>");
|
||||
}
|
||||
```
|
||||
|
||||
Lo que HTMX haga después con el fragmento lo deciden los atributos `hx-*` de la página, que son
|
||||
HTML: no hay lógica de cliente que probar.
|
||||
|
||||
## 5. Usa otra configuración para las pruebas
|
||||
|
||||
Las pruebas leen la misma cascada de configuración que la aplicación. Para que usen sus propios
|
||||
ajustes (otra base de datos, menos trazas...), créalos en `config/test.toml` y ejecuta las pruebas
|
||||
en ese modo:
|
||||
|
||||
```toml
|
||||
# config/test.toml
|
||||
[log]
|
||||
tracing = "Warn"
|
||||
|
||||
[database]
|
||||
db_name = "tests?mode=memory"
|
||||
max_pool_size = 1
|
||||
```
|
||||
|
||||
```sh
|
||||
PAGETOP_RUN_MODE=test cargo test
|
||||
```
|
||||
|
||||
Una base de datos SQLite en memoria es nueva en cada ejecución. Con `max_pool_size = 1` todas las
|
||||
consultas comparten la misma conexión, y por tanto las mismas tablas.
|
||||
|
||||
## Comprueba
|
||||
|
||||
```sh
|
||||
cargo test
|
||||
```
|
||||
|
||||
```text
|
||||
running 2 tests
|
||||
test greets_by_name ... ok
|
||||
test unknown_routes_answer_with_404 ... ok
|
||||
|
||||
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
|
||||
```
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Tareas del huerto con HTMX](../tutorials/htmx-tasks.md#8-prueba-la-aplicación): pruebas de una
|
||||
aplicación completa.
|
||||
- [Registrar trazas](logging.md).
|
||||
193
doc/v0.6/es/src/how-to/themes.md
Normal file
193
doc/v0.6/es/src/how-to/themes.md
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
# Crear un tema
|
||||
|
||||
**Objetivo:** elegir el aspecto de la aplicación y, si hace falta, crear un tema propio que herede
|
||||
de otro y cambie sólo lo necesario.
|
||||
|
||||
El tema es la **piel** de la aplicación: maqueta la página por regiones, aporta estilos y
|
||||
*scripts*, y decide cómo se ve cada componente. Cambiar de tema no obliga a tocar las páginas.
|
||||
|
||||
## 1. Elige un tema
|
||||
|
||||
PageTop trae el tema `Basic`. Hay otros como extensiones:
|
||||
|
||||
| Tema | *Crate* | Estilo |
|
||||
|---|---|---|
|
||||
| Basic | `pagetop` | Sobrio, sin dependencias |
|
||||
| Bootsier | `pagetop-bootsier` | [Bootstrap 5](https://getbootstrap.com) |
|
||||
| Aliner | `pagetop-aliner` | Muestra la estructura de la página, para pruebas |
|
||||
|
||||
Para usar uno, declara su extensión como dependencia y selecciónalo en la configuración:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
pub struct MyApp;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for MyApp {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_bootsier::Bootsier]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```toml
|
||||
[app]
|
||||
theme = "Bootsier"
|
||||
```
|
||||
|
||||
Si el tema configurado no está disponible, PageTop usa `Basic` y avisa al arrancar.
|
||||
|
||||
## 2. Crea un tema
|
||||
|
||||
Un tema es una extensión que además implementa `Theme`. Todos los métodos de `Theme` tienen
|
||||
implementación por defecto, así que el mínimo es éste:
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
|
||||
pub struct Earth;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Earth {
|
||||
fn theme(&self) -> Option<ThemeRef> {
|
||||
Some(&Self)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Theme for Earth {}
|
||||
```
|
||||
|
||||
## 3. Hereda de otro tema
|
||||
|
||||
Lo más práctico es partir de un tema existente y cambiar sólo lo necesario. Un **tema hijo**
|
||||
hereda todo de su padre:
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
|
||||
pub struct Earth;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Earth {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_bootsier::Bootsier]
|
||||
}
|
||||
|
||||
fn theme(&self) -> Option<ThemeRef> {
|
||||
Some(&Self)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Theme for Earth {
|
||||
fn parent(&self) -> Option<ThemeRef> {
|
||||
Some(&pagetop_bootsier::Bootsier)
|
||||
}
|
||||
|
||||
// Adds its own style sheet to every page.
|
||||
fn before_render_page_body(&self, page: &mut Page) {
|
||||
if let Some(parent) = self.parent() {
|
||||
parent.before_render_page_body(page);
|
||||
}
|
||||
page.alter_assets(StyleSheet::from("/static/css/earth.css").with_weight(10));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`before_render_page_body()` es donde un tema añade sus recursos. Al sobrescribirlo, llama al del
|
||||
padre para no perder los suyos.
|
||||
|
||||
No olvides seleccionarlo en la configuración (`theme = "Earth"`) y declararlo como dependencia
|
||||
de la aplicación.
|
||||
|
||||
## 4. Ajusta componentes
|
||||
|
||||
`setup_component()` permite retocar cualquier componente antes de pintarlo. La macro
|
||||
`setup_component!` lo distingue por tipo:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# pub struct Earth;
|
||||
# #[async_trait]
|
||||
# impl Extension for Earth {}
|
||||
#[async_trait]
|
||||
impl Theme for Earth {
|
||||
fn setup_component(&self, component: &mut dyn Component, _cx: &mut Context) {
|
||||
setup_component!(component, {
|
||||
Button => |button| { button.alter_prop(PropsOp::add_classes("earth-button")); },
|
||||
Block => |block| { block.alter_prop(PropsOp::add_classes("earth-block")); },
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 5. Reescribe componentes
|
||||
|
||||
Para cambiar el HTML entero de un componente, usa `render_component()` con la macro
|
||||
`render_component!`. Lo que no captures se pinta como siempre:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# pub struct Earth;
|
||||
# #[async_trait]
|
||||
# impl Extension for Earth {}
|
||||
#[async_trait]
|
||||
impl Theme for Earth {
|
||||
async fn render_component(
|
||||
&self,
|
||||
component: &dyn Component,
|
||||
cx: &mut Context,
|
||||
) -> Option<Result<Markup, ComponentError>> {
|
||||
render_component!(component, {
|
||||
Badge => |badge| Ok(html! {
|
||||
span class="earth-label" { (badge.label().using(cx)) }
|
||||
}),
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Como el componente expone sus datos con *getters* (`badge.label()`), el tema no depende de sus
|
||||
detalles internos.
|
||||
|
||||
## 6. Cambia las páginas de error
|
||||
|
||||
Las páginas 403, 404 y de error grave se pintan con la plantilla activa, para no perder la
|
||||
navegación. Un tema puede cambiar su contenido:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# pub struct Earth;
|
||||
# #[async_trait]
|
||||
# impl Extension for Earth {}
|
||||
#[async_trait]
|
||||
impl Theme for Earth {
|
||||
fn error_404(&self, page: &mut Page) {
|
||||
page.alter_title(Lc::n("Not found")).alter_child_in(
|
||||
&CoreRegions::Content,
|
||||
ChildOp::Prepend(
|
||||
Html::with(|_| {
|
||||
html! {
|
||||
h1 { "This page has gone off to plant tomatoes" }
|
||||
p { a href="/" { "Back to home" } }
|
||||
}
|
||||
})
|
||||
.into(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Más allá
|
||||
|
||||
Un tema también puede definir **regiones** y **plantillas** propias, fijar los anchos de los
|
||||
puntos de corte (`breakpoint_entry()`) o traducir las intenciones a su paleta de colores
|
||||
(`intent_color()`). La documentación del módulo `core::theme` en
|
||||
[docs.rs](https://docs.rs/pagetop) recorre los seis pasos para personalizar un tema por completo.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Intervenir con acciones](actions.md): retocar componentes desde una extensión que no es un tema.
|
||||
- [Componentes, temas y renderizado](../explanation/rendering.md).
|
||||
351
doc/v0.6/es/src/how-to/users.md
Normal file
351
doc/v0.6/es/src/how-to/users.md
Normal file
|
|
@ -0,0 +1,351 @@
|
|||
# Añadir usuarios y permisos
|
||||
|
||||
**Objetivo:** que los visitantes puedan iniciar sesión y que algunas páginas o acciones sólo estén
|
||||
al alcance de quien tenga el permiso adecuado.
|
||||
|
||||
La extensión `pagetop-user` aporta las cuentas, el inicio de sesión, las sesiones (guardadas en la
|
||||
base de datos), las contraseñas cifradas con Argon2 y el control de acceso por roles, con su
|
||||
interfaz de administración en `/admin`. Necesita una base de datos: mira antes [Conectar una base
|
||||
de datos](database.md).
|
||||
|
||||
## 1. Añade la extensión
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
pagetop-user = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
||||
pagetop-seaorm = { git = "https://git.cillero.es/manuelcillero/pagetop", features = ["sqlite"] }
|
||||
```
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
pub struct Board;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Board {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_user::User]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`User` declara por su cuenta lo que necesita: `pagetop-seaorm`, `pagetop-htmx` y el panel
|
||||
`pagetop-admin`. Al arrancar crea sus tablas y registra sus rutas, entre ellas `/user/login`,
|
||||
`/user/register` y `/user` (el perfil).
|
||||
|
||||
## 2. Configura la base de datos y el primer administrador
|
||||
|
||||
```toml
|
||||
# config/common.toml
|
||||
[database]
|
||||
db_type = "sqlite"
|
||||
db_name = "board.db?mode=rwc"
|
||||
```
|
||||
|
||||
```toml
|
||||
# config/local.toml (not versioned)
|
||||
[user.seed]
|
||||
admin_password = "choose-a-long-one"
|
||||
```
|
||||
|
||||
Con la base de datos vacía, el primer arranque crea la cuenta `admin` con esa contraseña. Si no la
|
||||
indicas, genera una aleatoria y la muestra **una sola vez** en el terminal:
|
||||
|
||||
```text
|
||||
pagetop-user: admin account created.
|
||||
username: admin
|
||||
password: ...
|
||||
```
|
||||
|
||||
Las demás opciones (registro abierto, bloqueo tras intentos fallidos, duración de las sesiones...)
|
||||
están en la [referencia de configuración](../reference/configuration.md#user).
|
||||
|
||||
## 3. Pon el menú de cuenta en la cabecera
|
||||
|
||||
`account_menu(cx)` construye el menú: «Iniciar sesión» para los anónimos, y el nombre del usuario
|
||||
con su perfil, la administración (si tiene acceso) y «Cerrar sesión» para los demás. Depende de
|
||||
quién pide la página, así que se construye al renderizar, dentro de un componente:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
use pagetop_user::prelude::*;
|
||||
|
||||
#[derive(AutoDefault, Clone, Debug)]
|
||||
struct TopBar;
|
||||
|
||||
#[async_trait]
|
||||
impl Component for TopBar {
|
||||
fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
|
||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
let brand = Brand::new()
|
||||
.with_title(Lc::n("Garden board"))
|
||||
.with_route(Route::from("/"));
|
||||
Ok(Navbar::brand_left(brand)
|
||||
.with_item(navbar::Item::nav(account_menu(cx)))
|
||||
.render(cx)
|
||||
.await)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Regístralo una vez en `initialize()`, para todas las páginas:
|
||||
|
||||
```rust,ignore
|
||||
InRegion::Global(&CoreRegions::Header).add(TopBar::new());
|
||||
```
|
||||
|
||||
## 4. Define tus permisos
|
||||
|
||||
Un permiso es un valor de un `enum` propio con una clave única. Su nombre y su grupo son los que
|
||||
verá el administrador al asignarlo:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum BoardPermission {
|
||||
PostNotices,
|
||||
}
|
||||
|
||||
impl Permission for BoardPermission {
|
||||
fn key(&self) -> CowStr {
|
||||
match self {
|
||||
Self::PostNotices => "board.post_notices".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn label(&self) -> Lc {
|
||||
Lc::n("Post notices on the board")
|
||||
}
|
||||
|
||||
fn group(&self) -> &'static str {
|
||||
"board"
|
||||
}
|
||||
|
||||
fn group_label(&self) -> Lc {
|
||||
Lc::n("Garden board")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Para que aparezca en la pantalla de roles, regístralo con la acción `DeclarePermissions`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# #[derive(Clone, Copy, Debug)]
|
||||
# enum BoardPermission { PostNotices }
|
||||
# impl Permission for BoardPermission {
|
||||
# fn key(&self) -> CowStr { "board.post_notices".into() }
|
||||
# }
|
||||
use pagetop_user::PermissionRegistry;
|
||||
use pagetop_user::prelude::*;
|
||||
|
||||
fn declare_permissions(registry: &mut PermissionRegistry) {
|
||||
registry.register(&BoardPermission::PostNotices);
|
||||
}
|
||||
|
||||
pub struct Board;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Board {
|
||||
fn actions(&self) -> Vec<ActionBox> {
|
||||
actions![DeclarePermissions::new(declare_permissions)]
|
||||
}
|
||||
|
||||
// ... dependencies(), initialize() and configure_router() ...
|
||||
}
|
||||
```
|
||||
|
||||
## 5. Protege rutas y adapta la interfaz
|
||||
|
||||
`require_permission()` corta la petición con un error 403 si falta el permiso. Va al principio del
|
||||
*handler*, con `?`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# #[derive(Clone, Copy, Debug)]
|
||||
# enum BoardPermission { PostNotices }
|
||||
# impl Permission for BoardPermission {
|
||||
# fn key(&self) -> CowStr { "board.post_notices".into() }
|
||||
# }
|
||||
async fn new_notice(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
require_permission(&request, &BoardPermission::PostNotices)?;
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("New notice"))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
```
|
||||
|
||||
`has_permission()` devuelve un `bool`, para mostrar u ocultar lo que no se puede usar:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# #[derive(Clone, Copy, Debug)]
|
||||
# enum BoardPermission { PostNotices }
|
||||
# impl Permission for BoardPermission {
|
||||
# fn key(&self) -> CowStr { "board.post_notices".into() }
|
||||
# }
|
||||
async fn board(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
let can_post = has_permission(&request, &BoardPermission::PostNotices);
|
||||
let mut page = Page::new(request)
|
||||
.with_title(Lc::n("Garden board"))
|
||||
.with_child(Html::with(|_| html! { p { "The water tank is full." } }));
|
||||
if can_post {
|
||||
page = page.with_child(Button::anchor(Lc::n("Post a notice"), "/notices/new"));
|
||||
}
|
||||
page.render().await
|
||||
}
|
||||
```
|
||||
|
||||
Y dentro de un componente, `cx.current_user()` dice quién está viendo la página:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Html {
|
||||
Html::with(|cx| {
|
||||
let user = cx.current_user();
|
||||
html! {
|
||||
@if let Some(name) = user.display_name() {
|
||||
p { "Hello, " (name) "." }
|
||||
}
|
||||
}
|
||||
})
|
||||
# }
|
||||
```
|
||||
|
||||
Ocultar el botón no basta: la ruta debe comprobar el permiso igualmente, porque cualquiera puede
|
||||
escribir la URL.
|
||||
|
||||
## 6. Asigna el permiso
|
||||
|
||||
Inicia sesión como `admin` y entra en **Administración** desde el menú de cuenta. En la lista de
|
||||
roles, abre los permisos de uno de ellos: verás el grupo «Garden board» con su permiso. Puedes
|
||||
concederlo:
|
||||
|
||||
- al rol **authenticated**, para todos los usuarios que inicien sesión;
|
||||
- o a un rol nuevo («Gardeners», por ejemplo), y asignar ese rol a las cuentas que quieras.
|
||||
|
||||
Los administradores tienen todos los permisos sin necesidad de asignarlos.
|
||||
|
||||
## El ejemplo completo
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
use pagetop_user::PermissionRegistry;
|
||||
use pagetop_user::prelude::*;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum BoardPermission {
|
||||
PostNotices,
|
||||
}
|
||||
|
||||
impl Permission for BoardPermission {
|
||||
fn key(&self) -> CowStr {
|
||||
match self {
|
||||
Self::PostNotices => "board.post_notices".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn label(&self) -> Lc {
|
||||
Lc::n("Post notices on the board")
|
||||
}
|
||||
|
||||
fn group(&self) -> &'static str {
|
||||
"board"
|
||||
}
|
||||
|
||||
fn group_label(&self) -> Lc {
|
||||
Lc::n("Garden board")
|
||||
}
|
||||
}
|
||||
|
||||
fn declare_permissions(registry: &mut PermissionRegistry) {
|
||||
registry.register(&BoardPermission::PostNotices);
|
||||
}
|
||||
|
||||
struct Board;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Board {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_user::User]
|
||||
}
|
||||
|
||||
fn actions(&self) -> Vec<ActionBox> {
|
||||
actions![DeclarePermissions::new(declare_permissions)]
|
||||
}
|
||||
|
||||
async fn initialize(&self) -> Result<(), BoxError> {
|
||||
InRegion::Global(&CoreRegions::Header).add(TopBar::new());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router
|
||||
.route("/", web::get(board))
|
||||
.route("/notices/new", web::get(new_notice))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(AutoDefault, Clone, Debug)]
|
||||
struct TopBar;
|
||||
|
||||
#[async_trait]
|
||||
impl Component for TopBar {
|
||||
fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
|
||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
let brand = Brand::new()
|
||||
.with_title(Lc::n("Garden board"))
|
||||
.with_route(Route::from("/"));
|
||||
Ok(Navbar::brand_left(brand)
|
||||
.with_item(navbar::Item::nav(account_menu(cx)))
|
||||
.render(cx)
|
||||
.await)
|
||||
}
|
||||
}
|
||||
|
||||
async fn board(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
let can_post = has_permission(&request, &BoardPermission::PostNotices);
|
||||
let mut page = Page::new(request)
|
||||
.with_title(Lc::n("Garden board"))
|
||||
.with_child(Html::with(|_| html! { p { "The water tank is full." } }));
|
||||
if can_post {
|
||||
page = page.with_child(Button::anchor(Lc::n("Post a notice"), "/notices/new"));
|
||||
}
|
||||
page.render().await
|
||||
}
|
||||
|
||||
async fn new_notice(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
require_permission(&request, &BoardPermission::PostNotices)?;
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("New notice"))
|
||||
.with_child(Html::with(|_| html! { p { "Write your notice here." } }))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
#[pagetop::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
Application::prepare(&Board).await.run().await
|
||||
}
|
||||
```
|
||||
|
||||
## Comprueba
|
||||
|
||||
1. Sin iniciar sesión, la portada no muestra *Post a notice*, y <http://localhost:8080/notices/new>
|
||||
responde con la página de acceso denegado (403).
|
||||
2. Inicia sesión como `admin`: aparece el botón y la página se abre.
|
||||
3. Crea una cuenta con el enlace «Crear una cuenta» del menú, concede el permiso al rol
|
||||
**authenticated** e inicia sesión con ella: también puede publicar.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Opciones de configuración](../reference/configuration.md#user): registro, sesiones y
|
||||
contraseñas.
|
||||
- [Extensiones oficiales](../reference/extensions.md): lo que aportan `pagetop-user` y
|
||||
`pagetop-admin`.
|
||||
89
doc/v0.6/es/src/intro.md
Normal file
89
doc/v0.6/es/src/intro.md
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
# PageTop
|
||||
|
||||
> **La web clásica, con la potencia de Rust.**
|
||||
> HTML generado en el servidor, componentes reutilizables y un único binario que lo lleva todo
|
||||
> dentro.
|
||||
|
||||
PageTop es un entorno de desarrollo para crear soluciones web **modulares, extensibles y
|
||||
configurables** en [Rust](https://www.rust-lang.org/es). Las páginas se generan en el servidor
|
||||
(SSR) con HTML, CSS y JavaScript de toda la vida, sin compilar un *frontend* aparte ni mantener dos
|
||||
aplicaciones que se hablan por una API.
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
|
||||
struct HelloWorld;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for HelloWorld {
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router.route("/", web::get(home))
|
||||
}
|
||||
}
|
||||
|
||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_child(Html::with(|_| html! { h1 { "Hello, world!" } }))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
#[pagetop::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
Application::prepare(&HelloWorld).await.run().await
|
||||
}
|
||||
```
|
||||
|
||||
Veinte líneas, un `cargo run`, y tienes un servidor web sirviendo una página completa en
|
||||
`http://localhost:8080`.
|
||||
|
||||
## Lo que te llevas
|
||||
|
||||
- **Un solo lenguaje, de principio a fin.** Rutas, lógica, componentes y plantillas son código
|
||||
Rust. El compilador revisa tu HTML igual que revisa el resto del programa.
|
||||
- **Componentes de verdad.** Botones, formularios, tablas, menús o rejillas son tipos Rust que
|
||||
se configuran con métodos encadenados, se reutilizan entre proyectos y se adaptan al tema activo.
|
||||
- **Temas intercambiables.** El aspecto se cambia sin tocar el código de las páginas: el tema
|
||||
puede reescribir cómo se pinta cualquier componente.
|
||||
- **Extensiones como piezas de LEGO.** Cada funcionalidad es una extensión que declara sus
|
||||
dependencias, sus rutas, sus ajustes y sus traducciones. Las aplicaciones se componen sumando
|
||||
extensiones.
|
||||
- **Interactividad sin escribir JavaScript.** Con [HTMX](explanation/htmx.md), un atributo en un
|
||||
botón basta para actualizar una parte de la página con HTML generado en el servidor: búsquedas en
|
||||
vivo, edición en línea, *scroll* infinito...
|
||||
- **Multilingüe desde el primer día.** Traducciones con [Fluent](https://projectfluent.org/),
|
||||
integradas en el binario.
|
||||
- **Despliegue trivial.** Estilos, *scripts* y traducciones viajan dentro del ejecutable. Copias
|
||||
un archivo, añades la configuración y listo.
|
||||
- **Rendimiento y seguridad de Rust.** Sin recolector de basura, con *async* sobre Tokio y
|
||||
Axum, y con los errores de memoria descartados por el compilador.
|
||||
|
||||
## ¿Para quién es?
|
||||
|
||||
Para quien quiere construir aplicaciones web de gestión, portales, intranets o sitios con
|
||||
contenido, y prefiere **HTML servido desde el servidor** (con un toque de
|
||||
[HTMX](https://htmx.org) cuando haga falta interactividad) a montar un *frontend* JavaScript
|
||||
completo. Si conoces lo básico de Rust, puedes empezar hoy; si aún no, [El libro de
|
||||
Rust](https://doc.rust-lang.org/book/) es el mejor punto de partida.
|
||||
|
||||
¿Dudas entre PageTop y otro *framework*? [PageTop frente a otros
|
||||
*frameworks*](explanation/comparison.md) los compara con franqueza.
|
||||
|
||||
## Cómo está organizada esta guía
|
||||
|
||||
| | Para... | Empieza por |
|
||||
|---|---|---|
|
||||
| **[Tutoriales](tutorials/first-app.md)** | Aprender haciendo, de principio a fin | [Tu primera aplicación](tutorials/first-app.md), en 10 minutos |
|
||||
| **Guías prácticas** | Resolver una tarea concreta | [Añadir rutas](how-to/routes.md), [Buscar mientras se escribe](how-to/htmx-search.md)... |
|
||||
| **[Referencia](reference/configuration.md)** | Consultar opciones, componentes y atributos | [Referencia rápida](reference/cheatsheet.md) |
|
||||
| **[Explicación](explanation/why.md)** | Entender el porqué | [Arquitectura](explanation/architecture.md) |
|
||||
|
||||
Si es tu primera vez, sigue los tutoriales en orden: en algo más de una hora pasas de no tener nada
|
||||
instalado a una aplicación interactiva con base de datos y pruebas.
|
||||
|
||||
Todos los ejemplos están escritos contra la versión actual de PageTop, y se compilan (y, los que
|
||||
pueden, se ejecutan) cada vez que PageTop cambia.
|
||||
|
||||
> **Aviso:** PageTop está en desarrollo activo y su API puede cambiar hasta la versión **1.0.0**.
|
||||
> Pruébalo, constrúyelo y cuéntanos qué tal, pero piénsalo dos veces antes de llevarlo a
|
||||
> producción.
|
||||
136
doc/v0.6/es/src/reference/cheatsheet.md
Normal file
136
doc/v0.6/es/src/reference/cheatsheet.md
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
# Referencia rápida
|
||||
|
||||
Lo esencial de PageTop en una página. Cada línea enlaza con la guía que lo explica.
|
||||
|
||||
## Aplicación
|
||||
|
||||
| Quiero... | Código |
|
||||
|---|---|
|
||||
| [Arrancar](../tutorials/first-app.md) | `Application::prepare(&MyApp).await.run().await` |
|
||||
| [Declarar dependencias](../how-to/extensions.md) | `fn dependencies(&self) -> Vec<ExtensionRef> { vec![&Other] }` |
|
||||
| [Ejecutar código al arrancar](../how-to/extensions.md#3-inicialízala-al-arrancar) | `async fn initialize(&self) -> Result<(), BoxError>` |
|
||||
| [Añadir rutas](../how-to/routes.md) | `router.route("/path", web::get(handler))` |
|
||||
| [Servir archivos](../how-to/assets.md) | `serve_static_files!(router, ["./static", app] => "/static")` |
|
||||
| [Leer un ajuste](../how-to/configuration.md) | `global::SETTINGS.app.name` |
|
||||
| [Escribir una traza](../how-to/logging.md) | `trace::info!("...")` |
|
||||
| [Compartir un servicio](../how-to/services.md) | `static X: LazyLock<Service> = LazyLock::new(...)` |
|
||||
| [Añadir *middleware*](../how-to/middleware.md) | `fn configure_middleware(&self, router: Router) -> Router` |
|
||||
|
||||
## *Handlers*
|
||||
|
||||
| Quiero... | Código |
|
||||
|---|---|
|
||||
| [Una página](../how-to/pages.md) | `Page::new(request).with_child(...).render().await` |
|
||||
| [Un segmento de la URL](../how-to/routes.md#3-lee-los-datos-de-la-petición) | `web::Path(id): web::Path<u32>` |
|
||||
| [Parámetros de consulta](../how-to/routes.md#3-lee-los-datos-de-la-petición) | `web::Query(q): web::Query<T>` |
|
||||
| [Un formulario](../how-to/forms.md#3-recibe-y-valida-los-datos) | `web::Form(data): web::Form<T>` (el último parámetro) |
|
||||
| [Un error 404](../how-to/error-pages.md) | `Err(ErrorPage::NotFound(Some(request)))` |
|
||||
| [Redirigir](../how-to/routes.md#4-elige-la-respuesta) | `Redirect::see_other("/target")` |
|
||||
| [Responder JSON](../how-to/routes.md#4-elige-la-respuesta) | `Json(value)` |
|
||||
| [Un error de API en JSON](../how-to/error-pages.md#7-errores-de-una-api-json) | `impl IntoResponse for ApiError` |
|
||||
| [Exigir un permiso](../how-to/users.md) | `require_permission(&request, &MyPermission::X)?` |
|
||||
|
||||
## Páginas
|
||||
|
||||
| Quiero... | Código |
|
||||
|---|---|
|
||||
| [Título](../how-to/pages.md) | `.with_title(Lc::n("..."))` |
|
||||
| [Contenido en una región](../how-to/pages.md#2-reparte-el-contenido-en-regiones) | `.with_child_in(&CoreRegions::Aside, component)` |
|
||||
| [Una hoja de estilos](../how-to/pages.md#4-añade-estilos-y-scripts) | `.with_assets(StyleSheet::from("/static/app.css"))` |
|
||||
| [Un *script*](../how-to/pages.md#4-añade-estilos-y-scripts) | `.with_assets(JavaScript::defer("/static/app.js"))` |
|
||||
| [Un aviso al usuario](../how-to/components.md#mensajes-al-usuario) | `page.context().push_message(MessageLevel::Info, Lc::n("..."))` |
|
||||
| [Algo en todas las páginas](../how-to/extensions.md#4-pon-componentes-en-todas-las-páginas) | `InRegion::Global(&CoreRegions::Footer).add(component)` |
|
||||
|
||||
## Textos
|
||||
|
||||
| Quiero... | Código |
|
||||
|---|---|
|
||||
| [Cargar traducciones](../how-to/localization.md) | `include_locales!(LOCALES_APP);` |
|
||||
| [Texto traducido](../how-to/localization.md) | `Lc::t("key", &LOCALES_APP)` |
|
||||
| [Texto literal](../how-to/localization.md) | `Lc::n("text")` |
|
||||
| [Con una variable](../how-to/localization.md) | `.with_arg("name", "Ana")` |
|
||||
| [Con plural](../how-to/localization.md) | `.with_number("total", 3)` |
|
||||
| [Como contenido HTML](../how-to/localization.md) | `(text.using(cx))` |
|
||||
| [Como atributo HTML](../how-to/localization.md) | `title=[text.lookup(cx)]` |
|
||||
| [Un enlace interno](../how-to/navigation.md#enlaces-que-conservan-el-idioma) | `a href=(cx.route("/path")) { ... }` |
|
||||
|
||||
## Componentes
|
||||
|
||||
| Quiero... | Código |
|
||||
|---|---|
|
||||
| [Marcado puntual](../how-to/html.md) | `Html::with(\|cx\| html! { ... })` |
|
||||
| [Agrupar](../how-to/components.md#contenedores) | `Container::new().with_child(...)` |
|
||||
| [Un botón-enlace](../how-to/components.md#botones) | `Button::anchor(Lc::n("..."), "/path")` |
|
||||
| [Una clase CSS](../how-to/components.md#identificadores-clases-y-estilos) | `.with_prop(PropsOp::add_classes("..."))` |
|
||||
| [Una fila o columna](../how-to/layout.md) | `Flex::new().with_direction(flex::Direction::Row)` |
|
||||
| [Una rejilla](../how-to/layout.md#grid-rejillas) | `Grid::new().with_columns(grid::Tracks::repeat(3, grid::AxisTrack::Fraction(1.0)))` |
|
||||
| [Un menú](../how-to/navigation.md) | `Nav::new().with_item(nav::Item::link(Lc::n("..."), "/path"))` |
|
||||
| [Una tabla](../how-to/tables.md) | `Table::new().with_column(...).with_row(...)` |
|
||||
|
||||
## HTMX
|
||||
|
||||
| Quiero... | Código |
|
||||
|---|---|
|
||||
| [Cargar HTMX en todas las páginas](../how-to/htmx-setup.md) | `vec![&pagetop_htmx::Htmx]` en `dependencies()` |
|
||||
| [Pedir un fragmento al pulsar](../how-to/htmx-setup.md) | `button hx-get="/path" hx-target="#id" { ... }` |
|
||||
| [Atributos en un componente](../how-to/htmx-setup.md#3-ponlos-en-componentes-con-with_prop) | `.with_prop(PropsOp::set(hx::POST, "/path"))` |
|
||||
| [Saber si llama HTMX](../how-to/htmx-setup.md#6-una-ruta-dos-respuestas) | `request.is_htmx()` |
|
||||
| [Responder un fragmento](../how-to/htmx-setup.md#4-responde-con-un-fragmento) | `HtmxResponse::new(html! { ... })` |
|
||||
| [Renderizar un componente suelto](../how-to/htmx-setup.md#5-renderiza-componentes-en-un-fragmento) | `component.render(&mut Context::new(request)).await` |
|
||||
| [Actualizar otra zona a la vez](../how-to/htmx-delete.md) | `.oob(html! { span id="x" hx-swap-oob="true" { ... } })` |
|
||||
| [Avisar a otras partes](../how-to/htmx-responses.md#2-avisar-a-otras-partes-de-la-página) | `.trigger("event")` y `hx-trigger="event from:body"` |
|
||||
| [Redirigir tras una acción](../how-to/htmx-responses.md#3-redirigir) | `HtmxResponse::empty().redirect("/path")` |
|
||||
|
||||
## Datos, usuarios y pruebas
|
||||
|
||||
| Quiero... | Código |
|
||||
|---|---|
|
||||
| [Aplicar migraciones](../how-to/database.md#4-aplícalas-al-arrancar) | `install_migrations!(m20261015_000001_create_plots)?` |
|
||||
| [Consultar](../how-to/database.md#6-consulta-los-datos) | `plot::Entity::find().filter(..).all(dbconn()).await?` |
|
||||
| [Paginar](../how-to/database.md#6-consulta-los-datos) | `paginate(plot::Entity::find(), page, 20).await?` |
|
||||
| [Traer lo relacionado](../how-to/database.md#7-relaciona-tablas) | `harvest::Entity::find().find_also_related(plot::Entity)` |
|
||||
| [SQL a mano](../how-to/database.md#8-escribe-sql-a-mano) | `fetch_all(&stmt).await?` / `execute("...").await?` |
|
||||
| [Saber quién pide la página](../how-to/users.md#5-protege-rutas-y-adapta-la-interfaz) | `cx.current_user()` |
|
||||
| [Comprobar un permiso](../how-to/users.md#5-protege-rutas-y-adapta-la-interfaz) | `has_permission(&request, &MyPermission::X)` |
|
||||
| [Una página en el panel](../how-to/admin.md) | `DeclareAdminPages::new(declare_pages)` |
|
||||
| [Leer un ajuste del panel](../how-to/admin.md#4-lee-los-ajustes-guardados) | `pagetop_admin::settings::get_or("app.key", default).await` |
|
||||
| [Probar una ruta](../how-to/testing.md) | `web::test::send_request(&app, request).await` |
|
||||
|
||||
## Crear un componente
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
|
||||
#[derive(AutoDefault, Clone, Debug, Getters)]
|
||||
pub struct MyComponent {
|
||||
/// Returns the text.
|
||||
text: Lc,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Component for MyComponent {
|
||||
fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
Ok(html! { div class="my-component" { (self.text().using(cx)) } })
|
||||
}
|
||||
}
|
||||
|
||||
#[builder_impl]
|
||||
impl MyComponent {
|
||||
/// Sets the text.
|
||||
pub fn with_text(mut self, text: Lc) -> Self {
|
||||
self.text = text;
|
||||
self
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Más información
|
||||
|
||||
- La API completa, con ejemplos, en [docs.rs/pagetop](https://docs.rs/pagetop).
|
||||
- El código y los ejemplos ejecutables, en el
|
||||
[repositorio oficial](https://git.cillero.es/manuelcillero/pagetop).
|
||||
- Todas las opciones de configuración, en [Opciones de configuración](configuration.md).
|
||||
94
doc/v0.6/es/src/reference/components.md
Normal file
94
doc/v0.6/es/src/reference/components.md
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
# Catálogo de componentes
|
||||
|
||||
Los componentes que trae PageTop, con sus constructores. Todos funcionan con cualquier tema, que
|
||||
decide cómo se ven. Para aprender a usarlos, empieza por [Usar componentes](../how-to/components.md).
|
||||
|
||||
## Lo común a todos
|
||||
|
||||
| Método | Para qué |
|
||||
|---|---|
|
||||
| `with_id(id)` | Fija el `id` del elemento raíz |
|
||||
| `with_prop(op)` | Añade o quita clases, atributos y estilos (`PropsOp`), o ajustes de maquetación (`FlexItem`, `GridItem`, `Margin`, `Padding`) |
|
||||
| `with_*()` / `alter_*()` | Configuran el componente: los primeros al construirlo, los segundos sobre uno ya creado |
|
||||
| `render(cx)` | Lo renderiza con un `Context`; dentro de una página lo hace `Page` por ti |
|
||||
|
||||
Los textos se pasan como [`Lc`](../how-to/localization.md), y las rutas como `Route`, que conserva
|
||||
el idioma del visitante.
|
||||
|
||||
## Contenido
|
||||
|
||||
| Componente | Qué genera | Constructores |
|
||||
|---|---|---|
|
||||
| `Html` | Marcado puntual con `html!` | `Html::with(\|cx\| html! { ... })` |
|
||||
| `Block` | Bloque con título opcional y contenido | `Block::new()` |
|
||||
| `Intro` | Portada con título, eslogan, botón y contenido | `Intro::new()`, `Intro::custom()` |
|
||||
| `Image` | Imagen, a su tamaño, adaptable o en miniatura | `Image::with(image::Source::plain(..))`, `responsive(..)`, `thumbnail(..)` |
|
||||
| `Badge` | Etiqueta pequeña de estado | `Badge::labeled()`, `primary()`, `neutral()`, `success()`, `info()`, `warning()`, `severe()` |
|
||||
| `Button` | Botón o enlace con aspecto de botón | `Button::submit()`, `reset()`, `plain()`, `anchor(label, ruta)` |
|
||||
| `Messages` | Avisos acumulados en el contexto | `Messages::new()` |
|
||||
| `Dialog` | Ventana modal con título, cuerpo y pie | `Dialog::new()` |
|
||||
| `PoweredBy` | Pie con el crédito de PageTop | `PoweredBy::new()` |
|
||||
|
||||
## Estructura y maquetación
|
||||
|
||||
| Componente | Qué genera | Constructores |
|
||||
|---|---|---|
|
||||
| `Container` | Agrupa componentes en una etiqueta | `Container::new()` (`<div>`), `main()`, `header()`, `footer()`, `section()`, `article()` |
|
||||
| `Flex` | Filas o columnas | `Flex::new()`, `inline()`, `at(punto)`, `inline_at(punto)` |
|
||||
| `Grid` | Rejillas | `Grid::new()`, `columns(..)`, `rows(..)`, `inline()`, `at(punto)`, `inline_at(punto)` |
|
||||
|
||||
Los ajustes de cada hijo se pasan a su `with_prop()`: `FlexItem` para `Flex`, `GridItem` para
|
||||
`Grid`. Ver [Maquetar con Flex y Grid](../how-to/layout.md).
|
||||
|
||||
## Navegación
|
||||
|
||||
| Componente | Qué genera | Constructores |
|
||||
|---|---|---|
|
||||
| `Brand` | Logotipo y nombre del sitio | `Brand::new()` |
|
||||
| `Nav` | Menú de enlaces | `Nav::new()`, con `nav::Item::link()`, `link_blank()`, `link_disabled()`, `dropdown()`, `html()`, `label()` |
|
||||
| `Dropdown` | Menú desplegable | `Dropdown::new()`, con `dropdown::Item::link()`, `button()`, `header()`, `label()`, `divider()` |
|
||||
| `Navbar` | Barra con marca y menús, plegable | `Navbar::simple()`, `simple_toggle()`, `simple_brand_left(..)`, `brand_left(..)`, `brand_right(..)`, con `navbar::Item::nav()`, `brand()`, `form()`, `text()` |
|
||||
| `Breadcrumb` | Migas de pan | `Breadcrumb::new()`, con `breadcrumb::Crumb::new()`, `text()`, `current()` |
|
||||
|
||||
Ver [Añadir navegación](../how-to/navigation.md).
|
||||
|
||||
## Formularios
|
||||
|
||||
| Componente | Qué genera | Constructores |
|
||||
|---|---|---|
|
||||
| `Form` | El formulario | `Form::new()` |
|
||||
| `form::Fieldset` | Grupo de campos con leyenda | `form::Fieldset::new()` |
|
||||
| `form::input::Field` | Campos de texto | `text()`, `email()`, `url()`, `telephone()`, `search()`, `password()` |
|
||||
| `form::Textarea` | Área de texto | `form::Textarea::new()` |
|
||||
| `form::Number`, `form::Range` | Números y deslizadores | `new()` |
|
||||
| `form::Checkbox` | Casilla o interruptor | `check()`, `switch()` |
|
||||
| `form::check::Field` | Grupo de casillas | `new()`, con `form::check::Item` |
|
||||
| `form::radio::Field` | Opciones excluyentes | `new()`, con `form::radio::Item` |
|
||||
| `form::select::Field` | Lista desplegable | `new()`, con `form::select::Item` |
|
||||
| `form::date::Field` | Fecha, hora, o las dos | `date()`, `time()`, `datetime()` |
|
||||
| `form::Hidden` | Campo oculto | `form::Hidden::field(name, value)` |
|
||||
| `form::SelectLanguage`, `SelectTheme`, `SelectTimezone` | Selectores de idioma, tema y zona horaria | `new()` |
|
||||
|
||||
Ver [Crear y procesar formularios](../how-to/forms.md).
|
||||
|
||||
## Datos
|
||||
|
||||
| Componente | Qué genera | Constructores |
|
||||
|---|---|---|
|
||||
| `Table` | Tabla con cabeceras ordenables | `Table::new()`, con `table::Column::new()`, `table::Row::new()`, `table::Cell::new()` y `table::SortLink::new()` |
|
||||
| `Pager` | Paginador de un listado | `Pager::new()` |
|
||||
|
||||
Ver [Mostrar tablas ordenables y paginadas](../how-to/tables.md).
|
||||
|
||||
## De las extensiones
|
||||
|
||||
| Componente | Extensión | Qué genera |
|
||||
|---|---|---|
|
||||
| `LoginForm` | `pagetop-user` | Formulario de inicio de sesión |
|
||||
| `AccountMenu` | `pagetop-user` | Menú de cuenta; también como función, `account_menu(cx)` |
|
||||
| `UserName` | `pagetop-user` | Nombre visible de un usuario |
|
||||
| `bs::Offcanvas` | `pagetop-bootsier` | Panel lateral deslizante (sólo con Bootsier) |
|
||||
| `bs::Icon` | `pagetop-bootsier` | Iconos de Bootstrap Icons (sólo con Bootsier) |
|
||||
|
||||
Los componentes de un tema sólo funcionan con ese tema: úsalos en la aplicación, no en extensiones
|
||||
que deban servir para cualquier tema.
|
||||
187
doc/v0.6/es/src/reference/configuration.md
Normal file
187
doc/v0.6/es/src/reference/configuration.md
Normal file
|
|
@ -0,0 +1,187 @@
|
|||
# Opciones de configuración
|
||||
|
||||
Todas las opciones que leen PageTop y sus extensiones oficiales, sección a sección. Para aprender a
|
||||
usarlas, empieza por [Configurar la aplicación](../how-to/configuration.md).
|
||||
|
||||
## Carga y precedencia
|
||||
|
||||
Los archivos se leen del directorio `config/`, en este orden; cada uno sobrescribe a los anteriores
|
||||
sólo en las claves que define:
|
||||
|
||||
| Orden | Archivo | Uso habitual |
|
||||
|---|---|---|
|
||||
| 1 | `config/common.toml` | Ajustes comunes a todos los entornos |
|
||||
| 2 | `config/{modo}.toml` | Ajustes del modo de ejecución |
|
||||
| 3 | `config/local.{modo}.toml` | Ajustes locales de ese modo (no se versiona) |
|
||||
| 4 | `config/local.toml` | Ajustes locales para cualquier modo (no se versiona) |
|
||||
|
||||
Todos son opcionales. Sólo se leen dos variables de entorno, y ninguna sobrescribe claves sueltas:
|
||||
|
||||
| Variable | Efecto |
|
||||
|---|---|
|
||||
| `PAGETOP_RUN_MODE` | El modo de ejecución, `{modo}` en la tabla anterior. Por defecto, `default` |
|
||||
| `CONFIG_DIR` | Otro directorio de configuración en lugar de `config/` |
|
||||
|
||||
Reglas comunes a todas las secciones:
|
||||
|
||||
- Una **clave desconocida** o un **valor no válido** impiden arrancar, con un mensaje que indica la
|
||||
sección y la clave.
|
||||
- Una **sección** que no corresponde a PageTop ni a ninguna extensión habilitada se ignora, con un
|
||||
aviso al arrancar.
|
||||
- En los valores fijos del núcleo (`"Full"`, `"Daily"`...) da igual escribir mayúsculas o
|
||||
minúsculas.
|
||||
|
||||
## `[app]`
|
||||
|
||||
```toml
|
||||
[app]
|
||||
name = "Urban Garden"
|
||||
theme = "Bootsier"
|
||||
language = "es-ES"
|
||||
lang_negotiation = "Full"
|
||||
timezone = "Europe/Madrid"
|
||||
startup_banner = "Slant"
|
||||
```
|
||||
|
||||
| Clave | Tipo | Por defecto | Notas |
|
||||
|---|---|---|---|
|
||||
| `name` | Texto | `"PageTop App"` | Nombre de la aplicación: título de las páginas, pie, banner |
|
||||
| `theme` | Texto | `"Basic"` | Tema predeterminado. Si no está habilitado, se usa `"Basic"` y se avisa |
|
||||
| `language` | Texto | Ninguno | Idioma predeterminado, en BCP 47 (`"es-ES"`). Sin él, se negocia |
|
||||
| `lang_negotiation` | `Full`, `NoQuery`, `ConfigOnly` | `"Full"` | Cómo se decide el idioma de cada petición (ver abajo) |
|
||||
| `timezone` | Texto | `"UTC"` | Zona horaria del sitio, en formato IANA (`"Europe/Madrid"`) |
|
||||
| `timezone_regions` | Texto | `""` (todas) | Regiones ofrecidas al elegir zona horaria, separadas por comas (`"Europe, America"`) |
|
||||
| `timezone_order` | `Nearest`, `Alphabetical`, `Listed` | `"Nearest"` | Orden de esas regiones en el selector |
|
||||
| `timezone_per_user` | Booleano | `true` | Si cada usuario puede tener su propia zona horaria |
|
||||
| `startup_banner` | `Off`, `Slant`, `Small`, `Speed`, `Starwars` | `"Slant"` | Banner al arrancar |
|
||||
|
||||
`lang_negotiation`:
|
||||
|
||||
| Valor | El idioma de cada petición sale de... |
|
||||
|---|---|
|
||||
| `Full` | `?lang=` de la URL, idioma del usuario, `language`, `Accept-Language` y respaldo (`en-US`) |
|
||||
| `NoQuery` | Lo mismo, sin `?lang=` |
|
||||
| `ConfigOnly` | Sólo `language` o el idioma de respaldo. No se ofrece elegir idioma |
|
||||
|
||||
## `[server]`
|
||||
|
||||
```toml
|
||||
[server]
|
||||
bind_address = "0.0.0.0"
|
||||
bind_port = 8080
|
||||
```
|
||||
|
||||
| Clave | Tipo | Por defecto | Notas |
|
||||
|---|---|---|---|
|
||||
| `bind_address` | Texto | `"localhost"` | Dirección en la que escucha. `"0.0.0.0"` acepta conexiones de fuera |
|
||||
| `bind_port` | Entero | `8080` | Puerto |
|
||||
|
||||
## `[log]`
|
||||
|
||||
```toml
|
||||
[log]
|
||||
tracing = "Info,sqlx=Warn"
|
||||
rolling = "Daily"
|
||||
format = "Json"
|
||||
```
|
||||
|
||||
| Clave | Tipo | Por defecto | Notas |
|
||||
|---|---|---|---|
|
||||
| `enabled` | Booleano | `true` | Activa o desactiva las trazas |
|
||||
| `tracing` | Texto | `"Info"` | Nivel (`Error`, `Warn`, `Info`, `Debug`, `Trace`) y niveles por módulo. Si no es válido, se usa `"Info"` y se avisa |
|
||||
| `rolling` | `Stdout`, `Daily`, `Hourly`, `Minutely`, `Endless` | `"Stdout"` | Terminal, archivos con rotación o un único archivo |
|
||||
| `path` | Texto | `"log"` | Directorio de los archivos de traza |
|
||||
| `prefix` | Texto | `"tracing.log"` | Prefijo de esos archivos |
|
||||
| `format` | `Full`, `Compact`, `Pretty`, `Json` | `"Full"` | Formato de cada traza |
|
||||
|
||||
## `[dev]`
|
||||
|
||||
| Clave | Tipo | Por defecto | Notas |
|
||||
|---|---|---|---|
|
||||
| `pagetop_static_dir` | Texto | `""` | Directorio `static/` de PageTop para servir sus archivos desde disco, editables sin recompilar. Vacío: los del binario |
|
||||
|
||||
## `[database]`
|
||||
|
||||
De [`pagetop-seaorm`](extensions.md#seaorm). Ver [Conectar una base de
|
||||
datos](../how-to/database.md).
|
||||
|
||||
```toml
|
||||
[database]
|
||||
db_type = "postgres"
|
||||
db_name = "garden"
|
||||
db_user = "garden"
|
||||
db_host = "localhost"
|
||||
```
|
||||
|
||||
| Clave | Tipo | Por defecto | Notas |
|
||||
|---|---|---|---|
|
||||
| `db_type` | `mysql`, `postgres`, `sqlite` | Ninguno | **Obligatorio.** También valen `mariadb` y `postgresql` |
|
||||
| `db_name` | Texto | `""` | Nombre de la base de datos; en SQLite, el archivo (admite parámetros como `?mode=rwc`) |
|
||||
| `db_user` | Texto | `""` | Usuario (MySQL y PostgreSQL) |
|
||||
| `db_pass` | Texto | `""` | Contraseña (MySQL y PostgreSQL). Mejor en `local.toml` |
|
||||
| `db_host` | Texto | `"localhost"` | Servidor (MySQL y PostgreSQL) |
|
||||
| `db_port` | Entero | 3306 / 5432 | Puerto, si no es el del motor |
|
||||
| `max_pool_size` | Entero | `5` | Conexiones simultáneas como máximo |
|
||||
|
||||
## `[user]`
|
||||
|
||||
De [`pagetop-user`](extensions.md#usuarios-y-permisos). Ver [Añadir usuarios y
|
||||
permisos](../how-to/users.md).
|
||||
|
||||
| Clave | Tipo | Por defecto | Notas |
|
||||
|---|---|---|---|
|
||||
| `allow_registration` | Booleano | `true` | Los visitantes pueden crear su propia cuenta |
|
||||
| `require_email_verification` | Booleano | `false` | Las cuentas nuevas quedan pendientes hasta verificar el correo |
|
||||
| `max_failed_logins` | Entero | `5` | Intentos fallidos antes de bloquear la cuenta |
|
||||
| `failed_login_window_secs` | Entero | `900` | Reservada; todavía no tiene efecto |
|
||||
| `locked_for_secs` | Entero | `600` | Segundos que dura el bloqueo |
|
||||
| `login_strict` | Booleano | `false` | Dificulta que el navegador recuerde las credenciales |
|
||||
|
||||
### `[user.session]`
|
||||
|
||||
| Clave | Tipo | Por defecto | Notas |
|
||||
|---|---|---|---|
|
||||
| `cookie_name` | Texto | `"pagetop"` | Nombre de la *cookie* de sesión |
|
||||
| `secure_cookie` | Booleano | `false` | Sólo por HTTPS. **Actívalo en producción** |
|
||||
| `idle_secs` | Entero | `7200` | Inactividad tras la que caduca la sesión (2 horas) |
|
||||
| `remember_idle_secs` | Entero | `1209600` | Lo mismo, si se marcó «recordarme» (14 días) |
|
||||
| `write_interval_secs` | Entero | `60` | Mínimo entre dos escrituras de la misma sesión para prorrogarla |
|
||||
|
||||
### `[user.password]`
|
||||
|
||||
| Clave | Tipo | Por defecto | Notas |
|
||||
|---|---|---|---|
|
||||
| `argon2_m_cost` | Entero | `19456` | Memoria de Argon2id, en KiB. Si cambia, las contraseñas se recifran en el siguiente acceso |
|
||||
| `argon2_t_cost` | Entero | `2` | Iteraciones |
|
||||
| `argon2_p_cost` | Entero | `1` | Hilos |
|
||||
| `min_length` | Entero | `8` | Longitud mínima de una contraseña |
|
||||
|
||||
### `[user.seed]`
|
||||
|
||||
El primer administrador, que se crea si no existe ningún usuario.
|
||||
|
||||
| Clave | Tipo | Por defecto | Notas |
|
||||
|---|---|---|---|
|
||||
| `admin_username` | Texto | `"admin"` | Nombre de usuario |
|
||||
| `admin_email` | Texto | `"admin@example.com"` | Correo |
|
||||
| `admin_password` | Texto | Ninguno | Sin valor, se genera una y se muestra una sola vez en el terminal |
|
||||
|
||||
### `[user.admin]`
|
||||
|
||||
| Clave | Tipo | Por defecto | Notas |
|
||||
|---|---|---|---|
|
||||
| `list_page_size` | Entero | `20` | Filas por página en los listados de administración |
|
||||
|
||||
## `[bootsier]`
|
||||
|
||||
De [`pagetop-bootsier`](extensions.md#bootsier).
|
||||
|
||||
| Clave | Tipo | Por defecto | Notas |
|
||||
|---|---|---|---|
|
||||
| `max_width` | Texto | `"1440px"` | Ancho máximo de la página (`"100%"`, `"90rem"`...) |
|
||||
| `static_dir` | Texto | `""` | Como `pagetop_static_dir`, para los archivos de Bootsier |
|
||||
|
||||
## El archivo de referencia
|
||||
|
||||
El repositorio de PageTop incluye `config/reference.toml`, con todas estas opciones comentadas y su
|
||||
valor por defecto. No se carga nunca: sirve para copiar de él lo que necesites.
|
||||
209
doc/v0.6/es/src/reference/extensions.md
Normal file
209
doc/v0.6/es/src/reference/extensions.md
Normal file
|
|
@ -0,0 +1,209 @@
|
|||
# Extensiones oficiales
|
||||
|
||||
PageTop mantiene un núcleo pequeño. Lo demás llega como extensiones que se suman a tu aplicación
|
||||
con una línea en `dependencies()`.
|
||||
|
||||
| Extensión | Qué aporta | Basada en |
|
||||
|---|---|---|
|
||||
| [`pagetop-bootsier`](#bootsier) | Tema completo para cualquier aplicación | [Bootstrap 5](https://getbootstrap.com) |
|
||||
| [`pagetop-htmx`](#htmx) | Interactividad sin escribir JavaScript | [HTMX 2](https://htmx.org) |
|
||||
| [`pagetop-seaorm`](#seaorm) | Bases de datos PostgreSQL, MySQL y SQLite | [SeaORM](https://www.sea-ql.org/SeaORM) |
|
||||
| [`pagetop-user`](#usuarios-y-permisos) | Usuarios, sesiones, roles y permisos | [Argon2](https://docs.rs/argon2) para las contraseñas |
|
||||
| [`pagetop-admin`](#administración) | Panel de administración en `/admin` | Componentes del núcleo |
|
||||
| [`pagetop-aliner`](../how-to/themes.md) | Tema de pruebas que muestra la estructura de la página | Componentes del núcleo |
|
||||
| [`pagetop-mdbook`](#documentación-con-mdbook) | Libros de mdBook servidos como páginas PageTop | [mdBook](https://rust-lang.github.io/mdBook/) |
|
||||
|
||||
## Dependencias y *features*
|
||||
|
||||
Todas se añaden igual al `Cargo.toml`, y casi ninguna tiene *features*:
|
||||
|
||||
| *Crate* | *Features* | Dónde se activan |
|
||||
|---|---|---|
|
||||
| `pagetop-seaorm` | `postgres`, `mysql`, `sqlite`: el motor de base de datos | Sólo en la **aplicación**; vale para todas sus extensiones (ve [Elige el motor](../how-to/database.md#1-elige-el-motor)) |
|
||||
| `pagetop-user` | `demo-data`: siembra roles y usuarios ficticios para explorar la administración | En la aplicación, sólo para desarrollo o demostraciones |
|
||||
| El resto | Ninguna | |
|
||||
|
||||
## Bootsier
|
||||
|
||||
Tema completo sobre [Bootstrap 5.3](https://getbootstrap.com): adapta los componentes del núcleo
|
||||
a Bootstrap y añade los suyos (como `Offcanvas`) y un selector de modo claro/oscuro.
|
||||
|
||||
```toml
|
||||
[app]
|
||||
theme = "Bootsier"
|
||||
|
||||
[bootsier]
|
||||
max_width = "90rem" # Maximum width of the content.
|
||||
```
|
||||
|
||||
Recuerda declarar `&pagetop_bootsier::Bootsier` como dependencia de tu aplicación. Más en [Crear un
|
||||
tema](../how-to/themes.md).
|
||||
|
||||
## HTMX
|
||||
|
||||
Con `pagetop-htmx`, todas las páginas incluyen [HTMX 2](https://htmx.org): basta con añadir
|
||||
atributos `hx-*` para que un enlace o un formulario actualice sólo una parte de la página.
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
|
||||
pub struct Clock;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Clock {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_htmx::Htmx]
|
||||
}
|
||||
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router
|
||||
.route("/", web::get(home))
|
||||
.route("/time", web::get(time))
|
||||
}
|
||||
}
|
||||
|
||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_child(Html::with(|_| html! {
|
||||
button hx-get="/time" hx-target="#result" { "What time is it?" }
|
||||
div id="result" {}
|
||||
}))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
// Returns only the HTML fragment that HTMX places in #result.
|
||||
async fn time() -> Markup {
|
||||
html! { p { "It is " (Utc::now().format("%H:%M")) " UTC" } }
|
||||
}
|
||||
```
|
||||
|
||||
También ofrece constantes para los atributos (`hx::GET`, `hx::TARGET`...), que se aplican a
|
||||
cualquier componente con `with_prop()`, y ayudas para leer y responder a peticiones HTMX. Diez
|
||||
guías prácticas, empezando por [Añadir HTMX a una aplicación](../how-to/htmx-setup.md), y la
|
||||
[referencia](htmx.md) lo cuentan todo.
|
||||
|
||||
## SeaORM
|
||||
|
||||
Conecta tu aplicación a una base de datos con [SeaORM](https://www.sea-ql.org/SeaORM) y aplica las
|
||||
migraciones al arrancar. Elige el motor con una *feature* en tu `Cargo.toml`:
|
||||
|
||||
```toml
|
||||
[features]
|
||||
default = ["postgres"]
|
||||
postgres = ["pagetop-seaorm/postgres"]
|
||||
mysql = ["pagetop-seaorm/mysql"]
|
||||
sqlite = ["pagetop-seaorm/sqlite"]
|
||||
```
|
||||
|
||||
Configura la conexión (la contraseña, mejor en `config/local.toml`):
|
||||
|
||||
```toml
|
||||
[database]
|
||||
db_type = "postgres"
|
||||
db_name = "garden"
|
||||
db_user = "garden"
|
||||
db_pass = "secret"
|
||||
db_host = "localhost"
|
||||
```
|
||||
|
||||
Y declara la extensión, instalando tus migraciones en `initialize()`:
|
||||
|
||||
```rust,ignore
|
||||
use pagetop::prelude::*;
|
||||
use pagetop_seaorm::install_migrations;
|
||||
|
||||
mod migration;
|
||||
|
||||
struct MyApp;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for MyApp {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_seaorm::SeaORM]
|
||||
}
|
||||
|
||||
async fn initialize(&self) -> Result<(), BoxError> {
|
||||
install_migrations!(m20240101_000001_create_users)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Si la base de datos no responde o una migración falla, la aplicación no arranca y lo explica. Más
|
||||
en [Conectar una base de datos](../how-to/database.md).
|
||||
|
||||
## Usuarios y permisos
|
||||
|
||||
`pagetop-user` aporta inicio de sesión, perfiles, sesiones guardadas en la base de datos,
|
||||
contraseñas con Argon2 y control de acceso por roles (RBAC), con su interfaz de administración. Se
|
||||
apoya en `pagetop-seaorm`.
|
||||
|
||||
El núcleo de PageTop define cómo se **expresa** un permiso; la extensión decide quién lo tiene:
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum BlogPermission {
|
||||
Publish,
|
||||
}
|
||||
|
||||
impl Permission for BlogPermission {
|
||||
fn key(&self) -> CowStr {
|
||||
match self {
|
||||
Self::Publish => "blog:publish".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn new_post(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
// Responds with 403 if the user lacks the permission.
|
||||
require_permission(&request, &BlogPermission::Publish)?;
|
||||
Page::new(request).with_title(Lc::n("New post")).render().await
|
||||
}
|
||||
```
|
||||
|
||||
Dentro de cualquier componente, `cx.current_user()` indica quién hace la petición:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Html {
|
||||
Html::with(|cx| {
|
||||
let user = cx.current_user();
|
||||
html! {
|
||||
@if user.is_authenticated() {
|
||||
p { "Welcome back." }
|
||||
} @else {
|
||||
a href=(cx.route("/user/login")) { "Sign in" }
|
||||
}
|
||||
}
|
||||
})
|
||||
# }
|
||||
```
|
||||
|
||||
Con `pagetop-user` activo, la extensión registra sus permisos con la acción `DeclarePermissions`
|
||||
para que aparezcan en la pantalla de roles y se puedan asignar. Paso a paso en [Añadir usuarios y
|
||||
permisos](../how-to/users.md).
|
||||
|
||||
## Administración
|
||||
|
||||
`pagetop-admin` monta el panel en `/admin`, con un menú de secciones construido con los
|
||||
componentes del núcleo (funciona con cualquier tema). Las extensiones registran en él sus páginas
|
||||
de administración; `pagetop-user` añade, por ejemplo, la gestión de usuarios y roles. Paso a paso
|
||||
en [Añadir páginas al panel de administración](../how-to/admin.md).
|
||||
|
||||
| Pieza | Qué hace |
|
||||
|---|---|
|
||||
| `DeclareAdminSections` | Acción para añadir secciones al panel |
|
||||
| `DeclareAdminPages` | Acción para añadir páginas a una sección, cada una con su permiso |
|
||||
| `DeclareAdminTasks`, `DeclareAdminActions` | Acciones para añadir pestañas y botones a una página |
|
||||
| `AdminPageKind::ConfigForm` | Página de ajustes que el panel pinta y guarda por sí solo |
|
||||
| `AdminFrame` | Marco de una página propia: migas, título, pestañas y botones |
|
||||
| `settings::get_or()` | Lee un ajuste guardado (`<ámbito>.<campo>`) |
|
||||
|
||||
## Documentación con mdBook
|
||||
|
||||
[`pagetop-mdbook`](https://git.cillero.es/manuelcillero/pagetop-mdbook) compila libros de
|
||||
[mdBook](https://rust-lang.github.io/mdBook/) al construir la aplicación y los sirve como páginas
|
||||
PageTop, dentro del tema activo. Esta misma guía se publica así.
|
||||
130
doc/v0.6/es/src/reference/htmx.md
Normal file
130
doc/v0.6/es/src/reference/htmx.md
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
# HTMX: atributos, cabeceras y respuestas
|
||||
|
||||
Lo que ofrece `pagetop-htmx`, en tablas. Para aprender a usarlo, empieza por [Añadir HTMX a una
|
||||
aplicación](../how-to/htmx-setup.md); la documentación completa de cada atributo está en
|
||||
[htmx.org](https://htmx.org/reference/).
|
||||
|
||||
```rust,no_run
|
||||
use pagetop_htmx::prelude::*; // hx, hx_table, hx_pager, HtmxRequestExt, HtmxResponse
|
||||
```
|
||||
|
||||
## Atributos
|
||||
|
||||
Cada atributo tiene su constante en `hx`, para usarla con `PropsOp::set()` en cualquier
|
||||
componente. En `html!` se escriben tal cual.
|
||||
|
||||
| Constante | Atributo | Para qué |
|
||||
|---|---|---|
|
||||
| `hx::GET`, `POST`, `PUT`, `PATCH`, `DELETE` | `hx-get`... | Método y URL de la petición |
|
||||
| `hx::TRIGGER` | `hx-trigger` | Evento que la lanza |
|
||||
| `hx::TARGET` | `hx-target` | Dónde va la respuesta: selector CSS, `this`, `closest tr`, `next`, `previous`, `find .x` |
|
||||
| `hx::SWAP` | `hx-swap` | Cómo se coloca la respuesta |
|
||||
| `hx::SWAP_OOB` | `hx-swap-oob` | En la respuesta: este fragmento va a su propio `id`, fuera de banda |
|
||||
| `hx::SELECT`, `SELECT_OOB` | `hx-select`... | Usa sólo una parte de la respuesta |
|
||||
| `hx::BOOST` | `hx-boost` | Convierte los enlaces y formularios contenidos en peticiones HTMX |
|
||||
| `hx::PUSH_URL`, `REPLACE_URL` | `hx-push-url`... | Añade o cambia la entrada del historial |
|
||||
| `hx::CONFIRM` | `hx-confirm` | Pide confirmación antes de enviar |
|
||||
| `hx::PROMPT` | `hx-prompt` | Pide un texto antes de enviar (llega en la cabecera `HX-Prompt`) |
|
||||
| `hx::INDICATOR` | `hx-indicator` | Elemento que se muestra durante la petición |
|
||||
| `hx::DISABLED_ELT` | `hx-disabled-elt` | Elementos que se desactivan durante la petición |
|
||||
| `hx::INCLUDE`, `PARAMS`, `VALS` | `hx-include`... | Qué valores se envían |
|
||||
| `hx::HEADERS`, `ENCODING` | `hx-headers`... | Cabeceras extra; `multipart/form-data` para archivos |
|
||||
| `hx::SYNC` | `hx-sync` | Coordina peticiones simultáneas (`this:replace`, `#form:abort`...) |
|
||||
| `hx::VALIDATE` | `hx-validate` | Valida el formulario con las reglas del navegador antes de enviar |
|
||||
| `hx::PRESERVE` | `hx-preserve` | Mantiene el elemento intacto al sustituir lo que lo rodea |
|
||||
| `hx::DISINHERIT`, `INHERIT` | `hx-disinherit`... | Controla qué atributos heredan los descendientes |
|
||||
| `hx::on("click")` | `hx-on:click` | JavaScript en línea ante un evento del DOM |
|
||||
| `hx::on_htmx("after-request")` | `hx-on::after-request` | JavaScript en línea ante un evento de HTMX |
|
||||
|
||||
### `hx-swap`
|
||||
|
||||
| Constante | Valor | Coloca la respuesta... |
|
||||
|---|---|---|
|
||||
| `hx::swap::INNER_HTML` | `innerHTML` | Dentro del destino, sustituyendo su contenido (por defecto) |
|
||||
| `hx::swap::OUTER_HTML` | `outerHTML` | En lugar del destino |
|
||||
| `hx::swap::OUTER_HTML_SCROLL_TOP` | `outerHTML scroll:top` | En lugar del destino, y vuelve arriba |
|
||||
| `hx::swap::BEFORE_BEGIN` | `beforebegin` | Justo antes del destino |
|
||||
| `hx::swap::AFTER_BEGIN` | `afterbegin` | Al principio de su contenido |
|
||||
| `hx::swap::BEFORE_END` | `beforeend` | Al final de su contenido |
|
||||
| `hx::swap::AFTER_END` | `afterend` | Justo después del destino |
|
||||
| `hx::swap::DELETE` | `delete` | Borra el destino, sea cual sea la respuesta |
|
||||
| `hx::swap::NONE` | `none` | En ningún sitio (sólo cuentan las cabeceras y los fragmentos fuera de banda) |
|
||||
|
||||
Admite modificadores tras el valor: `swap:300ms` retrasa la sustitución, `settle:...` el asentado,
|
||||
`scroll:top` y `show:top` mueven la vista.
|
||||
|
||||
### `hx-trigger`
|
||||
|
||||
| Constante | Evento |
|
||||
|---|---|
|
||||
| `hx::trigger::CLICK` | `click` (por defecto en botones y enlaces) |
|
||||
| `hx::trigger::CHANGE` | `change` (por defecto en campos) |
|
||||
| `hx::trigger::SUBMIT` | `submit` (por defecto en formularios) |
|
||||
| `hx::trigger::KEYUP` | `keyup` |
|
||||
| `hx::trigger::LOAD` | `load`: nada más cargarse el elemento |
|
||||
| `hx::trigger::REVEALED` | `revealed`: al entrar en la pantalla |
|
||||
| `hx::trigger::INTERSECT` | `intersect`: al cruzar el área visible, en cualquier contenedor |
|
||||
|
||||
Modificadores y formas habituales: `delay:300ms` (espera a que paren los eventos), `throttle:1s`
|
||||
(como mucho uno por intervalo), `changed` (sólo si cambió el valor), `once`, `from:body` (escucha
|
||||
eventos de otro elemento), `every 2s` (sondeo) y varios eventos separados por comas
|
||||
(`input delay:300ms, submit`).
|
||||
|
||||
## Cabeceras de la petición
|
||||
|
||||
Lo que HTMX envía, y cómo leerlo con `HtmxRequestExt` sobre `HttpRequest`:
|
||||
|
||||
| Método | Cabecera | Devuelve |
|
||||
|---|---|---|
|
||||
| `is_htmx()` | `HX-Request` | Si la petición viene de HTMX |
|
||||
| `is_boosted()` | `HX-Boosted` | Si viene de un enlace o formulario con `hx-boost` |
|
||||
| `is_history_restore()` | `HX-History-Restore-Request` | Si HTMX está reconstruyendo el historial |
|
||||
| `hx_current_url()` | `HX-Current-URL` | La URL que se ve en el navegador |
|
||||
| `hx_target()` | `HX-Target` | El `id` del destino |
|
||||
| `hx_trigger_id()` | `HX-Trigger` | El `id` del elemento que lanzó la petición |
|
||||
| `hx_trigger_name()` | `HX-Trigger-Name` | Su `name` |
|
||||
| `hx_prompt()` | `HX-Prompt` | Lo que el usuario escribió en un `hx-prompt` |
|
||||
|
||||
Los nombres, como constantes, están en `hx::request`.
|
||||
|
||||
## Respuestas
|
||||
|
||||
`HtmxResponse` devuelve un fragmento de HTML (`Content-Type: text/html`) con las cabeceras que se
|
||||
le añadan. Implementa `IntoResponse`.
|
||||
|
||||
| Método | Cabecera | Efecto |
|
||||
|---|---|---|
|
||||
| `HtmxResponse::new(markup)` | - | Respuesta con un fragmento |
|
||||
| `HtmxResponse::empty()` | - | Respuesta sin cuerpo, sólo cabeceras |
|
||||
| `oob(markup)` | - | Añade un fragmento fuera de banda (lleva su `id` y `hx-swap-oob`) |
|
||||
| `retarget(selector)` | `HX-Retarget` | Cambia el destino |
|
||||
| `reswap(estrategia)` | `HX-Reswap` | Cambia la forma de colocarla |
|
||||
| `reselect(selector)` | `HX-Reselect` | Usa sólo una parte de la respuesta |
|
||||
| `trigger(eventos)` | `HX-Trigger` | Dispara eventos en el cliente |
|
||||
| `trigger_after_swap(eventos)` | `HX-Trigger-After-Swap` | ...tras colocar la respuesta |
|
||||
| `trigger_after_settle(eventos)` | `HX-Trigger-After-Settle` | ...tras asentarla |
|
||||
| `push_url(url)`, `replace_url(url)` | `HX-Push-Url`... | Cambia la URL del navegador |
|
||||
| `redirect(url)` | `HX-Redirect` | Navegación completa |
|
||||
| `location(url)`, `location_json(json)` | `HX-Location` | Navegación con HTMX, sin recargar la página |
|
||||
| `refresh()` | `HX-Refresh` | Recarga la página |
|
||||
|
||||
Un `Markup` también es una respuesta válida para HTMX cuando no hacen falta cabeceras.
|
||||
|
||||
## Ayudas para tablas y paginadores
|
||||
|
||||
| Ayuda | Para qué |
|
||||
|---|---|
|
||||
| `hx_table::sort_link(href, destino, dirección)` | Cabecera ordenable que sustituye el destino, vuelve arriba y actualiza la URL |
|
||||
| `hx_pager` | Documenta el patrón para `Pager`: `hx::BOOST`, `TARGET`, `SWAP` y `PUSH_URL` en su `with_prop()` |
|
||||
|
||||
Ver [Ordenar y paginar sin recargar](../how-to/htmx-tables.md).
|
||||
|
||||
## Comportamientos de HTMX que conviene recordar
|
||||
|
||||
| Comportamiento | Consecuencia |
|
||||
|---|---|
|
||||
| Las respuestas 4xx y 5xx **no se colocan** | Responde con 200 a los errores de validación que el usuario deba ver |
|
||||
| Los atributos `hx-*` **se heredan** | Un `hx-swap` en un formulario afecta a los campos que hacen sus propias peticiones |
|
||||
| Una petición que no es `GET` envía el formulario que la contiene | Un campo dentro de un formulario envía también los demás campos |
|
||||
| El código **286** detiene el sondeo | Alternativa a sustituir el elemento que sondea |
|
||||
| Una redirección `3xx` la sigue HTMX por su cuenta | Para cambiar de página, usa `HtmxResponse::redirect()` |
|
||||
986
doc/v0.6/es/src/tutorials/database.md
Normal file
986
doc/v0.6/es/src/tutorials/database.md
Normal file
|
|
@ -0,0 +1,986 @@
|
|||
# Guarda las tareas en una base de datos
|
||||
|
||||
Las tareas del [tutorial anterior](htmx-tasks.md) viven en memoria: al reiniciar el servidor, se
|
||||
pierden. En éste las guardas en [SQLite](https://sqlite.org) con la extensión `pagetop-seaorm`, que
|
||||
integra [SeaORM](https://www.sea-ql.org/SeaORM) en PageTop. Lo interesante es lo que **no**
|
||||
cambia: las rutas, los fragmentos y los atributos `hx-*` siguen igual.
|
||||
|
||||
- **Tiempo:** unos 20 minutos.
|
||||
- **Necesitas:** el proyecto `garden-tasks` del tutorial anterior.
|
||||
- **Al terminar tendrás:** tareas persistentes, una migración que crea la tabla al arrancar y una
|
||||
prueba contra una base de datos en memoria.
|
||||
|
||||
## 1. Añade SeaORM
|
||||
|
||||
En `Cargo.toml`, añade la extensión con el motor que vas a usar:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
pagetop = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
||||
pagetop-htmx = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
||||
pagetop-seaorm = { git = "https://git.cillero.es/manuelcillero/pagetop", features = ["sqlite"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
```
|
||||
|
||||
Los motores disponibles son `sqlite`, `postgres` y `mysql`. El código que vas a escribir es el mismo
|
||||
para los tres; sólo cambian la *feature* y la configuración.
|
||||
|
||||
Crea `config/common.toml`, junto a `Cargo.toml`, con la conexión:
|
||||
|
||||
```toml
|
||||
[database]
|
||||
db_type = "sqlite"
|
||||
db_name = "garden.db?mode=rwc"
|
||||
```
|
||||
|
||||
`mode=rwc` le pide a SQLite que cree el archivo `garden.db` si no existe.
|
||||
|
||||
## 2. La migración
|
||||
|
||||
Una **migración** describe un cambio en el esquema de la base de datos. PageTop las aplica al
|
||||
arrancar, en orden, y anota en la tabla `seaql_migrations` las que ya aplicó para no repetirlas.
|
||||
|
||||
Cada migración es un módulo dentro de `migration`, con un nombre que empieza por la fecha. En un
|
||||
proyecto grande irían en `src/migration/`; aquí caben en `src/main.rs`:
|
||||
|
||||
```rust,no_run
|
||||
mod migration {
|
||||
pub mod m20261015_000001_create_tasks {
|
||||
use pagetop_seaorm::migration::*;
|
||||
|
||||
pub struct Migration;
|
||||
|
||||
#[pagetop::async_trait]
|
||||
impl MigrationTrait for Migration {
|
||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
table_auto(Tasks::Table)
|
||||
.col(pk_auto(Tasks::Id))
|
||||
.col(string(Tasks::Title))
|
||||
.col(boolean(Tasks::Done).default(false))
|
||||
.to_owned(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
enum Tasks {
|
||||
Table,
|
||||
Id,
|
||||
Title,
|
||||
Done,
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`table_auto()` crea la tabla `tasks` (si no existe) con dos columnas de regalo, `created_at` y
|
||||
`updated_at`. `pk_auto()` es una clave primaria autoincremental; `string()` y `boolean()`,
|
||||
columnas obligatorias.
|
||||
|
||||
## 3. La entidad
|
||||
|
||||
La **entidad** es el tipo Rust que representa una fila. Sustituye al `struct Task` del tutorial
|
||||
anterior:
|
||||
|
||||
```rust,no_run
|
||||
mod task {
|
||||
use pagetop_seaorm::db::*;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
||||
#[sea_orm(table_name = "tasks")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key)]
|
||||
pub id: i32,
|
||||
pub title: String,
|
||||
pub done: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
||||
pub enum Relation {}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
}
|
||||
```
|
||||
|
||||
El *struct* debe llamarse `Model`. A partir de él, `DeriveEntityModel` genera el resto: `Entity`
|
||||
para consultar, `Column` para filtrar y ordenar, y `ActiveModel` para insertar y modificar.
|
||||
|
||||
Borra el `struct Task`, el `struct Store`, `STORE` y `store()`: ya no los necesitas. En
|
||||
`task_url()`, `task_item()` y `edit_item()`, cambia `&Task` por `&task::Model`; los campos se llaman
|
||||
igual.
|
||||
|
||||
## 4. Conecta y migra al arrancar
|
||||
|
||||
Declara `pagetop_seaorm::SeaORM` como dependencia: abrirá la conexión con los ajustes de
|
||||
`[database]` antes de que se inicialice tu extensión. Después, en `initialize()`, aplica la
|
||||
migración y siembra las dos tareas de ejemplo si la tabla está vacía:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# use pagetop_seaorm::db::*;
|
||||
use pagetop_seaorm::install_migrations;
|
||||
# mod migration {
|
||||
# pub mod m20261015_000001_create_tasks {
|
||||
# use pagetop_seaorm::migration::*;
|
||||
# pub struct Migration;
|
||||
# #[pagetop::async_trait]
|
||||
# impl MigrationTrait for Migration {
|
||||
# async fn up(&self, _: &SchemaManager) -> Result<(), DbErr> { Ok(()) }
|
||||
# }
|
||||
# }
|
||||
# }
|
||||
# mod task {
|
||||
# use pagetop_seaorm::db::*;
|
||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
||||
# #[sea_orm(table_name = "tasks")]
|
||||
# pub struct Model {
|
||||
# #[sea_orm(primary_key)]
|
||||
# pub id: i32,
|
||||
# pub title: String,
|
||||
# pub done: bool,
|
||||
# }
|
||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
||||
# pub enum Relation {}
|
||||
# impl ActiveModelBehavior for ActiveModel {}
|
||||
# }
|
||||
# async fn add_task(_: &str) -> Result<task::Model, DbErr> { todo!() }
|
||||
# struct GardenTasks;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for GardenTasks {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_htmx::Htmx, &pagetop_seaorm::SeaORM]
|
||||
}
|
||||
|
||||
async fn initialize(&self) -> Result<(), BoxError> {
|
||||
install_migrations!(m20261015_000001_create_tasks)?;
|
||||
if task::Entity::find().count(dbconn()).await? == 0 {
|
||||
add_task("Water the tomatoes").await?;
|
||||
add_task("Turn the compost").await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ... configure_router() as before ...
|
||||
}
|
||||
```
|
||||
|
||||
Si la base de datos no responde o la migración falla, `?` devuelve el error y la aplicación **no
|
||||
arranca**: lo explica en el terminal y termina. Nunca funciona a medias con un esquema incompleto.
|
||||
|
||||
## 5. Las consultas
|
||||
|
||||
Las operaciones del almacén pasan a ser funciones `async` que hablan con la base de datos.
|
||||
`dbconn()` devuelve el *pool* de conexiones que abrió la extensión:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# use pagetop_seaorm::db::*;
|
||||
# mod task {
|
||||
# use pagetop_seaorm::db::*;
|
||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
||||
# #[sea_orm(table_name = "tasks")]
|
||||
# pub struct Model {
|
||||
# #[sea_orm(primary_key)]
|
||||
# pub id: i32,
|
||||
# pub title: String,
|
||||
# pub done: bool,
|
||||
# }
|
||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
||||
# pub enum Relation {}
|
||||
# impl ActiveModelBehavior for ActiveModel {}
|
||||
# }
|
||||
async fn all_tasks() -> Result<Vec<task::Model>, DbErr> {
|
||||
task::Entity::find()
|
||||
.order_by_asc(task::Column::Id)
|
||||
.all(dbconn())
|
||||
.await
|
||||
}
|
||||
|
||||
async fn find_task(id: i32) -> Result<Option<task::Model>, DbErr> {
|
||||
task::Entity::find_by_id(id).one(dbconn()).await
|
||||
}
|
||||
|
||||
async fn add_task(title: &str) -> Result<task::Model, DbErr> {
|
||||
task::ActiveModel {
|
||||
title: Set(title.to_string()),
|
||||
..Default::default()
|
||||
}
|
||||
.insert(dbconn())
|
||||
.await
|
||||
}
|
||||
|
||||
async fn pending() -> Result<u64, DbErr> {
|
||||
task::Entity::find()
|
||||
.filter(task::Column::Done.eq(false))
|
||||
.count(dbconn())
|
||||
.await
|
||||
}
|
||||
```
|
||||
|
||||
`pending_update()` recibe ahora un `u64`, que es lo que devuelve `count()`.
|
||||
|
||||
## 6. Los *handlers*
|
||||
|
||||
Una consulta puede fallar, así que los *handlers* devuelven un `Result`. Para no repetir el
|
||||
tratamiento del error en cada uno, define un tipo que lo convierta en respuesta: un error 500 y una
|
||||
traza con la causa. Gracias a `From<DbErr>`, el operador `?` hace el resto:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# use pagetop_seaorm::db::*;
|
||||
// Ends the request with a 500 error, and leaves a trace with the cause.
|
||||
struct DbFailure(DbErr);
|
||||
|
||||
impl From<DbErr> for DbFailure {
|
||||
fn from(error: DbErr) -> Self {
|
||||
Self(error)
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoResponse for DbFailure {
|
||||
fn into_response(self) -> Response {
|
||||
trace::error!("Database error: {}", self.0);
|
||||
web::http::StatusCode::INTERNAL_SERVER_ERROR.into_response()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Con eso, cada *handler* cambia muy poco. Por ejemplo, `toggle` lee la tarea, la convierte en un
|
||||
`ActiveModel`, cambia el campo y la guarda:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# use pagetop_htmx::prelude::*;
|
||||
# use pagetop_seaorm::db::*;
|
||||
# mod task {
|
||||
# use pagetop_seaorm::db::*;
|
||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
||||
# #[sea_orm(table_name = "tasks")]
|
||||
# pub struct Model {
|
||||
# #[sea_orm(primary_key)]
|
||||
# pub id: i32,
|
||||
# pub title: String,
|
||||
# pub done: bool,
|
||||
# }
|
||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
||||
# pub enum Relation {}
|
||||
# impl ActiveModelBehavior for ActiveModel {}
|
||||
# }
|
||||
# struct DbFailure(DbErr);
|
||||
# impl From<DbErr> for DbFailure { fn from(error: DbErr) -> Self { Self(error) } }
|
||||
# impl IntoResponse for DbFailure { fn into_response(self) -> Response { todo!() } }
|
||||
# async fn find_task(_: i32) -> Result<Option<task::Model>, DbErr> { todo!() }
|
||||
# async fn pending() -> Result<u64, DbErr> { todo!() }
|
||||
# fn task_item(_: &task::Model) -> Markup { html! {} }
|
||||
# fn pending_update(_: u64) -> Markup { html! {} }
|
||||
# fn not_found() -> Response { todo!() }
|
||||
async fn toggle(web::Path(id): web::Path<i32>) -> Result<Response, DbFailure> {
|
||||
let Some(task) = find_task(id).await? else {
|
||||
return Ok(not_found());
|
||||
};
|
||||
let done = !task.done;
|
||||
let mut task = task.into_active_model();
|
||||
task.done = Set(done);
|
||||
let task = task.update(dbconn()).await?;
|
||||
Ok(HtmxResponse::new(task_item(&task))
|
||||
.oob(pending_update(pending().await?))
|
||||
.into_response())
|
||||
}
|
||||
```
|
||||
|
||||
Fíjate en la última parte: **la respuesta es idéntica** a la del tutorial anterior. El navegador
|
||||
no nota ningún cambio.
|
||||
|
||||
Borrar es una sola llamada:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# use pagetop_htmx::prelude::*;
|
||||
# use pagetop_seaorm::db::*;
|
||||
# mod task {
|
||||
# use pagetop_seaorm::db::*;
|
||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
||||
# #[sea_orm(table_name = "tasks")]
|
||||
# pub struct Model {
|
||||
# #[sea_orm(primary_key)]
|
||||
# pub id: i32,
|
||||
# pub title: String,
|
||||
# pub done: bool,
|
||||
# }
|
||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
||||
# pub enum Relation {}
|
||||
# impl ActiveModelBehavior for ActiveModel {}
|
||||
# }
|
||||
# struct DbFailure(DbErr);
|
||||
# impl From<DbErr> for DbFailure { fn from(error: DbErr) -> Self { Self(error) } }
|
||||
# impl IntoResponse for DbFailure { fn into_response(self) -> Response { todo!() } }
|
||||
# async fn pending() -> Result<u64, DbErr> { todo!() }
|
||||
# fn pending_update(_: u64) -> Markup { html! {} }
|
||||
async fn remove(web::Path(id): web::Path<i32>) -> Result<Response, DbFailure> {
|
||||
task::Entity::delete_by_id(id).exec(dbconn()).await?;
|
||||
Ok(HtmxResponse::empty()
|
||||
.oob(pending_update(pending().await?))
|
||||
.into_response())
|
||||
}
|
||||
```
|
||||
|
||||
La página principal devuelve una página de error si la consulta falla, para no dejar al usuario
|
||||
ante una pantalla en blanco:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# use pagetop_seaorm::db::*;
|
||||
# mod task {
|
||||
# use pagetop_seaorm::db::*;
|
||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
||||
# #[sea_orm(table_name = "tasks")]
|
||||
# pub struct Model {
|
||||
# #[sea_orm(primary_key)]
|
||||
# pub id: i32,
|
||||
# pub title: String,
|
||||
# pub done: bool,
|
||||
# }
|
||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
||||
# pub enum Relation {}
|
||||
# impl ActiveModelBehavior for ActiveModel {}
|
||||
# }
|
||||
# async fn all_tasks() -> Result<Vec<task::Model>, DbErr> { todo!() }
|
||||
# async fn pending() -> Result<u64, DbErr> { todo!() }
|
||||
# fn add_form() -> Form { Form::new() }
|
||||
# fn task_item(_: &task::Model) -> Markup { html! {} }
|
||||
async fn load_list() -> Result<(Vec<task::Model>, u64), DbErr> {
|
||||
Ok((all_tasks().await?, pending().await?))
|
||||
}
|
||||
|
||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
let Ok((tasks, pending)) = load_list().await else {
|
||||
return Err(ErrorPage::InternalError(Some(request)));
|
||||
};
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("Garden tasks"))
|
||||
.with_child(Html::with(move |_| html! {
|
||||
h1 { "Garden tasks" }
|
||||
p { "Pending: " strong id="pending" { (pending) } }
|
||||
}))
|
||||
.with_child(add_form())
|
||||
.with_child(Html::with(move |_| html! {
|
||||
ul id="tasks" {
|
||||
@for task in &tasks {
|
||||
(task_item(task))
|
||||
}
|
||||
}
|
||||
}))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
```
|
||||
|
||||
Los demás *handlers* siguen el mismo patrón; los tienes todos en [el código
|
||||
completo](#el-código-completo). Los identificadores de las rutas pasan de `u32` a `i32`, el tipo de
|
||||
la clave primaria.
|
||||
|
||||
## 7. Pruébalo
|
||||
|
||||
```sh
|
||||
cargo run
|
||||
```
|
||||
|
||||
Al arrancar verás en el terminal la conexión y, una a una, las sentencias SQL de la migración.
|
||||
Si te sobran, baja el nivel de las trazas de `sqlx` en `config/common.toml`:
|
||||
|
||||
```toml
|
||||
[log]
|
||||
tracing = "Info,sqlx=Warn"
|
||||
```
|
||||
|
||||
Añade un par de tareas, marca alguna como hecha y **reinicia el servidor**: siguen ahí. El archivo `garden.db` ha aparecido junto a
|
||||
`Cargo.toml`; puedes abrirlo con cualquier cliente de SQLite.
|
||||
|
||||
Reinicia otra vez: la migración ya no se aplica, porque `seaql_migrations` la tiene anotada.
|
||||
|
||||
## 8. Pruebas con una base de datos en memoria
|
||||
|
||||
Las pruebas no deberían tocar `garden.db`. Crea `config/test.toml` para el modo de ejecución
|
||||
`test`, con una base de datos SQLite **en memoria**, nueva en cada ejecución:
|
||||
|
||||
```toml
|
||||
[database]
|
||||
db_name = "garden?mode=memory"
|
||||
max_pool_size = 1
|
||||
```
|
||||
|
||||
`db_type` llega de `common.toml`. Una base de datos en memoria vive dentro de su conexión: con
|
||||
`max_pool_size = 1` todas las consultas usan la misma y ven las mismas tablas.
|
||||
|
||||
La prueba es la del tutorial anterior. La tabla parte vacía y `initialize()` siembra dos tareas,
|
||||
así que la nueva es la tercera.
|
||||
|
||||
```rust
|
||||
# use pagetop::prelude::*;
|
||||
# use pagetop_htmx::prelude::*;
|
||||
# use pagetop_seaorm::db::*;
|
||||
# use pagetop_seaorm::install_migrations;
|
||||
# use serde::Deserialize;
|
||||
# mod migration {
|
||||
# pub mod m20261015_000001_create_tasks {
|
||||
# use pagetop_seaorm::migration::*;
|
||||
# pub struct Migration;
|
||||
# #[pagetop::async_trait]
|
||||
# impl MigrationTrait for Migration {
|
||||
# async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
# manager
|
||||
# .create_table(
|
||||
# table_auto(Tasks::Table)
|
||||
# .col(pk_auto(Tasks::Id))
|
||||
# .col(string(Tasks::Title))
|
||||
# .col(boolean(Tasks::Done).default(false))
|
||||
# .to_owned(),
|
||||
# )
|
||||
# .await
|
||||
# }
|
||||
# }
|
||||
# #[derive(DeriveIden)]
|
||||
# enum Tasks { Table, Id, Title, Done }
|
||||
# }
|
||||
# }
|
||||
# mod task {
|
||||
# use pagetop_seaorm::db::*;
|
||||
# #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
||||
# #[sea_orm(table_name = "tasks")]
|
||||
# pub struct Model {
|
||||
# #[sea_orm(primary_key)]
|
||||
# pub id: i32,
|
||||
# pub title: String,
|
||||
# pub done: bool,
|
||||
# }
|
||||
# #[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
||||
# pub enum Relation {}
|
||||
# impl ActiveModelBehavior for ActiveModel {}
|
||||
# }
|
||||
# struct GardenTasks;
|
||||
# #[async_trait]
|
||||
# impl Extension for GardenTasks {
|
||||
# fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
# vec![&pagetop_htmx::Htmx, &pagetop_seaorm::SeaORM]
|
||||
# }
|
||||
# async fn initialize(&self) -> Result<(), BoxError> {
|
||||
# install_migrations!(m20261015_000001_create_tasks)?;
|
||||
# if task::Entity::find().count(dbconn()).await? == 0 {
|
||||
# add_task("Water the tomatoes").await?;
|
||||
# add_task("Turn the compost").await?;
|
||||
# }
|
||||
# Ok(())
|
||||
# }
|
||||
# fn configure_router(&self, router: Router) -> Router {
|
||||
# router
|
||||
# .route("/", web::get(home))
|
||||
# .route("/tasks", web::post(create))
|
||||
# .route("/tasks/{id}", web::get(show).put(update).delete(remove))
|
||||
# .route("/tasks/{id}/edit", web::get(edit))
|
||||
# .route("/tasks/{id}/toggle", web::patch(toggle))
|
||||
# }
|
||||
# }
|
||||
# async fn all_tasks() -> Result<Vec<task::Model>, DbErr> {
|
||||
# task::Entity::find().order_by_asc(task::Column::Id).all(dbconn()).await
|
||||
# }
|
||||
# async fn find_task(id: i32) -> Result<Option<task::Model>, DbErr> {
|
||||
# task::Entity::find_by_id(id).one(dbconn()).await
|
||||
# }
|
||||
# async fn add_task(title: &str) -> Result<task::Model, DbErr> {
|
||||
# task::ActiveModel { title: Set(title.to_string()), ..Default::default() }
|
||||
# .insert(dbconn())
|
||||
# .await
|
||||
# }
|
||||
# async fn pending() -> Result<u64, DbErr> {
|
||||
# task::Entity::find().filter(task::Column::Done.eq(false)).count(dbconn()).await
|
||||
# }
|
||||
# fn add_form() -> Form {
|
||||
# Form::new()
|
||||
# .with_action("/tasks")
|
||||
# .with_method(form::Method::Post)
|
||||
# .with_prop(PropsOp::set(hx::POST, "/tasks"))
|
||||
# .with_prop(PropsOp::set(hx::TARGET, "#tasks"))
|
||||
# .with_prop(PropsOp::set(hx::SWAP, hx::swap::BEFORE_END))
|
||||
# .with_prop(PropsOp::set(hx::on_htmx("after-request"), "this.reset()"))
|
||||
# .with_child(
|
||||
# form::input::Field::text()
|
||||
# .with_name("title")
|
||||
# .with_label(Lc::n("New task"))
|
||||
# .with_required(true),
|
||||
# )
|
||||
# .with_child(Button::submit(Lc::n("Add")))
|
||||
# }
|
||||
# fn task_url(task: &task::Model) -> String {
|
||||
# util::join!("/tasks/", task.id.to_string())
|
||||
# }
|
||||
# fn task_item(task: &task::Model) -> Markup {
|
||||
# let url = task_url(task);
|
||||
# html! {
|
||||
# li hx-target="this" hx-swap="outerHTML" {
|
||||
# input type="checkbox" checked[task.done] hx-patch=(util::join!(url, "/toggle"));
|
||||
# " "
|
||||
# @if task.done { s { (task.title) } } @else { (task.title) }
|
||||
# " "
|
||||
# button type="button" hx-get=(util::join!(url, "/edit")) { "Edit" }
|
||||
# button type="button" hx-delete=(url) hx-confirm="Delete this task?" { "Delete" }
|
||||
# }
|
||||
# }
|
||||
# }
|
||||
# fn edit_item(task: &task::Model) -> Markup {
|
||||
# let url = task_url(task);
|
||||
# html! {
|
||||
# li hx-target="this" hx-swap="outerHTML" {
|
||||
# form hx-put=(url) {
|
||||
# input type="text" name="title" value=(task.title) required autofocus;
|
||||
# button type="submit" { "Save" }
|
||||
# button type="button" hx-get=(url) { "Cancel" }
|
||||
# }
|
||||
# }
|
||||
# }
|
||||
# }
|
||||
# fn pending_update(pending: u64) -> Markup {
|
||||
# html! { strong id="pending" hx-swap-oob="true" { (pending) } }
|
||||
# }
|
||||
# struct DbFailure(DbErr);
|
||||
# impl From<DbErr> for DbFailure { fn from(error: DbErr) -> Self { Self(error) } }
|
||||
# impl IntoResponse for DbFailure {
|
||||
# fn into_response(self) -> Response {
|
||||
# trace::error!("Database error: {}", self.0);
|
||||
# web::http::StatusCode::INTERNAL_SERVER_ERROR.into_response()
|
||||
# }
|
||||
# }
|
||||
# fn not_found() -> Response {
|
||||
# web::http::StatusCode::NOT_FOUND.into_response()
|
||||
# }
|
||||
# async fn load_list() -> Result<(Vec<task::Model>, u64), DbErr> {
|
||||
# Ok((all_tasks().await?, pending().await?))
|
||||
# }
|
||||
# async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
# let Ok((tasks, pending)) = load_list().await else {
|
||||
# return Err(ErrorPage::InternalError(Some(request)));
|
||||
# };
|
||||
# Page::new(request)
|
||||
# .with_child(Html::with(move |_| html! {
|
||||
# p { "Pending: " strong id="pending" { (pending) } }
|
||||
# }))
|
||||
# .with_child(add_form())
|
||||
# .with_child(Html::with(move |_| html! {
|
||||
# ul id="tasks" { @for task in &tasks { (task_item(task)) } }
|
||||
# }))
|
||||
# .render()
|
||||
# .await
|
||||
# }
|
||||
# #[derive(Deserialize)]
|
||||
# struct TaskForm { title: String }
|
||||
# async fn create(
|
||||
# request: HttpRequest,
|
||||
# web::Form(form): web::Form<TaskForm>,
|
||||
# ) -> Result<Response, DbFailure> {
|
||||
# let title = form.title.trim();
|
||||
# let added = if title.is_empty() { None } else { Some(add_task(title).await?) };
|
||||
# if !request.is_htmx() {
|
||||
# return Ok(Redirect::see_other("/"));
|
||||
# }
|
||||
# Ok(match added {
|
||||
# Some(task) => HtmxResponse::new(task_item(&task))
|
||||
# .oob(pending_update(pending().await?))
|
||||
# .into_response(),
|
||||
# None => HtmxResponse::empty().into_response(),
|
||||
# })
|
||||
# }
|
||||
# async fn toggle(web::Path(id): web::Path<i32>) -> Result<Response, DbFailure> {
|
||||
# let Some(task) = find_task(id).await? else { return Ok(not_found()) };
|
||||
# let done = !task.done;
|
||||
# let mut task = task.into_active_model();
|
||||
# task.done = Set(done);
|
||||
# let task = task.update(dbconn()).await?;
|
||||
# Ok(HtmxResponse::new(task_item(&task)).oob(pending_update(pending().await?)).into_response())
|
||||
# }
|
||||
# async fn remove(web::Path(id): web::Path<i32>) -> Result<Response, DbFailure> {
|
||||
# task::Entity::delete_by_id(id).exec(dbconn()).await?;
|
||||
# Ok(HtmxResponse::empty().oob(pending_update(pending().await?)).into_response())
|
||||
# }
|
||||
# async fn edit(web::Path(id): web::Path<i32>) -> Result<Response, DbFailure> {
|
||||
# Ok(match find_task(id).await? {
|
||||
# Some(task) => HtmxResponse::new(edit_item(&task)).into_response(),
|
||||
# None => not_found(),
|
||||
# })
|
||||
# }
|
||||
# async fn show(web::Path(id): web::Path<i32>) -> Result<Response, DbFailure> {
|
||||
# Ok(match find_task(id).await? {
|
||||
# Some(task) => HtmxResponse::new(task_item(&task)).into_response(),
|
||||
# None => not_found(),
|
||||
# })
|
||||
# }
|
||||
# async fn update(
|
||||
# web::Path(id): web::Path<i32>,
|
||||
# web::Form(form): web::Form<TaskForm>,
|
||||
# ) -> Result<Response, DbFailure> {
|
||||
# let Some(task) = find_task(id).await? else { return Ok(not_found()) };
|
||||
# let title = form.title.trim().to_string();
|
||||
# if title.is_empty() {
|
||||
# return Ok(HtmxResponse::new(task_item(&task)).into_response());
|
||||
# }
|
||||
# let mut task = task.into_active_model();
|
||||
# task.title = Set(title);
|
||||
# let task = task.update(dbconn()).await?;
|
||||
# Ok(HtmxResponse::new(task_item(&task)).into_response())
|
||||
# }
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Sends a request as HTMX does: with the `HX-Request` header.
|
||||
fn htmx(request: web::test::TestRequest) -> web::Request {
|
||||
request.header("hx-request", "true").to_request()
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn tasks_are_stored_in_the_database() {
|
||||
let app = web::test::init_router(Application::prepare(&GardenTasks).await.test());
|
||||
|
||||
let request = htmx(web::test::TestRequest::post().uri("/tasks").form("title=Plant+lettuces"));
|
||||
let body = web::test::read_body_text(web::test::send_request(&app, request).await).await;
|
||||
assert!(body.contains("Plant lettuces"));
|
||||
assert!(body.contains(r#"<strong id="pending" hx-swap-oob="true">3</strong>"#));
|
||||
|
||||
let request = htmx(web::test::TestRequest::patch().uri("/tasks/3/toggle"));
|
||||
let body = web::test::read_body_text(web::test::send_request(&app, request).await).await;
|
||||
assert!(body.contains("<s>Plant lettuces</s>"));
|
||||
|
||||
// The change is in the database, not only in the response.
|
||||
let stored = task::Entity::find_by_id(3).one(dbconn()).await.unwrap().unwrap();
|
||||
assert!(stored.done);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Ejecútala en el modo `test`:
|
||||
|
||||
```sh
|
||||
PAGETOP_RUN_MODE=test cargo test
|
||||
```
|
||||
|
||||
## El código completo
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
use pagetop_htmx::prelude::*;
|
||||
use pagetop_seaorm::db::*;
|
||||
use pagetop_seaorm::install_migrations;
|
||||
use serde::Deserialize;
|
||||
|
||||
// **< Database >***********************************************************************************
|
||||
|
||||
mod migration {
|
||||
pub mod m20261015_000001_create_tasks {
|
||||
use pagetop_seaorm::migration::*;
|
||||
|
||||
pub struct Migration;
|
||||
|
||||
#[pagetop::async_trait]
|
||||
impl MigrationTrait for Migration {
|
||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
table_auto(Tasks::Table)
|
||||
.col(pk_auto(Tasks::Id))
|
||||
.col(string(Tasks::Title))
|
||||
.col(boolean(Tasks::Done).default(false))
|
||||
.to_owned(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
enum Tasks {
|
||||
Table,
|
||||
Id,
|
||||
Title,
|
||||
Done,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mod task {
|
||||
use pagetop_seaorm::db::*;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
|
||||
#[sea_orm(table_name = "tasks")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key)]
|
||||
pub id: i32,
|
||||
pub title: String,
|
||||
pub done: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, DeriveRelation, EnumIter)]
|
||||
pub enum Relation {}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
}
|
||||
|
||||
async fn all_tasks() -> Result<Vec<task::Model>, DbErr> {
|
||||
task::Entity::find()
|
||||
.order_by_asc(task::Column::Id)
|
||||
.all(dbconn())
|
||||
.await
|
||||
}
|
||||
|
||||
async fn find_task(id: i32) -> Result<Option<task::Model>, DbErr> {
|
||||
task::Entity::find_by_id(id).one(dbconn()).await
|
||||
}
|
||||
|
||||
async fn add_task(title: &str) -> Result<task::Model, DbErr> {
|
||||
task::ActiveModel {
|
||||
title: Set(title.to_string()),
|
||||
..Default::default()
|
||||
}
|
||||
.insert(dbconn())
|
||||
.await
|
||||
}
|
||||
|
||||
async fn pending() -> Result<u64, DbErr> {
|
||||
task::Entity::find()
|
||||
.filter(task::Column::Done.eq(false))
|
||||
.count(dbconn())
|
||||
.await
|
||||
}
|
||||
|
||||
// **< The application >****************************************************************************
|
||||
|
||||
struct GardenTasks;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for GardenTasks {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_htmx::Htmx, &pagetop_seaorm::SeaORM]
|
||||
}
|
||||
|
||||
async fn initialize(&self) -> Result<(), BoxError> {
|
||||
install_migrations!(m20261015_000001_create_tasks)?;
|
||||
if task::Entity::find().count(dbconn()).await? == 0 {
|
||||
add_task("Water the tomatoes").await?;
|
||||
add_task("Turn the compost").await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router
|
||||
.route("/", web::get(home))
|
||||
.route("/tasks", web::post(create))
|
||||
.route("/tasks/{id}", web::get(show).put(update).delete(remove))
|
||||
.route("/tasks/{id}/edit", web::get(edit))
|
||||
.route("/tasks/{id}/toggle", web::patch(toggle))
|
||||
}
|
||||
}
|
||||
|
||||
#[pagetop::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
Application::prepare(&GardenTasks).await.run().await
|
||||
}
|
||||
|
||||
// **< Markup >*************************************************************************************
|
||||
|
||||
fn add_form() -> Form {
|
||||
Form::new()
|
||||
.with_action("/tasks")
|
||||
.with_method(form::Method::Post)
|
||||
.with_prop(PropsOp::set(hx::POST, "/tasks"))
|
||||
.with_prop(PropsOp::set(hx::TARGET, "#tasks"))
|
||||
.with_prop(PropsOp::set(hx::SWAP, hx::swap::BEFORE_END))
|
||||
.with_prop(PropsOp::set(hx::on_htmx("after-request"), "this.reset()"))
|
||||
.with_child(
|
||||
form::input::Field::text()
|
||||
.with_name("title")
|
||||
.with_label(Lc::n("New task"))
|
||||
.with_required(true),
|
||||
)
|
||||
.with_child(Button::submit(Lc::n("Add")))
|
||||
}
|
||||
|
||||
fn task_url(task: &task::Model) -> String {
|
||||
util::join!("/tasks/", task.id.to_string())
|
||||
}
|
||||
|
||||
fn task_item(task: &task::Model) -> Markup {
|
||||
let url = task_url(task);
|
||||
html! {
|
||||
li hx-target="this" hx-swap="outerHTML" {
|
||||
input type="checkbox" checked[task.done] hx-patch=(util::join!(url, "/toggle"));
|
||||
" "
|
||||
@if task.done {
|
||||
s { (task.title) }
|
||||
} @else {
|
||||
(task.title)
|
||||
}
|
||||
" "
|
||||
button type="button" hx-get=(util::join!(url, "/edit")) { "Edit" }
|
||||
button type="button" hx-delete=(url) hx-confirm="Delete this task?" { "Delete" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn edit_item(task: &task::Model) -> Markup {
|
||||
let url = task_url(task);
|
||||
html! {
|
||||
li hx-target="this" hx-swap="outerHTML" {
|
||||
form hx-put=(url) {
|
||||
input type="text" name="title" value=(task.title) required autofocus;
|
||||
button type="submit" { "Save" }
|
||||
button type="button" hx-get=(url) { "Cancel" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn pending_update(pending: u64) -> Markup {
|
||||
html! { strong id="pending" hx-swap-oob="true" { (pending) } }
|
||||
}
|
||||
|
||||
// **< Handlers >***********************************************************************************
|
||||
|
||||
// Ends the request with a 500 error, and leaves a trace with the cause.
|
||||
struct DbFailure(DbErr);
|
||||
|
||||
impl From<DbErr> for DbFailure {
|
||||
fn from(error: DbErr) -> Self {
|
||||
Self(error)
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoResponse for DbFailure {
|
||||
fn into_response(self) -> Response {
|
||||
trace::error!("Database error: {}", self.0);
|
||||
web::http::StatusCode::INTERNAL_SERVER_ERROR.into_response()
|
||||
}
|
||||
}
|
||||
|
||||
fn not_found() -> Response {
|
||||
web::http::StatusCode::NOT_FOUND.into_response()
|
||||
}
|
||||
|
||||
async fn load_list() -> Result<(Vec<task::Model>, u64), DbErr> {
|
||||
Ok((all_tasks().await?, pending().await?))
|
||||
}
|
||||
|
||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
let Ok((tasks, pending)) = load_list().await else {
|
||||
return Err(ErrorPage::InternalError(Some(request)));
|
||||
};
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("Garden tasks"))
|
||||
.with_child(Html::with(move |_| html! {
|
||||
h1 { "Garden tasks" }
|
||||
p { "Pending: " strong id="pending" { (pending) } }
|
||||
}))
|
||||
.with_child(add_form())
|
||||
.with_child(Html::with(move |_| html! {
|
||||
ul id="tasks" {
|
||||
@for task in &tasks {
|
||||
(task_item(task))
|
||||
}
|
||||
}
|
||||
}))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct TaskForm {
|
||||
title: String,
|
||||
}
|
||||
|
||||
async fn create(
|
||||
request: HttpRequest,
|
||||
web::Form(form): web::Form<TaskForm>,
|
||||
) -> Result<Response, DbFailure> {
|
||||
let title = form.title.trim();
|
||||
let added = if title.is_empty() { None } else { Some(add_task(title).await?) };
|
||||
if !request.is_htmx() {
|
||||
// Without JavaScript the browser posts the form: back to the list.
|
||||
return Ok(Redirect::see_other("/"));
|
||||
}
|
||||
Ok(match added {
|
||||
Some(task) => HtmxResponse::new(task_item(&task))
|
||||
.oob(pending_update(pending().await?))
|
||||
.into_response(),
|
||||
None => HtmxResponse::empty().into_response(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn toggle(web::Path(id): web::Path<i32>) -> Result<Response, DbFailure> {
|
||||
let Some(task) = find_task(id).await? else {
|
||||
return Ok(not_found());
|
||||
};
|
||||
let done = !task.done;
|
||||
let mut task = task.into_active_model();
|
||||
task.done = Set(done);
|
||||
let task = task.update(dbconn()).await?;
|
||||
Ok(HtmxResponse::new(task_item(&task))
|
||||
.oob(pending_update(pending().await?))
|
||||
.into_response())
|
||||
}
|
||||
|
||||
async fn remove(web::Path(id): web::Path<i32>) -> Result<Response, DbFailure> {
|
||||
task::Entity::delete_by_id(id).exec(dbconn()).await?;
|
||||
Ok(HtmxResponse::empty()
|
||||
.oob(pending_update(pending().await?))
|
||||
.into_response())
|
||||
}
|
||||
|
||||
async fn edit(web::Path(id): web::Path<i32>) -> Result<Response, DbFailure> {
|
||||
Ok(match find_task(id).await? {
|
||||
Some(task) => HtmxResponse::new(edit_item(&task)).into_response(),
|
||||
None => not_found(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn show(web::Path(id): web::Path<i32>) -> Result<Response, DbFailure> {
|
||||
Ok(match find_task(id).await? {
|
||||
Some(task) => HtmxResponse::new(task_item(&task)).into_response(),
|
||||
None => not_found(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn update(
|
||||
web::Path(id): web::Path<i32>,
|
||||
web::Form(form): web::Form<TaskForm>,
|
||||
) -> Result<Response, DbFailure> {
|
||||
let Some(task) = find_task(id).await? else {
|
||||
return Ok(not_found());
|
||||
};
|
||||
let title = form.title.trim().to_string();
|
||||
if title.is_empty() {
|
||||
return Ok(HtmxResponse::new(task_item(&task)).into_response());
|
||||
}
|
||||
let mut task = task.into_active_model();
|
||||
task.title = Set(title);
|
||||
let task = task.update(dbconn()).await?;
|
||||
Ok(HtmxResponse::new(task_item(&task)).into_response())
|
||||
}
|
||||
```
|
||||
|
||||
## Lo que has construido
|
||||
|
||||
- Una aplicación con **datos persistentes** en SQLite, que cambia de motor con una *feature* y dos
|
||||
líneas de configuración.
|
||||
- Una **migración** que se aplica sola al arrancar, una sola vez.
|
||||
- Una **entidad** con consultas tipadas: si te equivocas de columna, no compila.
|
||||
- Un tipo de error que convierte cualquier fallo de la base de datos en una respuesta 500 con su
|
||||
traza, sin repetir código.
|
||||
- Pruebas aisladas con una base de datos **en memoria**.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Conectar una base de datos](../how-to/database.md): PostgreSQL, MySQL, más migraciones y
|
||||
consultas.
|
||||
- [Añadir usuarios y permisos](../how-to/users.md): que sólo quien inicia sesión pueda borrar
|
||||
tareas.
|
||||
- [Ordenar y paginar sin recargar](../how-to/htmx-tables.md), para cuando la lista crezca.
|
||||
206
doc/v0.6/es/src/tutorials/first-app.md
Normal file
206
doc/v0.6/es/src/tutorials/first-app.md
Normal file
|
|
@ -0,0 +1,206 @@
|
|||
# Tu primera aplicación
|
||||
|
||||
En este tutorial pasas de no tener nada instalado a un servidor web propio con dos páginas, una
|
||||
de ellas con parámetros en la URL, y un ajuste que cambias sin recompilar.
|
||||
|
||||
- **Tiempo:** unos 10 minutos (más lo que tarde la primera compilación).
|
||||
- **Necesitas:** conocer lo básico de Rust y tener una terminal a mano.
|
||||
- **Al terminar tendrás:** una aplicación PageTop que entiendes línea a línea.
|
||||
|
||||
## 1. Instala Rust
|
||||
|
||||
PageTop necesita **Rust 1.88** o posterior. Si no lo tienes, instálalo con
|
||||
[rustup](https://rustup.rs) y comprueba la versión:
|
||||
|
||||
```sh
|
||||
rustc --version
|
||||
```
|
||||
|
||||
```text
|
||||
rustc 1.90.0 (1159e78c4 2025-09-14)
|
||||
```
|
||||
|
||||
Cualquier versión igual o superior sirve. Un editor con *rust-analyzer* (VS Code, Zed, RustRover...)
|
||||
te ahorrará muchos viajes a la documentación.
|
||||
|
||||
## 2. Crea el proyecto
|
||||
|
||||
```sh
|
||||
cargo new hello-pagetop
|
||||
cd hello-pagetop
|
||||
```
|
||||
|
||||
Añade PageTop a `Cargo.toml`. Esta guía describe la versión en desarrollo, que se obtiene del
|
||||
repositorio oficial:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
pagetop = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
||||
```
|
||||
|
||||
No necesitas añadir Tokio ni Axum: PageTop ya los trae y los expone a través de su **preludio**,
|
||||
`pagetop::prelude::*`.
|
||||
|
||||
## 3. Arranca el servidor
|
||||
|
||||
Sustituye el contenido de `src/main.rs`:
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
|
||||
#[pagetop::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
Application::new().await.run().await
|
||||
}
|
||||
```
|
||||
|
||||
Y ejecútalo:
|
||||
|
||||
```sh
|
||||
cargo run
|
||||
```
|
||||
|
||||
La primera compilación tarda unos minutos; las siguientes, segundos. Cuando termine, verás algo así:
|
||||
|
||||
```text
|
||||
PageTop App
|
||||
Powered by PageTop 0.5.0
|
||||
|
||||
INFO pagetop::core::extension::all: Loading settings for all extensions
|
||||
INFO pagetop::core::extension::all: Calling application bootstrap
|
||||
```
|
||||
|
||||
En un terminal de 80 columnas o más, el nombre aparece en letras grandes. Abre
|
||||
<http://localhost:8080>: es la página de bienvenida de PageTop. Para el servidor con `Ctrl+C`.
|
||||
|
||||
`Application::new()` arranca una aplicación vacía, útil para comprobar que todo funciona. Para hacer
|
||||
algo propio necesitas una **extensión raíz**.
|
||||
|
||||
## 4. Tu primera página
|
||||
|
||||
Todo en PageTop es una extensión, empezando por tu aplicación. Cambia `src/main.rs`:
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
|
||||
struct HelloPageTop;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for HelloPageTop {
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router.route("/", web::get(home))
|
||||
}
|
||||
}
|
||||
|
||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("Home"))
|
||||
.with_child(Html::with(|_| html! {
|
||||
h1 { "Hello, PageTop!" }
|
||||
p { "This page is generated by the server." }
|
||||
}))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
#[pagetop::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
Application::prepare(&HelloPageTop).await.run().await
|
||||
}
|
||||
```
|
||||
|
||||
Arranca de nuevo y recarga <http://localhost:8080>. Qué está pasando:
|
||||
|
||||
1. `HelloPageTop` es una extensión: un *struct* vacío que implementa `Extension`. Todos sus
|
||||
métodos son opcionales; aquí sólo usa uno.
|
||||
2. `configure_router()` registra la ruta `/` y la asocia al *handler* `home`.
|
||||
3. `home` recibe la petición, construye una `Page`, le pone título y contenido, y la **renderiza**:
|
||||
el tema activo añade el `<head>`, la estructura de la página, los estilos y el pie.
|
||||
4. `Application::prepare()` arranca la aplicación con `HelloPageTop` como **extensión raíz**.
|
||||
|
||||
El contenido se escribe con la macro `html!`: HTML con sintaxis de Rust, comprobado al compilar. Si
|
||||
olvidas cerrar una llave, no compila. La verás a fondo en [Escribir HTML con
|
||||
`html!`](../how-to/html.md).
|
||||
|
||||
## 5. Una ruta con parámetros
|
||||
|
||||
Las rutas pueden capturar segmentos de la URL. Añade una segunda ruta:
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
|
||||
struct HelloPageTop;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for HelloPageTop {
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router
|
||||
.route("/", web::get(home))
|
||||
.route("/hello/{name}", web::get(hello))
|
||||
}
|
||||
}
|
||||
|
||||
# async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
# Page::new(request).render().await
|
||||
# }
|
||||
async fn hello(
|
||||
request: HttpRequest,
|
||||
web::Path(name): web::Path<String>,
|
||||
) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("Greeting"))
|
||||
.with_child(Html::with(move |_| html! { h1 { "Hello, " (name) "!" } }))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
#[pagetop::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
Application::prepare(&HelloPageTop).await.run().await
|
||||
}
|
||||
```
|
||||
|
||||
Visita <http://localhost:8080/hello/Ana>. Ahora prueba
|
||||
<http://localhost:8080/hello/%3Cscript%3E>: verás `<script>` como texto, porque `html!` **escapa**
|
||||
todo lo que insertas. No tienes que acordarte de hacerlo.
|
||||
|
||||
Y una ruta que no existe, como <http://localhost:8080/nope>, responde con una página 404 que
|
||||
mantiene el aspecto del sitio.
|
||||
|
||||
## 6. Cambia un ajuste sin recompilar
|
||||
|
||||
El título de la pestaña dice «PageTop App | Greeting». Ese nombre es un **ajuste** de la
|
||||
aplicación. Crea `config/common.toml`, junto a `Cargo.toml`:
|
||||
|
||||
```toml
|
||||
[app]
|
||||
name = "Hello PageTop"
|
||||
```
|
||||
|
||||
Para el servidor y arráncalo con `cargo run`: no se recompila nada, sólo se lee la configuración.
|
||||
La pestaña dice ahora «Hello PageTop | Greeting», y el pie de página también usa el nuevo nombre.
|
||||
|
||||
Prueba a escribir mal la clave (`nmae = ...`): la aplicación no arranca y te dice qué clave no
|
||||
reconoce, y cuáles admite:
|
||||
|
||||
```text
|
||||
Invalid settings in section [app]: unknown field `nmae`, expected one of `name`, `theme`, ...
|
||||
```
|
||||
|
||||
Las erratas en la configuración no pasan desapercibidas.
|
||||
|
||||
## Lo que has construido
|
||||
|
||||
- Un servidor web completo en un solo archivo, sin añadir Tokio ni Axum a mano.
|
||||
- Una **extensión raíz** con dos rutas, una de ellas con parámetros.
|
||||
- Páginas completas que el tema rodea de cabecera, estilos y pie.
|
||||
- HTML comprobado al compilar y escapado automáticamente.
|
||||
- Un ajuste en `config/common.toml` que cambia la aplicación sin recompilar.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Recorrido por PageTop](tour.md): componentes, formularios, traducciones y pruebas en un solo
|
||||
paseo.
|
||||
- [Tareas del huerto con HTMX](htmx-tasks.md), si prefieres ir directo a la interactividad.
|
||||
- [Arquitectura: del arranque a la respuesta](../explanation/architecture.md), para entender qué
|
||||
hace `Application::prepare()` por dentro.
|
||||
1006
doc/v0.6/es/src/tutorials/htmx-tasks.md
Normal file
1006
doc/v0.6/es/src/tutorials/htmx-tasks.md
Normal file
File diff suppressed because it is too large
Load diff
525
doc/v0.6/es/src/tutorials/tour.md
Normal file
525
doc/v0.6/es/src/tutorials/tour.md
Normal file
|
|
@ -0,0 +1,525 @@
|
|||
# Recorrido por PageTop
|
||||
|
||||
Este recorrido va más rápido que [Tu primera aplicación](first-app.md). En una sola aplicación, un
|
||||
directorio de huertos vecinales, tocas las piezas que usarás a diario: un **tema**, un
|
||||
**componente** propio, una **rejilla**, un **formulario**, **traducciones**, **ajustes** propios y
|
||||
una **prueba**. Cada sección termina con un enlace a la guía que la explica a fondo.
|
||||
|
||||
- **Tiempo:** unos 20 minutos.
|
||||
- **Necesitas:** haber hecho [Tu primera aplicación](first-app.md).
|
||||
|
||||
## Prepara el proyecto
|
||||
|
||||
```sh
|
||||
cargo new gardens
|
||||
cd gardens
|
||||
```
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
pagetop = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
||||
pagetop-bootsier = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
```
|
||||
|
||||
Esta vez la aplicación vive en `src/lib.rs` y `src/main.rs` sólo la arranca. Así las pruebas, y
|
||||
cualquier otro programa, pueden usar la aplicación como una biblioteca:
|
||||
|
||||
```rust,ignore
|
||||
// src/main.rs
|
||||
use pagetop::prelude::*;
|
||||
|
||||
#[pagetop::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
Application::prepare(&gardens::Gardens).await.run().await
|
||||
}
|
||||
```
|
||||
|
||||
```rust,no_run
|
||||
// src/lib.rs
|
||||
use pagetop::prelude::*;
|
||||
|
||||
pub struct Gardens;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Gardens {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_bootsier::Bootsier]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`pagetop_bootsier::Bootsier` es un **tema** basado en Bootstrap 5. Declararlo como dependencia lo
|
||||
pone a disposición de la aplicación; elegirlo es cosa de la configuración. Crea
|
||||
`config/common.toml`:
|
||||
|
||||
```toml
|
||||
[app]
|
||||
name = "Urban Garden"
|
||||
theme = "Bootsier"
|
||||
```
|
||||
|
||||
Más en [Crear un tema](../how-to/themes.md) y [Extensiones oficiales](../reference/extensions.md).
|
||||
|
||||
## Un componente propio
|
||||
|
||||
Cada huerto se muestra en una tarjeta. Como la tarjeta se repite, se convierte en un
|
||||
**componente**: un tipo Rust con sus datos, sus métodos `with_*()` y su HTML. Añádelo a
|
||||
`src/lib.rs`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
#[derive(AutoDefault, Clone, Debug, Getters)]
|
||||
pub struct GardenCard {
|
||||
/// Returns the name of the garden.
|
||||
name: Lc,
|
||||
/// Returns the number of free plots.
|
||||
#[getters(copy)]
|
||||
free_plots: u32,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Component for GardenCard {
|
||||
fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
let plots = Lc::n(util::join!(self.free_plots().to_string(), " free plots"));
|
||||
let mut badge = if self.free_plots() > 0 {
|
||||
Badge::success(plots)
|
||||
} else {
|
||||
Badge::neutral(plots)
|
||||
};
|
||||
Ok(html! {
|
||||
article class="garden-card" {
|
||||
h3 { (self.name().using(cx)) }
|
||||
(badge.render(cx).await)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[builder_impl]
|
||||
impl GardenCard {
|
||||
/// Sets the name of the garden.
|
||||
pub fn with_name(mut self, name: Lc) -> Self {
|
||||
self.name = name;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the number of free plots.
|
||||
pub fn with_free_plots(mut self, free_plots: u32) -> Self {
|
||||
self.free_plots = free_plots;
|
||||
self
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Tres cosas a retener:
|
||||
|
||||
- Los textos son `Lc`, no cadenas: se resuelven al renderizar, en el idioma de cada visitante.
|
||||
- `prepare()` es `async` y puede usar otros componentes: aquí, un `Badge` verde o gris según
|
||||
queden parcelas libres. El tema decide cómo se ve cada intención.
|
||||
- `#[builder_impl]` genera, junto a cada `with_*()`, un `alter_*()` que modifica la tarjeta ya
|
||||
creada. Un tema o una extensión pueden usarlo para retocarla.
|
||||
|
||||
Más en [Crear un componente](../how-to/custom-components.md).
|
||||
|
||||
## Una página con rejilla
|
||||
|
||||
Los datos son una lista fija y la página los coloca en una rejilla de tres columnas con `Grid`, sin
|
||||
escribir CSS:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# #[derive(AutoDefault, Clone, Debug)]
|
||||
# pub struct GardenCard;
|
||||
# #[async_trait]
|
||||
# impl Component for GardenCard {
|
||||
# fn new() -> Self { Self }
|
||||
# async fn prepare(&self, _: &mut Context) -> Result<Markup, ComponentError> { Ok(html! {}) }
|
||||
# }
|
||||
# impl GardenCard {
|
||||
# pub fn with_name(self, _: Lc) -> Self { self }
|
||||
# pub fn with_free_plots(self, _: u32) -> Self { self }
|
||||
# }
|
||||
const GARDENS: &[(&str, u32)] = &[("Benimaclet", 4), ("Russafa", 0), ("Natzaret", 2)];
|
||||
|
||||
async fn list(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
let mut grid = Grid::new()
|
||||
.with_columns(grid::Tracks::repeat(3, grid::AxisTrack::Fraction(1.0)))
|
||||
.with_gap(align::Gap::Both(UnitValue::RelRem(1.0)));
|
||||
for (name, free_plots) in GARDENS {
|
||||
grid = grid.with_child(
|
||||
GardenCard::new()
|
||||
.with_name(Lc::n(*name))
|
||||
.with_free_plots(*free_plots),
|
||||
);
|
||||
}
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("Community gardens"))
|
||||
.with_child(Html::with(|_| html! { h1 { "Community gardens" } }))
|
||||
.with_child(grid)
|
||||
.with_child(Button::anchor(Lc::n("Propose a garden"), "/propose"))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
```
|
||||
|
||||
Regístrala en la extensión con `router.route("/", web::get(list))`, arranca y abre
|
||||
<http://localhost:8080>. Con Bootsier, las tarjetas, las etiquetas y el botón ya tienen el aspecto
|
||||
de Bootstrap. Cambia `theme = "Basic"` en la configuración, reinicia y verás el mismo contenido con
|
||||
otra piel.
|
||||
|
||||
Más en [Maquetar con Flex y Grid](../how-to/layout.md) y [Usar componentes](../how-to/components.md).
|
||||
|
||||
## Un formulario
|
||||
|
||||
Ahora, un formulario para proponer huertos nuevos. `Form` y sus campos generan las etiquetas, la
|
||||
marca de obligatorio y los atributos de accesibilidad:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
use serde::Deserialize;
|
||||
|
||||
fn proposal_form() -> Form {
|
||||
Form::new()
|
||||
.with_action("/propose")
|
||||
.with_method(form::Method::Post)
|
||||
.with_child(
|
||||
form::input::Field::text()
|
||||
.with_name("name")
|
||||
.with_label(Lc::n("Garden name"))
|
||||
.with_required(true),
|
||||
)
|
||||
.with_child(
|
||||
form::input::Field::email()
|
||||
.with_name("email")
|
||||
.with_label(Lc::n("Your email"))
|
||||
.with_help_text(Lc::n("Only to tell you how it goes.")),
|
||||
)
|
||||
.with_child(Button::submit(Lc::n("Send")))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Proposal {
|
||||
name: String,
|
||||
email: String,
|
||||
}
|
||||
|
||||
async fn propose(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("Propose a garden"))
|
||||
.with_child(Messages::new())
|
||||
.with_child(proposal_form())
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
async fn receive(
|
||||
request: HttpRequest,
|
||||
web::Form(proposal): web::Form<Proposal>,
|
||||
) -> Result<Response, ErrorPage> {
|
||||
if proposal.name.trim().is_empty() {
|
||||
let mut page = Page::new(request)
|
||||
.with_title(Lc::n("Propose a garden"))
|
||||
.with_child(Messages::new())
|
||||
.with_child(proposal_form());
|
||||
page.context()
|
||||
.push_message(MessageLevel::Error, Lc::n("The garden needs a name."));
|
||||
return page.render().await.map(IntoResponse::into_response);
|
||||
}
|
||||
trace::info!("New garden proposed: {} ({})", proposal.name, proposal.email);
|
||||
Ok(Redirect::see_other("/"))
|
||||
}
|
||||
```
|
||||
|
||||
Las dos funciones atienden la misma ruta, una por método:
|
||||
`router.route("/propose", web::get(propose).post(receive))`.
|
||||
|
||||
El navegador ya impide enviar el nombre vacío (`required`), pero el servidor lo comprueba igual:
|
||||
cualquiera puede saltarse el navegador. Si falta, la página se repite con un aviso en `Messages`. Si
|
||||
todo va bien, redirige con `see_other()`, para que recargar no reenvíe el formulario. La propuesta
|
||||
queda en las trazas del terminal.
|
||||
|
||||
Más en [Crear y procesar formularios](../how-to/forms.md).
|
||||
|
||||
## Traducciones
|
||||
|
||||
Los textos de la interfaz se traducen con [Fluent](https://projectfluent.org). Crea un archivo por
|
||||
idioma en `src/locale/`:
|
||||
|
||||
```text
|
||||
# src/locale/en-US/app.ftl
|
||||
gardens = Community gardens
|
||||
free-plots = { $count ->
|
||||
[0] No free plots
|
||||
[one] One free plot
|
||||
*[other] { $count } free plots
|
||||
}
|
||||
```
|
||||
|
||||
```text
|
||||
# src/locale/es-ES/app.ftl
|
||||
gardens = Huertos vecinales
|
||||
free-plots = { $count ->
|
||||
[0] Sin parcelas libres
|
||||
[one] Una parcela libre
|
||||
*[other] { $count } parcelas libres
|
||||
}
|
||||
```
|
||||
|
||||
Fluent resuelve los plurales en el propio archivo, cada idioma con sus reglas. En `src/lib.rs`,
|
||||
declara las traducciones una vez y usa `Lc::t()` donde antes había `Lc::n()`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
include_locales!(LOCALES_APP);
|
||||
|
||||
# struct Card { free_plots: u32 }
|
||||
# impl Card { fn free_plots(&self) -> u32 { self.free_plots } fn f(&self) {
|
||||
// In GardenCard::prepare():
|
||||
let plots = Lc::t("free-plots", &LOCALES_APP).with_number("count", self.free_plots());
|
||||
# }}
|
||||
# fn g() {
|
||||
// In list():
|
||||
let title = Lc::t("gardens", &LOCALES_APP);
|
||||
# }
|
||||
```
|
||||
|
||||
`include_locales!` mete los archivos en el binario al compilar. Abre
|
||||
<http://localhost:8080/?lang=es>: el título y las etiquetas salen en español. Sin `?lang=`,
|
||||
PageTop usa el idioma configurado o el que pida el navegador.
|
||||
|
||||
Más en [Traducir la aplicación](../how-to/localization.md).
|
||||
|
||||
## Ajustes propios
|
||||
|
||||
La aplicación muestra los huertos de una ciudad, y la ciudad debería poder cambiarse sin
|
||||
recompilar. Declara una sección propia de configuración, con sus valores por defecto:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
/// Settings of the `[gardens]` section.
|
||||
pub static SETTINGS: LazySettings<GardensSettings> = LazySettings::new();
|
||||
|
||||
/// The **`[gardens]`** section of the configuration.
|
||||
#[settings(section = "gardens")]
|
||||
pub struct GardensSettings {
|
||||
/// City whose gardens are listed.
|
||||
#[default = "Valencia"]
|
||||
pub city: String,
|
||||
}
|
||||
|
||||
pub struct Gardens;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Gardens {
|
||||
// ... dependencies() and configure_router() as before ...
|
||||
|
||||
fn settings(&self) -> Option<&'static dyn LoadSettings> {
|
||||
Some(&SETTINGS)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Úsala en la página, por ejemplo bajo el título, con `SETTINGS.city`. Y cámbiala en
|
||||
`config/common.toml`:
|
||||
|
||||
```toml
|
||||
[gardens]
|
||||
city = "Alicante"
|
||||
```
|
||||
|
||||
`settings()` hace que la sección se cargue y se **valide al arrancar**: una clave desconocida o un
|
||||
valor del tipo equivocado detienen la aplicación antes de servir una sola página.
|
||||
|
||||
Más en [Configurar la aplicación](../how-to/configuration.md).
|
||||
|
||||
## Una prueba
|
||||
|
||||
Las pruebas preparan la aplicación sin abrir ningún puerto y le envían peticiones. Crea
|
||||
`tests/gardens.rs`:
|
||||
|
||||
```rust
|
||||
# use pagetop::prelude::*;
|
||||
# use serde::Deserialize;
|
||||
# include_locales!(LOCALES_APP);
|
||||
# pub static SETTINGS: LazySettings<GardensSettings> = LazySettings::new();
|
||||
# #[settings(section = "gardens")]
|
||||
# pub struct GardensSettings {
|
||||
# #[default = "Valencia"]
|
||||
# pub city: String,
|
||||
# }
|
||||
# #[derive(AutoDefault, Clone, Debug, Getters)]
|
||||
# pub struct GardenCard {
|
||||
# name: Lc,
|
||||
# #[getters(copy)]
|
||||
# free_plots: u32,
|
||||
# }
|
||||
# #[async_trait]
|
||||
# impl Component for GardenCard {
|
||||
# fn new() -> Self {
|
||||
# Self::default()
|
||||
# }
|
||||
# async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
# let plots = Lc::t("free-plots", &LOCALES_APP).with_number("count", self.free_plots());
|
||||
# let mut badge = if self.free_plots() > 0 {
|
||||
# Badge::success(plots)
|
||||
# } else {
|
||||
# Badge::neutral(plots)
|
||||
# };
|
||||
# Ok(html! {
|
||||
# article class="garden-card" {
|
||||
# h3 { (self.name().using(cx)) }
|
||||
# (badge.render(cx).await)
|
||||
# }
|
||||
# })
|
||||
# }
|
||||
# }
|
||||
# #[builder_impl]
|
||||
# impl GardenCard {
|
||||
# pub fn with_name(mut self, name: Lc) -> Self {
|
||||
# self.name = name;
|
||||
# self
|
||||
# }
|
||||
# pub fn with_free_plots(mut self, free_plots: u32) -> Self {
|
||||
# self.free_plots = free_plots;
|
||||
# self
|
||||
# }
|
||||
# }
|
||||
# const GARDENS: &[(&str, u32)] = &[("Benimaclet", 4), ("Russafa", 0), ("Natzaret", 2)];
|
||||
# pub struct Gardens;
|
||||
# #[async_trait]
|
||||
# impl Extension for Gardens {
|
||||
# fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
# vec![&pagetop_bootsier::Bootsier]
|
||||
# }
|
||||
# fn settings(&self) -> Option<&'static dyn LoadSettings> {
|
||||
# Some(&SETTINGS)
|
||||
# }
|
||||
# fn configure_router(&self, router: Router) -> Router {
|
||||
# router
|
||||
# .route("/", web::get(list))
|
||||
# .route("/propose", web::get(propose).post(receive))
|
||||
# }
|
||||
# }
|
||||
# async fn list(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
# let mut grid = Grid::new()
|
||||
# .with_columns(grid::Tracks::repeat(3, grid::AxisTrack::Fraction(1.0)))
|
||||
# .with_gap(align::Gap::Both(UnitValue::RelRem(1.0)));
|
||||
# for (name, free_plots) in GARDENS {
|
||||
# grid = grid.with_child(
|
||||
# GardenCard::new()
|
||||
# .with_name(Lc::n(*name))
|
||||
# .with_free_plots(*free_plots),
|
||||
# );
|
||||
# }
|
||||
# let title = Lc::t("gardens", &LOCALES_APP);
|
||||
# Page::new(request)
|
||||
# .with_title(title.clone())
|
||||
# .with_child(Html::with(move |cx| html! {
|
||||
# h1 { (title.using(cx)) }
|
||||
# p { (SETTINGS.city) }
|
||||
# }))
|
||||
# .with_child(grid)
|
||||
# .with_child(Button::anchor(Lc::n("Propose a garden"), "/propose"))
|
||||
# .render()
|
||||
# .await
|
||||
# }
|
||||
# fn proposal_form() -> Form {
|
||||
# Form::new()
|
||||
# .with_action("/propose")
|
||||
# .with_method(form::Method::Post)
|
||||
# .with_child(
|
||||
# form::input::Field::text()
|
||||
# .with_name("name")
|
||||
# .with_label(Lc::n("Garden name"))
|
||||
# .with_required(true),
|
||||
# )
|
||||
# .with_child(Button::submit(Lc::n("Send")))
|
||||
# }
|
||||
# #[derive(Deserialize)]
|
||||
# struct Proposal {
|
||||
# name: String,
|
||||
# }
|
||||
# async fn propose(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
# Page::new(request).with_child(Messages::new()).with_child(proposal_form()).render().await
|
||||
# }
|
||||
# async fn receive(
|
||||
# request: HttpRequest,
|
||||
# web::Form(proposal): web::Form<Proposal>,
|
||||
# ) -> Result<Response, ErrorPage> {
|
||||
# if proposal.name.trim().is_empty() {
|
||||
# let mut page = Page::new(request)
|
||||
# .with_child(Messages::new())
|
||||
# .with_child(proposal_form());
|
||||
# page.context()
|
||||
# .push_message(MessageLevel::Error, Lc::n("The garden needs a name."));
|
||||
# return page.render().await.map(IntoResponse::into_response);
|
||||
# }
|
||||
# Ok(Redirect::see_other("/"))
|
||||
# }
|
||||
# mod gardens {
|
||||
# pub use super::Gardens;
|
||||
# }
|
||||
use pagetop::prelude::*;
|
||||
|
||||
#[pagetop::test]
|
||||
async fn lists_the_gardens_in_both_languages() {
|
||||
let app = web::test::init_router(Application::prepare(&gardens::Gardens).await.test());
|
||||
|
||||
let request = web::test::TestRequest::get().uri("/").to_request();
|
||||
let body = web::test::read_body_text(web::test::send_request(&app, request).await).await;
|
||||
assert!(body.contains("Community gardens"));
|
||||
assert!(body.contains("4 free plots"));
|
||||
assert!(body.contains("No free plots"));
|
||||
|
||||
let request = web::test::TestRequest::get().uri("/?lang=es").to_request();
|
||||
let body = web::test::read_body_text(web::test::send_request(&app, request).await).await;
|
||||
assert!(body.contains("Huertos vecinales"));
|
||||
assert!(body.contains("Sin parcelas libres"));
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn a_proposal_without_name_is_rejected() {
|
||||
let app = web::test::init_router(Application::prepare(&gardens::Gardens).await.test());
|
||||
|
||||
// The form is sent as a browser does, with an empty name.
|
||||
let request = web::test::TestRequest::post()
|
||||
.uri("/propose")
|
||||
.form("name=+&email=ana%40example.com")
|
||||
.to_request();
|
||||
let body = web::test::read_body_text(web::test::send_request(&app, request).await).await;
|
||||
assert!(body.contains("The garden needs a name."));
|
||||
}
|
||||
```
|
||||
|
||||
```sh
|
||||
cargo test
|
||||
```
|
||||
|
||||
`#[pagetop::test]` ejecuta cada prueba en el mismo *runtime* asíncrono que usa la aplicación real.
|
||||
|
||||
Más en [Probar rutas y componentes](../how-to/testing.md).
|
||||
|
||||
## Lo que has recorrido
|
||||
|
||||
| Pieza | Lo que hace | Para profundizar |
|
||||
|---|---|---|
|
||||
| Extensión | Declara dependencias, rutas y ajustes | [Crear una extensión](../how-to/extensions.md) |
|
||||
| Tema | Da el aspecto; se elige en la configuración | [Crear un tema](../how-to/themes.md) |
|
||||
| Componente | Interfaz reutilizable con datos y HTML propios | [Crear un componente](../how-to/custom-components.md) |
|
||||
| `Grid` | Rejillas sin CSS | [Maquetar con Flex y Grid](../how-to/layout.md) |
|
||||
| `Form` | Formularios accesibles | [Crear y procesar formularios](../how-to/forms.md) |
|
||||
| `Lc` y Fluent | Textos traducidos, con plurales | [Traducir la aplicación](../how-to/localization.md) |
|
||||
| `#[settings]` | Ajustes propios validados al arrancar | [Configurar la aplicación](../how-to/configuration.md) |
|
||||
| `#[pagetop::test]` | Pruebas sin servidor | [Probar rutas y componentes](../how-to/testing.md) |
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Tareas del huerto con HTMX](htmx-tasks.md): la misma forma de trabajar, ahora sin recargar la
|
||||
página.
|
||||
- [Componentes, temas y renderizado](../explanation/rendering.md): qué pasa entre `with_child()` y
|
||||
el HTML final.
|
||||
Loading…
Add table
Add a link
Reference in a new issue