Skip to content

feat: clear translation cache #39

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 30 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,32 @@ window.resetTranslation(

---

### 5. 🗑️ Clear Cache with `window.clearCache()`

Clear translation cache from localStorage. You can clear cache for all languages or selectively for specific languages:

#### Clear All Languages Cache

```js
window.clearCache([], () => {
console.log('All translation cache cleared successfully');
}, (err) => {
console.error('Error clearing cache:', err);
}); // Clears all translation cache
```

#### Clear Specific Languages Cache

```js
window.clearCache(['es', 'fr', 'de'], () => {
console.log('Cache cleared for Spanish, French, and German');
}, (err) => {
console.error('Error clearing cache:', err);
}); // Clear cache for specific languages only
```

----------

### ✅ Tips:

- Both `translate()` and `resetTranslation()` can be used to build your own custom language selector.
Expand All @@ -444,7 +470,7 @@ The widget determines which language to display using the following priority ord
| 2 | User preference (selected language) | Language the user selects in the widget |
| 3 | `pageLanguage` (default page language) | The default language set for the page |

### 5. Font Size Adjustment
### 6. Font Size Adjustment

The translation widget automatically adjusts font sizes when translating text to prevent overflow issues. This is particularly useful when translating to languages that typically have longer text lengths. The font size adjustment works as follows:

Expand All @@ -457,8 +483,10 @@ The translation widget automatically adjusts font sizes when translating text to
- Original font sizes are preserved and restored when resetting translations

The font size adjustment is automatic and requires no additional configuration. It helps maintain readability while preventing text overflow in translated content.


### 7. 🚀 Faster and More Accurate than Google Translate

### 6. 🚀 Faster and More Accurate than Google Translate

Our engine offers **contextual accuracy** and **lower latency**, especially for dynamic content.

Expand Down
13 changes: 13 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,19 @@ <h2>Customer Stories</h2>
</p>
</article>
</section>

<button onclick="window.translate('hi', (res)=>{
console.log(res);
}, (err)=>{
console.log(err);
})" class="tw-button notranslate">Translate to hindi</button>

<button onclick="window.resetTranslation('en', (res)=>{
console.log(res);
})">Reset Translio</button>
<button onclick="window.clearCache([])" class="button button-secondary">Clear Cache</button>


</main>
<script defer src="http://localhost:5173/dist/index.min.js"></script>
<script defer type="module">
Expand Down
13 changes: 11 additions & 2 deletions src/lib/storage/localstorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,10 +108,19 @@ export class LocalStorageWrapper {
delete this.cache[key]; // Invalidate the cache for this key
}

clear(): void {
clear(lang_code: string[] = []): void {
if (this.prefix) {
for (let key in localStorage) {
if (key.startsWith(this.prefix)) {
if (
key.startsWith(this.prefix) &&
(!lang_code.length || lang_code.includes(key.split("--")[1]))
) {
localStorage.removeItem(key);
}
}
} else if (lang_code && lang_code.length > 0) {
for (let key in localStorage) {
if (lang_code.includes(key.split("--")[1])) {
localStorage.removeItem(key);
delete this.cache[key];
}
Expand Down
23 changes: 22 additions & 1 deletion src/widget/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1130,6 +1130,7 @@ declare global {
onError?: (error: Error) => void
) => void;
translate: (langCode: string, onComplete?: (result: TranslationResult) => void, onError?: (error: Error) => void) => Promise<TranslationResult>;
clearCache: (lang_code:string[], onComplete?: () => void, onError?: (error: Error) => void) => void;
}
}

Expand All @@ -1139,7 +1140,7 @@ if (typeof window !== "undefined") {
* @param defaultLang The default language to reset to
* @param onComplete Callback function that will be called when the translation is complete
* @param onError Callback function that will be called if the translation fails
* @returns A promise that resolves to the translation result
* @returns void
*/
window.resetTranslation = (
defaultLang: string,
Expand Down Expand Up @@ -1199,4 +1200,24 @@ if (typeof window !== "undefined") {
};
}
};

/**
* @param langArr Array of language codes to clear cache for. Empty array clears all languages.
* @param onComplete Callback function that will be called when the translation is complete
* @param onError Callback function that will be called if the translation fails
* @returns void
*/
window.clearCache = (
lang_code: string[] = [],
onComplete?: () => void,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Currently, the clear() function removes all cached translations from localStorage. I’d like to add an optional lang_code parameter—if provided, it should only clear the cache for that specific language. If not provided, it should continue to clear everything as before.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

alright will add this

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've added this as well.

just one thing, when clearing cache for specific language it doesn't clear jss-pref. Let me know if u want to clear this as well.

onError?: (error: Error) => void
) => {
const localStorageWrapper = new LocalStorageWrapper(CACHE_PREFIX);
try {
localStorageWrapper.clear(lang_code);
onComplete?.();
} catch (error) {
onError?.(error as Error);
}
};
}