hudozka app added edit from 2018.02

This commit is contained in:
tmshv committed 2019-05-29 22:29:21 +03:00
1 parent 6805e07434
commit 759f1217b5
57 files changed
+3630 -1247

No files matched your search

+141
View File
@@ -0,0 +1,141 @@
import React, {Component} from 'react'
import Marker from '../Marker'
import './App.less'
import {MarkerWidgetHtml, MarkerWidgetText, MarkerWidgetUrl} from '../Marker/MarkerWidget'
import ContentEditable from '../Marker/ContentEditable'
import Editor from '../Editor/'
// import Map from '../Map'
// import Body from '../Body'
// import AppWrapper from './AppWrapper'
//
// import {bindActionCreators} from 'redux'
// import {connect} from 'react-redux'
// import * as actions from './duck'
//
// import {routerActions} from 'react-router-redux'
// import {title as defaultTitle} from '../../../config'
// import {getVariable} from '../../../lib/style'
// import {debounce} from '../../../lib/fn'
// const hit = debounce(50, path => ym('hit', path))
//
// const projectPath = project => `/projects/${project.name}`
// const frameSize = isVertical => [window.innerWidth, window.innerHeight]
// const frameSizeMultiplier = () => getVariable('--content-width-state-normal')
// const landscapeProjectBounds = (width, height, ratio=frameSizeMultiplier()) => [
// [0, 0],
// [width * ratio, 0],
// ]
// const portraitProjectBounds = (width, height, ratio=frameSizeMultiplier()) => [
// [0, 0],
// [0, width * ratio],
// ]
//
// function mapStateToProps(state) {
// const {fullPage, isVertical, halfPageAvailable} = state.app.page
//
// return {
// projects: state.app.projects.items,
// activeProject: state.app.projects.activeProject,
// fullPage: halfPageAvailable
// ? fullPage
// : true,
// showFullPageToggle: halfPageAvailable,
// isVertical,
// }
// }
//
// function mapDispatchToProps(dispatch) {
// return bindActionCreators({
// ...actions,
// push: routerActions.push
// }, dispatch)
// }
// async function build_document(data) {
// // text = data['caption'] if data['caption'] else data['file']
// // # document = await self.build()
// document = {
// 'url': data['file'],
// 'image_url': data['file'],
// 'file_url': data['file'],
// 'title': text,
// 'file_size': '0 KB',
// 'file_format': 'PDF',
// }
// return document
// }
// async function read_csv(data) {
// return '\n'.join([
// 'N,Name',
// `0,${data}`,
// '1,Pop',
// '2,Top',
// ])
// }
// async function read_document(data) {
// const doc = await Document.find_one({'id': data})
// return {
// 'url': doc['url'],
// 'image_url': doc['url'],
// 'file_url': doc['url'],
// 'title': doc['title'],
// 'file_size': '0 KB',
// 'file_format': 'PDF',
// }
// }
export default class App extends Component {
constructor(props) {
super(props)
this.onMarkerUpdate = this.onMarkerUpdate.bind(this)
this.state = {
tokens: [],
}
}
onMarkerUpdate(tokens) {
// console.log('Update')
// console.log(tokens)
this.setState({tokens})
}
componentWillMount() {
const {data, marker} = this.props
marker.evaluate(data)
.then(tokens => {
this.setState({
tokens,
})
})
// this.setState({
// data: this
// .getData()
// .reduce((acc, x) => [...acc, ...x], []),
// })
}
render() {
return (
<div className="App">
<div className={'App-Body'}>
<Editor/>
{/* <Marker */}
{/* data={this.state.tokens} */}
{/* marker={this.props.marker} */}
{/* onUpdate={this.onMarkerUpdate} */}
{/* /> */}
</div>
</div>
)
}
}
// export default connect(mapStateToProps, mapDispatchToProps)(App)
+9
View File
@@ -0,0 +1,9 @@
.App {
display: flex;
justify-content: center;
&-Body {
padding-top: 10px;
width: 800px;
}
}
+8
View File
@@ -0,0 +1,8 @@
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
});
+26
View File
@@ -0,0 +1,26 @@
.AppWrapper {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
z-index: 1000;
display: flex;
flex-direction: column;
justify-content: flex-start; /* align items in Main Axis */
align-items: stretch; /* align items in Cross Axis */
align-content: stretch; /* Extra space in Cross Axis */
pointer-events: none;
}
.AppWrapper footer {
background-color: rgba(34, 34, 34, 0.95);
color: #ebebeb;
padding: 1em 0.5em 0.5em;
font-weight: 100;
}
+88
View File
@@ -0,0 +1,88 @@
import React, {Component} from 'react'
import {Link} from 'react-router'
import './AppWrapper.css'
import './AppWrapperHeader.css'
import './AppWrapperBody.css'
import './AppWrapperContent.css'
import './Icon.css'
const Icon = ({children: iconName}) => (
<span className={`Icon ${iconName}`}/>
)
class Toggle extends Component {
constructor(props) {
super(props)
this.state = {
value: true
}
}
onClick = () => {
const {value} = this.state
const {onClick} = this.props
this.setState({
value: !value,
})
onClick(!value)
}
render() {
const {value} = this.state
const icon = value
? 'IconFullScreenOn'
: 'IconFullScreenOff'
return (
<button className="InvisibleButton" onClick={this.onClick}>
<Icon>{icon}</Icon>
</button>
)
}
}
const Head = ({title, onToggleFullPage, showFullPageToggle, showControls = false}) => (
<header className="AppWrapperHeader">
<div>
</div>
<div className="AppWrapperHeader-main">
<h1>{title}</h1>
</div>
<div>
{!showControls ? null : (
<div className="controls">
{!showFullPageToggle ? null: (
<Toggle onClick={onToggleFullPage}/>
)}
</div>
)}
</div>
</header>
)
const Body = ({children}) => (
<div className="AppWrapperBody">
<div className="AppWrapperContent">
{children}
</div>
</div>
)
const AppWrapper = ({title, children, showControls, showFullPageToggle, onToggleFullPage}) => (
<div className="AppWrapper">
<Head
title={title}
showControls={showControls}
onToggleFullPage={onToggleFullPage}
showFullPageToggle={showFullPageToggle}
/>
<Body>{children}</Body>
</div>
)
export default AppWrapper
+7
View File
@@ -0,0 +1,7 @@
.AppWrapperBody {
display: flex;
flex: 1;
width: 100%;
height: 100%;
}
@@ -0,0 +1,11 @@
.AppWrapperContent {
margin: 0;
padding: 0;
width: 100%;
position: relative;
/* Needed for when the area gets squished too far and there is content
that can't be displayed */
overflow: auto;
}
@@ -0,0 +1,39 @@
.AppWrapperHeader {
background-color: rgba(34, 34, 34, 0.95);
color: #ebebeb;
/*background-color: rgba(255, 255, 255, 0.95);*/
/*color: #222;*/
box-shadow: 0 3px 10px rgba(0, 0, 0, 0.15);
pointer-events: auto;
display: flex;
align-items: center;
}
.AppWrapperHeader-main {
flex: 1;
}
.AppWrapperHeader h1 {
text-align: center;
margin: 0;
padding: .5em 0 .4em;
font-size: 1.25rem;
font-weight: 100;
}
.controls {
margin: 0 15px;
}
.controls a{
color: #bbb;
text-decoration: none;
}
.controls a:hover{
color: white;
}
+37
View File
@@ -0,0 +1,37 @@
.Icon {
display: inline-block;
width: 20px;
height: 20px;
/*background: grey;*/
background-size: 100%;
}
.IconFullScreenOn {
background-image: url('/icon-fullscreen-on.svg');
}
.IconFullScreenOff {
background-image: url('/icon-fullscreen-off.svg');
}
.InvisibleButton {
background: none;
border: none;
outline: none;
}
.InvisibleButton {
width: 24px;
height: 24px;
padding: 0;
border-radius: 0;
cursor: pointer;
}
/*.InvisibleButton:focus {*/
/*border: 2px solid #2f9fff;*/
/*}*/
+107
View File
@@ -0,0 +1,107 @@
import {combineReducers} from 'redux'
import api from '../../../api'
import {pack} from '../../../lib/fn'
import {isMobile, isLandscape} from '../../../lib/device'
const FETCH_PROJECTS = 'arch/app/FETCH_PROJECTS'
const FOCUS_PROJECT = 'arch/app/FOCUS_PROJECT'
const TOGGLE_FULL_PAGE = 'arch/app/TOGGLE_FULL_PAGE'
const CHANGE_PAGE_ORIENTATION = 'arch/app/CHANGE_PAGE_ORIENTATION'
export const PAGE_ORIENTATION_LANDSCAPE = 'landscape'
export const PAGE_ORIENTATION_PORTRAIT = 'portrait'
export function fetchProjects() {
return {
type: FETCH_PROJECTS,
async: api.projects.fetch()
.then(pack('data'))
}
}
export function focusProject(projectName) {
return {
type: FOCUS_PROJECT,
projectName
}
}
export function toggleFullPage() {
return {
type: TOGGLE_FULL_PAGE,
}
}
export function changePageOrientation(orientation) {
return {
type: CHANGE_PAGE_ORIENTATION,
orientation,
}
}
const init = {
items: [],
total: 0,
activeProject: null,
}
const initPage = {
fullPage: false,
halfPageAvailable: !isMobile(),
isVertical: !isLandscape(),
}
function projects(state = init, action) {
switch (action.type) {
case FETCH_PROJECTS: {
const {items, total} = action.data
return {...state, items, total}
}
case FOCUS_PROJECT: {
const projectName = action.projectName
const activeProject = state.items.find(p => p.name === projectName)
return {...state, activeProject}
}
default:
return state
}
}
function page(state = initPage, action) {
switch (action.type) {
case TOGGLE_FULL_PAGE: {
const fullPage = !state.fullPage
return {...state, fullPage}
}
case CHANGE_PAGE_ORIENTATION: {
const {orientation} = action
const isVertical = orientation === PAGE_ORIENTATION_PORTRAIT
return {...state, isVertical}
}
case FOCUS_PROJECT: {
let fullPage = state.fullPage
const projectName = action.projectName
fullPage = !projectName
? false
: fullPage
return {...state, fullPage}
}
default:
return state
}
}
export default combineReducers({
projects,
page,
})
+1
View File
@@ -0,0 +1 @@
export {default} from './App'
+11
View File
@@ -0,0 +1,11 @@
/**
* Draft v0.10.5
*
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
.DraftEditor-editorContainer,.DraftEditor-root,.public-DraftEditor-content{height:inherit;text-align:initial}.public-DraftEditor-content[contenteditable=true]{-webkit-user-modify:read-write-plaintext-only}.DraftEditor-root{position:relative}.DraftEditor-editorContainer{background-color:rgba(255,255,255,0);border-left:.1px solid transparent;position:relative;z-index:1}.public-DraftEditor-block{position:relative}.DraftEditor-alignLeft .public-DraftStyleDefault-block{text-align:left}.DraftEditor-alignLeft .public-DraftEditorPlaceholder-root{left:0;text-align:left}.DraftEditor-alignCenter .public-DraftStyleDefault-block{text-align:center}.DraftEditor-alignCenter .public-DraftEditorPlaceholder-root{margin:0 auto;text-align:center;width:100%}.DraftEditor-alignRight .public-DraftStyleDefault-block{text-align:right}.DraftEditor-alignRight .public-DraftEditorPlaceholder-root{right:0;text-align:right}.public-DraftEditorPlaceholder-root{color:#9197a3;position:absolute;z-index:1}.public-DraftEditorPlaceholder-hasFocus{color:#bdc1c9}.DraftEditorPlaceholder-hidden{display:none}.public-DraftStyleDefault-block{position:relative;white-space:pre-wrap}.public-DraftStyleDefault-ltr{direction:ltr;text-align:left}.public-DraftStyleDefault-rtl{direction:rtl;text-align:right}.public-DraftStyleDefault-listLTR{direction:ltr}.public-DraftStyleDefault-listRTL{direction:rtl}.public-DraftStyleDefault-ol,.public-DraftStyleDefault-ul{margin:16px 0;padding:0}.public-DraftStyleDefault-depth0.public-DraftStyleDefault-listLTR{margin-left:1.5em}.public-DraftStyleDefault-depth0.public-DraftStyleDefault-listRTL{margin-right:1.5em}.public-DraftStyleDefault-depth1.public-DraftStyleDefault-listLTR{margin-left:3em}.public-DraftStyleDefault-depth1.public-DraftStyleDefault-listRTL{margin-right:3em}.public-DraftStyleDefault-depth2.public-DraftStyleDefault-listLTR{margin-left:4.5em}.public-DraftStyleDefault-depth2.public-DraftStyleDefault-listRTL{margin-right:4.5em}.public-DraftStyleDefault-depth3.public-DraftStyleDefault-listLTR{margin-left:6em}.public-DraftStyleDefault-depth3.public-DraftStyleDefault-listRTL{margin-right:6em}.public-DraftStyleDefault-depth4.public-DraftStyleDefault-listLTR{margin-left:7.5em}.public-DraftStyleDefault-depth4.public-DraftStyleDefault-listRTL{margin-right:7.5em}.public-DraftStyleDefault-unorderedListItem{list-style-type:square;position:relative}.public-DraftStyleDefault-unorderedListItem.public-DraftStyleDefault-depth0{list-style-type:disc}.public-DraftStyleDefault-unorderedListItem.public-DraftStyleDefault-depth1{list-style-type:circle}.public-DraftStyleDefault-orderedListItem{list-style-type:none;position:relative}.public-DraftStyleDefault-orderedListItem.public-DraftStyleDefault-listLTR:before{left:-36px;position:absolute;text-align:right;width:30px}.public-DraftStyleDefault-orderedListItem.public-DraftStyleDefault-listRTL:before{position:absolute;right:-36px;text-align:left;width:30px}.public-DraftStyleDefault-orderedListItem:before{content:counter(ol0) ". ";counter-increment:ol0}.public-DraftStyleDefault-orderedListItem.public-DraftStyleDefault-depth1:before{content:counter(ol1) ". ";counter-increment:ol1}.public-DraftStyleDefault-orderedListItem.public-DraftStyleDefault-depth2:before{content:counter(ol2) ". ";counter-increment:ol2}.public-DraftStyleDefault-orderedListItem.public-DraftStyleDefault-depth3:before{content:counter(ol3) ". ";counter-increment:ol3}.public-DraftStyleDefault-orderedListItem.public-DraftStyleDefault-depth4:before{content:counter(ol4) ". ";counter-increment:ol4}.public-DraftStyleDefault-depth0.public-DraftStyleDefault-reset{counter-reset:ol0}.public-DraftStyleDefault-depth1.public-DraftStyleDefault-reset{counter-reset:ol1}.public-DraftStyleDefault-depth2.public-DraftStyleDefault-reset{counter-reset:ol2}.public-DraftStyleDefault-depth3.public-DraftStyleDefault-reset{counter-reset:ol3}.public-DraftStyleDefault-depth4.public-DraftStyleDefault-reset{counter-reset:ol4}
+313
View File
@@ -0,0 +1,313 @@
import React from 'react'
import Immutable from 'immutable'
import {
DefaultDraftBlockRenderMap,
EditorState,
RichUtils,
convertFromRaw,
getDefaultKeyBinding,
AtomicBlockUtils,
Modifier
} from 'draft-js'
import DraftEditor, {composeDecorators} from 'draft-js-plugins-editor'
import createImagePlugin from 'draft-js-image-plugin'
import createAlignmentPlugin from 'draft-js-alignment-plugin'
import createFocusPlugin from 'draft-js-focus-plugin'
import createResizeablePlugin from 'draft-js-resizeable-plugin'
import createBlockDndPlugin from 'draft-js-drag-n-drop-plugin'
// import createDragNDropUploadPlugin from 'draft-js-drag-n-drop-upload-plugin'
import createDndFileUploadPlugin from '@mikeljames/draft-js-drag-n-drop-upload-plugin'
// import './Draft.less'
import 'draft-js/dist/Draft.css'
import 'draft-js-image-plugin/lib/plugin.css'
const focusPlugin = createFocusPlugin()
const resizeablePlugin = createResizeablePlugin()
const blockDndPlugin = createBlockDndPlugin()
const alignmentPlugin = createAlignmentPlugin()
const {AlignmentTool} = alignmentPlugin
const decorator = composeDecorators(
resizeablePlugin.decorator,
alignmentPlugin.decorator,
focusPlugin.decorator,
blockDndPlugin.decorator
)
const imagePlugin = createImagePlugin({decorator})
const dndFileUploadPlugin = createDndFileUploadPlugin({
handleUpload: console.log,
addImage: imagePlugin.addImage,
})
// const dragNDropFileUploadPlugin = createDragNDropUploadPlugin({
// handleUpload: mockUpload,
// addImage: imagePlugin.addImage,
// })
const plugins = [
dndFileUploadPlugin,
blockDndPlugin,
focusPlugin,
alignmentPlugin,
resizeablePlugin,
imagePlugin
]
const initialState = {
'entityMap': {
'0': {
'type': 'IMAGE',
'mutability': 'IMMUTABLE',
'data': {
'src': 'https://static.shlisselburg.org/art/images/7c206b4e211bb8486801fd84a3bf309b-big.jpg'
}
}
},
'blocks': [
{
'key': '9gm3s',
'text': 'You can have images in your text field. This is a very rudimentary example, but you can enhance the image plugin with resizing, focus or alignment plugins.',
'type': 'unstyled',
'depth': 0,
'inlineStyleRanges': [],
'entityRanges': [],
'data': {}
},
{
'key': 'ov7r',
'text': ' ',
'type': 'atomic',
'depth': 0,
'inlineStyleRanges': [],
'entityRanges': [{
'offset': 0,
'length': 1,
'key': 0
}],
'data': {}
},
{
'key': 'e23a8',
'text': 'See advanced examples further down …',
'type': 'unstyled',
'depth': 0,
'inlineStyleRanges': [],
'entityRanges': [],
'data': {}
}
]
}
class MyCustomBlock extends React.Component {
// constructor(props) {
// super(props)
// }
render() {
return (
<div className='MyCustomBlock'>
{/* here, this.props.children contains a <section> container, as that was the matching element */}
{this.props.children}
</div>
)
}
}
class MediaComponent extends React.Component {
render() {
const {block, contentState} = this.props
const {foo} = this.props.blockProps
const data = contentState.getEntity(block.getEntityAt(0)).getData()
console.log(data)
return (
<i>
{data.text}
<img src={data.text} alt=""/>
</i>
)
// Return a <figure> or some other content using this data.
}
}
function blockRendererFn(contentBlock) {
const type = contentBlock.getType()
if (type === 'atomic') {
console.log('blockRendererFn', contentBlock.getKey(), type)
return {
component: MediaComponent,
editable: false,
props: {
foo: 'bar',
},
}
} else {
return null
}
}
const blockRenderMap = Immutable.Map({
'section': {
element: 'section',
wrapper: MyCustomBlock,
}
})
// Include 'paragraph' as a valid block and updated the unstyled element but
// keep support for other draft default block types
const extendedBlockRenderMap = DefaultDraftBlockRenderMap.merge(blockRenderMap)
export default class Editor extends React.Component {
constructor(props) {
super(props)
this.state = {
editorState: EditorState.createWithContent(convertFromRaw(initialState)),
}
this.onChange = this.onChange.bind(this)
this.onBoldClick = () => {
this.onChange(RichUtils.toggleInlineStyle(this.state.editorState, 'BOLD'))
}
this.focus = () => {
this.editor.focus()
}
this.onZomboClick = () => {
const contentState = this.state.editorState.getCurrentContent();
const contentStateWithEntity = contentState.createEntity(
'LINK',
'MUTABLE',
{url: 'http://www.zombo.com'}
)
const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
const contentStateWithLink = Modifier.applyEntity(
contentStateWithEntity,
selectionState,
entityKey
)
this.onChange(contentStateWithLink);
// this.onChange(RichUtils.toggleInlineStyle(this.state.editorState, 'BOLD'))
}
this.handleKeyCommand = this.handleKeyCommand.bind(this)
this.keyBindingFn = this.keyBindingFn.bind(this)
this.insertBlock = this.insertBlock.bind(this)
}
insertBlock(type, data) {
const {editorState} = this.state
const contentState = editorState.getCurrentContent()
const contentStateWithEntity = contentState.createEntity(type, 'IMMUTABLE', data)
const entityKey = contentStateWithEntity.getLastCreatedEntityKey()
const newEditorState = EditorState.set(editorState, {
currentContent: contentStateWithEntity
})
this.setState({
editorState: AtomicBlockUtils.insertAtomicBlock(newEditorState, entityKey, ' '),
})
}
onChange(editorState) {
const content = editorState.getCurrentContent()
const s = editorState.getSelection()
const key = s.getStartKey()
const prevKey = content.getKeyBefore(key)
const block = content.getBlockForKey(key)
const prevBlock = content.getBlockForKey(prevKey)
const text = block.getText()
if (/\.jpg/.test(text)) {
this.insertBlock('jpg', {text})
// const newContent = Modifier.setBlockType(content, s, 'atomic')
//
// const newEditorState = EditorState.set(editorState, {
// currentContent: newContent,
// })
//
// this.setState({
// editorState: newEditorState,
// })
} else {
this.setState({editorState})
}
// const blockData = block.getData()
// console.log(block.getText(), block.getType())
// console.log(block.getEntityAt(0))
}
keyBindingFn(e) {
// console.log("K", e.key)
// if (e.key === 'Enter') {
// return 'enter'
// }
return getDefaultKeyBinding(e)
}
handleKeyCommand(command) {
console.log('CMD', command)
const newState = RichUtils.handleKeyCommand(this.state.editorState, command)
if (newState) {
this.onChange(newState)
return 'handled'
}
return 'not-handled'
}
render() {
const content = this.state.editorState.getCurrentContent()
const e = this.state.editorState
const s = e.getSelection()
const key = s.getStartKey()
const so = s.getStartOffset()
const block = content.getBlockForKey(key)
return (
<div>
<DraftEditor
editorState={this.state.editorState}
onChange={this.onChange}
blockRendererFn={blockRendererFn}
blockRenderMap={extendedBlockRenderMap}
handleKeyCommand={this.handleKeyCommand}
keyBindingFn={this.keyBindingFn}
plugins={plugins}
ref={(element) => {
this.editor = element
}}
/>
{/* <AlignmentTool/> */}
<button onClick={this.onBoldClick}>Bold</button>
<div>
<p>
block key: {key} type: {block.getType()}
</p>
<p>
start offset {so}
</p>
<pre>
{content.getPlainText('\n')}
</pre>
</div>
</div>
)
}
}
Whitespace-only changes.
+1
View File
@@ -0,0 +1 @@
export {default} from './Editor'
@@ -0,0 +1,78 @@
import React, {Component} from 'react'
export default class ContentEditable extends Component {
constructor(props) {
super(props)
this.emitChange = this.emitChange.bind(this)
this.onRef = this.onRef.bind(this)
}
getHtml() {
return this.props.children
}
onRef(element) {
this.htmlEl = element
}
emitChange() {
if (!this.htmlEl) return
const html = this.htmlEl.innerHTML
if (html !== this.lastHtml) this.props.onChange(html)
this.lastHtml = html
}
componentDidMount() {
this.htmlEl.focus()
}
shouldComponentUpdate(nextProps) {
let {props, htmlEl} = this
// We need not rerender if the change of props simply reflects the user's edits.
// Rerendering in this case would make the cursor/caret jump
// Rerender if there is no element yet... (somehow?)
if (!this.htmlEl) return true
// // ...or if html really changed... (programmatically, not by user edit)
// if (nextProps.html !== htmlEl.innerHTML && nextProps.html !== props.html) {
// return true
// }
return false
// let optional = ['style', 'className', 'disabled', 'tagName']
//
// // Handle additional properties
// return optional.some(name => props[name] !== nextProps[name])
}
componentDidUpdate() {
const html = this.getHtml()
if (this.htmlEl && this.htmlEl.innerHTML !== html) {
// Perhaps React (whose VDOM gets outdated because we often prevent
// rerendering) did not update the DOM. So we update it manually now.
this.htmlEl.innerHTML = html
}
}
render() {
const {mix} = this.props;
return <div
className={mix}
ref={this.onRef}
onInput={this.emitChange}
onChange={this.emitChange}
// onBlur={this.props.onBlur || this.emitChange}
contentEditable={true}
suppressContentEditableWarning={true}
// dangerouslySetInnerHTML={{__html: this.getHtml()}}
>
{this.getHtml()}
</div>
}
}
+214
View File
@@ -0,0 +1,214 @@
import React, {Component} from 'react'
import {MarkerTabIndex} from './MarkerTabIndex'
import {MarkerCell} from './MarkerCell'
import './Marker.less'
import {exist} from '../../lib/fn'
import ContentEditable from './ContentEditable'
import {constrain} from "./lib/fn";
export class Marker extends Component {
constructor(props) {
super(props)
this.state = {
currentCellIndex: 0,
}
this.onCellUpdate = this.onCellUpdate.bind(this)
this.onCellSelect = this.onCellSelect.bind(this)
this.onKeyDown = this.onKeyDown.bind(this)
}
onKeyDown(event) {
switch (event.key) {
case 'ArrowUp': {
console.log('Marker ArrowUp')
this.setState({
currentCellIndex: this.getPrevCellIndex(),
})
break
}
case 'ArrowDown': {
console.log('Marker ArrowDown')
this.setState({
currentCellIndex: this.getNextCellIndex(),
})
break
}
case 'Enter': {
console.log('Marker Enter')
const s = getSelection()
console.log(s, s.getRangeAt(0))
event.preventDefault()
// if (!event.shiftKey) return
// event.stopPropagation()
return this.handleEnter()
}
}
};
getCellIndex(n) {
const {data} = this.props
const {currentCellIndex} = this.state
const index = currentCellIndex + n
return constrain(index, 0, data.length - 1)
}
getPrevCellIndex(...args) {
return this.getCellIndex(-1, ...args)
}
getNextCellIndex(...args) {
return this.getCellIndex(1, ...args)
}
onCellSelect(index) {
this.setState({
currentCellIndex: index,
})
}
getDataAt(index) {
return this.props.data[index]
}
getBlankTextAt(index) {
if (index === 0) return ''
const cellBefore = this.getDataAt(index)
const textBefore = cellBefore.data
let text
const ol = (text) => {
const m = /^(\d+)\.\s/.exec(text)
if (m) {
const d = parseFloat(m[1])
return `${d + 1}.`
} else {
return null
}
}
const ul = (text) => /^-\s/.test(text)
? '- '
: null
text = ol(textBefore)
if (text) return text
text = ul(textBefore)
if (text) return text
return ''
}
async handleEnter() {
const {currentCellIndex} = this.state
const currentCell = this.getDataAt(currentCellIndex)
if (currentCell.data) {
const nextCellIndex = currentCellIndex + 1
if (nextCellIndex > this.props.data.length - 1) {
const {data, marker, onUpdate} = this.props
const blankText = this.getBlankTextAt(currentCellIndex)
const newCell = await marker.blank({text: blankText})
const newData = [
...data,
newCell,
]
onUpdate(newData)
} else {
}
this.setState({
currentCellIndex: nextCellIndex,
})
}
}
async onCellUpdate(index, text) {
console.log('UPDATE', text)
const {data, marker, onUpdate} = this.props
const cells = await marker.evaluate(text)
const before = data.slice(0, index)
const after = data.slice(index + 1)
let newData = [
...before,
...cells,
...after,
]
// const next = index + cells.length
// if (next > newData.length - 1) {
// const newCell = await marker.blank()
// newData.push(newCell)
// }
console.log(newData.map(x => x.data).join('\n'))
onUpdate(newData)
}
componentWillMount() {
// this.setState({
// currentCellIndex: 0,
// })
}
render() {
const {data} = this.props
if (!data.length) return null
const {currentCellIndex} = this.state
const tabIndex = 1
return (
<div
className='Marker'
// onKeyDownCapture={this.onKeyDown}
onKeyDown={this.onKeyDown}
>
{data.map((x, i) => {
return (i === currentCellIndex ? (
<ContentEditable
mix={'MarkerCell'}
tabIndex={tabIndex + i}
key={i}
onChange={text => this.onCellUpdate(i, text)}
>
{x.data}
</ContentEditable>
) : (
<div
className={'MarkerCell'}
tabIndex={tabIndex + i}
key={i}
onFocus={() => this.onCellSelect(i)}
>
{x.render()}
</div>
)
)
})}
</div>
)
}
}
+52
View File
@@ -0,0 +1,52 @@
.Marker {
//--active-color: #73acf6;
--active-color: #f0f0f0;
--cell-padding: 8px;
--font-size: 16px;
font-size: var(--font-size);
font-family: sans-serif;
//line-height: var(--font-size);
textarea {
width: 100%;
font-size: var(--font-size);
font-family: sans-serif;
padding: 0;
box-sizing: border-box;
height: var(--font-size);
//height: calc(2px + var(--font-size));
border: none;
background-color: var(--active-color);
outline: none;
display: block;
}
}
.MarkerCellTabIndex {
outline: none;
}
.MarkerCell {
//padding: var(--cell-padding);
padding-bottom: 8px;
position: relative;
&--active {
background-color: var(--active-color);
//background-color: #f6903b;
}
&--edit {
div {
outline: none;
}
//background-color: #00b7ec;
background-color: var(--active-color);
}
}
+72
View File
@@ -0,0 +1,72 @@
import React, {Component} from 'react'
import className from 'classnames'
import {trimNewline} from './lib/fn'
import './Marker.less'
import {MarkerEdit} from './MarkerEdit'
const Cell = ({children, active = false, edit = false}) => (
<div className={className('MarkerCell', {
'MarkerCell--active': active,
'MarkerCell--edit': edit,
})}>
{children}
</div>
)
export class MarkerCell extends Component {
constructor(props) {
super(props)
this.onSubmit = this.onSubmit.bind(this)
this.onChange = this.onChange.bind(this)
this.state = {
content: null,
}
}
getCellData() {
return this.state.content
? this.state.content
: this.props.cell.data
}
getCellComponent() {
return this.props.cell.render()
}
onSubmit(e) {
e.preventDefault()
const {onUpdate} = this.props
onUpdate(this.getCellData())
}
onChange(e) {
const content = trimNewline(e.target.value)
this.setState({
content,
})
}
render() {
const {active, edit} = this.props
return edit
? (
<Cell edit={edit}>
<MarkerEdit
onSubmit={this.onSubmit}
onChange={this.onChange}
>
{this.getCellData()}
</MarkerEdit>
</Cell>
) : (
<Cell active={active}>
{this.getCellComponent()}
</Cell>
)
}
}
+85
View File
@@ -0,0 +1,85 @@
import React, {Component, createContext} from 'react'
import className from 'classnames'
import {trim} from './lib/fn'
import {MarkerContext} from './Marker'
import './Marker.less'
import ContentEditable from './ContentEditable'
export class MarkerEdit extends Component {
constructor(props) {
super(props)
// this.onInputRef = this.onInputRef.bind(this)
this.onChange = this.onChange.bind(this)
this.onFocus = this.onFocus.bind(this)
this.onKeyDown = this.onKeyDown.bind(this)
}
onChange(event) {
console.log(event, event.target)
this.props.onChange(event)
}
onFocus(e) {
e.stopPropagation()
}
onKeyDown(event) {
switch (event.key) {
case 'ArrowUp': {
if (event.shiftKey) return
event.stopPropagation()
break
}
case 'ArrowDown': {
if (event.shiftKey) return
event.stopPropagation()
break
}
case 'Enter': {
console.log('MarkerEdit Enter')
if (event.shiftKey) return
// event.stopPropagation()
const {onSubmit} = this.props
onSubmit(event)
}
}
}
// onInputRef(e) {
// this.input = e
// }
//
// componentDidMount() {
// this.input.focus()
// }
render() {
const {children} = this.props
return (
<ContentEditable
// ref={this.onInputRef}
onChange={this.onChange}
onFocus={this.onFocus}
onKeyDown={this.onKeyDown}
>
{children}
</ContentEditable>
)
// return (
// <textarea
// value={children}
// ref={this.onInputRef}
// onChange={onChange}
// onFocus={this.onFocus}
// onKeyDown={this.onKeyDown}
// />
// )
}
}
@@ -0,0 +1,43 @@
import React, {Component, createContext} from 'react'
import './Marker.less'
export class MarkerTabIndex extends Component {
constructor(props) {
super(props)
this.onFocus = this.onFocus.bind(this)
this.onRef = this.onRef.bind(this)
}
onFocus() {
const {onFocus, data} = this.props
onFocus(data)
}
onRef(e) {
this.element = e
}
componentDidUpdate() {
const {focus} = this.props
if (focus) {
this.element.focus()
}
}
render() {
const {tabIndex, children} = this.props
return (
<div
className={'MarkerCellTabIndex'}
children={children}
tabIndex={tabIndex}
onFocus={this.onFocus}
ref={this.onRef}
role={'button'}
/>
)
}
}
+28
View File
@@ -0,0 +1,28 @@
import React from 'react'
import './Marker.less'
export const MarkerWidgetText = ({text}) => (
<div
className='MarkerWidgetText'
>
{text}
</div>
)
export const MarkerWidgetHtml = ({html}) => (
<div
className='MarkerWidgetHtml'
dangerouslySetInnerHTML={{__html: html}}
/>
)
export const MarkerWidgetUrl = ({url, text}) => (
<div
className='MarkerWidgetUrl'
>
<a href={url}>
{text}
</a>
</div>
)
+1
View File
@@ -0,0 +1 @@
export {Marker as default} from './Marker'
+31
View File
@@ -0,0 +1,31 @@
/**
* Remove trailing spaces from string
*
* f(_x_) => x
*
* @param str
*/
export function trim(str) {
return str
.replace(/^\s+/, '')
.replace(/\s+$/, '')
}
/**
* Remove trailing spaces from string
*
* f(_x_) => x
*
* @param str
*/
export function trimNewline(str) {
return str
.replace(/^\n+/, '')
.replace(/\n+$/, '')
}
export function constrain(n, min, max) {
if (n < min) return min
if (n > max) return max
return n
}
@@ -0,0 +1,34 @@
import React from 'react'
import Token from './Token'
import {trim} from '../fn'
import {getHtml} from './index'
export default class FileToken extends Token {
static test(data) {
return is_file(data, documentExtensions + imageExtensions)
}
constructor({data}) {
super({
name: 'file',
data,
})
this.joinable = false
}
async compile() {
const data = parse_file(this.getData())
const url = data['file']
const text = data.caption
? data.caption
: url
return (
<a href={url}>
{text}
</a>
)
}
}
@@ -0,0 +1,78 @@
import React from 'react'
import Token from './Token'
import {isImage, parseFile} from './index'
export class ImageToken extends Token {
static test(data) {
return isImage(data)
}
constructor({data}) {
super({
name: 'image',
data,
})
this.joinable = true
this.build = null
}
merge(token) {
const mergedToken = new ImageCollectionToken([this.data, token.data])
mergedToken.build = this.build
return mergedToken
}
async compile() {
}
}
export class ImageCollectionToken extends ImageToken {
constructor({data}) {
super({data})
this.name = 'image_collection'
this.build = null
}
merge(token) {
const data = Array.isArray(token.getData())
? token.getData()
: [token.getData()]
const mergedToken = new ImageCollectionToken({
data: [...self.getData(), ...data]
})
mergedToken.build = self.build
return mergedToken
}
async compile() {
const data = this.parseData()
let images = []
for (let x of data) {
const img = await this.build(x)
images.push(img)
}
return (
<div className='kazimir__image-collection'>
<div
className='fotorama'
data-width='100%'
data-ratio='800/600'
>
{images.map(({src}) => (
<img src={src}/>
))}
</div>
</div>
)
}
parseData() {
return this
.getData()
.map(parseFile)
}
}
@@ -0,0 +1,138 @@
import SplitToken from './SplitToken'
export class Marker {
constructor() {
this.tokenFactories = []
this.treeMiddlewares = []
this.join = true
this.blankFactory = null
}
async blank({text}) {
if (!this.blankFactory) {
throw new Error(`Blank factory is not defined`)
}
const token = await this.blankFactory.create(text)
return token.compile()
}
addTokenFactory(tokenFactory, {blank = false} = {}) {
this.tokenFactories.push(tokenFactory)
if (blank) {
this.blankFactory = tokenFactory
}
return this
}
addTreeMiddleware(callback) {
this.treeMiddlewares.push(callback)
return this
}
async evaluate(text) {
let tokens = text.split('\n')
tokens = this.markupTokens(tokens)
if (this.join) {
tokens = this.joinTokens(tokens)
}
return compileTokens(tokens)
// tree = lxml.html.fromstring(compiled)
// return await self.process_tree(tree)
}
joinTokens(tokens) {
return mergeTokens(joinTokens(tokens))
}
async processTree(tree) {
// for fn in self.treeMiddlewares:
// tree = await fn(tree)
// return tree
}
markupTokens(tokens) {
const markedTokens = []
tokens.forEach(data => {
const token = this.createToken(data)
if (!token) {
throw new Error(`Token not recognized for data ${data}`)
}
markedTokens.push(token)
})
return markedTokens
}
createToken(data) {
for (let factory of this.tokenFactories) {
if (factory.test(data)) {
return factory.create(data)
}
}
return null
}
}
function joinTokens(tokens) {
const isSplit = x => x instanceof SplitToken
let bufferTag = null
let tokensBuffer = []
let tokensList = []
for (let token of tokens) {
const tag = token.name
const changed = bufferTag !== null && tag !== bufferTag
let flush = isSplit(token)
if (changed) {
flush = true
}
if (!token.isJoinable()) {
flush = true
}
if (flush) {
if (tokensBuffer.length) {
tokensList.push(tokensBuffer)
}
if (isSplit(token)) {
tokensBuffer = []
bufferTag = null
} else {
tokensBuffer = [token]
bufferTag = tag
}
} else {
bufferTag = tag
tokensBuffer.push(token)
}
}
if (tokensBuffer.length) {
tokensList.push(tokensBuffer)
}
return tokensList
}
function mergeTokens(tokensList) {
return tokensList
.map(ts => ts
.reduce(
(token, x) => token.merge(x)
)
)
}
async function compileTokens(tokens) {
return Promise.all(
tokens.map(x => x.compile())
)
}
@@ -0,0 +1,24 @@
import Token from './Token'
import {trim} from '../fn'
export default class SplitToken extends Token {
static test(data) {
data = trim(data)
return data === ''
}
constructor(options) {
super({
...options,
name: 'split',
})
}
render() {
return null
}
merge(token) {
return this
}
}
@@ -0,0 +1,44 @@
import Token from './Token'
import {trim} from '../fn'
import {getHtml} from './index'
export default class TextToken extends Token {
static test(data) {
return true
}
constructor(options) {
super({
...options,
name: 'text',
})
}
merge(token) {
const data = [this.data, token.data].join('\n')
return new TextToken(this.getMergeOptions({
data: trim(data),
}))
}
async getData() {
const html = getHtml(this.data)
return {html}
}
// async compile() {
// // return getHtml(this.getData())
//
//
//
//
//
// return (
// <div
// className='MarkerWidgetHtml'
// dangerouslySetInnerHTML={{__html: html}}
// />
// )
// }
}
@@ -0,0 +1,51 @@
export default class Token {
static test(data) {
return true
}
constructor({name, data, component}) {
this.name = name
this.data = data
this.component = component
this.joinable = true
this.compiledData = null
}
isJoinable() {
return this.joinable
}
render() {
if (!this.compiledData) {
throw new Error('Token not compiled. Call Token::compile before.')
}
return this.component(this.compiledData)
}
async getData() {
return this.data
}
async compile() {
this.compiledData = await this.getData()
return this
}
merge(token) {
return this
}
getMergeOptions(extend) {
return {
name: this.name,
data: this.data,
component: this.component,
...extend,
}
}
toString() {
return `[Token ${this.name} ${this.data}]`
}
}
@@ -0,0 +1,35 @@
export class TokenFactory {
constructor({token, component}) {
this.token = token
this.component = component
}
test(sample) {
return this.token.test(sample)
}
create(data) {
const Token = this.token
return new Token({
data,
component: this.component,
})
}
}
export class BuildTokenFactory extends TokenFactory {
constructor({token, build, component}) {
super({token})
this.build = build
this.component = component
}
create(data) {
const Token = this.token
return new Token({
data,
component: this.component,
build: this.build,
})
}
}
@@ -0,0 +1,16 @@
import Token from './Token'
import {isUrl} from './index'
export default class UrlToken extends Token {
static test(data) {
return isUrl(data)
}
constructor(options) {
super({
...options,
name: 'url',
})
this.joinable = false
}
}
@@ -0,0 +1,24 @@
import {isUrl} from './index'
import React from 'react'
import UrlToken from './UrlToken'
export default class YoutubeToken extends UrlToken {
static test(data) {
if (!isUrl(data)) {
return false
}
const url = new URL(data)
return ['www.youtube.com', 'youtube.com']
.includes(url.hostname)
}
async getData() {
const url = new URL(this.data)
const youtubeId = url.searchParams.get('v')
return {
url: `//www.youtube.com/embed/${youtubeId}`
}
}
}
@@ -0,0 +1,76 @@
import {markdown} from 'markdown'
const {toHTML: markdownToHtml} = markdown
const splitExt = s => {
const parts = s.split('.')
const name = parts.splice(0, parts.length - 1)
const ext = parts[parts.length - 1]
return {name, ext}
}
export const imageExtensions = ['.jpg', '.jpeg', '.png']
export const documentExtensions = ['.doc', '.docx', '.pdf', '.xls', '.xlsx']
export function getHtml(text) {
return markdownToHtml(text)
}
export function isUrl(sample) {
try {
return Boolean(new URL(sample))
} catch (e) {
return false
}
}
export function isImage(sample) {
const file = parseFile(sample)['file']
return isFile(file, imageExtensions)
}
export function isDocument(sample) {
const file = parseFile(sample)['file']
return isFile(file, documentExtensions)
}
export function isFile(sample, extensions) {
let {name, ext} = splitExt(sample)
ext = ext.toLowerCase()
return extensions.include(ext)
}
export function parseFile(sample) {
const re = /![(.*)]((.*))/
const p = re.exec(sample)
let caption
let file
if (p) {
caption = p.group(1)
file = p.group(2)
} else {
sample = sample.split(' ')
file = sample[0]
caption = ' '.join(sample.substr(1))
}
return {
file,
caption,
}
}
export function parseLink(sample) {
const re = /![(.*)]((.*))/
const p = re.exec(sample)
if (!p) {
return null
}
const url = p[2]
return {
url: new URL(url),
alt: p[1],
}
}