naive-ui/packages/utils/data/linkedOptions.js

52 lines
1.4 KiB
JavaScript
Raw Normal View History

2019-08-28 22:37:43 +08:00
/**
* For Select Component to use
* Todo: Refactor to avoid link list, since it will make component intrinsic
* logic more complex
*/
import cloneDeep from 'lodash/cloneDeep'
2019-12-26 14:48:45 +08:00
function markAvailableOptionValues (options) {
2019-09-02 15:55:23 +08:00
const length = options.length
if (length === 0) return
let lastAvailableOption = null
2019-12-26 14:48:45 +08:00
options.firstAvailableOptionValue = null
2019-09-02 15:55:23 +08:00
for (let i = 0; i < length; ++i) {
const option = options[i]
if (!option.disabled) {
2019-12-26 14:48:45 +08:00
options.firstAvailableOptionValue = option.value
2019-09-02 15:55:23 +08:00
break
}
}
for (let i = 0; i < length; ++i) {
const option = options[i]
2019-12-26 14:48:45 +08:00
option.nextAvailableOptionValue = null
option.prevAvailableOptionValue = null
2019-09-02 15:55:23 +08:00
}
for (let i = 0; i <= length * 2; ++i) {
const option = options[i % length]
if (lastAvailableOption) {
2019-12-26 14:48:45 +08:00
option.prevAvailableOptionValue = lastAvailableOption.value
2019-09-02 15:55:23 +08:00
}
if (!option.disabled) {
lastAvailableOption = option
}
}
lastAvailableOption = null
for (let i = length * 2; i >= 0; --i) {
const option = options[i % length]
if (lastAvailableOption) {
2019-12-26 14:48:45 +08:00
option.nextAvailableOptionValue = lastAvailableOption.value
2019-09-02 15:55:23 +08:00
}
if (!option.disabled) {
lastAvailableOption = option
}
}
}
export default function linkedOptions (options) {
2019-12-26 14:48:45 +08:00
const decoratedOptions = cloneDeep(options)
markAvailableOptionValues(decoratedOptions)
return decoratedOptions
}