0
0
mirror of https://github.com/naturalcrit/homebrewery.git synced 2026-01-23 14:23:21 +00:00

add color-selector component and colorings

This commit is contained in:
Charlie Humphreys
2023-07-17 00:46:55 -05:00
parent 46f413c656
commit 379f260de5
11 changed files with 236 additions and 49 deletions

View File

@@ -3,6 +3,7 @@
@import (less) 'codemirror/addon/search/matchesonscrollbar.css';
@import (less) 'codemirror/addon/dialog/dialog.css';
@import (less) 'codemirror/addon/hint/show-hint.css';
@import 'naturalcrit/styles/colors.less';
@keyframes sourceMoveAnimation {
50% {background-color: red; color: white;}
@@ -52,4 +53,30 @@
max-width: 10vw;
}
}
.widget-field {
border: 2px solid #ddd;
&.default {
background-color: @purple;
border: 2px solid @purple;
color: white;
>input {
background-color: @purple;
color: white;
}
}
&.suggested {
background-color: #ddd;
border: 2px dashed grey;
color: grey;
>input {
background-color: #ddd;
color: black;
}
}
}
}

View File

@@ -7,10 +7,11 @@ const CodeMirror = require('../../../code-mirror.js');
const Checkbox = createClass({
getDefaultProps : function() {
return {
value : '',
prefix : '',
cm : {},
n : -1
value : '',
prefix : '',
cm : {},
n : -1,
default : false
};
},
@@ -28,11 +29,15 @@ const Checkbox = createClass({
},
render : function() {
const { cm, n, value, prefix } = this.props;
const { cm, n, value, prefix, def } = this.props;
const { text } = cm.lineInfo(n);
const id = [prefix, value, n].join('-');
let className = 'widget-field widget-checkbox';
if(def) {
className += ' default';
}
return <React.Fragment>
<div className='widget-checkbox'>
<div className={className}>
<input type='checkbox' id={id} onChange={this.handleChange} checked={_.includes(text, `,${value}`)}/>
<label htmlFor={id}>{_.startCase(value)}</label>
</div>

View File

@@ -0,0 +1,92 @@
require('./color-selector.less');
const React = require('react');
const createClass = require('create-react-class');
const { PATTERNS, STYLE_FN } = require('../constants');
const CodeMirror = require('../../../code-mirror');
const debounce = require('lodash.debounce');
const ColorSelector = createClass({
getDefaultProps : function() {
return {
field : {},
cm : {},
n : undefined,
text : '',
def : false
};
},
getInitialState : function() {
return {
value : ''
};
},
componentDidMount : function() {
const { field, text } = this.props;
const pattern = PATTERNS.field[field.type](field.name);
const [_, __, value] = text.match(pattern) ?? [];
this.setState({
value : value,
});
},
componentDidUpdate({ text }) {
const { field } = this.props;
if(this.props.text !== text) {
const pattern = PATTERNS.field[field.type](field.name);
const [_, __, value] = this.props.text.match(pattern) ?? [];
this.setState({
value,
});
}
},
onChange : function(e) {
const { cm, text, field, n } = this.props;
const pattern = PATTERNS.field[field.type](field.name);
const [_, label, current] = text.match(pattern) ?? [null, field.name, ''];
let index = text.indexOf(`${label}:${current}`);
while (index !== -1 && text[index - 1] === '-') {
index = text.indexOf(`${label}:${current}`, index + 1);
}
let value = e.target.value;
if(index === -1) {
index = text.length;
value = `,${field.name}:${value}`;
} else {
index = index + 1 + field.name.length;
}
cm.replaceRange(value, CodeMirror.Pos(n, index), CodeMirror.Pos(n, index + current.length), '+insert');
this.setState({
value : e.target.value,
});
},
debounce : debounce((self, e)=>self.onChange(e), 300),
onChangeDebounce : function(e) {
this.setState({
value : e.target.value,
});
this.debounce(this, e);
},
render : function() {
const { field, n, text, def } = this.props;
const { value } = this.state;
const style = STYLE_FN(value);
const id = `${field?.name}-${n}`;
const pattern = PATTERNS.field[field.type](field.name);
const [_, label, __] = text.match(pattern) ?? [null, undefined, ''];
let className = 'widget-field color-selector';
if(!label) {
className += ' suggested';
}
if(def) {
className += ' default';
}
return <React.Fragment>
<div className={className}>
<label htmlFor={id}>{field.name}:</label>
<input className='color' type='color' value={value} onChange={this.onChangeDebounce}/>
<input id={id} className='text' type='text' style={style} value={value} onChange={this.onChange}/>
</div>
</React.Fragment>;
}
});
module.exports = ColorSelector;

View File

@@ -0,0 +1,8 @@
.color-selector {
.color {
height: 17px;
width: 13px;
padding: 0;
margin: 0;
}
}

View File

@@ -1,3 +1,5 @@
const _ = require('lodash');
export const UNITS = ['cm', 'mm', 'in', 'px', 'pt', 'pc', 'em', 'ex', 'ch', 'rem', 'vw', 'vh', 'vmin', 'vmax', '%'];
export const HINT_TYPE = {
@@ -15,8 +17,10 @@ export const FIELD_TYPE = {
TEXT : 0,
CHECKBOX : 1,
IMAGE_SELECTOR : 2,
COLOR_SELECTOR : 3,
};
const textField = (name)=>new RegExp(`[{,;](${name}):([^};,"\\(]*\\((?!,)[^};"\\)]*\\)|"[^},;"]*"|[^},;]*)`);
export const PATTERNS = {
snippet : {
[SNIPPET_TYPE.BLOCK] : (name)=>new RegExp(`^{{${name}(?:[^a-zA-Z].*)?`),
@@ -24,10 +28,23 @@ export const PATTERNS = {
[SNIPPET_TYPE.INJECTOR] : ()=>new RegExp(`^\\!\\[(?:[a-zA-Z -]+)?\\]\\(.*\\).*{[a-zA-Z0-9:, "'-]+}$`),
},
field : {
[FIELD_TYPE.TEXT] : (name)=>new RegExp(`[{,;](${name}):([^};,"\\(]*\\((?!,)[^};"\\)]*\\)|"[^},;"]*"|[^},;]*)`),
[FIELD_TYPE.TEXT] : textField,
[FIELD_TYPE.IMAGE_SELECTOR] : (name)=>new RegExp(`{{(${name})(\\d*)`),
[FIELD_TYPE.COLOR_SELECTOR] : textField
},
collectStyles : new RegExp(`(?:([a-zA-Z-]+):(?!\\/))+`, 'g'),
};
export const NUMBER_PATTERN = new RegExp(`([^-\\d]*)([-\\d]+)(${UNITS.join('|')})?(.*)`);
export const fourDigitNumberFromValue = (value)=>typeof value === 'number' ? (()=>{
const str = String(value);
return _.range(0, 4 - str.length).map(()=>'0').join('') + str;
})() : value;
const DEFAULT_WIDTH = '30px';
export const STYLE_FN = (value, extras = {})=>({
width : `calc(${value?.length ?? 0}ch + ${value?.length ? `${DEFAULT_WIDTH} / 2` : DEFAULT_WIDTH})`,
...extras
});

View File

@@ -1,8 +1,7 @@
require('./image-selector.less');
const React = require('react');
const ReactDOMClient = require('react-dom/client');
const createClass = require('create-react-class');
const Modal = require('../modal/modal.jsx');
const { Modal, modalHelpers } = require('../modal/modal.jsx');
const { PATTERNS } = require('../constants.js');
const CodeMirror = require('../../../code-mirror.js');
const _ = require('lodash');
@@ -25,13 +24,7 @@ const ImageSelector = createClass({
},
componentDidMount : function() {
const el = document.createElement('div');
const root = ReactDOMClient.createRoot(el);
document.querySelector('body').append(el);
this.setState({
el,
modalRoot : root
});
modalHelpers.mount(this);
},
componentDidUpdate : function() {
@@ -39,7 +32,7 @@ const ImageSelector = createClass({
const { selected } = this.state;
const images = values.map((v, i)=>{
const className = selected === v ? 'selected' : '';
const className = String(selected) === String(v) ? 'selected' : '';
return <img key={i} className={className} src={preview(v)} alt={`${name} image ${v}`} onClick={()=>this.select(v)}/>;
});
@@ -51,7 +44,7 @@ const ImageSelector = createClass({
},
componentWillUnmount : function() {
this.state.el.remove();
modalHelpers.unmount(this);
},
save : function() {
@@ -75,9 +68,23 @@ const ImageSelector = createClass({
});
},
showModal : function() {
const { cm, field, n } = this.props;
const { text } = cm.lineInfo(n);
const pattern = PATTERNS.field[field.type](field.name);
const [fullmatch, _, current] = text.match(pattern);
if(!fullmatch) {
return;
}
this.setState({
selected : current
});
this.modalRef.current.setVisible(true);
},
render : function () {
return <React.Fragment>
<button onClick={()=>this.modalRef.current.setVisible(true)}>Select Image</button>
<button onClick={this.showModal}>Select Image</button>
</React.Fragment>;
}
});

View File

@@ -1,9 +1,11 @@
const Text = require('./text/text.jsx');
const Checkbox = require('./checkbox/checkbox.jsx');
const ImageSelector = require('./image-selector/image-selector.jsx');
const ColorSelector = require('./color-selector/color-selector.jsx');
module.exports = {
Text : Text,
Checkbox : Checkbox,
ImageSelector : ImageSelector
ImageSelector : ImageSelector,
ColorSelector : ColorSelector,
};

View File

@@ -1,5 +1,6 @@
require('./modal.less');
const React = require('react');
const ReactDOMClient = require('react-dom/client');
const createClass = require('create-react-class');
const Modal = createClass({
@@ -46,4 +47,29 @@ const Modal = createClass({
}
});
module.exports = Modal;
module.exports = {
/*
* Requirements:
* - modalRef member variable
* - should be re-rendered via `this.state.modalRoot?.render` in `componentDidUpdate`
*/
Modal,
modalHelpers : {
// should be called in `componentDidMount`
// `self` should be passed as the component instance (`this`)
mount : (self)=>{
const el = document.createElement('div');
const root = ReactDOMClient.createRoot(el);
document.querySelector('body').append(el);
self.setState({
el,
modalRoot : root
});
},
// should be called in `componentWillUnmount`
// `self` should be passed as the component instance (`this`)
unmount : (self)=>{
self.state.el.remove();
}
}
};

View File

@@ -2,15 +2,9 @@ require('./text.less');
const React = require('react');
const createClass = require('create-react-class');
const _ = require('lodash');
const { NUMBER_PATTERN, HINT_TYPE, PATTERNS } = require('../constants');
const { NUMBER_PATTERN, HINT_TYPE, PATTERNS, STYLE_FN } = require('../constants');
const CodeMirror = require('../../../code-mirror.js');
const DEFAULT_WIDTH = '30px';
const STYLE_FN = (value)=>({
width : `calc(${value?.length ?? 0}ch + ${value?.length ? `${DEFAULT_WIDTH} / 2` : DEFAULT_WIDTH})`
});
const Text = createClass({
fieldRef : {},
@@ -21,14 +15,14 @@ const Text = createClass({
n : 0,
setHints : ()=>{},
onChange : ()=>{},
getStyleHints : ()=>{}
getStyleHints : ()=>{},
def : false
};
},
getInitialState : function() {
return {
value : '',
style : STYLE_FN(),
id : ''
};
},
@@ -40,7 +34,6 @@ const Text = createClass({
const [_, __, value] = this.props.text.match(pattern) ?? [];
this.setState({
value : value,
style : STYLE_FN(value),
id : `${field?.name}-${n}`
});
}
@@ -58,7 +51,6 @@ const Text = createClass({
const [_, __, value] = text.match(pattern) ?? [];
this.setState({
value : value,
style : STYLE_FN(value),
id
});
this.fieldRef[id] = React.createRef();
@@ -133,19 +125,26 @@ const Text = createClass({
} else {
index = index + 1 + field.name.length;
}
if(!value) return;
cm.replaceRange(value, CodeMirror.Pos(n, index), CodeMirror.Pos(n, index + current.length), '+insert');
this.setState({
value : e.target.value,
style : STYLE_FN(e.target.value)
});
},
render : function() {
const { value, id, style } = this.state;
const { field } = this.props;
const { value, id } = this.state;
const { field, text, def } = this.props;
const style = STYLE_FN(value);
const pattern = PATTERNS.field[field.type](field.name);
const [_, label, __] = text.match(pattern) ?? [null, undefined, ''];
let className = 'widget-field';
if(!label) {
className += ' suggested';
}
if(def) {
className += ' default';
}
return <React.Fragment>
<div className='widget-field'>
<div className={className}>
<label htmlFor={id}>{field.name}:</label>
<input id={id} type='text' value={value}
style={style}

View File

@@ -2,7 +2,7 @@ const React = require('react');
const ReactDOMClient = require('react-dom/client');
const { PATTERNS, FIELD_TYPE, HINT_TYPE, UNITS } = require('./widget-elements/constants');
require('./widget-elements/hints/hints.jsx');
const { Text, Checkbox, ImageSelector } = require('./widget-elements');
const { Text, Checkbox, ImageSelector, ColorSelector } = require('./widget-elements');
const CodeMirror = require('../code-mirror.js');
// See https://codemirror.net/5/addon/hint/css-hint.js for code reference
@@ -86,17 +86,19 @@ module.exports = function(widgets, cm, setHints) {
const id = `${widget.name}-${n}`;
parent.id = id;
const textFieldNames = (widget.fields || []).filter((f)=>f.type === FIELD_TYPE.TEXT).map((f)=>f.name);
const textFieldNames = (widget.fields || []).filter((f)=>f.type === FIELD_TYPE.TEXT || f.type === FIELD_TYPE.COLOR_SELECTOR).map((f)=>f.name);
const { text } = cm.lineInfo(n);
const fields = (widget.fields || []).map((field)=>{
const key = genKey(widget.name, n, field.name);
if(field.type === FIELD_TYPE.CHECKBOX) {
return <Checkbox key={key} cm={cm} CodeMirror={CodeMirror} n={n} prefix={widget.name} value={field.name}/>;
return <Checkbox key={key} cm={cm} n={n} prefix={widget.name} value={field.name} def={true}/>;
} else if(field.type === FIELD_TYPE.TEXT) {
return <Text key={key} cm={cm} CodeMirror={CodeMirror} field={field} n={n} text={text} setHints={(f, h)=>setHints(h, f)} getStyleHints={getStyleHints}/>;
return <Text key={key} field={field} cm={cm} n={n} text={text} setHints={(f, h)=>setHints(h, f)} getStyleHints={getStyleHints} def={true}/>;
} else if(field.type === FIELD_TYPE.IMAGE_SELECTOR) {
return <ImageSelector key={key} field={field} cm={cm} n={n}/>;
} else if(field.type === FIELD_TYPE.COLOR_SELECTOR) {
return <ColorSelector key={key} field={field} cm={cm} n={n} text={text} def={true}/>;
} else {
return null;
}
@@ -110,7 +112,11 @@ module.exports = function(widgets, cm, setHints) {
increment : 5,
hints : true,
};
return <Text key={genKey(widget.name, n, style)} cm={cm} CodeMirror={CodeMirror} field={field} n={n} text={text} setHints={(f, h)=>setHints(h, f)} getStyleHints={getStyleHints}/>;
const key = genKey(widget.name, n, style);
if(style.includes('color')) {
return <ColorSelector key={key} field={field} cm={cm} n={n} text={text}/>;
}
return <Text key={key} field={field} cm={cm} n={n} text={text} setHints={(f, h)=>setHints(h, f)} getStyleHints={getStyleHints}/>;
}).filter(Boolean);
const root = roots[n][id] ?? ReactDOMClient.createRoot(node || parent);

View File

@@ -1,10 +1,5 @@
const _ = require('lodash');
const { SNIPPET_TYPE, FIELD_TYPE } = require('../../../shared/naturalcrit/codeEditor/helpers/widget-elements/constants');
const fourDigitNumberFromValue = (value)=>typeof value === 'number' ? (()=>{
const str = String(value);
return _.range(0, 4 - str.length).map(()=>'0').join('') + str;
})() : value;
const { SNIPPET_TYPE, FIELD_TYPE, fourDigitNumberFromValue } = require('../../../shared/naturalcrit/codeEditor/helpers/widget-elements/constants');
module.exports = [{
name : 'monster',
@@ -93,6 +88,9 @@ module.exports = [{
name : 'opacity',
type : FIELD_TYPE.TEXT,
increment : 5
}, {
name : 'background-color',
type : FIELD_TYPE.COLOR_SELECTOR,
}]
}, {
name : 'imageMaskCenter',