DeepL API—Office Add-in Starter Snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
name: Blank snippet | |
description: Create a new snippet from a blank template. | |
host: WORD | |
api_set: {} | |
script: | |
content: > | |
/* | |
MIT License | |
Copyright 2022 DeepL SE (https://www.deepl.com) | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all | |
copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
SOFTWARE. | |
*/ | |
/* | |
Thank you Marvin Becker (https://github.com/derwebcoder) for contributing this gist! | |
Provide your API key here. | |
You can find it here after logging in: https://www.deepl.com/account/summary | |
If you need to create an API account, you can do so here: https://www.deepl.com/pro-api | |
Don't forget to remove the key if you share your snippet with others. | |
*/ | |
const apiKey = ""; | |
/* | |
======================== | |
Section: HTML elements | |
======================== | |
*/ | |
async function tryCatch(callback) { | |
try { | |
await callback(); | |
} catch (error) { | |
console.error(error); | |
} | |
} | |
const selectElements: Record<LanguageRequest["type"], HTMLSelectElement> = { | |
source: document.querySelector("select#language-from"), | |
target: document.querySelector("select#language-to") | |
}; | |
const iframeElement: HTMLIFrameElement = | |
document.querySelector("iframe#preview"); | |
/* | |
======================== | |
Section: Utilities | |
======================== | |
*/ | |
/** | |
* Load the supported languages, create an <option> element for each and append it to the corresponding <select> element that already exists in the HTML file | |
*/ | |
const hydrateLanguageDropdown = async (type: LanguageRequest["type"]) => { | |
let languages = await fetchLanguages(type); | |
// For each language create an <option> element | |
languages.forEach((lang) => { | |
const option = document.createElement("option"); | |
option.setAttribute("value", lang.language); | |
option.innerHTML = lang.name; | |
selectElements[type].append(option); | |
}); | |
// For convenience set the target language to the interface language | |
if (type === "target") { | |
setDefaultTargetLanguage(languages); | |
} | |
}; | |
/** | |
* For convenience we can set the target language automatically to the users interface language. | |
* If we don't support a matching language we just default to the first of the list. | |
*/ | |
const setDefaultTargetLanguage = (languages: LanguagesResponse) => { | |
const interfaceLanguage = Office.context.displayLanguage.toUpperCase(); | |
if (languages.find((l) => l.language === interfaceLanguage)) { | |
selectElements["target"].value = interfaceLanguage; | |
} else { | |
selectElements["target"].value = languages[0].language; | |
} | |
}; | |
/** | |
* For some reason Office adds control characters to the string. We have to remove them otherwise they would end up in the translation. | |
*/ | |
const cleanOfficeHTML = (htmlString: string) => { | |
return htmlString.replace(/[\u0000-\u001F\u007F-\u009F]/g, " "); | |
}; | |
/* | |
======================== | |
Section: DeepL API | |
======================== | |
*/ | |
/** | |
* Fetching the list of supported languages. | |
* * @see https://www.deepl.com/docs-api/general/get-languages/ | |
*/ | |
const fetchLanguages = async (type: LanguageRequest["type"]): | |
Promise<LanguagesResponse> => { | |
try { | |
const response = await fetch(`https://api.deepl.com/v2/languages?auth_key=${apiKey}`, { | |
method: "POST", | |
headers: { | |
Accept: "*/*", | |
"Content-Type": "application/x-www-form-urlencoded" | |
}, | |
body: `auth_key=${apiKey}&type=${type}` | |
}); | |
if (!response.ok) { | |
if (response.status === 403) { | |
throw new Error("Your API key is invalid. Try another one."); | |
} | |
throw new Error( | |
`API returned error code ${response.status}. See https://www.deepl.com/docs-api/api-access/error-handling/.` | |
); | |
} | |
return await response.json(); | |
} catch (e) { | |
throw new Error(`Fetching languages failed. ${e}`); | |
} | |
}; | |
/** | |
* Fetching the translation for a given HTML input and languages. | |
* @see https://www.deepl.com/docs-api/translate-text/translate-text/ | |
*/ | |
const fetchTranslation = async (text: string, targetLang: string, | |
sourceLang?: string): Promise<string> => { | |
try { | |
const response = await fetch(`https://api.deepl.com/v2/translate?auth_key=${apiKey}`, { | |
method: "POST", | |
headers: { | |
Accept: "*/*", | |
"Content-Type": "application/x-www-form-urlencoded" | |
}, | |
body: `auth_key=${apiKey}&text=${encodeURIComponent(text)}&source_lang=${encodeURIComponent( | |
sourceLang | |
)}&target_lang=${encodeURIComponent(targetLang)}&tag_handling=html` // we want to handle HTML | |
}); | |
const result: TranslationReponse = await response.json(); | |
return result.translations[0].text; | |
} catch (e) { | |
throw new Error("Fetching translation failed"); | |
} | |
}; | |
/* | |
======================== | |
Section: TypeScript types | |
======================== | |
Some simple TypeScript types for convenience | |
These are not complete and stripped to our use case | |
*/ | |
type LanguageRequest = { | |
type: "source" | "target"; | |
}; | |
type LanguagesResponse = Array<{ | |
language: string; | |
name: string; | |
}>; | |
type TranslationReponse = { | |
translations: Array<{ | |
text: string; | |
}>; | |
}; | |
/* | |
======================== | |
Section: Main | |
======================== | |
*/ | |
Office.onReady((info) => { | |
// First we want to hydrate our view | |
tryCatch(async () => { | |
await hydrateLanguageDropdown("source"); | |
await hydrateLanguageDropdown("target"); | |
}); | |
Word.run(async (context) => { | |
// Add an event listener for when the user selects something | |
Office.context.document.addHandlerAsync(Office.EventType.DocumentSelectionChanged, () => { | |
// Get the selected text (in HTML format) | |
Office.context.document.getSelectedDataAsync<string>(Office.CoercionType.Html, (asyncResult) => { | |
tryCatch(async () => { | |
iframeElement.setAttribute("srcdoc", "loading ..."); | |
// if receiving the selected text failed for some reason stop right here | |
if (asyncResult.status === Office.AsyncResultStatus.Failed) { | |
iframeElement.setAttribute("srcdoc", "Getting the selected text failed."); | |
throw new Error("Action failed. Error: " + asyncResult.error.message); | |
} | |
const cleanedHTML = cleanOfficeHTML(asyncResult.value); | |
try { | |
// load the translation for the selected text | |
// note that in the fetchTranslation function we have set the API parameter of `tag_handling` to `html` | |
const translation = await fetchTranslation( | |
cleanedHTML, | |
selectElements["target"].value, | |
selectElements["source"].value | |
); | |
// set the iframe content with the translation | |
iframeElement.setAttribute("srcdoc", translation); | |
} catch (e) { | |
// if something fails show an error message | |
iframeElement.setAttribute("srcdoc", e); | |
} | |
}); | |
}); | |
}); | |
}); | |
}); | |
language: typescript | |
template: | |
content: "<section>\n\t<div id=\"languages\">\n\t\t<select id=\"language-from\">\n <option value=\"\">(automatic)</option>\n </select>\n\t\t<span>></span>\n\t\t<select id=\"language-to\">\n </select>\n\t</div>\n\n\t<iframe id=\"preview\"></iframe>\n</section>" | |
language: html | |
style: | |
content: |- | |
html, body { | |
margin: 0; | |
padding: 0; | |
background: #ececec; | |
} | |
section { | |
display: grid; | |
grid-template-rows: 32px 1fr; | |
gap: 8px; | |
height: 100vh; | |
align-items: center; | |
padding: 12px; | |
box-sizing: border-box; | |
} | |
#languages { | |
display: grid; | |
grid-template-columns: 1fr 24px 1fr; | |
} | |
#languages span { | |
text-align: center; | |
} | |
iframe { | |
height: 100%; | |
width: 100%; | |
background: white; | |
border: 1px solid #c6c6c6; | |
padding: 0 10px; | |
box-sizing: border-box; | |
} | |
language: css | |
libraries: | | |
https://appsforoffice.microsoft.com/lib/1/hosted/office.js | |
@types/office-js |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment