Browse Source

Get countries list from api

master
Eduard Kuzmenko 3 years ago
parent
commit
600c62af61
  1. 3
      src/components/appSearchSuper..ts
  2. 2
      src/components/chat/bubbles.ts
  3. 5
      src/components/inputField.ts
  4. 41
      src/components/misc.ts
  5. 2
      src/config/app.ts
  6. 20
      src/countries.ts
  7. 4
      src/helpers/dom/clickEvent.ts
  8. 4
      src/helpers/dom/dispatchEvent.ts
  9. 125
      src/helpers/formatPhoneNumber.ts
  10. 3
      src/layer.d.ts
  11. 2
      src/lib/appManagers/appUsersManager.ts
  12. 46
      src/lib/langPack.ts
  13. 117
      src/pages/pageSignIn.ts
  14. 67
      src/scripts/format_jsons.js
  15. 4205
      src/scripts/in/countries.mtproto.json
  16. 3
      src/scripts/in/schema_additional_params.json
  17. 2
      src/scripts/out/countries.json
  18. 8
      src/scss/partials/_document.scss
  19. 4
      src/vendor/emoji/index.ts

3
src/components/appSearchSuper..ts

@ -21,7 +21,7 @@ import AppMediaViewer from "./appMediaViewer"; @@ -21,7 +21,7 @@ import AppMediaViewer from "./appMediaViewer";
import { SearchGroup, SearchGroupType } from "./appSearch";
import { horizontalMenu } from "./horizontalMenu";
import LazyLoadQueue from "./lazyLoadQueue";
import { putPreloader, formatPhoneNumber } from "./misc";
import { putPreloader } from "./misc";
import { ripple } from "./ripple";
import Scrollable, { ScrollableX } from "./scrollable";
import { wrapDocument, wrapPhoto, wrapVideo } from "./wrappers";
@ -41,6 +41,7 @@ import cleanSearchText from "../helpers/cleanSearchText"; @@ -41,6 +41,7 @@ import cleanSearchText from "../helpers/cleanSearchText";
import { isTouchSupported } from "../helpers/touchSupport";
import handleTabSwipe from "../helpers/dom/handleTabSwipe";
import windowSize from "../helpers/windowSize";
import { formatPhoneNumber } from "../helpers/formatPhoneNumber";
//const testScroll = false;

2
src/components/chat/bubbles.ts

