Files
drawlogo/js/core/iconlib.js
T

209 lines
7.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 画个标 · 内置素材库加载器(懒加载)
* 素材库由 scripts/build-icons.js 构建拆分为:
* - js/data/builtin-icons.js 轻量索引(sources 元数据 + AI iconIndex,无全量 svg)
* - js/data/sources/{id}.js 每源一个数据文件(HGB_Source_{id} = {icons:[...]})
* 本模块负责:按源懒加载 + 缓存 + 同步读已加载源 + 预加载核心源
*/
const HGB_IconLib = (function () {
'use strict';
const VERSION = '20261105a'; // 与 index.html 中 builtin-icons.js?v= 版本联动
const cache = {}; // sid -> {icons:[...]}
const pending = {}; // sid -> Promise
function fileURL(sid) {
return 'js/data/sources/' + sid + '.js?v=' + VERSION;
}
function loadScript(url) {
return new Promise((resolve, reject) => {
const s = document.createElement('script');
s.src = url;
s.onload = resolve;
s.onerror = function () { reject(new Error('素材源加载失败: ' + url)); };
document.head.appendChild(s);
});
}
/** 加载单个源(缓存 + 并发去重) */
function loadSource(sid) {
if (cache[sid]) return Promise.resolve(cache[sid]);
if (pending[sid]) return pending[sid];
pending[sid] = loadScript(fileURL(sid)).then(() => {
const data = window['HGB_Source_' + sid];
if (!data || !data.icons) throw new Error('素材源不存在: ' + sid);
cache[sid] = data;
delete pending[sid];
return data;
}).catch((e) => {
delete pending[sid];
throw e;
});
return pending[sid];
}
/** 并行加载多个源(全部成功才 resolve) */
function loadSources(ids) {
return Promise.all((ids || []).map(loadSource));
}
/** 并行加载多个源(容忍单个失败,返回已成功加载的) */
function preload(ids) {
return Promise.allSettled((ids || []).map(loadSource)).then((rs) =>
rs.filter(r => r.status === 'fulfilled').map(r => r.value));
}
/** 加载全部源(搜索全部/导出等场景) */
function loadAll() {
const ids = Object.keys((typeof HGB_BuiltinIcons !== 'undefined' ? HGB_BuiltinIcons.sources : {}) || {});
return preload(ids);
}
/** 同步读取已加载源(未加载返回 null) */
function getSource(sid) {
return cache[sid] || null;
}
/** 是否已加载 */
function loaded(sid) {
return !!cache[sid];
}
/** 已加载的全部源 id */
function loadedIds() {
return Object.keys(cache);
}
/** 从已加载源按 名称/id 找图标(返回 {id,name,svg,...} 或 null) */
function findIcon(ref) {
if (!ref || typeof ref !== 'string') return null;
const name = ref.trim();
const parts = name.split(':');
if (parts.length === 2) {
const src = cache[parts[0]];
const hit = src && (src.icons || []).find(i => i.name === parts[1] || i.id === name);
if (hit) return hit;
}
const lower = name.toLowerCase();
for (const sid of Object.keys(cache)) {
const hit = (cache[sid].icons || []).find(i =>
i.id === name || i.name === name ||
String(i.name).toLowerCase() === lower ||
String(i.name).toLowerCase().includes(lower));
if (hit) return hit;
}
return null;
}
/**
* 中文查询展开:'学校' → ['school','graduation','book'...]
* 依赖 js/data/cn-tags.js(window.HGB_CnTags),未加载时退化为原样匹配。
*/
function expandKeyword(keyword) {
var q = String(keyword || '').trim().toLowerCase();
if (!q) return [];
var set = new Set([q]);
var tags = (typeof HGB_CnTags !== 'undefined' && HGB_CnTags) || null;
if (tags) {
if (tags[q]) tags[q].forEach(function (r) { set.add(String(r).toLowerCase()); });
// 支持「学校图标」这类包含式查询(长词优先)
Object.keys(tags).forEach(function (cn) {
if (cn.length >= 2 && q.indexOf(cn) !== -1) {
tags[cn].forEach(function (r) { set.add(String(r).toLowerCase()); });
}
});
}
return Array.from(set);
}
/** 词根匹配:英文按 -/_ 分词精确匹配,含连字符的词根用包含匹配(避免 car→card) */
function nameHasRoot(name, root) {
if (!root) return false;
if (root.indexOf('-') !== -1) return name.indexOf(root) !== -1;
return name.split(/[-_\s]+/).indexOf(root) !== -1;
}
function iconMatches(ic, q, roots) {
return scoreIcon(ic, q, roots) >= 0;
}
/**
* 相关性评分(越小越相关):名称精确 > 前缀 > 包含 > 词根(按词表位次)> 分类
* @returns {number} 分数;-1 表示不匹配
*/
function scoreIcon(ic, q, roots) {
var name = String(ic.name || '').toLowerCase();
var cat = String(ic.categoryCn || ic.category || '');
if (!q) return 0;
if (name === q) return 0;
if (name.indexOf(q) === 0) return 1;
if (name.indexOf(q) !== -1) return 2;
var best = -1;
for (var i = 0; i < roots.length; i++) {
if (nameHasRoot(name, roots[i])) {
var s = 10 + i; // 词表里越靠前的词根越相关
if (best < 0 || s < best) best = s;
}
}
if (best >= 0) return best;
if (q && cat.indexOf(q) !== -1) return 300;
return -1;
}
/** 搜索已加载源(名称 / 中文分类 / 中文语义词根),按相关性排序 */
function searchLoaded(keyword, limit) {
var q = String(keyword || '').trim().toLowerCase();
var roots = expandKeyword(q);
var hits = [];
var sids = Object.keys(cache);
for (var _i = 0; _i < sids.length; _i++) {
var sid = sids[_i];
var list = cache[sid].icons || [];
for (var j = 0; j < list.length; j++) {
var ic = list[j];
var sc = scoreIcon(ic, q, roots);
if (sc >= 0) {
hits.push({
sc: sc,
item: { id: sid + ':' + ic.name, name: ic.name, svg: ic.svg, source: sid, type: ic.type }
});
}
}
}
hits.sort(function (a, b) { return a.sc - b.sc; });
return hits.slice(0, limit || 60).map(function (h) { return h.item; });
}
/** 搜索索引(全量 id/name,无 svg,用于技能/白名单展示) */
function searchIndex(keyword, limit) {
var q = String(keyword || '').trim().toLowerCase();
var roots = expandKeyword(q);
var idx = (typeof HGB_BuiltinIcons !== 'undefined' && HGB_BuiltinIcons.iconIndex) || [];
var hits = [];
for (var i = 0; i < idx.length; i++) {
var ic = idx[i];
var sc = scoreIcon(ic, q, roots);
if (sc >= 0) {
hits.push({
sc: sc,
item: { id: ic.id, name: ic.name, source: String(ic.id).split(':')[0], category: ic.category }
});
}
}
hits.sort(function (a, b) { return a.sc - b.sc; });
return hits.slice(0, limit || 20).map(function (h) { return h.item; });
}
/** 按 id 反查来源 id */
function sourceOf(fullId) {
return String(fullId || '').split(':')[0];
}
return {
VERSION, loadSource, loadSources, preload, loadAll,
getSource, loaded, loadedIds, findIcon, searchLoaded, searchIndex, sourceOf,
expandKeyword, matchIcon: iconMatches, scoreIcon
};
})();