Files
drawlogo/js/core/iconlib.js
T
sgp b10184bf94 feat(expand): P0-P3 素材扩库批次(发现器 + Google Fonts + Poly Haven + Noto Emoji 3D)
- P0: scripts/discover-sources.js 四通道候选发现,产出 candidates.json / registry.json

- P1: build-posters 新增 fontsource 适配器,接入 Google Fonts 2766 个 woff2

- P2: 新增 polyhaven 适配器,接入 Poly Haven CC0 纹理 238 张

- P3: build-icons 新增 gh-raster listPath(Git Tree 逐级下钻),接入 Noto Emoji 3D 3797 个 PNG

- 修复: GitHub Contents API 不支持目录分页导致重复/截断,改为 Git Tree 下钻并按路径去重;audit-files.json 同步重建

- 判定 noto-emoji-2d / twemoji-png 与既有 Iconify 源同图重复,不予收录

- 基线: 图标 264 源/448,551;海报 69 源/5,366;版本联动 20261108a
2026-11-08 01:46:52 +08:00

260 lines
9.1 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 = '20261108a'; // 与 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 || [];
// 源级中文名匹配(如「圣诞」→ withicons-christmas 全部图标)
var meta = (typeof HGB_BuiltinIcons !== 'undefined' && HGB_BuiltinIcons.sources &&
HGB_BuiltinIcons.sources[sid]) || null;
var srcHit = !!(q && meta &&
((meta.name || '') + ' ' + (meta.nameCn || '')).toLowerCase().indexOf(q) !== -1);
for (var j = 0; j < list.length; j++) {
var ic = list[j];
var sc = scoreIcon(ic, q, roots);
if (sc < 0 && srcHit) sc = 250;
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];
}
/* ---------- 位图图标内联(PNG 导出用) ---------- */
// 3D 位图图标的数据文件以 <image href="js/data/sources/...png"> 引用原图,
// 页面内联渲染可直接显示;但导出 PNG/PDF/SVG 时 SVG 会被转成 blob/data URI,
// 相对路径失效 → 导出前把 href 内联成 data URI(按路径缓存,只取一次)。
var rasterCache = {}; // 相对路径 -> data URI
var RASTER_RE = /href="(js\/data\/sources\/[^"]+\.png)"/g;
/** 是否含位图图标引用 */
function hasRaster(svg) {
return typeof svg === 'string' && svg.indexOf('js/data/sources/') !== -1 && svg.indexOf('.png"') !== -1;
}
function fetchDataURI(p) {
if (rasterCache[p]) return Promise.resolve(rasterCache[p]);
return fetch(p).then(function (r) {
if (!r.ok) throw new Error('位图加载失败: ' + p);
return r.blob();
}).then(function (blob) {
return new Promise(function (resolve, reject) {
var fr = new FileReader();
fr.onload = function () { rasterCache[p] = fr.result; resolve(fr.result); };
fr.onerror = reject;
fr.readAsDataURL(blob);
});
});
}
/** 把 svg 里的位图相对引用内联为 data URI(导出前调用;无位图时原样返回) */
function inlineRasters(svg) {
if (!hasRaster(svg)) return Promise.resolve(svg);
var paths = [], m;
RASTER_RE.lastIndex = 0;
while ((m = RASTER_RE.exec(svg))) {
if (paths.indexOf(m[1]) === -1) paths.push(m[1]);
}
return Promise.all(paths.map(fetchDataURI)).then(function () {
var out = svg;
paths.forEach(function (p) {
out = out.split('href="' + p + '"').join('href="' + rasterCache[p] + '"');
});
return out;
});
}
return {
VERSION, loadSource, loadSources, preload, loadAll,
getSource, loaded, loadedIds, findIcon, searchLoaded, searchIndex, sourceOf,
expandKeyword, matchIcon: iconMatches, scoreIcon,
hasRaster, inlineRasters
};
})();