Skip to content

Commit

Permalink
feat/add custom key naming pattern (#117)
Browse files Browse the repository at this point in the history
  • Loading branch information
VetalLozik committed Jan 12, 2023
1 parent e1158f6 commit 245c74f
Show file tree
Hide file tree
Showing 6 changed files with 161 additions and 23 deletions.
4 changes: 3 additions & 1 deletion assets/texts.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"overrideTranslationsSaved": "Override translations flag updated",
"contentSegmentationSaved": "Content segmentation flag updated",
"stringsKeyNamingSaved": "Key naming pattern option updated",
"stringsCustomKeyNamingSaved": "Key naming pattern option updated",
"credentialsSaved": "Credentials saved",
"stringsUploadedToCrowdin": "Strings were successfully pushed to Crowdin. You can now either pre-translate them via Machine Translation engines or invite translators to your Crowdin project",
"creatingNewDirectory": "Creating new directory",
Expand Down Expand Up @@ -131,7 +132,8 @@
"pseudoLocalizationPrefixSuffixLabel": "Prefix/Suffix",
"pseudoLocalizationPrefixSuffixText": "Allows you to add special characters at the beginning and end of each string.",
"pseudoLocalizationCharacterTransformationLabel": "Character Transformation",
"pseudoLocalizationCharacterTransformationText": "Are foreign language character sets displayed correctly in your application? Character Transformation replaces English characters with easily identifiable accented versions, random Arabic symbols, or Chinese ideographs to make it obvious if there are some hard-coded strings in your application. This ensures that your application is ready to be localized into other languages (including right-to-left and left-to-right ones)."
"pseudoLocalizationCharacterTransformationText": "Are foreign language character sets displayed correctly in your application? Character Transformation replaces English characters with easily identifiable accented versions, random Arabic symbols, or Chinese ideographs to make it obvious if there are some hard-coded strings in your application. This ensures that your application is ready to be localized into other languages (including right-to-left and left-to-right ones).",
"customKeyNamingPattern": "Custom Key Naming Pattern"
},
"details": {
"translationsDetails": "Generate multi-language creative assets like banners or social media graphics. Send designs for translation and upload translated copies back.",
Expand Down
42 changes: 40 additions & 2 deletions src/action/settings.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import ui from 'sketch/ui';
import dom from 'sketch/dom';
import settings from 'sketch/settings';
import { capitalize, snakeCase } from 'lodash';
import {
ACCESS_TOKEN_KEY,
PROJECT_ID,
Expand All @@ -10,7 +11,8 @@ import {
DEFAULT_STRINGS_KEY_NAMING_OPTION,
KEY_NAMING_PATTERN,
STRINGS_KEY_NAMING_OPTIONS,
BRANCH_ID
BRANCH_ID,
CUSTOM_KEY_NAMING_PATTERN
} from '../constants';
import { default as displayTexts } from '../../assets/texts.json';
import * as domUtil from '../util/dom';
Expand Down Expand Up @@ -92,6 +94,39 @@ function saveKeyPatternOption(value) {
ui.message(displayTexts.notifications.info.stringsKeyNamingSaved);
}

function saveCustomKeyPattern(value) {
settings.setSettingForKey(CUSTOM_KEY_NAMING_PATTERN, value);
ui.message(displayTexts.notifications.info.stringsCustomKeyNamingSaved);
}

function getCustomKeyPattern() {
const customKey = settings.settingForKey(CUSTOM_KEY_NAMING_PATTERN);
return customKey
}

const keyNaming = {
artboard: ({ page }) => `${snakeCase(page)}`,
Artboard: ({ page }) => `${capitalize(snakeCase(page))}`,
group: ({ frame }) => `${snakeCase(frame)}`,
Group: ({ frame }) => `${capitalize(snakeCase(frame))}`,
element_name: ({ element }) => `${snakeCase(element)}`,
Element_name: ({ element }) => `${capitalize(snakeCase(element))}`,
};

const getSearchHelperList = (value) => {
let substring = null;
const helpers = [];
Object.keys(keyNaming).forEach((el) => {
const lastIndex = value.lastIndexOf("[%");
substring = lastIndex === -1 ? null : value.substring(lastIndex + 2, value.length);
if (el.indexOf(substring) !== -1) {
helpers.push(el);
}
});

return helpers;
};

function saveCredentials(creds) {
const token = settings.settingForKey(ACCESS_TOKEN_KEY);
let initValue = undefined;
Expand Down Expand Up @@ -177,5 +212,8 @@ export {
saveBranch,
logout,
isArtboardSelected,
fileFormats
fileFormats,
saveCustomKeyPattern,
getSearchHelperList,
getCustomKeyPattern
};
4 changes: 3 additions & 1 deletion src/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export const BRANCH_ID = `${KEY_PREFIX}-branch-id`;
export const OVERRIDE_TRANSLATIONS = `${KEY_PREFIX}-override-translations`;
export const CONTENT_SEGMENTATION = `${KEY_PREFIX}-content-segmentation`;
export const KEY_NAMING_PATTERN = `${KEY_PREFIX}-key-naming`;
export const CUSTOM_KEY_NAMING_PATTERN = `${KEY_PREFIX}-custom-key-naming`;

export const SYMBOL_TYPE = 'symbol-override';
export const TEXT_TYPE = 'text';
Expand All @@ -30,7 +31,8 @@ export const STRINGS_KEY_NAMING_OPTIONS = [
{ id: 14, name: 'artboard::element_name' },
{ id: 15, name: 'artboard__element_name' },
{ id: 16, name: 'element_name' },
{ id: 17, name: 'Element text' }
{ id: 17, name: 'Element text' },
{ id: 18, name: 'Custom key naming pattern' }
];

export const DEFAULT_STRINGS_KEY_NAMING_OPTION = 16;
8 changes: 7 additions & 1 deletion src/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ import {
saveKeyPatternOption,
logout,
isArtboardSelected,
fileFormats
fileFormats,
saveCustomKeyPattern,
getSearchHelperList,
getCustomKeyPattern
} from './action/settings';

const identifier = 'crowdin';
Expand Down Expand Up @@ -63,6 +66,9 @@ export default function start() {
browserWindow.webContents.on('saveContentSegmentation', saveContentSegmentation);
browserWindow.webContents.on('getKeyPatternOptions', getKeyPatternOptions);
browserWindow.webContents.on('saveKeyPatternOption', saveKeyPatternOption);
browserWindow.webContents.on('saveCustomKeyPatternOption', saveCustomKeyPattern);
browserWindow.webContents.on('getSearchHelperList', getSearchHelperList);
browserWindow.webContents.on('getCustomKeyPattern', getCustomKeyPattern);
browserWindow.webContents.on('logout', logout);

//data
Expand Down
109 changes: 91 additions & 18 deletions ui/plugin.html
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,15 @@
<p crowdin-ui-text-label="stringsKeyNamingText" class="form-text text-muted help-text">
</p>
</div>
<div class="form-group" style="position: relative">
<label crowdin-ui-text-label="customKeyNamingPattern"></label>
<input type="text" class="form-control" id="customKeyNamingPattern"
onchange="saveCustomKeyNaming()" oninput="handleHelperList()" disabled placeholder="e.g. [%Artboard].[%group].[%element_name]">
<div id="custom-naming-helper-list" class="custom-naming-helper-list">
</div>
<p crowdin-ui-text-label="stringsKeyNamingText" class="form-text text-muted help-text">
</p>
</div>
<div class="form-group">
<div class="inline-select d-flex flex-row">
<label crowdin-ui-text-label="selectBranchLabel"></label>
Expand Down Expand Up @@ -477,7 +486,6 @@
</body>

<script>

const editableFileTypes = [
"csv",
"resx",
Expand All @@ -492,13 +500,16 @@
"yaml"
];

var openedModal;
const CUSTOM_KEY_NAMING_PATTERN = "Custom key naming pattern";

let openedModal;
//initialization of the settings modal
showLoading();
getCredentials()
.then(getOverrideTranslations)
.then(getContentSegmentation)
.then(getKeyNamingOptions)
.then(getCustomKeyPatternValue)
.then(getProjects)
.then(getBranches)
.finally(() => {
Expand All @@ -525,18 +536,18 @@
});
}, 100);

var validationMessages = {};
var allLanguagesOption;
var noBranchOption;
let validationMessages = {};
let allLanguagesOption;
let noBranchOption;

var projectsInfo;
var sourceLanguage;
var languages;
var strings;
var files;
var labels;
var openedString;
var selectedText = [];
let projectsInfo;
let sourceLanguage;
let languages;
let strings;
let files;
let labels;
let openedString;
let selectedText = [];

//basic functions

Expand Down Expand Up @@ -571,10 +582,15 @@
case 'settings':
cancelEditString();
cancelPseudoLocalization();
openSettingsTab();
break;
}
}

