utils.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { showToast } from "./components/ui-lib";
  2. import Locale from "./locales";
  3. export function trimTopic(topic: string) {
  4. const s = topic.split("");
  5. let lastChar = s.at(-1); // 获取 s 的最后一个字符
  6. let pattern = /[,。!?、]/; // 定义匹配中文标点符号的正则表达式
  7. while (lastChar && pattern.test(lastChar!)) {
  8. s.pop();
  9. lastChar = s.at(-1);
  10. }
  11. return s.join("");
  12. }
  13. export function copyToClipboard(text: string) {
  14. navigator.clipboard
  15. .writeText(text)
  16. .then((res) => {
  17. showToast(Locale.Copy.Success);
  18. })
  19. .catch((err) => {
  20. showToast(Locale.Copy.Failed);
  21. });
  22. }
  23. export function downloadAs(text: string, filename: string) {
  24. const element = document.createElement("a");
  25. element.setAttribute(
  26. "href",
  27. "data:text/plain;charset=utf-8," + encodeURIComponent(text)
  28. );
  29. element.setAttribute("download", filename);
  30. element.style.display = "none";
  31. document.body.appendChild(element);
  32. element.click();
  33. document.body.removeChild(element);
  34. }
  35. export function isIOS() {
  36. const userAgent = navigator.userAgent.toLowerCase();
  37. return /iphone|ipad|ipod/.test(userAgent);
  38. }
  39. export function selectOrCopy(el: HTMLElement, content: string) {
  40. const currentSelection = window.getSelection();
  41. if (currentSelection?.type === "Range") {
  42. return false;
  43. }
  44. copyToClipboard(content);
  45. return true;
  46. }
  47. export function queryMeta(key: string, defaultValue?: string): string {
  48. let ret: string;
  49. if (document) {
  50. const meta = document.head.querySelector(
  51. `meta[name='${key}']`
  52. ) as HTMLMetaElement;
  53. ret = meta?.content ?? "";
  54. } else {
  55. ret = defaultValue ?? "";
  56. }
  57. return ret;
  58. }
  59. let currentId: string;
  60. export function getCurrentCommitId() {
  61. if (currentId) {
  62. return currentId;
  63. }
  64. currentId = queryMeta("version");
  65. return currentId;
  66. }