Created
September 15, 2019 20:29
-
-
Save MingweiSamuel/82d65b3199ded3637f4277a788fdab55 to your computer and use it in GitHub Desktop.
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
function onOpen() { | |
const ui = DocumentApp.getUi(); | |
// Or DocumentApp or FormApp. | |
ui.createAddonMenu() | |
.addItem('Invert Selected', 'doInvertSelected') | |
.addToUi(); | |
} | |
function invertColor(val) { | |
return '#' + ('00000' + (0xFFFFFF - parseInt(val.substr(1), 16)).toString(16)).substr(-6); | |
} | |
function doInvertSelected() { | |
const doc = DocumentApp.getActiveDocument(); | |
const selection = doc.getSelection(); | |
if (!selection) | |
return; | |
const rangeElements = selection.getRangeElements(); | |
for (const rangeElement of rangeElements) { | |
const element = rangeElement.getElement(); | |
rinvert(element); | |
} | |
} | |
function rinvert(element) { | |
if (element.getNumChildren) { | |
console.log(element.getNumChildren()); | |
for (let i = 0; i < element.getNumChildren(); i++) { | |
rinvert(element.getChild(i)); | |
} | |
return; | |
} | |
const oldStyle = element.getAttributes(); | |
const oldBackground = oldStyle[DocumentApp.Attribute.BACKGROUND_COLOR]; | |
const style = {}; | |
if (oldBackground) { | |
style[DocumentApp.Attribute.BACKGROUND_COLOR] = invertColor(oldBackground); | |
} | |
element.setAttributes(style); | |
if (element.getForegroundColor) { | |
for (let i = 0; i < element.getText().length; i++) { | |
element.setForegroundColor(i, i, invertColor(element.getForegroundColor(i))); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment