Prechádzať zdrojové kódy

feat: 工具函数新增replaceKeyword和isElementInScrollArea

cuiyalong 1 rok pred
rodič
commit
16e8a6c38b

+ 1 - 0
packages/util/index.js

@@ -1 +1,2 @@
 export * from './modules/format'
+export * from './modules/dom'

+ 1 - 0
packages/util/modules/dom/index.js

@@ -0,0 +1 @@
+export * from './scroll'

+ 16 - 0
packages/util/modules/dom/scroll.js

@@ -0,0 +1,16 @@
+/**
+ * 判断元素是否在滚动区域内
+ * element: 目标元素dom
+ * scrollContainer: 滚动区域
+ */
+export function isElementInScrollArea(element, scrollContainer) {
+  const elementRect = element.getBoundingClientRect()
+  const containerRect = scrollContainer.getBoundingClientRect()
+
+  // 判断元素的上边界和下边界是否在滚动容器的上边界和下边界之间
+  const isElementAboveContainer = elementRect.bottom < containerRect.top
+  const isElementBelowContainer = elementRect.top > containerRect.bottom
+
+  // 如果元素在滚动容器的上下边界之间,则认为它在滚动区域内
+  return !(isElementAboveContainer || isElementBelowContainer)
+}

+ 1 - 0
packages/util/modules/format/index.js

@@ -1,2 +1,3 @@
 export * from './money'
 export * from './date'
+export * from './str'

+ 66 - 0
packages/util/modules/format/str.js

@@ -0,0 +1,66 @@
+/**
+ * 通用关键字高亮替换
+ * @param {String} value 要高亮的字符串
+ * @param {String|Array} oldChar 要被替换的字符串(或数组)
+ * @param {String|Array} newChar 要替换成的字符串(或数组)
+ *
+ * 比如:要将 - `剑鱼标讯工具函数` 字符串中的 `工具` 高亮
+ * 则此时 value -> `剑鱼标讯工具函数`
+ *        oldChar -> `工具`
+ *        newChar -> `<span class="highlight-text">工具</span>`
+ *
+ * 批量高亮-----
+ * 比如:要将 - `剑鱼标讯工具函数` 字符串中的 `工具` `剑鱼` 高亮
+ * 则此时 value -> `剑鱼标讯工具函数`批量高亮
+ *        oldChar -> ['工具', '剑鱼']
+ *        newChar -> ['<span class="highlight-text">', '</span>']
+ *
+ *   注意:此时newChar为一个长度为2的数组,数组中为高亮标签的起始标签和结束标签
+ *
+ */
+
+export function replaceKeyword(
+  value,
+  oldChar,
+  newChar = ['<span class="highlight-text">', '</span>']
+) {
+  if (!oldChar || !newChar) return value
+  // oldChar的字符串数组
+  let oldCharArr = []
+
+  if (Array.isArray(oldChar)) {
+    oldCharArr = oldChar.concat()
+  } else {
+    oldCharArr.push(oldChar)
+  }
+
+  // 数组去重
+  oldCharArr = Array.from(new Set(oldCharArr))
+  for (let i = 0; i < oldCharArr.length; i++) {
+    if (!oldCharArr[i]) {
+      continue
+    } else {
+      oldCharArr[i] = oldCharArr[i]
+        .replace(/([$()*+.[\]?/\\^{}|])/g, '\\$1')
+        .replace(/\s+/g, '')
+    }
+  }
+
+  // 数组去空
+  const lastArr = oldCharArr
+    .filter((item) => !!item)
+    .sort((a, b) => b.length - a.length)
+  const regExp = new RegExp(`(${lastArr.join('|')})`, 'gmi')
+
+  if (lastArr.length === 0) {
+    return value
+  }
+
+  if (Array.isArray(newChar)) {
+    // 批量高亮
+    return value.replace(regExp, newChar.join('$1'))
+  } else {
+    // 普通单个高亮
+    return value.replace(regExp, newChar)
+  }
+}