lodash#isNil JavaScript Examples
The following examples show how to use
lodash#isNil.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.js From hzero-front with Apache License 2.0 | 7 votes |
function getDisplayValue({ field, dataSource = {}, componentProps = {} }) {
let format;
let dateStr;
let value;
switch (field.componentType) {
case 'ValueList':
case 'Lov':
value =
dataSource[componentProps.displayField] ||
dataSource[`${field.fieldCode}Meaning`] ||
dataSource[field.fieldCode];
return value;
case 'DatePicker':
format = getDatePickerFormat(field, getDateFormat());
dateStr = dataSource[componentProps.displayField] || dataSource[field.fieldCode];
return dateStr && moment(dateStr, DEFAULT_DATE_FORMAT).format(format);
case 'TimePicker':
format = getDatePickerFormat(field, DEFAULT_TIME_FORMAT);
dateStr = dataSource[componentProps.displayField] || dataSource[field.fieldCode];
return dateStr && moment(dateStr, DEFAULT_TIME_FORMAT).format(format);
case 'Checkbox':
case 'Switch':
value = dataSource[componentProps.displayField] || dataSource[field.fieldCode];
if (isNil(value)) {
return;
}
return toInteger(value) === 1
? intl.get('hzero.common.status.yes')
: intl.get('hzero.common.status.no');
default:
return dataSource[componentProps.displayField] || dataSource[field.fieldCode];
}
}
Example #2
Source File: ethereum.js From RRWallet with MIT License | 6 votes |
formatInput = input => {
if (isNil(input)) {
throw new Error("invaild input");
} else if (isString(input)) {
return input.startsWith("0x") ? input.substring(2) : input;
} else if (isNumber(input)) {
return input.toString(16);
}
}
Example #3
Source File: App.js From fluentui-starter with MIT License | 6 votes |
function renderRoute(route) {
const isGroup = isArray(route.children);
const PageComponent = isNil(route.component)
? isGroup
? RouteIndexList
: ComingSoon
: route.component;
const routeComponent = (
<AuthorizedRoute
key={route.uniqueKey}
path={route.path}
exact={route.exact || isArray(route.children)}
strict={route.strict}
isPublic={route.isPublic}
>
<PageComponent route={route} />
</AuthorizedRoute>
);
const childComponents = isGroup ? route.children.map(renderRoute) : [];
return [routeComponent, ...childComponents];
}
Example #4
Source File: addTrackedExchanges.js From bonded-stablecoin-ui with MIT License | 6 votes |
addTrackedExchanges = ({ payload = {}, aa, ...props }) => async (dispatch, _, socket) => {
await socket.justsaying("light/new_aa_to_watch", { aa });
const cleanPayload = omitBy(payload, isNil);
dispatch({
type: ADD_TRACKED_EXCHANGES,
payload: { ...props, created_at: Date.now(), payload: cleanPayload, aa }
})
}
Example #5
Source File: index.js From hzero-front with Apache License 2.0 | 6 votes |
// Table
/**
* 清除新增的数据
* @param record
*/
@Bind()
handleClearRecord(record) {
const { updateModelState, dataSource = [], expandKeys = [] } = this.props;
let needRemoveExpandKey = false;
const newDataSource = isNil(record.parentRegionId)
? dataSource.filter(item => item.regionId !== record.regionId)
: buildNewTreeDataSource(dataSource, item => {
if (record.parentRegionId === item.regionId) {
const newChildren = item.children.filter(child => child.regionId !== record.regionId);
const newItem = { ...item };
if (newChildren.length === 0) {
needRemoveExpandKey = true;
newItem.hasNextFlag = item._prevHasNextFlag;
}
return {
...newItem,
children: newChildren,
};
} else {
return item;
}
});
updateModelState({
treeDataSource: newDataSource,
expandKeys: needRemoveExpandKey
? expandKeys.filter(item => item !== record.parentRegionId)
: expandKeys,
});
}
Example #6
Source File: downloadFromUrl.js From ui with MIT License | 6 votes |
downloadFromUrl = (url, filename = null) => {
const link = document.createElement('a');
link.style.display = 'none';
link.href = url;
if (!isNil(filename)) link.download = filename;
document.body.appendChild(link);
link.click();
setTimeout(() => {
URL.revokeObjectURL(link.href);
link.parentNode.removeChild(link);
}, 0);
}
Example #7
Source File: CustModal.js From hzero-front with Apache License 2.0 | 6 votes |
// 还原
@Bind()
reset() {
const { modifyConfig = {}, activeUnitCode } = this.state;
const { config = {} } = modifyConfig[activeUnitCode];
this.setState({ resetLoading: true });
if (!isEmpty(config)) {
resetUserCustConfig({
unitId: config.unitId,
}).then((res) => {
if (!isNil(res)) {
notification.success();
this.fetchUserCustConfig(activeUnitCode);
}
this.setState({ resetLoading: false });
});
}
}
Example #8
Source File: conversions.js From jafar with MIT License | 5 votes |
withNil = (props, func) => (isNil(props.value) ? props.value : func(props))
Example #9
Source File: index.js From hzero-front with Apache License 2.0 | 5 votes |
/**
* 对保存的数据新增下级
* @param record
*/
@Bind()
handleAddRecordChild(record) {
const { updateModelState, dataSource = [], expandKeys = [], organizationId } = this.props;
const unitId = uuid();
const newItem = {
unitId,
tenantId: organizationId,
unitCode: '',
unitName: '',
unitTypeMeaning: '',
unitTypeCode: '',
orderSeq: '',
supervisorFlag: 0, // 默认非主管组织
enabledFlag: 1, // 新增节点默认启用
parentUnitName: record.unitName,
parentUnitId: record.unitId,
_status: 'create', // 新增节点的标识
indent: record.indent + 1,
};
let needAddExpandKey = false;
const newDataSource = buildNewTreeDataSource(dataSource, item => {
if (item.unitId === record.unitId) {
if (item.hasNextFlag !== 1) {
// 本身没有子节点
needAddExpandKey = true;
} else if (!expandKeys.includes(item.unitId)) {
// 本身有子节点但是没有展开
needAddExpandKey = true;
}
return {
...item,
hasNextFlag: 1,
// 存储之前的 标记, 用于 清除后 还原
_prevHasNextFlag: isNil(item._prevHasNextFlag) ? item.hasNextFlag : item._prevHasNextFlag,
children: item.children ? [newItem, ...item.children] : [newItem],
};
} else {
return item;
}
});
updateModelState({
treeDataSource: newDataSource,
expandKeys: needAddExpandKey ? [...expandKeys, record.unitId] : expandKeys,
});
}
Example #10
Source File: validityHelper.js From weatherman-react with GNU General Public License v3.0 | 5 votes |
isValid = (value) => {
return !isEmpty(value) && !isNil(value);
}
Example #11
Source File: index.js From hzero-front with Apache License 2.0 | 5 votes |
add() {
const { editingRows, dataSource } = this.state;
const { roleDatasource = {} /* , resourceLevel = [] */ } = this.props;
const item = { key: uuidv4() };
// if (roleDatasource.tenantId === 0) {
// item.organizationId = roleDatasource.tenantId;
// item.tenantName = roleDatasource.tenantName;
// // item.assignLevel = 'site';
// // item.assignLevelMeaning = getCodeMeaning('site', resourceLevel);
// // item.assignLevelValue = 0;
// // item.assignLevelValueMeaning = roleDatasource.tenantName;
// }
if (roleDatasource.level === 'site') {
item.assignLevel = 'organization';
item.assignLevelValue = roleDatasource.tenantId;
item.assignLevelValueMeaning = roleDatasource.tenantName;
// 之前的逻辑
// item.organizationId = roleDatasource.tenantId;
// item.tenantName = roleDatasource.tenantName;
// item.assignLevel = 'organization';
// // item.assignLevelMeaning = getCodeMeaning('site', resourceLevel);
// item.assignLevelValue = 0;
// // item.assignLevelValueMeaning = roleDatasource.tenantName;
}
if (!isNil(roleDatasource.parentRoleAssignUnitId)) {
item.assignLevel = 'org';
}
if (currentTenantId !== 0 && VERSION_IS_OP) {
item.organizationId = roleDatasource.tenantId;
item.tenantName = roleDatasource.tenantName;
item.assignLevel = 'organization';
// item.assignLevelMeaning = getCodeMeaning('site', resourceLevel);
item.assignLevelValue = 0;
// item.assignLevelValueMeaning = roleDatasource.tenantName;
}
this.setState({
dataSource: [item].concat(dataSource),
editingRows: uniqBy(editingRows.concat(item), 'key'),
});
}
Example #12
Source File: ETHWallet.js From RRWallet with MIT License | 4 votes |
async sendBatchTransaction(coin, targets, gasPrice, perGasLimit, pwd, callback) {
targets = JSON.parse(JSON.stringify(targets));
const token = coin;
if (!token || !isNumber(token.decimals)) {
throw new Error("token不存在");
}
if (!isArray(targets) || targets.length === 0) {
throw new Error("targets参数格式不正确");
}
gasPrice = new BigNumber(gasPrice + "");
perGasLimit = new BigNumber(perGasLimit + "");
if (perGasLimit.isLessThan(ETH_ERC20_TX_MIN_GASLIMIT)) {
throw new Error(
`单笔转账的gasLimit需大于${ETH_ERC20_TX_MIN_GASLIMIT}, 为保证交易正常, 请尽可能多的设置gasLimit, 未使用的gas将会在交易结束后退回`
);
}
const tos = [];
const amounts = [];
let totalAmount = new BigNumber(0);
for (const { address, amount } of targets) {
if (isNil(address) || isNil(amount)) {
throw new Error("targets含有非法输入");
}
if (!isString(address) || !isString(amount)) {
throw new Error("非法输入,地址和数量必须为字符串");
}
let isStartsWith0x = _.startsWith(address, "0x"); //address.indexOf('0x') == 0;
if ((isStartsWith0x && address.length != 42) || (!isStartsWith0x && address.length != 40)) {
throw new Error(`含有非法地址${address}`);
}
tos.push(address);
const amountBigNumber = new BigNumber(amount);
amounts.push(new BigNumber(amountBigNumber));
totalAmount = totalAmount.plus(amountBigNumber);
}
const balanceBigNumber = new BigNumber(token.balance + "");
if (totalAmount.isGreaterThan(balanceBigNumber)) {
throw new Error(
`${token.name}余额不足, 转账数量:${toFixedLocaleString(totalAmount)}}, 余额:${toFixedLocaleString(
balanceBigNumber
)}`
);
}
//两次approve 一次测试转账, 所以需要预留3笔gas数量
const totalGasBignumber = ethereum.toEther(perGasLimit.multipliedBy(tos.length + 3).multipliedBy(gasPrice), "gwei");
if (totalGasBignumber.isGreaterThan(this.ETH.balance + "")) {
throw new Error(
`ETH余额不足, 矿工费:${toFixedLocaleString(totalGasBignumber)}}, 余额:${toFixedLocaleString(this.ETH.balance)}`
);
}
if (token instanceof ETH) {
if (totalGasBignumber.plus(totalAmount).isGreaterThan(token.balance + "")) {
throw new Error(
`ETH余额不足, 矿工费:${toFixedLocaleString(totalGasBignumber)}}, 转账数量:${toFixedLocaleString(
totalAmount
)} 余额:${toFixedLocaleString(balanceBigNumber)}`
);
}
}
Device.keepScreenOn(true);
try {
if (coin instanceof ETH) {
await this.sendETHBatchTransactionContract(token, tos, amounts, gasPrice, perGasLimit, pwd, callback);
} else if (await this.shouldUseBatchTransactionContract(token.contract)) {
let skinTestSuccess = false;
try {
//尝试调用单笔批量合约, 如果合约执行失败则降级到looping, 其他异常则中断发币
await this.sendERC20BatchTransactionContract(
token,
_.take(tos, 1),
_.take(amounts, 1),
gasPrice,
perGasLimit,
pwd,
callback
);
skinTestSuccess = true;
} catch (error) {
if (error.message === "批量发币合约执行失败") {
await this.sendERC20BatchTransactionLooping(token, tos, amounts, gasPrice, perGasLimit, pwd, callback);
} else {
throw error;
}
}
if (!skinTestSuccess) {
return;
}
tos.splice(0, 1);
amounts.splice(0, 1);
await this.sendERC20BatchTransactionContract(token, tos, amounts, gasPrice, perGasLimit, pwd, result => {
_.isFunction(callback) &&
callback({
...result,
from: result.from + 1,
});
});
} else {
await this.sendERC20BatchTransactionLooping(token, tos, amounts, gasPrice, perGasLimit, pwd, callback);
}
} catch (error) {
throw error;
}
Device.keepScreenOn(false);
}
Example #13
Source File: index.js From hivemind with Apache License 2.0 | 4 votes |
MindMapsAPI = async (req, res) => {
const { token } = req.headers
try {
const claims = await verifyIdToken(token)
const key = claims.uid
const userId = `users/${key}`
let mindmap, response, message, query, cursor, mindmaps, name
switch (req.method) {
case 'GET':
query = aql`
for v, e in 1
outbound ${userId}
graph 'mindmaps'
return { mindmap: v, access: e }
`
cursor = await db.query(query)
mindmaps = await cursor.all()
return res.status(200).json(mindmaps)
case 'POST':
name = req.body.name
mindmap = {
name,
isRoot: true,
title: name,
createdBy: userId,
}
response = await rg.post('/document/mindmaps', mindmap)
if (response.statusCode === 201) {
mindmap = response.body
const access = {
_from: `users/${key}`,
_to: mindmap._id,
access: 'admin',
}
response = await rg.post('/document/access', access)
if (response.statusCode === 201) {
message = 'Mindmap created.'
await recordCompoundEvent('created', userId, [mindmap])
} else {
message = response.body
await rg.delete(
'/history/purge',
{ path: `/n/${mindmap._id}` },
{ silent: true, deleteUserObjects: true }
)
}
} else {
message = response.body
}
return res.status(response.statusCode).json({ message })
case 'PATCH':
if (isEmpty(req.body._id)) {
return res.status(400).json({ message: 'Mindmap id is required' })
}
if (await hasWriteAccess(req.body._id, userId)) {
mindmap = chain(req.body)
.pick('audio', 'summary', 'content', '_rev', '_id', 'title', 'name')
.omitBy(isNil)
.value()
mindmap.lastUpdatedBy = userId
response = await rg.patch('/document/mindmaps', mindmap, {
keepNull: false,
ignoreRevs: false,
})
await recordCompoundEvent('updated', userId, [response.body])
return res.status(response.statusCode).json(response.body)
} else {
return res.status(401).json({ message: 'Access Denied.' })
}
}
} catch (error) {
console.error(error.message, error.stack)
return res.status(401).json({ message: 'Access Denied.' })
}
}
Example #14
Source File: index.js From ThreatMapper with Apache License 2.0 | 4 votes |
DagreGraph = ({ data, height, width, style, className }) => {
const ref = useRef(null);
const graphRef = useRef(null)
useEffect(() => {
if (!graphRef.current) {
const tooltip = new G6.Tooltip({
getContent(e) {
const nodeType = e.item.getType();
const outDiv = document.createElement('div');
if (nodeType === 'node') {
const model = e.item.getModel();
outDiv.innerHTML = getTooltipContent(model);
return outDiv
}
},
itemTypes: ['node'],
className: 'dagre-node-tooltip',
});
const graph = new G6.Graph({
container: ref.current,
width: width ?? 0,
height: height ?? 0,
fitView: true,
layout: {
type: 'dagre',
rankdir: 'LR',
nodesepFunc: () => 0,
ranksepFunc: () => 0,
controlPoints: true,
},
modes: {
default: [],
},
plugins: [tooltip],
defaultNode: {
type: 'circle',
size: 15,
style: {
opacity: 0.8,
stroke: 'rgb(192, 192, 192)',
fill: '#0079f2',
lineWidth: 0.7,
},
labelCfg,
},
defaultEdge: {
type: 'spline',
style: {
stroke: '#55c1e9',
lineWidth: 1.2,
opacity: 0.4,
endArrow: {
opacity: 0.9,
shadowBlur: 0,
path: G6.Arrow.triangle(2, 3, 0),
fill: "#55c1e9",
stroke: "#55c1e9",
},
},
},
});
graph.read(data);
graphRef.current = graph;
}
}, []);
const [initialData] = useState(data);
useEffect(() => {
if (graphRef.current && initialData !== data) {
graphRef.current.data(data);
graphRef.current.render();
}
}, [data]);
return (
<div style={{ position: 'relative', textAlign: 'left' }} className={styles.dagreGraphContainer}>
<AutoSizer>
{({ height: calculatedHeight, width: calculatedWidth }) => {
if ((isNil(height) || isNil(width)) && graphRef.current) {
graphRef.current.changeSize(width ?? calculatedWidth, height ?? calculatedHeight);
graphRef.current.render();
}
return (<div style={style} className={className} ref={ref} />);
}}
</AutoSizer>
</div>
);
}
Example #15
Source File: cadastrapp.js From mapstore2-cadastrapp with GNU General Public License v3.0 | 4 votes |
/**
* Holds the state of cadastrapp.
* The shape of the state is the following:
* ```
* {
* loading: true | false // general loading flag
* loadingFlags: {} // object that contain loading flag, for various parts of the application.
* searchType: undefined // one of constant.SEARCH_TOOLS
* selectionType: undefined // one of constant.SELECTION_TYPE
* plots: [{ // an entry for each tab of the plot selection
* data: [{parcelle: "12345", ...}] // data of the tab
* selected: [parcelle1, parcelle2]
* }],
* configuration: { // the configuration from server. e.g.
* cadastreLayerIdParcelle: "geo_parcelle"
* cadastreWFSLayerName: "qgis:cadastrapp_parcelle"
* cadastreWFSURL: "https://domain.org/geoserver/wfs"
* cadastreWMSLayerName: "qgis:cadastrapp_parcelle"
* cadastreWMSURL: "https://domain.org/geoserver/wms"
* cnil1RoleName: "ROLE_EL_APPLIS_CAD_CNIL1"
* cnil2RoleName: "ROLE_EL_APPLIS_CAD_CNIL2"
* dateValiditeEDIGEO: "01/01/2018"
* dateValiditeMajic: "01/01/2018"
* maxRequest: "8"
* minNbCharForSearch: "3"
* minParacelleIdLength: "14"
* organisme: "Un service fourni par "
* pdfbasemapthumbnails: [{,…}, {,…}]
* pdfbasemaptitles: [{value: "Cadastre", key: "pdf.baseMap.0.title"},…]
* uFWFSLayerName: "qgis:cadastrapp_unite_fonciere"
* uFWFSURL: "https://domain.org/geoserver/wfs"
* }
* }
* ```
*
* @param {object} state the application state
* @param {object} action a redux action
*/
export default function cadastrapp(state = DEFAULT_STATE, action) {
const type = action.type;
switch (type) {
case SETUP:
return set('pluginCfg', action.cfg, state);
case SET_CONFIGURATION:
return set('configuration', action.configuration, state);
case LOADING: {
let newValue = action.value;
if (action.mode === 'count') {
const oldValue = get(state, `loadFlags.${action.name}`) ?? 0;
newValue = isNumber(newValue)
? newValue // set with passed value if number
: newValue
? oldValue + 1 // increment if true
: Math.max(oldValue - 1, 0); // decrement if false
}
// anyway sets loading to true
return set(action.name === "loading" ? "loading" : `loadFlags.${action.name}`, newValue, state);
}
case TOGGLE_SELECTION: {
const {selectionType} = action;
// if the current selection button is clicked, it turns off selection
return set("selectionType", selectionType, state);
}
case TOGGLE_SEARCH: {
const { searchType } = action;
// if the current search button is clicked, it closes the search section
return set("searchType", searchType, state);
}
case ADD_PLOTS: {
const { plots, target, activate = true } = action;
const {activePlotSelection = 0 } = state;
let targetPlotSelection = activePlotSelection;
let newState = state;
if (!isNil(target)) {
const targetIndex = isObject(target) ? findIndex(state.plots, {id: target.id}) : target;
// create
if (targetIndex < 0) {
newState = set(`plots`, [...state.plots, { ...EMPTY_PLOT_SELECTION, ...target }], state);
targetPlotSelection = newState.plots.length - 1;
} else {
newState = set(`plots[${targetIndex}]`, {...state.plots[targetIndex], ...target});
targetPlotSelection = targetIndex;
}
}
if (activate) {
newState = set(`activePlotSelection`, targetPlotSelection, newState);
}
// get the current selection or create a new one if it not exists.
let currentSelection = newState?.plots?.[targetPlotSelection] ?? EMPTY_PLOT_SELECTION;
// add every plot received and toggle selection if exist
plots.map(({ parcelle, ...other}) => {
// if exists, toggle selection
currentSelection = toggleSelection(currentSelection, parcelle);
// update/insert the value at the en
currentSelection = arrayUpsert(`data`, { parcelle, ...other }, {parcelle}, currentSelection);
});
// update with new values the state
return set(`plots[${targetPlotSelection}]`, currentSelection, newState);
}
case REMOVE_PLOTS: {
const { parcelles = []} = action;
const {activePlotSelection = 0 } = state;
// get the current selection or create a new one if it not exists.
let currentSelection = state?.plots?.[activePlotSelection] ?? EMPTY_PLOT_SELECTION;
currentSelection = {
...currentSelection,
data: currentSelection.data.filter(({ parcelle }) => !parcelles.includes(parcelle)),
selected: currentSelection.selected.filter(parcelle => !parcelles.includes(parcelle))
};
// update with new values the state
return set(`plots[${activePlotSelection}]`, currentSelection, state);
}
case SELECT_PLOTS:
case DESELECT_PLOTS: {
const { activePlotSelection = 0 } = state;
let currentSelection = state?.plots?.[activePlotSelection] ?? EMPTY_PLOT_SELECTION;
const {plots = []} = action;
const parcelles = plots.map(({ parcelle }) => parcelle);
const selected = action.type === SELECT_PLOTS
? uniq([...(currentSelection.selected || []), ...parcelles])
: (currentSelection.selected || []).filter(id => !parcelles.includes(id));
currentSelection = {
...currentSelection,
selected
};
return set(`plots[${activePlotSelection}]`, currentSelection, state);
}
case ADD_PLOT_SELECTION: {
const {plot = {}} = action;
const currentPlots = state?.plots ?? [];
return compose(
set(`plots`, [...currentPlots, { ...EMPTY_PLOT_SELECTION, ...plot}]),
set(`activePlotSelection`, state?.plots?.length ?? 0) // select the new tab
)(state);
}
case REMOVE_PLOT_SELECTION: {
const active = action.active ?? state.activePlotSelection;
const newPlots = [...state.plots.filter((_, i) => i !== active)];
return compose(
set(`plots`, newPlots),
set(`activePlotSelection`, Math.max(state.activePlotSelection - 1, 0))
)(state);
}
case SET_ACTIVE_PLOT_SELECTION: {
return set('activePlotSelection', action.active, state);
}
case SET_LAYER_STYLE: {
return set(`styles.${action.styleType}`, action.value, state);
}
case UPDATE_LAYER_STYLE: {
return set(`styles.${action.styleType}`, {...(state?.styles?.[action.styleType] ?? {}), ...action.values}, state);
}
case SET_STYLES: {
return set('styles', action.styles, state);
}
case SHOW_OWNERS: {
return compose(
set('owners.data', action.owners),
set('owners.show', true)
)(state);
}
case CLEAR_OWNERS: {
return set('owners', undefined, state);
}
case SHOW_LANDED_PROPERTIES_INFORMATION: {
return set('landedProperty.parcelle', action.parcelle, state);
}
case INFORMATION_UPDATE: {
return set(
`informationData["${action.parcelle}"]${action.path ? '.' + action.path : ''}`, action.data, state
);
}
case INFORMATION_CLEAR: {
return set(
`informationData`, undefined, state
);
}
case SAVE_BUBBLE_INFO: {
return set('infoBulle', action.data, state);
}
case PRINT_RESPONSE: {
return {...state, requestFormData: {...state.requestFormData, allowDocument: action.allowDocument, requestId: action.requestId}};
}
default:
return state;
}
}
Example #16
Source File: controls.js From iceberg-editor with GNU General Public License v2.0 | 4 votes |
render() {
const {
isActive,
title,
rootBlocks,
selectBlock,
selectedBlockClientId,
headingBlockCount,
} = this.props;
if ( ! isActive ) {
return false;
}
if ( headingBlockCount === 0 ) {
return false;
}
return (
<Fragment>
<div className="components-iceberg-table-of-contents">
<ul className="components-iceberg-table-of-contents__list">
<li
key="toc-post-title"
className={ classnames(
'components-iceberg-heading-level--1'
) }
>
<Button
className={ classnames(
'iceberg-block-navigation__item-button'
) }
onClick={ () => {
this.scrollToSelected(
'.editor-post-title__input',
true
);
document
.querySelector(
'.editor-post-title__input'
)
.focus();
} }
>
{ title }
</Button>
</li>
{ map( omitBy( rootBlocks, isNil ), ( block ) => {
const isSelected =
block.clientId === selectedBlockClientId;
// Limit to Heading blocks only.
if ( ! [ 'core/heading' ].includes( block.name ) ) {
return false;
}
return (
<li
key={ block.clientId }
className={ classnames(
'components-iceberg-heading-level--' +
block.attributes.level,
{
'is-selected': isSelected,
}
) }
>
<Button
className={ classnames(
'iceberg-block-navigation__item-button'
) }
onClick={ () => {
this.scrollToSelected(
'block-' + block.clientId
);
selectBlock( block.clientId );
} }
>
{ block.attributes.content.replace(
/(<([^>]+)>)/gi,
''
) }
</Button>
</li>
);
} ) }
</ul>
</div>
</Fragment>
);
}
Example #17
Source File: custCollapseForm.js From hzero-front with Apache License 2.0 | 4 votes |
export default function custCollapseForm(options = {}, form) {
const proxyForm = form;
const { custConfig = {}, loading = false, cacheType } = this.state;
const { code = '', readOnly: readOnly1 } = options;
const { dataSet = { data: [{}] } } = proxyForm.props;
if (loading) {
proxyForm.props.children = [];
}
if (!code || isEmpty(custConfig[code])) return form;
const fieldMap = new Map();
const formChildren = isArray(proxyForm.props.children)
? proxyForm.props.children
: [proxyForm.props.children];
formChildren.forEach((item, seq) => {
if (item?.props?.name) {
fieldMap.set(item.props.name, { item, seq, empty: item.props.empty });
}
});
const tools = { ...this.getToolFuns(), code };
// TODO: c7n不支持字段宽度配置
const { maxCol = 3, fields = [], unitAlias = [], readOnly: readOnly2 } = custConfig[code];
const readOnly = readOnly1 || readOnly2;
const current = dataSet.current || { toData: () => ({}) };
this.setDataMap(code, current.toData());
const unitData = getFieldValueObject(unitAlias, this.getToolFuns(), code);
if (!cacheType[code]) {
cacheType[code] = 'collapse-form';
dataSet.addEventListener(
'update',
({ name, record, value }) => {
const ds = dataSet.get(0) || { toData: () => ({}) };
const data = ds.toData();
this.setDataMap(code, data);
fields.forEach((item) => {
const { conditionHeaderDTOs = [], fieldCode, lovMappings = [], conValidDTO = {} } = item;
const newFieldConfig = getFieldConfig({
required: item.required,
editable: item.editable,
...coverConfig(conditionHeaderDTOs, tools, ['visible']),
});
const validators = selfValidator(conValidDTO, tools);
const { defaultValue } = defaultValueFx({ ...tools, code }, item);
const oldFieldConfig = (dataSet.getField(fieldCode) || {}).pristineProps || {};
if (defaultValue !== undefined) {
oldFieldConfig.defaultValue = defaultValue;
}
dataSet.addField(fieldCode, {
...parseProps(
omit(item, [
'width',
'fieldName',
'fieldCode',
'fixed',
'renderOptions',
'conditionHeaderDTOs',
]),
tools,
oldFieldConfig
),
...newFieldConfig,
...validators,
});
if (lovMappings.length > 0 && name === fieldCode && typeof value === 'object') {
lovMappings.forEach((i) => {
record.set(i.targetCode, value[i.sourceCode]);
});
}
});
this.setState({ lastUpdateUnit: `${code}${name}` });
},
false
);
dataSet.addEventListener(
'load',
() => {
fields.forEach((item) => {
if (item.fieldType === 'EMPTY') return;
const { conditionHeaderDTOs = [], fieldCode, conValidDTO = {} } = item;
const data = (dataSet.current && dataSet.current.toData()) || {};
this.setDataMap(code, data);
const newFieldConfig = getFieldConfig({
required: item.required,
editable: item.editable,
...coverConfig(conditionHeaderDTOs, tools, ['visible']),
});
const validators = selfValidator(conValidDTO, tools);
const { defaultValue } = defaultValueFx({ ...tools, code }, item);
const oldFieldConfig = (dataSet.getField(fieldCode) || {}).pristineProps || {};
if (defaultValue !== undefined) {
oldFieldConfig.defaultValue = defaultValue;
}
dataSet.addField(fieldCode, {
...parseProps(
omit(item, [
'width',
'fieldName',
'fieldCode',
'fixed',
'renderOptions',
'conditionHeaderDTOs',
]),
this.getToolFuns(),
oldFieldConfig
),
...newFieldConfig,
...validators,
});
});
this.setState({ lastUpdateUnit: `load${code}` });
},
false
);
}
const proxyFields = [];
const tempFields = fields.filter((i) => {
const originSeq = fieldMap[i.fieldName] && fieldMap[i.fieldName].seq;
if ((i.formRow === undefined || i.formCol === undefined) && originSeq === undefined) {
return true;
}
const seq = i.formRow * maxCol + i.formCol;
proxyFields.push({ ...i, seq: typeof seq === 'number' ? seq : originSeq });
return false;
});
proxyFields.sort((p, n) => p.seq - n.seq);
let newChildren = [];
proxyFields.concat(tempFields).forEach((item) => {
const {
fieldCode,
fieldName,
renderOptions,
conditionHeaderDTOs,
renderRule,
colSpan,
conValidDTO = {},
...otherProps
} = item;
const oldChild = fieldMap.get(fieldCode);
const {
visible = item.visible,
required = item.required,
editable = item.editable,
} = coverConfig(conditionHeaderDTOs, tools);
const validators = selfValidator(conValidDTO, tools);
const { defaultValue } = defaultValueFx({ ...tools, code }, item);
const newFieldConfig = getFieldConfig({
visible,
required,
editable,
});
if (visible === 0) {
dataSet.addField(fieldCode, { required: false });
fieldMap.delete(fieldCode);
return;
}
if (item.fieldType !== 'EMPTY') {
if (item.fieldType === 'CHECKBOX' || item.fieldType === 'SWITCH') {
newFieldConfig.trueValue = 1;
newFieldConfig.falseValue = 0;
}
if (fieldName !== undefined) {
newFieldConfig.label = fieldName;
}
const oldFieldConfig = (dataSet.getField(fieldCode) || {}).pristineProps || {};
if (defaultValue !== undefined) {
oldFieldConfig.defaultValue = defaultValue;
}
dataSet.addField(fieldCode, {
...parseProps(otherProps, tools, oldFieldConfig),
...newFieldConfig,
...validators,
});
}
if (visible !== undefined) {
// 做新增扩展字段处理
if (!oldChild && visible !== -1) {
if (readOnly || renderOptions === 'TEXT') {
const outputProps = {
name: fieldCode,
label: fieldName,
colSpan,
};
if (item.fieldType === 'DATE_PICKER') {
outputProps.renderer = ({ value }) => value && moment(value).format(item.dateFormat);
}
if (!isNil(renderRule)) {
const renderer = () => (
// eslint-disable-next-line react/no-danger
<div dangerouslySetInnerHTML={{ __html: template.render(renderRule, unitData) }} />
);
newChildren.push(<Output {...outputProps} renderer={renderer} />);
} else {
newChildren.push(<Output {...outputProps} />);
}
} else {
newChildren.push(
getComponent(item.fieldType, { currentData: dataSet.toData() })({
name: fieldCode,
label: fieldName,
...transformCompProps(otherProps),
})
);
}
} else if (oldChild) {
if (item.editable !== -1) {
oldChild.item.props.disabled = !item.editable;
}
if (colSpan) {
oldChild.item.props.colSpan = colSpan;
}
if (item.placeholder !== undefined) {
oldChild.item.props.placeholder = item.placeholder;
}
newChildren.push(oldChild.item);
}
}
fieldMap.delete(fieldCode);
});
if (dataSet.all.length === 0) {
dataSet.create();
}
newChildren = newChildren.concat(Array.from(fieldMap.values()).map((i) => i.item));
proxyForm.props.children = newChildren;
proxyForm.props.columns = maxCol;
return form;
}