Skip to content

Commit

Permalink
flags solved
Browse files Browse the repository at this point in the history
  • Loading branch information
eddow committed Jun 7, 2024
1 parent f156ab1 commit 06b7722
Show file tree
Hide file tree
Showing 11 changed files with 138 additions and 40 deletions.
3 changes: 2 additions & 1 deletion .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@
*.config.js
*.config.json
.gitignore
/.svelte-kit
/.svelte-kit
package-lock.json
14 changes: 1 addition & 13 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,4 @@ Projects using OmnI18n use it in 4 layers

The library can be imported in a [static website](umd.md).

## Bonus

### Flags

Just realized it was [not working on windows](https://answers.microsoft.com/en-us/windows/forum/all/flag-emoji/85b163bc-786a-4918-9042-763ccf4b6c05)...

```js
import { localeFlags, flagCodeExceptions }
localeFlags('en-GB') // ['๐Ÿ‡ฌ๐Ÿ‡ง']
localeFlags('en-US') //['๐Ÿ‡ฌ๐Ÿ‡ง', '๐Ÿ‡บ๐Ÿ‡ธ']
flagCodeExceptions.en = '๐Ÿด๓ ง๓ ข๓ ฅ๓ ฎ๓ ง๓ ฟ'
localeFlags('en-GB') // ['๐Ÿด๓ ง๓ ข๓ ฅ๓ ฎ๓ ง๓ ฟ', '๐Ÿ‡ฌ๐Ÿ‡ง']
```
There are [some utils that have been done for the library](./bonus.md) and are exported with it (flags, js-like json & defer)
54 changes: 54 additions & 0 deletions docs/bonus.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Bonuses

## Flags

The library takes in consideration two cases:

- On systems who support flags emojis, flags will just be this, a 2~3 unicode characters that form the emoji
- On windows, the library `flag-icons` will be downloaded dynamically from [cdnjs.com](https://cdnjs.com/libraries/flag-icon-css) (~28k) and `localeFlag` will return a `<span...` string. This is done transparently client-side

Note, the generic behavior can be set with `setFlagEngine` (taking `'emojis' | 'flag-icons'` ), even though it should be hydrated dynamically

Two `exceptions` lists are kept (one for emojis, one for flag class name): `flagEmojiExceptions` and `flagClassExceptions`. These are for languages who are not bound to a country (by default, it only contains `en` -> `gb`)

> Note: under windows, you won't see flags here beside '๐Ÿด๓ ง๓ ข๓ ฅ๓ ฎ๓ ง๓ ฟ' who is not even the correct one.
```js
import { localeFlags, flagCodeExceptions }
localeFlags('en-GB') // ['๐Ÿ‡ฌ๐Ÿ‡ง']
localeFlags('en-US') //['๐Ÿ‡ฌ๐Ÿ‡ง', '๐Ÿ‡บ๐Ÿ‡ธ']
flagEmojiExceptions.en = '๐Ÿด๓ ง๓ ข๓ ฅ๓ ฎ๓ ง๓ ฟ'
flagClassExceptions.en = 'gb-eng'
localeFlags('en-GB') // ['๐Ÿด๓ ง๓ ข๓ ฅ๓ ฎ๓ ง๓ ฟ', '๐Ÿ‡ฌ๐Ÿ‡ง']
```

> Note: The returned strings must therefore be considered as html code, not pure text, even if for most, it will be pure text
## js-like "jsonability"

The dictionary uses a human "json" format. It's really minimalistic and didn't deserve the 25k of `json5` or `hjson`, it doesn't have more ability than json but:

- allows js-like comment
- uses indifferently <">, <'>, or <`> as quote markers
- does not need quotes for keys

The main difference with JavaScript is that all quotes behave the same than <`> for new lines:

```
{
myMultilineString: "Hello
here"
}
```

The library exports the 2 functions `parse` and `stringify`.

The `maxLength` (2nd argument of `stringify`) specifies the maximum length an object/array can have on a line. When it exceeds this limit, the object/array is described with one line per element.

## Defer

The defer class allows to plan an action "on next tick" but let the code finish its modifications before actually doing it.

The callback can be given on constructor or when calling `.defer(...)`

You can get its `.promise` to wait (or `then`), get its instant `.deferring` status (boolean) or forcefully `.cancel()` or `.resolve()`
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "omni18n",
"version": "1.1.11",
"version": "1.1.12",
"exports": {
".": {
"browser": {
Expand Down Expand Up @@ -37,7 +37,7 @@
"build": "rollup -c",
"build-umd": "rollup -c rollup.umd.js --watch",
"build-extract": "rollup -c rollup.extract.js",
"prepare": "npm run prettier && npm run build"
"prepack": "npm run prettier && npm run build"
},
"repository": {
"type": "git",
Expand Down
12 changes: 11 additions & 1 deletion src/client.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,12 @@
export * from './server-shared/client'
export * from './types'
export * from './client/index'
export * from './tools/cgpt-js'
export * from './tools/flags'
import { default as Defer } from './tools/defer'
export { Defer }

declare global {
interface Set<T> {
union(...sets: Set<T>[]): this
}
}
4 changes: 3 additions & 1 deletion src/s-a.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
export * from './server-shared/s-a'
export * from './client'
export * from './server/index'
export * from './db/index'
export * from './tools/flags'
9 changes: 0 additions & 9 deletions src/server-shared/client.ts

This file was deleted.

3 changes: 0 additions & 3 deletions src/server-shared/s-a.ts

This file was deleted.

2 changes: 1 addition & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export * from './server-shared/s-a'
export * from './s-a'
import FileDB from './db/fileDb'
export { FileDB }
69 changes: 62 additions & 7 deletions src/tools/flags.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,76 @@
import { Locale } from '../types'

function toEmoji(name: string) {
return String.fromCodePoint(...Array.from(name).map((k) => k.charCodeAt(0) + 127365))
}

/**
* Some language codes do not have a clear country code and should be indicated here
*
* https://emojipedia.org/flags
*/
export const flagCodeExceptions: Record<string, string> = { en: '๐Ÿ‡ฌ๐Ÿ‡ง' }
export const flagEmojiExceptions: Record<string, string> = { en: '๐Ÿ‡ฌ๐Ÿ‡ง' }
export const flagClassExceptions: Record<string, string> = { en: 'gb' }

const styleSheet = `<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/7.2.3/css/flag-icons.min.css" integrity="sha512-bZBu2H0+FGFz/stDN/L0k8J0G8qVsAL0ht1qg5kTwtAheiXwiRKyCq1frwfbSFSJN3jooR5kauE0YjtPzhZtJQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />`

export let flagEngine: 'emojis' | 'flag-icons'
export let headStyle: string = ''
flagEngine = 'emojis' // Do not initialize on declaration, rollup considers it as a constant

export function setFlagEngine(engine: 'emojis' | 'flag-icons') {
flagEngine = engine
headStyle = engine === 'flag-icons' ? styleSheet : ''
if (engine === 'flag-icons' && typeof window !== undefined) {
let alreadyHasStyleSheet = false
//const stylesheets = document.querySelectorAll('link[rel="stylesheet"][href*="/flag-icons."]')
const stylesheets = document.querySelectorAll('link[rel="stylesheet"]')
for (let i = 0; i < stylesheets.length; i++) {
if (stylesheets[i].getAttribute('href')?.includes('/flag-icons.')) {
alreadyHasStyleSheet = true
break
}
}
if (!alreadyHasStyleSheet) document.head.insertAdjacentHTML('beforeend', styleSheet)
}
}

if (typeof navigator !== 'undefined') gotUserAgent(navigator.userAgent)

/**
* Set the global flag engine based on the user agent
* @param userAgent The kind of string returned by `navigator.userAgent` or given in the `user-agent` request header
*/
export function gotUserAgent(userAgent: string) {
if (userAgent.toLowerCase().includes('windows')) setFlagEngine('flag-icons')
}

export function localeFlags(locale: Locale) {
function localeFlagsEmojis(locale: Locale) {
const parts = locale
.toLowerCase()
.split('-', 3)
.slice(0, 2)
.map((code) => flagCodeExceptions[code] || toEmoji(code))
.map(
(code) =>
flagEmojiExceptions[code] ||
String.fromCodePoint(...Array.from(code).map((k) => k.charCodeAt(0) + 127365))
)
return parts[0] === parts[1] ? [parts[0]] : parts
}

function localeFlagsIcons(locale: Locale) {
function createSpan(code: string) {
return `<span class="fi fi-${code}"></span>`
}
const parts = locale
.toLowerCase()
.split('-', 2)
.map((code) => createSpan(flagClassExceptions[code] || code))
return parts[0] === parts[1] ? [parts[0]] : parts
}

/**
* Gets one or two html strings representing the flags for the given locale (2 in case of `en-US` for example)
* @param locale The locale
* @param engine Optional: specify wether the targeted system is windows or not (if not, just use emojis)
* @returns
*/
export function localeFlags(locale: Locale, engine?: 'emojis' | 'flag-icons'): string[] {
return (engine ?? flagEngine) === 'emojis' ? localeFlagsEmojis(locale) : localeFlagsIcons(locale)
}
4 changes: 2 additions & 2 deletions test/specifics.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
bulkObject,
reports,
localeFlags,
flagCodeExceptions,
flagEmojiExceptions,
parse,
stringify
} from '~/s-a'
Expand Down Expand Up @@ -91,7 +91,7 @@ describe('specifics', () => {
expect(localeFlags('en')).toEqual(['๐Ÿ‡ฌ๐Ÿ‡ง'])
expect(localeFlags('en-GB')).toEqual(['๐Ÿ‡ฌ๐Ÿ‡ง'])
expect(localeFlags('en-US-gb')).toEqual(['๐Ÿ‡ฌ๐Ÿ‡ง', '๐Ÿ‡บ๐Ÿ‡ธ'])
flagCodeExceptions.en = '๐Ÿด๓ ง๓ ข๓ ฅ๓ ฎ๓ ง๓ ฟ'
flagEmojiExceptions.en = '๐Ÿด๓ ง๓ ข๓ ฅ๓ ฎ๓ ง๓ ฟ'
expect(localeFlags('en-GB')).toEqual(['๐Ÿด๓ ง๓ ข๓ ฅ๓ ฎ๓ ง๓ ฟ', '๐Ÿ‡ฌ๐Ÿ‡ง'])
expect(localeFlags('fr')).toEqual(['๐Ÿ‡ซ๐Ÿ‡ท'])
expect(localeFlags('fr-FR')).toEqual(['๐Ÿ‡ซ๐Ÿ‡ท'])
Expand Down

0 comments on commit 06b7722

Please sign in to comment.