function openSettingsTab() {
$('#custom-naming-helper-list').hide()
}

function contactUsClick() {
window.postMessage('contactUs');
}
Expand Down Expand Up @@ -672,10 +688,47 @@
}

function saveKeyNamingOption() {
const text = $('#stringsKeyNaming option:selected').text();
$('#customKeyNamingPattern').attr('disabled', text != CUSTOM_KEY_NAMING_PATTERN);
const option = Number($('#stringsKeyNaming option:selected').val());
return window.postMessage('saveKeyPatternOption', option);
}

function saveCustomKeyNaming() {
const text = $('#customKeyNamingPattern').val();
return window.postMessage('saveCustomKeyPatternOption', text);
}

function handleHelperList() {
const text = $('#customKeyNamingPattern').val();
window.postMessage("getSearchHelperList", text).then(renderCustomNamingHelpers);
}

function onClikToHelperText(el) {
const customKeyInputValue = $('#customKeyNamingPattern').val();
const lastIndex = customKeyInputValue.lastIndexOf("[%");
const substring = customKeyInputValue.substring(0, lastIndex + 2) + `${$(el).text()}]`;
$('#customKeyNamingPattern').val(substring);
window.postMessage('saveCustomKeyPatternOption', substring);
$('#custom-naming-helper-list').hide();

}

