在昨天我們已經完成複製帶連結的通知文字了!
但如果要讓其他人使用的話,我們需要讓使用者在 Popup 輸入自訂範本時,能直覺且獨立操作完成 —— 也就是防呆設計。
第一次使用的人可能會遇到的情況:
<textarea class="w-full h-20 border-1 border-gray-600 rounded p-2" rows="5" :placeholder="templateExample" v-model="templateContent"></textarea>
const templateExample = "例:Hello {REVIEWER_NAME},這是最新的 {MR_LINK},再麻煩你,謝謝"
<div class="mt-2">
<ul class="list-disc">
<li class="font-bold border-b border-b-gray-400">
<div>範本選項</div>
<div>說明</div>
</li>
<li>
<div>{REVIEWER_NAME}</div>
<div>Reviewer 名字純文字</div>
</li>
<li>
<div>{MR_LINK}</div>
<div>
<div>Merge Request 連結</div>
<div class="text-xs">(會自動填入完整連結,讓 Slack 自動識別)</div>
</div>
</li>
</ul>
</div>
<div class="bg-sky-100 rounded p-2">
<span class="bg-sky-200 px-2 rounded-full text-sky-800">參考</span>
<div class="text-sky-600 mt-1">{{ dynamicContent }}</div>
</div>
const defaultData = {
REVIEWER_NAME: 'Jason',
MR_LINK: 'Demonstrate clangsa with compiledb and inlined scripts'
}
const dynamicContent = computed(() => applyTemplate(templateContent.value, defaultData))
// 套用範本
function applyTemplate(template, data) {
return template.replace(/\{([A-Z0-9_]+)\}/g, (_, key) => {
const val = data[key];
if (Array.isArray(val)) return val.join(', ');
return val ?? '<--未知變數-->';
});
}
// 取得佔位符清單
function extractPlaceholders(template) {
return [...template.matchAll(/\{([A-Z0-9_]+)\}/g)].map(m => m[1]);
}
規則:
{}
將名稱包起來_
區分單字// 儲存範例
const error = ref('')
async function saveTemplate() {
const template = templateContent.value.trimEnd()
if (template.length > 1000) {
error.value = '文字太長,請縮短一點~'
return
};
const availableKey = Object.keys(defaultData)
const unknownKey = extractPlaceholders(template).filter(k => !availableKey.includes(k));
if (unknownKey.length) {
error.value = `發現未知變數:${unknownKey.join(', ')}`
return
};
chrome.storage.sync.set({ reviewTemplate: template })
templateContent.value = template
error.value = ''
}
在可用佔位符清單放小按鈕,點擊就插入 {REVIEWER_NAME}、{MR_LINK} 等,避免打錯字。
<button class="text-emerald-800 bg-emerald-100 hover:bg-emerald-200 px-1 rounded-full" @click="insertKey('{REVIEWER_NAME}')">{REVIEWER_NAME}</button>
//快速插入佔位符
function insertKey(keyName) {
templateContent.value += keyName
}