@greatapps/common 1.1.174 → 1.1.176

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@greatapps/common",
3
- "version": "1.1.174",
3
+ "version": "1.1.176",
4
4
  "description": "Shared library for GreatApps frontend applications",
5
5
  "main": "./dist/index.mjs",
6
6
  "types": "./src/index.ts",
@@ -44,6 +44,7 @@
44
44
  "@radix-ui/react-switch": "^1.2.6",
45
45
  "@radix-ui/react-tabs": "^1.1.13",
46
46
  "@radix-ui/react-tooltip": "^1.2.8",
47
+ "@tabler/icons-react": "^3.40.0",
47
48
  "@tanstack/query-broadcast-client-experimental": "^5.95.2",
48
49
  "@tanstack/react-query-persist-client": "^5.95.2",
49
50
  "axios": "^1.13.6",
@@ -53,7 +54,7 @@
53
54
  "date-fns": "^4.1.0",
54
55
  "idb-keyval": "^6.2.2",
55
56
  "input-otp": "^1.4.2",
56
- "@tabler/icons-react": "^3.40.0",
57
+ "libphonenumber-js": "^1.12.40",
57
58
  "lucide-react": "^0.575.0",
58
59
  "react-day-picker": "^9.14.0",
59
60
  "server-only": "^0.0.1",
@@ -1,76 +1,79 @@
1
1
  'use client';
2
2
 
3
3
  import { useState, useCallback } from 'react';
4
- import { useForm } from 'react-hook-form';
5
- import { zodResolver } from '@hookform/resolvers/zod';
6
4
  import { toast } from 'sonner';
7
5
  import { Toast } from '../../ui/feedback/Toast';
8
- import { changePhoneSchema, type ChangePhoneFormData } from '../../../utils/validators/account';
9
- import { formatPhone } from '../../../utils/format/masks';
10
6
  import { requestPhoneChangeAction } from '../../../modules/accounts/actions/account-management.action';
11
- import { PHONE_COUNTRIES, type PhoneCountry } from '../../ui/form/PhoneInput';
7
+
8
+ function splitPhoneValue(fullValue: string): { ddi: string; local: string } {
9
+ const trimmed = fullValue.trim();
10
+ const spaceIdx = trimmed.indexOf(' ');
11
+ if (spaceIdx === -1) return { ddi: '+55', local: trimmed };
12
+ return { ddi: trimmed.slice(0, spaceIdx), local: trimmed.slice(spaceIdx + 1) };
13
+ }
12
14
 