function renderCustomNamingHelpers (options) {
if(!options[0].length) {
$('#custom-naming-helper-list').hide()
return
}
$("#custom-naming-helper-list").empty()
$('#custom-naming-helper-list').show()
options[0].forEach(el => {
if(el) {
const listItem = `<p onclick="onClikToHelperText(this)">${el}<p>`
$('#custom-naming-helper-list').append(listItem);
}
})
}

//translation

function translateComponent(wholePage) {
Expand Down Expand Up @@ -1008,13 +1061,14 @@

function generateIdentifier(selectedTextElement, identifiers) {
const pattern = $('#stringsKeyNaming option:selected').text();
const customKeyPattern = $('#customKeyNamingPattern').val();
const artboardName = selectedTextElement.artboard.toLowerCase();
const groupName = selectedTextElement.group.toLowerCase();
const elementName = selectedTextElement.elementName.toLowerCase();
const artboardNameUpperCase = capitalizeFirstLetter(artboardName);
const groupNameUpperCase = capitalizeFirstLetter(groupName);
const elementNameUpperCase = capitalizeFirstLetter(elementName);
const identifier = smartReplace(pattern, {
const identifier = smartReplace(pattern, customKeyPattern, {
'Artboard': artboardNameUpperCase,
'artboard': artboardName,
'Group': groupNameUpperCase,
Expand All @@ -1037,7 +1091,16 @@
return uniqueIdentifier;
}

function smartReplace(pattern, obj) {
function smartReplace(pattern, customPattern, obj) {
if (pattern === CUSTOM_KEY_NAMING_PATTERN) {
const patterns = Object.keys(obj);
patterns.forEach((el) => {
if (customPattern.indexOf(`[%${el}]`) !== -1) {
customPattern = customPattern.replaceAll(`[%${el}]`, obj[el]);
}
});
return customPattern;
}
const replacing = {};
for (let x in obj) {
if (pattern.indexOf(x) > -1) {
Expand Down Expand Up @@ -1403,6 +1466,9 @@
const options = info[0];
const html = options.map(o => {
if (o.selected) {
if(o.name === CUSTOM_KEY_NAMING_PATTERN){
$('#customKeyNamingPattern').attr('disabled', false);
}
return `<option value="${o.id}" selected>${o.name}</option>`;
} else {
return `<option value="${o.id}">${o.name}</option>`;
Expand All @@ -1412,6 +1478,13 @@
});
}

function getCustomKeyPatternValue() {
return window.postMessage('getCustomKeyPattern')
.then(value => {
$('#customKeyNamingPattern').val(value)
});
}

function getSourceLanguage() {
if (!sourceLanguage) {
return window.postMessage('getSourceLanguage')
Expand Down Expand Up @@ -1550,8 +1623,8 @@
function getBranches() {
return window.postMessage('getBranches')
.then(res => {
var resp = res[0];
var selectedBranch = resp.selectedBranchId;
let resp = res[0];
let selectedBranch = resp.selectedBranchId;
let options = `<option value="-1" ${selectedBranch < 0 ? 'selected' : ''}>${noBranchOption || ''}</option>`;
options += resp.branches
.map(br => {
Expand All @@ -1565,7 +1638,7 @@
});
}

var searchTimer;
let searchTimer;
function debounceSearch() {
clearTimeout(searchTimer);
searchTimer = setTimeout(search, 700);
Expand Down
17 changes: 17 additions & 0 deletions ui/styles.scss
Original file line number Diff line number Diff line change
Expand Up @@ -530,6 +530,23 @@ p {
color: var(--labelSecondary) !important;
}

#custom-naming-helper-list {
background-color: var(--buttonSecondaryBGColor);
padding: 16px 8px;
border-radius: 2px;
margin: 0;
z-index: 1000;
overflow-x: overlay;
overflow-y: auto;
width: 100%;
position: absolute;
p {
cursor: pointer;
margin-bottom: 8px;
color: var(--labelPrimary);
}
}

.help-text {
font-size: 0.75rem;
line-height: 1.25;
Expand Down

0 comments on commit 245c74f

Please sign in to comment.