Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- let fgLayer = null
- const keypresses = {}
- const l = console.log
- class Styles {
- constructor(layer) {
- this.text = layer.textStyleId
- this.color = layer.fillStyleId
- }
- }
- const getStyles = (layer) => {
- return new Styles(layer)
- }
- const styles = {
- get color() {
- return new Styles(fSelected()).color
- },
- get text() {
- return new Styles(fSelected()).text
- }
- }
- function isNumeric(str) {
- if (typeof str != "string") return false // we only process strings!
- return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...
- !isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail
- }
- alphabet = {
- getCharCodes(lower=true) {
- const addValue = lower ? 97 : 65
- const emptyArray = Array.from(Array(26))
- return emptyArray.map((e, i) => i + addValue)
- },
- generateAlphabesArray(lower=true) {
- const charCodes = this.getCharCodes(lower)
- return charCodes.map((x) => String.fromCharCode(x))
- },
- get lower() {
- return this.generateAlphabesArray(lower=true)
- },
- get upper() {
- return this.generateAlphabesArray(lower=false)
- }
- }
- const selected = () => figma.currentPage.selection
- const sleep = delay => new Promise(resolve => setTimeout(resolve, delay));
- const select = (arrayLayers) => {
- figma.currentPage.selection = arrayLayers
- }
- const getStrDate = () => {
- date = new Date()
- d = date.getDate()
- mm = date.getMonth()
- y = date.getFullYear()
- h = date.getHours()
- m = date.getMinutes()
- s = date.getSeconds()
- return `${d}.${mm}.${y} ${h}:${m}:${s}`
- }
- // Object.prototype.__defineGetter__(
- // 'values',
- // function() {
- // return Object.values(this)
- // }
- // )
- // Object.prototype.__defineGetter__(
- // 'keys',
- // function() {
- // return Object.keys(this)
- // }
- // )
- const fSelected = () => {
- return figma.currentPage.selection[0]
- }
- const replaceWithRandomNumbers = async(min, max) => {
- let allNumbers = []
- while(allNumbers.length < selected().length){
- let numberReplaceWith = getRandomNmber(min, max)
- numberReplaceWith = String(numberReplaceWith)
- if(allNumbers.indexOf(numberReplaceWith) === -1) allNumbers.push(numberReplaceWith);
- }
- for (let number = 0; number < selected().length; number++) {
- await figma.loadFontAsync(selected()[number].fontName)
- selected()[number].characters = allNumbers[number]
- }
- }
- const randomizeHotCold = () => {
- let bools = createRandomBooArray(80)
- let hot = figma.getNodeById("41:149")
- let cold = figma.getNodeById("41:155")
- let swapWith
- for (let frame = 0; frame < selected().length; frame++) {
- if (bools[frame] === true) {
- swapWith = hot
- } else {
- swapWith = cold
- }
- selected()[frame].children.slice(-1)[0].swapComponent(swapWith)
- }
- }
- class Archive {
- constructor() {
- this.id = null
- this.page = this.find()
- this.exists = Boolean(this.page)
- this.create()
- this.notEmpty = this.page.findChild(e => e)
- this.placeholderNode = this.createPlaceholderNode()
- }
- find() {
- const archive = figma.root.findChild(
- e => e.type == "PAGE" && e.name == "Archive"
- )
- if (archive) this.id = archive.id
- return archive
- }
- create() {
- if (this.exists) return
- this.page = figma.createPage()
- this.page.name = "Archive"
- this.id = this.page.id
- }
- createPlaceholderNode() {
- /*
- In case there were no layers in archive
- It should have been better implemented
- but there is no time for that,
- and it works
- so I'm leaving it as is
- */
- if (this.notEmpty) return
- const placeholderNode = figma.createRectangle()
- this.page.appendChild(placeholderNode)
- return placeholderNode
- }
- removePlaceholder() {
- if (!this.placeholderNode) return
- this.placeholderNode.remove()
- }
- }
- const createRandomBooArray = (amount) => {
- let allNumbers = []
- while(allNumbers.length < amount){
- let number = getRandomNmber(0, amount)
- allNumbers.push(number)
- }
- let allBools = []
- for (number of allNumbers) {
- if (number % 2 === 0) {
- allBools.push(true)
- } else {
- allBools.push(false)
- }
- }
- return allBools
- }
- const getRandomNmber = (min, max) => {
- number = Math.random() * (max - min) + min
- return Math.floor(number);
- }
- const doublePressed = (event) => {
- key = event.key
- if (!keypresses[key]) {
- keypresses[key] = Date.now()
- return false
- }
- difference = Date.now() - keypresses[key]
- if (difference < 1000) {
- delete keypresses[key]
- return true
- } else {
- delete keypresses[key]
- return false
- }
- }
- const operators = {
- '+': function(a) { return a + 1 },
- '-': function(a) { return a - 1 },
- };
- const revertResize = (currentlySelectedLayers, resizeDirection, horizontalOrVerical="horizontal") => {
- for (let x=0; x<currentlySelectedLayers.length; x++) {
- let currentlySelectedLayerWidth = currentlySelectedLayers[x].width
- let currentlySelectedLayerHeight = currentlySelectedLayers[x].height
- if (horizontalOrVerical == "vertical") {
- if (currentlySelectedLayers[x].type === "LINE") {continue}
- currentlySelectedLayers[x].resize(currentlySelectedLayerWidth, operators[resizeDirection](currentlySelectedLayerHeight))
- continue
- }
- currentlySelectedLayers[x].resize(operators[resizeDirection](currentlySelectedLayerWidth), currentlySelectedLayerHeight)
- }
- }
- const collapseParentOf = (currentlySelectedLayer) => {
- let parent = currentlySelectedLayer.parent
- try {
- figma.currentPage.selection = [parent]
- parent.expanded = false
- } catch {
- currentlySelectedLayer.expanded = false
- }
- }
- const ToggleCurrentLayerCollapsion = () => {
- selectedLayer = fSelected()
- if ( selectedLayer.expanded == undefined ) {
- select([selectedLayer.parent])
- selectedLayer.parent.expanded = !selectedLayer.parent.expanded
- return
- }
- selectedLayer.expanded = !selectedLayer.expanded
- }
- const selectFirstLayerInGroup = () => {
- let nodeToSelect = figma.currentPage.selection[0].children.slice(-1)[0] // last
- figma.currentPage.selection = [nodeToSelect]
- nodeToSelect.expanded = false
- }
- const toggleTextBoundBox = async() => {
- textLayer = figma.currentPage.selection[0]
- await figma.loadFontAsync(textLayer.fontName)
- if (textLayer.textAutoResize != "WIDTH_AND_HEIGHT") {
- textLayer.textAutoResize = "WIDTH_AND_HEIGHT"
- } else {
- textLayer.textAutoResize = "HEIGHT"
- }
- }
- const getNextLayer = (parentChildren, nextLayer, event) => {
- layerToSelect = [parentChildren[nextLayer]]
- layersToSelect = layerToSelect.concat(figma.currentPage.selection)
- let layersToSelectSatuses = {}
- for (layer of layersToSelect) {
- let layerStatus = layer.expanded
- layersToSelectSatuses[layer.id] = layerStatus
- }
- if (event.altKey) {
- figma.currentPage.selection = layersToSelect
- } else {
- figma.currentPage.selection = [layersToSelect[0]]
- }
- for (layer of layersToSelect) {
- let layerStatus = layersToSelectSatuses[layer.id]
- node = figma.getNodeById(layer.id)
- node.expanded = layerStatus
- }
- }
- const getPrevLayer = (parentChildren, previousLayer, event) => {
- layerToSelect = [parentChildren[previousLayer]]
- layersToSelect = layerToSelect.concat(figma.currentPage.selection)
- l(layersToSelect)
- let layersToSelectSatuses = {}
- for (layer of layersToSelect) {
- let layerStatus = layer.expanded
- layersToSelectSatuses[layer.id] = layerStatus
- }
- if (event.altKey) {
- figma.currentPage.selection = layersToSelect
- } else {
- figma.currentPage.selection = [layersToSelect[0]]
- }
- for (layer of layersToSelect) {
- let layerStatus = layersToSelectSatuses[layer.id]
- node = figma.getNodeById(layer.id)
- node.expanded = layerStatus
- }
- }
- // const getPrevLayer = (parentChildren, previousLayer, event) => {
- // layerToSelect = [parentChildren[previousLayer]]
- // layersToSelect = figma.currentPage.selection.concat(layerToSelect)
- // let layersToSelectSatuses = {}
- // for (layer of layersToSelect) {
- // let layerStatus = layer.expanded
- // layersToSelectSatuses[layer.id] = layerStatus
- // }
- // if (event.altKey) {
- // figma.currentPage.selection = layersToSelect
- // } else {
- // figma.currentPage.selection = [layersToSelect[0]]
- // }
- // for (layer of layersToSelect) {
- // let layerStatus = layersToSelectSatuses[layer.id]
- // node = figma.getNodeById(layer.id)
- // node.expanded = layerStatus
- // }
- // }
- const getLayer = (order="next", event) => {
- selection = figma.currentPage.selection
- if (order == "next") {
- selection = selection[0]
- } else {
- selection = selection[selection.length-1]
- }
- parent = selection.parent
- parentChildren = parent.children
- selectionId = selection.id
- orderOfSelectedLayerInGroup = 0
- for (let x = 0; x<=parentChildren.length; x++) {
- if (parentChildren[x].id == selectionId) {
- break
- }
- orderOfSelectedLayerInGroup += 1
- }
- nextLayer = orderOfSelectedLayerInGroup - 1
- previousLayer = orderOfSelectedLayerInGroup + 1
- if (order == "next") {
- getNextLayer(parentChildren, nextLayer, event)
- } else {
- getPrevLayer(parentChildren, previousLayer, event)
- }
- }
- const revertFixedHeightTextLayer = async(currentlySelectedLayers) => {
- for (let x=0; x<currentlySelectedLayers.length; x++) {
- currentlySelectedLayer = currentlySelectedLayers[x]
- if (currentlySelectedLayer.type == "TEXT") {
- await figma.loadFontAsync(currentlySelectedLayer.fontName)
- textAutoResize = localStorage.getItem(currentlySelectedLayer.id);
- currentlySelectedLayer.textAutoResize = textAutoResize
- }
- }
- }
- const saveTextLayerProperty = async(currentlySelectedLayers, event) => {
- for (let x=0; x<currentlySelectedLayers.length; x++) {
- currentlySelectedLayer = currentlySelectedLayers[x]
- if (currentlySelectedLayer.type == "TEXT") {
- await figma.loadFontAsync(currentlySelectedLayer.fontName)
- localStorage.setItem(currentlySelectedLayer.id, currentlySelectedLayer.textAutoResize);
- }
- }
- }
- const resetVerticalAlignment = () => {
- selected()[0].textAlignVertical = "TOP"
- }
- const fixPositionOfLayerWhichWasTakenOutOfGroup = (previousProperties) => {
- fSelected().x = previousProperties.parent.x + previousProperties.x
- fSelected().y = previousProperties.parent.y + previousProperties.y
- }
- const getOutLayerOfTheGroup = () => {
- layerToGetOut = figma.getNodeById(selected()[0].id)
- layers = layerToGetOut.parent.parent.children
- ids = layers.map(layer => layer.id)
- layerIndex = ids.indexOf(layerToGetOut.parent.id)
- layerToGetOut.parent.parent.insertChild(layerIndex+1, layerToGetOut)
- }
- const pasteY = (rect) => {
- rectSmall = selected()[0]
- rectSmall.y = rect.y + rect.height + 144
- rectSmall.x = rect.x
- }
- const align = () => {
- previouslySelected = selected()[0]
- let focusSwitched = setInterval(function() {
- if (previouslySelected.id != selected()[0].id) {
- pasteY(previouslySelected)
- clearInterval(focusSwitched);
- }
- }, 100); // check every 100ms
- }
- const copyPastePosition = () => {
- positions = localStorage.getItem('positions')
- if (positions && positions != null) {
- positions = JSON.parse(positions)
- selected()[0].x = positions.x
- selected()[0].y = positions.y
- localStorage.removeItem('positions')
- } else {
- x = selected()[0].x
- y = selected()[0].y
- let xy = {"x": x, "y": y}
- positions = JSON.stringify(xy)
- localStorage.setItem('positions', positions)
- }
- }
- document.addEventListener('keydown', function(event) {
- if (event.ctrlKey && event.key === 't') {
- resetVerticalAlignment()
- }
- });
- document.addEventListener('keydown', function(event) {
- if (event.ctrlKey && event.key != 'ArrowDown' && event.key != 'ArrowUp' && event.key != 'ArrowLeft') {
- let currentlySelectedLayers = figma.currentPage.selection
- saveTextLayerProperty(currentlySelectedLayers, event)
- }
- });
- document.addEventListener('keydown', function(event) {
- if (event.ctrlKey && event.key === 'ArrowLeft') {
- let currentlySelectedLayers = figma.currentPage.selection
- revertResize(currentlySelectedLayers, "+")
- collapseParentOf(currentlySelectedLayers[0])
- revertFixedHeightTextLayer(currentlySelectedLayers)
- }
- });
- document.addEventListener('keydown', function(event) {
- if (event.shiftKey && event.key === 'Ç') {
- ToggleCurrentLayerCollapsion()
- }
- });
- document.addEventListener('keydown', function(event) {
- if (event.ctrlKey && event.key === 'ArrowRight') {
- let currentlySelectedLayers = figma.currentPage.selection
- revertResize(currentlySelectedLayers, "-")
- selectFirstLayerInGroup()
- }
- });
- document.addEventListener('keydown', function(event) {
- if (event.shiftKey && event.altKey && event.key === 'ˇ') {
- toggleTextBoundBox()
- }
- });
- document.addEventListener('keydown', function(event) {
- if (event.ctrlKey && event.key === 'ArrowUp') {
- let currentlySelectedLayers = figma.currentPage.selection
- revertResize(currentlySelectedLayers, "+", horizontalOrVerical="vertical")
- getLayer("prev", event)
- revertFixedHeightTextLayer(currentlySelectedLayers)
- }
- });
- document.addEventListener('keydown', function(event) {
- if (event.ctrlKey && event.key === 'ArrowDown') {
- let currentlySelectedLayers = figma.currentPage.selection
- revertResize(currentlySelectedLayers, "-", horizontalOrVerical="vertical")
- getLayer("next", event)
- revertFixedHeightTextLayer(currentlySelectedLayers)
- event.stopPropagation()
- }
- });
- document.addEventListener('keyup', function(event) {
- if (event.key === 'Enter') {
- let layer = figma.currentPage.selection[0]
- if (layer.name == "bg") {
- layer.name = "Background"
- }
- }
- });
- document.addEventListener('keydown', function(event) {
- if (event.ctrlKey && event.key === 'a') {
- align()
- }
- });
- document.addEventListener('keydown', function(event) {
- if (event.shiftKey && event.key === 'G') {
- if (doublePressed(event)) {
- // previousProperties = {x: fSelected().x, y: fSelected().y, parent: fSelected().parent}
- getOutLayerOfTheGroup()
- // fixPositionOfLayerWhichWasTakenOutOfGroup(previousProperties)
- }
- }
- });
- document.addEventListener('keydown', function(event) {
- if (event.shiftKey && event.key === '~') {
- copyPastePosition()
- }
- });
- const exportImageAsync = async(layer) => {
- return await layer.exportAsync({format: "PNG", constraint: { type: "SCALE", value: 4 }})
- }
- const sendNotification = async(message, hideAfterSeconds=1000) => {
- let notification = document.createElement("p")
- notification.innerText = message
- notification.style.textAlign = "center"
- notification.style.padding = "0px 0 0px 0"
- notification.style.zIndex = "100"
- notification.style.position = 'fixed'
- notification.style.width = '0%'
- notification.style.height = '48px'
- notification.style.lineHeight = '48px'
- notification.style.color = 'white'
- notification.style.background = 'blue'
- notification.style.overflow = 'hidden'
- notification.style.left = '50%'
- notification.style.transform = 'translateX(-50%)'
- notification.style.fontFamily = 'Roboto'
- notification.classList.add('notificationCustom')
- let parent = document.getElementById("fullscreen-body")
- parent.insertBefore(notification, parent.firstChild);
- await sleep(hideAfterSeconds);
- notification.remove()
- }
- const copyImage = async() => {
- const image = await exportImageAsync(fSelected())
- const blob = new Blob([image.buffer], { type: 'image/png' })
- const clipimage = new ClipboardItem({
- 'image/png': blob
- })
- navigator.clipboard.write([clipimage])
- figma.notify("Image copied to clipboard :)")
- }
- const downloadImage = async() => {
- for ( layer of selected() ) {
- const image = await exportImageAsync(layer)
- const link = document.createElement( 'a' );
- link.style.display = 'none';
- document.body.appendChild( link );
- const blob = new Blob( [ image ], { type: 'text/plain' } );
- const objectURL = URL.createObjectURL( blob );
- link.href = objectURL;
- link.href = URL.createObjectURL( blob );
- fileName = `${layer.name}.png`
- link.download = fileName;
- link.click();
- const data = [new ClipboardItem({ [blob.type]: blob })]
- await navigator.clipboard.write(data)
- }
- }
- document.addEventListener('keydown', function(event) {
- if (event.shiftKey && event.ctrlKey && event.key === 'E') {
- downloadImage()
- }
- });
- document.addEventListener('keydown', function(event) {
- if (event.ctrlKey && event.altKey && event.which === 69) {
- copyImage()
- }
- });
- const markApproved = () => {
- layer = selected()[0]
- if (layer.name.includes("✅✅ ")) {
- layer.name = layer.name.replace("✅✅ ", "")
- } else if (layer.name.charAt(0) == "✅") {
- layer.name = "✅" + layer.name
- } else {
- layer.name = "✅ " + layer.name
- }
- }
- document.addEventListener('keydown', function(event) {
- if (event.shiftKey && event.key === ' ') {
- markApproved()
- }
- });
- const saveFgLayer = () => {
- fgLayer = fSelected()
- }
- const pasteSelectedLayerOverCopiedLayer = () => {
- bgLayer = fSelected()
- bgLayer.parent
- bgParentChildren = bgLayer.parent.children
- orderOfSelectedLayerInGroup = 0
- for (let x = 0; x<bgParentChildren.length; x++) {
- l(bgParentChildren[x])
- if (bgParentChildren[x].id == bgLayer.id) {
- break
- }
- orderOfSelectedLayerInGroup += 1
- }
- bgLayer.parent.insertChild(orderOfSelectedLayerInGroup+1, fgLayer)
- figma.currentPage.selection = [fgLayer]
- }
- document.addEventListener('keydown', function(event) {
- if (event.altKey && event.shiftKey && event.key === 'Ç') {
- l("layerindexcopied")
- saveFgLayer()
- }
- });
- document.addEventListener('keydown', function(event) {
- if (event.altKey && event.shiftKey && event.key === '◊') {
- l("layerindexpasted")
- pasteSelectedLayerOverCopiedLayer()
- }
- });
- const increaseSpace = () => {
- let selection = selected()
- selection = [].concat(selection)
- selection.sort(function(a, b) {return a.x - b.x})
- let addBy = 1
- for (let layer = 1; layer < selection.length; layer++) {
- l(selection[layer].name)
- selection[layer].x = selection[layer].x + addBy
- addBy += 1
- }
- }
- const decreaseSpace = () => {
- let selection = selected()
- selection = [].concat(selection)
- selection.sort(function(a, b) {return a.x - b.x})
- let subtractBy = 1
- for (let layer = 1; layer < selection.length; layer++) {
- l(selection[layer].name)
- selection[layer].x = selection[layer].x - subtractBy
- subtractBy += 1
- }
- }
- const increaseSpaceVertical = () => {
- let selection = selected()
- selection = [].concat(selection)
- selection.sort(function(a, b) {return a.y - b.y})
- let subtractBy = 1
- for (let layer = 1; layer < selection.length; layer++) {
- l(selection[layer].name)
- selection[layer].y = selection[layer].y + subtractBy
- subtractBy += 1
- }
- }
- const decreaseSpaceVertical = () => {
- let selection = selected()
- selection = [].concat(selection)
- selection.sort(function(a, b) {return a.y - b.y})
- let subtractBy = 1
- for (let layer = 1; layer < selection.length; layer++) {
- l(selection[layer].name)
- selection[layer].y = selection[layer].y - subtractBy
- subtractBy += 1
- }
- }
- document.addEventListener('keydown', function(event) {
- if (event.altKey && event.key === '≠') {
- increaseSpace()
- }
- else if (event.altKey && event.key === '–') {
- decreaseSpace()
- }
- else if (event.altKey && event.key === '‘') {
- increaseSpaceVertical()
- }
- else if (event.altKey && event.key === '“') {
- decreaseSpaceVertical()
- }
- });
- // document.addEventListener('keydown', function(event) {
- // if (event.ctrlKey && event.key === 'u') {
- // const layer = figma.union(selected(), fSelected().parent)
- // figma.currentPage.selection = [layer]
- // } else if (event.ctrlKey && event.key === 's') {
- // const layer = figma.subtract(selected(), fSelected().parent)
- // figma.currentPage.selection = [layer]
- // }
- // })
- document.addEventListener('keydown', function(event) {
- if (!(event.ctrlKey)) return
- const booleanOperations = {u: figma.union, s: figma.subtract}
- if (!(Object.keys(booleanOperations).includes(event.key))) return
- let operation = booleanOperations[event.key]
- let layer = operation(selected(), fSelected().parent)
- figma.currentPage.selection = [layer]
- })
- // document.addEventListener('keydown', function(event) {
- // const operatorsDecimal = {
- // x: {
- // 'ArrowRight': function() { return fSelected().x - 0.9 },
- // 'ArrowLeft': function() { return fSelected().x + 0.9 }
- // },
- // y: {
- // 'ArrowUp': function() { return fSelected().y - 0.9 },
- // 'ArrowDown': function() { return fSelected().y + 0.9 },
- // }
- // }
- // if (!event.altKey) return
- // fSelected().x = operatorsDecimal.x[event.key]()
- // fSelected().y = operatorsDecimal.y[event.key]()
- // });
- // document.addEventListener('keydown', function(event) {
- // if (event.shiftKey) return
- // const operatorsDecimal = {
- // x: {
- // 'ArrowRight': function() { return Math.round(fSelected().x * 10)/10 - 0.9 },
- // 'ArrowLeft': function() { return Math.round(fSelected().x * 10)/10 + 0.9 }
- // },
- // y: {
- // 'ArrowUp': function() { return Math.round(fSelected().y * 10)/10 + 0.9 },
- // 'ArrowDown': function() { return Math.round(fSelected().y * 10)/10 - 0.9 },
- // }
- // }
- // for (let i of Object.keys(operatorsDecimal)) {
- // if (!(event.altKey && event.ctrlKey && Object.keys(operatorsDecimal[i]).includes(event.key))) continue
- // if (Object.keys(operatorsDecimal[i]).includes(event.key)){
- // fSelected()[i] = operatorsDecimal[i][event.key]()
- // }
- // }
- // });
- let previouslySelected = null
- previouslySelectedArray = []
- previouslySelectedArrayLastTen = []
- let focusSwitched = setInterval(function() {
- if (fSelected() == undefined) return
- if (previouslySelected == null) {
- previouslySelected = fSelected()
- }
- if (previouslySelected.id != fSelected().id) {
- previouslySelected = fSelected()
- }
- currentlySelected = selected().map(el => el.id).toString()
- wasPreviouslySelected = previouslySelectedArray.map(el => el.id).toString()
- if (currentlySelected == wasPreviouslySelected) return
- previouslySelectedArray = selected()
- if (fSelected().parent.id != '638:3349') {
- previouslySelectedArrayLastTen.push(...previouslySelectedArray)
- if (previouslySelectedArrayLastTen.length > 10) {
- previouslySelectedArrayLastTen = previouslySelectedArrayLastTen.slice(Math.max(previouslySelectedArrayLastTen.length - 10, 0))
- }
- }
- l("changed")
- }, 100); // check every 100ms
- const getBottomLayerOfArchive = () => {
- archive = new Archive().page
- children = [ ...archive.children]
- children.sort(function(a, b) {return a.y - b.y})
- bottomLayer = children.slice(-1)[0]
- return bottomLayer
- }
- const getRightLayerOfArchive = () => {
- archive = new Archive().page
- children = [ ...archive.children]
- children.sort(function(a, b) {return a.x - b.x})
- rightLayer = children.slice(-1)[0]
- return rightLayer
- }
- const getDateFromStr = (str) => {
- str = str.split("|").slice(-1)[0].split(" ").filter(el => el != "")
- let dateLayer = str[0]
- return dateLayer
- }
- const dateOfBottomLayerIsDifferent = () => {
- let dateAndTimeLayer = getRightLayerOfArchive().name
- let dateLayer = getDateFromStr(dateAndTimeLayer)
- let currentDate = getDateFromStr(getStrDate())
- return !( [currentDate, dateLayer].every((val, i, arr) => val == arr[0]) )
- }
- const getFurthestXLayerX = (layers) => {
- let biggestXLayerValue = Number.NEGATIVE_INFINITY
- let biggestXLayer = null
- for (const layer of layers) {
- if ( layer.x > biggestXLayerValue ) {
- biggestXLayerValue = layer.x
- biggestXLayer = layer
- }
- }
- return biggestXLayer.x
- }
- const getXCoordToPutNewDayLayer = () => {
- const dateAndTimeLayer = getRightLayerOfArchive()
- const layers = archive.findAll(
- layer => layer.name.includes(
- getDateFromStr(dateAndTimeLayer.name)
- )
- )
- const widths = layers.map(layer => layer.width)
- const maxWidth = Math.max(...widths)
- const furthestXLayerX = getFurthestXLayerX(layers)
- return furthestXLayerX + maxWidth + 500
- }
- document.addEventListener("keydown", function(event) {
- if (event.which == 8 && event.shiftKey && event.altKey) {
- if (
- // selected().length && selected().map((el) => el.type).every( (val, i, arr) => {l(val); return val === arr[0] && (val == "FRAME" && arr[0] == "FRAME")})
- selected().length
- ) {
- const archive = new Archive
- for (layer of selected()) {
- layer.name = layer.name + " | " + getStrDate()
- rightLayer = getRightLayerOfArchive()
- if (dateOfBottomLayerIsDifferent() ) {
- archive.page.appendChild(layer)
- layer.x = getXCoordToPutNewDayLayer()
- layer.y = 5915
- } else {
- archive.page.appendChild(layer)
- layer.x = rightLayer.x
- layer.y = rightLayer.y + rightLayer.height + 200
- }
- }
- archive.removePlaceholder()
- /*^ in case there were no layers in archive */
- figma.currentPage.selection = []
- }
- }
- });
- // let dateTimeWorkdayIsFinished = new Date('September 17, 2021 00:36:00');
- // let timeLeft = new Date( dateTimeWorkdayIsFinished - Date.now()).toISOString().substr(11, 8)
- // document.title = timeLeft
- let timeLeftToEndWorkday = setInterval(function() {
- let dateTimeWorkdayIsFinished = new Date('September 18, 2021 01:17:00');
- if (dateTimeWorkdayIsFinished - Date.now() < 0) {
- return
- }
- let timeLeft = new Date( dateTimeWorkdayIsFinished - Date.now()).toISOString().substr(11, 8)
- document.title = timeLeft
- }, 1000)
- const layerInCurrentPage = (layer) => {
- if (!(layer)) return
- layer = figma.currentPage.findAll(l => l.id === layer.id)
- return Boolean(layer.length)
- }
- // while
- // figmaIsLoaded = () => {
- // try {
- // figma
- // return true
- // } catch {
- // return false
- // }
- // }
- // while (true) {
- // if ( figmaIsLoaded() ) {
- // Object.prototype.select = function() {figma.currentPage.selection = [this]}
- // }
- // }
- // document.addEventListener('keydown', function(event) {
- // if (!(event.ctrlKey && event.key === 'Enter')) return
- // for (layer of previouslySelectedArray.reverse()) {
- // if (layerInCurrentPage(layer)) {
- // figma.currentPage.
- // }
- // }
- // })
- const isSpeacialCharAndNotNumber = (inputString) => {
- return inputString
- .match(/^[^a-zA-Z]+$/)
- ? true : false
- }
- const enumerate = (array) => {
- return array.map((item, index) => [index, item])
- }
- const insertAfterFirsItemOfArray = (array, value) => {
- const newArray = [
- array[0], value, ...array.slice(1)
- ]
- return newArray
- }
- const fakeTranslateReplacementForWord = (charObject) => {
- if (charObject.isSpecialOrNumber) {
- return charObject.char
- } else {
- return charObject.fakeTranslateReplacement
- }
- }
- const defineCharToAdd = (wordObject) => {
- if (wordObject.isAllUpper) return "P"
- return "v"
- }
- const fakeTranslateReplacementForStr = (wordObject) => {
- let word
- if (wordObject.wholeWordIsSpecialCharOrNumber) {
- word = wordObject.fakeTranslateReplacement
- word = word.join("")
- return word
- }
- const fakeTranslateReplacement = wordObject.fakeTranslateReplacement
- let amountCharsToAdd = 12 - wordObject.length.nonSpecial
- if (amountCharsToAdd < 0) amountCharsToAdd = 0
- const charToAdd = defineCharToAdd(wordObject)
- const charsToAdd = charToAdd.repeat(amountCharsToAdd)
- word = insertAfterFirsItemOfArray(fakeTranslateReplacement, charsToAdd)
- word = word.join("")
- return word
- }
- const convertStrToStrObject = (inputString) => {
- const strObject = {}
- strObject.string = inputString
- strObject.fakeTranslateReplacement = ""
- const words = inputString.split(" ")
- const wordObjects = []
- for (let [wordOrder, word] of enumerate(words)) {
- const wordObject = {}
- wordObject.word = word
- wordObject.fakeTranslateReplacement = []
- wordObject.specialCharInWord = false
- wordObject.isLast = wordOrder == words.length-1
- wordObject.isAllUpper = false
- wordObject.wholeWordIsSpecialCharOrNumber = false
- wordObject.length = {}
- wordObject.length.total = word.length
- wordObject.length.nonSpecial = 0
- wordObject.length.special = 0
- wordObject.chars = []
- word = Array.from(word)
- for (const [charOrder, char] of enumerate(word)) {
- const speacialChar = isSpeacialCharAndNotNumber(char)
- wordObject.length.nonSpecial += ( () => !speacialChar ? 1 : 0 )()
- wordObject.length.special += ( () => speacialChar ? 1 : 0 )()
- wordObject.specialCharInWord = speacialChar
- strObject.specialCharInStr = speacialChar
- const charObject = {}
- charObject.char = char
- charObject.fakeTranslateReplacement = ""
- charObject.isSpecialOrNumber = speacialChar
- charObject.isLast = charOrder == word.length-1
- charObject.isUpper = char == char.toUpperCase()
- charObject.fakeTranslateReplacement = charObject.isUpper ? "P" : "v"
- charObject.charOrder = charOrder
- wordObject.chars.push(charObject)
- }
- wordObject.fakeTranslateReplacement = wordObject.chars.map(
- charObject => (fakeTranslateReplacementForWord(charObject))
- )
- wordObject.isAllUpper = (
- wordObject.chars
- .every(char => char.isUpper)
- )
- wordObject.wholeWordIsSpecialCharOrNumber = (
- wordObject.chars
- .every(char => char.isSpecialOrNumber)
- )
- wordObjects.push(wordObject)
- }
- strObject.wordObjects = wordObjects
- let strFakeTranslateReplacement = strObject.wordObjects.map(
- word => ( fakeTranslateReplacementForStr(word) )
- )
- strFakeTranslateReplacement = strFakeTranslateReplacement.join(" ")
- strObject.fakeTranslateReplacement = strFakeTranslateReplacement
- return strObject
- }
- const fakeTranslate = async() => {
- await figma.loadFontAsync( fSelected().fontName )
- const layersText = fSelected().characters
- const StrObject = convertStrToStrObject(layersText)
- fSelected().name = layersText
- fSelected().characters = StrObject.fakeTranslateReplacement
- }
- const revertTranslate = async() => {
- await figma.loadFontAsync( fSelected().fontName )
- fSelected().characters = fSelected().name
- }
- document.addEventListener('keydown', function(event) {
- /* option + shift + L */
- if (event.shiftKey && event.altKey && event.which === 76) {
- l("FAKE traaaaanslate")
- fakeTranslate()
- }
- });
- document.addEventListener('keydown', function(event) {
- if (event.shiftKey && event.altKey && event.key === '') {
- revertTranslate()
- }
- });
- const collapseAllCollapsableLayers = () => {
- const page = figma.currentPage
- const filterFunction = (layer) => {
- return layer.expanded != undefined
- }
- const collapsableLayers = page.findAll(filterFunction)
- for (const layer of collapsableLayers) {
- layer.expanded = false
- }
- }
- const controlOptionC = {
- get pressed() {
- return (
- event.which == 67 &&
- event.altKey &&
- event.ctrlKey
- )
- }
- }
- document.addEventListener('keydown', function(event){
- if (controlOptionC.pressed) {
- collapseAllCollapsableLayers()
- }
- })
- const getElementsByPartialClassName = (part) => {
- return document.querySelectorAll(`[class*=${part}]`)
- }
- const updateSelectedItemsCounter = (cls='selectedCounter') => {
- setInterval(function(){
- try {
- const counter = document.querySelector(`.${cls}`)
- counter.innerText = figma.currentPage.selection.length
- } catch {}
- }, 100)
- }
- const addCounterToToolBar = (
- cls='selectedCounter',
- innerText="Selected",
- width="100px"
- ) => {
- const counterShell = document.createElement('div')
- counterShell.style.width = width
- counterShell.style.background = "black"
- counterShell.style.padding = "10px 10px 10px 0px"
- counterShell.style.textAlign = "right"
- counterShell.style.borderRadius = "6px"
- counterShell.style.marginRight = "6px"
- counterShell.style.position = "relative"
- const counterText = document.createElement('span')
- counterText.classList.add(cls)
- try {
- counterText.innerText = figma.currentPage.selection.length
- } catch {
- counterText.innerText = "0"
- }
- const infoText = document.createElement('span')
- infoText.innerText = innerText
- infoText.style.position = "absolute"
- infoText.style.left = "10px"
- infoText.style.color = "#bbbbbb"
- counterShell.appendChild(counterText)
- counterShell.appendChild(infoText)
- toolBar = getElementsByPartialClassName('toolbar_view--sideButtonGroup')[1]
- toolBar.appendChild(counterShell)
- updateSelectedItemsCounter()
- }
- document.addEventListener('keydown', async function(event){
- if (!(event.metaKey && event.which == 190)) return
- await sleep(100)
- addCounterToToolBar()
- })
- const shiftAsterisk = {
- get pressed() {
- return (
- event.which == 192 &&
- event.shiftKey
- )
- }
- }
- function *iterateOverSelected() {
- addCounterToToolBar(cls='mmessage', innerText='iterated', width="150px")
- const iteratedCounter = document.querySelector(".mmessage")
- document.addEventListener('keydown', () => {
- if (!shiftAsterisk.pressed) return
- iteratedCounter.parentNode.remove()
- })
- let sel
- let order = 0
- for (const layer of sel = selected()) {
- if (order == 0) {
- console.log(
- "document.addEventListener(" +
- " 'keydown', function(e) {" +
- " if (e.key == \"`\") {" +
- " s.next()" +
- " }})"
- )
- }
- select([layer])
- figma.viewport.scrollAndZoomIntoView([layer])
- order++
- const message = `${order} / ${sel.length}`
- console.log(message)
- iteratedCounter.innerText = message
- yield layer
- }
- return iteratedCounter.parentNode.remove()
- }
- const commandOptionG = {
- get pressed() {
- return (
- event.which == 71 &&
- event.altKey &&
- event.metaKey
- )
- }
- }
- document.addEventListener('keydown', function(event){
- if (!commandOptionG.pressed) return
- if (fSelected().fills.some(fill => fill.visible)) return
- fSelected().fills = []
- })
- let selectedNodes = ""
- const getFrameToSelect = (arraySwitch) => {
- const toReturn = arraySwitch ? 1 : 0
- arraySwitch = !arraySwitch
- return toReturn
- }
- const switchFrameViews = () => {
- if (selected().length <= 1) return
- let arraySwitch
- if ( selectedNodes != selected().map(e => e.id).join("") ) {
- arraySwitch = true
- selectedNodes = selected().map(e => e.id).join("")
- } else {
- arraySwitch = false
- selectedNodes = ""
- }
- let frameToSelect = getFrameToSelect(arraySwitch)
- frameToSelect = selected()[frameToSelect]
- figma.viewport.scrollAndZoomIntoView([frameToSelect])
- figma.viewport.zoom = 1
- return frameToSelect
- }
- document.addEventListener('keydown', (event) => {
- if (!(event.which == 27 && event.shiftKey)) return
- switchFrameViews()
- })
- const alignLayersVertically = (verticalSpaceInPixels=200) => {
- let height = 0
- const layers = Array.from( selected() ).sort(e => e.y)
- for (layer of layers) {
- layer.y = layers[0].y + height
- height += layer.height + verticalSpaceInPixels
- }
- }
- const figmaFunctions = {
- "alignLayersVertically(verticalSpaceInPixels: string = 200)": {
- "howToUse": [
- `Select layers i want to align verically
- with 200px
- `
- ],
- use(verticalSpaceInPixels=200) {
- alignLayersVertically(verticalSpaceInPixels)
- }
- }
- }
- /* Move layers without cursor hold (as in Sketch) start */
- const mousePositions = {
- initial: {
- x: null,
- y: null
- },
- end: {
- x: 0,
- y: 0
- }
- }
- const releasedKeys = {
- Alt: false,
- Control: false
- }
- const pressedKeys = {
- Shift: false
- }
- let selectedLayers = []
- let selectedLayerXs = []
- let selectedLayerYs = []
- const trackCursorAndMoveLayers = (event) => {
- if (mousePositions.initial.x == null) {
- mousePositions.initial.x = event.clientX
- mousePositions.initial.y = event.clientY
- }
- mousePositions.end.x = event.clientX
- mousePositions.end.y = event.clientY
- let reduceByX = (mousePositions.initial.x - mousePositions.end.x) * 1 / figma.viewport.zoom
- let reduceByY = (mousePositions.initial.y - mousePositions.end.y) * 1 / figma.viewport.zoom
- /*
- * 1 / figma.viewport.zoom
- To deal with different scale of the Figma's viewport
- */
- // console.log(Math.abs(reduceByX), Math.abs(reduceByY))
- if (pressedKeys.Shift) {
- if( Math.abs(reduceByX) > Math.abs(reduceByY) ) {
- reduceByY = 0
- } else if( Math.abs(reduceByY) > Math.abs(reduceByX) ) {
- reduceByX = 0
- }
- }
- /*
- To move layers with Shift key pressed
- */
- for (let selectedLayer = 0; selectedLayer < selectedLayers.length; selectedLayer++) {
- selectedLayers[selectedLayer].x = Math.round(selectedLayerXs[selectedLayer] - reduceByX)
- selectedLayers[selectedLayer].y = Math.round(selectedLayerYs[selectedLayer] - reduceByY)
- }
- }
- const setLayerToMove = (event) => {
- if (event.key == 'Shift') {
- pressedKeys.Shift = true
- }
- if (!(event.altKey && event.ctrlKey)) return // 3 keys are pressed
- selectedLayers = figma.currentPage.selection
- if (!selectedLayers.length) return
- for (let selectedLayer = 0; selectedLayer < selectedLayers.length; selectedLayer++) {
- selectedLayerXs.push(selectedLayers[selectedLayer].x)
- selectedLayerYs.push(selectedLayers[selectedLayer].y)
- }
- document.addEventListener('mousemove', trackCursorAndMoveLayers )
- }
- const unsetLayerToMove = (event) => {
- if (!(event.key == 'Alt' || event.key == 'Control' || event.key == 'Shift')) return
- releasedKeys[event.key] = true
- pressedKeys.Shift = false
- if (!(releasedKeys.Alt == true && releasedKeys.Control == true)) return // 3 keys are released
- releasedKeys.Alt = false
- releasedKeys.Control = false
- selectedLayers = []
- selectedLayerXs = []
- selectedLayerYs = []
- document.removeEventListener('mousemove', trackCursorAndMoveLayers )
- mousePositions.initial.x = null
- mousePositions.initial.y = null
- }
- document.addEventListener('keydown', setLayerToMove )
- document.addEventListener('keyup', unsetLayerToMove )
- /* Move layers without cursor hold (as in Sketch) end */
- let view = {
- page: null,
- center: null,
- zoom: null
- }
- const bookmarkView = () => {
- view.page = figma.currentPage
- view.center = figma.viewport.center
- view.zoom = figma.viewport.zoom
- sendNotification("View bookmarked")
- }
- const gotoBookmarkedView = () => {
- if (view.page == null) {
- sendNotification("Bookmark view first")
- return
- }
- figma.currentPage = view.page
- figma.viewport.center = view.center
- figma.viewport.zoom = view.zoom
- sendNotification("Switched to bookmarked view")
- }
- const pressedKeysForBookmark = {
- 32: false, // space
- }
- const doBookmarkAction = (event) => {
- if (![32, 66, 71].includes(event.which)) return
- pressedKeysForBookmark[event.which] = true
- if (!pressedKeysForBookmark[32]) return
- switch (event.which) {
- case 66:
- bookmarkView()
- break
- case 71:
- gotoBookmarkedView()
- break
- }
- }
- const updatePressedKeys = (event) => {
- if (!(event.which == 32)) return
- pressedKeysForBookmark[32] = false
- }
- document.addEventListener('keydown', doBookmarkAction )
- document.addEventListener('keyup', updatePressedKeys )
- const keysPressedForBgRename = {
- 66: { // B
- isPressed: false,
- timestamp: Infinity
- },
- 71: { // G
- isPressed: false,
- timestamp: Infinity
- },
- }
- const renameToBg = (event) => {
- if (event.which == 66 || event.which == 71) {
- keysPressedForBgRename[event.which].isPressed = true
- keysPressedForBgRename[event.which].timestamp = event.timeStamp
- // console.log('rename', fSelected());
- if (
- Object.values(keysPressedForBgRename)
- .every(v => v.isPressed) &&
- Math.abs(
- keysPressedForBgRename[66].timestamp -
- keysPressedForBgRename[71].timestamp
- ) < 100
- ) {
- keysPressedForBgRename[66].isPressed = false
- keysPressedForBgRename[71].isPressed = false
- if (
- fSelected() &&
- ['RECTANGLE', 'ELLIPSE']
- .includes(fSelected().type)
- ) {
- fSelected().name = 'Background'
- }
- }
- return
- }
- keysPressedForBgRename[66].isPressed = false
- keysPressedForBgRename[71].isPressed = false
- }
- document.addEventListener('keydown', renameToBg)
- /* Batch rename layers START */
- const insertCharsIntoChildrenName = (strToInsert = 'Note = false') => {
- for (child of fSelected().children) {
- addChars = []
- if (!child.name.endsWith(",") ) addChars.push(",")
- if (!child.name.endsWith(" ") ) addChars.push(" ")
- child.name = child.name +
- addChars.join("") + ' ' + strToInsert
- }
- }
- /* Batch rename layers END */
- const changeLineHeight = async (lineHeight, layerToChange = null) => {
- const selection = figma.currentPage.selection
- const selectedLayer = selection[0]
- const layer = layerToChange ?? selectedLayer
- if (!layer) return
- const fontName = layer.fontName
- await figma.loadFontAsync(fontName)
- const prevHeight = layer.height
- layer.lineHeight = {
- unit: "PIXELS",
- value: lineHeight
- }
- layer.y = Math.ceil( layer.y - ( ( layer.height - prevHeight ) / 2 ) )
- }
- const changeLineHeightOfSelected = (lineHeight) => {
- for (let layer of figma.currentPage.selection) {
- changeLineHeight(lineHeight, layer)
- }
- }
Add Comment
Please, Sign In to add comment