13
15
  export default function useChangePhoneForm() {
14
16
  const [showVerification, setShowVerification] = useState(false);
15
- const [selectedCountry, setSelectedCountry] = useState<PhoneCountry>(PHONE_COUNTRIES[0]);
16
-
17
- const form = useForm<ChangePhoneFormData>({
18
- resolver: zodResolver(changePhoneSchema),
19
- mode: 'onChange',
20
- defaultValues: { phone: '' },
21
- });
17
+ const [phoneValue, setPhoneValue] = useState('');
18
+ const [phoneError, setPhoneError] = useState('');
19
+ const [isSubmitting, setIsSubmitting] = useState(false);
20
+ const [submittedPhone, setSubmittedPhone] = useState({ ddi: '+55', local: '' });
22
21
 
23
- const phoneValue = form.watch('phone');
24
- const errors = form.formState.errors;
25
- const isSubmitting = form.formState.isSubmitting;
22
+ const handlePhoneChange = useCallback((value: string) => {
23
+ setPhoneValue(value);
24
+ if (phoneError) setPhoneError('');
25
+ }, [phoneError]);
26
26
 
27
- const handlePhoneChange = useCallback(
28
- (e: React.ChangeEvent<HTMLInputElement>) => {
29
- const formatted = formatPhone(e.target.value);
30
- form.setValue('phone', formatted, { shouldValidate: true });
31
- },
32
- [form]
33
- );
34
-
35
- const handleCountryChange = useCallback((country: PhoneCountry) => {
36
- setSelectedCountry(country);
37
- }, []);
27
+ const handleContinue = useCallback(async (e: React.FormEvent) => {
28
+ e.preventDefault();
38
29
 
39
- const handleContinue = form.handleSubmit(async (data) => {
40
- const result = await requestPhoneChangeAction(data.phone, selectedCountry.code);
30
+ const { ddi, local } = splitPhoneValue(phoneValue);
41
31
 
42
- if (!result.success) {
43
- toast.custom((t) => (
44
- <Toast
45
- variant="error"
46
- message={result.error ?? 'Número já existente ou ocorreu um erro. Tente novamente mais tarde.'}
47
- toastId={t}
48
- />
49
- ));
32
+ if (!local || local.replace(/\D/g, '').length < 8) {
33
+ setPhoneError('Número de telefone inválido');
50
34
  return;
51
35
  }
52
36
 
53
- setShowVerification(true);
54
- });
37
+ setIsSubmitting(true);
38
+ try {
39
+ const result = await requestPhoneChangeAction(local, ddi);
40
+
41
+ if (!result.success) {
42
+ toast.custom((t) => (
43
+ <Toast
44
+ variant="error"
45
+ message={result.error ?? 'Número já existente ou ocorreu um erro. Tente novamente mais tarde.'}
46
+ toastId={t}
47
+ />
48
+ ));
49
+ return;
50
+ }
51
+
52
+ setSubmittedPhone({ ddi, local });
53
+ setShowVerification(true);
54
+ } finally {
55
+ setIsSubmitting(false);
56
+ }
57
+ }, [phoneValue]);
55
58
 
56
59
  const handleBack = useCallback(() => {
57
60
  setShowVerification(false);
58
61
  }, []);
59
62
 
60
63
  const resetForm = useCallback(() => {
61
- form.reset();
64
+ setPhoneValue('');
65
+ setPhoneError('');
66
+ setSubmittedPhone({ ddi: '+55', local: '' });
62
67
  setShowVerification(false);
63
- setSelectedCountry(PHONE_COUNTRIES[0]);
64
- }, [form]);
68
+ }, []);
65
69
 
