utils.mjs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import {
  2. isObject,
  3. isPromise,
  4. isFunction,
  5. getRootScrollTop,
  6. setRootScrollTop
  7. } from "../utils/index.mjs";
  8. function isEmptyValue(value) {
  9. if (Array.isArray(value)) {
  10. return !value.length;
  11. }
  12. if (value === 0) {
  13. return false;
  14. }
  15. return !value;
  16. }
  17. function runSyncRule(value, rule) {
  18. if (isEmptyValue(value)) {
  19. if (rule.required) {
  20. return false;
  21. }
  22. if (rule.validateEmpty === false) {
  23. return true;
  24. }
  25. }
  26. if (rule.pattern && !rule.pattern.test(String(value))) {
  27. return false;
  28. }
  29. return true;
  30. }
  31. function runRuleValidator(value, rule) {
  32. return new Promise((resolve) => {
  33. const returnVal = rule.validator(value, rule);
  34. if (isPromise(returnVal)) {
  35. returnVal.then(resolve);
  36. return;
  37. }
  38. resolve(returnVal);
  39. });
  40. }
  41. function getRuleMessage(value, rule) {
  42. const { message } = rule;
  43. if (isFunction(message)) {
  44. return message(value, rule);
  45. }
  46. return message || "";
  47. }
  48. function startComposing({ target }) {
  49. target.composing = true;
  50. }
  51. function endComposing({ target }) {
  52. if (target.composing) {
  53. target.composing = false;
  54. target.dispatchEvent(new Event("input"));
  55. }
  56. }
  57. function resizeTextarea(input, autosize) {
  58. const scrollTop = getRootScrollTop();
  59. input.style.height = "auto";
  60. let height = input.scrollHeight;
  61. if (isObject(autosize)) {
  62. const { maxHeight, minHeight } = autosize;
  63. if (maxHeight !== void 0) {
  64. height = Math.min(height, maxHeight);
  65. }
  66. if (minHeight !== void 0) {
  67. height = Math.max(height, minHeight);
  68. }
  69. }
  70. if (height) {
  71. input.style.height = `${height}px`;
  72. setRootScrollTop(scrollTop);
  73. }
  74. }
  75. function mapInputType(type, inputmode) {
  76. if (type === "number") {
  77. type = "text";
  78. inputmode != null ? inputmode : inputmode = "decimal";
  79. }
  80. if (type === "digit") {
  81. type = "tel";
  82. inputmode != null ? inputmode : inputmode = "numeric";
  83. }
  84. return { type, inputmode };
  85. }
  86. function getStringLength(str) {
  87. return [...str].length;
  88. }
  89. function cutString(str, maxlength) {
  90. return [...str].slice(0, maxlength).join("");
  91. }
  92. export {
  93. cutString,
  94. endComposing,
  95. getRuleMessage,
  96. getStringLength,
  97. isEmptyValue,
  98. mapInputType,
  99. resizeTextarea,
  100. runRuleValidator,
  101. runSyncRule,
  102. startComposing
  103. };