helpers.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { getOptionalValidationContext } from "@json-render/svelte";
  2. type ValidateOn = "change" | "blur" | "submit";
  3. type ValidationCheck = {
  4. type: string;
  5. message: string;
  6. args?: Record<string, unknown>;
  7. };
  8. export type ValidationCtx = ReturnType<typeof getOptionalValidationContext>;
  9. export function getPaginationRange(
  10. current: number,
  11. total: number,
  12. ): Array<number | "ellipsis"> {
  13. if (total <= 7) {
  14. return Array.from({ length: total }, (_, i) => i + 1);
  15. }
  16. const pages: Array<number | "ellipsis"> = [1];
  17. if (current > 3) pages.push("ellipsis");
  18. const start = Math.max(2, current - 1);
  19. const end = Math.min(total - 1, current + 1);
  20. for (let i = start; i <= end; i += 1) pages.push(i);
  21. if (current < total - 2) pages.push("ellipsis");
  22. pages.push(total);
  23. return pages;
  24. }
  25. export function createValidation(
  26. validation: ValidationCtx,
  27. path?: string,
  28. checks?: ValidationCheck[] | null,
  29. ) {
  30. const config = checks && checks.length > 0 ? { checks } : null;
  31. function register(validateOn: ValidateOn) {
  32. if (!validation || !path || !config) return;
  33. validation.registerField(path, {
  34. checks: config.checks,
  35. validateOn,
  36. });
  37. }
  38. function run(validateOn: ValidateOn): string[] {
  39. if (!validation || !path || !config) return [];
  40. const result = validation.validate(path, {
  41. checks: config.checks,
  42. validateOn,
  43. });
  44. return result.errors;
  45. }
  46. return {
  47. hasValidation: !!(validation && path && config),
  48. register,
  49. run,
  50. };
  51. }