rob-revisited/ide/ui/js/symfony-forms-model.js

195 lines
15 KiB
JavaScript

// The Symfony Forms window's knowledge (ide/ui/js/symfony-forms.js): Symfony's form types with the options each one
// takes (by kind: text, yes / no, a choice, a map, a class, a form type, constraints, PHP code), the validator's
// constraints with their options and default messages, the form events and the form themes. Pure: the HTML preview
// (symfony-forms-preview.js) and node --test use it too.
// A value of the model is a scalar, a list, a map, or {'@class': fqcn} (X::class), {'@new': fqcn, args: {...}} (a
// constraint), {'@php': code} (kept as written): ide/src/Symfony/FormValues.php.
export const CORE = 'Symfony\\Component\\Form\\Extension\\Core\\Type\\';
export const ENTITY_TYPE = 'Symfony\\Bridge\\Doctrine\\Form\\Type\\EntityType';
export const CONSTRAINTS = 'Symfony\\Component\\Validator\\Constraints\\';
/** the short name of a class */
export const shortName = (fqcn) => String(fqcn || '').split('\\').pop();
/** Symfony's humanize(): firstName -> "First name" (the default label of a field) */
export function humanize(text) {
const s = String(text).replace(/([A-Z])/g, '_$1').replace(/[_\s]+/g, ' ').trim().toLowerCase();
return s.charAt(0).toUpperCase() + s.slice(1);
}
/** Symfony's block prefix of a form type: App\Form\UserProfileType -> user_profile (the form's name, ids, field names) */
export function blockPrefix(fqcn) {
const name = shortName(fqcn).replace(/Type$/i, '') || 'form';
return name.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2').replace(/([a-z\d])([A-Z])/g, '$1_$2').toLowerCase();
}
const COMMON = ['label', 'required', 'help', 'attr', 'row_attr', 'constraints', 'mapped', 'disabled', 'empty_data', 'data', 'label_attr'];
const BUTTON = ['label', 'attr', 'disabled', 'validation_groups'];
const CHOICES = ['expanded', 'multiple', 'placeholder', 'preferred_choices'];
const DATES = ['widget', 'input', 'html5', 'format'];
/** Symfony's form types: [short name, group, options of their own] (the common ones are added) */
const TYPE_LIST = [
['TextType', 'Text', []], ['TextareaType', 'Text', []], ['EmailType', 'Text', []], ['PasswordType', 'Text', ['always_empty']],
['UrlType', 'Text', ['default_protocol']], ['TelType', 'Text', []], ['SearchType', 'Text', []], ['ColorType', 'Text', ['html5']],
['IntegerType', 'Numbers', []], ['NumberType', 'Numbers', ['scale', 'html5', 'input']], ['MoneyType', 'Numbers', ['currency', 'divisor', 'scale', 'html5']],
['PercentType', 'Numbers', ['scale', 'type', 'symbol']], ['RangeType', 'Numbers', []],
['ChoiceType', 'Choices', ['choices', ...CHOICES, 'choice_label']], ['EnumType', 'Choices', ['class', ...CHOICES, 'choice_label']],
['EntityType', 'Choices', ['class', 'choice_label', 'query_builder', ...CHOICES, 'by_reference']],
['CountryType', 'Choices', CHOICES], ['LanguageType', 'Choices', CHOICES], ['LocaleType', 'Choices', CHOICES], ['CurrencyType', 'Choices', CHOICES], ['TimezoneType', 'Choices', CHOICES],
['DateType', 'Dates', DATES], ['DateTimeType', 'Dates', DATES], ['TimeType', 'Dates', ['widget', 'input', 'html5', 'with_seconds']], ['BirthdayType', 'Dates', DATES],
['WeekType', 'Dates', ['widget', 'input']], ['DateIntervalType', 'Dates', ['widget', 'input']],
['CheckboxType', 'Other', []], ['RadioType', 'Other', []], ['FileType', 'Other', ['multiple']], ['HiddenType', 'Other', []],
['CollectionType', 'Other', ['entry_type', 'entry_options', 'allow_add', 'allow_delete', 'by_reference', 'prototype', 'prototype_name', 'delete_empty']],
['RepeatedType', 'Other', ['type', 'invalid_message', 'first_options', 'second_options', 'options']], ['UuidType', 'Other', []], ['UlidType', 'Other', []],
['SubmitType', 'Buttons', []], ['ResetType', 'Buttons', []], ['ButtonType', 'Buttons', []],
];
export const TYPES = TYPE_LIST.map(([name, group, own]) => ({
name, group, fqcn: name === 'EntityType' ? ENTITY_TYPE : CORE + name,
options: group === 'Buttons' ? BUTTON : [...COMMON.slice(0, 6), ...own, ...COMMON.slice(6)],
}));
export const GROUPS = ['Text', 'Numbers', 'Choices', 'Dates', 'Other', 'Buttons'];
/** a type by its class (or null: the project's own form types, a sub-form) */
export const typeOf = (fqcn) => TYPES.find((t) => t.fqcn.toLowerCase() === String(fqcn || '').replace(/^\\/, '').toLowerCase()) || null;
/** the options a sub-form (a project's form type) takes */
export const SUBFORM_OPTIONS = ['label', 'required', 'help', 'attr', 'row_attr', 'constraints', 'mapped', 'by_reference', 'inherit_data', 'data_class', 'label_attr'];
/** the options a field of this type shows (none: a field without type, Symfony guesses it) */
export function optionsOf(type) {
if (!type) return COMMON;
return typeOf(type)?.options || SUBFORM_OPTIONS;
}
/**
* How each option is edited: text, bool (yes / no / not set), int, number, select (values), map (key -> text),
* list (texts), choices (label -> value), class (entity | enum | any), type (a form type), code (PHP), constraints.
*/
export const OPTIONS = {
label: { kind: 'label' }, required: { kind: 'bool', def: true }, help: { kind: 'text' }, attr: { kind: 'map', keys: ['placeholder', 'class', 'autocomplete', 'rows', 'min', 'max', 'step'] },
row_attr: { kind: 'map', keys: ['class'] }, label_attr: { kind: 'map', keys: ['class'] }, constraints: { kind: 'constraints' }, mapped: { kind: 'bool', def: true },
disabled: { kind: 'bool', def: false }, empty_data: { kind: 'text' }, data: { kind: 'code' }, validation_groups: { kind: 'list' },
always_empty: { kind: 'bool', def: true }, default_protocol: { kind: 'text' }, html5: { kind: 'bool' }, scale: { kind: 'int' }, input: { kind: 'select', values: ['datetime', 'datetime_immutable', 'string', 'timestamp', 'array', 'number'] },
currency: { kind: 'text', placeholder: 'EUR' }, divisor: { kind: 'int' }, type: { kind: 'type' }, symbol: { kind: 'text' },
choices: { kind: 'choices' }, expanded: { kind: 'bool', def: false }, multiple: { kind: 'bool', def: false }, placeholder: { kind: 'text' }, preferred_choices: { kind: 'list' },
choice_label: { kind: 'text' }, class: { kind: 'class' }, query_builder: { kind: 'code', sample: "fn (EntityRepository $er) => $er->createQueryBuilder('e')->orderBy('e.id', 'ASC')", uses: ['Doctrine\\ORM\\EntityRepository'] },
by_reference: { kind: 'bool', def: true }, widget: { kind: 'select', values: ['single_text', 'choice', 'text'] }, format: { kind: 'text' }, with_seconds: { kind: 'bool', def: false },
entry_type: { kind: 'type' }, entry_options: { kind: 'map', keys: ['label', 'attr'] }, allow_add: { kind: 'bool', def: false }, allow_delete: { kind: 'bool', def: false },
prototype: { kind: 'bool', def: true }, prototype_name: { kind: 'text', placeholder: '__name__' }, delete_empty: { kind: 'bool', def: false },
invalid_message: { kind: 'text' }, first_options: { kind: 'map', keys: ['label'] }, second_options: { kind: 'map', keys: ['label'] }, options: { kind: 'map', keys: ['attr'] },
inherit_data: { kind: 'bool', def: false }, data_class: { kind: 'class' },
};
// the RepeatedType's 'type' is a form type; PercentType's 'type' is fractional / integer
export const PERCENT_TYPE = { kind: 'select', values: ['fractional', 'integer'] };
/** the validator's constraints: [name, its options (name: kind), default message] */
const CONSTRAINT_LIST = [
['NotBlank', { message: 'text', allowNull: 'bool' }, 'This value should not be blank.'],
['NotNull', { message: 'text' }, 'This value should not be null.'],
['Length', { min: 'int', max: 'int', minMessage: 'text', maxMessage: 'text' }, 'This value is too short. It should have {{ limit }} characters or more.'],
['Email', { message: 'text', mode: 'select:html5,html5-allow-no-tld,strict' }, 'This value is not a valid email address.'],
['Url', { message: 'text', requireTld: 'bool' }, 'This value is not a valid URL.'],
['Regex', { pattern: 'text', message: 'text', match: 'bool' }, 'This value is not valid.'],
['Range', { min: 'number', max: 'number', notInRangeMessage: 'text' }, 'This value should be between {{ min }} and {{ max }}.'],
['Positive', { message: 'text' }, 'This value should be positive.'],
['PositiveOrZero', { message: 'text' }, 'This value should be either positive or zero.'],
['Negative', { message: 'text' }, 'This value should be negative.'],
['GreaterThan', { value: 'number', message: 'text' }, 'This value should be greater than {{ compared_value }}.'],
['GreaterThanOrEqual', { value: 'number', message: 'text' }, 'This value should be greater than or equal to {{ compared_value }}.'],
['LessThan', { value: 'number', message: 'text' }, 'This value should be less than {{ compared_value }}.'],
['LessThanOrEqual', { value: 'number', message: 'text' }, 'This value should be less than or equal to {{ compared_value }}.'],
['EqualTo', { value: 'text', message: 'text' }, 'This value should be equal to {{ compared_value }}.'],
['IsTrue', { message: 'text' }, 'This value should be true.'],
['IsFalse', { message: 'text' }, 'This value should be false.'],
['Choice', { choices: 'list', multiple: 'bool', message: 'text' }, 'The value you selected is not a valid choice.'],
['Count', { min: 'int', max: 'int' }, 'This collection should contain {{ limit }} elements or more.'],
['File', { maxSize: 'text', mimeTypes: 'list', maxSizeMessage: 'text', mimeTypesMessage: 'text' }, 'The file is too large.'],
['Image', { maxSize: 'text', minWidth: 'int', maxWidth: 'int', minHeight: 'int', maxHeight: 'int' }, 'This file is not a valid image.'],
['Date', { message: 'text' }, 'This value is not a valid date.'],
['DateTime', { format: 'text', message: 'text' }, 'This value is not a valid datetime.'],
['Time', { message: 'text' }, 'This value is not a valid time.'],
['Uuid', { message: 'text' }, 'This is not a valid UUID.'],
['Json', { message: 'text' }, 'This value should be valid JSON.'],
['Iban', { message: 'text' }, 'This is not a valid International Bank Account Number (IBAN).'],
['Bic', { message: 'text' }, 'This is not a valid Business Identifier Code (BIC).'],
['Isbn', { type: 'select:isbn10,isbn13', message: 'text' }, 'This value is neither a valid ISBN-10 nor a valid ISBN-13.'],
['CardScheme', { schemes: 'list', message: 'text' }, 'Unsupported card type or invalid card number.'],
['Luhn', { message: 'text' }, 'Invalid card number.'],
['Country', { message: 'text' }, 'This value is not a valid country.'],
['Language', { message: 'text' }, 'This value is not a valid language.'],
['Currency', { message: 'text' }, 'This value is not a valid currency.'],
['Timezone', { message: 'text' }, 'This value is not a valid timezone.'],
['Hostname', { message: 'text' }, 'This value is not a valid hostname.'],
['Ip', { version: 'select:4,6,all', message: 'text' }, 'This is not a valid IP address.'],
['CssColor', { message: 'text' }, 'This value is not a valid CSS color.'],
['PasswordStrength', { minScore: 'int', message: 'text' }, 'The password strength is too low. Please use a stronger password.'],
['NotCompromisedPassword', { message: 'text' }, 'This password has been leaked in a data breach, it must not be used. Please use another password.'],
['Type', { type: 'text', message: 'text' }, 'This value should be of type {{ type }}.'],
['Expression', { expression: 'text', message: 'text' }, 'This value is not valid.'],
['Valid', {}, ''],
];
export const CONSTRAINT_TYPES = CONSTRAINT_LIST.map(([name, options, message]) => ({ name, fqcn: CONSTRAINTS + name, options, message }));
export const constraintOf = (fqcn) => CONSTRAINT_TYPES.find((c) => c.fqcn.toLowerCase() === String(fqcn || '').replace(/^\\/, '').toLowerCase()) || null;
/** the message a constraint shows (its own 'message', else Symfony's, its {{ limit }}... filled) */
export function constraintMessage(c) {
const known = constraintOf(c?.['@new']);
const args = c?.args && typeof c.args === 'object' ? c.args : {};
let msg = (typeof args.message === 'string' && args.message) || known?.message || 'This value is not valid.';
if (known?.name === 'Length' && args.min === undefined && args.max !== undefined) msg = 'This value is too long. It should have {{ limit }} characters or less.';
const limit = args.min ?? args.max ?? args.limit;
return msg.replace(/\{\{ limit \}\}/g, limit ?? '…').replace(/\{\{ min \}\}/g, args.min ?? '…').replace(/\{\{ max \}\}/g, args.max ?? '…')
.replace(/\{\{ compared_value \}\}/g, args.value ?? '…').replace(/\{\{ type \}\}/g, args.type ?? '…');
}
export const EVENTS = ['PRE_SET_DATA', 'POST_SET_DATA', 'PRE_SUBMIT', 'SUBMIT', 'POST_SUBMIT'];
/** what each event is for (shown under it) */
export const EVENT_HELP = {
PRE_SET_DATA: 'Before the data is put in the form: add or remove fields from the data (edit vs new).',
POST_SET_DATA: 'After the data is in the form.',
PRE_SUBMIT: 'Before the request\'s values are used: change what was sent (normalize, add a dependent field).',
SUBMIT: 'The values are normalized, not yet in the object.',
POST_SUBMIT: 'After the values are in the object: check or react (dependent fields of a parent).',
};
/** onPreSetData for PRE_SET_DATA */
export const listenerName = (event) => 'on' + String(event).toLowerCase().split('_').map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join('');
/** Symfony's form themes (twig.yaml form_themes / {% form_theme %}) */
export const THEMES = ['form_div_layout.html.twig', 'form_table_layout.html.twig', 'bootstrap_5_layout.html.twig', 'bootstrap_5_horizontal_layout.html.twig',
'bootstrap_4_layout.html.twig', 'bootstrap_4_horizontal_layout.html.twig', 'bootstrap_3_layout.html.twig', 'foundation_6_layout.html.twig', 'tailwind_2_layout.html.twig'];
/** how the preview draws a theme: bootstrap_5, tailwind_2, table or div (a project's own theme: the default one under it) */
export function rendererOf(themes) {
const list = (Array.isArray(themes) ? themes : [themes]).filter(Boolean).map(String);
for (const t of [...list].reverse()) {
if (/bootstrap_[345]/.test(t)) return 'bootstrap_5';
if (/tailwind/.test(t)) return 'tailwind_2';
if (/table_layout/.test(t)) return 'table';
}
return 'div';
}
/** a value shown as PHP code (what the writer writes; for display, the options the builder does not know) */
export function phpOf(v) {
if (v === null || v === undefined) return 'null';
if (typeof v === 'boolean') return v ? 'true' : 'false';
if (typeof v === 'number') return String(v);
if (typeof v === 'string') return "'" + v.replace(/\\/g, '\\\\').replace(/'/g, "\\'") + "'";
if (Array.isArray(v)) return '[' + v.map(phpOf).join(', ') + ']';
if (typeof v === 'object') {
if (typeof v['@class'] === 'string') return shortName(v['@class']) + '::class';
if (typeof v['@php'] === 'string') return v['@php'];
if (typeof v['@new'] === 'string') {
const args = v.args && typeof v.args === 'object' ? Object.entries(v.args).map(([k, x]) => (/^\d+$/.test(k) ? '' : k + ': ') + phpOf(x)) : [];
return 'new ' + shortName(v['@new']) + '(' + args.join(', ') + ')';
}
return '[' + Object.entries(v).map(([k, x]) => phpOf(k) + ' => ' + phpOf(x)).join(', ') + ']';
}
return String(v);
}
/** an empty map arrives from PHP as [] */
export const asMap = (v) => (v && typeof v === 'object' && !Array.isArray(v) ? v : {});