You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

script-custom_elements.js 15 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. /*
  2. * Detail: 仿照 DOMTokenList 功能实现的自定义 CustomTokenList
  3. */
  4. class CustomTokenList extends Array {
  5. //Reference: https://stackoverflow.com/questions/49349195/using-splice-method-in-subclass-of-array-in-javascript/56181665#56181665 让splice能够用
  6. static get [Symbol.species]() { return Array; }
  7. static #illegalTokenRegRex = /\s/;
  8. #node = null;
  9. #attributeName = null;
  10. #refreshAttribute = true;
  11. #observer = null;
  12. #observerOptions = {
  13. attributeFilter: [],
  14. attributeOldValue: true,
  15. subtree: true
  16. };
  17. get #attribute() { //获取绑定的参数
  18. return this.#node.getAttributeNode(this.#attributeName);
  19. }
  20. set #attribute(node) { //直接设定绑定的参数AttrNode
  21. if (node instanceof Attr) {
  22. this.#node = node.ownerElement;
  23. this.#attributeName = node.nodeName;
  24. this.#observerOptions.attributeFilter = [this.#attributeName];
  25. } else {
  26. throw new TypeError(`${CustomTokenList.name}.#attribute: Argument 1 is not an Attr.\n参数 1 不是 Attr。`);
  27. }
  28. }
  29. constructor(node, attributeName){ //传入 HTMLElement 和需要绑定的 参数名称
  30. super();
  31. if (node instanceof Attr) {
  32. this.#attribute = node;
  33. } else if (node instanceof HTMLElement) {
  34. this.#node = node;
  35. this.#attributeName = attributeName.toString().toLowerCase(); //attributeName 只支持小写
  36. this.#observerOptions.attributeFilter = [this.#attributeName];
  37. } else {
  38. throw new TypeError(`${CustomTokenList.name}.constructor: Argument 1 is not an Attr or HTMLElement.\n参数 1 不是 Attr 或 HTMLElement。`);
  39. }
  40. let initializeValue = this.#attribute.nodeValue;
  41. if (initializeValue) { //如果值已经存在,则先添加到TokenList
  42. this.value = initializeValue;
  43. }
  44. const _this = this;
  45. this.#observer = new MutationObserver(function(mutationList) {
  46. for (const mutation of mutationList) {
  47. if (mutation.type == 'attributes' && mutation.attributeName == _this.#attributeName) {
  48. //因为可能是删除属性,所以i需要重新取得属性
  49. _this.#attribute = _this.#node.getAttributeNode(_this.#attributeName);
  50. //清空旧值
  51. _this.length = 0;
  52. if (_this.#attribute) {
  53. _this.#refreshAttribute = false; //外部属性变化时,添加内容不再循环进行属性的更新
  54. _this.add(...new Set(_this.#attribute.nodeValue.split(/\s+/g)));
  55. _this.#refreshAttribute = true;
  56. }
  57. break;
  58. }
  59. }
  60. });
  61. this.#observer.observe(this.#node, this.#observerOptions);
  62. }
  63. static #InvalidCharacterError(functionName) {
  64. return new DOMException(`${CustomTokenList.name}.${functionName}:The token can not contain whitespace.\bToken 不允许包含空格。`, "InvalidCharacterError");
  65. }
  66. #refreshAttributeValue() {
  67. if (this.#refreshAttribute) {
  68. this.#observer.disconnect(); //解除绑定
  69. if (!this.#attribute) {
  70. this.#node.setAttributeNode(document.createAttribute(this.#attributeName));
  71. }
  72. this.#attribute.value = this.value;
  73. this.#observer.observe(this.#node, this.#observerOptions); //恢复绑定
  74. }
  75. }
  76. add(...tokens){
  77. //全部强制转换为字符串
  78. tokens = tokens.map(token=>token.toString());
  79. //如果任何 token 里存在空格,就直接抛出错误
  80. if (tokens.some(token=>CustomTokenList.#illegalTokenRegRex.test(token)))
  81. throw CustomTokenList.#InvalidCharacterError('add');
  82. //经过测试普通循环push性能最高,并且由于需要去重,需要每次判断是否存在
  83. tokens.forEach(token => {
  84. if (!this.includes(token)) this.push(...token);
  85. });
  86. this.#refreshAttributeValue();
  87. return;
  88. }
  89. remove(...tokens){
  90. //全部强制转换为字符串
  91. tokens = tokens.map(token=>token.toString());
  92. //如果任何 token 里存在空格,就直接抛出错误
  93. if (tokens.some(token=>CustomTokenList.#illegalTokenRegRex.test(token)))
  94. throw CustomTokenList.#InvalidCharacterError('remove');
  95. //splice性能特别低,但是这里只能用这个
  96. tokens.forEach(token => {
  97. const index = this.indexOf(token);
  98. if (index>=0) this.valueOf().splice(index,1);
  99. });
  100. this.#refreshAttributeValue();
  101. return;
  102. }
  103. contains(token){
  104. return this.includes(token.toString());
  105. }
  106. toggle(token, force){
  107. if (CustomTokenList.#illegalTokenRegRex.test(token))
  108. throw CustomTokenList.#InvalidCharacterError('toggle');
  109. if (force !== undefined) {
  110. if(Boolean(force)) {
  111. this.add(token);
  112. return true;
  113. }else{
  114. this.remove(token);
  115. return false;
  116. }
  117. } else {
  118. if (this.contains(token)) {
  119. this.remove(token);
  120. return false;
  121. } else {
  122. this.add(token);
  123. return true;
  124. }
  125. }
  126. }
  127. get value() {
  128. return this.join(' ');
  129. }
  130. set value(attrValue) {
  131. //将值确保转为字符串,然后以空格拆分,并加入Set确保唯一性
  132. const inputTokens = [...new Set(attrValue.toString().split(/\s+/g))];
  133. this.length = 0;
  134. this.push(...inputTokens);
  135. this.#refreshAttributeValue();
  136. }
  137. replace(oldToken, newToken){
  138. oldToken = oldToken.toString();
  139. newToken = newToken.toString();
  140. if (CustomTokenList.#illegalTokenRegRex.test(oldToken) || CustomTokenList.#illegalTokenRegRex.test(newToken))
  141. throw CustomTokenList.#InvalidCharacterError('replace');
  142. const index = this.indexOf(oldToken);
  143. if (index>=0) {
  144. this.splice(index,1, this.includes(newToken) ? undefined : newToken);
  145. if (this.#refreshAttribute) {
  146. this.#observer.disconnect(); //解除绑定
  147. this.#attribute.value = this.value;
  148. this.#observer.observe(this.#node, this.#observerOptions); //恢复绑定
  149. }
  150. return true;
  151. } else {
  152. return false;
  153. }
  154. }
  155. item(index) {
  156. return this[index];
  157. }
  158. };
  159. const svgNS = "http://www.w3.org/2000/svg"; //svg用的命名空间
  160. // Create a class for the element
  161. class CardAvatar extends HTMLElement {
  162. // Specify observed attributes so that
  163. // attributeChangedCallback will work
  164. static get observedAttributes() {
  165. return ['iid'];
  166. }
  167. #iid = 0;
  168. get iid() {
  169. return this.#iid;
  170. }
  171. /**
  172. * @param {string | number} x
  173. */
  174. set iid(x) {
  175. //this.#iid = x; //在属性改变的内容里已经写入了
  176. this.setAttribute('iid', x);
  177. }
  178. //#member = new Member();
  179. /**
  180. * @param {Member} m
  181. */
  182. /*get member() {
  183. return this.#member;
  184. }*/
  185. /**
  186. * @param {Member} m
  187. */
  188. /*set member(m) {
  189. this.#member = m;
  190. console.log("设定新的Member",m);
  191. this.setAttribute('id', m.id);
  192. }*/
  193. constructor() {
  194. // Always call super first in constructor
  195. super();
  196. // Create a shadow root
  197. const shadow = this.attachShadow({mode: 'open'});
  198. // Create some CSS to apply to the shadow dom
  199. const linkElem = shadow.appendChild(document.createElement('link'));
  200. linkElem.setAttribute('rel', 'stylesheet');
  201. linkElem.setAttribute('href', 'css/card-avatar.css');
  202. // Create spans
  203. const wrapper = shadow.appendChild(document.createElement('a'));
  204. wrapper.className = 'wrapper';
  205. wrapper.target = '_blank';
  206. const dAttr1 = wrapper.appendChild(document.createElement('div'));
  207. dAttr1.className = 'attribute attribute-main';
  208. const dAttr2 = wrapper.appendChild(document.createElement('div'));
  209. dAttr2.className = 'attribute attribute-sub';
  210. const dLeftTop = wrapper.appendChild(document.createElement('div'));
  211. dLeftTop.className = "flex-box flex-left-top";
  212. const dLeftBottom = wrapper.appendChild(document.createElement('div'));
  213. dLeftBottom.className = "flex-box flex-left-bottom";
  214. const dRightTop = wrapper.appendChild(document.createElement('div'));
  215. dRightTop.className = "flex-box flex-right-top";
  216. const dRightBottom = wrapper.appendChild(document.createElement('div'));
  217. dRightBottom.className = "flex-box flex-right-bottom";
  218. const dId = dLeftBottom.appendChild(document.createElement('div'));
  219. dId.className = 'card-id';
  220. const dLevel = dLeftBottom.appendChild(document.createElement('div'));
  221. dLevel.className = 'level';
  222. dLevel.textContent = "110";
  223. const dEnhancement = dLeftTop.appendChild(document.createElement('div'));
  224. dEnhancement.className = 'enhancement';
  225. dEnhancement.textContent = "297";
  226. const dActiveSkillCD = dRightBottom.appendChild(document.createElement('div'));
  227. dActiveSkillCD.className = 'active-skill-cd';
  228. dActiveSkillCD.textContent = "99";
  229. }
  230. connectedCallback() {
  231. console.log('自定义标签添加到页面');
  232. this.update();
  233. }
  234. attributeChangedCallback(name, oldValue, newValue) {
  235. console.log('自定义标签属性改变', name, oldValue, newValue);
  236. //if (name == 'id') this.#id = parseInt(this.getAttribute('id'));
  237. if (name == 'iid') this.#iid = parseInt(newValue);
  238. this.update();
  239. }
  240. update() {
  241. //得到怪物ID
  242. const id = this.#iid || 0;
  243. this.iid = id;
  244. const card = Cards[id] || Cards[0];
  245. const dataSource = this.getAttribute('source') || currentDataSource.code;
  246. const shadow = this.shadowRoot;
  247. const wrapper = shadow.querySelector('.wrapper');
  248. wrapper.href = currentLanguage.guideURL(id, card.name);
  249. wrapper.style.backgroundImage = `url(images/cards_${dataSource.toLowerCase()}/CARDS_${Math.ceil(id / 100).toString().padStart(3,"0")}.PNG)`;
  250. const idxInPage = (id - 1) % 100; //获取当前页面内的序号
  251. wrapper.setAttribute("data-cards-pic-x", idxInPage % 10); //添加X方向序号
  252. wrapper.setAttribute("data-cards-pic-y", Math.floor(idxInPage / 10)); //添加Y方向序号
  253. const dAttr1 = wrapper.querySelector('.attribute-main');
  254. dAttr1.setAttribute('data-attr', card.attrs[0]);
  255. const dAttr2 = wrapper.querySelector('.attribute-sub');
  256. dAttr2.setAttribute('data-attr', card.attrs[1]);
  257. const dId = wrapper.querySelector('.card-id');
  258. dId.setAttribute('data-id', id);
  259. }
  260. }
  261. // Define the new element
  262. customElements.define('card-avatar', CardAvatar);
  263. class PadIcon extends HTMLElement {
  264. // Specify observed attributes so that
  265. // attributeChangedCallback will work
  266. static get observedAttributes() {
  267. return [
  268. 'type', //图标类型
  269. 'number', //编号或数字,必须是数字
  270. 'lang', //英语、中文特殊图标的设定
  271. 'icon-type',//子图标类型
  272. //'icon-value',//子图标的值
  273. 'flags', //各种选项开关,类似className
  274. ];
  275. }
  276. static ELEMENT_TYPE_AWOKEN = 'awoken';
  277. static ELEMENT_TYPE_TYPE = 'type';
  278. static ELEMENT_TYPE_AWOKEN_COUNT = 'awoken-count';
  279. #svg = document.createElementNS(svgNS,'svg');
  280. #flags = null;
  281. get flagsList() { return this.#flags; }
  282. #number = 0;
  283. #type = PadIcon.ELEMENT_TYPE_AWOKEN;
  284. #iconType = null;
  285. get number() { return this.#number; }
  286. set number(x) {
  287. const number = Number(x);
  288. if (Number.isNaN(number)) throw new Error('传入的 number 不是数字!');
  289. this.setAttribute('number', number);
  290. this.#number = number;
  291. }
  292. get type() { return this.#type; }
  293. set type(x) {
  294. if (x == null) {
  295. this.removeAttribute('type');
  296. } else {
  297. this.setAttribute('type', x);
  298. }
  299. this.#type = x;
  300. }
  301. get iconType() { this.#iconType; }
  302. set iconType(x) {
  303. if (x == null) {
  304. this.removeAttribute('icon-type');
  305. } else {
  306. this.setAttribute('icon-type', x);
  307. }
  308. this.#iconType = x;
  309. }
  310. constructor() {
  311. // Always call super first in constructor
  312. super();
  313. this.#flags = new CustomTokenList(this, "flags");
  314. // Create a shadow root
  315. const shadow = this.attachShadow({mode: 'open'});
  316. // Create some CSS to apply to the shadow dom
  317. const linkElem = shadow.appendChild(document.createElement('link'));
  318. linkElem.setAttribute('rel', 'stylesheet');
  319. linkElem.setAttribute('href', 'css/svg-icon.css');
  320. const svg = this.#svg;
  321. const use = document.createElementNS(svgNS, 'use');
  322. svg.appendChild(use);
  323. shadow.appendChild(svg);
  324. }
  325. connectedCallback() { //自定义标签添加到页面
  326. this.update();
  327. }
  328. attributeChangedCallback(name, oldValue, newValue) { //自定义标签属性改变
  329. const svg = this.shadowRoot.querySelector('svg');
  330. if (name == 'type') {
  331. this.#type = newValue;
  332. //如果更换类型,删除use以外的其他node
  333. const use = svg.querySelector('use');
  334. [...svg.childNodes].forEach(child=>{if(child!=use) child.remove();});
  335. }
  336. if (name == 'number') {
  337. const number = Number(newValue);
  338. this.#number = Number.isNaN(number) ? 0 : number;
  339. }
  340. if (name == 'icon-type') this.#iconType = newValue;
  341. //将这些属性全都复制到svg上去
  342. if (newValue == null) {
  343. svg.removeAttribute(name);
  344. } else {
  345. svg.setAttribute(name, newValue);
  346. }
  347. this.update();
  348. }
  349. update() {
  350. const number = this.#number;
  351. const lang = this.getAttribute('lang') || currentLanguage.i18n;
  352. //const shadow = this.shadowRoot;
  353. const svg = this.#svg;
  354. //svg.setAttribute("type", this.#type);
  355. //this.#iconType ? svg.setAttribute("icon-type", this.#iconType) : svg.removeAttribute("icon-type");
  356. const use = svg.querySelector(':scope>use');
  357. svg.setAttribute("viewBox", "0 0 32 32");
  358. switch (this.#type) {
  359. case PadIcon.ELEMENT_TYPE_AWOKEN: {
  360. if (/^(?:en|ko)/.test(lang) && [40,46,47,48].includes(number)) number += '-en'; //英文不一样的觉醒
  361. if (/^(?:zh)/.test(lang) && [46,47].includes(number)) number += '-zh'; //中文不一样的觉醒
  362. use.href.baseVal = `images/icon-awoken.svg#awoken-${number}`;
  363. break;
  364. }
  365. case PadIcon.ELEMENT_TYPE_TYPE: {
  366. if (/^(?:en|ko)/.test(lang) && [9,12].includes(number)) number += '-en'; //英文不一样的类型
  367. use.href.baseVal = `images/icon-type.svg#type-${number}`;
  368. break;
  369. }
  370. case PadIcon.ELEMENT_TYPE_AWOKEN_COUNT: {
  371. const full = this.flagsList.contains("full");
  372. const weapon = this.flagsList.contains("weapon");
  373. const canAssist = this.flagsList.contains("can-assist");
  374. //svg.setAttribute("viewBox", "0 0 34 38");
  375. svg.viewBox.baseVal.width = 34;
  376. svg.viewBox.baseVal.height = 38;
  377. if (full && weapon && canAssist) {
  378. use.href.baseVal = `images/icon-awoken.svg#awoken-49`;
  379. svg.querySelector('text')?.remove();
  380. break;
  381. }
  382. use.href.baseVal = `images/icon-awoken-count.svg#awoken-count-bg`;
  383. const text = svg.querySelector('text') || svg.appendChild(document.createElementNS(svgNS, 'text'));
  384. text.textContent = full ? '★' : number;
  385. //text.setAttribute("x", "50%");
  386. const lengthX = svg.createSVGLength();
  387. lengthX.newValueSpecifiedUnits(SVGLength.SVG_LENGTHTYPE_PERCENTAGE, 50);
  388. text.x.baseVal.initialize(lengthX);
  389. //text.setAttribute("y", "47%");
  390. const lengthY = svg.createSVGLength();
  391. lengthY.newValueSpecifiedUnits(SVGLength.SVG_LENGTHTYPE_PERCENTAGE, 47);
  392. text.y.baseVal.initialize(lengthY);
  393. text.classList.add("number");
  394. text.textLength.baseVal.newValueSpecifiedUnits(
  395. full ? SVGLength.SVG_LENGTHTYPE_EMS : SVGLength.SVG_LENGTHTYPE_PERCENTAGE,
  396. full ? 0.9 : 100);
  397. text.lengthAdjust.baseVal = full ? SVGTextElement.LENGTHADJUST_SPACINGANDGLYPHS : SVGTextElement.LENGTHADJUST_SPACING;
  398. break;
  399. }
  400. case 'latent':
  401. case 'badge':
  402. case 'attr':
  403. case 'orb':
  404. case 'common':
  405. case 'skill':
  406. default:
  407. break;
  408. }
  409. }
  410. }
  411. // Define the new element
  412. customElements.define('pad-icon', PadIcon);

智龙迷城队伍图制作工具