prop.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. /* eslint-disable @typescript-eslint/no-unsafe-return */
  2. const i18nPrefix = 'i18n:';
  3. /*
  4. * Returns the ordered PropMap
  5. * @param {*} value of dump
  6. * @returns {key:string dump:object}[]
  7. */
  8. exports.sortProp = function(propMap) {
  9. const orderList = [];
  10. const normalList = [];
  11. Object.keys(propMap).forEach((key) => {
  12. const item = propMap[key];
  13. if (item != null) {
  14. if ('displayOrder' in item) {
  15. orderList.push({
  16. key,
  17. dump: item,
  18. });
  19. } else {
  20. normalList.push({
  21. key,
  22. dump: item,
  23. });
  24. }
  25. }
  26. });
  27. orderList.sort((a, b) => a.dump.displayOrder - b.dump.displayOrder);
  28. return orderList.concat(normalList);
  29. };
  30. /**
  31. *
  32. * This method is used to update the custom node
  33. * @param {HTMLElement} container
  34. * @param {string[]} excludeList
  35. * @param {object} dump
  36. * @param {(element,prop)=>void} update
  37. */
  38. exports.updateCustomPropElements = function(container, excludeList, dump, update) {
  39. const sortedProp = exports.sortProp(dump.value);
  40. container.$ = container.$ || {};
  41. /**
  42. * @type {Array<HTMLElement>}
  43. */
  44. const children = [];
  45. sortedProp.forEach((prop) => {
  46. if (!excludeList.includes(prop.key)) {
  47. if (!prop.dump.visible) {
  48. return;
  49. }
  50. let node = container.$[prop.key];
  51. if (!node) {
  52. node = document.createElement('ui-prop');
  53. node.setAttribute('type', 'dump');
  54. node.dump = prop.dump;
  55. node.key = prop.key;
  56. container.$[prop.key] = node;
  57. }
  58. if (typeof update === 'function') {
  59. update(node, prop);
  60. }
  61. children.push(node);
  62. }
  63. });
  64. const currentChildren = Array.from(container.children);
  65. children.forEach((child, i) => {
  66. if (child === currentChildren[i]) {
  67. return;
  68. }
  69. container.appendChild(child);
  70. });
  71. // delete extra children
  72. currentChildren.forEach(($child) => {
  73. if (!children.includes($child)) {
  74. $child.remove();
  75. }
  76. });
  77. };
  78. /**
  79. * Tool function: recursively set readonly in resource data
  80. */
  81. exports.loopSetAssetDumpDataReadonly = function(dump) {
  82. if (typeof dump !== 'object') {
  83. return;
  84. }
  85. if (dump.readonly === undefined) {
  86. return;
  87. }
  88. dump.readonly = true;
  89. if (dump.isArray) {
  90. for (let i = 0; i < dump.value.length; i++) {
  91. exports.loopSetAssetDumpDataReadonly(dump.value[i]);
  92. }
  93. return;
  94. }
  95. for (const key in dump.value) {
  96. exports.loopSetAssetDumpDataReadonly(dump.value[key]);
  97. }
  98. };
  99. /**
  100. * Tool functions: set to unavailable
  101. * @param {object} data dump | function
  102. * @param element
  103. */
  104. exports.setDisabled = function(data, element) {
  105. if (!element) {
  106. return;
  107. }
  108. let disabled = data;
  109. if (typeof data === 'function') {
  110. disabled = data();
  111. }
  112. if (disabled === true) {
  113. element.setAttribute('disabled', 'true');
  114. } else {
  115. element.removeAttribute('disabled');
  116. }
  117. };
  118. /**
  119. * Tool function: Set read-only status
  120. * @param {object} data dump | function
  121. * @param element
  122. */
  123. exports.setReadonly = function(data, element) {
  124. if (!element) {
  125. return;
  126. }
  127. let readonly = data;
  128. if (typeof data === 'function') {
  129. readonly = data();
  130. }
  131. if (readonly === true) {
  132. element.setAttribute('readonly', 'true');
  133. } else {
  134. element.removeAttribute('readonly');
  135. }
  136. if (element.render && element.dump) {
  137. element.dump.readonly = readonly;
  138. element.render();
  139. }
  140. };
  141. /**
  142. * Tool function: Set the display status
  143. * @param {Function | boolean} data dump | function
  144. * @param {HTMLElement} element
  145. */
  146. exports.setHidden = function(data, element) {
  147. if (!element) {
  148. return;
  149. }
  150. let hidden = data;
  151. if (typeof data === 'function') {
  152. hidden = data();
  153. }
  154. if (hidden === true) {
  155. element.setAttribute('hidden', '');
  156. } else {
  157. element.removeAttribute('hidden');
  158. }
  159. };
  160. // In order to avoid a large number of operations in a short time, the function of returning the same operation result in a time period is added
  161. let getMessageProtocolSceneResult = '';
  162. let getMessageProtocolSceneStartTime = Date.now();
  163. exports.getMessageProtocolScene = function(element) {
  164. if (getMessageProtocolSceneResult && Date.now() - getMessageProtocolSceneStartTime < 1000) {
  165. return getMessageProtocolSceneResult;
  166. }
  167. getMessageProtocolSceneResult = '';
  168. getMessageProtocolSceneStartTime = Date.now();
  169. while (element) {
  170. element = element.parentElement || element.getRootNode().host;
  171. if (element && element.messageProtocol) {
  172. getMessageProtocolSceneResult = element.messageProtocol.scene;
  173. break;
  174. }
  175. }
  176. if (!getMessageProtocolSceneResult) {
  177. getMessageProtocolSceneResult = 'scene';
  178. }
  179. return getMessageProtocolSceneResult;
  180. };
  181. exports.updatePropByDump = function(panel, dump) {
  182. panel.dump = dump;
  183. if (!panel.elements) {
  184. panel.elements = {};
  185. }
  186. if (!panel.$props) {
  187. panel.$props = {};
  188. }
  189. if (!panel.$groups) {
  190. panel.$groups = {};
  191. }
  192. const oldPropKeys = Object.keys(panel.$props);
  193. const newPropKeys = [];
  194. Object.keys(dump.value).forEach((key, index) => {
  195. const info = dump.value[key];
  196. if (!info.visible) {
  197. return;
  198. }
  199. newPropKeys.push(key);
  200. const element = panel.elements[key];
  201. let $prop = panel.$props[key];
  202. if (!$prop) {
  203. if (element && element.create) {
  204. // when it need to go custom initialize
  205. $prop = panel.$props[key] = panel.$[key] = element.create.call(panel, info);
  206. } else {
  207. $prop = panel.$props[key] = panel.$[key] = document.createElement('ui-prop');
  208. $prop.setAttribute('type', 'dump');
  209. }
  210. const _displayOrder = info.group?.displayOrder ?? info.displayOrder;
  211. $prop.displayOrder = _displayOrder === undefined ? index : Number(_displayOrder);
  212. if (element && element.displayOrder !== undefined) {
  213. $prop.displayOrder = element.displayOrder;
  214. }
  215. if (!element || !element.isAppendToParent || element.isAppendToParent.call(panel)) {
  216. if (info.group && dump.groups) {
  217. const { id = 'default', name } = info.group;
  218. if (!panel.$groups[id] && dump.groups[id]) {
  219. if (dump.groups[id].style === 'tab') {
  220. panel.$groups[id] = exports.createTabGroup(dump.groups[id], panel);
  221. } else if (dump.groups[id].style === 'section') {
  222. panel.$groups[id] = exports.createGroup(dump.groups[id]);
  223. }
  224. }
  225. if (panel.$groups[id]) {
  226. if (!panel.$groups[id].isConnected) {
  227. exports.appendChildByDisplayOrder(panel.$.componentContainer, panel.$groups[id]);
  228. }
  229. if (dump.groups[id].style === 'tab') {
  230. exports.appendToTabGroup(panel.$groups[id], name);
  231. } else if (dump.groups[id].style === 'section') {
  232. exports.appendToGroup(panel.$groups[id], name);
  233. }
  234. }
  235. if (dump.groups[id].style === 'tab') {
  236. exports.appendChildByDisplayOrder(panel.$groups[id].tabs[name], $prop);
  237. } else if (dump.groups[id].style === 'section') {
  238. exports.appendChildByDisplayOrder(panel.$groups[id].names[name], $prop);
  239. }
  240. } else {
  241. exports.appendChildByDisplayOrder(panel.$.componentContainer, $prop);
  242. }
  243. }
  244. } else if (!$prop.isConnected || !$prop.parentElement) {
  245. if (!element || !element.isAppendToParent || element.isAppendToParent.call(panel)) {
  246. if (info.group && dump.groups) {
  247. const { id = 'default', name } = info.group;
  248. if (dump.groups[id].style === 'tab') {
  249. exports.appendChildByDisplayOrder(panel.$groups[id].tabs[name], $prop);
  250. } else {
  251. exports.appendChildByDisplayOrder(panel.$groups[id].names[name], $prop);
  252. }
  253. } else {
  254. exports.appendChildByDisplayOrder(panel.$.componentContainer, $prop);
  255. }
  256. }
  257. }
  258. $prop.render(info);
  259. });
  260. for (const id of oldPropKeys) {
  261. if (!newPropKeys.includes(id)) {
  262. const $prop = panel.$props[id];
  263. if ($prop && $prop.parentElement) {
  264. $prop.parentElement.removeChild($prop);
  265. }
  266. }
  267. }
  268. for (const key in panel.elements) {
  269. const element = panel.elements[key];
  270. if (element && element.ready) {
  271. element.ready.call(panel, panel.$[key], dump.value);
  272. element.ready = undefined; // ready needs to be executed only once
  273. }
  274. }
  275. for (const key in panel.elements) {
  276. const element = panel.elements[key];
  277. if (element && element.update) {
  278. element.update.call(panel, panel.$[key], dump.value);
  279. }
  280. }
  281. exports.toggleGroup(panel.$groups);
  282. };
  283. /**
  284. * Tool function: check whether the value of the attribute is consistent after multi-selection
  285. */
  286. exports.isMultipleInvalid = function(dump) {
  287. let invalid = false;
  288. if (dump.values && dump.values.some((ds) => ds !== dump.value)) {
  289. invalid = true;
  290. }
  291. return invalid;
  292. };
  293. /**
  294. * Get the name based on the dump data
  295. */
  296. exports.getName = function(dump) {
  297. if (!dump) {
  298. return '';
  299. }
  300. if (typeof dump.displayName === 'string') {
  301. const displayName = dump.displayName.trim();
  302. if (displayName.startsWith(i18nPrefix)) {
  303. const key = displayName.substring(i18nPrefix.length);
  304. if (Editor.I18n.t(key)) {
  305. return displayName;
  306. }
  307. } else if (displayName) {
  308. return displayName;
  309. }
  310. }
  311. let name = dump.name || '';
  312. name = name.trim().replace(/^\S/, (str) => str.toUpperCase());
  313. name = name.replace(/_/g, (str) => ' ');
  314. name = name.replace(/ \S/g, (str) => ` ${str.toUpperCase()}`);
  315. // 驼峰转中间空格
  316. name = name.replace(/([a-z])([A-Z])/g, '$1 $2');
  317. return name.trim();
  318. };
  319. exports.createGroup = function(dump) {
  320. const $group = document.createElement('div');
  321. $group.setAttribute('class', 'ui-prop-group');
  322. $group.dump = dump;
  323. $group.names = {};
  324. $group.displayOrder = dump.displayOrder;
  325. return $group;
  326. };
  327. exports.createTabGroup = function(dump, panel) {
  328. const $group = document.createElement('div');
  329. $group.setAttribute('class', 'tab-group');
  330. $group.dump = dump;
  331. $group.tabs = {};
  332. $group.displayOrder = dump.displayOrder;
  333. $group.$header = document.createElement('ui-tab');
  334. $group.$header.setAttribute('class', 'tab-header');
  335. $group.appendChild($group.$header);
  336. $group.$header.addEventListener('change', (e) => {
  337. active(e.target.value);
  338. });
  339. function active(index) {
  340. const tabNames = Object.keys($group.tabs);
  341. const tabName = tabNames[index];
  342. $group.childNodes.forEach((child) => {
  343. if (!child.classList.contains('tab-content')) {
  344. return;
  345. }
  346. if (child.getAttribute('name') === tabName) {
  347. child.style.display = 'block';
  348. } else {
  349. child.style.display = 'none';
  350. }
  351. });
  352. }
  353. // check style
  354. if (!panel.$this.shadowRoot.querySelector('style#group-style')) {
  355. const style = document.createElement('style');
  356. style.setAttribute('id', 'group-style');
  357. style.innerText = `
  358. .tab-group {
  359. margin-top: 4px;
  360. }
  361. .tab-content {
  362. display: none;
  363. padding-bottom: 6px;
  364. }`;
  365. panel.$.componentContainer.before(style);
  366. }
  367. setTimeout(() => {
  368. active(0);
  369. });
  370. return $group;
  371. };
  372. exports.appendToGroup = function($group, name) {
  373. if ($group.names[name]) {
  374. return;
  375. }
  376. const $content = document.createElement('ui-section');
  377. $content.setAttribute('class', 'ui-prop-group-content');
  378. $content.setAttribute('expand', '');
  379. let parentCacheKey = 'ui-prop-group-content';
  380. let $parent = $group;
  381. while ($parent) {
  382. if ($parent.hasAttribute('cache-expand')) {
  383. parentCacheKey = $parent.getAttribute('cache-expand');
  384. break;
  385. }
  386. $parent = $parent.parentElement;
  387. }
  388. $content.setAttribute('cache-expand', `${parentCacheKey}-${name}`);
  389. const $header = document.createElement('ui-label');
  390. $header.setAttribute('slot', 'header');
  391. let displayName = name;
  392. if (displayName.startsWith(i18nPrefix)) {
  393. displayName = exports.getName({ displayName: name });
  394. } else {
  395. displayName = exports.getName({ name });
  396. }
  397. $header.setAttribute('value', displayName);
  398. $content.appendChild($header);
  399. $group.appendChild($content);
  400. $group.names[name] = $content;
  401. };
  402. exports.appendToTabGroup = function($group, tabName) {
  403. if ($group.tabs[tabName]) {
  404. return;
  405. }
  406. const $content = document.createElement('div');
  407. $group.tabs[tabName] = $content;
  408. $content.setAttribute('class', 'tab-content');
  409. $content.setAttribute('name', tabName);
  410. $group.appendChild($content);
  411. const $label = document.createElement('ui-label');
  412. let displayName = tabName;
  413. if (displayName.startsWith(i18nPrefix)) {
  414. displayName = exports.getName({ displayName: tabName });
  415. } else {
  416. displayName = exports.getName({ name: tabName });
  417. }
  418. $label.setAttribute('value', displayName);
  419. const $button = document.createElement('ui-button');
  420. $button.setAttribute('name', tabName);
  421. $button.appendChild($label);
  422. $group.$header.appendChild($button);
  423. };
  424. exports.appendChildByDisplayOrder = function(parent, newChild) {
  425. const displayOrder = newChild.displayOrder || 0;
  426. const children = Array.from(parent.children);
  427. const child = children.find((child) => {
  428. if (child.dump && child.displayOrder > displayOrder) {
  429. return child;
  430. }
  431. return null;
  432. });
  433. if (child) {
  434. child.before(newChild);
  435. } else {
  436. parent.appendChild(newChild);
  437. }
  438. };
  439. exports.toggleGroup = function($groups) {
  440. for (const id in $groups) {
  441. if ($groups[id].dump.style === 'section') {
  442. const $contents = $groups[id].querySelectorAll('.ui-prop-group-content');
  443. $contents.forEach($content => {
  444. const $props = Array.from($content.querySelectorAll(':scope > ui-prop'));
  445. const show = $props.some($prop => getComputedStyle($prop).display !== 'none');
  446. if (show) {
  447. $content.removeAttribute('hidden');
  448. } else {
  449. $content.setAttribute('hidden', '');
  450. }
  451. });
  452. }
  453. if ($groups[id].dump.style === 'tab') {
  454. const $props = Array.from($groups[id].querySelectorAll('.tab-content > ui-prop'));
  455. const show = $props.some($prop => getComputedStyle($prop).display !== 'none');
  456. if (show) {
  457. $groups[id].removeAttribute('hidden');
  458. } else {
  459. $groups[id].setAttribute('hidden', '');
  460. }
  461. }
  462. }
  463. },
  464. exports.disconnectGroup = function(panel) {
  465. if (panel.$groups) {
  466. for (const key in panel.$groups) {
  467. if (panel.$groups[key] instanceof HTMLElement) {
  468. panel.$groups[key].remove();
  469. }
  470. }
  471. panel.$groups = {};
  472. }
  473. };
  474. /**
  475. * Create ui-radio-group according to configuration
  476. * @param {object} options
  477. * @param {any[]} options.enumList
  478. * @param {string} options.tooltip
  479. * @param {(elementName: string) => string}options.getIconName
  480. * @param {(event: CustomEvent) => {}} options.onChange
  481. * @returns
  482. */
  483. exports.createRadioGroup = function(options) {
  484. const { enumList, getIconName, onChange, tooltip: rawTooltip } = options;
  485. const $radioGroup = document.createElement('ui-radio-group');
  486. $radioGroup.setAttribute('slot', 'content');
  487. $radioGroup.addEventListener('change', (e) => {
  488. onChange(e);
  489. });
  490. for (let index = 0; index < enumList.length; index++) {
  491. const element = enumList[index];
  492. const icon = document.createElement('ui-icon');
  493. const button = document.createElement('ui-radio-button');
  494. const iconName = getIconName(element.name);
  495. const tooltip = `${rawTooltip}_${element.name.toLocaleLowerCase()}`;
  496. icon.value = iconName;
  497. button.appendChild(icon);
  498. button.value = element.value;
  499. button.setAttribute('tooltip', tooltip);
  500. $radioGroup.appendChild(button);
  501. }
  502. return $radioGroup;
  503. };
  504. exports.injectionStyle = `
  505. ui-prop,
  506. ui-section { margin-top: 4px; }
  507. ui-prop > ui-section,
  508. ui-prop > ui-prop,
  509. ui-section > ui-prop[slot="header"],
  510. ui-prop [slot="content"] ui-prop {
  511. margin-top: 0;
  512. margin-left: 0;
  513. }
  514. ui-prop[ui-section-config] + ui-section.config,
  515. ui-prop[ui-section-config] + ui-prop[ui-section-config],
  516. ui-section.config + ui-prop[ui-section-config],
  517. ui-section.config + ui-section.config { margin-top: 0; }
  518. ui-prop[ui-section-config]:last-child {
  519. border-bottom: solid 1px var(--color-normal-fill-emphasis);
  520. }
  521. `;
  522. /**
  523. * Obtain the api document path and obtain the className through the cc.xxx.properties configured by i18n.
  524. * If it does not exist, the ui-link component will not be added.
  525. * @param dump
  526. */
  527. function getDocsURL(dump) {
  528. const mathResults = dump.displayName && dump.displayName.match(/(?<=cc\.\s*)(\w+)/);
  529. const className = mathResults && mathResults.length > 0 ? mathResults[0] : '';
  530. if (!className) {
  531. return '';
  532. }
  533. return `${Editor.App.urls.api}/class/${className}?id=${dump.name}`;
  534. }
  535. exports.setTooltip = function(dump, $label, name) {
  536. if (!name) {
  537. name = exports.getName(dump);
  538. }
  539. if (dump.tooltip) {
  540. let tooltipValid = true;
  541. if (dump.tooltip.startsWith(i18nPrefix)) {
  542. const key = dump.tooltip.substring(i18nPrefix.length);
  543. if (!Editor.I18n.t(key)) {
  544. tooltipValid = false;
  545. }
  546. }
  547. if (tooltipValid) {
  548. const url = getDocsURL(dump);
  549. const attributeTitle = `<ui-label style="font-weight:bold;" value="i18n:ENGINE.common.attribute.title"></ui-label>`;
  550. const attributeName = url ? `
  551. <ui-link value='${url}'>
  552. <ui-label value="${dump.name || name}"></ui-label>
  553. </ui-link>`.trim() : `<ui-label value="${dump.name || name}"></ui-label>`;
  554. $label.setAttribute('tooltip', `
  555. <div style='margin-bottom: 10px'>${attributeTitle}${attributeName}</div><ui-label value="${dump.tooltip}"></ui-label>`.trim()
  556. );
  557. }
  558. }
  559. };
  560. exports.setLabel = function(dump, $label) {
  561. const name = exports.getName(dump);
  562. $label.value = name;
  563. exports.setTooltip(dump, $label, name);
  564. };