code
stringlengths
24
2.07M
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
92
language
stringclasses
1 value
repo
stringlengths
5
64
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
_focus() { this._checkEmptyValue() this.ieClipboardDivFocus = false this.focusHappening = true try { // IE requires a non-empty selection in order to fire the copy event, annoying this.input.value = ' ' this.input.focus() this.input.select() } finally { this.focusHappening = false } }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_focus
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_checkEmptyValue() { let value = this.input.value if(value.length > 0 && value !== ' ') { console.warn('The hidden input area is not empty, missed an event? Inserting now. Please report this to https://github.com/ritzyed/ritzy/issues/12. Value=', value) EditorActions.insertChars(value) this.input.value = ' ' } }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_checkEmptyValue
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_handleKeyArrow(e, key) { this._checkEmptyValue() if(key === 'left') { EditorActions.navigateLeft() } else if(key === 'right') { EditorActions.navigateRight() } else if(key === 'up') { EditorActions.navigateUp() } else if(key === 'down') { EditorActions.navigateDown() } return false }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_handleKeyArrow
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_handleKeySelectionArrow(e, key) { this._checkEmptyValue() if(key === 'shift+left') { EditorActions.selectionLeft() } else if(key === 'shift+right') { EditorActions.selectionRight() } else if(key === 'shift+up') { EditorActions.selectionUp() } else if(key === 'shift+down') { EditorActions.selectionDown() } return false }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_handleKeySelectionArrow
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_handleKeyBackspace() { this._checkEmptyValue() EditorActions.eraseCharBack() return false }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_handleKeyBackspace
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_handleKeyDelete() { this._checkEmptyValue() EditorActions.eraseCharForward() return false }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_handleKeyDelete
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_handleKeyWordBackspace() { this._checkEmptyValue() EditorActions.eraseWordBack() return false }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_handleKeyWordBackspace
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_handleKeyWordDelete() { this._checkEmptyValue() EditorActions.eraseWordForward() return false }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_handleKeyWordDelete
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_handleKeyNavigationPage(e, key) { if(key === 'pageup') { EditorActions.navigatePageUp() } else if(key === 'pagedown') { EditorActions.navigatePageDown() } return false }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_handleKeyNavigationPage
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_handleKeySelectionPage(e, key) { if(key === 'shift+pageup') { EditorActions.selectionPageUp() } else if(key === 'shift+pagedown') { EditorActions.selectionPageDown() } return false }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_handleKeySelectionPage
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_handleKeyNavigationHomeEnd(e, key) { if(key === 'mod+home') { EditorActions.navigateStart() } else if(key === 'home') { EditorActions.navigateStartLine() } else if(key === 'mod+end') { EditorActions.navigateEnd() } else if(key === 'end') { EditorActions.navigateEndLine() } return false }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_handleKeyNavigationHomeEnd
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_handleKeyNavigationWord(e, key) { this._checkEmptyValue() if(key === 'mod+left') { EditorActions.navigateWordLeft() } else if(key === 'mod+right') { EditorActions.navigateWordRight() } return false }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_handleKeyNavigationWord
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_handleKeySelectionHomeEnd(e, key) { if(key === 'mod+shift+home') { EditorActions.selectionStart() } else if(key === 'shift+home') { EditorActions.selectionStartLine() } else if(key === 'mod+shift+end') { EditorActions.selectionEnd() } else if(key === 'shift+end') { EditorActions.selectionEndLine() } return false }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_handleKeySelectionHomeEnd
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_handleKeySelectionWord(e, key) { if(key === 'shift+mod+left') { EditorActions.selectionWordLeft() } else if(key === 'shift+mod+right') { EditorActions.selectionWordRight() } return false }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_handleKeySelectionWord
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_handleKeySelectionAll() { EditorActions.selectionAll() return false }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_handleKeySelectionAll
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_handleKeyBold() { EditorActions.toggleBold() return false }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_handleKeyBold
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_handleKeyItalics() { EditorActions.toggleItalics() return false }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_handleKeyItalics
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_handleKeyUnderline() { EditorActions.toggleUnderline() return false }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_handleKeyUnderline
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_handleKeyStrikethrough() { EditorActions.toggleStrikethrough() return false }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_handleKeyStrikethrough
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_handleKeySuperscript() { EditorActions.toggleSuperscript() return false }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_handleKeySuperscript
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_handleKeySubscript() { EditorActions.toggleSubscript() return false }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_handleKeySubscript
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_onInputFocusLost() { if(!this.ieClipboardDivFocus) { EditorActions.inputFocusLost() } }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_onInputFocusLost
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_onInputFocusGained() { if(!this.focusHappening && !this.ieClipboardDivFocus && this.input === document.activeElement) { // regaining focus, perhaps the user switched windows and the browser is now focused again EditorActions.focusInput() } }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_onInputFocusGained
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_onCopy(e) { let copyHandler = window.clipboardData ? _.partial(this._handleIeCopy) : _.partial(this._handleNormalCopy, e) EditorActions.copySelection(copyHandler) }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_onCopy
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_onCut(e) { this._onCopy(e) EditorActions.eraseSelection() }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_onCut
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_handleNormalCopy(e, copiedText, copiedHtml, copiedRich) { e.clipboardData.setData(MIME_TYPE_TEXT_PLAIN, copiedText) e.clipboardData.setData(MIME_TYPE_TEXT_HTML, copiedHtml) // some browsers e.g. Chrome support arbitrary MIME types, makes paste way more efficient // Firefox allows setting the type, but not pasting it -- see https://bugzilla.mozilla.org/show_bug.cgi?id=860857 e.clipboardData.setData(MIME_TYPE_RITZY_RICH_TEXT, JSON.stringify(copiedRich)) e.preventDefault() e.stopPropagation() }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_handleNormalCopy
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_handleIeCopy(copiedText, copiedHtml) { window.clipboardData.setData('Text', copiedText) this.ieClipboardDiv.innerHTML = copiedHtml this._focusIeClipboardDiv() this._selectIeClipboardDivContents() setTimeout(() => { emptyNode(this.ieClipboardDiv) this._focus() }, 0) }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_handleIeCopy
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_onPaste(e) { this._checkEmptyValue() if(e.clipboardData.types) { this._handleNormalPaste(e) } else { // IE does not provide access to HTML in the paste event but does allow HTML to paste into a contentEditable // see http://stackoverflow.com/a/27279218/430128 this._handleIePaste() } }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_onPaste
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_handleNormalPaste(e) { let clipboardDataTypes if(e.clipboardData.types.findIndex) { clipboardDataTypes = e.clipboardData.types } else { // Firefox uses DOMStringList instead of an array type, convert it clipboardDataTypes = Array.from(e.clipboardData.types) } if(clipboardDataTypes.findIndex(t => t === MIME_TYPE_RITZY_RICH_TEXT) > -1) { let pasted = e.clipboardData.getData(MIME_TYPE_RITZY_RICH_TEXT) EditorActions.insertCharsBatch(JSON.parse(pasted)) } else if(clipboardDataTypes.findIndex(t => t === MIME_TYPE_TEXT_HTML) > -1) { let pasted = e.clipboardData.getData(MIME_TYPE_TEXT_HTML) let pastedChunks = parseHtml(pasted, this.hiddenContainer) EditorActions.insertCharsBatch(pastedChunks) } else if(clipboardDataTypes.findIndex(t => t === MIME_TYPE_TEXT_PLAIN) > -1) { let pasted = e.clipboardData.getData(MIME_TYPE_TEXT_PLAIN) EditorActions.insertChars(pasted) } else { console.warn('Paste not supported yet for types: ' + JSON.stringify(clipboardDataTypes)) } e.preventDefault() e.stopPropagation() }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_handleNormalPaste
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_handleIePaste() { setTimeout(() => { let pasted = this.ieClipboardDiv.innerHTML try { let pastedChunks = parseHtml(pasted, this.hiddenContainer) EditorActions.insertCharsBatch(pastedChunks) } finally { emptyNode(this.ieClipboardDiv) this._focus() } }, 0) }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_handleIePaste
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_focusIeClipboardDiv() { this.ieClipboardDivFocus = true this.ieClipboardDiv.focus() }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_focusIeClipboardDiv
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_selectIeClipboardDivContents() { let range = document.createRange() range.selectNodeContents(this.ieClipboardDiv) let selection = window.getSelection() selection.removeAllRanges() selection.addRange(range) }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_selectIeClipboardDivContents
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
_onChange(e) { // all character input, including IME events should trigger this event let value = e.target.value EditorActions.insertChars(value) e.target.value = ' ' this._focus() }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
_onChange
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
render() { let divStyle = { position: 'absolute', overflow: 'hidden', height: 0, outline: 'none', left: this.props.coordinates.x, top: this.props.coordinates.y } // we can't focus an element with display: none so wrap them in another invisible div return ( <div style={divStyle}> <textarea key="input" ref="input" onChange={this._onChange} onCopy={this._onCopy} onCut={this._onCut} onPaste={this._onPaste} onBlur={this._onInputFocusLost} onFocus={this._onInputFocusGained}/> <div style={{display: 'none'}} ref="hiddenContainer"></div> <div contentEditable="true" ref="ieClipboardDiv" onPaste={this._onPaste}></div> </div> ) }
A React component to obtain TextInput from the user and insert it into the editor. We capture shortcuts via Mousetrap.js bindings. All other characters bypass Mousetrap and are inserted by the browser into the focused hidden text input area (so the browser's internal machinery deals with the key capture and translation to characters, so it should work for complex IME input as well), and from there the browser triggers the onInput event on the input area, at which point we grab the character and place it into the editor.
render
javascript
ritzyed/ritzy
src/components/TextInput.js
https://github.com/ritzyed/ritzy/blob/master/src/components/TextInput.js
Apache-2.0
function detectMinFontSize() { let elem = document.createElement('div') elem.style['font-size'] = '1px' elem.style.display = 'none' elem.style.visibility = 'hidden' document.body.appendChild(elem) let style = getComputedStyle(elem, null) let size = getPixelStyleProperty(style, 'font-size') document.body.removeChild(elem) return size }
Returns the currently set browser minimum font size. We create an invisible element and set its font-size style to 1px. We then obtain the browser's computed font-size property, which should be the minimum size allowed by the browser's current settings. TODO is there a better way to get the browser minimum font size?
detectMinFontSize
javascript
ritzyed/ritzy
src/core/dom.js
https://github.com/ritzyed/ritzy/blob/master/src/core/dom.js
Apache-2.0
function elementPosition(elem, until) { let x = 0 let y = 0 let inner = true while (elem) { let style = getComputedStyle(elem, null) if(until && until(elem, style)) break x += elem.offsetLeft y += elem.offsetTop y += getNumericStyleProperty(style, 'border-top-width') x += getNumericStyleProperty(style, 'border-left-width') if (inner) { y += getNumericStyleProperty(style, 'padding-top') x += getNumericStyleProperty(style, 'padding-left') } inner = false elem = elem.offsetParent } return {x: x, y: y} }
Returns the position of an element relative to the page, or until a parent element for which the provided 'until' function is truthy. Basic implementation from http://stackoverflow.com/a/5776220/430128. @param elem @param until A function, if provided, is passed each parent element and computed style. If it returns a truthy value, the returned position will be relative to that element. @returns {{x: number, y: number}}
elementPosition
javascript
ritzyed/ritzy
src/core/dom.js
https://github.com/ritzyed/ritzy/blob/master/src/core/dom.js
Apache-2.0
function scrollByToVisible(el, xGutter, yGutter) { let rect = el.getBoundingClientRect() let xDelta = 0 let yDelta = 0 xGutter = xGutter || 0 yGutter = yGutter || 0 let windowWidth = document.documentElement.clientWidth || document.body.clientWidth if(rect.right < xGutter) xDelta = rect.right - xGutter else if(rect.left > windowWidth - xGutter) xDelta = rect.left - windowWidth + xGutter let windowHeight = document.documentElement.clientHeight || document.body.clientHeight if(rect.top < yGutter) yDelta = rect.top - yGutter else if(rect.bottom > windowHeight - yGutter) yDelta = rect.bottom - windowHeight + yGutter return { xDelta: xDelta, yDelta: yDelta } }
Returns the number of pixels to scroll the window by (in the x and y directions) to make an element completely visible within the viewport. @param el The element @param xGutter @param yGutter @return {{xDelta: number, yDelta: number}}
scrollByToVisible
javascript
ritzyed/ritzy
src/core/dom.js
https://github.com/ritzyed/ritzy/blob/master/src/core/dom.js
Apache-2.0
function emptyNode(node) { while (node.firstChild) { node.removeChild(node.firstChild) } }
Empties a DOM node of all its children. @param {Node} node
emptyNode
javascript
ritzyed/ritzy
src/core/dom.js
https://github.com/ritzyed/ritzy/blob/master/src/core/dom.js
Apache-2.0
function charEq(charOrId1, charOrId2) { if(charOrId1 === charOrId2) return true if(!charOrId1) return Object.is(charOrId1, charOrId2) return charId(charOrId1) === charId(charOrId2) }
Determines whether two chars are the same or not. @param {Char|number} charOrId1 @param {Char|number} charOrId2
charEq
javascript
ritzyed/ritzy
src/core/EditorCommon.js
https://github.com/ritzyed/ritzy/blob/master/src/core/EditorCommon.js
Apache-2.0
constructor(chars, chunks, start, end, advance) { this.chars = chars this.chunks = chunks this.start = start this.end = end this.advance = advance }
@param {Array} chars @param {Array} chunks @param {Char} start @param {Char} end @param {number} advance
constructor
javascript
ritzyed/ritzy
src/core/EditorCommon.js
https://github.com/ritzyed/ritzy/blob/master/src/core/EditorCommon.js
Apache-2.0
hasChar(charOrId) { if(!charOrId) return false // lazy evaluation of charIds if necessary if(!this._charIds) { this._charIds = new Set() this.chars.forEach(c => this._charIds.add(c.id)) } return this._charIds.has(charId(charOrId)) }
@param {Array} chars @param {Array} chunks @param {Char} start @param {Char} end @param {number} advance
hasChar
javascript
ritzyed/ritzy
src/core/EditorCommon.js
https://github.com/ritzyed/ritzy/blob/master/src/core/EditorCommon.js
Apache-2.0
first() { return this.chars.length > 0 ? this.chars[0] : null }
The first character of the line. This is not equal to "start" since start is the *position* at which the first character is present (i.e. the previous char === the previous line.end). @returns {Char}
first
javascript
ritzyed/ritzy
src/core/EditorCommon.js
https://github.com/ritzyed/ritzy/blob/master/src/core/EditorCommon.js
Apache-2.0
isHard() { return this.end.char === '\n' }
The first character of the line. This is not equal to "start" since start is the *position* at which the first character is present (i.e. the previous char === the previous line.end). @returns {Char}
isHard
javascript
ritzyed/ritzy
src/core/EditorCommon.js
https://github.com/ritzyed/ritzy/blob/master/src/core/EditorCommon.js
Apache-2.0
isEof() { return this.end === EOF }
The first character of the line. This is not equal to "start" since start is the *position* at which the first character is present (i.e. the previous char === the previous line.end). @returns {Char}
isEof
javascript
ritzyed/ritzy
src/core/EditorCommon.js
https://github.com/ritzyed/ritzy/blob/master/src/core/EditorCommon.js
Apache-2.0
indexOf(charOrId) { for (let i = 0; i < this.chars.length; i++) { if (charEq(this.chars[i], charOrId)) { return i } } return -1 }
The first character of the line. This is not equal to "start" since start is the *position* at which the first character is present (i.e. the previous char === the previous line.end). @returns {Char}
indexOf
javascript
ritzyed/ritzy
src/core/EditorCommon.js
https://github.com/ritzyed/ritzy/blob/master/src/core/EditorCommon.js
Apache-2.0
charsBetween(fromCharOrId, toCharOrId) { let indexFrom = 0 let indexTo = this.chars.length if(!charEq(fromCharOrId, this.start)) { indexFrom = this.indexOf(fromCharOrId) + 1 } if(toCharOrId !== EOF && !charEq(toCharOrId, this.end)) { indexTo = this.indexOf(toCharOrId) + 1 } return this.chars.slice(indexFrom, indexTo) }
Obtains chars between the given char (exclusive) to the given char (inclusive). Note the begin exclusivity operates differently than array slice (which is end exclusive), but corresponds generally with how character ranges in the editor are used. @param fromCharOrId @param toCharOrId
charsBetween
javascript
ritzyed/ritzy
src/core/EditorCommon.js
https://github.com/ritzyed/ritzy/blob/master/src/core/EditorCommon.js
Apache-2.0
charsTo(charOrId) { return this.chars.slice(0, this.indexOf(charOrId) + 1) }
Obtains chars between the given char (exclusive) to the given char (inclusive). Note the begin exclusivity operates differently than array slice (which is end exclusive), but corresponds generally with how character ranges in the editor are used. @param fromCharOrId @param toCharOrId
charsTo
javascript
ritzyed/ritzy
src/core/EditorCommon.js
https://github.com/ritzyed/ritzy/blob/master/src/core/EditorCommon.js
Apache-2.0
function linesEq(line1, line2) { if(line1 === line2) return true if(!line1) return Object.is(line1, line2) if(_.isArray(line1.chars) && _.isArray(line2.chars) && line1.chars.length !== line2.chars.length) return false if(!_.isEqual(line1.start, line2.start)) return false if(!_.isEqual(line1.end, line2.end)) return false if(!_.isEqual(line1.chunks, line2.chunks)) return false return _.isEqual(line1.chars, line2.chars) }
Determines whether two lines are the same or not i.e. that the lines refer to the same chars with the same attributes. Will also return true if both lines are undefined or both are null. @param line1 @param line2
linesEq
javascript
ritzyed/ritzy
src/core/EditorCommon.js
https://github.com/ritzyed/ritzy/blob/master/src/core/EditorCommon.js
Apache-2.0
function charArrayEq(cArr1, cArr2) { if(cArr1 === cArr2) return true if(!cArr1 || !_.isArray(cArr1)) return Object.is(cArr1, cArr2) if(cArr1.length !== cArr2.length) return false for(let i = 0; i < cArr1.length; i++) { if(!charEq(cArr1[i], cArr2[i])) return false } return true }
Determines whether two char arrays are the same or not i.e. that the arrays refer to the same chars (but note that this only checks char identity, and ignores char properties like attributes and deleted chars). Will also return true if both arrays are undefined or both are null. @param {Char[]} cArr1 @param {Char[]} cArr2
charArrayEq
javascript
ritzyed/ritzy
src/core/EditorCommon.js
https://github.com/ritzyed/ritzy/blob/master/src/core/EditorCommon.js
Apache-2.0
function lineContainingChar(searchSpace, charOrId, nextIfEol) { if(_.isUndefined(nextIfEol)) nextIfEol = false if(!searchSpace || searchSpace.length === 0) { return { line: EMPTY_LINE, index: -1, endOfLine: null } } // shortcut searches at the beginning or end of the searchSpace, this is used often and these comparisons are fast if(charEq(searchSpace[0].start, charOrId)) { return { line: searchSpace[0], index: 0, endOfLine: !charEq(charOrId, BASE_CHAR) } } else if(charEq(searchSpace[searchSpace.length - 1].end, charOrId)) { return { line: searchSpace[searchSpace.length - 1], index: searchSpace.length - 1, endOfLine: true } } for(let i = 0; i < searchSpace.length; i++) { let line = searchSpace[i] if(line.hasChar(charOrId)) { let index = i let endOfLine = charEq(charOrId, line.end) if(nextIfEol && endOfLine && !line.isEof() && searchSpace.length - 1 > i) { index++ line = searchSpace[index] } return { line: line, index: index, endOfLine: endOfLine } } } return null }
Search the given search space for the line containing the provided char. If the search space is empty, an empty "virtual" line starting at BASE_CHAR and ending at EOF is returned. @param searchSpace The set of lines to search. @param charOrId The char or char id to search for. @param {boolean} [nextIfEol=false] If at end of line, return the next line. @returns {*}
lineContainingChar
javascript
ritzyed/ritzy
src/core/EditorCommon.js
https://github.com/ritzyed/ritzy/blob/master/src/core/EditorCommon.js
Apache-2.0
function ignoredNode(node) { return node.nodeType === Node.COMMENT_NODE || node.nodeType === Node.PROCESSING_INSTRUCTION_NODE || (node.nodeType === Node.ELEMENT_NODE && getComputedStyle(node, null).getPropertyValue('display') === 'none') }
https://rawgit.com/timdown/rangy/master/fiddlings/spec/innerText.htm#ignored-node @param node @returns {boolean}
ignoredNode
javascript
ritzyed/ritzy
src/core/htmlparser.js
https://github.com/ritzyed/ritzy/blob/master/src/core/htmlparser.js
Apache-2.0
function elementLeadingWhitespace(el) { let style = getComputedStyle(el, null) let display = style.getPropertyValue('display') let firstNotIgnoredChild = () => { for(let i = 0; i < el.children.length; i++) { let n = el.children[i] if(!ignoredNode(n)) return n } return null } if(display === 'inline') { let first = firstNotIgnoredChild() if(first && first.nodeType === Node.ELEMENT_NODE) { return elementLeadingWhitespace(first) } else { return '' } } else if(display === 'inline-block' || display === 'inline-table' || display === 'none' || display === 'table-cell' || display === 'table-column' || display === 'table-column-group') { return '' } else { return '\n' } }
https://rawgit.com/timdown/rangy/master/fiddlings/spec/innerText.htm#leading-whitespace @param el
elementLeadingWhitespace
javascript
ritzyed/ritzy
src/core/htmlparser.js
https://github.com/ritzyed/ritzy/blob/master/src/core/htmlparser.js
Apache-2.0
firstNotIgnoredChild = () => { for(let i = 0; i < el.children.length; i++) { let n = el.children[i] if(!ignoredNode(n)) return n } return null }
https://rawgit.com/timdown/rangy/master/fiddlings/spec/innerText.htm#leading-whitespace @param el
firstNotIgnoredChild
javascript
ritzyed/ritzy
src/core/htmlparser.js
https://github.com/ritzyed/ritzy/blob/master/src/core/htmlparser.js
Apache-2.0
firstNotIgnoredChild = () => { for(let i = 0; i < el.children.length; i++) { let n = el.children[i] if(!ignoredNode(n)) return n } return null }
https://rawgit.com/timdown/rangy/master/fiddlings/spec/innerText.htm#leading-whitespace @param el
firstNotIgnoredChild
javascript
ritzyed/ritzy
src/core/htmlparser.js
https://github.com/ritzyed/ritzy/blob/master/src/core/htmlparser.js
Apache-2.0
function elementTrailingWhitespace(el) { let style = getComputedStyle(el, null) let display = style.getPropertyValue('display') let lastNotIgnoredChild = () => { for(let i = el.children.length - 1; i >= 0; i--) { let n = el.children[i] if(!ignoredNode(n)) return n } return null } if(display === 'inline') { let last = lastNotIgnoredChild() if(last && last.nodeType === Node.ELEMENT_NODE) { let lastChunks = [] innerRichText(last, lastChunks) return elementTrailingWhitespace(last, lastChunks) } else { return '' } } else if(display === 'inline-block' || display === 'inline-table' || display === 'none' || display === 'table-column' || display === 'table-column-group') { return '' } else if(display === 'table-cell') { return '\t' } else { let elChunks = [] innerRichText(el, elChunks) if(elChunks && elChunks.length > 0) { let marginBottom = getPixelStyleProperty(style, 'margin-bottom') let fontSize = getPixelStyleProperty(style, 'font-size') if(marginBottom >= fontSize / 2) return '\n\n' else return '\n' } else return '' } }
https://rawgit.com/timdown/rangy/master/fiddlings/spec/innerText.htm#trailing-whitespace @param el
elementTrailingWhitespace
javascript
ritzyed/ritzy
src/core/htmlparser.js
https://github.com/ritzyed/ritzy/blob/master/src/core/htmlparser.js
Apache-2.0
lastNotIgnoredChild = () => { for(let i = el.children.length - 1; i >= 0; i--) { let n = el.children[i] if(!ignoredNode(n)) return n } return null }
https://rawgit.com/timdown/rangy/master/fiddlings/spec/innerText.htm#trailing-whitespace @param el
lastNotIgnoredChild
javascript
ritzyed/ritzy
src/core/htmlparser.js
https://github.com/ritzyed/ritzy/blob/master/src/core/htmlparser.js
Apache-2.0
lastNotIgnoredChild = () => { for(let i = el.children.length - 1; i >= 0; i--) { let n = el.children[i] if(!ignoredNode(n)) return n } return null }
https://rawgit.com/timdown/rangy/master/fiddlings/spec/innerText.htm#trailing-whitespace @param el
lastNotIgnoredChild
javascript
ritzyed/ritzy
src/core/htmlparser.js
https://github.com/ritzyed/ritzy/blob/master/src/core/htmlparser.js
Apache-2.0
function elementHasNonIgnoredSiblingElement(el) { let sibling = el.nextSibling while (sibling) { if (ignoredNode(sibling) || sibling.nodeName === 'BR') { sibling = sibling.nextSibling } else if (sibling.nodeType === Node.ELEMENT_NODE) { return true } else { sibling = sibling.nextSibling } } return false }
https://rawgit.com/timdown/rangy/master/fiddlings/spec/innerText.htm#trailing-whitespace @param el
elementHasNonIgnoredSiblingElement
javascript
ritzyed/ritzy
src/core/htmlparser.js
https://github.com/ritzyed/ritzy/blob/master/src/core/htmlparser.js
Apache-2.0
function innerRichTextForTextNode(node, nodeStyle, chunks, nodeAttributes, trailingSpace) { if(_.isUndefined(trailingSpace)) trailingSpace = false let inSet = (c, setString) => setString.indexOf(c) > -1 let advanceUntilNotInSet = (data, position, setString) => { let consume = true while(consume && position < data.length) { if(!inSet(data.charAt(position), setString)) { consume = false } else { position++ } } return position } let lastChunk = chunks.length > 0 ? chunks[chunks.length - 1] : null // child is text, step #2 let data = node.data // child is text, step #3 let whitespace = nodeStyle.getPropertyValue('white-space') let whitespaceCollapse = whitespace === 'normal' || whitespace === 'nowrap' || whitespace === 'pre-line' if(whitespaceCollapse) { // child is text, step #4 - 1 let whitespaceChars = whitespace === 'normal' || whitespace === 'nowrap' ? SPACE_CHARS : SPACE_CHARS_EXCEPT_LF // child is text, step #4 - 2 let position = 0 // child is text, step #4 - 3 let newData = '' // child is text, step #4 - 4 while(position < data.length) { let c = data.charAt(position) if(whitespaceChars.indexOf(c) > -1) { // child is text, step #4 - 4 - 1 newData += ' ' position++ position = advanceUntilNotInSet(data, position, whitespaceChars) } else if(c === '\n') { // child is text, step #4 - 4 - 2 if(newData.length > 0 && newData.charAt(newData.length - 1) === ' ') { newData = newData.slice(0, newData.length - 1) } newData += '\n' position++ position = advanceUntilNotInSet(data, position, whitespaceChars) } else { // child is text, step #4 - 4 - 3 newData += c position++ } } // child is text, step #4 - 5 data = newData } // child is text, step #5 if(trailingSpace && (data.length === 0 || !inSet(data.charAt(0), SPACE_CHARS)) && lastChunk) { lastChunk.text += ' ' } // child is text, step #6 if((!lastChunk || lastChunk.text.length === 0 || inSet(lastChunk.text.charAt(lastChunk.text.length - 1), SPACE_CHARS)) && (data.length > 0 && data.charAt(0) === ' ') && whitespaceCollapse) { data = data.slice(1) } // child is text, step #7 if(whitespaceCollapse && (data.length > 0 && data.charAt(data.length - 1) === ' ')) { data = data.slice(0, data.length - 1) trailingSpace = true } else { trailingSpace = false } // child is text, step #8 // ignore text-transform let textTransform = nodeStyle.getPropertyValue('text-transform') if(textTransform !== 'none' && textTransform !== 'normal') { console.warn(`Unsupported text-transform ${textTransform} during HTML parsing, ignoring.`) } // child is text, step #9 if(data.length > 0) { chunks.push({ text: data, attrs: nodeAttributes }) } return trailingSpace }
The text element portion of Aryeh Gregor's aborted innerText proposal. See https://rawgit.com/timdown/rangy/master/fiddlings/spec/innerText.htm. Does not apply any CSS text-transform instructions, but does warn about them to the console. @param node The text node. @param nodeStyle The style of the node containing the text node. @param chunks The array of rich text chunks to append the text node data to. @param nodeAttributes The rich text attributes of the containing node. @param trailingSpace Whether the previous text node had a trailing space.
innerRichTextForTextNode
javascript
ritzyed/ritzy
src/core/htmlparser.js
https://github.com/ritzyed/ritzy/blob/master/src/core/htmlparser.js
Apache-2.0
advanceUntilNotInSet = (data, position, setString) => { let consume = true while(consume && position < data.length) { if(!inSet(data.charAt(position), setString)) { consume = false } else { position++ } } return position }
The text element portion of Aryeh Gregor's aborted innerText proposal. See https://rawgit.com/timdown/rangy/master/fiddlings/spec/innerText.htm. Does not apply any CSS text-transform instructions, but does warn about them to the console. @param node The text node. @param nodeStyle The style of the node containing the text node. @param chunks The array of rich text chunks to append the text node data to. @param nodeAttributes The rich text attributes of the containing node. @param trailingSpace Whether the previous text node had a trailing space.
advanceUntilNotInSet
javascript
ritzyed/ritzy
src/core/htmlparser.js
https://github.com/ritzyed/ritzy/blob/master/src/core/htmlparser.js
Apache-2.0
advanceUntilNotInSet = (data, position, setString) => { let consume = true while(consume && position < data.length) { if(!inSet(data.charAt(position), setString)) { consume = false } else { position++ } } return position }
The text element portion of Aryeh Gregor's aborted innerText proposal. See https://rawgit.com/timdown/rangy/master/fiddlings/spec/innerText.htm. Does not apply any CSS text-transform instructions, but does warn about them to the console. @param node The text node. @param nodeStyle The style of the node containing the text node. @param chunks The array of rich text chunks to append the text node data to. @param nodeAttributes The rich text attributes of the containing node. @param trailingSpace Whether the previous text node had a trailing space.
advanceUntilNotInSet
javascript
ritzyed/ritzy
src/core/htmlparser.js
https://github.com/ritzyed/ritzy/blob/master/src/core/htmlparser.js
Apache-2.0
function innerRichText(node, chunks, trailingSpace) { let nodeAttributes = attributesForElement(node) for(let i = 0; i < node.childNodes.length; i++) { let child = node.childNodes[i] let ignored = ignoredNode(child) if (!ignored && child.nodeType === Node.TEXT_NODE) { // child is text, step #1 let nodeStyle = getComputedStyle(node, null) if(nodeStyle.getPropertyValue('visibility') !== 'hidden') { trailingSpace = innerRichTextForTextNode(child, nodeStyle, chunks, nodeAttributes, trailingSpace) } } else if (!ignored && child.nodeType === Node.ELEMENT_NODE) { // child is element, step #1 let lastChunk = chunks.length > 0 ? chunks[chunks.length - 1] : null if(lastChunk && lastChunk.text.length > 0 && lastChunk.text.charAt(lastChunk.text.length - 1) !== '\n') { let leadingWhitespace = elementLeadingWhitespace(child) if(leadingWhitespace && leadingWhitespace.length > 0) { lastChunk.text += leadingWhitespace trailingSpace = false } } // child is element, step #2 trailingSpace = innerRichText(child, chunks, trailingSpace) // child is element, step #3 (with addition to special-case br tag) if(child.nodeName === 'BR') { chunks.push({ text: '\n', attrs: nodeAttributes }) trailingSpace = false } else if (elementHasNonIgnoredSiblingElement(child)) { // we ignore BR's here too, special cased above // a sibling node that is not an ignored node, so we need our trailing whitespace lastChunk = chunks.length > 0 ? chunks[chunks.length - 1] : null let trailingWhitespace = elementTrailingWhitespace(child) if (trailingWhitespace && trailingWhitespace.length > 0) { if(!lastChunk) { lastChunk = { text: '', attrs: nodeAttributes } chunks.push(lastChunk) } lastChunk.text += trailingWhitespace trailingSpace = false } } } } return trailingSpace }
Writes the innerRichText chunks of a node. Logic from Aryeh Gregor's aborted innerText proposal. See https://rawgit.com/timdown/rangy/master/fiddlings/spec/innerText.htm#append-the-plaintext. @param {Node} node The context node for which to obtain the rich text. @param {Array} chunks The array to which parsed rich text chunks (with attributes) should be pushed. @param {boolean} [trailingSpace] Whether the previous node had a trailing space.
innerRichText
javascript
ritzyed/ritzy
src/core/htmlparser.js
https://github.com/ritzyed/ritzy/blob/master/src/core/htmlparser.js
Apache-2.0
function parseHtml(html, tempContainer) { let parser = new DOMParser() let doc = parser.parseFromString(html, 'text/html') let chunks = [] // IE does not give us an empty body, only a null one, shortcut the subsequent logic in this case if(!doc.body) { return chunks } insertIntoContainer(doc.body, tempContainer) try { innerRichText(tempContainer, chunks) } finally { emptyNode(tempContainer) } return chunks }
Parses HTML into chunks of rich text. Argh, getting the appropriate text from an HTML DOM tree is not simple. See http://perfectionkills.com/the-poor-misunderstood-innerText/. Implement Aryeh Gregor's aborted innerText proposal: https://www.w3.org/Bugs/Public/show_bug.cgi?id=13145 and https://rawgit.com/timdown/rangy/master/fiddlings/spec/innerText.htm, which works quite well (see the test cases for this module). The innerText algorithm presented by Gregor was slightly modified to return chunks of styled rich text (text with attributes) based on the DOM nodes and their computed styles. @param {string} html The html String to parse. @param {Node} tempContainer An invisible container within the document that can hold the parsed HTML temporarily so that the browser can compute the CSS styles. This is a hack but there doesn't seem to be a better way of doing this.
parseHtml
javascript
ritzyed/ritzy
src/core/htmlparser.js
https://github.com/ritzyed/ritzy/blob/master/src/core/htmlparser.js
Apache-2.0
function writeHtmlAsDom(chunks) { let html = document.createDocumentFragment() if(!chunks) { chunks = [] } let pendingChunks = [] let pushToHtml = fragment => { html.appendChild(fragment) } let createSpan = chunk => { let textNode = document.createTextNode(chunk.text) let span = document.createElement('SPAN') span.appendChild(textNode) setStyle(span, styleForAttributes(chunk.attrs), true) return span } let pushBreakToHtml = () => { pushToHtml(document.createElement('BR')) } let pushSpansToHtml = () => { if(pendingChunks.length === 0) { return } let spans = pendingChunks.map(createSpan) let fragment = document.createDocumentFragment() spans.forEach(s => fragment.appendChild(s)) pushToHtml(fragment) pendingChunks = [] } let pushParaToHtml = () => { if(pendingChunks.length === 0) { return } let para = document.createElement('P') if(pendingChunks.length > 1) { // encapsulate chunks in styled spans let spans = pendingChunks.map(createSpan) spans.forEach(s => para.appendChild(s)) } else if(pendingChunks.length === 1) { // encapsulate chunk in styled para let textNode = document.createTextNode(pendingChunks[0].text) para.appendChild(textNode) setStyle(para, styleForAttributes(pendingChunks[0].attrs), true) } pushToHtml(para) pendingChunks = [] } let newlineCount = 0 let paraClean = true let handleNewlines = (atEnd) => { if(newlineCount > 0) { if(newlineCount >= 2) { // a bunch of newlines in a row, we need to push a paragraph for the first two and assume the rest are breaks // see http://www.w3.org/TR/html5/dom.html#palpable-content pushParaToHtml(pendingChunks) paraClean = false if(atEnd) { // add line breaks too while(newlineCount > 0) { pushBreakToHtml() newlineCount-- } } else { newlineCount -= 2 } } // treat any more newlines as line breaks while(newlineCount > 0) { pushSpansToHtml(pendingChunks) pushBreakToHtml() newlineCount-- } } } chunks.forEach(c => { if(c.text === '\n') { newlineCount++ } else { handleNewlines(false) pendingChunks.push(c) } }) // trailing newlines handleNewlines(true) if(paraClean) { pushSpansToHtml(pendingChunks) } else { pushParaToHtml(pendingChunks) } return html }
Writes chunks of rich text into an HTML document. @param {Array} chunks The rich text chunks to write.
writeHtmlAsDom
javascript
ritzyed/ritzy
src/core/htmlwriter.js
https://github.com/ritzyed/ritzy/blob/master/src/core/htmlwriter.js
Apache-2.0
createSpan = chunk => { let textNode = document.createTextNode(chunk.text) let span = document.createElement('SPAN') span.appendChild(textNode) setStyle(span, styleForAttributes(chunk.attrs), true) return span }
Writes chunks of rich text into an HTML document. @param {Array} chunks The rich text chunks to write.
createSpan
javascript
ritzyed/ritzy
src/core/htmlwriter.js
https://github.com/ritzyed/ritzy/blob/master/src/core/htmlwriter.js
Apache-2.0
createSpan = chunk => { let textNode = document.createTextNode(chunk.text) let span = document.createElement('SPAN') span.appendChild(textNode) setStyle(span, styleForAttributes(chunk.attrs), true) return span }
Writes chunks of rich text into an HTML document. @param {Array} chunks The rich text chunks to write.
createSpan
javascript
ritzyed/ritzy
src/core/htmlwriter.js
https://github.com/ritzyed/ritzy/blob/master/src/core/htmlwriter.js
Apache-2.0
pushSpansToHtml = () => { if(pendingChunks.length === 0) { return } let spans = pendingChunks.map(createSpan) let fragment = document.createDocumentFragment() spans.forEach(s => fragment.appendChild(s)) pushToHtml(fragment) pendingChunks = [] }
Writes chunks of rich text into an HTML document. @param {Array} chunks The rich text chunks to write.
pushSpansToHtml
javascript
ritzyed/ritzy
src/core/htmlwriter.js
https://github.com/ritzyed/ritzy/blob/master/src/core/htmlwriter.js
Apache-2.0
pushSpansToHtml = () => { if(pendingChunks.length === 0) { return } let spans = pendingChunks.map(createSpan) let fragment = document.createDocumentFragment() spans.forEach(s => fragment.appendChild(s)) pushToHtml(fragment) pendingChunks = [] }
Writes chunks of rich text into an HTML document. @param {Array} chunks The rich text chunks to write.
pushSpansToHtml
javascript
ritzyed/ritzy
src/core/htmlwriter.js
https://github.com/ritzyed/ritzy/blob/master/src/core/htmlwriter.js
Apache-2.0
pushParaToHtml = () => { if(pendingChunks.length === 0) { return } let para = document.createElement('P') if(pendingChunks.length > 1) { // encapsulate chunks in styled spans let spans = pendingChunks.map(createSpan) spans.forEach(s => para.appendChild(s)) } else if(pendingChunks.length === 1) { // encapsulate chunk in styled para let textNode = document.createTextNode(pendingChunks[0].text) para.appendChild(textNode) setStyle(para, styleForAttributes(pendingChunks[0].attrs), true) } pushToHtml(para) pendingChunks = [] }
Writes chunks of rich text into an HTML document. @param {Array} chunks The rich text chunks to write.
pushParaToHtml
javascript
ritzyed/ritzy
src/core/htmlwriter.js
https://github.com/ritzyed/ritzy/blob/master/src/core/htmlwriter.js
Apache-2.0
pushParaToHtml = () => { if(pendingChunks.length === 0) { return } let para = document.createElement('P') if(pendingChunks.length > 1) { // encapsulate chunks in styled spans let spans = pendingChunks.map(createSpan) spans.forEach(s => para.appendChild(s)) } else if(pendingChunks.length === 1) { // encapsulate chunk in styled para let textNode = document.createTextNode(pendingChunks[0].text) para.appendChild(textNode) setStyle(para, styleForAttributes(pendingChunks[0].attrs), true) } pushToHtml(para) pendingChunks = [] }
Writes chunks of rich text into an HTML document. @param {Array} chunks The rich text chunks to write.
pushParaToHtml
javascript
ritzyed/ritzy
src/core/htmlwriter.js
https://github.com/ritzyed/ritzy/blob/master/src/core/htmlwriter.js
Apache-2.0
handleNewlines = (atEnd) => { if(newlineCount > 0) { if(newlineCount >= 2) { // a bunch of newlines in a row, we need to push a paragraph for the first two and assume the rest are breaks // see http://www.w3.org/TR/html5/dom.html#palpable-content pushParaToHtml(pendingChunks) paraClean = false if(atEnd) { // add line breaks too while(newlineCount > 0) { pushBreakToHtml() newlineCount-- } } else { newlineCount -= 2 } } // treat any more newlines as line breaks while(newlineCount > 0) { pushSpansToHtml(pendingChunks) pushBreakToHtml() newlineCount-- } } }
Writes chunks of rich text into an HTML document. @param {Array} chunks The rich text chunks to write.
handleNewlines
javascript
ritzyed/ritzy
src/core/htmlwriter.js
https://github.com/ritzyed/ritzy/blob/master/src/core/htmlwriter.js
Apache-2.0
handleNewlines = (atEnd) => { if(newlineCount > 0) { if(newlineCount >= 2) { // a bunch of newlines in a row, we need to push a paragraph for the first two and assume the rest are breaks // see http://www.w3.org/TR/html5/dom.html#palpable-content pushParaToHtml(pendingChunks) paraClean = false if(atEnd) { // add line breaks too while(newlineCount > 0) { pushBreakToHtml() newlineCount-- } } else { newlineCount -= 2 } } // treat any more newlines as line breaks while(newlineCount > 0) { pushSpansToHtml(pendingChunks) pushBreakToHtml() newlineCount-- } } }
Writes chunks of rich text into an HTML document. @param {Array} chunks The rich text chunks to write.
handleNewlines
javascript
ritzyed/ritzy
src/core/htmlwriter.js
https://github.com/ritzyed/ritzy/blob/master/src/core/htmlwriter.js
Apache-2.0
function writeHtml(chunks) { let html = writeHtmlAsDom(chunks) // fragments don't have an innerHTML method so we need to wrap it in another container first let container = document.createElement('div') container.appendChild(html) return container.innerHTML }
Writes chunks of rich text into an HTML document. @param {Array} chunks The rich text chunks to write.
writeHtml
javascript
ritzyed/ritzy
src/core/htmlwriter.js
https://github.com/ritzyed/ritzy/blob/master/src/core/htmlwriter.js
Apache-2.0
function parseSpec(spec) { // spec seems to have some internal parsing state "index" which prevents accessing it consistently // https://github.com/gritzko/swarm/issues/53 let oldIndex = spec.index spec.index = 0 let source try { source = spec.source() } catch (e) { source = null } let op try { op = spec.op() } catch (e) { op = null } spec.index = oldIndex return { source: source, op: op } }
Parses a Swarm spec and returns its data as an object. @param spec @returns {{source: *, op: *}}
parseSpec
javascript
ritzyed/ritzy
src/core/replica.js
https://github.com/ritzyed/ritzy/blob/master/src/core/replica.js
Apache-2.0
function sourceOf(spec) { return parseSpec(spec).source }
Returns the source from within a Swarm spec. @param spec @returns {*}
sourceOf
javascript
ritzyed/ritzy
src/core/replica.js
https://github.com/ritzyed/ritzy/blob/master/src/core/replica.js
Apache-2.0
constructor() { BASE_CHAR.deletedIds = new Set() this.chars = [BASE_CHAR] }
Contains the textual data and corresponding lamport timestamps (ids) for each character. Each character has a primary id, but may have secondary ids in a Set representing deleted characters at that position. In addition, each character has a list of other "rich" attributes, such as bold, color, and so forth. Currently the data storage is in regular JS arrays, but perhaps we could use immutable-js: - (possible) faster or more consistent insertion performance, splice performance is implementation dependent - blazing fast reference equality comparisons
constructor
javascript
ritzyed/ritzy
src/core/RichText.js
https://github.com/ritzyed/ritzy/blob/master/src/core/RichText.js
Apache-2.0
len() { return this.chars.length }
Contains the textual data and corresponding lamport timestamps (ids) for each character. Each character has a primary id, but may have secondary ids in a Set representing deleted characters at that position. In addition, each character has a list of other "rich" attributes, such as bold, color, and so forth. Currently the data storage is in regular JS arrays, but perhaps we could use immutable-js: - (possible) faster or more consistent insertion performance, splice performance is implementation dependent - blazing fast reference equality comparisons
len
javascript
ritzyed/ritzy
src/core/RichText.js
https://github.com/ritzyed/ritzy/blob/master/src/core/RichText.js
Apache-2.0
getChar(pos) { invariant(pos < this.len(), 'Index ' + pos + ' out of bounds.') // TODO Char should be immutable so that it cannot be modified outside of this class, use Immutable.js Record? return this.chars[pos] }
Contains the textual data and corresponding lamport timestamps (ids) for each character. Each character has a primary id, but may have secondary ids in a Set representing deleted characters at that position. In addition, each character has a list of other "rich" attributes, such as bold, color, and so forth. Currently the data storage is in regular JS arrays, but perhaps we could use immutable-js: - (possible) faster or more consistent insertion performance, splice performance is implementation dependent - blazing fast reference equality comparisons
getChar
javascript
ritzyed/ritzy
src/core/RichText.js
https://github.com/ritzyed/ritzy/blob/master/src/core/RichText.js
Apache-2.0
insertChar(pos, char, id, attributes) { invariant(pos !== 0, 'Cannot insert at position 0.') invariant(pos <= this.len(), 'Index ' + pos + ' out of bounds.') this.chars.splice(pos, 0, new Char(id, char, null, this._normalizeAttrs(attributes))) }
Contains the textual data and corresponding lamport timestamps (ids) for each character. Each character has a primary id, but may have secondary ids in a Set representing deleted characters at that position. In addition, each character has a list of other "rich" attributes, such as bold, color, and so forth. Currently the data storage is in regular JS arrays, but perhaps we could use immutable-js: - (possible) faster or more consistent insertion performance, splice performance is implementation dependent - blazing fast reference equality comparisons
insertChar
javascript
ritzyed/ritzy
src/core/RichText.js
https://github.com/ritzyed/ritzy/blob/master/src/core/RichText.js
Apache-2.0
deleteChar(pos) { invariant(pos !== 0, 'Cannot delete position 0.') invariant(pos < this.len(), 'Index ' + pos + ' out of bounds.') let previousChar = this.chars[pos - 1] let deletedChar = this.chars.splice(pos, 1)[0] if(!previousChar.deletedIds) { previousChar.deletedIds = new Set() } previousChar.deletedIds.add(deletedChar.id) if(deletedChar.deletedIds) { pushSet(deletedChar.deletedIds, previousChar.deletedIds) } }
Contains the textual data and corresponding lamport timestamps (ids) for each character. Each character has a primary id, but may have secondary ids in a Set representing deleted characters at that position. In addition, each character has a list of other "rich" attributes, such as bold, color, and so forth. Currently the data storage is in regular JS arrays, but perhaps we could use immutable-js: - (possible) faster or more consistent insertion performance, splice performance is implementation dependent - blazing fast reference equality comparisons
deleteChar
javascript
ritzyed/ritzy
src/core/RichText.js
https://github.com/ritzyed/ritzy/blob/master/src/core/RichText.js
Apache-2.0
setCharAttr(pos, attributes) { invariant(pos !== 0, 'Cannot set attributes of position 0.') invariant(pos < this.len(), 'Index ' + pos + ' out of bounds.') this.chars[pos].attributes = this._normalizeAttrs(_.clone(attributes)) }
Contains the textual data and corresponding lamport timestamps (ids) for each character. Each character has a primary id, but may have secondary ids in a Set representing deleted characters at that position. In addition, each character has a list of other "rich" attributes, such as bold, color, and so forth. Currently the data storage is in regular JS arrays, but perhaps we could use immutable-js: - (possible) faster or more consistent insertion performance, splice performance is implementation dependent - blazing fast reference equality comparisons
setCharAttr
javascript
ritzyed/ritzy
src/core/RichText.js
https://github.com/ritzyed/ritzy/blob/master/src/core/RichText.js
Apache-2.0
matches(pos, ids, includeDeleted) { invariant(pos < this.len(), 'Index out of bounds.') includeDeleted = includeDeleted !== false if(_.isArray(ids) || ids.iterator) { if(!ids.iterator) { ids = new Set(ids) } if(ids.has(this.chars[pos].id)) { return true } if(includeDeleted && this.chars[pos].deletedIds) { return setIntersection(this.chars[pos].deletedIds, ids).length > 0 } } else { if(ids === this.chars[pos].id) { return true } if(includeDeleted && this.chars[pos].deletedIds) { return this.chars[pos].deletedIds.has(ids) } } return false }
Contains the textual data and corresponding lamport timestamps (ids) for each character. Each character has a primary id, but may have secondary ids in a Set representing deleted characters at that position. In addition, each character has a list of other "rich" attributes, such as bold, color, and so forth. Currently the data storage is in regular JS arrays, but perhaps we could use immutable-js: - (possible) faster or more consistent insertion performance, splice performance is implementation dependent - blazing fast reference equality comparisons
matches
javascript
ritzyed/ritzy
src/core/RichText.js
https://github.com/ritzyed/ritzy/blob/master/src/core/RichText.js
Apache-2.0
matchCount(pos, ids, includeDeleted) { invariant(pos < this.len(), 'Index out of bounds.') includeDeleted = includeDeleted !== false let matches = 0 if(_.isArray(ids) || ids.iterator) { if(!ids.iterator) { ids = new Set(ids) } if(ids.has(this.chars[pos].id)) { matches += 1 } if(includeDeleted && this.chars[pos].deletedIds) { matches += setIntersection(this.chars[pos].deletedIds, ids).length } } else { if(ids === this.chars[pos].id) { matches += 1 } if(includeDeleted && this.chars[pos].deletedIds && this.chars[pos].deletedIds.has(ids)) { matches += 1 } } return matches }
Contains the textual data and corresponding lamport timestamps (ids) for each character. Each character has a primary id, but may have secondary ids in a Set representing deleted characters at that position. In addition, each character has a list of other "rich" attributes, such as bold, color, and so forth. Currently the data storage is in regular JS arrays, but perhaps we could use immutable-js: - (possible) faster or more consistent insertion performance, splice performance is implementation dependent - blazing fast reference equality comparisons
matchCount
javascript
ritzyed/ritzy
src/core/RichText.js
https://github.com/ritzyed/ritzy/blob/master/src/core/RichText.js
Apache-2.0
text() { return this.chars.map(c => c.char).join('') }
Contains the textual data and corresponding lamport timestamps (ids) for each character. Each character has a primary id, but may have secondary ids in a Set representing deleted characters at that position. In addition, each character has a list of other "rich" attributes, such as bold, color, and so forth. Currently the data storage is in regular JS arrays, but perhaps we could use immutable-js: - (possible) faster or more consistent insertion performance, splice performance is implementation dependent - blazing fast reference equality comparisons
text
javascript
ritzyed/ritzy
src/core/RichText.js
https://github.com/ritzyed/ritzy/blob/master/src/core/RichText.js
Apache-2.0
_normalizeAttrs(attrs) { if(!attrs) return null Object.keys(attrs).filter(a => !attrs[a]).forEach(a => delete attrs[a]) return _.isEmpty(attrs) ? null : attrs }
Contains the textual data and corresponding lamport timestamps (ids) for each character. Each character has a primary id, but may have secondary ids in a Set representing deleted characters at that position. In addition, each character has a list of other "rich" attributes, such as bold, color, and so forth. Currently the data storage is in regular JS arrays, but perhaps we could use immutable-js: - (possible) faster or more consistent insertion performance, splice performance is implementation dependent - blazing fast reference equality comparisons
_normalizeAttrs
javascript
ritzyed/ritzy
src/core/RichText.js
https://github.com/ritzyed/ritzy/blob/master/src/core/RichText.js
Apache-2.0
setAttributes(spec, attrs, src) { // eslint-disable-line no-unused-vars if(!attrs) return let attrKeys = Object.keys(attrs) for (let i = 1; i < this.data.len(); i++) { for(let j = 0; j < attrKeys.length; j++) { if (this.data.matches(i, attrKeys[j], false)) { this.data.setCharAttr(i, attrs[attrKeys[j]]) } } } }
Set attributes for the given chars. Attributes are overwritten, therefore it is client code's responsibility to "merge" existing attributes with new ones.
setAttributes
javascript
ritzyed/ritzy
src/core/RichText.js
https://github.com/ritzyed/ritzy/blob/master/src/core/RichText.js
Apache-2.0
text() { return this.data.text() }
Set attributes for the given chars. Attributes are overwritten, therefore it is client code's responsibility to "merge" existing attributes with new ones.
text
javascript
ritzyed/ritzy
src/core/RichText.js
https://github.com/ritzyed/ritzy/blob/master/src/core/RichText.js
Apache-2.0
applyDelta(delta) { let rm = null let ins = null let pos = 1 // skip \n #00000+swarm for(let i = 0; i < delta.length; i++) { let op = delta[i] if(op.insert) { invariant(pos > 0, 'Cannot insert at position 0.') if(!ins) ins = {} ins[this.data.getChar(pos - 1).id] = { value: op.insert, attributes: op.attributes } // we don't increment pos here because the insert hasn't actually happened yet } if(op.delete) { invariant(pos > 0, 'Cannot delete position 0.') if(!rm) rm = {} let rmcount = op.delete for (let j = 0; j < rmcount; j++) { rm[this.data.getChar(pos).id] = true pos += 1 } } if(op.retain) { pos += op.retain } } if(rm) this.remove(rm) if(ins) this.insert(ins) }
A delta is based on the operational transform rich text type. See https://github.com/ottypes/rich-text. @param delta
applyDelta
javascript
ritzyed/ritzy
src/core/RichText.js
https://github.com/ritzyed/ritzy/blob/master/src/core/RichText.js
Apache-2.0
deltaFromInsert(op) { let delta = [] let foundCount = 0 let opKeys = op ? Object.keys(op) : [] let lastInsert = 0 for (let i = 0; i < this.data.len(); i++) { for(let j = 0; j < opKeys.length; j++) { let opKey = opKeys[j] if (this.data.matches(i, opKey)) { if (i - lastInsert > 0) delta.push({retain: i - lastInsert}) let str = op[opKey].value let deltaOp = {insert: str} let attrs = op[opKey].attributes if(attrs) { deltaOp.attributes = attrs } delta.push(deltaOp) lastInsert = i + str.length foundCount += 1 if (foundCount >= opKeys.length) { return delta } } } } return delta }
Obtain a delta based on an insert operation. Note that this must be run *after* the insert has already occurred on the replica. This can be used to obtain deltas for updating a local editor based on an op received from the replica event system. @param op @returns {Array}
deltaFromInsert
javascript
ritzyed/ritzy
src/core/RichText.js
https://github.com/ritzyed/ritzy/blob/master/src/core/RichText.js
Apache-2.0
deltaFromRemove(op) { let delta = [] let foundCount = 0 let opKeys = Object.keys(op) let lastRemove = 0 for (let i = 0; i < this.data.len(); i++) { let matchCount = this.data.matchCount(i, opKeys) if (matchCount > 0) { if(i - lastRemove > 0) delta.push({ retain: i - lastRemove }) // since the delete has already occurred we need to use the number of matched ids at the current char delta.push({ delete: matchCount }) lastRemove = i foundCount += matchCount if(foundCount >= opKeys.length) { return delta } } } return delta }
Obtain a delta based on a remove operation. Note that this must be run *after* the remove has already occurred on the replica. This can be used to obtain deltas for updating a local editor based on an op received from the replica event system. @param op @returns {Array}
deltaFromRemove
javascript
ritzyed/ritzy
src/core/RichText.js
https://github.com/ritzyed/ritzy/blob/master/src/core/RichText.js
Apache-2.0
insertCharsAt(char, value, attributes) { let ins = {} ins[char.id] = { value: value, attributes: attributes } this.insert(ins) }
Insert chars with optional attributes at a given position. @param {Char} char The position at which to insert. @param {string} value The string value to insert. @param {object} [attributes] Attributes to set, or no attributes if not set. The attributes are cloned before setting so that they cannot be modified by simply changing the object reference. This type of change would not propagate through the replica.
insertCharsAt
javascript
ritzyed/ritzy
src/core/RichText.js
https://github.com/ritzyed/ritzy/blob/master/src/core/RichText.js
Apache-2.0
rmChars(chars) { if(!chars) return let rm = {} if(_.isArray(chars)) { for(let i = 0; i < chars.length; i++) { rm[chars[i].id] = true } } else { rm[chars.id] = true } this.remove(rm) }
Delete the given chars. @param {Char|Char[]} chars
rmChars
javascript
ritzyed/ritzy
src/core/RichText.js
https://github.com/ritzyed/ritzy/blob/master/src/core/RichText.js
Apache-2.0
set(newText, attributes) { this.rmChars(this.getTextRange(BASE_CHAR)) this.insertCharsAt(BASE_CHAR, newText, attributes) }
Sets new text. All current text contents are deleted (though the deleted ids remain). @param {string} newText @param {object} [attributes]
set
javascript
ritzyed/ritzy
src/core/RichText.js
https://github.com/ritzyed/ritzy/blob/master/src/core/RichText.js
Apache-2.0
len() { return this.data.len() }
Gets the length of the current replica data, including the BASE_CHAR (the length of the actual data). @returns {number}
len
javascript
ritzyed/ritzy
src/core/RichText.js
https://github.com/ritzyed/ritzy/blob/master/src/core/RichText.js
Apache-2.0
getChar(charOrId) { return this.getCharRelativeTo(charOrId, 0, 'error') }
Gets the char for the given char or id. Can be used to "refresh" the char information which is a snapshot with the latest replica information. @param {Char|number} charOrId @returns {*}
getChar
javascript
ritzyed/ritzy
src/core/RichText.js
https://github.com/ritzyed/ritzy/blob/master/src/core/RichText.js
Apache-2.0
getCharAt(pos) { return this.data.getChar(pos) }
Gets the char at the given position. Position 0 is always the BASE_CHAR. An Error is thrown if the position is out of bounds. @param {number} pos @returns {*}
getCharAt
javascript
ritzyed/ritzy
src/core/RichText.js
https://github.com/ritzyed/ritzy/blob/master/src/core/RichText.js
Apache-2.0
indexOf(charOrId, includeDeleted) { invariant(charOrId, 'From char must be defined.') let id = _.has(charOrId, 'id') ? charOrId.id : charOrId for (let i = 0; i < this.data.len(); i++) { if (this.data.matches(i, id, includeDeleted)) return i } return -1 }
Returns the index of a given char or ID. Index 0 is always the BASE_CHAR. If the char is not found, returns -1. @param {Char|number} charOrId @param {boolean} [includeDeleted=true] Whether to include deletec chars in the match. @returns number
indexOf
javascript
ritzyed/ritzy
src/core/RichText.js
https://github.com/ritzyed/ritzy/blob/master/src/core/RichText.js
Apache-2.0
getTextRange(fromCharOrId, toCharOrId) { invariant(fromCharOrId, 'From char must be defined.') let fromMatched = false let chars = [] let fromId = _.has(fromCharOrId, 'id') ? fromCharOrId.id : fromCharOrId let toId if(!_.isUndefined(toCharOrId)) { toId = _.has(toCharOrId, 'id') ? toCharOrId.id : toCharOrId } if(fromId === toId) { return chars } for (let i = 0; i < this.data.len(); i++) { if (!fromMatched && this.data.matches(i, fromId)) { // the fromId is exclusive fromMatched = true if(fromId === toId) { chars.push(this.getCharAt(i)) return chars } } else if(toId && this.data.matches(i, toId)) { invariant(fromMatched, 'From id must precede To id.') chars.push(this.getCharAt(i)) return chars } else if(fromMatched) { chars.push(this.getCharAt(i)) } } return chars }
Gets all the chars from a given ID (exclusive) to a given ID (inclusive). The length of the returned range is going to be `pos(toChar) - pos(fromChar)`. @param {Char|string} fromCharOrId @param {Char|string} [toCharOrId = last] If the to char does not exist, then to char is the last char. @returns {Array}
getTextRange
javascript
ritzyed/ritzy
src/core/RichText.js
https://github.com/ritzyed/ritzy/blob/master/src/core/RichText.js
Apache-2.0
compareCharPos(charOrId1, charOrId2) { invariant(charOrId1, 'First char must be defined.') invariant(charOrId2, 'Second char must be defined.') if(charOrId1 === EOF && charOrId2 === EOF) return 0 else if(charOrId1 === EOF) return 1 else if(charOrId2 === EOF) return -1 let char1Id = _.has(charOrId1, 'id') ? charOrId1.id : charOrId1 let char2Id = _.has(charOrId2, 'id') ? charOrId2.id : charOrId2 let seen1 = false let seen1Index let seen2 = false let seen2Index for (let i = 0; i < this.data.len(); i++) { if (!seen1 && this.data.matches(i, char1Id)) { seen1 = true seen1Index = i // special case same char if(char1Id === char2Id) { return 0 } } if (!seen2 && this.data.matches(i, char2Id)) { seen2 = true seen2Index = i } if (seen1 && seen2) { if(seen1Index < seen2Index) return -1 else if(seen1Index === seen2Index) return 0 else return 1 } } throw new Error('One or both chars were not found.') }
Compares the position of two chars. Follows the contract of Java Comparator (http://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#compare-T-T-) and returns a negative integer, zero, or a positive integer as the first argument is positioned before, equal to, or positioned after the second. @param {Char|string} charOrId1 @param {Char|string} charOrId2 @return {number}
compareCharPos
javascript
ritzyed/ritzy
src/core/RichText.js
https://github.com/ritzyed/ritzy/blob/master/src/core/RichText.js
Apache-2.0
reduceOt = function(currentAdvance, char) { return currentAdvance + calcCharAdvanceOpenType(char, fontSize, font, unitsPerEm) }
Tests various string widths and compares the advance width (in pixels) results between OpenType.js and the canvas fallback mechanism which returns the browser's actual rendered font width. @type {Function}
reduceOt
javascript
ritzyed/ritzy
src/core/TextFontMetrics.js
https://github.com/ritzyed/ritzy/blob/master/src/core/TextFontMetrics.js
Apache-2.0