66
70
  return {
67
71
  showVerification,
68
72
  phoneValue,
73
+ phoneError,
69
74
  isSubmitting,
70
- errors,
71
- selectedCountry,
75
+ submittedPhone,
72
76
  handlePhoneChange,
73
- handleCountryChange,
74
77
  handleContinue,
75
78
  handleBack,
76
79
  resetForm,
@@ -32,11 +32,10 @@ export function ChangePhoneModal({ open, onClose }: ChangePhoneModalProps) {
32
32
  const {
33
33
  showVerification,
34
34
  phoneValue,
35
+ phoneError,
35
36
  isSubmitting,
36
- errors,
37
- selectedCountry,
37
+ submittedPhone,
38
38
  handlePhoneChange,
39
- handleCountryChange,
40
39
  handleContinue,
41
40
  handleBack,
42
41
  resetForm,
@@ -63,12 +62,12 @@ export function ChangePhoneModal({ open, onClose }: ChangePhoneModalProps) {
63
62
  onSuccess: handleSuccess,
64
63
  successMessage: 'Telefone alterado',
65
64
  validateFn: async (token) => {
66
- const result = await confirmPhoneChangeAction(token, phoneValue, selectedCountry.code);
65
+ const result = await confirmPhoneChangeAction(token, submittedPhone.local, submittedPhone.ddi);
67
66
  return result.success;
68
67
  },
69
68
  resendFn: async () => {
70
69
  const { requestPhoneChangeAction } = await import('../../../modules/accounts/actions/account-management.action');
71
- const result = await requestPhoneChangeAction(phoneValue, selectedCountry.code);
70
+ const result = await requestPhoneChangeAction(submittedPhone.local, submittedPhone.ddi);
72
71
  if (!result.success) {
73
72
  throw new Error(result.error);
74
73
  }
@@ -211,10 +210,8 @@ export function ChangePhoneModal({ open, onClose }: ChangePhoneModalProps) {
211
210
  placeholder="(00) 0 0000-0000"
212
211
  value={phoneValue}
213
212
  onChange={handlePhoneChange}
214
- error={!!errors.phone}
215
- errorMessage={errors.phone?.message}
216
- selectedCountry={selectedCountry}
217
- onCountryChange={handleCountryChange}
213
+ error={!!phoneError}
214
+ errorMessage={phoneError}
218
215
  />
219
216
  </div>
220
217
 
@@ -233,12 +233,14 @@ export function MyProfileSection({ onClose, storageUrl }: MyProfileSectionProps)
233
233
  <div className="flex flex-col gap-4">
234
234
  <span className="paragraph-medium-semibold text-gray-600">Dados de acesso</span>
235
235
  <div className="relative">
236
- <FormField
237
- label="E-mail"
238
- value={user?.email ?? ''}
239
- disabled
240
- classnameContainer="bg-gray-50 border-0!"
241
- />
236
+ <div className="opacity-50">
237
+ <FormField
238
+ label="E-mail"
239
+ value={user?.email ?? ''}
240
+ disabled
241
+ classnameContainer="bg-gray-50 border-0!"
242
+ />
243
+ </div>
242
244
  <button
243
245
  type="button"
244
246
  className="absolute right-3 top-5.5 h-10 flex items-center paragraph-xsmall-semibold text-gray-950 underline cursor-pointer"
@@ -1,148 +1,205 @@
1
1
  'use client';
2
2
 
3
- import { ComponentPropsWithoutRef, forwardRef } from 'react';
4
- import Image from 'next/image';
5
- import { ChevronDown } from 'lucide-react';
6
- import { Input } from './Input';
7
- import { Separator } from '../data-display/Separator';
8
- import { cn } from '../../../infra/utils/clsx';
9
-
10
- export interface PhoneCountry {
11
- code: string;
12
- label: string;
13
- emoji: string;
3
+ import { useState, useEffect, useRef } from 'react';
4
+ import { AsYouType, CountryCode } from 'libphonenumber-js';
5
+ import { Input, Separator, Popover, PopoverTrigger, PopoverContent, cn } from '@greatapps/common';
6
+ import { IconChevronDown, IconSearch } from '@tabler/icons-react';
7
+ import { COUNTRIES, Country, flagUrl, parsePhoneValue } from '../../../utils/countries';
8
+
9
+ function formatNational(digits: string, iso: string): string {
10
+ const raw = digits.replace(/\D/g, '');
11
+ if (!raw) return '';
12
+ return new AsYouType(iso as CountryCode).input(raw);
14
13
  }
15
14
 
16
- export const PHONE_COUNTRIES: PhoneCountry[] = [
17
- { code: '+55', label: 'Brasil', emoji: '🇧🇷' },
18
- { code: '+1', label: 'EUA', emoji: '🇺🇸' },
19
- { code: '+351', label: 'Portugal', emoji: '🇵🇹' },
20
- { code: '+54', label: 'Argentina', emoji: '🇦🇷' },
21
- { code: '+56', label: 'Chile', emoji: '🇨🇱' },
22
- { code: '+52', label: 'México', emoji: '🇲🇽' },
23
- { code: '+44', label: 'Reino Unido', emoji: '🇬🇧' },
24
- { code: '+34', label: 'Espanha', emoji: '🇪🇸' },
25
- { code: '+49', label: 'Alemanha', emoji: '🇩🇪' },
26
- { code: '+33', label: 'França', emoji: '🇫🇷' },
27
- { code: '+57', label: 'Colômbia', emoji: '🇨🇴' },
28
- { code: '+598', label: 'Uruguai', emoji: '🇺🇾' },
29
- ];
30
-
31
- interface PhoneInputProps extends Omit<ComponentPropsWithoutRef<'input'>, 'type'> {
15
+ interface PhoneInputProps {
16
+ value?: string;
17
+ onChange?: (value: string) => void;
32
18
  label?: string;
33
19
  optional?: boolean;
34
20
  required?: boolean;
35
21
  hintMessage?: string;
36
22
  error?: boolean;
37
23
  errorMessage?: string;
38
- countryCode?: string;
39
- countryFlagSrc?: string;
40
- countryFlagAlt?: string;
24
+ placeholder?: string;
25
+ disabled?: boolean;
41
26
  classnameContainer?: string;
42
- selectedCountry?: PhoneCountry;
43
- onCountryChange?: (country: PhoneCountry) => void;
27
+ className?: string;
44
28
  }
45
29
 
46
- const PhoneInput = forwardRef<HTMLInputElement, PhoneInputProps>(
47
- (
48
- {
49
- label,
50
- optional = false,
51
- required = false,
52
- hintMessage,
53
- error = false,
54
- errorMessage,
55
- countryCode = '+55',
56
- countryFlagSrc = '/icons/brazil-flag.svg',
57
- countryFlagAlt = 'Brazil flag',
58
- className,
59
- classnameContainer,
60
- selectedCountry,
61
- onCountryChange,
62
- ...props
63
- },
64
- ref
65
- ) => {
66
- const finalMessage = error && errorMessage ? errorMessage : hintMessage;
67
- const showMessage = finalMessage && finalMessage.trim() !== '';
68
-
69
- const displayCode = selectedCountry ? selectedCountry.code : countryCode;
70
-
71
- return (
72
- <div className={cn('flex flex-col gap-1.5')}>
73
- {label && (
74
- <div className="flex items-center gap-1 paragraph-xsmall-semibold">
75
- <span className="text-gray-600">{label}</span>
76
- {optional && <span className="text-gray-500">(Opcional)</span>}
77
- {required && <span className="text-red-600">*</span>}
78
- </div>
79
- )}
30
+ export default function PhoneInput({
31
+ value,
32
+ onChange,
33
+ label,
34
+ optional = false,
35
+ required = false,
36
+ hintMessage,
37
+ error = false,
38
+ errorMessage,
39
+ placeholder,
40
+ disabled = false,
41
+ classnameContainer,
42
+ className,
43
+ }: PhoneInputProps) {
44
+ const parsed = parsePhoneValue(value ?? '');
45
+ const [selectedCountry, setSelectedCountry] = useState<Country>(parsed.country);
46
+ const [phoneNumber, setPhoneNumber] = useState(parsed.number);
47
+ const [search, setSearch] = useState('');
48
+ const [open, setOpen] = useState(false);
49
+ const prevValueRef = useRef(value);
50
+ const inputRef = useRef<HTMLInputElement>(null);
80
51
 
81
- <div
82
- className={cn(
83
- 'flex gap-2 items-center border rounded-lg h-10 transition-colors',
84
- error
85
- ? 'border-red-600 hover:border-red-700'
86
- : 'border-gray-200 hover:border-gray-400 focus-within:border-gray-950',
87
- classnameContainer
88
- )}
89
- >
90
- {onCountryChange ? (
91
- <div className="relative flex items-center gap-2 px-4 cursor-pointer shrink-0">
92
- <span className="text-base leading-none">{selectedCountry?.emoji ?? '🇧🇷'}</span>
93
- <span className="paragraph-small-regular text-gray-950">{displayCode}</span>
94
- <ChevronDown size={14} className="text-gray-500" />
95
- <select
96
- className="absolute inset-0 opacity-0 cursor-pointer w-full"
97
- value={displayCode}
98
- onChange={(e) => {
99
- const country = PHONE_COUNTRIES.find((c) => c.code === e.target.value);
100
- if (country) onCountryChange(country);
101
- }}
102
- >
103
- {PHONE_COUNTRIES.map((c) => (
104
- <option key={c.code} value={c.code}>
105
- {c.emoji} {c.code} {c.label}
106
- </option>
107
- ))}
108
- </select>
109
- </div>
110
- ) : (
111
- <div className="flex items-center gap-2 px-4">
112
- <Image
113
- src={countryFlagSrc}
114
- alt={countryFlagAlt}
115
- width={20}
116
- height={20}
117
- className="h-5! w-5! rounded-full"
118
- />
119
- <span className="paragraph-small-regular text-gray-950">{countryCode}</span>
120
- </div>
121
- )}
52
+ useEffect(() => {
53
+ if (value !== prevValueRef.current) {
54
+ prevValueRef.current = value;
55
+ const p = parsePhoneValue(value ?? '');
56
+ setSelectedCountry(p.country);
57
+ setPhoneNumber(formatNational(p.number, p.country.iso));
58
+ }
59
+ }, [value]);
60
+
61
+ const emit = (country: Country, number: string) => {
62
+ onChange?.(`${country.dial} ${number}`);
63
+ };
64
+
65
+ const handleCountrySelect = (country: Country) => {
66
+ const reformatted = formatNational(phoneNumber, country.iso);
67
+ setSelectedCountry(country);
68
+ setPhoneNumber(reformatted);
69
+ setOpen(false);
70
+ setSearch('');
71
+ emit(country, reformatted);
72
+ };
73
+
74
+ const handleNumberChange = (e: React.ChangeEvent<HTMLInputElement>) => {
75
+ const rawInput = e.target.value;
76
+ const cursorPos = e.target.selectionStart ?? rawInput.length;
77
+ const digitsBeforeCursor = rawInput.slice(0, cursorPos).replace(/\D/g, '').length;
78
+
79
+ const formatted = formatNational(rawInput, selectedCountry.iso);
80
+ setPhoneNumber(formatted);
81
+ emit(selectedCountry, formatted);
122
82
 
123
- <Separator orientation="vertical" />
124
-
125
- <Input
126
- ref={ref}
127
- type="tel"
128
- className={cn(
129
- 'paragraph-small-medium w-full h-full text-gray-950 border-0 focus-visible:ring-0 focus-visible:ring-offset-0',
130
- className
131
- )}
132
- {...props}
133
- />
83
+ requestAnimationFrame(() => {
84
+ if (!inputRef.current) return;
85
+ let digitCount = 0;
86
+ let newPos = formatted.length;
87
+ for (let i = 0; i < formatted.length; i++) {
88
+ if (/\d/.test(formatted[i])) {
89
+ digitCount++;
90
+ if (digitCount === digitsBeforeCursor) {
91
+ newPos = i + 1;
92
+ break;
93
+ }
94
+ }
95
+ }
96
+ inputRef.current.setSelectionRange(newPos, newPos);
97
+ });
98
+ };
99
+
100
+ const filtered = COUNTRIES.filter(
101
+ (c) =>
102
+ c.name.toLowerCase().includes(search.toLowerCase()) ||
103
+ c.dial.includes(search) ||
104
+ c.iso.toLowerCase().includes(search.toLowerCase())
105
+ );
106
+
107
+ const finalMessage = error && errorMessage ? errorMessage : hintMessage;
108
+ const showMessage = finalMessage && finalMessage.trim() !== '';
109
+
110
+ return (
111
+ <div className="flex flex-col gap-1.5">
112
+ {label && (
113
+ <div className="flex items-center gap-1 paragraph-xsmall-semibold">
114
+ <span className="text-zinc-600">{label}</span>
115
+ {optional && <span className="text-zinc-500">(Opcional)</span>}
116
+ {required && <span className="text-red-600">*</span>}
134
117
  </div>
118
+ )}
135
119
 
136
- {showMessage && (
137
- <span className={cn('paragraph-xsmall-medium', error ? 'text-red-600' : 'text-gray-600')}>
138
- {finalMessage}
139
- </span>
120
+ <div
121
+ className={cn(
122
+ 'flex gap-2 items-center border rounded-lg h-10 transition-colors',
123
+ error
124
+ ? 'border-red-600 hover:border-red-700'
125
+ : 'border-zinc-200 hover:border-zinc-400 focus-within:border-zinc-950',
126
+ disabled && 'opacity-50 cursor-not-allowed',
127
+ classnameContainer
140
128
  )}
141
- </div>
142
- );
143
- }
144
- );
129
+ >
130
+ <Popover open={open} onOpenChange={setOpen}>
131
+ <PopoverTrigger asChild>
132
+ <button
133
+ type="button"
134
+ className="flex items-center gap-1.5 px-3 h-full shrink-0 focus:outline-none"
135
+ disabled={disabled}
136
+ >
137
+ <img src={flagUrl(selectedCountry.iso)} alt={selectedCountry.iso} className="w-5 h-5 rounded-full" />
138
+ <span className="paragraph-small-regular text-zinc-950">{selectedCountry.dial}</span>
139
+ <IconChevronDown size={14} className={cn("text-zinc-500 transition-transform duration-200", open && "rotate-180")} />
140
+ </button>
141
+ </PopoverTrigger>
142
+ <PopoverContent className="w-72 p-0 z-[1010]" align="start" side="top">
143
+ <div className="flex items-center gap-2 p-2 border-b border-zinc-100">
144
+ <IconSearch size={14} className="text-zinc-400 shrink-0" />
145
+ <input
146
+ type="text"
147
+ className="flex-1 text-sm outline-none placeholder:text-zinc-400"
148
+ placeholder="Buscar país..."
149
+ value={search}
150
+ onChange={(e) => setSearch(e.target.value)}
151
+ autoFocus
152
+ />
153
+ </div>
154
+ <div className="max-h-60 overflow-y-auto overscroll-contain" onTouchMove={(e) => e.stopPropagation()}>
155
+ {filtered.map((country) => (
156
+ <button
157
+ key={country.iso}
158
+ type="button"
159
+ className={cn(
160
+ 'flex items-center gap-2.5 w-full px-3 py-2 text-left hover:bg-zinc-50 transition-colors',
161
+ selectedCountry.iso === country.iso && 'bg-zinc-100'
162
+ )}
163
+ onClick={() => handleCountrySelect(country)}
164
+ >
165
+ <img src={flagUrl(country.iso)} alt={country.iso} className="w-5 h-5 rounded-full shrink-0" />
166
+ <span className="paragraph-small-regular text-zinc-950 flex-1 truncate">
167
+ {country.name}
168
+ </span>
169
+ <span className="paragraph-small-regular text-zinc-500 shrink-0">
170
+ {country.dial}
171
+ </span>
172
+ </button>
173
+ ))}
174
+ {filtered.length === 0 && (
175
+ <p className="text-sm text-zinc-500 p-3 text-center">Nenhum país encontrado</p>
176
+ )}
177
+ </div>
178
+ </PopoverContent>
179
+ </Popover>
180
+
181
+ <Separator orientation="vertical" />
145
182
 
146
- PhoneInput.displayName = 'PhoneInput';
183
+ <Input
184
+ ref={inputRef}
185
+ type="tel"
186
+ value={phoneNumber}
187
+ onChange={handleNumberChange}
188
+ placeholder={placeholder}
189
+ disabled={disabled}
190
+ className={cn(
191
+ 'paragraph-small-medium w-full h-full text-zinc-950 border-0 focus-visible:ring-0 focus-visible:ring-offset-0',
192
+ disabled && 'cursor-not-allowed',
193
+ className
194
+ )}
195
+ />
196
+ </div>
147
197
 
148
- export default PhoneInput;
198
+ {showMessage && (
199
+ <span className={cn('paragraph-xsmall-medium', error ? 'text-red-600' : 'text-zinc-600')}>
200
+ {finalMessage}
201
+ </span>
202
+ )}
203
+ </div>
204
+ );
205
+ }