@ -35,7 +35,6 @@ import mediaSizes from "../../helpers/mediaSizes"; @@ -35,7 +35,6 @@ import mediaSizes from "../../helpers/mediaSizes";
import { isAndroid, isApple, isMobile, isSafari } from "../../helpers/userAgent";
import I18n, { i18n, langPack } from "../../lib/langPack";
import AvatarElement from "../avatar";
import { formatPhoneNumber } from "../misc";
import { ripple } from "../ripple";
import { wrapAlbum, wrapPhoto, wrapVideo, wrapDocument, wrapSticker, wrapPoll, wrapGroupedDocuments } from "../wrappers";
import { MessageRender } from "./messageRender";
@ -75,6 +74,7 @@ import debounce from "../../helpers/schedulers/debounce"; @@ -75,6 +74,7 @@ import debounce from "../../helpers/schedulers/debounce";
import { formatNumber } from "../../helpers/number";
import { SEND_WHEN_ONLINE_TIMESTAMP } from "../../lib/mtproto/constants";
import windowSize from "../../helpers/windowSize";
import { formatPhoneNumber } from "../../helpers/formatPhoneNumber";
const USE_MEDIA_TAILS = false;
const IGNORE_ACTIONS: Set<Message.messageService['action']['_']> = new Set([

5
src/components/inputField.ts

@ -4,10 +4,10 @@ @@ -4,10 +4,10 @@
* https://github.com/morethanwords/tweb/blob/master/LICENSE
*/
import simulateEvent from "../helpers/dom/dispatchEvent";
import findUpAttribute from "../helpers/dom/findUpAttribute";
import getRichValue from "../helpers/dom/getRichValue";
import isInputEmpty from "../helpers/dom/isInputEmpty";
import debounce from "../helpers/schedulers/debounce";
import { i18n, LangPackKey, _i18n } from "../lib/langPack";
import RichTextProcessor from "../lib/richtextprocessor";
@ -240,8 +240,7 @@ class InputField { @@ -240,8 +240,7 @@ class InputField {
set value(value: string) {
this.setValueSilently(value, false);
const event = new Event('input', {bubbles: true, cancelable: true});
this.input.dispatchEvent(event);
simulateEvent(this.input, 'input');
}
public setValueSilently(value: string, fireFakeInput = true) {

41
src/components/misc.ts

@ -5,7 +5,6 @@ @@ -5,7 +5,6 @@
*/
import { MOUNT_CLASS_TO } from "../config/debug";
import Countries, { Country, PhoneCodesMain } from "../countries";
import { cancelEvent } from "../helpers/dom/cancelEvent";
import { CLICK_EVENT_NAME } from "../helpers/dom/clickEvent";
import ListenerSetter from "../helpers/listenerSetter";
@ -51,46 +50,6 @@ export function setButtonLoader(elem: HTMLButtonElement, icon = 'check') { @@ -51,46 +50,6 @@ export function setButtonLoader(elem: HTMLButtonElement, icon = 'check') {
};
}
let sortedCountries: Country[];
export function formatPhoneNumber(originalStr: string) {
let str = originalStr.replace(/\D/g, '');
let phoneCode = str.slice(0, 6);
////console.log('str', str, phoneCode);
if(!sortedCountries) {
sortedCountries = Countries.slice().sort((a, b) => b.phoneCode.length - a.phoneCode.length);
}
let country = sortedCountries.find((c) => {
return c.phoneCode.split(' and ').find((c) => phoneCode.indexOf(c.replace(/\D/g, '')) === 0);
});
if(!country) return {formatted: str, country, leftPattern: ''};
country = PhoneCodesMain[country.phoneCode] || country;
let pattern = country.pattern || country.phoneCode;
pattern.split('').forEach((symbol, idx) => {
if(symbol === ' ' && str[idx] !== ' ' && str.length > idx) {
str = str.slice(0, idx) + ' ' + str.slice(idx);
}
});
/* if(country.pattern) {
str = str.slice(0, country.pattern.length);
} */
let leftPattern = pattern && pattern.length > str.length ? pattern.slice(str.length) : '';
if(leftPattern) {
/* const length = str.length;
leftPattern = leftPattern.split('').map((_, idx) => (length + idx).toString().slice(-1)).join(''); */
leftPattern = leftPattern.replace(/X/g, '‒');
// leftPattern = leftPattern.replace(/X/g, '0');
}
return {formatted: str, country, leftPattern};
}
/* export function parseMenuButtonsTo(to: {[name: string]: HTMLElement}, elements: HTMLCollection | NodeListOf<HTMLElement>) {
Array.from(elements).forEach(el => {
const match = el.className.match(/(?:^|\s)menu-(.+?)(?:$|\s)/);

2
src/config/app.ts

@ -17,7 +17,7 @@ const App = { @@ -17,7 +17,7 @@ const App = {
id: 1025907,
hash: '452b0359b988148995f22ff0f4229750',
version: '0.7.2',
langPackVersion: '0.3.2',
langPackVersion: '0.3.3',
langPack: 'macos',
langPackCode: 'en',
domains: [MAIN_DOMAIN] as string[],

20
src/countries.ts

File diff suppressed because one or more lines are too long

4
src/helpers/dom/clickEvent.ts

@ -6,6 +6,7 @@ @@ -6,6 +6,7 @@
import type ListenerSetter from "../listenerSetter";
import { isTouchSupported } from "../touchSupport";
import simulateEvent from "./dispatchEvent";
export const CLICK_EVENT_NAME: 'mousedown' | 'touchend' | 'click' = (isTouchSupported ? 'mousedown' : 'click') as any;
export type AttachClickOptions = AddEventListenerOptions & Partial<{listenerSetter: ListenerSetter, touchMouseDown: true}>;
@ -53,6 +54,5 @@ export function detachClickEvent(elem: HTMLElement, callback: (e: TouchEvent | M @@ -53,6 +54,5 @@ export function detachClickEvent(elem: HTMLElement, callback: (e: TouchEvent | M
}
export function simulateClickEvent(elem: HTMLElement) {
const event = new Event(CLICK_EVENT_NAME, {bubbles: true, cancelable: true});
elem.dispatchEvent(event);
simulateEvent(elem, CLICK_EVENT_NAME);
}

4
src/helpers/dom/dispatchEvent.ts

@ -0,0 +1,4 @@ @@ -0,0 +1,4 @@
export default function simulateEvent(elem: HTMLElement, name: string) {
const event = new Event(name, {bubbles: true, cancelable: true});
elem.dispatchEvent(event);
}

125
src/helpers/formatPhoneNumber.ts

@ -0,0 +1,125 @@ @@ -0,0 +1,125 @@
/*
* https://github.com/morethanwords/tweb
* Copyright (C) 2019-2021 Eduard Kuzmenko
* https://github.com/morethanwords/tweb/blob/master/LICENSE
*/
import { HelpCountry, HelpCountryCode } from "../layer";
import I18n from "../lib/langPack";
let sortedCountries: HelpCountry[];
type PrefixCountry = {country: HelpCountry, code: HelpCountryCode};
const prefixes: Map<string, PrefixCountry> = new Map();
let maxPrefixLength = 0;
const setPrefix = (country: HelpCountry, code: HelpCountryCode, prefix: string = '') => {
prefix = code.country_code + prefix;
/* if(prefixes.has(prefix)) {
console.error('asdasdasd', prefixes.get(prefix), country, code);
} */
maxPrefixLength = Math.max(maxPrefixLength, prefix.length);
prefixes.set(prefix, {country, code});
};
export function formatPhoneNumber(originalStr: string): {
formatted: string,
country: HelpCountry,
code: HelpCountryCode,
leftPattern: string
} {
if(!prefixes.size) {
I18n.countriesList.forEach(country => {
country.country_codes.forEach(code => {
const s = {country, code};
if(code.prefixes) {
code.prefixes.forEach(prefix => {
setPrefix(country, code, prefix);
});
} else {
setPrefix(country, code);
}
});
});
}
// return {formatted: originalStr, country: undefined as any, leftPattern: ''};
let str = originalStr.replace(/\D/g, '');
let phoneCode = str.slice(0, maxPrefixLength);
////console.log('str', str, phoneCode);
// if(!sortedCountries) {
// sortedCountries = I18n.countriesList.slice().sort((a, b) => b.country_codes[0].country_code.length - a.country_codes[0].country_code.length);
// }
// let country = sortedCountries.find((c) => {
// return c.country_codes.find((c) => phoneCode.indexOf(c.replace(/\D/g, '')) === 0);
// });
let prefixCountry: PrefixCountry;
for(let i = phoneCode.length - 1; i >= 0; --i) { // lookup for country by prefix
prefixCountry = prefixes.get(phoneCode.slice(0, i + 1));
if(prefixCountry) {
break;
}
}
if(!prefixCountry) {
return {
formatted: str,
country: undefined,
code: undefined,
leftPattern: ''
};
}
// country = /* PhoneCodesMain[country.phoneCode] || */country;
const country = prefixCountry.country;
const patterns = prefixCountry.code.patterns || [];
const searchForPattern = str.slice(prefixCountry.code.country_code.length); // splice country code
let pattern = '', mostMatchedPatternMatches = 0, mostMatchedPattern = '';
for(let i = patterns.length - 1; i >= 0; --i) {
pattern = patterns[i];
const _pattern = pattern.replace(/ /g, '');
let patternMatches = 0;
for(let k = 0, length = Math.min(searchForPattern.length, _pattern.length); k < length; ++k) {
if(searchForPattern[k] === _pattern[k] || _pattern[k] === 'X') {
++patternMatches;
} else {
patternMatches = 0;
break;
}
}
if(patternMatches > mostMatchedPatternMatches) {
mostMatchedPatternMatches = patternMatches;
mostMatchedPattern = pattern;
}
}
pattern = mostMatchedPattern || pattern;
pattern = pattern.replace(/\d/g, 'X');
pattern = prefixCountry.code.country_code + ' ' + pattern;
// let pattern = country.pattern || country.phoneCode;
pattern.split('').forEach((symbol, idx) => {
if(symbol === ' ' && str[idx] !== ' ' && str.length > idx) {
str = str.slice(0, idx) + ' ' + str.slice(idx);
}
});
/* if(country.pattern) {
str = str.slice(0, country.pattern.length);
} */
let leftPattern = pattern && pattern.length > str.length ? pattern.slice(str.length) : '';
if(leftPattern) {
/* const length = str.length;
leftPattern = leftPattern.split('').map((_, idx) => (length + idx).toString().slice(-1)).join(''); */
leftPattern = leftPattern.replace(/X/g, '‒');
// leftPattern = leftPattern.replace(/X/g, '0');
}
return {formatted: str, country, code: prefixCountry.code, leftPattern};
}

3
src/layer.d.ts vendored

@ -6146,7 +6146,8 @@ export namespace LangPackDifference { @@ -6146,7 +6146,8 @@ export namespace LangPackDifference {
version: number,
strings: Array<LangPackString>,
local?: boolean,
appVersion?: string
appVersion?: string,
countries?: HelpCountriesList.helpCountriesList
};
}

2
src/lib/appManagers/appUsersManager.ts

@ -9,12 +9,12 @@ @@ -9,12 +9,12 @@
* https://github.com/zhukov/webogram/blob/master/LICENSE
*/
import { formatPhoneNumber } from "../../components/misc";
import { MOUNT_CLASS_TO } from "../../config/debug";
import { filterUnique } from "../../helpers/array";
import cleanSearchText from "../../helpers/cleanSearchText";
import cleanUsername from "../../helpers/cleanUsername";
import { tsNow } from "../../helpers/date";
import { formatPhoneNumber } from "../../helpers/formatPhoneNumber";
import { safeReplaceObject, isObject } from "../../helpers/object";
import { Chat, InputUser, User as MTUser, UserProfilePhoto, UserStatus } from "../../layer";
import I18n, { i18n, LangPackKey } from "../langPack";

46
src/lib/langPack.ts

@ -9,7 +9,7 @@ import { safeAssign } from "../helpers/object"; @@ -9,7 +9,7 @@ import { safeAssign } from "../helpers/object";
import { capitalizeFirstLetter } from "../helpers/string";
import type lang from "../lang";
import type langSign from "../langSign";
import { LangPackDifference, LangPackString } from "../layer";
import { HelpCountriesList, HelpCountry, LangPackDifference, LangPackString } from "../layer";
import apiManager from "./mtproto/mtprotoworker";
import stateStorage from "./stateStorage";
import App from "../config/app";
@ -66,6 +66,7 @@ export type FormatterArguments = FormatterArgument[]; @@ -66,6 +66,7 @@ export type FormatterArguments = FormatterArgument[];
namespace I18n {
export const strings: Map<LangPackKey, LangPackString> = new Map();
export const countriesList: HelpCountry[] = [];
let pluralRules: Intl.PluralRules;
let cacheLangPackPromise: Promise<LangPackDifference>;
@ -101,8 +102,9 @@ namespace I18n { @@ -101,8 +102,9 @@ namespace I18n {
lastRequestedLangCode = defaultCode;
return Promise.all([
import('../lang'),
import('../langSign')
]).then(([lang, langSign]) => {
import('../langSign'),
import('../countries')
]).then(([lang, langSign, countries]) => {
const strings: LangPackString[] = [];
formatLocalStrings(lang.default, strings);
formatLocalStrings(langSign.default, strings);
@ -113,7 +115,8 @@ namespace I18n { @@ -113,7 +115,8 @@ namespace I18n {
lang_code: defaultCode,
strings,
version: 0,
local: true
local: true,
countries: countries.default
};
return saveLangPack(langPack);
});
@ -132,7 +135,11 @@ namespace I18n { @@ -132,7 +135,11 @@ namespace I18n {
}),
import('../lang'),
import('../langSign'),
polyfillPromise
apiManager.invokeApiCacheable('help.getCountriesList', {
lang_code: langCode,
hash: 0
}) as Promise<HelpCountriesList.helpCountriesList>,
polyfillPromise,
]);
}
@ -168,21 +175,22 @@ namespace I18n { @@ -168,21 +175,22 @@ namespace I18n {
export function getLangPack(langCode: string) {
lastRequestedLangCode = langCode;
return loadLangPack(langCode).then(([langPack, _langPack, __langPack, ___langPack, _]) => {
return loadLangPack(langCode).then(([langPack1, langPack2, localLangPack1, localLangPack2, countries, _]) => {
let strings: LangPackString[] = [];
[__langPack, ___langPack].forEach(l => {
[localLangPack1, localLangPack2].forEach(l => {
formatLocalStrings(l.default as any, strings);
});
strings = strings.concat(langPack.strings);
strings = strings.concat(langPack1.strings);
for(const string of _langPack.strings) {
for(const string of langPack2.strings) {
strings.push(string);
}
langPack.strings = strings;
return saveLangPack(langPack);
langPack1.strings = strings;
langPack1.countries = countries;
return saveLangPack(langPack1);
});
}
@ -223,6 +231,22 @@ namespace I18n { @@ -223,6 +231,22 @@ namespace I18n {
strings.set(string.key as LangPackKey, string);
}
if(langPack.countries) {
countriesList.length = 0;
countriesList.push(...langPack.countries.countries);
langPack.countries.countries.forEach(country => {
if(country.name) {
const langPackKey: any = country.default_name;
strings.set(langPackKey, {
_: 'langPackString',
key: langPackKey,
value: country.name
});
}
});
}
rootScope.dispatchEvent('language_change', langPack.lang_code);
const elements = Array.from(document.querySelectorAll(`.i18n`)) as HTMLElement[];

117
src/pages/pageSignIn.ts

@ -4,9 +4,8 @@ @@ -4,9 +4,8 @@
* https://github.com/morethanwords/tweb/blob/master/LICENSE
*/
import { formatPhoneNumber, putPreloader } from "../components/misc";
import { putPreloader } from "../components/misc";
import Scrollable from '../components/scrollable';
import Countries, { Country as _Country } from "../countries";
import appStateManager from "../lib/appManagers/appStateManager";
import apiManager from "../lib/mtproto/mtprotoworker";
import { RichTextProcessor } from '../lib/richtextprocessor';
@ -14,12 +13,12 @@ import Page from "./page"; @@ -14,12 +13,12 @@ import Page from "./page";
import InputField from "../components/inputField";
import CheckboxField from "../components/checkboxField";
import Button from "../components/button";
import { isAndroid, isApple, isAppleMobile, isSafari } from "../helpers/userAgent";
import { isAndroid, isApple, isAppleMobile } from "../helpers/userAgent";
import fastSmoothScroll from "../helpers/fastSmoothScroll";
import { isTouchSupported } from "../helpers/touchSupport";
import App from "../config/app";
import Modes from "../config/modes";
import { _i18n, i18n } from "../lib/langPack";
import I18n, { _i18n, i18n } from "../lib/langPack";
import lottieLoader from "../lib/lottieLoader";
import { ripple } from "../components/ripple";
import findUpTag from "../helpers/dom/findUpTag";
@ -36,39 +35,48 @@ import toggleDisability from "../helpers/dom/toggleDisability"; @@ -36,39 +35,48 @@ import toggleDisability from "../helpers/dom/toggleDisability";
import sessionStorage from "../lib/sessionStorage";
import { DcAuthKey } from "../types";
import placeCaretAtEnd from "../helpers/dom/placeCaretAtEnd";
type Country = _Country & {
li?: HTMLLIElement[]
};
import { formatPhoneNumber } from "../helpers/formatPhoneNumber";
import { HelpCountry, HelpCountryCode } from "../layer";
import { getCountryEmoji } from "../vendor/emoji";
import simulateEvent from "../helpers/dom/dispatchEvent";
import stateStorage from "../lib/stateStorage";
//import _countries from '../countries_pretty.json';
let btnNext: HTMLButtonElement = null, btnQr: HTMLButtonElement;
let onFirstMount = () => {
if(Modes.test) {
/* if(Modes.test) {
Countries.push({
name: 'Test Country',
phoneCode: '999 66',
code: 'TC',
emoji: '🤔',
pattern: '999 66 XXX XX'
_: 'help.country',
default_name: 'Test Country',
country_codes: [{
_: 'help.countryCode',
country_code: '999 66',
patterns: ['999 66 XXX XX']
}],
iso2: 'KK'
});
console.log('Added test country to list!');
}
} */
//const countries: Country[] = _countries.default.filter(c => c.emoji);
const countries: Country[] = Countries.filter(c => c.emoji).sort((a, b) => a.name.localeCompare(b.name));
// const countries: Country[] = Countries.filter(c => c.emoji).sort((a, b) => a.name.localeCompare(b.name));
// const countries = I18n.countriesList.filter(country => !country.pFlags?.hidden);
const countries = I18n.countriesList
.filter(country => !country.pFlags?.hidden)
.sort((a, b) => (a.name || a.default_name).localeCompare(b.name || b.default_name));
let lastCountrySelected: Country = null;
const liMap: Map<string, HTMLLIElement[]> = new Map();
let lastCountrySelected: HelpCountry, lastCountryCodeSelected: HelpCountryCode;
const inputWrapper = document.createElement('div');
inputWrapper.classList.add('input-wrapper');
const countryInputField = new InputField({
label: 'Login.CountrySelectorLabel',
name: randomLong(),
plainText: true
name: randomLong()
});
countryInputField.container.classList.add('input-select');
@ -92,10 +100,10 @@ let onFirstMount = () => { @@ -92,10 +100,10 @@ let onFirstMount = () => {
initSelect = null;
countries.forEach((c) => {
const emoji = c.emoji;
const emoji = getCountryEmoji(c.iso2);
const liArr: Array<HTMLLIElement> = [];
c.phoneCode.split(' and ').forEach((phoneCode: string) => {
c.country_codes.forEach((countryCode) => {
const li = document.createElement('li');
let wrapped = RichTextProcessor.wrapEmojiText(emoji);
@ -107,18 +115,20 @@ let onFirstMount = () => { @@ -107,18 +115,20 @@ let onFirstMount = () => {
li.innerHTML = wrapped;
}
li.append(c.name);
const el = i18n(c.default_name as any);
el.dataset.defaultName = c.default_name;
li.append(el);
const span = document.createElement('span');
span.classList.add('phone-code');
span.innerText = '+' + phoneCode;
span.innerText = '+' + countryCode.country_code;
li.appendChild(span);
liArr.push(li);
selectList.append(li);
});
c.li = liArr;
liMap.set(c.iso2, liArr);
});
selectList.addEventListener('mousedown', (e) => {
@ -126,9 +136,7 @@ let onFirstMount = () => { @@ -126,9 +136,7 @@ let onFirstMount = () => {
return;
}
let target = e.target as HTMLElement;
if(target.tagName !== 'LI') target = findUpTag(target, 'LI');
const target = findUpTag(e.target, 'LI')
selectCountryByTarget(target);
//console.log('clicked', e, countryName, phoneCode);
});
@ -137,11 +145,12 @@ let onFirstMount = () => { @@ -137,11 +145,12 @@ let onFirstMount = () => {
};
const selectCountryByTarget = (target: HTMLElement) => {
const countryName = target.childNodes[1].textContent;//target.innerText.split('\n').shift();
const defaultName = (target.childNodes[1] as HTMLElement).dataset.defaultName;
const phoneCode = target.querySelector<HTMLElement>('.phone-code').innerText;
countryInput.value = countryName;
lastCountrySelected = countries.find(c => c.name === countryName);
replaceContent(countryInput, i18n(defaultName as any));
simulateEvent(countryInput, 'input');
lastCountrySelected = countries.find(c => c.default_name === defaultName);
telInputField.value = lastValue = phoneCode;
hidePicker();
@ -160,7 +169,7 @@ let onFirstMount = () => { @@ -160,7 +169,7 @@ let onFirstMount = () => {
initSelect();
} else {
countries.forEach((c) => {
c.li.forEach(li => li.style.display = '');
liMap.get(c.iso2).forEach(li => li.style.display = '');
});
}
@ -216,11 +225,11 @@ let onFirstMount = () => { @@ -216,11 +225,11 @@ let onFirstMount = () => {
//let i = new RegExp('^' + this.value, 'i');
let _value = this.value.toLowerCase();
let matches: Country[] = [];
let matches: HelpCountry[] = [];
countries.forEach((c) => {
let good = c.name.toLowerCase().indexOf(_value) !== -1/* === 0 */;//i.test(c.name);
let good = !![c.name, c.default_name].filter(Boolean).find(str => str.toLowerCase().indexOf(_value) !== -1)/* === 0 */;//i.test(c.name);
c.li.forEach(li => li.style.display = good ? '' : 'none');
liMap.get(c.iso2).forEach(li => li.style.display = good ? '' : 'none');
if(good) matches.push(c);
});
@ -235,10 +244,10 @@ let onFirstMount = () => { @@ -235,10 +244,10 @@ let onFirstMount = () => {
return false;
} else */if(matches.length === 0) {
countries.forEach((c) => {
c.li.forEach(li => li.style.display = '');
liMap.get(c.iso2).forEach(li => li.style.display = '');
});
} else if(matches.length === 1 && e.key === 'Enter') {
selectCountryByTarget(matches[0].li[0]);
selectCountryByTarget(liMap.get(matches[0].iso2)[0]);
}
});
@ -302,7 +311,7 @@ let onFirstMount = () => { @@ -302,7 +311,7 @@ let onFirstMount = () => {
telInputField.setLabel();
let formatted: string, country: Country, leftPattern = '';
let formatted: string, country: HelpCountry, countryCode: HelpCountryCode, leftPattern = '';
if(telInputField.value.replace(/\++/, '+') === '+') {
telInputField.setValueSilently('+');
} else {
@ -310,6 +319,7 @@ let onFirstMount = () => { @@ -310,6 +319,7 @@ let onFirstMount = () => {
formatted = o.formatted;
country = o.country;
leftPattern = o.leftPattern;
countryCode = o.code;
telInputField.setValueSilently(lastValue = formatted ? '+' + formatted : '');
}
@ -317,10 +327,18 @@ let onFirstMount = () => { @@ -317,10 +327,18 @@ let onFirstMount = () => {
//console.log(formatted, country);
let countryName = country ? country.name : ''/* 'Unknown' */;
if(countryName !== countryInput.value && (!lastCountrySelected || !country || lastCountrySelected.phoneCode !== country.phoneCode)) {
countryInput.value = countryName;
let countryName = country ? country.name || country.default_name : ''/* 'Unknown' */;
if(countryName !== countryInputField.value && (
!lastCountrySelected ||
!country || (
lastCountrySelected !== country &&
lastCountryCodeSelected.country_code !== countryCode.country_code
)
)
) {
replaceContent(countryInput, country ? i18n(country.default_name as any) : countryName);
lastCountrySelected = country;
lastCountryCodeSelected = countryCode;
}
//if(country && (telInputField.value.length - 1) >= (country.pattern ? country.pattern.length : 9)) {
@ -468,6 +486,13 @@ let onFirstMount = () => { @@ -468,6 +486,13 @@ let onFirstMount = () => {
let tryAgain = () => {
apiManager.invokeApi('help.getNearestDc').then((nearestDcResult) => {
const langPack = stateStorage.getFromCache('langPack');
if(langPack && !langPack.countries?.hash) {
I18n.getLangPack(langPack.lang_code).then(() => {
simulateEvent(telEl, 'input');
});
}
const dcs = new Set([1, 2, 3, 4, 5]);
const done: number[] = [nearestDcResult.this_dc];
@ -504,16 +529,8 @@ let onFirstMount = () => { @@ -504,16 +529,8 @@ let onFirstMount = () => {
return nearestDcResult;
}).then((nearestDcResult) => {
if(!countryInput.value.length && !telInputField.value.length) {
const country = countries.find((c) => c.code === nearestDcResult.country);
if(country) {
countryInput.value = country.name;
lastCountrySelected = country;
const str = '+' + country.phoneCode.split(' and ').shift();
const {leftPattern} = formatPhoneNumber(str);
telInputField.setValueSilently(lastValue = str);
telEl.dataset.leftPattern = leftPattern;
}
if(!countryInputField.value.length && !telInputField.value.length) {
selectCountryByTarget(liMap.get(nearestDcResult.country)[0]);
}
//console.log('woohoo', nearestDcResult, country);

67
src/scripts/format_jsons.js

@ -7,7 +7,8 @@ @@ -7,7 +7,8 @@
let emoji = require('./in/emoji_pretty.json');
//let countries = require('./countries_pretty.json');
let countries = require('fs').readFileSync('./in/countries.dat').toString();
// let countries = require('fs').readFileSync('./in/countries.dat').toString();
let countries = require('./in/countries.mtproto.json');
//console.log(countries);
//console.log(emoji, countries);
@ -188,31 +189,49 @@ if(false) { @@ -188,31 +189,49 @@ if(false) {
require('fs').writeFileSync('./emoji.json', JSON.stringify(obj));
} */
{
let arr = [];
/* countries.forEach(e => {
let {name, code, phoneCode} = e;
// old countries format
// {
// let arr = [];
// /* countries.forEach(e => {
// let {name, code, phoneCode} = e;
arr.push([name, code, phoneCode]);
}); */
// arr.push([name, code, phoneCode]);
// }); */
const lines = countries.split('\n');
const data2 = [];
lines.forEach(x => {
if(!x.trim()) return;
const split = x.split(';');
const item = {
phoneCode: split[0],
code: split[1],
name: split[2],
pattern: split[3],
//count: Number(split[4]),
emoji: split[5]
};
// const lines = countries.split('\n');
// const data2 = [];
// lines.forEach(x => {
// if(!x.trim()) return;
// const split = x.split(';');
// const item = {
// phoneCode: split[0],
// code: split[1],
// name: split[2],
// pattern: split[3],
// //count: Number(split[4]),
// emoji: split[5]
// };
// arr.push(item);
// //console.log(item);
// });
// require('fs').writeFileSync(writePathTo + 'countries.json', JSON.stringify(arr));
// }
arr.push(item);
//console.log(item);
{
const c = countries.filter(country => !country.pFlags.hidden);
c.forEach(country => {
delete country._;
delete country.pFlags;
delete country.flags;
country.country_codes.forEach(countryCode => {
delete countryCode._;
delete countryCode.pFlags;
delete countryCode.flags;
});
});
require('fs').writeFileSync(writePathTo + 'countries.json', JSON.stringify(arr));
require('fs').writeFileSync(writePathTo + 'countries.json', JSON.stringify(c));
}

4205
src/scripts/in/countries.mtproto.json

File diff suppressed because it is too large Load Diff

3
src/scripts/in/schema_additional_params.json

@ -225,7 +225,8 @@ @@ -225,7 +225,8 @@
"predicate": "langPackDifference",
"params": [
{"name": "local", "type": "boolean"},
{"name": "appVersion", "type": "string"}
{"name": "appVersion", "type": "string"},
{"name": "countries", "type": "HelpCountriesList.helpCountriesList"}
]
}, {
"predicate": "updateNewDiscussionMessage",

2
src/scripts/out/countries.json

File diff suppressed because one or more lines are too long

8
src/scss/partials/_document.scss

@ -109,7 +109,6 @@ @@ -109,7 +109,6 @@
&-name {
white-space: nowrap;
font-weight: 500;
line-height: 1.3;
font-size: 1rem;
}
@ -118,7 +117,12 @@ @@ -118,7 +117,12 @@
color: var(--secondary-text-color);
font-size: .875rem;
//padding-right: 32px;
line-height: 1.3;
text-overflow: ellipsis;
overflow: hidden;
}
&-name, &-size {
line-height: var(--line-height);
}
.preloader-container {

4
src/vendor/emoji/index.ts vendored

@ -40,6 +40,10 @@ export function getEmojiToneIndex(input: string) { @@ -40,6 +40,10 @@ export function getEmojiToneIndex(input: string) {
return match ? 5 - (57343 - match[0].charCodeAt(0)) : 0;
}
export function getCountryEmoji(iso2: string) {
return String.fromCharCode(55356, 56741 + iso2.charCodeAt(0), 55356, 56741 + iso2.charCodeAt(1));
}
export function emojiFromCodePoints(codePoints: string) {
return codePoints.split('-').reduce((prev, curr) => prev + String.fromCodePoint(parseInt(curr, 16)), '');
}
Loading…
Cancel
Save