Created
June 26, 2018 05:54
-
-
Save vtno/cecf4263759bc255ae4fc62ae5257996 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Bind it to click event of that specific button. | |
const buildFormFromTemplateBtn = (evt: Event, | |
addBtn: HTMLAnchorElement, | |
editorIdx: number, | |
isNewVersion: boolean = false) => { | |
if (evt.target instanceof window.HTMLAnchorElement) { | |
// Swap in the time to generate new unique key for a form input. | |
const time: number = new Date().getTime() | |
const uniqueId = addBtn.getAttribute('data-id') || '' | |
const regex: RegExp = new RegExp(uniqueId, 'g') | |
const templateString: string = addBtn.getAttribute('data-template-for-insertion') || '' | |
const uniqueTemplateString: string = templateString.replace(regex, time.toString()) | |
const form: HTMLDivElement = document.createElement('div') | |
const htmlTemplate = stringToHtml(uniqueTemplateString) | |
if (htmlTemplate) { | |
form.innerHTML = htmlTemplate | |
if (!isNewVersion) { | |
const input: HTMLInputElement = ((form.querySelector('input[type="text"], textarea'): any): HTMLInputElement) | |
if (input) { | |
input.value = '' | |
} | |
} | |
// make sure new input is empty | |
const positionInput = ((form.querySelector('.position-input'): any): HTMLInputElement) | |
if (positionInput) { | |
// Index start from 0 so -1 | |
const nextPosition: ?number = countEditorContent(editorIdx) - 1 | |
positionInput.value = String(nextPosition) | |
} | |
return form.firstChild | |
} else { | |
throw new FormTemplateError('Cannot parsed template string from Rails: DynamicFormHelper') | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment