1// Forms (decisions/F13.md): fields stating their rules, each2// field's error shown once it was left changed, the form submitted or a3// server refused it, and from then on as it changes; a submit focusing4// the first field in error in Tab order.5//6// A form keeps its fields as slots: the label, the hint and whether it is7// required, the signals of its text and of what the form knows of it,8// the element showing it, and its rules behind a `Checking` object, so9// only giving a value is generic. Nothing of a verdict is kept: each read10// parses and checks again, so a binding showing an error follows every11// signal the rules read. Leaving is seen through the focus hook the12// first form sets.1314import std::string;15import std::vector;16import std::option;17import std::text;18import std::math;19import std::number;20import std::time;21import std::locale;22import std::result as std_result;23import pkg::alloy::window;24import pkg::alloy::draw;25import pkg::alloy::text as typeset;2627import pkg::alloy::ui;28import pkg::alloy::ui::store;29import pkg::alloy::ui::tree;30import pkg::alloy::ui::layout;31import pkg::alloy::ui::painting;32import pkg::alloy::ui::events;33import pkg::alloy::ui::widgets;34import pkg::alloy::ui::fields;35import pkg::alloy::ui::scrolling;36import pkg::alloy::ui::running;37import pkg::alloy::ui::timers;38import pkg::alloy::ui::layers;39import pkg::alloy::ui::motion;40import pkg::alloy::ui::transitions;41import pkg::alloy::ui::languages;42import pkg::alloy::ui::extensions;43import pkg::alloy::ui::views;44import ui_app;45import screens;46import dates;47import pkg::alloy::ui_controls;4849// The forms made, the gone forgotten as the focus moves, and the50// messages a program set.51pub type FormsState = struct {52 pub forms: Vector<Form> = Vector<Form>::empty(),53 pub messages: Option<FormMessages> = ::None,54};5556// The forms' state, a signal of the app's made with the first form or57// the messages set, as an extension, which follows the text fields' focus.58pub type Forms : Extension = struct {59 pub state: Signal<FormsState>,60};6162// A text field of a form left changed shows its error from then on.63pub fn focused(self f: &var Forms, ui: &var Ui, from: Option<u32>, onto: Option<u32>, ring: bool) {64 if (from is ::Some |left| && ui.is_text_field(left)) {65 field_focused(&var ui, left, false);66 }67 if (onto is ::Some |entered| && ui.is_text_field(entered)) {68 field_focused(&var ui, entered, true);69 }70}7172fn is_text_field(self ui: &Ui, index: u32) -> bool {73 if (ui.node(index).widget is ::Some |&w|) {74 return w is TextField;75 }76 return false;77}7879pub fn forms_state(self ui: &var Ui) -> &var FormsState {80 if (ui.extension<Forms>() is ::None) {81 const saved = ui.owner;82 ui.owner = 0;83 const state = ui.signal(FormsState {});84 ui.owner = saved;85 ui.install(new Forms { .state = state });86 }87 if (ui.extension<Forms>() is ::Some |&f|) {88 const state = f.state;89 return &var state.peek_var(&var ui);90 }91 panic "pkg::alloy::ui: no forms";92}9394// The messages a program set, if it did.95fn messages(self ui: &Ui) -> Option<&FormMessages> {96 if (ui.extension<Forms>() is ::Some |&f| && f.state.peek(&ui).messages is ::Some |&m|) {97 return ::Some(&m);98 }99 return ::None;100}101102// What a form keeps: its fields, and what a submit that passes runs.103pub type FormFields = struct {104 pub slots: Vector<FieldSlot>,105 pub then: Option<|=| (&var Ui)>,106};107108pub type FieldSlot = struct {109 pub label: String,110 pub hint: String,111 pub required: bool,112 pub wanted: Wanted,113 pub text: Signal<String>, // a typed field's114 pub state: Signal<FieldState>,115 pub check: *Checking,116 pub element: Option<Element> = ::None, // showing it, once made117 pub entered: Option<String> = ::None, // its text as the focus came to it118};119120// What the form knows of a field, which its error's showing follows.121pub type FieldState = struct {122 pub left: bool = false, // left changed, or a value picked123 pub refused: String = String::empty(), // a server's verdict, until it changes124};125126// Where a field's value comes from.127pub type Source<T> = enum {128 Typed: Parser<T>,129 Picked: Signal<Option<T>>,130};131132// What a field's value comes to, the value aside.133pub type Check = enum {134 Empty,135 Valid,136 Invalid: String,137};138139// A field's parsing and rules, its value's type hidden.140pub interface Checking {141 // What the text typed, or the value picked, comes to now.142 fn check(self: &, ui: &Ui, text: &String) -> Check;143}144145pub type Checked<T> : Checking = struct {146 pub source: Source<T>,147 pub rules: Vector<Rule<T>>,148};149150// Whether a picked value stands for nothing: a box left unchecked.151fn Checked::unset(value: &T) -> bool => false;152153fn Checked<bool>::unset(value: &bool) -> bool => !value;154155// What a required picked field asks for.156pub fn Checked::wanted() -> Wanted => Wanted::Pick;157158pub fn Checked<bool>::wanted() -> Wanted => Wanted::Check;159160// The field's value and its rules' verdict, its being required aside.161pub fn outcome<T>(self c: &Checked<T>, ui: &Ui, text: &String) -> Verdict<T> {162 var found = Option<T>::None;163 if (c.source is ::Typed |&parse|) {164 if (text.view().trim().length() == 0) {165 return Verdict<T>::Empty;166 }167 match (parse(&ui, &text.view())) {168 ::Ok |move value| {169 found = ::Some(move value);170 }171 ::Err |move why| {172 return Verdict<T>::Invalid(move why);173 }174 }175 } else if (c.source is ::Picked |picked|) {176 if (picked.get(&ui) is ::Some |&value| && !Checked<T>::unset(&value)) {177 found = ::Some(copy value);178 }179 }180 var value = if (found is ::Some |move v|) move v else {181 return Verdict<T>::Empty;182 };183 for (c.rules.view()) |&rule| {184 if (rule(&ui, &value) is ::Some |move why|) {185 return Verdict<T>::Invalid(move why);186 }187 }188 return Verdict<T>::Valid(move value);189}190191pub fn check<T>(self c: &Checked<T>, ui: &Ui, text: &String) -> Check {192 return match (c.outcome(&ui, &text)) {193 ::Empty Check::Empty;194 ::Valid Check::Valid;195 ::Invalid |&why| Check::Invalid(copy why);196 };197}198199/* --- Forms and fields --- */200201pub fn make_form(self ui: &var Ui) -> Form {202 const form = Form {203 .fields = ui.signal(FormFields { .slots = Vector<FieldSlot>::empty(), .then = ::None }),204 .tried = ui.signal(false),205 .failure = ui.signal(String::empty())206 };207 ui.forms_state().forms.push(form);208 return form;209}210211pub fn add_text_field(212 self ui: &var Ui,213 form: &Form,214 text: String,215 options: FieldOptions<String>216) -> Field<String> {217 const same: Parser<String> = (ui, typed) => ::Ok(String::from(&typed));218 return ui.add_field(219 &form,220 move text,221 Source<String>::Typed(copy same),222 Wanted::Text,223 move options224 );225}226227pub fn add_field<T>(228 self ui: &var Ui,229 form: &Form,230 text: String,231 source: Source<T>,232 wanted: Wanted,233 options: FieldOptions<T>234) -> Field<T> {235 var checked = Checked<T> {236 .source = move source,237 .rules = Vector<Rule<T>>::from(&options.rules)238 };239 var slot = FieldSlot {240 .label = copy options.label,241 .hint = copy options.hint,242 .required = options.required,243 .wanted = wanted,244 .text = ui.signal(move text),245 .state = ui.signal(FieldState {}),246 .check = new move checked247 };248 const fields = &var form.fields.peek_var(&var ui);249 fields.slots.push(move slot);250 return Field<T> { .form = copy form, .index = (fields.slots.length() - 1) to u32 };251}252253// The field's slot in its form, no read recorded.254pub fn slot<T>(self field: &Field<T>, ui: &Ui) -> &FieldSlot {255 return &field.form.fields.peek(&ui).slots.get(field.index to u64);256}257258fn slot_at(self ui: &Ui, form: Form, index: u32) -> &FieldSlot {259 return &form.fields.peek(&ui).slots.get(index to u64);260}261262// The index of the element, if there is one.263fn index(self element: &Option<Element>) -> Option<u32> {264 if (element is ::Some |e|) {265 return ::Some(e.index);266 }267 return ::None;268}269270// Whether the field's owner is still there.271fn alive(self slot: &FieldSlot, ui: &Ui) -> bool {272 return ui.signal_alive(slot.state.index, slot.state.generation);273}274275// Whether the form checks the field: an element showing it exists, in no276// hidden view.277fn counted(self slot: &FieldSlot, ui: &Ui) -> bool {278 if (!slot.alive(&ui)) {279 return false;280 }281 const element = if (slot.element is ::Some |e| && ui.exists(e)) e else {282 return false;283 };284 var at: Option<u32> = ::Some(element.index);285 while (at is ::Some |k|) {286 if (ui.node(k).hidden) {287 return false;288 }289 at = ui.node(k).parent;290 }291 return true;292}293294// What is wrong with the field now, shown or not: a server's refusal,295// else the required message while empty, else what its rules found.296fn problem(self slot: &FieldSlot, ui: &Ui) -> Option<String> {297 const refused = &slot.state.get(&ui).refused;298 if (refused.length() > 0) {299 return ::Some(copy refused);300 }301 return match (slot.check.check(&ui, &slot.text.get(&ui))) {302 ::Empty if (slot.required) ::Some(ui.required_message(slot.wanted)) else ::None;303 ::Valid ::None;304 ::Invalid |&why| ::Some(copy why);305 };306}307308pub fn field_verdict<T>(self ui: &Ui, field: Field<T>) -> Verdict<T> {309 const slot = &field.slot(&ui);310 const refused = &slot.state.get(&ui).refused;311 if (refused.length() > 0) {312 return Verdict<T>::Invalid(copy refused);313 }314 if (slot.check is Checked<T> |&c|) {315 var verdict = c.outcome(&ui, &slot.text.get(&ui));316 if (verdict is ::Empty && slot.required) {317 return Verdict<T>::Invalid(ui.required_message(slot.wanted));318 }319 return move verdict;320 }321 panic "pkg::alloy::ui: a field of another type";322}323324// The field's error as it shows now: once left changed, the form325// submitted or a server refused it.326pub fn shown_error(self ui: &Ui, form: Form, index: u32) -> String {327 const slot = &ui.slot_at(form, index);328 const state = &slot.state.get(&ui);329 if (330 (state.left || state.refused.length() > 0 || form.tried.get(&ui))331 && slot.problem(&ui) is ::Some |move why|332 ) {333 return move why;334 }335 return String::empty();336}337338pub fn edit_field(self ui: &var Ui, form: Form, index: u32, text: String) {339 const slot = &ui.slot_at(form, index);340 const typed = slot.text;341 const state = slot.state;342 typed.set(&var ui, move text);343 if (state.peek(&ui).refused.length() > 0) {344 state.update(&var ui, (s) => s.refused.clear());345 }346}347348pub fn pick_field<T>(self ui: &var Ui, field: Field<T>, value: Option<T>) {349 const slot = &field.slot(&ui);350 const state = slot.state;351 var picked = Option<Signal<Option<T>>>::None;352 if (slot.check is Checked<T> |&c| && c.source is ::Picked |p|) {353 picked = ::Some(p);354 }355 if (picked is ::Some |p|) {356 p.set(&var ui, move value);357 }358 state.update(&var ui, (s) {359 s.left = true;360 s.refused.clear();361 });362}363364pub fn refuse_field(self ui: &var Ui, form: Form, index: u32, message: String) {365 const slot = &ui.slot_at(form, index);366 const state = slot.state;367 const element = slot.element;368 ui.announce(f"{slot.label}: {message}", true);369 state.update(&var ui, |move message| (s: &var FieldState) => s.refused = move message);370 const errors = ui.form_errors(form);371 if (errors.try_get(0) is ::Some |&first| && element == ::Some(first.element)) {372 ui.focus_field(first.element);373 }374}375376pub fn record_field(self ui: &var Ui, form: Form, index: u32, element: Element) {377 form.fields.peek_var(&var ui).slots.get_var(index to u64).element = ::Some(element);378}379380/* --- Submitting --- */381382pub fn submit_form(self ui: &var Ui, form: Form) {383 if (form.failure.peek(&ui).length() > 0) {384 form.failure.set(&var ui, String::empty());385 }386 if (!form.tried.peek(&ui)) {387 form.tried.set(&var ui, true);388 }389 const errors = ui.form_errors(form);390 if (errors.length() == 0) {391 const then = copy form.fields.peek(&ui).then;392 if (then is ::Some |&f|) {393 f(&var ui);394 }395 return;396 }397 ui.focus_field(errors.get(0).element);398 var said = ui.summary_message(errors.length());399 said.append(&": ");400 for (errors.view(), [..errors.length()]) |&e, k| {401 if (k > 0) {402 said.append(&", ");403 }404 said.append(&e.label.view());405 }406 said.push('.');407 ui.announce(move said, true);408}409410// Focuses the element, or the first taking the focus in it, with the411// ring, scrolling it into view.412pub fn focus_field(self ui: &var Ui, element: Element) {413 if (!ui.exists(element)) {414 return;415 }416 var within = Vector<u32>::empty();417 ui.collect_focusable(element.index, &var within);418 if (within.try_get(0) is ::Some |&first|) {419 ui.focus_node(::Some(first), true);420 }421}422423pub fn form_errors(self ui: &Ui, form: Form) -> Vector<FormError> {424 var found = Vector<FormError>::empty();425 for (form.fields.peek(&ui).slots.view()) |&slot| {426 if (427 slot.counted(&ui)428 && slot.problem(&ui) is ::Some |move why|429 && slot.element is ::Some |e|430 ) {431 found.push(FormError { .label = copy slot.label, .message = move why, .element = e });432 }433 }434 if (found.length() < 2) {435 return move found;436 }437 // in Tab order: each where the first element taking the focus in it438 // comes, those taking none after, as made439 const order = ui.tab_order();440 var ranks = Vector<u64>::empty();441 for (found.view()) |&e| {442 var rank = order.length();443 for (order.view(), [..order.length()]) |index, k| {444 if (ui.within(index, e.element.index)) {445 rank = k;446 break;447 }448 }449 ranks.push(rank);450 }451 var sorted = Vector<FormError>::with_capacity(found.length());452 var taken = Vector<bool>::filled(false, found.length());453 for ([..found.length()]) |n| {454 var best = found.length();455 for ([..found.length()]) |k| {456 if (!taken.get(k) && (best == found.length() || ranks.get(k) < ranks.get(best))) {457 best = k;458 }459 }460 taken.set(best, true);461 sorted.push(copy found.get(best));462 }463 return move sorted;464}465466pub fn reset_form(self ui: &var Ui, form: Form) {467 if (form.tried.peek(&ui)) {468 form.tried.set(&var ui, false);469 }470 if (form.failure.peek(&ui).length() > 0) {471 form.failure.set(&var ui, String::empty());472 }473 var states = Vector<Signal<FieldState>>::empty();474 for (form.fields.peek(&ui).slots.view()) |&slot| {475 if (slot.alive(&ui)) {476 states.push(slot.state);477 }478 }479 for (states.view()) |state| {480 if (state.peek(&ui) != FieldState {}) {481 state.set(&var ui, FieldState {});482 }483 }484}485486// A text field took the focus or lost it: a field left with its text487// changed since it came shows its error from now on.488fn field_focused(ui: &var Ui, element: u32, gained: bool) {489 var forms = Vector<Form>::empty();490 for (ui.forms_state().forms.view()) |form| {491 if (ui.signal_alive(form.fields.index, form.fields.generation)) {492 forms.push(form);493 }494 }495 ui.forms_state().forms = copy forms;496 for (forms.view()) |form| {497 const count = form.fields.peek(&ui).slots.length();498 for ([..count]) |k| {499 const slot = &form.fields.peek(&ui).slots.get(k);500 if (!slot.alive(&ui) || slot.element.index() != ::Some(element)) {501 continue;502 }503 var now = copy slot.text.peek(&ui);504 const state = slot.state;505 const field = &var form.fields.peek_var(&var ui).slots.get_var(k);506 if (gained) {507 field.entered = ::Some(move now);508 continue;509 }510 var changed = false;511 if (field.entered is ::Some |&was|) {512 changed = was != now;513 }514 field.entered = ::None;515 if (changed && !state.peek(&ui).left) {516 state.update(&var ui, (s) => s.left = true);517 }518 }519 }520}521522/* --- Showing fields --- */523524pub fn make_text_field(self ui: &var Ui, form: Form, index: u32, look: TextField) -> Element {525 var label = copy ui.slot_at(form, index).label;526 const element = ui.bind(|move look, move label, form, index| (ui: &Ui) -> TextField {527 const slot = &ui.slot_at(form, index);528 var options = copy look;529 options.text = copy slot.text.get(&ui);530 options.error = ui.shown_error(form, index);531 options.description = copy slot.hint;532 options.required = slot.required;533 if (options.accessible.length() == 0) {534 options.accessible = copy label;535 }536 options.on_change = (ui, text) => ui.edit_field(form, index, move text);537 if (!options.multiline) {538 options.on_submit = (ui) => ui.submit_form(form);539 }540 return move options;541 });542 ui.record_field(form, index, element);543 return element;544}545546pub fn make_labelled(self ui: &var Ui, form: Form, index: u32, input: Element) -> Element {547 const slot = &ui.slot_at(form, index);548 var label = copy slot.label;549 var hint = copy slot.hint;550 const required = slot.required;551 // a checkbox shows its own label552 var own = false;553 if (ui.node(input.index).widget is ::Some |&widget|) {554 own = widget.semantics().role is ::CheckBox;555 }556 var children = Vector<Element>::empty();557 if (!own) {558 const name = ui.add(Text { .text = move label, .weight = SEMIBOLD, .size = ::Some(13.0) });559 if (required) {560 children.push(name);561 } else {562 children.push(ui.add(Row {563 .gap = 4.0,564 .children = &[565 name,566 ui.add(Text {567 .text = ui.optional_word(),568 .size = ::Some(13.0),569 .color = Ink::Muted570 }),571 ],572 }));573 }574 }575 if (hint.length() > 0) {576 children.push(ui.add(Text {577 .text = move hint,578 .size = ::Some(13.0),579 .color = Ink::Muted580 }));581 }582 children.push(input);583 children.push(ui.show((ui) => ui.shown_error(form, index).length() > 0, (ui) => ui.transition(ui.bind((ui) => Text {584 .text = ui.shown_error(form, index),585 .size = ::Some(13.0),586 .color = Ink::Danger,587 }), Transition { .reveal = true })));588 return ui.add(Column { .gap = 5.0, .align = Alignment::Stretch, .children = &children.view() });589}590591// The summary's panel: a group to screen readers, named by its title.592pub type SummaryPanel : Widget = struct {593 pub label: String,594 pub children: &[Element] = &[],595};596597pub fn layout(self p: &var SummaryPanel, arrange: &var Arrange, limits: Limits) -> Extent {598 const size = arrange.lay_out(0, limits);599 arrange.place(0, Point { .x = 0.0, .y = 0.0 });600 return limits.constrain(size);601}602603pub fn paint(self p: &SummaryPanel, look: &Look, paint: &var Paint) {}604605pub fn children(self p: &SummaryPanel) -> &[Element] => &p.children;606607pub fn renew(self p: &var SummaryPanel, next: SummaryPanel) -> Change => Change::Nothing;608609pub fn semantics(self p: &SummaryPanel) -> Semantics => Semantics {610 .role = Role::Group,611 .label = copy p.label612};613614pub fn make_summary(self ui: &var Ui, form: Form) -> Element {615 return ui.show((ui) => form.tried.get(&ui) && (616 form.failure.get(&ui).length() > 0 || ui.form_errors(form).length() > 0617 ), (ui) => ui.transition(618 ui.switch(619 (ui) => summary_key(&ui, form),620 (ui, key) => summary_panel(&var ui, form),621 Keep::None622 ),623 Transition { .reveal = true }624 ));625}626627// What the summary shows, which makes it again when it changes.628fn summary_key(ui: &Ui, form: Form) -> String {629 var key = copy form.failure.get(&ui);630 for (ui.form_errors(form).view()) |&e| {631 key.push(0);632 key.append(&e.label.view());633 key.push(0);634 key.append(&e.message.view());635 }636 return move key;637}638639fn summary_panel(ui: &var Ui, form: Form) -> Element {640 var title = ui.summary_message(0);641 var lines = Vector<Element>::empty();642 lines.push(ui.add(Text { .text = copy title, .weight = SEMIBOLD, .color = Ink::Danger }));643 var failure = copy form.failure.peek(&ui);644 if (failure.length() > 0) {645 lines.push(ui.add(Text::from(move failure)));646 }647 for (ui.form_errors(form).view()) |&e| {648 const element = e.element;649 lines.push(ui.add(Button {650 .label = f"{e.label}: {e.message}",651 .variant = ButtonVariant::Plain,652 .padding = Padding::symmetric(0.0, 2.0),653 .on_press = (ui) => ui.focus_field(element),654 }));655 }656 return ui.add(SummaryPanel {657 .label = move title,658 .children = &[ui.add(Column {659 .gap = 6.0,660 .padding = Padding::symmetric(16.0, 12.0),661 .background = Ink::Surface,662 .border = Ink::Danger,663 .radius = 8.0,664 .align = Alignment::Start,665 .children = &lines.view(),666 })],667 });668}669670/* --- Rules --- */671672pub fn length_rule(least: u64, most: u64) -> Rule<String> {673 return |least, most| (ui: &Ui, text: &String) -> Option<String> {674 const now = typeset::grapheme_count(&text.view().trim());675 if (now < least || now > most) {676 return ::Some(ui.length_message(least, most, now));677 }678 return ::None;679 };680}681682pub fn email_rule() -> Rule<String> {683 return (ui: &Ui, text: &String) -> Option<String> {684 if (valid_email(&text.view().trim())) {685 return ::None;686 }687 return ::Some(ui.email_message());688 };689}690691// WHATWG's valid email address: a local part of letters, digits and692// .!#$%&'*+/=?^_`{|}~-, an @, and labels of letters, digits and inner693// hyphens, at most 63 long; here with at least two labels.694pub fn valid_email(text: &[u8]) -> bool {695 const at = if (text.find_byte('@', 0) is ::Some |n|) n else {696 return false;697 };698 if (at == 0) {699 return false;700 }701 for (text[..at]) |c| {702 if (!is_alphanumeric(c) && !((&".!#$%&'*+/=?^_`{|}~-").find_byte(c, 0) is ::Some)) {703 return false;704 }705 }706 const domain = &text[at + 1..];707 var labels: u64 = 0;708 var start: u64 = 0;709 while (start <= domain.length()) {710 var end = start;711 while (end < domain.length() && domain[end] != '.') {712 end += 1;713 }714 const label = &domain[start..end];715 if (label.length() == 0 || label.length() > 63) {716 return false;717 }718 if (label[0] == '-' || label[label.length() - 1] == '-') {719 return false;720 }721 for (label) |c| {722 if (!is_alphanumeric(c) && c != '-') {723 return false;724 }725 }726 labels += 1;727 start = end + 1;728 }729 return labels >= 2;730}731732fn is_alphanumeric(c: u8) -> bool => is_letter(c) || is_digit(c);733734fn is_letter(c: u8) -> bool => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');735736fn is_digit(c: u8) -> bool => c >= '0' && c <= '9';737738pub fn shape_rule(shape: &[u8], like: &[u8]) -> Rule<String> {739 var wanted = String::from(&shape);740 var example = String::from(&like);741 return |move wanted, move example| (ui: &Ui, text: &String) -> Option<String> {742 if (fits_shape(&text.view().trim(), &wanted.view())) {743 return ::None;744 }745 return ::Some(ui.shape_message(&example.view()));746 };747}748749// Whether the text is written in the shape: 9 a digit, A a letter, * either.750pub fn fits_shape(text: &[u8], shape: &[u8]) -> bool {751 if (text.length() != shape.length()) {752 return false;753 }754 for (text, shape) |c, s| {755 const fits = match (s) {756 '9' is_digit(c);757 'A' is_letter(c);758 '*' is_alphanumeric(c);759 else c == s;760 };761 if (!fits) {762 return false;763 }764 }765 return true;766}767768pub fn said_rule<T>(rule: &Rule<T>, message: &[u8]) -> Rule<T> {769 var checks = copy rule;770 var said = String::from(&message);771 return |move checks, move said| (ui: &Ui, value: &T) -> Option<String> {772 if (checks(&ui, &value) is ::Some) {773 return ::Some(copy said);774 }775 return ::None;776 };777}778779/* --- Messages --- */780781pub fn required_message(self ui: &Ui, wanted: Wanted) -> String {782 if (ui.messages() is ::Some |&m|) {783 return m.required(&ui, wanted);784 }785 return english_required(&ui, wanted);786}787788fn length_message(self ui: &Ui, least: u64, most: u64, now: u64) -> String {789 if (ui.messages() is ::Some |&m|) {790 return m.length(&ui, least, most, now);791 }792 return english_length(&ui, least, most, now);793}794795fn email_message(self ui: &Ui) -> String {796 if (ui.messages() is ::Some |&m|) {797 return m.email(&ui);798 }799 return english_email(&ui);800}801802fn shape_message(self ui: &Ui, like: &[u8]) -> String {803 if (ui.messages() is ::Some |&m|) {804 return m.shape(&ui, &like);805 }806 return english_shape(&ui, &like);807}808809fn optional_word(self ui: &Ui) -> String {810 if (ui.messages() is ::Some |&m|) {811 return m.optional(&ui);812 }813 return english_optional(&ui);814}815816fn summary_message(self ui: &Ui, count: u64) -> String {817 if (ui.messages() is ::Some |&m|) {818 return m.summary(&ui, count);819 }820 return english_summary(&ui, count);821}822823pub fn english_required(ui: &Ui, wanted: Wanted) -> String => String::from(match (wanted) {824 ::Text &"Fill in this field.";825 ::Pick &"Choose one.";826 ::Check &"Check this box to go on.";827});828829pub fn english_length(ui: &Ui, least: u64, most: u64, now: u64) -> String {830 if (now < least) {831 return f"Use at least {least} {characters(least)} (now {now}).";832 }833 return f"Use at most {most} {characters(most)} (now {now}).";834}835836fn characters(n: u64) -> &[u8] => if (n == 1) &"character" else &"characters";837838pub fn english_email(ui: &Ui) -> String => String::from(839 &"Enter an email address, like [email protected]."840);841842pub fn english_shape(ui: &Ui, like: &[u8]) -> String => f"Write it like {like}.";843844pub fn english_optional(ui: &Ui) -> String => String::from(&"(optional)");845846pub fn english_summary(ui: &Ui, count: u64) -> String {847 if (count == 0) {848 return String::from(&"There is a problem");849 }850 if (count == 1) {851 return String::from(&"1 field needs attention");852 }853 return f"{count} fields need attention";854}855856pub fn english_integer(ui: &Ui) -> String => String::from(&"Enter a whole number.");857858pub fn english_number(ui: &Ui) -> String {859 var example = String::empty();860 ui.locale().format_number(2.5, 1, &var example);861 return f"Enter a number, like {example}.";862}863864pub fn english_between(ui: &Ui, least: f64, most: f64) -> String {865 const locale = ui.locale();866 return f"Enter a number from {written(&locale, least)} to {written(&locale, most)}.";867}868869// The number in the locale, with as many decimals as it needs, up to six.870pub fn written(locale: &Locale, value: f64) -> String {871 var fraction: u8 = 0;872 var scaled = value;873 while (fraction < 6 && scaled != floor(scaled)) {874 fraction += 1;875 scaled = scaled * 10.0;876 }877 var out = String::empty();878 locale.format_number(value, fraction, &var out);879 return move out;880}881882pub fn english_date(ui: &Ui, day: &Date) -> String {883 var shown = String::empty();884 ui.locale().format_date(&day, &DateFormat { .month = Width::Numeric }, &var shown);885 return f"Enter a date, like {shown}.";886}887888pub fn english_time(ui: &Ui, time: &TimeOfDay) -> String {889 return f"Enter a time, like {time_label(&ui.locale(), &time)}.";890}891892/* --- Typed values (F13b) --- */893894pub fn integer_parser() -> Parser<i64> {895 return (ui: &Ui, text: &[u8]) -> std_result::Result<i64, String> {896 if (read_integer(&text.trim()) is ::Some |n|) {897 return ::Ok(n);898 }899 return ::Err(ui.integer_message());900 };901}902903// The whole number the text writes in ASCII digits or those of another904// script (Arabic-Indic, Devanagari, ...), its sign `-`, `−` or `+`, no905// groups.906pub fn read_integer(text: &[u8]) -> Option<i64> {907 var ascii = String::empty();908 var at: u64 = 0;909 if (text.starts_with(&"\u{2212}")) {910 ascii.push('-');911 at = 3;912 }913 while (at < text.length()) {914 const c = text[at];915 if (c < 0x80) {916 ascii.push(c);917 at += 1;918 continue;919 }920 var end = at + 1;921 while (end < text.length() && (text[end] & 0xC0) == 0x80) {922 end += 1;923 }924 const digit = if (script_digit(decode_char(&text[at..end])) is ::Some |d|) d else {925 return ::None;926 };927 ascii.push('0' + digit);928 at = end;929 }930 return ascii.view().parse_integer();931}932933// The zeros of the scripts' decimal digits, nine more following each.934const ZEROS: [u32 : 17] = [935 0x660, 0x6F0, 0x7C0, 0x966, 0x9E6, 0xA66, 0xAE6, 0xB66, 0xBE6, 0xC66, 0xCE6, 0xD66, 0xE50,936 0xED0, 0x1040, 0x17E0, 0xFF10937];938939fn script_digit(c: u32) -> Option<u8> {940 for (ZEROS) |zero| {941 if (c >= zero && c < zero + 10) {942 return ::Some((c - zero) to u8);943 }944 }945 return ::None;946}947948fn decode_char(bytes: &[u8]) -> u32 {949 const lead = bytes[0] to u32;950 var c = if (lead >= 0xF0) lead & 7 else if (lead >= 0xE0) lead & 15 else lead & 31;951 for (bytes[1..]) |b| {952 c = c << 6 | (b & 63) to u32;953 }954 return c;955}956957pub fn number_parser() -> Parser<f64> {958 return (ui: &Ui, text: &[u8]) -> std_result::Result<f64, String> {959 if (ui.locale().parse_number(&text) is ::Some |n|) {960 return ::Ok(n);961 }962 return ::Err(ui.number_message());963 };964}965966pub fn date_parser() -> Parser<Date> {967 return (ui: &Ui, text: &[u8]) -> std_result::Result<Date, String> {968 if (ui.locale().parse_date(&text) is ::Some |d|) {969 return ::Ok(d);970 }971 return ::Err(ui.date_message(&ui.today()));972 };973}974975pub fn time_parser() -> Parser<TimeOfDay> {976 return (ui: &Ui, text: &[u8]) -> std_result::Result<TimeOfDay, String> {977 if (ui.locale().parse_time(&text) is ::Some |t|) {978 return ::Ok(t);979 }980 return ::Err(ui.time_message(&TimeOfDay::of(14, 30)));981 };982}983984pub fn between_rule<T: Number>(least: T, most: T) -> Rule<T> {985 return |move least, move most| (ui: &Ui, value: &T) -> Option<String> {986 if (value < least || value > most) {987 return ::Some(ui.between_message(least to f64, most to f64));988 }989 return ::None;990 };991}992993fn integer_message(self ui: &Ui) -> String {994 if (ui.messages() is ::Some |&m|) {995 return m.integer(&ui);996 }997 return english_integer(&ui);998}9991000fn number_message(self ui: &Ui) -> String {1001 if (ui.messages() is ::Some |&m|) {1002 return m.number(&ui);1003 }1004 return english_number(&ui);1005}10061007fn date_message(self ui: &Ui, example: &Date) -> String {1008 if (ui.messages() is ::Some |&m|) {1009 return m.date(&ui, &example);1010 }1011 return english_date(&ui, &example);1012}10131014fn time_message(self ui: &Ui, example: &TimeOfDay) -> String {1015 if (ui.messages() is ::Some |&m|) {1016 return m.time(&ui, &example);1017 }1018 return english_time(&ui, &example);1019}10201021fn between_message(self ui: &Ui, least: f64, most: f64) -> String {1022 if (ui.messages() is ::Some |&m|) {1023 return m.between(&ui, least, most);1024 }1025 return english_between(&ui, least, most);1026}