A text replacer component for vue3.

Related tags

Vue.js vue3-replacer
Overview

A text replacer component for Vue 3.

Requires Vue 3 as peer-dependency.

Installation

Install it from npm.

npm install vue3-replacer
pnpm add vue3-replacer
yarn add vue3-replacer

Usage

Import the component and use it.

By default Replacer splits given text from white spaces (keeps whitespaces) to a string[], and by default Replacer understands mention (@someone), url (https://url.com) and hashtags (#JusticeForSomeone).

<script setup>
import { Replacer } from 'vue3-replacer';

import Mention from './components/Mention.vue';
import Hashtag from './components/Hashtag.vue';
</script>

<template>
   <Replacer
      text="Sample text https://yandex.com https://google.com @hello #JusticeForSomething"
   >
      <!-- Text will resolve #JusticeForSomething> -->
      <template #mention="text">
         <Mention>{{ text }}</Mention>
      </template>

      <!-- text will resolve https://yandex.com and then https://google.com> -->
      <template #url="text">
         <RouterLink :to="text">{{ text.slice(0, 12) }}</RouterLink>
      </template>

      <!-- text will resolve #JusticeForSomething -->
      <template #hashtag="text">
         <Hashtag>{{ text }}</Hashtag>
      </template>

      <!-- 
         If you want to resolve plain text a.k.a unmatched texts, you can 
         text can be whitespace too, ' '.
      -->
      <template #text>
         <span style="font-weight: bold">{{ text }}</span>
      </template>
   </Replacer>
</template>

How it works

If you give Hi welcome to @vue3-replacer https://github.com/kadiryazici/vue3-replacer #reallyGood text, Replacer will convert it to array of strings.

const given = 'Hi welcome to @vue3-replacer https://github.com/kadiryazici/vue3-replacer #reallyGood';

const out = [
   'Hi',
   ' ',
   'welcome',
   ' ',
   'to',
   ' ',
   '@vue3-replacer',
   ' ',
   'https://github.com/kadiryazici/vue3-replacer',
   ' ',
   '#reallyGood'
]

and then runs handlers for each text (stops at first match per text). If you have 2 matchers for single text first one will succeed. Queue matters.

Replacer will generate a simple schema like this to resolve texts with slots:

const out = [
   ['Hi', 'text'],
   [' ', 'text'],
   ['welcome', 'text'],
   [' ', 'text'],
   ['to', 'text'],
   [' ', 'text'],
   ['@vue3-replacer', 'mention'],
   [' ', 'text'],
   ['https://github.com/kadiryazici/vue3-replacer', 'url'],
   [' ', 'text'],
   ['#reallyGood', 'hashtag']
]

Extending handlers and splitter.

You can add your own handlers and can change splitters' behavior.

Let's write our own the splliter that only splits by brackets.

<script setup>
import { Replacer } from 'vue3-replacer'
import type { Handler } from 'vue3-replacer';

const addCharacterToLastElement = (array, character) => {
   if(typeof array[array.length - 1] === 'string') {
      array[array.length - 1] += character;
      return;
   }

   array.push(character)
}

/**
 * @param { string } text / this will be given text prop.
 * @returns { string[] } splliter has to return string[] to run handlers per each word/split.
 */
const handleSplit = (text) => {
   /**
      Lets iterate over character by character.
      Create a new string element for brackets and push characters inside the bracket to that
      element. Push an empty string to array when you exit bracket.
   */
   const splittedByBrackets = [...text].reduce((acc, character) => {
      if (character === '(') {
         acc.push('(');
      } 
      else if (character === ')') {
         addCharacterToLastElement(acc, ')');
         acc.push('');
      }
      else {
         addCharacterToLastElement(acc, character);
      }

      return acc;
   }, [])

   /*
      We got: ['Hi how are you? ', '(sad)', ' ', '(happy)', ''], we need to get rid of empty strings.
   */
   return splittedByBrackets.filter(Boolean);
}

// Let's write our own handler for brackets.
// Custom handlers should be an array.
const customHandlers: Handler[] = [
   {
      name: 'brackets', // we will use this name as slot name.
      /*
         we will get each element of the array, we need to return `true` or `false`
         to let Replacer know what it is.

         You can use whatever you want as long as you return boolean.
      */
      check(text) {
         return text.startsWith('(') && text.endsWith(')')
      }
   }
]

</script>

<template>
   <Replacer
      text="Hi how are you? (sad) (happy)"
      :splitter="handleSplit"
      :customHandlers="customHandlers"
   >
      <!-- Lets resolve our brackets -->
      <template #brackets="text">
         <span style="color: purple">{{ text }} </span>
      </template>
   </Replacer>
</template>

Overriding default handlers

By default Replacer has mention | url | hashtag handlers. If you want override these handlers, just call your handler's name with existing ones.

<script>
import { Replacer } from 'vue3-replacer'
import type { Handler } from 'vue3-replacer'

const customHandlers: Handler[] = {
   // Default hashtag is overwritten;
   {
      name: 'hashtag',
      check(text) {
         return text.startsWith('#')
      }
   }
}
</script>

<template>
   <Replacer text="hi mom #good", :customHandlers="customHandlers">
      <template #hashtag="text"> {{ text }} </template>
   </Replacer>
</template>
You might also like...

Obsidian plugin to add keyboard shortcuts commonly found in code editors such as Visual Studio Code or Sublime Text

Code Editor Shortcuts This Obsidian plugin adds keyboard shortcuts (hotkeys) commonly found in code editors such as Visual Studio Code or Sublime Text

Dec 30, 2022

Bionic ReadingTool - Convert Text into Better Way to Read Faster

Bionic ReadingTool - Convert Text into Better Way to Read Faster

📓 Bionic ReadingTool A revolutionary way for guiding the eyes through text using artificial fixation spots to make reading easier. As a result, the r

Dec 24, 2022

Morse code is a method used in telecommunication to encode text characters as standardized sequences of two different signal durations, called dots and dashes, or dits and dahs.

@elonehoo/point-line Install # npm npm i @elonehoo/point-line # yarn yarn add @elonehoo/point-line #pnpm pnpm i @elonehoo/point-line Usage import {dec

Aug 3, 2022

Frolics is an offline, lightweight, full-text search library for Frontend applications

Frolics What Is Frolics Installation Document Preparing Customized Fields Hand-on Example Cache Usage What Is Frolics ? Frolics is an offline, lightwe

Dec 4, 2022

📓 The UI component explorer. Develop, document, & test React, Vue, Angular, Web Components, Ember, Svelte & more!

📓 The UI component explorer. Develop, document, & test React, Vue, Angular, Web Components, Ember, Svelte & more!

Build bulletproof UI components faster Storybook is a development environment for UI components. It allows you to browse a component library, view the

Jan 9, 2023

🐉 Material Component Framework for Vue

🐉 Material Component Framework for Vue

Supporting Vuetify Vuetify is a MIT licensed project that is developed and maintained full-time by John Leider and Heather Leider; with support from t

Jan 3, 2023

Universal select/multiselect/tagging component for Vue.js

Universal select/multiselect/tagging component for Vue.js

vue-multiselect Probably the most complete selecting solution for Vue.js 2.0, without jQuery. Documentation Visit: vue-multiselect.js.org Sponsors Gol

Jan 6, 2023

Everything you wish the HTML select element could do, wrapped up into a lightweight, extensible Vue component.

vue-select Everything you wish the HTML select element could do, wrapped up into a lightweight, zero dependency, extensible Vue component. Vue Selec

Jan 2, 2023

:fire::fire::fire: 强大的动态表单生成器|form-create is a form generation component that can generate dynamic rendering, data collection, verification and submission functions through JSON.

:fire::fire::fire: 强大的动态表单生成器|form-create is a form generation component that can generate dynamic rendering, data collection, verification and submission functions through JSON.

form-create form-create is a form generation component that can generate dynamic rendering, data collection, verification and submission functions thr

Jan 3, 2023
Owner
Kadir Yazıcı
TypeScript and Vue developer.
Kadir Yazıcı
A simple, customization star rating component for your vue3 projects

vue3-star-ratings A simple, customizable component for star ratings Documentation Features Uses svg for the stars, so it can scale without quality los

Abiodun Olunu 14 Oct 7, 2022
A API documentation generator for Vue3 single file component.

doc-vue A API documentation generator for Vue3 single file component. Table of Contents Installation Write API Description Command Line Usage Programm

annnhan 36 Oct 20, 2022
🎉🎉使用Vite + Vue3 + TypeScript + Element-plus + Mock开发的后台管理系统🎉🎉

Vite-Vue-Admin 介绍 Cli 配置 vue3.X vuex@4 vue-router@4 vite@2 typescript mock 内置 element-plus 二开封装 upload-file (文件上传,支持指定文件格式,文件大小) powerful-table (多功能表格

PengXiaoShuai 103 Dec 17, 2022
使用 vue3 来实现俄罗斯方块

Tetris-vue3 使用 vue3 实现俄罗斯方块 单机版本实现 联机版本实现 实现原理 采用了 Functional Core, Imperative Shell 模式来实现 提高了可测试性 业务核心逻辑和视图逻辑拆分 可以移植到任意 UI 库 todo 游戏重来 收获 应用程序从 0 到 1

阿崔cxr 29 Mar 25, 2022
vite2.7 + vue3.2 + ts + eslint + prettier

vite-vue-template 一个vue3项目模板 主要依赖 vite 2.7.2 vue 3.2.25 typescript eslint prettier 准备 Windows系统下将编辑器 行尾(eol) 设置为 LF('\n') vscode配置: { "files.eol":

shaaaaaaaa 5 Sep 13, 2022
⏳ vue3 + electron + ts + vite = mini template

v3-electron ?? Electron16 + Vue3 + Vite2 运行项目 # enter the project directory cd v3-electron # install dependency yarn # develop yarn dev # build exe

UNPany 8 Nov 11, 2022
vite+vue3.2+setup+elementPlus+eslint+js+stylelint

前期准备工作,npm包和vscode配置 !!!很重要,关乎整个Vue3开发阶段的代码提示 Volar使用 使用Vue3开发需要禁用vscode插件Vetur 然后安装 Volar(Vue Language Features),这样Vue3代码提示即使是使用js开发也非常友好 如果volar没有任何

null 2 Feb 8, 2022
vue3 + vite + typescript template

Vue 3 + Typescript + Vite This template should help get you started developing with Vue 3 and Typescript in Vite. The template uses Vue 3 <script setu

BrowLi 6 Aug 1, 2022
Vue3 SSR prod-ready multi-languages template

vue3-ssr-template About This template is a prod ready starter for your Vue SSR application where you can do what you want at any level, client or serv

null 9 Mar 11, 2022
A renderless rich-text editor for Vue.js

We’re working on tiptap 2. Become a sponsor to get access immediately! Sponsor ?? tiptap A renderless and extendable rich-text editor for Vue.js [FAQ]

überdosis 17.4k Dec 29, 2022